80 Commits

Author SHA1 Message Date
Ty 8749b07611 Fix preview cropping: canvas fits within viewport, preserves aspect ratio
.preview was width:100% inside max-height:50vh container — tall photos
were clipped. Now: max-width:100%, max-height:50vh, width/height auto,
object-fit:contain, flex-centered in the wrap.

Added e2e regression test: loads a photo, verifies the canvas bounding
box fits the viewport, preserves aspect ratio, and is not clipped by
the container.
2026-09-14 11:51:44 -07:00
Ty 2d5ff95441 Fix SSR browser gate: use browser from $app/environment
The gate check ran during SSR where navigator is undefined,
rendering the 'Unsupported browser' div into the initial HTML.
Now gated on browser (client-only) so SSR renders the app
and the gate evaluates in the browser.
2026-09-14 11:49:01 -07:00
Ty 2bc7eecd7c UAT-8b: axis UI — mask carry-forward, remove axis line, slider
1. drawOverlay: checkerboard mask overlay now drawn in axis + measure
   states (mask carry-forward — slab is isolated)
2. Removed the separate red axis line + arrowhead — the rect's long
   side IS the axis
3. Rect rotates: uses axisState.rect.angle (from UAT-8a)
4. Replace three rotate buttons with slider (-180..180, step 1) +
   minus/plus nudge buttons (same pattern as Sensitivity slider)

587 lines, 109/109 tests, build OK.
2026-09-14 11:45:12 -07:00
Ty f00c4a7460 UAT-8a: rotate the rect, not a separate axis vector
reduceAxisState 'rotate' now changes state.rect.angle and re-derives
state.axis via axisFromRect(newRect). The rectangle rotates as a whole;
the axis for Measure is derived from the rotated rect's long side.

2 new regression tests: rect.angle changes on rotate, axis is
re-derived from rotated rect. 109/109 tests green.
2026-09-14 11:23:00 -07:00
Ty 0d06e6f7b7 UAT-3: browser gate (hard stop) + iPad Safari fix
Spec CAPTURE.md §Browsers: Phone iOS Safari / Android Chrome, PC
Chrome / Edge / Firefox, others hard stop.

- browserGate.js: UA detection + allowlist (pure, DOM-free)
- +layout.svelte: renders hard-stop panel when unsupported
- iPadOS 13+ reports as Macintosh — added Safari rule (Version/ +
  Safari/ without Chrome/) so iPad Safari is not blocked
- 27 unit tests incl. iPad Safari regression
- 107/107 full suite green
2026-09-14 07:44:49 -07:00
Ty a83c9239ff UAT-7: fix auto key selection — prefer key that removes more background
Root cause: auto selected the key with MORE kept pixels, which always
picked the green key (it keeps 100% of dark non-green backgrounds).
The black key correctly isolates the slab on dark surfaces.

Fix:
- auto now prefers the key with FEWER kept pixels (removed more bg)
  when both are non-empty
- green key has a greenness pre-filter: non-greenish pixels pass
  through (kept) so the black key can handle them, instead of the
  green key keeping 100% of a dark surface
- added 3 regression tests: dark-bg auto selection, green-sheet auto
  selection, green-key passthrough on non-green surfaces

106/106 unit tests green.
2026-09-14 07:41:51 -07:00
Ty 88b9c47200 UAT-4: remove non-spec controls (edge offset, feather) from Mask UI
Spec CAPTURE.md §Mask lists exactly two controls: Sheet and Sensitivity. Edge offset and feather nudge buttons were extra. Removed from the UI; core params (edgeOffset, feather) remain in maskState.js, still unit-tested.
2026-09-14 07:24:42 -07:00
Ty eca306e869 M1-6: record UAT host in INVENTORY.md 2026-09-14 07:08:41 -07:00
Ty 509e2e82a3 Add M1-6 deploy script 2026-09-14 02:14:08 -07:00
Ty 25b1650a8a M1-5: clean up debug artifacts 2026-09-14 02:12:53 -07:00
Ty b124450d0c M1-5: Measure + PNG + full capture UI (TDD)
- measure.js: sampleWidthsPx scanline sampler
- inventory.js: prepareInventoryMetadata
- +page.svelte: full 4-state capture flow (Add photo, Mask, Axis, Measure)
- Canvas overlay: checkerboard mask, bounding rect, axis line
- Inventory PNG: 3:4 portrait, slab centered 80% fill, alpha
- 77/77 unit tests green
2026-09-14 02:11:28 -07:00
Ty 507865e30b Add e2e fixtures: slab-green.jpg, sheet-only-green.jpg, slab.heic 2026-09-14 00:43:58 -07:00
Ty 0284a2211a M1-4: Length axis (TDD)
- Add axis.js: length axis rectangle state, 28 tests
- 71/71 unit tests green
2026-09-14 00:32:42 -07:00
Ty 7e2a1845cf M1-3: Capture + Mask state (TDD)
- Add maskState.js: sheet Auto/Green/Black, sensitivity, edge offset, feather
- Overlay = slab photo + checkerboard on removed px
- Debounced recompute 2.0s after last sensitivity change
- Approve blocked when maskStats empty
- HEIC shows retake notice
- Refactored mask.test.js + extended e2e mask.spec.js
- 43/43 unit tests green
2026-09-14 00:02:36 -07:00
Ty dd011207a0 feat(m1-2,m1-3): deterministic core + mask keying (TDD, green)
Card 2 (deterministic core) + Card 3 (capture+mask geometry):
- src/lib/core/math.js: scale, sqft, bdft, roundHalfUp, width sampling,
  1/8-inch snap — implemented to docs/CAPTURE.md identities.
- src/lib/core/mask.js: keySheet green/black/auto chroma keys + maskStats.
  - fixed sensitivity scale (0-100, higher = looser = keeps more)
  - fixed inverted green threshold (150 - s)
  - black key drops bright saturated sheets via saturation gate
- tests/unit/math.test.js: corrected 3 wrong expected values to match the
  spec (sqft 21x12in = 1.75 not 17.5; bdft 3.06; sample avg 11.25).
- tests/e2e/mask.spec.js: skeleton, skipped pending M1-5 live UI.

Full unit suite green: 24/24. E2e collects clean.
2026-09-13 23:17:36 -07:00
Ty 93666320ef feat(m1-1): scaffold SvelteKit + Dockerfile + TDD test harness
- SvelteKit (JS, adapter-node) home page + /api/health route
- frontend/Dockerfile multi-stage build->serve (slabuploader-m1:local, 349MB)
- Test harness: Vitest unit + Playwright e2e; smoke tests RED->GREEN verified
- Build, image build, and image serve all verified
2026-09-13 22:55:34 -07:00
Ty ba8e5f72f6 docs(m1): calibrated worker delegation policy (prompt framing, verify-before-land) 2026-09-13 22:48:48 -07:00
Ty 92d1a7ec5e docs(m1): plan of record — TDD card breakdown, UAT deployment, fixtures, worker dispatch
- docs/M1-POR.md: scope, TDD method, 6-card breakdown, deployment POR,
  test plan, real-slab fixtures, dev/QA worker dispatch (.202:8081 text,
  .202:8082 vision; one task per endpoint)
- docs/CAPTURE.md: input photo (JPEG + HEIC fallback), 200KB soft goal
- deploy/README.md: Milestone 1 UAT deployment POR (one container, LAN URL)
- tests/fixtures/: 3 black-sheet slab photos + calibration records
  (152422 28x2.25 irregular, 155818 21x1.75, 155754 21x1.75)
2026-09-13 22:37:19 -07:00
Ty 3bae76cea3 docs: Calculate runs measure after length and thickness 2026-09-11 15:16:14 +00:00
Ty 74bd8b2863 docs: restore Milestone 1 user/app use case 2026-09-11 15:14:00 +00:00
Ty 92c4f81640 docs: remove structure check that pins the old doc set 2026-09-11 15:11:23 +00:00
Ty 566ea0675c docs: mark leftover compose as pre-Milestone 1 2026-09-11 15:06:24 +00:00
Ty 7db28438ad docs: strip full-factory release process from Milestone 1 2026-09-11 15:06:04 +00:00
Ty d411352644 docs: strip host-specific deploy inventory 2026-09-11 15:06:02 +00:00
Ty 47abad22bc docs: Milestone 1 deploy is a Docker image; host is runtime 2026-09-11 15:06:00 +00:00
Ty 0f0bd71f35 docs: system seams for client capture vs server Woo 2026-09-11 15:02:56 +00:00
Ty daf03248c4 docs: runtime, one photo, empty mask, browsers 2026-09-11 15:02:47 +00:00
Ty 188905e778 docs: Milestone 1 states, display vs source pixels, mask controls 2026-09-11 14:53:33 +00:00
Ty ea4931e53f docs: state Milestone 1 has no inference URL 2026-09-11 14:43:58 +00:00
Ty baf2f89b3e docs: Milestone 1 is inference-free client code 2026-09-11 14:43:48 +00:00
Ty 9ca4b4520d docs: CAPTURE.md is Milestone 1 only 2026-09-11 14:36:38 +00:00
Ty 53830dcb91 docs: PRD milestones with acceptance 2026-09-11 14:36:25 +00:00
Ty 9418cc2eb5 docs: agent context is Milestone 1 2026-09-11 14:36:16 +00:00
Ty fb9a8c820c docs: use milestone vocabulary in README 2026-09-11 14:36:12 +00:00
Ty fd48105c99 docs: name device draft vs Woo draft in PRD 2026-09-11 14:33:19 +00:00
Ty 121ff7035e docs: Milestone 1 ends at step 8; separate device draft from Woo draft 2026-09-11 14:33:13 +00:00
Ty 65ec1ca3d2 docs: device draft continue or start fresh 2026-09-11 14:30:58 +00:00
Ty ff245529aa docs: lock inventory PNG properties from Woo research 2026-09-11 14:20:51 +00:00
Ty f08569894e docs: PRD starting state is green or black sheet 2026-09-11 14:16:06 +00:00
Ty 82e9e652f8 docs: capture setup on green or black sheet 2026-09-11 14:15:57 +00:00
Ty 10eee46097 docs: PRODUCT.md as PRD with milestones 2026-09-11 14:14:17 +00:00
Ty 781bfd17ec docs: AGENTS.md as invariants and current increment context 2026-09-11 14:14:12 +00:00
Ty b4bff31d58 docs: map PRD, invariants, and current increment 2026-09-11 14:14:07 +00:00
Ty f63f95a730 docs: state mask as background removal 2026-09-11 14:05:24 +00:00
Ty 18294f6ed8 docs: align Slice 1 with capture flow 2026-09-11 14:03:47 +00:00
Ty b01527fb4f docs: add capture user flow and rectangle length axis 2026-09-11 14:03:43 +00:00
Ty fb50e6e7b4 docs: strip editorial language from CAPTURE.md 2026-09-11 14:01:29 +00:00
Ty 6f5ae7e724 docs: strip editorial language from PRODUCT.md 2026-09-11 14:01:24 +00:00
Ty 440fedc90f docs: strip editorial language from AGENTS.md 2026-09-11 14:01:19 +00:00
Ty b9028ec1bd docs: strip editorial language from README 2026-09-11 14:01:13 +00:00
Ty 5bb9f9e7fb docs: clarify archive vs main snapshot 2026-09-11 13:47:46 +00:00
Ty 627f0fd2c0 docs: remove live UAT-PRACTICE.md 2026-09-11 13:47:38 +00:00
Ty cf635aa0b0 docs: remove live PROMPTS.md 2026-09-11 13:47:31 +00:00
Ty 1c64f96b54 docs: remove live Build-release-standard.md 2026-09-11 13:47:26 +00:00
Ty a719fa9fc6 docs: remove live UX.md 2026-09-11 13:47:25 +00:00
Ty bbaab9f2c7 docs: remove live TECH-SPEC-PIPELINE.md 2026-09-11 13:47:18 +00:00
Ty 813af72d98 docs: remove live OPENAPI.md 2026-09-11 13:47:16 +00:00
Ty fb74b28404 docs: remove live DEPLOYMENT.md 2026-09-11 13:47:15 +00:00
Ty bbaa759f5e docs: remove live DATA-MODEL.md 2026-09-11 13:47:14 +00:00
Ty 5346fc8402 docs: remove live CONTENT-WOO.md 2026-09-11 13:47:12 +00:00
Ty dd952441aa docs: remove live IMPL-PLAN.md 2026-09-11 13:47:08 +00:00
Ty 3353f86f62 docs: remove live TEST-SPEC.md 2026-09-11 13:47:07 +00:00
Ty f5b3f4ebe6 docs: remove live UX-DESIGN.md 2026-09-11 13:47:06 +00:00
Ty b36e33e239 docs: remove live ARCHITECTURE.md (see archive + main 13bfa792) 2026-09-11 13:47:05 +00:00
Ty 6e2b9b3008 docs: archive index for pre-simplification specs 2026-09-11 13:46:40 +00:00
Ty 1254bd9cd7 docs: slim README to live file map 2026-09-11 13:46:17 +00:00
Ty 8d95a8e518 docs: replace AGENTS.md with Slice 1 contract 2026-09-11 13:46:13 +00:00
Ty 13ab6097e6 docs: add live CAPTURE spec on doc-simplification 2026-09-11 13:45:59 +00:00
Ty f1c60de355 docs: add live PRODUCT spec on doc-simplification 2026-09-11 13:45:53 +00:00
grokbot_ty 13bfa792bb docs: add release/deploy process with Gitea release workflow
- deploy/RELEASE-PROCESS.md: three build surfaces (dev, UAT, debug),
  Gitea release workflow, naming conventions, promotion and rollback
- AGENTS.md: add deploy/RELEASE-PROCESS.md to doc index

Follows GitHub release management conventions adapted for Gitea.
Dev builds run on cursor machine without tags. UAT builds require
a Gitea release tag. All test submissions use draft status.
2026-09-09 21:46:17 +00:00
Ty 9aa0ca3e92 Update docs/Build-release-standard.md 2026-09-09 21:40:32 +00:00
Ty 5e364cfa41 Update docs/Build-release-standard.md 2026-09-09 21:37:24 +00:00
Ty 478ae2bcc2 Add docs/Build-release-standard 2026-09-09 21:37:09 +00:00
Ty 5c1da50174 docs(structure): single Gates home and honest scaffold targets
Merge docs/structure-pass into main as docs SoT.

Nits fixed on 2c73e5f. check-structure.sh PASSED. Product locks unchanged.
2026-09-09 20:02:29 +00:00
grokbot_ty 2c73e5fa4e docs(structure): fix single-home wording nits
Point UAT at IMPL-PLAN only. Soften AGENTS and IMPL-PLAN so the meanings
table has one home while TEST-SPEC may still map cases to phases.
2026-09-09 19:56:31 +00:00
grokbot_ty 4576df7253 docs(structure): restore Gate B wording and harden pin
Drop the Gate B parenthetical that was not in the frozen AGENTS table.
Require Phase 0 labels in both compose and DEPLOYMENT, and pin the full
client-authoritative math lock phrase.
2026-09-09 19:47:17 +00:00
grokbot_ty 32547cad8c docs(audit): structure-pass decision trail
TSV log for the docs/structure-pass figure-it-out run.
2026-09-09 19:45:25 +00:00
grokbot_ty f855f91b8b docs: label Phase 0 scaffold targets on docs-only main
TEST-SPEC harness paths and compose Dockerfiles are deliverables until code
lands. Cases stay not run. Stops agents inventing alternate test trees.
2026-09-09 19:45:25 +00:00
grokbot_ty 8d65984936 docs: single Gates home and honest UX ownership
Move Gate A/B/C meanings to IMPL-PLAN. List UX-DESIGN as non-normative with
signed UX.md winning conflicts. List INVENTORY in AGENTS §0.
2026-09-09 19:45:25 +00:00
grokbot_ty bad96f944b docs(checks): add structure pin harness
Fails closed until ownership, calendar home, UX demotion, TEST-SPEC honesty,
and Gate A lock phrases hold. Reviewers re-run docs/checks/check-structure.sh.
2026-09-09 19:45:25 +00:00
93 changed files with 7003 additions and 3683 deletions
+7
View File
@@ -0,0 +1,7 @@
ts phase decision why evidence result
2026-09-09T19:43:56Z harness ran check-structure.sh on untouched main tip capture red baseline before structure edits docs/checks/check-structure.sh FAILED as expected (red baseline)
2026-09-09T19:43:56Z frame done predicate is check-structure.sh exit 0 with lock phrases intact falsifiable gate for structure pass .audit/docs-structure-pass.tsv open
2026-09-09T19:45:25Z unit AGENTS ownership complete; Gates table removed; UX-DESIGN demoted; IMPL-PLAN owns gate meanings subtract calendar restatement and close ownership gap AGENTS.md,docs/UX-DESIGN.md,docs/IMPL-PLAN.md check-structure PASSED
2026-09-09T19:45:25Z unit TEST-SPEC and deploy docs label missing tree as Phase 0 targets stop agents inventing harness paths that are not on main docs/TEST-SPEC.md,docs/DEPLOYMENT.md,deploy/docker-compose.yml,README.md check-structure PASSED
2026-09-09T19:45:25Z verify ran docs/checks/check-structure.sh after all edits prove done predicate on real artifact docs/checks/check-structure.sh exit 0 VERIFIED
2026-09-09T19:47:17Z attention-fix restored Gate B meaning to original AGENTS wording; hardened check-structure for both deploy files and fuller math lock phrase Attention review flagged Gate B parenthetical as lock drift and weak deploy grep docs/IMPL-PLAN.md,docs/checks/check-structure.sh check-structure PASSED
1 ts phase decision why evidence result
2 2026-09-09T19:43:56Z harness ran check-structure.sh on untouched main tip capture red baseline before structure edits docs/checks/check-structure.sh FAILED as expected (red baseline)
3 2026-09-09T19:43:56Z frame done predicate is check-structure.sh exit 0 with lock phrases intact falsifiable gate for structure pass .audit/docs-structure-pass.tsv open
4 2026-09-09T19:45:25Z unit AGENTS ownership complete; Gates table removed; UX-DESIGN demoted; IMPL-PLAN owns gate meanings subtract calendar restatement and close ownership gap AGENTS.md,docs/UX-DESIGN.md,docs/IMPL-PLAN.md check-structure PASSED
5 2026-09-09T19:45:25Z unit TEST-SPEC and deploy docs label missing tree as Phase 0 targets stop agents inventing harness paths that are not on main docs/TEST-SPEC.md,docs/DEPLOYMENT.md,deploy/docker-compose.yml,README.md check-structure PASSED
6 2026-09-09T19:45:25Z verify ran docs/checks/check-structure.sh after all edits prove done predicate on real artifact docs/checks/check-structure.sh exit 0 VERIFIED
7 2026-09-09T19:47:17Z attention-fix restored Gate B meaning to original AGENTS wording; hardened check-structure for both deploy files and fuller math lock phrase Attention review flagged Gate B parenthetical as lock drift and weak deploy grep docs/IMPL-PLAN.md,docs/checks/check-structure.sh check-structure PASSED
+454
View File
@@ -0,0 +1,454 @@
// this file is generated — do not edit it
/// <reference types="@sveltejs/kit" />
/**
* This module provides access to environment variables that are injected _statically_ into your bundle at build time and are limited to _private_ access.
*
* | | Runtime | Build time |
* | ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
* | Private | [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private) | [`$env/static/private`](https://svelte.dev/docs/kit/$env-static-private) |
* | Public | [`$env/dynamic/public`](https://svelte.dev/docs/kit/$env-dynamic-public) | [`$env/static/public`](https://svelte.dev/docs/kit/$env-static-public) |
*
* Static environment variables are [loaded by Vite](https://vitejs.dev/guide/env-and-mode.html#env-files) from `.env` files and `process.env` at build time and then statically injected into your bundle at build time, enabling optimisations like dead code elimination.
*
* **_Private_ access:**
*
* - This module cannot be imported into client-side code
* - This module only includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](https://svelte.dev/docs/kit/configuration#env) (if configured)
*
* For example, given the following build time environment:
*
* ```env
* ENVIRONMENT=production
* PUBLIC_BASE_URL=http://site.com
* ```
*
* With the default `publicPrefix` and `privatePrefix`:
*
* ```ts
* import { ENVIRONMENT, PUBLIC_BASE_URL } from '$env/static/private';
*
* console.log(ENVIRONMENT); // => "production"
* console.log(PUBLIC_BASE_URL); // => throws error during build
* ```
*
* The above values will be the same _even if_ different values for `ENVIRONMENT` or `PUBLIC_BASE_URL` are set at runtime, as they are statically replaced in your code with their build time values.
*/
declare module '$env/static/private' {
export const LESSOPEN: string;
export const TMUX: string;
export const HERMES_DELEGATED_CHILD_CONTEXT: string;
export const timezone: string;
export const CUDACXX: string;
export const BROWSERBASE_PROXIES: string;
export const HERMES_RESTART_DRAIN_TIMEOUT: string;
export const _HERMES_GATEWAY: string;
export const AI_AGENT: string;
export const USER: string;
export const SSH_CLIENT: string;
export const npm_config_user_agent: string;
export const TERMINAL_CONTAINER_CPU: string;
export const AGENT_BROWSER_EXECUTABLE_PATH: string;
export const TERMINAL_DOCKER_ENV: string;
export const TERMINAL_CWD: string;
export const HERMES_REAL_HOME: string;
export const XDG_SESSION_TYPE: string;
export const npm_node_execpath: string;
export const SHLVL: string;
export const HERMES_PROFILE: string;
export const npm_config_noproxy: string;
export const HOME: string;
export const OLDPWD: string;
export const TERMINAL_DOCKER_FORWARD_ENV: string;
export const TERM_PROGRAM_VERSION: string;
export const BROWSER_SESSION_TIMEOUT: string;
export const HERMES_KANBAN_BOARD: string;
export const SSH_TTY: string;
export const HERMES_HOME: string;
export const npm_package_json: string;
export const TERMINAL_DOCKER_EXTRA_ARGS: string;
export const HF_HUB_DISABLE_XET: string;
export const IM_CONFIG_ENTRY: string;
export const TERMINAL_DOCKER_IMAGE: string;
export const PAGER: string;
export const TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE: string;
export const TERMINAL_CONTAINER_MEMORY: string;
export const SSL_CERT_FILE: string;
export const TERMINAL_CONTAINER_PERSISTENT: string;
export const npm_config_userconfig: string;
export const npm_config_local_prefix: string;
export const HERMES_TURN_LEASE_TIMEOUT: string;
export const HERMES_MEDIA_DELIVERY_STRICT: string;
export const TERMINAL_MODAL_IMAGE: string;
export const DBUS_SESSION_BUS_ADDRESS: string;
export const COLORTERM: string;
export const TERMINAL_DOCKER_NETWORK: string;
export const file_read_max_chars: string;
export const COLOR: string;
export const DEBUGINFOD_URLS: string;
export const TERMINAL_DOCKER_VOLUMES: string;
export const TERMINAL_ENV: string;
export const TERMINAL_VERCEL_RUNTIME: string;
export const LOGNAME: string;
export const HERMES_KANBAN_DB: string;
export const IMAGE_TOOLS_DEBUG: string;
export const _: string;
export const npm_config_prefix: string;
export const npm_config_npm_version: string;
export const group_sessions_per_user: string;
export const HERMES_KANBAN_WORKSPACES_ROOT: string;
export const HERMES_SINGLE_QUERY_SESSION: string;
export const XDG_SESSION_CLASS: string;
export const BROWSERBASE_ADVANCED_STEALTH: string;
export const paste_collapse_threshold: string;
export const TERM: string;
export const TERMINAL_DAYTONA_IMAGE: string;
export const XDG_SESSION_ID: string;
export const npm_config_cache: string;
export const TERMINAL_TEMP_DIR: string;
export const TERMINAL_LIFETIME_SECONDS: string;
export const TERMINAL_TIMEOUT: string;
export const HERMES_GATEWAY_BUSY_INPUT_MODE: string;
export const paste_collapse_char_threshold: string;
export const TERMINAL_DOCKER_SHARED_CONTAINER_KEY: string;
export const npm_config_node_gyp: string;
export const PATH: string;
export const HERMES_AGENT_TIMEOUT: string;
export const NODE: string;
export const TERMINAL_DOCKER_SHM_SIZE: string;
export const HERMES_KANBAN_WORKSPACE: string;
export const XDG_RUNTIME_DIR: string;
export const TERMINAL_PERSISTENT_SHELL: string;
export const LANG: string;
export const HERMES_QUIET: string;
export const MOA_TOOLS_DEBUG: string;
export const HERMES_MEDIA_TRUST_RECENT_FILES: string;
export const LS_COLORS: string;
export const HERMES_MEDIA_TRUST_RECENT_SECONDS: string;
export const HERMES_MAX_ITERATIONS: string;
export const TERM_PROGRAM: string;
export const npm_lifecycle_script: string;
export const HERMES_SESSION_ID: string;
export const HERMES_AGENT_TIMEOUT_WARNING: string;
export const prefill_messages_file: string;
export const SHELL: string;
export const HERMES_AGENT_NOTIFY_INTERVAL: string;
export const TERMINAL_DEGRADED_MODE: string;
export const TERMINAL_MODAL_MODE: string;
export const npm_lifecycle_event: string;
export const WEB_TOOLS_DEBUG: string;
export const VISION_TOOLS_DEBUG: string;
export const LESSCLOSE: string;
export const TERMINAL_CONTAINER_DISK: string;
export const TERMINAL_DOCKER_RUN_AS_HOST_USER: string;
export const GIT_PAGER: string;
export const paste_collapse_threshold_fallback: string;
export const npm_config_globalconfig: string;
export const npm_config_init_module: string;
export const PWD: string;
export const HERMES_INTERACTIVE: string;
export const _config_version: string;
export const HERMES_AUTO_CONTINUE_FRESHNESS: string;
export const npm_execpath: string;
export const SSH_CONNECTION: string;
export const XDG_DATA_DIRS: string;
export const npm_config_global_prefix: string;
export const hooks_auto_accept: string;
export const npm_command: string;
export const TMUX_PLUGIN_MANAGER_PATH: string;
export const BROWSER_INACTIVITY_TIMEOUT: string;
export const HERMES_REDACT_SECRETS: string;
export const HERMES_CUSTOM_192_168_1_203_8084_API_KEY: string;
export const TERMINAL_SINGULARITY_IMAGE: string;
export const TMUX_PANE: string;
export const TERMINAL_HOME_MODE: string;
export const TERMINAL_DOCKER_SNAP_COMPAT: string;
export const HERMES_AGENT: string;
export const HERMES_SESSION_SOURCE: string;
export const INIT_CWD: string;
export const EDITOR: string;
export const TEST: string;
export const VITEST: string;
export const NODE_ENV: string;
}
/**
* This module provides access to environment variables that are injected _statically_ into your bundle at build time and are _publicly_ accessible.
*
* | | Runtime | Build time |
* | ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
* | Private | [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private) | [`$env/static/private`](https://svelte.dev/docs/kit/$env-static-private) |
* | Public | [`$env/dynamic/public`](https://svelte.dev/docs/kit/$env-dynamic-public) | [`$env/static/public`](https://svelte.dev/docs/kit/$env-static-public) |
*
* Static environment variables are [loaded by Vite](https://vitejs.dev/guide/env-and-mode.html#env-files) from `.env` files and `process.env` at build time and then statically injected into your bundle at build time, enabling optimisations like dead code elimination.
*
* **_Public_ access:**
*
* - This module _can_ be imported into client-side code
* - **Only** variables that begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) (which defaults to `PUBLIC_`) are included
*
* For example, given the following build time environment:
*
* ```env
* ENVIRONMENT=production
* PUBLIC_BASE_URL=http://site.com
* ```
*
* With the default `publicPrefix` and `privatePrefix`:
*
* ```ts
* import { ENVIRONMENT, PUBLIC_BASE_URL } from '$env/static/public';
*
* console.log(ENVIRONMENT); // => throws error during build
* console.log(PUBLIC_BASE_URL); // => "http://site.com"
* ```
*
* The above values will be the same _even if_ different values for `ENVIRONMENT` or `PUBLIC_BASE_URL` are set at runtime, as they are statically replaced in your code with their build time values.
*/
declare module '$env/static/public' {
}
/**
* This module provides access to environment variables set _dynamically_ at runtime and that are limited to _private_ access.
*
* | | Runtime | Build time |
* | ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
* | Private | [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private) | [`$env/static/private`](https://svelte.dev/docs/kit/$env-static-private) |
* | Public | [`$env/dynamic/public`](https://svelte.dev/docs/kit/$env-dynamic-public) | [`$env/static/public`](https://svelte.dev/docs/kit/$env-static-public) |
*
* Dynamic environment variables are defined by the platform you're running on. For example if you're using [`adapter-node`](https://github.com/sveltejs/kit/tree/main/packages/adapter-node) (or running [`vite preview`](https://svelte.dev/docs/kit/cli)), this is equivalent to `process.env`.
*
* **_Private_ access:**
*
* - This module cannot be imported into client-side code
* - This module includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](https://svelte.dev/docs/kit/configuration#env) (if configured)
*
* > [!NOTE] In `dev`, `$env/dynamic` includes environment variables from `.env`. In `prod`, this behavior will depend on your adapter.
*
* > [!NOTE] To get correct types, environment variables referenced in your code should be declared (for example in an `.env` file), even if they don't have a value until the app is deployed:
* >
* > ```env
* > MY_FEATURE_FLAG=
* > ```
* >
* > You can override `.env` values from the command line like so:
* >
* > ```sh
* > MY_FEATURE_FLAG="enabled" npm run dev
* > ```
*
* For example, given the following runtime environment:
*
* ```env
* ENVIRONMENT=production
* PUBLIC_BASE_URL=http://site.com
* ```
*
* With the default `publicPrefix` and `privatePrefix`:
*
* ```ts
* import { env } from '$env/dynamic/private';
*
* console.log(env.ENVIRONMENT); // => "production"
* console.log(env.PUBLIC_BASE_URL); // => undefined
* ```
*/
declare module '$env/dynamic/private' {
export const env: {
LESSOPEN: string;
TMUX: string;
HERMES_DELEGATED_CHILD_CONTEXT: string;
timezone: string;
CUDACXX: string;
BROWSERBASE_PROXIES: string;
HERMES_RESTART_DRAIN_TIMEOUT: string;
_HERMES_GATEWAY: string;
AI_AGENT: string;
USER: string;
SSH_CLIENT: string;
npm_config_user_agent: string;
TERMINAL_CONTAINER_CPU: string;
AGENT_BROWSER_EXECUTABLE_PATH: string;
TERMINAL_DOCKER_ENV: string;
TERMINAL_CWD: string;
HERMES_REAL_HOME: string;
XDG_SESSION_TYPE: string;
npm_node_execpath: string;
SHLVL: string;
HERMES_PROFILE: string;
npm_config_noproxy: string;
HOME: string;
OLDPWD: string;
TERMINAL_DOCKER_FORWARD_ENV: string;
TERM_PROGRAM_VERSION: string;
BROWSER_SESSION_TIMEOUT: string;
HERMES_KANBAN_BOARD: string;
SSH_TTY: string;
HERMES_HOME: string;
npm_package_json: string;
TERMINAL_DOCKER_EXTRA_ARGS: string;
HF_HUB_DISABLE_XET: string;
IM_CONFIG_ENTRY: string;
TERMINAL_DOCKER_IMAGE: string;
PAGER: string;
TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE: string;
TERMINAL_CONTAINER_MEMORY: string;
SSL_CERT_FILE: string;
TERMINAL_CONTAINER_PERSISTENT: string;
npm_config_userconfig: string;
npm_config_local_prefix: string;
HERMES_TURN_LEASE_TIMEOUT: string;
HERMES_MEDIA_DELIVERY_STRICT: string;
TERMINAL_MODAL_IMAGE: string;
DBUS_SESSION_BUS_ADDRESS: string;
COLORTERM: string;
TERMINAL_DOCKER_NETWORK: string;
file_read_max_chars: string;
COLOR: string;
DEBUGINFOD_URLS: string;
TERMINAL_DOCKER_VOLUMES: string;
TERMINAL_ENV: string;
TERMINAL_VERCEL_RUNTIME: string;
LOGNAME: string;
HERMES_KANBAN_DB: string;
IMAGE_TOOLS_DEBUG: string;
_: string;
npm_config_prefix: string;
npm_config_npm_version: string;
group_sessions_per_user: string;
HERMES_KANBAN_WORKSPACES_ROOT: string;
HERMES_SINGLE_QUERY_SESSION: string;
XDG_SESSION_CLASS: string;
BROWSERBASE_ADVANCED_STEALTH: string;
paste_collapse_threshold: string;
TERM: string;
TERMINAL_DAYTONA_IMAGE: string;
XDG_SESSION_ID: string;
npm_config_cache: string;
TERMINAL_TEMP_DIR: string;
TERMINAL_LIFETIME_SECONDS: string;
TERMINAL_TIMEOUT: string;
HERMES_GATEWAY_BUSY_INPUT_MODE: string;
paste_collapse_char_threshold: string;
TERMINAL_DOCKER_SHARED_CONTAINER_KEY: string;
npm_config_node_gyp: string;
PATH: string;
HERMES_AGENT_TIMEOUT: string;
NODE: string;
TERMINAL_DOCKER_SHM_SIZE: string;
HERMES_KANBAN_WORKSPACE: string;
XDG_RUNTIME_DIR: string;
TERMINAL_PERSISTENT_SHELL: string;
LANG: string;
HERMES_QUIET: string;
MOA_TOOLS_DEBUG: string;
HERMES_MEDIA_TRUST_RECENT_FILES: string;
LS_COLORS: string;
HERMES_MEDIA_TRUST_RECENT_SECONDS: string;
HERMES_MAX_ITERATIONS: string;
TERM_PROGRAM: string;
npm_lifecycle_script: string;
HERMES_SESSION_ID: string;
HERMES_AGENT_TIMEOUT_WARNING: string;
prefill_messages_file: string;
SHELL: string;
HERMES_AGENT_NOTIFY_INTERVAL: string;
TERMINAL_DEGRADED_MODE: string;
TERMINAL_MODAL_MODE: string;
npm_lifecycle_event: string;
WEB_TOOLS_DEBUG: string;
VISION_TOOLS_DEBUG: string;
LESSCLOSE: string;
TERMINAL_CONTAINER_DISK: string;
TERMINAL_DOCKER_RUN_AS_HOST_USER: string;
GIT_PAGER: string;
paste_collapse_threshold_fallback: string;
npm_config_globalconfig: string;
npm_config_init_module: string;
PWD: string;
HERMES_INTERACTIVE: string;
_config_version: string;
HERMES_AUTO_CONTINUE_FRESHNESS: string;
npm_execpath: string;
SSH_CONNECTION: string;
XDG_DATA_DIRS: string;
npm_config_global_prefix: string;
hooks_auto_accept: string;
npm_command: string;
TMUX_PLUGIN_MANAGER_PATH: string;
BROWSER_INACTIVITY_TIMEOUT: string;
HERMES_REDACT_SECRETS: string;
HERMES_CUSTOM_192_168_1_203_8084_API_KEY: string;
TERMINAL_SINGULARITY_IMAGE: string;
TMUX_PANE: string;
TERMINAL_HOME_MODE: string;
TERMINAL_DOCKER_SNAP_COMPAT: string;
HERMES_AGENT: string;
HERMES_SESSION_SOURCE: string;
INIT_CWD: string;
EDITOR: string;
TEST: string;
VITEST: string;
NODE_ENV: string;
[key: `PUBLIC_${string}`]: undefined;
[key: `${string}`]: string | undefined;
}
}
/**
* This module provides access to environment variables set _dynamically_ at runtime and that are _publicly_ accessible.
*
* | | Runtime | Build time |
* | ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
* | Private | [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private) | [`$env/static/private`](https://svelte.dev/docs/kit/$env-static-private) |
* | Public | [`$env/dynamic/public`](https://svelte.dev/docs/kit/$env-dynamic-public) | [`$env/static/public`](https://svelte.dev/docs/kit/$env-static-public) |
*
* Dynamic environment variables are defined by the platform you're running on. For example if you're using [`adapter-node`](https://github.com/sveltejs/kit/tree/main/packages/adapter-node) (or running [`vite preview`](https://svelte.dev/docs/kit/cli)), this is equivalent to `process.env`.
*
* **_Public_ access:**
*
* - This module _can_ be imported into client-side code
* - **Only** variables that begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) (which defaults to `PUBLIC_`) are included
*
* > [!NOTE] In `dev`, `$env/dynamic` includes environment variables from `.env`. In `prod`, this behavior will depend on your adapter.
*
* > [!NOTE] To get correct types, environment variables referenced in your code should be declared (for example in an `.env` file), even if they don't have a value until the app is deployed:
* >
* > ```env
* > MY_FEATURE_FLAG=
* > ```
* >
* > You can override `.env` values from the command line like so:
* >
* > ```sh
* > MY_FEATURE_FLAG="enabled" npm run dev
* > ```
*
* For example, given the following runtime environment:
*
* ```env
* ENVIRONMENT=production
* PUBLIC_BASE_URL=http://example.com
* ```
*
* With the default `publicPrefix` and `privatePrefix`:
*
* ```ts
* import { env } from '$env/dynamic/public';
* console.log(env.ENVIRONMENT); // => undefined, not public
* console.log(env.PUBLIC_BASE_URL); // => "http://example.com"
* ```
*
* ```
*
* ```
*/
declare module '$env/dynamic/public' {
export const env: {
[key: `PUBLIC_${string}`]: string | undefined;
}
}
+1
View File
@@ -0,0 +1 @@
// See https://svelte.dev/docs/kit/environment-variables for more information
+38
View File
@@ -0,0 +1,38 @@
// in dev, this makes Vite inject its client as this module's first dependency,
// so that global constant replacements are installed before any other module
// (including user hooks) evaluates. In build it's inert.
import.meta.hot;
export { matchers } from './matchers.js';
export const nodes = [
() => import('./nodes/0'),
() => import('./nodes/1')
];
export const server_loads = [];
export const dictionary = {
};
export const hooks = {
handleError: (({ error }) => { console.error(error) }),
reroute: (() => {}),
transport: {}
};
export const decoders = Object.fromEntries(Object.entries(hooks.transport).map(([k, v]) => [k, v.decode]));
export const encoders = Object.fromEntries(Object.entries(hooks.transport).map(([k, v]) => [k, v.encode]));
export const hash = false;
export const decode = (type, value) => decoders[type](value);
export { default as root } from '../root.js';
export const get_error_template = () => import('../shared/error-template.js').then(m => m.default);
+1
View File
@@ -0,0 +1 @@
export const matchers = {};
+1
View File
@@ -0,0 +1 @@
export { default as component } from "../../../../frontend/node_modules/@sveltejs/kit/src/runtime/components/svelte-5/layout.svelte";
+1
View File
@@ -0,0 +1 @@
export { default as component } from "../../../../frontend/node_modules/@sveltejs/kit/src/runtime/components/svelte-5/error.svelte";
@@ -0,0 +1 @@
export default ({ status, message }) => "<!doctype html>\n<html lang=\"en\">\n\t<head>\n\t\t<meta charset=\"utf-8\" />\n\t\t<title>" + message + "</title>\n\n\t\t<style>\n\t\t\tbody {\n\t\t\t\t--bg: white;\n\t\t\t\t--fg: #222;\n\t\t\t\t--divider: #ccc;\n\t\t\t\tbackground: var(--bg);\n\t\t\t\tcolor: var(--fg);\n\t\t\t\tfont-family:\n\t\t\t\t\tsystem-ui,\n\t\t\t\t\t-apple-system,\n\t\t\t\t\tBlinkMacSystemFont,\n\t\t\t\t\t'Segoe UI',\n\t\t\t\t\tRoboto,\n\t\t\t\t\tOxygen,\n\t\t\t\t\tUbuntu,\n\t\t\t\t\tCantarell,\n\t\t\t\t\t'Open Sans',\n\t\t\t\t\t'Helvetica Neue',\n\t\t\t\t\tsans-serif;\n\t\t\t\tdisplay: flex;\n\t\t\t\talign-items: center;\n\t\t\t\tjustify-content: center;\n\t\t\t\theight: 100vh;\n\t\t\t\tmargin: 0;\n\t\t\t}\n\n\t\t\t.error {\n\t\t\t\tdisplay: flex;\n\t\t\t\talign-items: center;\n\t\t\t\tmax-width: 32rem;\n\t\t\t\tmargin: 0 1rem;\n\t\t\t}\n\n\t\t\t.status {\n\t\t\t\tfont-weight: 200;\n\t\t\t\tfont-size: 3rem;\n\t\t\t\tline-height: 1;\n\t\t\t\tposition: relative;\n\t\t\t\ttop: -0.05rem;\n\t\t\t}\n\n\t\t\t.message {\n\t\t\t\tborder-left: 1px solid var(--divider);\n\t\t\t\tpadding: 0 0 0 1rem;\n\t\t\t\tmargin: 0 0 0 1rem;\n\t\t\t\tmin-height: 2.5rem;\n\t\t\t\tdisplay: flex;\n\t\t\t\talign-items: center;\n\t\t\t}\n\n\t\t\t.message h1 {\n\t\t\t\tfont-weight: 400;\n\t\t\t\tfont-size: 1em;\n\t\t\t\tmargin: 0;\n\t\t\t}\n\n\t\t\t@media (prefers-color-scheme: dark) {\n\t\t\t\tbody {\n\t\t\t\t\t--bg: #222;\n\t\t\t\t\t--fg: #ddd;\n\t\t\t\t\t--divider: #666;\n\t\t\t\t}\n\t\t\t}\n\t\t</style>\n\t</head>\n\t<body>\n\t\t<div class=\"error\">\n\t\t\t<span class=\"status\">" + status + "</span>\n\t\t\t<div class=\"message\">\n\t\t\t\t<h1>" + message + "</h1>\n\t\t\t</div>\n\t\t</div>\n\t</body>\n</html>\n";
+50
View File
@@ -0,0 +1,50 @@
{
"compilerOptions": {
"paths": {
"$app/types": [
"./types/index.d.ts"
]
},
"rootDirs": [
"..",
"./types"
],
"verbatimModuleSyntax": true,
"isolatedModules": true,
"lib": [
"esnext",
"DOM",
"DOM.Iterable"
],
"moduleResolution": "bundler",
"module": "esnext",
"noEmit": true,
"target": "esnext"
},
"include": [
"ambient.d.ts",
"env.d.ts",
"non-ambient.d.ts",
"./types/**/$types.d.ts",
"../vite.config.js",
"../vite.config.ts",
"../src/**/*.js",
"../src/**/*.ts",
"../src/**/*.svelte",
"../test/**/*.js",
"../test/**/*.ts",
"../test/**/*.svelte",
"../tests/**/*.js",
"../tests/**/*.ts",
"../tests/**/*.svelte"
],
"exclude": [
"../node_modules/**",
"../src/service-worker.js",
"../src/service-worker/**/*.js",
"../src/service-worker.ts",
"../src/service-worker/**/*.ts",
"../src/service-worker.d.ts",
"../src/service-worker/**/*.d.ts"
]
}
+21 -190
View File
@@ -1,197 +1,28 @@
# AGENTS.md — SlabUploader
# AGENTS.md
Working contract for coding agents. Read before writing code.
## Agent context
Status: **Gate A freeze** · signed 2026-08-31 PT · docs cut to `main` 2026-09-06 · SoT: Gitea `Ty_Tech/SlabUploader` on **gitea-atd** (not mirrors).
Read this file and `docs/CAPTURE.md`.
Implement Milestone 1 only. Specification: `docs/CAPTURE.md`.
PRD: `docs/PRODUCT.md` for destination and field names. Do not implement Milestone 2, 3, or 4.
---
## Milestone 1
## 0. Where each doc lives
Capture.
Acceptance: on a phone, one real slab, approved mask, approved length-axis rectangle, user length and thickness, inventory PNG on screen, widths and board feet on screen.
| Doc | Owns |
|---|---|
| `docs/TECH-SPEC-PIPELINE.md` | Deterministic math, image prep, constants, test vectors |
| `docs/ARCHITECTURE.md` | Hybrid topology, what-runs-where, secrets why, status machine |
| `AGENTS.md` | Hard rules for coding agents (locks below) |
| `docs/DATA-MODEL.md` | Store row / schema facts |
| `docs/OPENAPI.md` | Wire / HTTP contracts |
| `docs/CONTENT-WOO.md` | Listing copy and Woo payload |
| `docs/PROMPTS.md` | Call 1 / Call 2 prompt files |
| `docs/DEPLOYMENT.md` | Compose, Caddy, secrets placement, ops |
| `docs/UX.md` | Presentation: what the mill owner sees and does |
| `docs/TEST-SPEC.md` | Engineer test bar: pyramid cases, phased by gate, through PROD |
| `docs/UAT-PRACTICE.md` | Walkable practice UAT for `SLAB-UAT-*` |
| `docs/IMPL-PLAN.md` | Phases 0–6. Phase 2 is a deferred stub (offline PWA / OCR / ruler). |
| `README.md` | Orientation only |
| `docs/archive/PRD-2026-08.txt` | Frozen archive. Not a source for new work. |
Milestone 1 is inference-free. Background removal, rectangle, measurements, and PNG encode run in the browser as ordinary code. There is no inference URL and no model call in this milestone.
Live docs agree. If two live files disagree, that is a docs bug: fix the files, then continue.
## Invariants
### Known open gaps
- Issue #4: exact minimum browser version pins and deeper load-bearing API inventory. Phone + PC families are already locked in `docs/UX.md` / TECH-SPEC.
---
## 0b. Gates (human map)
| Label | Human name | What it means |
|---|---|---|
| Gate A | Docs freeze | Product locks written into the repo |
| Gate B | Run-host setup | Inventory the real host, deploy skeleton |
| Gate C | First draft listing | One Woo draft listing with inference OFF |
Phase map: **Phase 0 = Gates A+B.** **Gate C = early Phase 1** claimable publish slice. Call 1/2 after Gate C, still inside POC. Depth: `docs/IMPL-PLAN.md`.
### Freeze provenance (Gate A)
| SHA | What locked |
|---|---|
| `a94d81d` | gitea-atd `Ty_Tech/SlabUploader` as remotes SoT |
| `457711b` | AGENTS.md + hybrid IMPL Phase 0 |
| `4ec478f` | Contradiction patches (README/PRD/Woo/DEPLOYMENT) |
| `4d9f307` / `4e97770` | Inference review + hybrid capture pipeline (pre-freeze baseline) |
Docs refactor is on `main` (cut 2026-09-06). Product locks above are unchanged.
### Known stale PRD lines
`docs/archive/PRD-2026-08.txt` is frozen history. These PRD lines are superseded by live docs:
FR17 (fig-* 1+, feat-* 0+), FR19 (species $/bdft only), FR40 (client-side, not server-side
processing), NFR server normalization timing, FR42 (env-agnostic DEPLOYMENT + deploy/INVENTORY.md).
---
## 1. Topology (locked — hybrid)
**Client (SvelteKit) owns the happy path:**
- Capture 1–5 photos
- Sheet detect + chroma-key / black threshold + **four knobs inline on capture** (sheet, sensitivity, edge offset, feather) with **live re-run** and mask overlay on the source photo
- Mask overlay + **user confirm** before measurement
- Length axis overlay (rotate / confirm)
- sqft, bdft, 6" width samples
- 3:4 transparent PNG, 80% fill at extremes, shorter side ≥ 1600 when source allows
- Draft payload: originals + processed PNGs + length/thickness/SKU/sqft/bdft/widths
**Server (FastAPI) owns:**
- Store drafts / settings / taxonomy cache
- U2Net "Try harder" — **deferred from POC**, not deleted. Architecture keeps the one-photo server path for awkward backgrounds post-POC. POC mask tuning is **client-side only** (sheet + four knobs, live re-run).
- WooCommerce (taxonomy sync, SKU check, create product) — browser never calls Woo
- Inference **proxy** (Call 1 / Call 2) — keys never in browser
- Prompt files (server text files, read fresh)
Happy path never leaves the phone until the user continues after confirmed mask + numbers.
Deferred work and non-goals are in `docs/ARCHITECTURE.md` and `docs/IMPL-PLAN.md`.
Depth: `docs/ARCHITECTURE.md`.
---
## 2. Deferred work
The MVP is online-only. Measuring lives in the browser. Manual SKU entry, manual length, and client-side measure/crop are the source of truth. Undersized source warns and requires retake. The server stores client-sent numbers; there is no server happy-path pipeline for the deterministic core.
Phase 2 is a deferred stub for offline PWA, OCR, and ruler detection. Post-POC items: LoRA / fine-tune, figure-/category-weighted pricing (v1.5), auto-dimension overlay (v1.5), bulk publish, staff roles, analytics, SKU update path. Depth: `docs/ARCHITECTURE.md` §4 and `docs/IMPL-PLAN.md` Phase 2.
---
## 3. Deterministic core (non-negotiable)
Encode TECH-SPEC exactly:
- **bdft = sqft × thickness_in** (identity: 1 sqft @ 1" = 1 bdft).
- Units: inches in 1/8" steps; sqft/bdft 2 decimals; price half-up 2 decimals.
- Manual length, thickness, SKU, price always win.
- Image prep: sheet/sliders → mask confirm → length axis confirm → 3:4 PNG / 80% fill / ≥1600px when source allows.
- Undersized source warns and requires retake. Photo is not publishable until retake.
- Pricing: species `$/bdft` from Settings, seeded by Woo species sync; `rec = bdft × price_per_bdft`; user override sticks; missing rule leaves rec empty, manual allowed.
- Port TECH-SPEC **TV-1 through TV-10** (including TV-10 Rounding). Client (or shared pure modules the client uses) is authoritative for math; server **stores** client-sent numbers.
Depth: `docs/TECH-SPEC-PIPELINE.md`.
---
## 4. Secrets and settings
**Server-side only:**
- Woo WordPress username + application password (dedicated low-privilege WP user for product create/edit + media)
- Inference API key and endpoint (treat inference URL as sensitive)
- AES master key (`SLAB_AES_KEY` env only; never in DB or repo)
**`WOO_BASE_URL`:** compose / host `.env` only (`https://` required). Settings shows it read-only. Not a SQLite settings row. FastAPI rejects `http://` at startup.
**Server:** AES-GCM at rest in SQLite for Woo Application Password + inference secrets. Settings UI POSTs username + application password to FastAPI; server encrypts. All Woo and inference calls are server-side. Rotate by revoking the application password in WP Users → Profile and re-entering in Settings. WooCommerce consumer keys (`ck_`/`cs_`) are not implemented.
**Browser may persist (non-secret):** sheet mode, sensitivity, edge offset, feather (localStorage OK; reset-to-default required).
Why/flow: `docs/ARCHITECTURE.md` §5. Ciphertext key inventory: `docs/DATA-MODEL.md` settings table.
---
## 5. Woo UAT and create status (Ty locked 2026-08-31)
- Store URL: **`WOO_BASE_URL`** from Docker Compose (`https://` only). Intended UAT/POC store is Whidbey Wood Store production; the compose value is the SoT, not a Settings field.
- Mid-phase UAT creates: Woo status **draft**, SKU prefix **`SLAB-UAT-*`**
- Settings field **`woo_create_status`**: **`draft | publish`**, default **`draft`**
- Hard rule: if SKU matches `SLAB-UAT-*`, force **Woo draft** even if Settings say publish
- Final POC success: one real (non-UAT) SKU → **Woo publish** only after Ty review
- Duplicate SKU → stop; UI maps **409** to the SKU field (edit SKU or open existing)
- After successful publish: purge originals + processed images on server
Woo draft/publish status is separate from slab lifecycle status (§7).
Payload and publish sequence depth: `docs/CONTENT-WOO.md`. Key only: DATA-MODEL `woo_create_status`.
---
## 6. Inference (inside POC, sequenced)
- Feature-flagged; **full suite must pass with inference OFF**.
- **Gate C** claimable path: inference **OFF**; manual taxonomy + deterministic numbers + Woo draft path.
- **Call 1 (vision) / Call 2 (text) only after Gate C is green**, still inside overall POC before "done."
- Call 1 auto only if `inference_enabled`; Call 2 never auto-fires (user taps Generate text).
- Call 1 body: all inventory photos @1024. Taxonomy lists sent to Call 1 are **exactly the Woo-synced species / attribute sets**.
- **Confidence 0.7 (default):** ≥ 0.7 → pre-populate species, wood categories, edge, figure, grade, and feat-* from Call 1 (**mutable**). < 0.7 → those fields stay **empty**. Ready still requires the full named set in §7. Presentation: `docs/UX.md`.
- **Taxonomy cache:** `taxonomy_last_sync_at` vs `taxonomy_anchor` (bump only on stored-subset hash change, including deletions). Client re-pulls iff the anchor advanced. `test-woo` always syncs; publish if last_sync >1h. No per-nav sync. No Woo taxonomy timestamp.
- Call 2 portable context: default full resend; never require `previous_response_id`. `test-inference` two-turn probe `stateful|stateless|fail`. Fail blocks **Call 2 enablement only**.
- Templates inject deterministic numbers. LLM does not invent dimensions.
Prompt file mechanics: `docs/PROMPTS.md`.
---
## 7. Slab status machine (app-internal only)
`draft → calibrated → ready → publishing → published` (or `failed` with detail).
- **calibrated:** mask + axis confirmed; length/thickness/SKU entered; client computed sqft/bdft/widths; draft uploaded.
- **ready:** SKU, length, thickness, client sqft/bdft/widths, ≥1 inventory PNG, exactly one species, ≥1 wood category, 1 edge type, ≥1 figure term, ≥1 fig-* tag, ≥1 grade, thickness store band (round-up), 1 moisture (default kiln-dried; not inferred), price. feat-* 0+. Title/description may be typed, generated, or templated at publish. Vision may prefill the taxonomy subset only when confidence ≥ 0.7.
- Inference does not gate publish. Below-threshold Call 1 does not prefill; empty mandatory fields block ready.
Slab `draft` is separate from Woo draft (`woo_create_status`).
---
## 8. Test and delivery expectations
- No feature without a passing test and shown execution output (PR/commit message).
- Deterministic core unit-tested before UI consumes it.
- One phase = reviewable, shippable increment; Ty exit-gates phases.
- Phase naming: Phase 0–6 stay delivery chapters. **Phase 0 = Gates A+B.** **Gate C = early Phase 1** claimable publish slice.
- Secrets, real Woo application passwords, and AES keys stay out of the repo.
---
## 9. Deploy sketch
- Target: inventoried Docker host. Docker Compose (`frontend` + `fastapi`) + Caddy → `https://${APP_HOSTNAME}` (LAN/Tailscale).
- Fill `deploy/INVENTORY.md` before binding ports or merging Caddy (co-resident apps can collide; bolt.diy is one example).
- Health: `GET https://${APP_HOSTNAME}/api/health`.
- `WOO_BASE_URL` in compose (HTTPS). Settings displays it read-only.
- Inference is a remote configurable endpoint, not on the app host by default.
Depth: `docs/DEPLOYMENT.md`.
- Quantity per listing is one.
- User enters length, thickness, and SKU.
- App proposes remaining listing fields. User reviews before create.
- Non-math fields remain editable until create.
- `bdft = sqft × thickness_in`
- Price proposal is `bdft × species $/bdft`. User may replace it. Missing rate leaves price empty.
- User-entered length, thickness, SKU, price, and taxonomy override computed or inferred values.
- SKUs matching `SLAB-UAT-*` create as Woo draft.
- Create works with inference off.
- Source below the PNG size floor requires a new photo.
- Existing store SKU blocks create.
+15
View File
@@ -0,0 +1,15 @@
# M1-6 UAT Deploy — run these on 192.168.1.202
# 1. Copy the repo to .202 (from THIS machine, /home/ty):
rsync -az --exclude node_modules --exclude .svelte-kit --exclude build \
/home/ty/SlabUploader/ ty@192.168.1.202:SlabUploader/
# 2. Build the image on .202:
ssh ty@192.168.1.202 "cd SlabUploader/frontend && docker build -t slabuploader-m1 . && \
docker rm -f slabuploader-m1 2>/dev/null; \
docker run -d --name slabuploader-m1 --restart unless-stopped -p 18080:80 slabuploader-m1 && \
echo 'Container running at http://192.168.1.202:18080'"
# 3. Verify from your phone:
# Open http://192.168.1.202:18080 in Safari/Chrome
# Flow: Add photo → Mask (green sheet, sensitivity) → Approve → Axis → Approve → Measure → Calculate
+8 -51
View File
@@ -1,56 +1,13 @@
# SlabUploader
Browser app for listing one-of-a-kind wood slabs on the Whidbey Wood Store.
Lists one-of-a-kind wood slabs on Whidbey Wood Store.
You photograph a slab, confirm the cut and the numbers, review the listing, and create the WooCommerce product. The browser does the measuring and crop. The server stores the draft, talks to the store, and (later) runs vision. Runs on phones and PCs.
Owner: Ty (Whidbey). Store: www.whidbeywoodstore.com. Runs in Docker Compose behind Caddy on a host you inventory first (`APP_HOSTNAME`).
## Where we are
Gate A freeze signed 2026-08-31. All live docs sit on `main`. Read `AGENTS.md` before writing code.
The bar for this first version: a real slab, photographed on a phone or a PC, listed on the real store. Practice listings are WooCommerce **drafts** with SKUs that start `SLAB-UAT-`. After Ty reviews, one real SKU goes **live**. Online only for now; offline capture is deferred.
Build order is in `docs/IMPL-PLAN.md`. Empty app on the real host first, then the first draft listing, then vision.
## Documentation
| File | What |
| Artifact | File |
|---|---|
| `AGENTS.md` | Hard rules. Read first. |
| `docs/ARCHITECTURE.md` | Hybrid topology, what runs where, secrets, status machine |
| `docs/TECH-SPEC-PIPELINE.md` | Math, image pipeline, constants, test vectors TV-1–TV-10 |
| `docs/DATA-MODEL.md` | SQLite tables, slab statuses, settings |
| `docs/OPENAPI.md` | Browser to server API |
| `docs/CONTENT-WOO.md` | Titles, descriptions, WooCommerce payload |
| `docs/PROMPTS.md` | Call 1 / Call 2 prompt files (server text files) |
| `docs/DEPLOYMENT.md` | Compose, Caddy, secrets placement, ops |
| `docs/UX.md` | Presentation: what the mill owner sees and does |
| `docs/UAT-PRACTICE.md` | Walkable practice UAT for `SLAB-UAT-*` |
| `docs/IMPL-PLAN.md` | Phases 0–6, exit gates, deferred stub (Phase 2) |
| `deploy/INVENTORY.md` | Host worksheet before binding ports |
| `docs/archive/PRD-2026-08.txt` | Frozen history, not a source for new work |
| PRD | `docs/PRODUCT.md` |
| Invariants and agent context | `AGENTS.md` |
| Milestone 1 | `docs/CAPTURE.md` |
| Hosting | `deploy/` |
## Short map
- Client (SvelteKit) owns the happy path: mask knobs, sqft, bdft, 3:4 PNG. Server (FastAPI) stores drafts, talks to WooCommerce, and proxies vision. Server matting ("Try harder") is deferred from POC; POC mask tuning is client-side only.
- Board feet = square feet × thickness in inches. No divide-by-12. Test vectors TV-1 through TV-10 run in the browser.
- Secrets never sit in the browser. Encrypted on the server. Store login is a WordPress application password on a low-privilege user; WooCommerce consumer keys are not implemented.
- Practice SKUs `SLAB-UAT-*` are always drafts, even if Settings say publish.
- Vision stays off until the first draft listing works. Species suggestion and Generate text come after, still inside this project.
- Two containers (`frontend`, `fastapi`) plus Caddy. One SQLite, image volumes. Inventory the host first.
Where deferred items live: `docs/ARCHITECTURE.md` §4 and `docs/IMPL-PLAN.md` Phase 2 (offline PWA, OCR, ruler — deferred stub).
## Repo
Source of truth: Gitea `Ty_Tech/SlabUploader` on gitea-atd
(`https://gitea.vps1.afterthedemo.com/Ty_Tech/SlabUploader`). TrueNAS and GitHub copies are not the source of truth for this work.
## Getting started
1. Read `AGENTS.md` and Phase 0 in `docs/IMPL-PLAN.md`.
2. Build the client math modules and a thin FastAPI health/settings app. Measuring lives in the browser.
3. Ty signs each phase.
4. Live docs on `main` are the source of truth. The archive PRD is frozen history only.
Owner: Ty. Store: https://www.whidbeywoodstore.com/
Repo: `Ty_Tech/SlabUploader`
+36
View File
@@ -0,0 +1,36 @@
# SlabUploader M1 — shared build context (for :202 worker tasks)
REPO: /home/ty/SlabUploader — work ONLY inside /home/ty/SlabUploader/frontend.
Branch: M1-dev-rev4 (already checked out; DO NOT switch branches, DO NOT push).
This is Milestone 1 (Capture) of a slab-measuring web app. Browser-only, NO backend,
NO inference, NO OpenCV/ONNX. Pure JS (not TS). Svelte 5 + SvelteKit + adapter-node.
TEST COMMANDS (run these, show real output):
unit: cd /home/ty/SlabUploader/frontend && npx vitest run
e2e: npx playwright test --list (collection only; full e2e needs the M1-6 container)
EXISTING (already committed, green, DO NOT break):
src/lib/core/mask.js -> keySheet(data,{sheet,sensitivity}), maskStats(mask)
src/lib/core/math.js -> scale, sqft, bdft, roundHalfUp, sampledWidths,
sampledWidthsFrom, snapToEighth
tests/unit/mask.test.js, tests/unit/math.test.js (24 tests, all pass)
src/routes/+page.svelte (placeholder home — M1-3 replaces it)
src/routes/+layout.svelte, src/routes/api/health/+server.js
TDD IS MANDATORY (test-driven-development skill):
1. Write the failing test(s) FIRST.
2. Run them and WATCH them fail for the right reason (feature missing, not a typo).
3. Write the MINIMAL code to pass.
4. Run them and confirm they pass.
5. Run the FULL unit suite (npx vitest run) and confirm no regressions + pristine output.
6. Only then are you done. Commit is done by the coordinator — you do NOT commit.
CONVENTIONS:
- Tab indentation (the repo uses tabs).
- Pure logic lives in src/lib/core/*.js (DOM-free, unit-testable under node).
- Svelte components live under src/lib/ (e.g. src/lib/components/).
- Every new exported function needs a unit test that you SAW fail first.
- No console.log left in production code.
- Do not add dependencies.
- Report at the end: files created/changed, the exact test command output, and
any place you had to make a judgment call.
+6 -68
View File
@@ -1,69 +1,7 @@
# Deploy inventory worksheet
# Host
Fill this at **Gate B** on the designated host before any port bind or Caddy merge.
The host must be inventoried before any deployment. See `docs/DEPLOYMENT.md`.
## Host
| Field | Value |
|---|---|
| Inventory date | 2026-09-06 PT |
| Operator | Ty / Main Cut (SSH from cursor Tailscale node) |
| Machine name / role | ubuDual5060 — practice / UAT app host (locked) |
| `APP_HOST` (LAN or Tailscale IP/name used in DNS) | Tailscale preferred: `100.64.0.9` (`ubudual5060`). LAN also: `192.168.1.202` |
| `APP_HOSTNAME` (HTTPS site name, e.g. `slab.example.local`) | `slab.local` (LAN-first; Pi-hole or hosts → `192.168.1.202`) |
| OS / Docker version | Ubuntu 26.04.1 LTS; Docker 29.8.0; Compose v5.5.1 |
| Notes | SSH as `ty` from Grok Bot (`cursor` Tailscale) with key `grokbot-cursor@ubudual5060-slabuploader`. User `ty` is in `docker` group. Disk ~15G free of 172G (92% used) — watch volume growth. Gitea is code SoT only; runtime is this host. |
| `WOO_BASE_URL` (`https://` store; not editable in app) | `https://www.whidbeywoodstore.com` (practice drafts via `SLAB-UAT-*`) |
## Ports and collisions
| Check | Result |
|---|---|
| `docker ps` summary (names + published ports) | Running: `whisperx-stt` `0.0.0.0:9000->9000`. Host also has `llama-server` on `0.0.0.0:8082`. Firecrawl stack present but exited. |
| Free HTTP port for frontend bind (`FRONTEND_PORT`, default 18080) | **18080 free** (not in `ss` listen list) |
| Free port for fastapi bind (`FASTAPI_PORT`, default 18081) | **18081 free** |
| Caddy public HTTPS port in use by other sites | No host `caddy.service`. No Caddy container found. HTTPS front still to be added. |
| Co-resident apps that own ports (example: bolt.diy on 8443-class) | 9000 (whisperx-stt), 8082 (llama-server), 22 (sshd). Avoid those. |
## Caddy
| Field | Value |
|---|---|
| Caddy config path (host file or container) | **Not installed yet** — choose host install vs compose sidecar at Gate B execute |
| Existing site blocks that share this host | none found |
| TLS mode (`internal` CA vs other) | TBD (Tailscale HTTPS / Caddy `internal` / existing lab CA) |
| Phone CA trust verified? (yes/no + how) | no — not deployed yet |
## DNS / reachability
| Field | Value |
|---|---|
| DNS source (Pi-hole / AdGuard / MagicDNS / hosts) | LAN-first: Pi-hole or hosts for `slab.local` → `192.168.1.202`. Tailscale MagicDNS remains for SSH (`ubudual5060`). |
| A record: `APP_HOSTNAME` → `APP_HOST` | `slab.local` → `192.168.1.202` (LAN). Optional Tailscale alias later. |
| Reachable from phone on LAN? | TBD after deploy |
| Reachable from phone on Tailscale? | TBD after deploy (path intended) |
## Volumes and backup
| Field | Value |
|---|---|
| Docker volume dir convention | TBD on first compose up (prefer under a dedicated path; disk pressure noted) |
| Backup target path (local) | TBD |
| Off-box mirror (if any) | TBD |
## Smoke after first up
| Check | Pass? |
|---|---|
| `curl -k https://${APP_HOSTNAME}/api/health` | not run |
| Compose `frontend` + `fastapi` healthy | not run |
| Caddy `/api/*` reaches fastapi (not frontend) | not run |
## Sign-off
| Role | Name | Date |
|---|---|---|
| Inventory draft (SSH + ports + hostname + store) | Main Cut | 2026-09-06 PT |
| Inventory complete | | |
| Ty Gate B (optional) | | |
- Machine: ubuDual5060 (192.168.1.202)
- Container: slabuploader-m1 (image sha256:98d11c23, restart unless-stopped)
- URL: http://192.168.1.202:18080
- Port: 18080 (LAN interface, bound 0.0.0.0)
- Started: 2026-09-14 (M1 UAT)
+17
View File
@@ -0,0 +1,17 @@
# Deploy
Milestone 1 ships as a Docker image that serves the capture app.
Where the container runs is chosen at runtime.
No FastAPI and no Woo client in this milestone.
`docker-compose.yml`, `Caddyfile.fragment`, and `.env.example` describe an older two-service stack. They are not the Milestone 1 contract.
## Milestone 1 UAT — deployment POR
- **One container.** Build a single Docker image that serves the SvelteKit capture app. No FastAPI, no Woo client, no Caddy TLS edge in M1. (Caddy/compose/Woo are Milestone 3.)
- **Host chosen at runtime.** Record the machine and URL in `INVENTORY.md` when the container starts. Do not put a host name in the product spec.
- **LAN-reachable UAT URL.** For UAT the container binds a port on the LAN interface (not only `127.0.0.1`), so other machines on the LAN — e.g. a phone — reach the app at `http://<host-lan-ip>:<port>`.
- **No backend.** The app is browser-only in M1 (see `docs/CAPTURE.md`). There is no `/api` route and no inference.
Reference for the current UAT host: see `INVENTORY.md` (filled in when the container starts).
+4
View File
@@ -0,0 +1,4 @@
# Release
Build the Docker image. Run it on the host chosen for that test.
Milestone 3 adds the Woo service and a tagged UAT path.
+5 -2
View File
@@ -1,5 +1,8 @@
# Implementable compose for SlabUploader (docs/refactor-v2).
# From repo root:
# Implementable compose for SlabUploader.
# Phase 0 deliverable targets: frontend/Dockerfile, backend/Dockerfile,
# backend/app/prompts/, and deploy/.env.example are not yet in the tree on
# docs-only main. This file pins their paths so scaffolding does not invent them.
# From repo root (after those scaffolds exist):
# cp deploy/.env.example deploy/.env && chmod 600 deploy/.env
# docker compose -f deploy/docker-compose.yml --env-file deploy/.env up -d
# Bind loopback only. Caddy is the TLS edge. Services on the compose network
-230
View File
@@ -1,230 +0,0 @@
# Architecture
Status: SPEC · hybrid topology locked at Gate A freeze (2026-08-31) · SlabUploader
Normative for hybrid split, swimlane, what-runs-where, secrets **why**, and status
transitions. Ops depth lives in DEPLOYMENT. Schema enums live in DATA-MODEL.
Agent-facing hard rules live in AGENTS.md (verbatim locks stay there).
Companion: `docs/TECH-SPEC-PIPELINE.md`. Historical PRD: `docs/archive/PRD-2026-08.txt` (frozen; not a source for new work). Agent locks: `AGENTS.md`.
## 1. Topology (hybrid)
Phone does the happy-path pipeline (mask knobs, length axis, sqft/bdft, 3:4 PNG).
FastAPI stores drafts, proxies inference, talks to Woo. reverse proxy terminates HTTPS.
Server U2Net (“Try harder”) is **deferred from POC**, not deleted.
```
phone (SvelteKit)
capture, four knobs inline, live mask overlay on the source photo,
length axis, sqft/bdft, 3:4 PNG
(POC: retake if mask still bad — no U2Net control)
server
reverse proxy → frontend (static)
→ fastapi : store, settings, taxonomy cache, Woo, inference proxy, prompt files
→ U2Net endpoint reserved post-POC
```
- Happy path never leaves the phone.
- Mask knobs live on capture; changing a knob re-runs client BG removal immediately.
- Woo + LLM keys stay on the server. Browser does not call Woo or the vision endpoint directly.
## 2. Swimlane
```mermaid
flowchart TB
subgraph Phone["Phone — SvelteKit"]
P1[New Wood: 1–5 photos]
P2[BG overlay + sheet / sensitivity / edge / feather]
P3{Edge OK?}
P4[Length axis overlay — rotate / confirm]
P5[User length + thickness + SKU]
P6[sqft, bdft, 6in widths, 3:4 PNGs]
P7[Review: Call 1 pre-fill or manual taxonomy]
P8[Tap Generate text]
P9[Review title / desc — publish]
end
subgraph API["server — FastAPI"]
A1[U2Net reserved post-POC]
A2[Store draft: originals + PNGs + numbers]
A3[Call 1 proxy — vision]
A4[Call 2 proxy — text]
A5[Woo: taxonomy, SKU check, create product]
end
subgraph LLM["Your OpenAI-compatible endpoint"]
L1[Wood expert — all photos at 1024]
L2[Title / desc / short desc]
end
subgraph Woo["WooCommerce store"]
W1[Categories / attributes / fig-* tags]
W2[New product live or draft per setting]
end
P1 --> P2 --> P3
P3 -->|no — retune knobs or retake| P2
P3 -->|no — Retake| P1
P3 -->|yes| P4 --> P5 --> P6
P6 --> A2
A2 --> A3 --> L1 --> A3 --> P7
P7 --> P8 --> A4 --> L2 --> A4 --> P9
P9 --> A5
A5 --> W1
A5 --> W2
```
## 3. Clarifications
1. **Happy path** stays on the phone through PNG + numbers. FastAPI is idle until the user has a confirmed mask.
2. **Mask knobs** live on capture; each change re-runs client BG removal. Server U2Net “Try harder” is deferred from POC. The one-photo contract stays in the architecture; the control is not shipped until post-POC.
3. **Draft upload** sends **originals + processed PNGs + length/thickness/SKU/sqft/bdft/widths**. Originals are needed if Call 1 or a later retry must not depend on the tab still being open. After successful Woo publish, server deletes both.
4. **Call 1** is server-side so the vision key never sits in the browser. Auto-run
on slab create **only if** `inference_enabled` is true. If disabled, Call 1
is skipped; user can manually fill taxonomy and still trigger Call 2. Body:
all originals downscaled to 1024 + **Woo-synced taxonomy only** + SKU/length/thickness.
Timeout 45s → error + retry on the phone. ≥0.7 confidence **pre-populates**
species, wood categories, edge/figure/grade, feat-* (mutable). Below 0.7 those
fields stay **empty**. Manual entry stays authoritative. Presentation: `docs/UX.md`.
5. **Call 2** does not auto-fire. User taps Generate text. Server must send
**portable Call 1 context** (default: full conversation resend). Stateful
`previous_response_id` only after `test-inference` proves the provider supports
it. Call 2 inputs distinguish confirmed user values from inferred ones. Per-slab
thread; delete on submit or abandon.
6. **Woo** is only FastAPI. Browser never sees the WordPress application
password. Duplicate SKU → 409 mapped on the SKU field (edit SKU or open existing).
Stale value → 422 on that field. Draft stays on the phone.
7. **Settings** (species $/bdft, prompts, inference endpoint, Woo credentials,
publish status) live on the server. Store URL is env, displayed read-only.
## 4. What runs where
| Job | Where |
|---|---|
| Camera, 1-5 photos | Client |
| Sheet detect, chroma-key / black threshold, four knobs, live re-run, flood-fill | Client |
| U2Net “Try harder” | Server, **deferred from POC** |
| Length axis overlay, 6" widths, sqft, bdft | Client |
| 3:4 PNG, 80% fill (configurable aspect) | Client |
| Draft + originals + processed PNGs | Server (after user continues) |
| Species $/bdft, Woo creds, prompts, brand/GEO | Server |
| Call 1 (vision, all photos @1024) | Server proxy |
| Call 2 (title/desc) | Server proxy, after Call 1 curation |
| Woo taxonomy sync + publish | Server |
## 5. Secrets and settings
**Server-side only (never in browser JS):**
1. WordPress username + **application password** for a dedicated low-privilege
WP user. Server uses HTTP Basic Auth (`username:application_password`) against
`/wp-json/wc/v3/`. Stored encrypted at rest in SQLite (AES-GCM). Not Woo
consumer keys. Not the account login password.
2. Inference endpoint base URL + API key. Stored encrypted. Server proxies all
inference calls.
3. AES master key. Env var on server (`SLAB_AES_KEY`), never in the DB.
4. `WOO_BASE_URL` env (compose). HTTPS only. Not user-editable; Settings displays it read-only.
**Browser-side (no secrets):**
1. User preferences: sheet mode, sensitivity, edge offset, feather. Persisted in localStorage, reset-to-default available.
2. Species list with $/bdft. Read from server settings sync.
3. Taxonomy snapshot (categories, attributes, tags). Read from server. No auth needed.
**Flow:**
1. Deploy sets `WOO_BASE_URL` (`https://`) in compose. Operator creates a
low-privilege WP user on that store (HTTPS required for Application
Passwords UI). Generates an application password under Users → Profile.
2. User enters that username + application password in Settings UI
(store URL shown read-only from env).
3. Browser POSTs them to `/api/v1/settings` on FastAPI. Server encrypts with
AES-GCM and stores ciphertext only.
4. Server syncs taxonomy from Woo, caches in SQLite.
5. Client reads taxonomy from `/api/v1/admin/taxonomy` — no auth needed.
6. All Woo calls go server-to-Woo. Browser never calls Woo REST directly.
Browser-to-Woo REST would need CORS on the store, which this design does not use.
## 6. Status machine
```
draft → calibrated → ready → publishing → published
│ │ ↑
└→ failed ────┴────────────────┘ (woo_product_id set)
any → failed (with error)
```
1. **draft** — user took photos, no mask confirmed yet.
2. **calibrated** — user confirmed the BG edge, confirmed length axis, entered length/thickness/SKU. Client computed sqft/bdft/widths. Draft uploaded to server.
3. **ready** — SKU, length, thickness, client sqft/bdft/widths, ≥1 inventory PNG,
exactly one species, ≥1 wood category, 1 edge type, ≥1 figure term, ≥1 fig-* tag,
≥1 grade, thickness store band (round-up), 1 moisture (default kiln-dried), price.
feat-* 0+. Title/description may be typed, generated, or templated at publish.
Values can come from Call 1 (≥ 0.7 pre-fill the user kept), manual entry, or a mix.
**Review gate:** below-threshold Call 1 leaves species, wood category, figure,
edge, grade, and feat-* empty. That subset is not the submit list. Inline nudges
on every still-required control, not submit-only. Presentation: `docs/UX.md`. Inference is
optional; with inference OFF the user fills everything by hand.
4. **publishing** — Woo create in flight. Poll for result.
5. **published** — Woo product created, woo_product_id stored. Images purged.
6. **failed** — pipeline, inference, or publish error. Error detail stored. Retry available.
Call 1 and Call 2 are assist-only. They do not gate publish. Low-confidence Call 1
results do not auto-fill. If the user skips inference, the path is: calibrated →
ready → publishing → published.
## 7. Taxonomy cache (manufactured last-modified)
Woo REST exposes **no usable last-modified** on categories, attributes, or tags
(only products carry `date_modified`). The client never talks to Woo. FastAPI is
the sole freshness source. It persists two UTC stamps: `taxonomy_last_sync_at`
(every successful Woo pull) and `taxonomy_anchor` (bumps only when the stored-subset
hash changes, including deletions).
- Anchor bumps **only** when a row-level change is detected in the **stored
subset** of cache fields (whatever columns the cache tables actually keep:
species/wood-category leaves, five attributes + terms, `fig-*`/`feat-*` tags).
Scope is schema-driven: adding a cache column later automatically includes it.
- Spelling/name edits, additions, and deletions all bump. Diff must catch missing
rows (deletions), not only changed rows.
- A no-op sync (stored subset unchanged) **does not** bump, so the client does
not churn.
- Client reads the anchor. If it advanced past the client's last value, re-pull
the **full** taxonomy cache. One timestamp governs categories, attributes, and
tags together.
- `taxonomy_anchor` is app-managed; no Woo-side timestamp or per-table anchor is used.
**Triggers**
1. `POST /api/v1/settings/test-woo` **always** resyncs taxonomy after a successful
connection test (unlocks the species list).
2. Publish / product submit: opportunistic resync if the last successful sync is
older than **1 hour**; bump anchor only if the stored subset changed.
3. Optional: app launch check (sync only if stale) and a Settings “Refresh
taxonomy” control. Not required for POC.
4. Do **not** sync on every screen navigation.
Species pickers and Call 1 option lists are **exactly** this cached set. No
hardcoded, invented, or fallback species list. A new Woo species is selectable
only after the next sync that lands it in the cache.
## 8. Shared validation module
One FastAPI module is source of truth (`GET /api/v1/validation/module` → `{ hash, rules[] }`).
Two consumers: review UI and Call 2 prompt builder. Client caches the module.
- SKU charset: `[A-Z0-9-]{3,24}` (printable ASCII subset). Title / short_title / description: UTF-8 within Woo `maxLength`. Not “ASCII-only” and not “extended ASCII”.
- Field-exit: local check against the cache. Empty optional is valid.
- Length: `maxLength` is a hard input cap; server still enforces.
- Submit carries `validation_hash`. Match → validate. Mismatch → HTTP **412** + fresh module; UI “Updating rules”; re-validate; retry. Never show 412. 409 is duplicate SKU only. Woo-shaped 422 is store rejection (#18).
## 9. Call 1 → Call 2 context
Providers differ. Default portable path: **resend the full Call 1 turn** (prompt + images metadata + assistant JSON) with Call 2. Opt into `previous_response_id` only after probe.
`POST /api/v1/settings/test-inference` two-turn probe records `stateful | stateless | fail`.
**Fail blocks Call 2 enablement only** (Gate C inference-OFF still works). Call 2 always carries the full Call 1 context; `previous_response_id` is optional after probe.
Per-slab thread on the **server** (client does not hold provider IDs). Best-effort delete on publish / abandon / fail; log and continue.
Presentation: `docs/UX.md`.
+136
View File
@@ -0,0 +1,136 @@
# Milestone 1 — Capture
Runs in the browser on phone and PC as ordinary client code.
No inference URL. No model. No backend. Mask, rectangle, measurements, and PNG encode are deterministic functions of the photo and user inputs.
Milestone 1 uses one reference photo. Further angles are later milestones.
Milestone 1 ends when the user sees the inventory PNG and measurements. Milestone 2 is Review. Milestone 3 is Create. This file does not create a WooCommerce product.
## Setup
Photograph the slab on a green or black sheet.
- Sheet fills the frame around the slab.
- Slab is fully on the sheet.
- First photo is top-down, lens parallel to the face.
- Length of the slab is aligned with the long side of the picture.
The app expects that sheet. Background removal keys green or black. Other backgrounds are out of Milestone 1.
## Use case
If a device draft exists:
- App opens Resume.
- User chooses Continue or Start fresh.
- Continue: app restores the last approved state.
- Start fresh: app discards the draft and opens Add photo.
Otherwise the app opens Add photo.
1. User adds one photo taken under Setup.
2. App decodes the photo and opens Mask. App keys green or black and shows an overlay: slab stays the photograph; removed pixels are a light gray checkerboard.
3. User sets sheet Auto / Green / Black and sensitivity 0–100 (slider or minus / plus). App updates the control immediately. App recomputes the overlay 2.0 seconds after the last sensitivity change. User adjusts until only the slab remains, then approves. App blocks approve if the mask has no slab pixels; user retakes. The approved mask is the footprint for every later step.
4. App draws the minimum-area bounding rectangle of the mask and the length axis on the long side of that rectangle. User rotates the axis if it does not follow the slab length, then approves the axis.
5. User enters length `L` in inches (1/8 in steps) and thickness (1/8 in steps), then presses Calculate.
6. App sets `scale = longest_axis_px / L`.
7. App computes widths, sqft, and bdft from the mask, and writes the inventory PNG.
8. User sees the PNG and the numbers. Milestone 1 stops here.
Calculate does not create a WooCommerce product.
## Browsers
Phone: iOS Safari, Android Chrome.
PC: Chrome, Edge, Firefox.
Other clients get a hard stop.
## Input photo
Accepted input: JPEG. Phones typically save JPEG; Android Chrome delivers JPEG by default.
If the file is HEIC and the browser cannot decode it, show a one-tap notice to retake the photo as JPEG. HEIC is never silently dropped and never decoded server-side in Milestone 1.
## States
One photo component is reused. Each state advances on approve. Back returns to the previous state. A device draft restores the last approved state.
1. Resume — only when a device draft exists. Continue or Start fresh.
2. Add photo — camera or picker. One photo. Setup rules visible.
3. Mask — background removal on that photo.
4. Length axis — bounding rectangle and long-side axis on the same photo.
5. Measure — length, thickness, Calculate, inventory PNG, widths, sqft, bdft. Milestone 1 stops here.
## Display
Preview fits the device width. Height is capped so Mask and Measure controls stay on screen. Phone and PC use the same states.
The preview is display only. Mask, rectangle, `scale`, sqft, and PNG encode use the source photo pixels, not the CSS size of the preview.
## Runtime
Browser APIs: `createImageBitmap`, `canvas` / `OffscreenCanvas`, Web Worker, `convertToBlob({ type: "image/png" })`, IndexedDB.
`idb-keyval` may wrap IndexedDB.
No OpenCV, ONNX, U2Net, or image-editor kit.
Sensitivity 0–100 maps to green chroma tightness and black brightness cutoff in the worker.
## Mask
Overlay: slab remains the photograph. Removed pixels are a light gray checkerboard.
Controls on this state, with the photo visible:
- Sheet: Auto, Green, or Black
- Sensitivity: 0–100, step 1. Slider with minus and plus on each side. Button hit targets sized for a thumb.
The control value updates immediately. The overlay recomputes 2.0 seconds after the last sensitivity change. A sheet change may recompute on the change.
Mask work runs in the worker. The last good overlay stays visible while a pass runs. Show a busy mark only if a pass lasts more than a fraction of a second. If a pass fails, keep the last overlay; the user may retake.
Approve is blocked when the mask has no slab pixels. User retakes.
User approves the mask when only the slab remains. That mask is the footprint for Length axis, measurements, and the inventory PNG.
## Length axis
On the same photo, draw the minimum-area bounding rectangle of the mask and the length axis on the long side of that rectangle. User rotates the axis if it does not follow the slab length, then approves the axis.
## Measure
User enters length `L` in inches (1/8 in steps) and thickness (1/8 in steps), then presses Calculate.
- `scale = longest_axis_px / L`
- Widths: min, max, avg, sampled every 6 in along the approved length axis, perpendicular to it
- `sqft = (mask_pixels / scale²) / 144` (2 decimals)
- `bdft = sqft × thickness_in` (2 decimals)
User sees the inventory PNG and those numbers. Stop. Calculate does not create a WooCommerce product.
## Device draft
One in-progress slab is stored on the device. This is not a WooCommerce draft.
On open or refresh, if that draft exists, the app opens in Resume.
- Continue restores the last approved state, including Measure.
- Start fresh discards the device draft and opens Add photo.
Milestone 3 clears the device draft after Woo create.
## Inventory PNG
Role: `kind=inventory`. Filename is an implementation detail.
The first inventory photo is the measurement reference. Later inventory photos use the same file properties.
| Property | Value |
|---|---|
| Format | PNG, 8-bit RGBA (`image/png`) |
| Alpha | Kept through encode and upload |
| Aspect | 3:4 portrait |
| Layout | Slab centered, 80% fill at the widest and tallest points |
| Size | After crop, shorter side ≥ 1600px when the source can supply it |
Source below that floor: warn and require a new photo. No upscale from an undersized source.
Editor preview of alpha is a light gray checkerboard. The storefront uses the theme background.
File size: aim under 200KB per image (soft goal, not a hard gate in Milestone 1).
-198
View File
@@ -1,198 +0,0 @@
# Listing copy and the store
How titles and descriptions are built, how we talk to WooCommerce, and the exact create payload. Templates always run. Generate text is optional and never publishes on its own.
## 1. Titles and descriptions
### 1.1 Templates (always on)
Templates live in Settings. Defaults below. Placeholders use `{field}`.
**title** (default):
```
{species} {length_ft}ft {length_in_remainder}in × {width_avg_in}in Wood Slab — {character}
```
Example: `Black Walnut 16ft 0in × 18.2in Wood Slab — Cathedral`
- `length_ft` = floor(length_in / 12), `length_in_remainder` = length_in mod 12 (1 dp).
**short_title** (default):
```
{species} Slab — {character}
```
Example: `Black Walnut Slab — Cathedral`
**description** (default, multi-paragraph):
```
A one-of-a-one {character} {species} slab, {length_ft}ft {length_in_remainder}in long with an
average width of {width_avg_in}in and {thickness_in}in thickness ({bdft} bdft).
Each slab is naturally shaped — width varies along the length at {width_min_in}in to
{width_max_in}in. Sold by the slab; dimensions as measured. {geo_sentence}
```
`geo_sentence` is the geography sentence from Settings, e.g.
`"Locally milled and shipped from the Pacific Northwest."` (default if unset: none).
All template math fields come from the deterministic pipeline (never from the LLM).
### 1.2 Generate text (optional)
The mill owner taps Generate text on review. It never runs by itself. It is off unless `content_llm_enabled` is true.
The model writes prose only (character, color, grain, uses). Measured length, width, thickness, square feet, and board feet are facts in the prompt. The model does not invent numbers. Templates inject those numbers into the title and description after the prose comes back.
The mill owner can always edit the result. `content_source` is `llm` when this path ran.
If the text endpoint is missing or down, disable the button. Templates still work. Publish is never blocked because Generate text failed.
### 1.3 Audit
Every content generation (template or LLM) is logged with inputs (template version,
slab facts), the LLM request/response payload when used (inference calls logged for audit),
and the final stored content.
## 2. WooCommerce
### 2.1 Auth & client
- REST v3 surface unchanged: `GET/POST/PATCH/DELETE {WOO_BASE_URL}/wp-json/wc/v3/…`
- Auth is **WordPress Application Passwords**, not WooCommerce consumer keys
(`ck_`/`cs_`) and not the user's login password.
- Create a **dedicated low-privilege WordPress user** (shop manager, or a custom
role with product create/edit + media upload). A dedicated low-privilege user, not the admin account, is used.
- Generate the application password under **Users → Profile → Application
Passwords**. WordPress requires **HTTPS** for that UI; the store must already
be on TLS (Caddy enforces HTTPS on the app side too).
- Basic auth shape: `woo_wp_username:woo_app_password` (username + application
password). Spaces in the generated password are ignored by WordPress; store
the value as entered.
- FastAPI is the sole Woo caller. Credentials live encrypted at rest in SQLite
(AES-GCM, `SLAB_AES_KEY` env). The browser never holds them.
- Rotation: revoke the application password in the WP user profile, enter a new
one in Settings UI, then `POST /api/v1/settings/test-woo`.
- Client: `httpx` with timeouts (connect 10s, read 60s for image-heavy create).
- Store URL is **`WOO_BASE_URL`** from Docker Compose / host `.env` (HTTPS only).
FastAPI refuses `http://` at startup. Not a Settings field; UI shows it read-only.
### 2.2 Store lists (species, tags, attributes)
`POST /api/v1/admin/taxonomy/sync` pulls, in order:
1. `GET /products/categories?per_page=100` (paginate) → species + wood-category leaves
2. `GET /products/tags?per_page=100` → `fig-*` / `feat-*` only (other tags ignored)
3. `GET /products/attributes` (+ terms) → five locked attributes
Rebuilds cache tables in one transaction. Failure → `502 woo_error`; previous
cache retained (never delete-then-fail).
**Manufactured stamps.** Woo REST has **no** usable last-modified on categories,
attributes, or tags. FastAPI persists `taxonomy_last_sync_at` (every successful
pull) and `taxonomy_anchor` (bump only when stored-subset hash changes, including
deletions). Client re-pulls the full taxonomy iff the anchor advanced. No Woo-side
taxonomy timestamp; no per-navigation sync.
**Triggers:** (1) successful `test-woo` **always** resyncs; (2) publish if
`now - taxonomy_last_sync_at > 1 hour` then reconcile (bump only on real change);
(3) optional app launch / Settings refresh. If a picked id vanished after a refresh, show that field as no longer valid. The selection is not silently swapped.
**Species exclusivity.** UI pickers, pricing seeds, and Call 1 species lists are
**exactly** the synced species-category leaves. No hardcoded, invented, or fallback
species set. A species new in Woo is selectable only after the next sync stores it.
### 2.3 What goes on the listing
When vision is on and it is at least 0.7 sure, it fills species, wood categories,
edge, figure, grade, and feature tags (character, inclusions, voids, checks map
to existing `feat-*` tags only). The mill owner can change every filled value.
Typed values always win.
If it is less sure, those fields stay empty. That empty-start subset is not
the submit list. Review will not continue until the full ready set is filled:
SKU, length, thickness, price, species, wood category, edge type, figure,
grade, thickness band, moisture, fig-* tags, and inventory PNG(s). Species
plus one figure is not enough. Presentation: `docs/UX.md`.
Low-confidence guesses are not filled.
Names from vision or from typing match store ids case-insensitive, trimmed. No
match leaves the field empty so they can pick from the list. The store will still
reject a missing required field at publish.
Field rules:
- **Categories**: species leaf (1 required) plus wood-category leaf ids (1+).
- **Tags**: `fig-*` (1+ required) and `feat-*` (0+). Only documented
character or species product tags are used. Woo is authoritative for tag definitions.
- **Attributes**: the five locked Woo attributes only — Edge Type, Figure, Grade,
Thickness, Moisture — using term ids from the cache. Species,
character, length, or free-text thickness as product attributes. Missing
attributes are skipped, not created (v1: no attribute creation).
Vision only suggests. It never blocks publish. With vision off, everything is typed.
### 2.4 Create payload
`POST /products` — body (only non-null fields sent):
```jsonc
{
"name": "{title}",
"type": "simple",
"status": "{woo_create_status}", // draft | publish; default draft; SLAB-UAT-* forced draft
"sku": "{sku}",
"regular_price": "{price}", // 2 dp string, e.g. "2730.00"
"description": "{description}",
"short_description": "{short_title}",
"categories": [ { "id": <species category id> } ],
"tags": [ { "id": <fig-* tag id> }, { "id": <feat-* tag id> }, … ],
"images": [
{ "src": "<data URL or pre-uploaded attachment URL>", "alt": "{species} {character} slab" }
],
"attributes": [ … if present … ],
"virtual": false,
"downloadable": false,
"catalog_visibility": "visible"
}
```
**Image upload strategy** (Woo v3): `images[].src` accepts a URL or a data URL.
For reliability the server:
1. For each customer-facing inventory photo in `seq` order (processed transparent PNGs
from the client TECH-SPEC path): `POST /media` with the **PNG bytes** → get attachment
`source_url`. Woo accepts `image/*`; keep alpha. JPEG re-encoding drops alpha and must not happen.
2. Reference those `source_url` values in `images` (≤5 inventory photos).
3. Only `kind=inventory` photos. Calibration photos do not exist in this design.
**Status** comes from Settings `woo_create_status` (`draft` or `publish`, default
`draft`). Practice SKUs `SLAB-UAT-*` are always created as drafts, even if Settings
say publish. Existing SKUs are not edited in this version. After a successful create,
the server deletes the original and processed photos. A slab marked published in the
app means the store create succeeded. That is not the same as WooCommerce "publish."
The force-draft rule is in `AGENTS.md`. This file only owns the payload and the steps.
### 2.5 Duplicate SKU
Before create: `GET /products?sku={sku}` (any store status).
- Found: stop. The phone shows the SKU field with Edit SKU and Open existing listing. This version does not update the other product.
- Not found: create. Still do the check every time.
### 2.6 After a failed publish
The mill owner sees a message on the field, not a status number or a stack. The form stays on the phone. The server marks the slab failed so they can try again.
If the SKU already exists: under SKU, "This SKU already exists in the store (any status)." Edit SKU, or open the existing listing (admin link when we have it).
If a category, attribute, or price is no longer valid: under that field, "This value is no longer valid. Pick from the current list," with the current store options.
The server still writes `sync_log`. Success still sets `woo_product_id`, marks published locally, and deletes photos.
- **Partial-failure note** (risk, see IMPL-PLAN): if media uploads succeed but the
final product POST fails, orphaned Woo attachments may exist. v1: log it; surface
a manual cleanup note. Not auto-deleted.
## 3. End-to-end publish sequence (server side)
```
1. check the listing against the shared rules (current copy of the rules on submit)
2. look up the SKU in the store (any status). Stop if it already exists.
3. refresh store lists if the last successful pull is older than 1 hour. Only bump the client list-version if something actually changed.
4. resolve categories, tags, and attributes from the synced lists (vision names or typed names)
5. upload processed PNG inventory photos to media, keep the URLs
6. POST /products with draft/publish per Settings, always draft for SLAB-UAT-* SKUs
7. on success: log, mark published locally, delete originals and processed photos
on failure: log, mark failed, keep photos, put the error on the field (§2.6)
```
## 4. What the model may and may not do
Templates, numbers, matching names to store ids, payload, dedupe, logging: code.
Generate text may write description prose only. It must not invent dimensions. It may only pick species and attributes that exist in the synced store lists.
Presentation: `docs/UX.md`. The wire uses `{ field, code, message, actions[] }`. The mill owner never sees those codes. If the phone's copy of the rules is stale, refresh the copy and retry. That is not a duplicate-SKU conflict.
-241
View File
@@ -1,241 +0,0 @@
# Data Model
Status: SPEC · 2026-08-27 · SlabUploader
Storage: single SQLite file. Schema portable to Postgres.
Conventions:
- IDs: client-generated UUIDv4 for slabs so the SvelteKit client can reference a slab before it exists server-side.
- Timestamps: UTC ISO-8601 TEXT.
- Soft state via status column; no hard deletes for slabs (audit).
- Money: float64 USD, rounded half-up to cents at write.
- All rounded values are what gets stored. No full-precision internal storage.
- Inches stored as 1/8" increments. Sqft/bdft to 2 decimals.
- Multi-select fields stored as JSON arrays of Woo IDs.
---
## slabs
Draft-only. Deleted on successful publish. WooCommerce is the source of truth for product data.
| Column | Type | Notes |
|---|---|---|
| `id` | TEXT PK | client-generated UUID |
| `sku` | TEXT UNIQUE NOT NULL | `[A-Z0-9-]{3,24}` printable ASCII subset |
| `status` | TEXT NOT NULL | draft \| calibrated \| ready \| publishing \| published \| failed |
| `length_in` | REAL NOT NULL | 1/8" step |
| `thickness_in` | REAL NOT NULL | 1/8" step |
| `sqft` | REAL | 2 decimals |
| `bdft` | REAL | 2 decimals |
| `width_min_in` | REAL | min width at 6" stations, 2 decimals |
| `width_max_in` | REAL | max width at 6" stations, 2 decimals |
| `width_avg_in` | REAL | avg width at 6" stations, 2 decimals |
| `species_id` | INTEGER | → woo_categories (leaf only, 1 required) |
| `wood_category_ids` | INTEGER[] JSON | → woo_categories (leaf, 1+) |
| `edge_type_term_id` | INTEGER | → woo_attribute_terms (1 required) |
| `figure_term_ids` | INTEGER[] JSON | → woo_attribute_terms (1+) |
| `grade_term_ids` | INTEGER[] JSON | → woo_attribute_terms (1+) |
| `thickness_term_id` | INTEGER | → woo_attribute_terms (round-up) |
| `moisture_term_id` | INTEGER | → woo_attribute_terms (1 required, defaults to kiln-dried term; user overrides; not inferred) |
| `fig_tag_ids` | INTEGER[] JSON | → woo_tags (fig-*, 1+) |
| `feat_tag_ids` | INTEGER[] JSON | → woo_tags (feat-*, 0+) |
| `price_per_bdft` | REAL | from pricing_rules for species |
| `price` | REAL NOT NULL | 2 decimals |
| `price_source` | TEXT | 'recommendation' \| 'override' |
| `title` | TEXT | |
| `short_title` | TEXT | |
| `description` | TEXT | |
| `content_source` | TEXT | 'manual' \| 'llm' |
| `client_rev` | INTEGER NOT NULL DEFAULT 1 | |
| `server_rev` | INTEGER NOT NULL DEFAULT 1 | |
| `created_at` | TEXT NOT NULL | |
| `updated_at` | TEXT NOT NULL | |
| `inference_thread_id` | TEXT | optional stateful provider id; delete on publish or abandon |
Indexes: `sku` (unique), `status`, `updated_at`.
### Status state machine
```
draft → calibrated → ready → publishing → published
│ │ ↑
└→ failed ────┴────────────────┘ (woo_product_id in sync_log)
any → failed (with error)
```
1. **draft** — photos taken, no mask confirmed.
2. **calibrated** — BG edge confirmed, length axis confirmed, length/thickness/SKU entered. Client computed sqft/bdft/widths. Draft uploaded to server.
3. **ready** — SKU, length_in, thickness_in, client sqft/bdft/widths, ≥1 inventory PNG, exactly one species, ≥1 wood category, 1 edge type, ≥1 figure term, ≥1 fig-* tag, ≥1 grade, thickness_term_id (round-up from measured thickness), 1 moisture (default kiln-dried; user override; not inferred), price. feat-* 0+. Title/short_title/description may be typed, generated, or written by templates at publish. Call 1 may prefill only the vision subset when confidence ≥ 0.7. Inference optional. Publishable.
4. **publishing** — Woo create in flight. Poll for result.
5. **published** — Woo product created. This row + all photos deleted. sync_log retained.
6. **failed** — pipeline, inference, or publish error. Error detail stored. Retry available.
---
## slab_photos
| Column | Type | Notes |
|---|---|---|
| `id` | TEXT PK | |
| `slab_id` | TEXT FK → slabs.id ON DELETE CASCADE | |
| `kind` | TEXT NOT NULL | 'inventory' |
| `role` | TEXT | 'topdown' \| 'extra' |
| `seq` | INTEGER | display order |
| `original_path` | TEXT | relative to images volume |
| `processed_path` | TEXT | relative to images volume |
| `created_at` | TEXT | |
Rule: only inventory photos. Calibration photos do not exist in this design.
---
## pricing_rules
| Column | Type | Notes |
|---|---|---|
| `id` | TEXT PK UUID | |
| `species` | TEXT NOT NULL | matches woo_categories.name (leaf) |
| `price_per_bdft` | REAL NOT NULL | flat, no tiers |
| `created_at` | TEXT | |
| `updated_at` | TEXT | |
`UNIQUE(species)`. Seeded from synced Woo categories. User sets price per species.
---
## woo_categories
| Column | Type | Notes |
|---|---|---|
| `woo_id` | INTEGER PK | |
| `name` | TEXT | |
| `slug` | TEXT | |
| `parent_id` | INTEGER | NULL for root |
| `synced_at` | TEXT | |
Only species + wood category. Sync pulls all Woo categories; the app filters to the two we use.
Species leaves from this table (after filter) are the **only** species the UI and Call 1 may offer.
`UNIQUE(woo_id)`.
---
## woo_attributes
| Column | Type | Notes |
|---|---|---|
| `woo_id` | INTEGER PK | |
| `name` | TEXT | |
| `slug` | TEXT | |
| `type` | TEXT | 'select' |
| `synced_at` | TEXT | |
Only the five first-class attributes: Edge Type, Figure, Grade, Thickness, Moisture.
`UNIQUE(woo_id)`.
---
## woo_attribute_terms
| Column | Type | Notes |
|---|---|---|
| `woo_id` | INTEGER PK | |
| `attribute_id` | INTEGER FK → woo_attributes.woo_id | |
| `name` | TEXT | |
| `slug` | TEXT | |
| `synced_at` | TEXT | |
The actual selectable values. E.g., "Cathedral" under Figure, "1\"–1 1/2\"" under Thickness.
`UNIQUE(woo_id)`.
---
## woo_tags
| Column | Type | Notes |
|---|---|---|
| `woo_id` | INTEGER PK | |
| `name` | TEXT | |
| `slug` | TEXT | |
| `synced_at` | TEXT | |
Only `fig-*` and `feat-*` tags. Other Woo tags ignored. WooCommerce is the
authoritative source for tag definitions; this table caches synced Woo tags.
`UNIQUE(woo_id)`.
---
## settings
| Column | Type | Notes |
|---|---|---|
| `key` | TEXT PK | |
| `value_enc` | BLOB | AES-GCM ciphertext |
| `updated_at` | TEXT | |
Keys (server settings; secrets encrypted at rest):
- `woo_wp_username`, `woo_app_password`
(username + WordPress application password for a dedicated low-priv WP user;
not WooCommerce consumer keys)
- Store URL is **not** a settings row: `WOO_BASE_URL` env (compose), HTTPS only
- `inference_base_url`, `inference_api_key`, `inference_model`
- `inference_enabled`, `content_llm_enabled`
- `brand_voice`, `geo_context`
- `woo_create_status` ('draft' | 'publish'), default `draft` — Woo product create status key only; safety policy lives in AGENTS.md §5
- `taxonomy_last_sync_at` — UTC ISO; every successful Woo taxonomy pull
- `taxonomy_anchor` — UTC ISO; bump only when stored-subset hash changes (incl. deletions). No-op sync does not bump. Not Woo `date_modified`.
- `aspect_ratio` ('3:4'), `output_px` (1600), `output_px_min` (1600), `fill_target` (0.80)
Sheet/slider prefs (`sheet_mode`, sensitivity, edge offset, feather) persist in client
localStorage only. Client localStorage is source of truth (AGENTS §4 / ARCHITECTURE §5).
Server sync of these prefs is deferred post-POC.
**Prompt files** — not in the settings table. Shipped as text files in
`backend/app/prompts/` (repo), bind-mounted read-only to `/app/prompts/` in the
FastAPI container. Read fresh on each invocation. Default prompts shipped with the
app; owner edits on the host; no restart needed. A reset-to-default script
restores originals from the app bundle.
This table is the ciphertext **key inventory** and schema only. The never-browser /
AES-GCM / `SLAB_AES_KEY` env policy lives in AGENTS.md §4; flow lives in ARCHITECTURE §5.
AES master key is an env var (`SLAB_AES_KEY`, 32 bytes base64). Never in the DB.
Each `value_enc` = `nonce(12) || ciphertext`.
---
## sync_log
Append-only history. Not deleted on publish.
| Column | Type | Notes |
|---|---|---|
| `id` | INTEGER PK AUTOINCREMENT | |
| `slab_id` | TEXT FK | |
| `sku` | TEXT | |
| `woo_product_id` | INTEGER | |
| `status` | TEXT | 'success' \| 'failed' |
| `http_status` | INTEGER | |
| `error` | TEXT | machine-readable code |
| `detail` | TEXT | Woo error body |
| `payload_hash` | TEXT | sha256 of Woo payload sent |
| `created_at` | TEXT | |
---
## inference_log
Append-only audit.
| Column | Type | Notes |
|---|---|---|
| `id` | INTEGER PK AUTOINCREMENT | |
| `slab_id` | TEXT FK | |
| `call` | TEXT | '1' \| '2' |
| `request_payload` | TEXT | JSON of what was sent |
| `response_payload` | TEXT | JSON of what came back |
| `created_at` | TEXT | |
-196
View File
@@ -1,196 +0,0 @@
# Deployment Playbook (Docker Compose + Caddy)
Status: SPEC · env-agnostic · 2026-09-01 · SlabUploader
**Target:** any inventoried Docker host. Fill `deploy/INVENTORY.md` before bind.
Variables: `APP_HOST`, `APP_HOSTNAME`, `FRONTEND_PORT`, `FASTAPI_PORT`.
Health URL: `https://${APP_HOSTNAME}/api/health`.
> Gate A freeze (2026-08-31): hybrid client owns measure/crop SoT. Server-side measure/crop scaffolding is not done.
> server ruler/pipeline as authoritative. Woo UAT = draft + `SLAB-UAT-*` on PROD.
> Inference is **not** on the app host by default. It is a remote configurable endpoint.
**Historical lab example (non-normative):** TyUBUMini at `192.168.1.201` with hostname
`slab.tyubumini.local` was one early candidate. The inventory worksheet determines the host.
Use the inventory worksheet.
## 1. Host inventory (required before deployment)
Before deploying, fill `deploy/INVENTORY.md` (hard rule: inventory before execute):
1. `docker ps` — existing containers, published ports (avoid collisions with
co-resident apps; bolt.diy is one known example of 8443-class port use).
2. Caddy config location (host file or container) and existing site blocks.
3. Free port choice for the compose stack (proposal: `18080` http, `18443` https —
verify free on **this** host).
4. Docker volume dir convention on the host.
5. Reachability: confirm `${APP_HOSTNAME}` is reachable from the phone network
(same LAN or Tailscale). Add DNS (Pi-hole/AdGuard or Tailscale MagicDNS) if needed:
one A record → `${APP_HOST}` (LAN and/or Tailscale name).
Write the chosen values into `deploy/INVENTORY.md` and the host `.env` before compose up.
## 2. Repository layout (at scaffold)
```
SlabUploader/
├── AGENTS.md
├── README.md
├── docs/ # this plan set
├── deploy/
│ ├── docker-compose.yml
│ ├── Caddyfile.fragment # slab site block (merged into host Caddy)
│ ├── INVENTORY.md # filled at Gate B on the designated host
│ ├── .env.example # SLAB_AES_KEY, APP_*, WOO_BASE_URL (https only)
│ └── backup.sh # sqlite .backup + images tar, with retention
├── frontend/ # SvelteKit app
└── backend/ # FastAPI app
├── app/
│ ├── main.py
│ ├── (no happy-path pipeline SoT here) # hybrid: TECH-SPEC modules live in frontend/ or shared pure TS; backend = store/Woo/inference/U2Net stub
│ ├── woo/ # Woo client, taxonomy, publish
│ ├── inference/ # vision + content wrappers (toggleable)
│ ├── prompts/ # call1.txt, call2.txt (shipped defaults)
│ ├── api/ # routers (slabs, photos, pricing, taxonomy, settings)
│ ├── db/ # schema.sql, models, migrations (alembic)
│ └── security/ # AES-GCM settings encryption
├── tests/ # pytest — unit (deterministic) + integration (woo)
└── Dockerfile
```
## 3. docker-compose.yml (checked in)
Canonical file: `deploy/docker-compose.yml`. Placeholders: `deploy/.env.example`.
From **repo root**:
```
cp deploy/.env.example deploy/.env && chmod 600 deploy/.env
# fill SLAB_AES_KEY, APP_HOSTNAME, WOO_BASE_URL (https:// only)
docker compose -f deploy/docker-compose.yml --env-file deploy/.env up -d
```
Caddy site block: `deploy/Caddyfile.fragment` (merge into host Caddy). Compose
service names `frontend` and `fastapi` must match that fragment.
**Store URL (`WOO_BASE_URL`):**
- Set in `deploy/.env` and injected into the FastAPI container at start.
- **HTTPS only.** FastAPI must refuse missing / `http://` values at startup.
- Not a Settings input and **not** a SQLite settings row.
- Settings UI shows the URL as **read-only** text (which store this deploy hits).
- Change store = edit `.env` + recreate the fastapi container.
Woo Application Password stays out of compose. Enter it in Settings; FastAPI stores it AES-GCM encrypted.
Conventions (house rules):
- `mem_limit` on services (not host-level tuning).
- Services bind to 127.0.0.1 only; Caddy is the only public surface.
- No `latest` tags on base images — pin versions.
- `restart: unless-stopped`; compose is the supervisor (no systemd units).
## 4. Caddy (fragment)
Canonical file: `deploy/Caddyfile.fragment`. API must win over the frontend
catch-all. Put `handle /api/*` **before** the frontend `handle` block:
```caddyfile
{$APP_HOSTNAME} {
tls internal # Caddy internal CA (or host-appropriate TLS)
handle /api/* {
reverse_proxy fastapi:8000
}
handle {
reverse_proxy frontend:80 {
header_up X-Real-IP {remote_host}
}
}
}
```
- HTTPS enforced (http→https redirect automatic when using Caddy TLS).
- If the host Caddy already serves a wildcard for this domain family, add this as a
site block. Verify the cert is trusted on the phone.
- LAN/Tailscale only — no public exposure for POC.
## 5. Secrets
| Secret | Where | Notes |
|---|---|---|
| `SLAB_AES_KEY` | `deploy/.env` (mode 600) → compose env | 32-byte base64; NEVER in the repo |
| `WOO_BASE_URL` | `deploy/.env` → compose → FastAPI env | `https://` only; Settings **read-only** |
| Woo WP username + application password | SQLite `settings` (AES-GCM) via Settings UI | dedicated low-priv WP user; not consumer keys |
| Inference API key | SQLite `settings` (AES-GCM) via Settings UI | usually empty for local llama.cpp |
| `.env.example` | repo | placeholders only, committed |
**Woo credential setup (once per store):**
1. Store must already be on **HTTPS**. WordPress will not offer Application
Passwords over plain HTTP.
2. Create a dedicated low-privilege WordPress user (shop manager, or custom role
with product create/edit + media upload). Admin logins are not reused.
3. Sign in as that user → **Users → Profile → Application Passwords** → generate
a password for "SlabUploader".
4. Enter the username + application password in the app Settings UI. FastAPI
stores them AES-GCM encrypted. Browser never keeps them.
5. Rotate by revoking the old application password in the WP profile and
re-entering a new one in Settings, then `test-woo`.
Key rotation (AES): `SLAB_AES_KEY` change requires re-encrypting settings —
provide `python -m app.security.rekey NEW_KEY` (reads old key from env
`SLAB_AES_KEY_OLD`, decrypts, re-encrypts, updates). Documented in playbook §7.
## 6. Backup and restore
`deploy/backup.sh` (run via cron on the app host, e.g. daily 03:00):
```
1. sqlite3 /data/slab.db ".backup /backups/slab-YYYYMMDD.db" # WAL-safe
2. tar czf /backups/slab-images-YYYYMMDD.tgz -C /images .
3. retain: 7 daily + 4 weekly; prune older
4. log result to /var/log/slab-backup.log; alert (Hermes) on failure
```
Prompt files live in the git repo (`backend/app/prompts/`) and are version-controlled;
they do not need a separate backup. The `reset-to-default` script restores shipped
defaults from the app bundle.
- Backup target: local dir first; mirror to an off-box share for safety (same pattern
as other stacks on the host).
- **Restore**: stop compose → restore DB file + untar images → start compose.
Tested at least once during Phase 6 (UAT) before declaring backup done.
## 7. Operations runbook
| Task | Command / how |
|---|---|
| Deploy (first) | inventory §1 → `docker compose -f deploy/docker-compose.yml build` → `up -d` → Caddy reload → smoke §8 |
| Update | `git pull` → `docker compose build fastapi frontend` → `up -d` (DB migrations run on start via alembic) |
| Logs | `docker compose logs -f fastapi` / `frontend` |
| Health | `curl -k https://${APP_HOSTNAME}/api/health` |
| Rekey AES | §5 |
| Rotate Woo creds | WP user profile → revoke old application password → new one → Settings UI → `POST /api/v1/settings/test-woo` |
| Rotate inference key | Settings UI (if external) |
| Edit a prompt | Edit the text file on host, no restart needed (read fresh each time) |
| Rollback image | `git checkout <tag>` → rebuild → up -d; DB down-migrations provided for schema changes |
| Reset one slab | delete its photos dir + `UPDATE slabs SET status='draft'` (admin script) |
## 8. Smoke test (after every deploy)
1. `GET https://${APP_HOSTNAME}/api/health` → ok (from phone over HTTPS once CA trust is proven)
2. Settings: WP application password + `test-woo` ok; `woo_create_status=draft`; inference OFF for early gates
3. Create a slab → upload test photos (fixture set) → poll to `ready`
4. Verify bdft/price match the fixture's expected values (golden test; bdft = sqft × thickness)
5. Publish test slab with SKU `SLAB-UAT-…` → slab may show local `published`; Woo product must be **draft**
6. Leave or delete the Woo draft UAT product (never customer-visible). Final live publish is a non-UAT SKU after Ty review.
For the full human-run walk (host check → App Password → one `SLAB-UAT-*` prove → confirm →
cleanup), see `docs/UAT-PRACTICE.md`.
## 9. Scaling path (not v1)
- Postgres when SQLite write contention appears (schema already portable).
- Redis+arq when in-process queue shows lag.
- GPU on the app host only if on-demand U2Net latency becomes a bottleneck. Keep CPU
first. Never lower `output_px_min` below 1600; undersized source means retake, not a
smaller min. RemBG is not part of the hybrid happy path.
-336
View File
@@ -1,336 +0,0 @@
# Implementation Plan
Status: SPEC · Gate A freeze 2026-08-31 · hybrid rewrite complete 2026-09-01 · SlabUploader
Phases 0–6 below are hybrid-aligned. Phase 2 remains a deferred stub only; offline PWA, OCR, ruler, and server happy-path measure/crop as SoT are not implemented.
The build plan a professional (or a fresh Hermes session) executes against. Each phase
has: goal, deliverables, acceptance criteria (testable), and exit gate. Ordering is by
dependency. Definition of done for every phase: code + tests + real
execution output in the PR/commit message + docs updated.
Ground rules (from AGENTS.md):
- Deterministic core is unit-tested before any UI consumes it.
- No feature without a passing test and shown output.
- Inference stays toggleable; the full suite must pass with it disabled.
- One phase = a reviewable, shippable increment.
Test specification: `docs/TEST-SPEC.md` — pyramid cases, phased by gate, affirmative only.
---
## Phase 0 — Hybrid skeleton and client deterministic core (= Gates A+B)
Goal: scaffold the hybrid app and ship a **tested client-authoritative** TECH-SPEC
pipeline (mask → axis → sqft/bdft → 3:4 PNG) plus a minimal FastAPI store/settings
shell. No Woo publish, no inference, no offline/OCR/ruler.
**Gate A (docs):** AGENTS.md + this Phase 0 rewrite + review package locks (signed
2026-08-31). **Gate B (infra/code):** items below.
Scope — in:
- Repo layout: `frontend/` (SvelteKit), `backend/` (FastAPI), `deploy/` stubs; docs stay SoT.
- Client pure modules implementing TECH-SPEC: constants, sheet/chroma/black + sliders,
mask confirm hooks, length axis, scale, 6" widths, sqft, **bdft = sqft × thickness_in**,
pricing rec from species $/bdft, 3:4 PNG / 80% fill / ≥1600 guard (**no upscale**).
- FastAPI: app factory, logging, config, `GET /api/health`, SQLite + alembic skeleton,
settings stub with AES-GCM round-trip (secrets never returned on GET), draft store stub
(accept client numbers + files — store only, no server-side recompute of SoT).
- `deploy/docker-compose.yml`, `Caddyfile.fragment`, `.env.example` (placeholders only).
- Unit tests for TECH-SPEC **TV-1 through TV-10** (esp. TV-3 bdft, TV-6/7 crop/no-upscale,
TV-8 pricing, TV-10 rounding).
- Fixture photo set for Ty Gate B review.
Phase 0 covers:
- Server happy-path pipeline / CLI that recomputes mask/crop/bdft as SoT: client is authoritative; server stores client-sent numbers only.
- Real U2Net: stub OK; on-demand later. The one-photo server path stays in architecture.
- Woo create/publish and live taxonomy sync: Phase 1. Species offered in UI, pricing seeds, and Call 1 are **exactly** Woo-synced species-category leaves (CONTENT-WOO §2.2 / AGENTS §6 / DATA-MODEL `woo_categories`).
- Inference Call 1/2, LoRA: Phase 5.
- Offline PWA, IndexedDB sync, OCR, ruler: Phase 2 (deferred stub).
- Fake upscale / inventing pixels: undersized source warns and requires retake.
Deliverables:
- `frontend/` scaffold + deterministic modules + unit tests TV-1…TV-10.
- `backend/` FastAPI health + settings encryption + draft persistence stub + schema migration baseline.
- `deploy/` compose + `.env.example` + Caddy fragment.
- Shown output in PR/commit: printed TV-3, TV-6, TV-7 (no-upscale/retake), and TV-10 on **real fixtures**.
Acceptance:
- Gate B: client (or shared pure) tests green for TECH-SPEC vectors; bdft identity holds
(no `/12`); undersized source warns and refuses fake upscale; rounding matches TV-10.
- `GET https://${APP_HOSTNAME}/api/health` up in compose after `deploy/INVENTORY.md` is filled and Caddy is merged.
- Settings AES round-trip; secret fields never appear in GET.
- Draft can store client-uploaded originals + PNGs + numbers without server recompute.
- Coverage target: deterministic modules ≥ 95% where practical; property checks
(bdft monotonic in thickness/sqft; fill band; no upscale path).
Exit gate: Ty confirms Gate B math/image prep shown output on real fixtures; health +
encrypted settings + draft store stub demonstrated (curl or thin UI).
**Next:** Gate C = early Phase 1 claimable publish — online hybrid capture + Woo **draft**
+ `SLAB-UAT-*` on the configured store, inference OFF. Call 1/2 after Gate C, still inside POC.
---
## Phase 1 — Gate C claimable path, then full API surface (rewritten)
### Early Phase 1 / Gate C slice (claimable first draft listing)
Goal: one Woo **draft** listing Ty can open in store admin, with inference **OFF**.
Online hybrid capture only. No OCR, ruler, or offline.
Deliverables:
- Online capture of 1–5 inventory photos (no airplane-mode requirement).
- Client sheet + **four knobs inline** on capture (live re-run, mask overlay on
source photo); user confirm; length axis overlay + confirm. No U2Net control.
- Client sqft / bdft / 6" widths; 3:4 transparent PNG prep per TECH-SPEC.
- Manual SKU, length, thickness; manual taxonomy as needed for one listing.
- Calibrated draft upload: originals + processed PNGs + client-sent numbers. Server
stores only (OPENAPI POST returns `status: calibrated`).
- Woo **draft** create with SKU prefix `SLAB-UAT-*` on the configured PROD store.
Honor AGENTS Woo safety: `SLAB-UAT-*` forces draft even if Settings say publish.
- Inference remains OFF for this slice. Full suite still green with inference disabled.
Acceptance:
- Ty captures a real slab on phone (online), adjusts any mask knob and sees a fresh
overlay without leaving the screen, confirms mask + axis, sees client numbers.
- Species picker offers **only** Woo-synced species (after test-woo / sync).
- One `SLAB-UAT-*` product appears in Woo admin as **draft** with correct SKU/price/images
enough for Ty to open and inspect.
- No Call 1/Call 2 required. No offline, OCR, ruler, or U2Net path exercised.
- Duplicate SKU → stop with field-level recovery; no second product.
Exit gate: Ty opens one draft listing in Woo admin. Gate C is green.
### Phase 1 remainder (API / settings / taxonomy cache)
Goal: full slab CRUD + photo upload + settings + taxonomy cache read, still hybrid.
No server happy-path math. No `processing` slab status.
Deliverables:
- Routers per OPENAPI: slabs (CRUD + upload + poll), photos (serve), pricing-rules,
settings (AES-GCM + test stubs), taxonomy (cache read/write + manufactured
`taxonomy_anchor` / `taxonomy_last_sync_at`).
- Optimistic concurrency (`client_rev` / `server_rev`, 409 paths).
- Status machine only: `draft → calibrated → ready → publishing → published | failed`.
Job queue only for publish and inference (later). U2Net-on-demand is deferred from POC. Never for measure/crop.
- Integration tests (httpx TestClient): create calibrated → poll → ready (manual fields);
revision conflict; duplicate SKU; settings encryption round-trip (secret never returned);
taxonomy anchor bumps on stored-subset change and stays put on no-op sync.
Acceptance:
- OPENAPI.md endpoints implemented; a generated `openapi.yaml` matches the doc.
- Integration tests green; secrets never leak into any GET response (asserted).
- `docker compose up` (backend + a throwaway frontend stub) serves the API.
- PUT stores client-sent derived fields; does not recompute sqft/bdft/widths as SoT.
- Taxonomy: anchor advances only on real stored-subset change; client re-pulls only
when anchor is newer; `test-woo` always resyncs; publish respects the 1h threshold.
Exit gate: Ty drives the API with curl through a full calibrated → ready cycle (manual).
---
## Phase 2 — Deferred: offline PWA / OCR / ruler (stub only)
**Deferred post-POC.** The online-only MVP does not implement offline capture.
Capture UX for POC lives in early Phase 1 / Gate C (online hybrid). See AGENTS.md §2.
Offline PWA, OCR, and ruler detection are deferred to a later product decision:
- Workbox service worker, IndexedDB draft sync, airplane-mode capture
- Tesseract.js OCR for SKU
- OpenCV.js ruler / scale detection
No airplane-mode acceptance. No OCR or ruler exit gate in POC.
---
## Phase 3 — Frontend: enrich, review, publish UI (rewritten)
Goal: online review + publish UI on top of Gate C calibrated drafts. Hybrid only.
Client already owns mask/numbers/PNGs. This phase does not re-measure on the server.
Deliverables:
- Review screen after calibrated upload: all fields editable (length, thickness, SKU,
widths/sqft/bdft shown as client-computed with manual override paths, species and
wood categories, five attributes, fig-*/feat-* tags, price with species $/bdft
recommendation, title/short/description).
- Show client-processed transparent PNGs (and originals while retained). No server
re-crop UI as SoT.
- Inference UI (only meaningful after Gate C and when `inference_enabled`): Call 1
results with confidence. **≥ 0.7** (configurable default) → pre-fill mutable
fields. **< 0.7** → leave empty; inline nudges. Continue/ready is blocked until
the **full ready set** is filled — not species + wood category + figure alone.
Canonical lock (AGENTS §7 / DATA-MODEL slabs **ready**): SKU, length, thickness,
client sqft/bdft/widths, ≥1 inventory PNG, exactly one species, ≥1 wood category,
1 edge type, ≥1 figure term, ≥1 fig-* tag, ≥1 grade, thickness store band
(round-up), 1 moisture (default kiln-dried; not inferred), price. feat-* 0+.
Title/description may be typed, generated, or templated at publish. Presentation:
`docs/UX.md`. "Generate text" triggers Call 2; never auto.
- Capture: four knobs on the mask screen with live re-run. No U2Net control in POC.
- Publish button (online-only), poll `publishing` → `published` | `failed`, surface
error detail from sync_log.
- Settings UI: WP username + application password + test-woo, inference endpoint +
test (vision + portable-context probe), pricing rules editor, brand voice/GEO,
`woo_create_status`. Store URL read-only from `WOO_BASE_URL`. Sheet/slider prefs
stay in client localStorage. Prompts are server files, not UI settings.
- Secrets never appear in GET settings responses (masked `*_configured` only).
Acceptance:
- Browser round-trip: online capture → mask/axis confirm → calibrated upload →
review → edit → publish → local `published` (Woo mock in tests; real store Phase 6).
- Inference OFF → full manual taxonomy + content path works; no inference network calls.
- Field overrides persist across poll/refresh (asserted).
- No offline/IndexedDB requirement. No OCR/ruler UI.
Exit gate: Ty publishes a test slab to the real store as a **Woo draft** (`SLAB-UAT-*`).
(Gate A lock: not pending/published for UAT.)
---
## Phase 4 — WooCommerce integration (rewritten)
Goal: production Woo sync, taxonomy, dedupe, logging. Browser never calls Woo.
Media bytes are client-processed **PNGs**. Safety policy from AGENTS §5.
Deliverables:
- Woo client (httpx, Basic auth with WP username + application password, timeouts),
taxonomy sync into cache tables, auto-assign per CONTENT-WOO §2.3 (categories +
five attributes + fig-*/feat-* tags only). No WooCommerce consumer keys.
- Media upload of processed PNG inventory photos; product create via `woo_create_status`
(default **draft**). If SKU matches `SLAB-UAT-*`, force Woo **draft** even when
Settings say publish.
- Dedupe by SKU before create (any Woo status); `409 duplicate_sku` with field recovery
paths (edit SKU / open existing); no edit-same-SKU path in MVP.
- `422 stale_field` recovery with current options from cache (CONTENT-WOO §2.6).
- `sync_log` with payload_hash; on success set local `published`, purge originals +
processed images on server.
- `POST /api/v1/admin/taxonomy/sync` against the real store; manufactured anchor.
- Integration tests against a Woo mock (respx) for success + error + duplicate +
stale-field paths.
- Partial-failure handling (orphaned media noted, per CONTENT-WOO §2.6).
Acceptance:
- Real UAT publish: product appears in store admin as **draft** under `SLAB-UAT-*`,
correct SKU/price/PNG images/category/tags/attributes; `woo_product_id` stored;
`sync_log` written with payload_hash.
- Duplicate SKU publish → 409 mapped to SKU field, no second product created.
- Stale taxonomy value → 422 on that field with current options; draft retained.
- Woo error (bad creds / 500) → slab `failed` with detail; retry path works.
- All Woo integration tests green (mock + one live smoke).
Exit gate: Ty verifies a real **Woo draft** `SLAB-UAT-*` product in the store is correct.
---
## Phase 5 — Inference (vision + optional content) (rewritten)
Goal: scoped, toggleable inference **after Gate C is green**, still inside POC.
Does not gate publish. Full suite must pass with inference OFF.
Deliverables:
- Call 1 (vision) proxy: **all inventory photos** downscaled to 1024 + Woo taxonomy
snapshot + user metadata; OpenAI-compatible endpoint; model constrained to cached
taxonomy **from the Woo cache only**; confidence threshold **0.7** (configurable
default; not a POC Settings slider). Auto-run on calibrated create only if
`inference_enabled`. Not top-down-only.
- Apply AGENTS §6 prefill: ≥ threshold → pre-fill mutable species/categories/attributes/
tags; < threshold → those fields stay empty. Call 1 is assist only and does not
define ready. Ready/publish requires the **full ready set** in AGENTS §7 /
DATA-MODEL (SKU, length, thickness, client sqft/bdft/widths, ≥1 inventory PNG,
exactly one species, ≥1 wood category, 1 edge type, ≥1 figure term, ≥1 fig-* tag,
≥1 grade, thickness store band round-up, 1 moisture default kiln-dried not
inferred, price; feat-* 0+). Species + wood category + figure is not the gate.
Presentation: `docs/UX.md`.
- Call 2 (text) proxy: never auto. Portable Call 1 context (full resend default).
LLM prose only; templates inject deterministic numbers. See `docs/PROMPTS.md`.
- `test-inference` endpoint (vision + portable vs stateful probe). Fail closed if
neither Call 1→Call 2 path works.
- Feature flags; `inference_log` audit rows; prompt files read fresh each call.
- No numeric/dimension invention by the LLM. LoRA deferred.
Acceptance:
- Local vision model configured: ≥ 0.7 fields pre-fill and remain editable; user
override sticks.
- Below 0.7: fields stay empty; UI blocks continue/ready until the full AGENTS §7
/ DATA-MODEL ready set is filled (asserted). Species + wood category + figure
is not the ready definition.
- No doc/code path auto-fills below-threshold guesses or treats inference as a
publish gate.
- Inference OFF: app works end-to-end; tests assert zero calls to the inference endpoint.
- Audit payloads present after a call; prompt file edits apply without server restart.
- Gate C path remains green with inference OFF.
Exit gate: Ty runs species detection on 3 real slabs; results acceptable or manually
corrected (that is the design).
---
## Phase 6 — Deployment, UAT, hardening (rewritten, online only)
Goal: production deploy on the **inventoried** host + online user acceptance tests.
Deliverables:
- Host inventory pass: complete `deploy/INVENTORY.md` per DEPLOYMENT §1 → final compose + Caddyfile.
- Deploy to `https://${APP_HOSTNAME}` from inventory; backup/restore runbook executed once (restore tested).
- **UAT suite** for the hybrid online path: scripted real slabs (≥3 species, ≥1 cathedral,
≥1 manual-width path, ≥1 duplicate-SKU attempt) with expected bdft/price/image-fill
asserted. **No** offline capture, OCR, or ruler cases in POC UAT.
- Performance: client measure/crop budgets on device; optional U2Net-on-demand latency.
No server happy-path “normalization 3–5s” budget. No OCR 1–2s budget.
- Docs: README, runbook, key-rotation verified.
Acceptance (measured):
- E2E capture→publish on iPhone, Android, and PC browsers (desktop Chrome/Edge/Firefox) works (online).
- Manual length override recalculates widths/sqft/bdft correctly (UAT asserts).
- Client crop: slab ~80% frame in ≥95% of UAT photos; shorter side ≥1600 when source allows.
- Woo product created with processed PNG images + correct taxonomy.
- Deterministic functions unit-tested; inference calls logged for audit when used.
- Backup restore demonstrated once.
Exit gate: Ty signs off on UAT results; v1 declared done.
---
## Risks and mitigations
| Risk | Impact | Mitigation |
|---|---|---|
| Green-sheet color varies | bad mask, wrong sqft | chroma-key / black threshold + inline knobs + live re-run; retake; U2Net deferred from POC; never drop `output_px_min` below 1600 |
| No vision model available at deploy | species inference off | inference is toggleable; manual species/character fully functional — v1 not blocked |
| Woo partial publish (media up, product POST fails) | orphaned images, confusing state | sync_log + retained images for retry; manual cleanup note; no auto-delete |
| Local vision endpoint not up | inference off | configurable endpoint; deploy-time config; app works without it |
| SQLite contention under concurrent polls | slowdown | single owner, low volume; Postgres path documented |
| Host port/Caddy collision with co-resident apps (e.g. bolt.diy) | deploy conflict | Phase 0/6 inventory worksheet before any port bind |
Ruler detection is **deferred** with offline/OCR (Phase 2 stub). Manual length is
authoritative for POC. Ruler confidence is not a POC risk row.
---
## Definition of Done (v1, project-level)
- All 6 phases exit-gated by Ty (Phase 2 remains deferred stub unless product reopens it).
- Hybrid online acceptance met (measured in Phase 6 UAT). Gates A/B/C meanings match AGENTS §0b.
- `pytest` + integration + UAT green; inference-off path green.
- Deployed on the inventoried host (`APP_HOSTNAME` from `deploy/INVENTORY.md`), HTTPS, backed up, restore tested, runbook + key-rotation verified.
- Repo on gitea-atd (`Ty_Tech/SlabUploader`) is source of truth; docs current.
- `docs/archive/PRD-2026-08.txt` is frozen history only; live docs are the implementation SoT.
+100
View File
@@ -0,0 +1,100 @@
# Milestone 1 — Plan of Record (POR)
Decisions captured as they are made. This is the working plan for implementing and UAT-ing Milestone 1. It is the source of truth for scope, order, and dispatch; the spec detail lives in `docs/CAPTURE.md` and `docs/PRODUCT.md`.
## Scope
Implement **Milestone 1 — Capture** only (see `AGENTS.md`). Browser-only, inference-free, no backend, no Woo create. Milestones 2–4 are out of scope.
## Method — TDD (non-negotiable)
Every card is delivered **test-first** per the `test-driven-development` skill:
```
NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST
```
- **Red-Green-Refactor**, tracer-bullet: one behavior slice at a time (RED→GREEN→REFACTOR), not all-tests-then-all-code.
- **Verify RED** (watch it fail for the right reason) and **Verify GREEN** (it passes + full suite stays green) are mandatory before the card is done.
- Code written before a failing test is **deleted and redone** — not kept as "reference."
- The deterministic core (math + PNG contract) is unit-tested in a browser-runnable JS suite; UI behaviors are tested with Playwright against the fixtures.
- A card is not complete until: every new function has a test, each test was seen failing first, the full suite passes with pristine output.
## Card breakdown (implementation order)
Each card follows TDD. "Define" = write the failing tests (RED); "Build" = minimal code to pass (GREEN); "Refactor" = clean up keeping green.
1. **Scaffold + Dockerfile + test harness** — SvelteKit project with the browser-only M1 runtime (Web Worker, canvas/OffscreenCanvas, IndexedDB via `idb-keyval`), `frontend/Dockerfile`, and the test harness (JS unit runner + **Playwright** web).
- *TDD note:* this card establishes the harness itself (a smoke test that runs and fails, then passes) so every later card has a place to be RED/GREEN.
2. **Deterministic core** — the pure math + PNG-encode functions.
- *RED:* unit tests for `scale`, `sqft`, `bdft`, width sampling, 1/8″ stepping, rounding, and the PNG contract (3:4, 8-bit RGBA, 80% fill, ≥1600px floor, undersized→retake). Run on the fixtures' calibration records.
- *GREEN/REFACTOR:* implement to pass; core is authoritative and server-less.
3. **Capture + Mask** — Add photo (JPEG; HEIC→"retake as JPEG" notice), green/black key, four knobs, debounced recompute, mask approve.
- *RED:* Playwright — load fixture, key sheet, approve; empty-mask blocks approve; HEIC shows the notice.
- *GREEN/REFACTOR:* build the Mask state to pass.
4. **Length axis** — min-area bounding rectangle + long-side axis, user rotate, approve.
- *RED:* Playwright — rect drawn from the approved mask, axis on long side, rotate, approve.
- *GREEN/REFACTOR:* build the axis state.
5. **Measure + PNG** — length/thickness (1/8″), compute sqft/bdft/widths, write the 3:4 inventory PNG. M1 stops here.
- *RED:* Playwright — enter L/thickness → Calculate; assert PNG is 3:4 with alpha, and numbers equal the fixture's expected values.
- *GREEN/REFACTOR:* build Measure + PNG encode.
6. **M1 UAT** — serve the container per `deploy/README.md` §Milestone 1 UAT; run the full Playwright suite in the container; then the manual phone pass. Record host + URL in `deploy/INVENTORY.md`.
## Deployment (UAT)
See `deploy/README.md` §Milestone 1 UAT — deployment POR: one container, host chosen at runtime, LAN-reachable URL, no backend.
## Dev / QA worker dispatch
Two local inference endpoints are available as dispatchable workers for test / dev / QA:
- **`.202:8081`** — `gemma-4-12B-it-q4_k_m` (12B, Q4) — **completion only, no vision.** Use for lighter text: drafting, code review, summaries.
- **`.202:8082`** — `Qwen3.8-27B-UD-IQ3_XXS` (27B, IQ3) — **completion + multimodal (vision).** The **vision worker** (any task that must look at a slab photo) and the stronger general-reasoning endpoint.
Coordinator: Hermes (me) — plans, decomposes, dispatches, verifies, and does work directly when a card is small or judgment-heavy.
### Calibrated delegation policy (2026-09-14)
- **Frame every prompt**: system role + "show each step" + explicit constraints. Small/low-quant models drop multi-step arithmetic in one-shot "reply JSON only" prompts but get it exactly right with scratch-space framing. Do not judge capability from under-framed probes.
- **The deterministic core stays the coordinator's** (TDD'd, unit-tested). A model that's "usually right" on math is not good enough for the spec — math is cheap to test and must be exact.
- **Verify before land**: any load-bearing model output is checked against tests/spec before entering the repo. Workers are assist, not autonomous builders.
- **Output quirks**: gemma wraps JSON in ``` fences — strip before parsing. Vision calls run ~18s/image (text ~1s).
- **One task per endpoint at a time** (no parallel on the same endpoint — backs up and overheats).
- Both run low-quant (Q4/IQ3). Fine for framed assist; deep sustained reasoning is best done by the coordinator directly.
## Test plan (M1)
Three layers. The deterministic core is unit-tested; the end-to-end path is Playwright; a real phone is the final UAT gate.
### 1. Unit (deterministic core) — must pass before any UI consumes it
- `bdft = sqft × thickness_in`; `sqft = (mask_px / scale²) / 144`; `scale = longest_axis_px / L`.
- 1/8 in stepping; rounding (sqft/bdft 2 decimals).
- Width sampling every 6 in along the approved axis.
- PNG encode contract: 3:4 aspect, 8-bit RGBA, 80% fill, shorter side ≥ 1600px when source allows; undersized source → warn + retake (no upscale).
- Mask empty → approve blocked.
### 2. Playwright (automated end-to-end, runs in the UAT container's browser)
Walks the 5 states against a **sample photo**:
- Add photo → Mask (set sheet + sensitivity) → approve → Length axis → approve → Measure (enter L, thickness) → Calculate.
- Assert: PNG rendered, dimensions = 3:4, alpha present; sqft/bdft/widths equal the expected values for that fixture (within tolerance); numbers visible on screen.
- HEIC input → "retake as JPEG" notice shown (not a crash).
- Device draft: reload → Resume → Continue restores last approved state.
### 3. Manual phone UAT (final gate)
On a real phone (iOS Safari / Android Chrome) over the LAN UAT URL: repeat the happy path with one real slab; confirm PNG + numbers on screen. Record host + URL in `deploy/INVENTORY.md`.
## Test fixtures (sample pics)
Real slab photos are the fixtures (supplied by Ty from `\\truenas.local\Business\Samples`, SMB user `SMBSVC`). Each is a DJI MIMO top-down JPEG, ~4000×2256, slab on a green/black sheet.
`tests/fixtures/`:
- **sample_01 … sample_0N.JPG** — a representative handful of real slab photos (pulled on demand from the TrueNAS Samples share; do not bulk-copy the whole folder).
- Each fixture gets a **calibration record** in `tests/fixtures/<name>.json`: the slab's true length and thickness (in inches), the sheet color, and the approved mask/axis reference — used to compute the expected `scale`, `sqft`, `bdft`, and sampled widths for assertions.
The real photos drive both **bg removal** (green/black key) and **rectangle/axis calibration**. Expected values come from the calibration records, so assertions stay deterministic even on real imagery.
**M1 fixture set (agreed, complete for M1):** three black-sheet slabs — one irregular (stress-tests the min-area rectangle/axis), two clean elongated. Green-sheet keying is deferred (not an M1 fixture). A 1 HEIC sample (optional) for the decode-fallback test.
## Open decisions
- (none outstanding for M1 as of this plan; new decisions append here)
-328
View File
@@ -1,328 +0,0 @@
# OpenAPI Contract — SvelteKit Client ↔ FastAPI
Status: SPEC · 2026-08-27 · SlabUploader
Base path: `/api/v1`. All requests/responses JSON unless noted.
All timestamps UTC ISO-8601.
## Conventions
### Auth
No client auth. Trusted LAN/Tailscale + HTTPS.
### Errors
Uniform envelope:
```json
{ "error": { "code": "string", "message": "string", "detail": "object|null" } }
```
- `400 validation` — payload failed validation.
- `404 not_found` — unknown slab/photo/setting.
- `409 revision_conflict` — client_rev/server_rev mismatch. `detail` carries `current_server_rev`.
- `409 duplicate_sku` — SKU already exists in WooCommerce, any status (draft, private, publish, etc.).
- `422 unpublishable` — slab not in a publishable state or missing required field.
- `502 woo_error` — WooCommerce rejected the request. `detail` carries Woo error body.
- `500 internal` — unexpected.
### Revisions
Create/update carry `client_rev`. Server echoes `server_rev`. Client stores `server_rev` and sends it back on the next update. Mismatch → `409 revision_conflict`.
### Photos
Uploaded as `multipart/form-data`. Max 40 MB per request. Two fields per photo:
- `files[]` — the original image file
- `meta[]` — JSON `{ kind: "inventory", role: "topdown"|"extra", seq: 1 }`
### Pagination
Lists are small (single owner, slab-by-slab). Lists return full arrays.
### API Version
URL is `/api/v1`. Breaking changes bump to `/api/v2`.
---
## Schemas
### SlabCreate
```jsonc
{
"id": "uuid (client-generated)",
"sku": "string 3..24 [A-Z0-9-]",
"length_in": 96.0, // 1/8" step
"thickness_in": 1.5, // 1/8" step
"sqft": 0.64, // computed by client
"bdft": 0.96, // computed by client
"width_min_in": 14.0,
"width_max_in": 22.0,
"width_avg_in": 18.2,
"species_id": 42, // → woo_categories (leaf)
"wood_category_ids": [15, 23], // JSON array → woo_categories (leaf, 1+)
"edge_type_term_id": 8, // → woo_attribute_terms
"figure_term_ids": [3], // JSON array → woo_attribute_terms (1+)
"grade_term_ids": [7], // JSON array → woo_attribute_terms (1+)
"thickness_term_id": 12, // → woo_attribute_terms (round-up)
"moisture_term_id": 5, // → woo_attribute_terms (defaults kiln-dried)
"fig_tag_ids": [99], // JSON array → woo_tags (fig-*, 1+)
"feat_tag_ids": [42], // JSON array → woo_tags (feat-*, 0+)
"price_per_bdft": 12.50, // from pricing_rules
"price": 12.00, // 2 decimals
"price_source": "recommendation|override|null",
"title": "string|null",
"short_title": "string|null",
"description": "string|null",
"content_source": "manual|llm|null",
"client_rev": 1
}
```
Photos come as multipart `files[]` + `meta[]` alongside this JSON (wrapped in a multipart request where one part is the JSON and the others are the files).
### Slab (read model)
All `SlabCreate` fields (resolved) plus:
`status`, `species_confidence`, `woo_product_id`, `published_at`,
`server_rev`, `created_at`, `updated_at`, `photos: [PhotoRead]`,
`inference_status: null|inferring|done|failed`, `inference_error: string|null`.
### PhotoRead
```jsonc
{ "id": "uuid", "kind": "inventory", "role": "topdown|extra",
"seq": 1, "original_url": "/api/v1/slabs/{id}/photos/{pid}/original",
"processed_url": "/api/v1/slabs/{id}/photos/{pid}/processed|null" }
```
### InferenceCall1Result (returned by infer-taxon)
Taxonomy fields are Woo IDs from the synced cache. Character/inclusions/voids/checks
are free-text observations; the server maps them to Woo `feat-*` product tags after
the call returns. WooCommerce is the authoritative source for `feat-*` definitions.
```jsonc
{ "species_id": 42, "species_confidence": 0.92,
"wood_category_ids": [15, 23],
"edge_type_term_id": 8,
"figure_term_ids": [3], "figure_confidence": 0.87,
"grade_term_ids": [7], "grade_confidence": 0.75,
"character": { "type": "knot", "severity": "minor" },
"inclusions": { "type": "bark pocket", "severity": "none" },
"voids": "none",
"checks": "none",
"wood_categories": [ { "name": "Live edge", "confidence": 0.95 },
{ "name": "Bowl blank", "confidence": 0.82 },
{ "name": "Table slab", "confidence": 0.61 } ] }
```
### InferenceCall2Result (returned by infer-content)
```jsonc
{ "title": "string", "short_title": "string", "description": "string" }
```
### PriceRule
```jsonc
{ "id": "uuid", "species": "string", "price_per_bdft": 12.50,
"created_at": "timestamp", "updated_at": "timestamp" }
```
### SettingsView (read; secrets masked)
```jsonc
{ "woo_base_url": "https://www.whidbeywoodstore.com", // WOO_BASE_URL env; read-only
"woo_wp_username": "slab-uploader", // non-secret identity; password never returned
"woo_credentials_configured": true,
"inference_base_url": "http://192.168.1.202:8080/v1",
"inference_model": "<model>", "inference_enabled": true,
"content_llm_enabled": false,
"brand_voice": "...", "geo_context": "...",
"woo_create_status": "draft",
"aspect_ratio": "3:4", "output_px": 1600, "output_px_min": 1600,
"fill_target": 0.80 }
```
Secrets (application password, inference API key) are never returned. Only a
`*_configured` boolean. Woo auth is WordPress Application Passwords
(`woo_wp_username` + `woo_app_password` write-only), not consumer keys.
Sheet/slider prefs are client localStorage only in POC (not in SettingsView).
---
## Endpoints
### Health & meta
- `GET /api/health` → `{ "status":"ok", "version":"...", "woo_reachable": bool }` (canonical deploy/smoke path; may also be exposed as `/api/v1/health`)
- `GET /api/v1/meta` → `{ "version":"...", "templates_configured": bool }`
### Slabs
- `POST /api/v1/slabs` — Create a calibrated draft. Body: multipart with `data` (SlabCreate JSON) + `files[]` (photos) + `meta[]` (photo metadata).
- Returns `201` `Slab` with `status: "calibrated"` (mask + axis confirmed; client-sent sqft/bdft/widths stored).
- Server auto-runs Call 1 **only if** `inference_enabled` is true. `inference_status` becomes `inferring`, then `done`/`failed`.
- After Call 1, persist inferred values onto the slab **only** for fields with confidence ≥ 0.7. Below 0.7 leave those columns null so GET does not prefill.
- `409 duplicate_sku` if SKU already exists in Woo, any status (payload as PUT).
- `GET /api/v1/slabs` → `200` `[Slab]` (most recent first).
- `GET /api/v1/slabs/{id}` → `200` `Slab` / `404`.
- Also used as the poll endpoint for inference and publish. Long-running ops set status to `inferring`/`publishing`; client backs off (1s, 2s, 4s, cap 10s).
- `PUT /api/v1/slabs/{id}` — Update draft fields. Body: partial `SlabCreate` (any subset of editable fields + `client_rev`).
- Server **stores** client-sent derived fields (`sqft`, `bdft`, widths). It may validate shape and ranges. It must **not** recompute mask, sqft, bdft, or widths as source of truth. Client re-runs TECH-SPEC math and PUTs the new numbers.
- `409 revision_conflict`.
- `409 duplicate_sku` → `{ "field":"sku", "code":"duplicate_sku", "message":"...", "actions":["edit_sku","open_existing"], "woo_product_id": "...?", "woo_admin_url": "...?" }`. `open_existing` is required even if lookup failed (then omit id/url). Never show the code. Presentation: `docs/UX.md`.
- `422` stale/invalid field → `{ "field":"species_id", "code":"stale_field", "message":"...", "actions":[], "options": [...] }` after a submission-time taxonomy refresh. Draft: phone form + server slab `failed` (retryable).
- `412` validation module stale → `{ "code":"validation_module_stale", "module": { "hash":"...", "rules":[] } }`. Not a 409.
- `DELETE /api/v1/slabs/{id}` → `204`. Soft: only unpublished drafts. Published slabs cannot be deleted from the app.
### Photo operations
- `POST /api/v1/slabs/{id}/u2net/{pid}` — **post-POC.** "Try harder." Server runs U2Net on this one photo, returns a better mask. The contract is preserved but not implemented or exposed in Gate C / first listing.
- Returns `202` `{ mask_url: "..." }`. Client uses the mask to re-compute area/widths locally.
- `404` if photo not found.
- `GET /api/v1/slabs/{id}/photos/{pid}/original` → `image/*` (original, while retained).
- `GET /api/v1/slabs/{id}/photos/{pid}/processed` → `image/*` (processed PNG, while retained).
- After publish, both → `410 Gone`.
### Inference
- `POST /api/v1/slabs/{id}/infer-taxon` — Trigger or retry Call 1 (vision).
- Server reads the Call 1 prompt file fresh, uses cached taxonomy + original
photos downscaled to 1024px + user metadata, and sends to the configured
vision endpoint.
- Returns `202` `{ "status": "inferring" }`. Client polls `GET /api/v1/slabs/{id}` for results.
- Timeout > 45s → `504 gateway_timeout` with error detail.
- `POST /api/v1/slabs/{id}/infer-content` — Trigger Call 2 (text).
- Server reads the Call 2 prompt file fresh. Default: **resend full Call 1
context** (prompt + assistant JSON + confirmed vs inferred labels). Use
`previous_response_id` only if test-inference reported stateful support.
Per-slab thread; delete on publish or abandon.
- Taxonomy + deterministic numbers + brand/GEO; LLM prose then templates.
- Requires `test-inference` `ok: true`. Else `422` (not connected / not portable).
- Returns `202` `{ "status": "inferring" }`. Client polls for results.
- Timeout > 45s → `504` with error detail.
### Publish
- `POST /api/v1/slabs/{id}/publish` — Publish to WooCommerce.
- Pre-conditions: status `ready` with SKU, length_in, thickness_in, client sqft/bdft/widths, ≥1 inventory PNG, exactly one species, ≥1 wood category, 1 edge type, ≥1 figure term, ≥1 fig-* tag, ≥1 grade, thickness_term_id, 1 moisture, price. Else `422 unpublishable` with field keys. UI maps, no raw code.
- Dedupe: if SKU already exists in Woo under any status → `409 duplicate_sku` (same payload as PUT).
- Stale Woo value → `422 stale_field` as above. Draft stays on the phone.
- Returns `202` `{ "status": "publishing" }`. Client polls.
- Woo failure → slab `failed`, `sync_log` written, poll returns `502 woo_error`.
- Success → slab `published`, `woo_product_id` set, images purged, draft row deleted.
### Taxonomy
- `GET /api/v1/admin/taxonomy` → `200` taxonomy grouped by kind:
```jsonc
{ "categories": [...], "attributes": [{ name, slug, terms: [...] }],
"tags": [...],
"taxonomy_anchor": "ISO-8601",
"taxonomy_last_sync_at": "ISO-8601" }
```
Client re-pulls iff `taxonomy_anchor` advanced. Species/attribute/tag
lists here are the **only** legal options for UI pickers and Call 1.
- `POST /api/v1/admin/taxonomy/sync` → `200` `{ "categories": n, "attributes": n, "tags": n, "taxonomy_anchor": "...", "taxonomy_last_sync_at": "..." }`.
- Pulls from Woo, rebuilds the cache. Always set `taxonomy_last_sync_at` on success. Bump `taxonomy_anchor` **only** if stored-subset hash changed. `502 woo_error` on failure; previous cache retained.
### Pricing
- `GET /api/v1/admin/pricing` → `[PriceRule]`
- `POST /api/v1/admin/pricing` → `201` `PriceRule`
- `PUT /api/v1/admin/pricing/{id}` → `200` `PriceRule`
- `DELETE /api/v1/admin/pricing/{id}` → `204`
### Settings
- `GET /api/v1/settings` → `200` `SettingsView`
- `PUT /api/v1/settings` — Update settings. Body: partial `{ key: value }`.
- `woo_base_url` is **not** writable (ignore or `422`). SoT is `WOO_BASE_URL`
env (HTTPS, compose). GET still returns it for read-only Settings text.
- Woo credential keys: `woo_wp_username` (plain) and `woo_app_password`
(write-only; AES-GCM at rest). Reject any payload that still sends
`woo_consumer_key` / `woo_consumer_secret`.
- Secrets re-encrypted server-side. `200` `SettingsView` returned (password
never echoed).
- `POST /api/v1/settings/test-woo` → `200` `{ "ok": bool, "detail": "...", "taxonomy_anchor": "...", "taxonomy_last_sync_at": "..." }`
- Uses stored username + application password over HTTPS Basic Auth against
`WOO_BASE_URL` REST v3. Fails closed if credentials missing or URL is not https.
- On success, **always** run a taxonomy resync (set last_sync; bump anchor only if hash changed).
- `POST /api/v1/settings/test-inference` → `200` `{ "ok": bool, "mode": "stateful"|"stateless"|"fail", "vision_capable": bool, "detail": "..." }`
- Two-turn probe. Default Call 1→Call 2 path is full resend; never require `previous_response_id`.
- `mode=fail` **blocks Call 2 enablement only**. Gate C inference-OFF still works.
- `GET /api/v1/validation/module` → `200` `{ "hash": "...", "rules": [ ... ] }`
- Shared FastAPI module (UI + Call 2). Client caches it. Submit sends `validation_hash`.
- Match → validate. Mismatch → **412** + fresh module. SKU `[A-Z0-9-]{3,24}`; titles UTF-8 + Woo maxLength.
---
## Request/response examples
### Create a slab (multipart)
```
POST /api/v1/slabs
Content-Type: multipart/form-data; boundary=---
---
Content-Disposition: form-data; name="data"
Content-Type: application/json
{ "id":"9f1c...","sku":"BW-0042","length_in":96.0,"thickness_in":1.5,
"sqft":0.64,"bdft":0.96,"width_min_in":14.0,"width_max_in":22.0,
"width_avg_in":18.2,"species_id":42,"wood_category_ids":[15,23],
"edge_type_term_id":8,"figure_term_ids":[3],"grade_term_ids":[7],
"thickness_term_id":12,"moisture_term_id":5,"fig_tag_ids":[99],
"price_per_bdft":12.50,"price":12.00,"price_source":"recommendation",
"title":null,"short_title":null,"description":null,
"content_source":null,"client_rev":1 }
---
Content-Disposition: form-data; name="files[]"; filename="topdown.jpg"
Content-Type: image/jpeg
<binary>
---
Content-Disposition: form-data; name="meta[]"
Content-Type: application/json
{ "kind": "inventory", "role": "topdown", "seq": 1 }
---
```
Response: `201`
```json
{ "id":"9f1c...","sku":"BW-0042","status":"calibrated",
"inference_status":"inferring","server_rev":1,"photos":[...],... }
```
### Call 1 completes (poll)
```
GET /api/v1/slabs/9f1c...
→ 200 { "status":"calibrated","inference_status":"done",
"species_id":42,"species_confidence":0.92,
"wood_category_ids":[15],"edge_type_term_id":8,
"figure_term_ids":[3],"grade_term_ids":[7],
"inference_error":null, ... }
```
### Call 2 (user taps Generate)
```
POST /api/v1/slabs/9f1c.../infer-content
→ 202 { "status":"inferring" }
GET /api/v1/slabs/9f1c...
→ 200 { "title":"Black Walnut 8ft 0in × 18.2in Slab — Cathedral",
"short_title":"Black Walnut Slab — Cathedral",
"description":"A one-of-a-one cathedral black walnut slab...",
"content_source":"llm", ... }
```
### Publish
```
POST /api/v1/slabs/9f1c.../publish
→ 202 { "status":"publishing" }
GET /api/v1/slabs/9f1c...
→ 200 { "status":"published","woo_product_id":1042,"published_at":"..." }
```
### Taxonomy sync
```
POST /api/v1/admin/taxonomy/sync
→ 200 { "categories": 24, "attributes": 5, "tags": 12, "synced_at": "..." }
```
### Test connections
```
POST /api/v1/settings/test-woo
→ 200 { "ok": true, "detail": "Connected to Whidbey Wood Store" }
POST /api/v1/settings/test-inference
→ 200 { "ok": true, "vision_capable": true, "detail": "Model Qwen3.8-27B confirmed" }
```
---
## Versioning
URL is `/api/v1`. Breaking changes bump to `/api/v2`. The SvelteKit client pins the version it was built against.
## Out of contract (v1)
- Bulk endpoints, staff/role endpoints, webhook push, analytics.
+74
View File
@@ -0,0 +1,74 @@
# Product requirements
SlabUploader creates one WooCommerce listing per wood slab for Whidbey Wood Store.
Each slab is one unit and one listing. Photos and metadata are the inventory record.
Photographs are taken of the slab on a green or black sheet. That is the capture starting state.
## Complete listing
- Inventory photo(s), uniform 3:4 transparent PNG
- SKU, length, thickness, price
- Species, wood category, edge type, figure, grade
- Thickness band, moisture
- One or more `fig-*` tags
- Title, short title, description
- Zero or more `feat-*` tags
Store categories, attributes, and `fig-*` / `feat-*` tags are the filters. Measured values feed title and description templates.
## Decision rights
| Field | Source |
|---|---|
| Length, thickness | User |
| SKU | User |
| Mask and crop | App proposal, user approve |
| Widths, sqft, bdft | App, from approved reference photo + length + thickness |
| Species, wood category, edge, figure, grade, tags | App may propose; user may change |
| Price | App proposal `bdft × species $/bdft`; user may replace |
| Title, short title, description | Templates from listing facts; user may edit |
## System seams
Milestone 1 runs in the browser. No backend and no inference URL.
Handoff is the device draft: source photo, approved mask, inventory PNG, length, thickness, widths, sqft, bdft.
Milestone 3 uses FastAPI as the Woo client. Store credentials stay on the server.
## Create
`SLAB-UAT-*` creates as a WooCommerce draft (store status).
Duplicate SKU blocks create.
A listing can be created with inference off.
A device draft in the app is separate from a WooCommerce draft.
## Milestones
Work is split into four milestones. Each milestone is done when its acceptance can be demonstrated.
### Milestone 1 — Capture
Spec: `docs/CAPTURE.md`. Current work.
User stories:
- Photograph a slab on a green or black sheet and remove the background.
- Set length from the bounding rectangle and get widths, sqft, and bdft.
- Leave and later Continue or Start fresh.
Acceptance: inventory PNG and measurements visible on a phone. No Woo create.
### Milestone 2 — Review
Remaining listing fields in the app.
Acceptance: every field in Complete listing is filled or proposed and editable.
### Milestone 3 — Create
WooCommerce draft for a practice SKU. Then clear the device draft.
Acceptance: `SLAB-UAT-*` exists in the store as draft.
### Milestone 4 — Assist
Optional vision and generated copy on the manual path from Milestones 1–3.
Acceptance: create still works with inference off.
-201
View File
@@ -1,201 +0,0 @@
# Inference Prompts
Status: SPEC · 2026-08-27 · SlabUploader
Prompts are server-side text files, not settings values. Read fresh on each
invocation. Shipped defaults live in `backend/app/prompts/`.
## Management
- **Location:** `/app/prompts/` inside the FastAPI container, mounted read-only
from host `backend/app/prompts/`.
- **Editing:** Edit the text files on the host. No server restart needed.
- **Versioning:** The inference_log stores the prompt content (or hash) with each
inference call, so you can trace which prompt version produced which result.
- **Reset-to-default:** `python -m app.prompts.reset` restores shipped defaults
from `backend/app/prompts/`.
## Call 1 — Vision (species/character classification)
File: `/app/prompts/call1.txt`
### Purpose
Classify the slab's species, edge type, figure, and grade by analyzing
inventory photos. Constrained to choose from the synced Woo taxonomy lists.
### Inputs assembled by the server
- 1–5 inventory photos, downscaled to 1024px max
- Species leaf categories from Woo (list with IDs and brief definitions)
- Edge Type attribute terms with IDs
- Figure attribute terms with IDs
- Grade attribute terms with IDs
- User metadata: SKU, length, thickness
### System prompt (template)
```
You are an expert wood slab classifier. Analyze the provided slab photos and
return taxonomy data. Only use the values provided in the taxonomy lists — do
not invent categories or attribute values.
```
### User prompt (assembled at runtime)
```
Analyze the following wood slab photos and classify the species, edge type,
figure, and grade.
Species options (choose ONLY from this list):
1. [species name] — [brief definition] (woo_id: <id>)
2. ...
Edge Type options:
- Live Edge — natural, uncut bark edge
- Flat Sawn — squared, milled edges
...
Figure options:
- Cathedral — U-shaped grain patterns
- Burl — swirling, knotted grain
...
Grade options:
- Premium — minimal defects, clean grain
- Standard — some minor characteristics
...
Slab metadata: SKU={sku}, Length={length}in, Thickness={thickness}in
Return valid JSON matching this schema:
{
"species_id": <woo_id or null>,
"species_confidence": 0.0-1.0,
"wood_category_ids": [<woo_id>, ...],
"edge_type_term_id": <woo_id or null>,
"figure_term_ids": [<woo_id>, ...],
"figure_confidence": 0.0-1.0,
"grade_term_ids": [<woo_id>, ...],
"grade_confidence": 0.0-1.0,
"character": { "type": "string", "severity": "string" },
"inclusions": { "type": "string", "severity": "string" },
"voids": "string",
"checks": "string",
"wood_categories": [
{ "name": "string", "confidence": 0.0-1.0 },
...
]
}
```
### Notes
- The taxonomy list (species, wood categories, edge type, figure, grade) is
pulled from the **synced Woo cache only**. No hardcoded mill species list. A term
not in the cache cannot be suggested or selected.
- Brief definitions help the model distinguish ambiguous cases
(e.g., "quarter-sawn" vs "cathedral").
- Character/inclusions/voids/checks are free-text observations. The server
maps them to Woo `feat-*` product tags after the call returns. WooCommerce
is the authoritative source for feat-* tag definitions; the design does not
duplicate them.
- **Pre-population (when `inference_enabled`):** Call 1 results are the primary
source that fills the review screen for species, wood categories, edge type,
figure, grade, and mapped `feat-*` tags from free-text observations.
- **Confidence gate (default threshold 0.7):**
- Field confidence **≥ threshold** → pre-populate that field (mutable;
user may clear or change it).
- Field confidence **< threshold** → leave empty. The model's
low-confidence guess as a default.
- Call 1 does not define the ready gate. Species + figure (or any vision
subset) is assist/prefill only. Ready is the **full named set** in AGENTS §7
/ DATA-MODEL (filled manually if Call 1 left fields empty). Species + one
figure is not enough.
- Manual entry always wins. Call 1 is assist-only and does not gate publish.
Full suite must pass with inference OFF. Canonical lock: AGENTS §6–7.
---
## Call 2 — Content (description prose)
File: `/app/prompts/call2.txt`
### Purpose
Generate compelling product description prose for the slab. The model writes
only the descriptive portion — dimensions, species, and measurements are
injected by deterministic templates.
### Inputs assembled by the server
- Portable Call 1 context (default: **full history resend** of Call 1 turn +
images metadata + assistant JSON). `previous_response_id` only if
`test-inference` recorded stateful support.
- Explicit **confirmed vs inferred** labels for species, dimensions, and other
attributes (user overrides marked confirmed).
- Deterministic measurements: length, widths, sqft, bdft, thickness (never invented)
- Brand voice, GEO context, title/short templates
- Shared validation module rules so Call 2 assembly rejects the same invalid
values the UI would
### System prompt (template)
```
You are a professional product copywriter for premium, one-of-a-one wood
slabs. Write compelling, natural-sounding descriptions. Use the brand voice
provided. Measurements are not invented; only the provided data is used.
```
### User prompt (assembled at runtime)
```
Write product copy for this wood slab.
Species: {species}
Figure: {figure}
Character: {character description from Call 1}
Length: {length_ft}ft {length_in_remainder}in
Average width: {width_avg_in}in
Width range: {width_min_in}in to {width_max_in}in
Thickness: {thickness_in}in
Board feet: {bdft} bdft
Grade: {grade}
Brand voice: {brand_voice}
GEO context: {geo_context}
Write:
1. A compelling opening sentence about the slab
2. A paragraph describing the character, grain, color, and use cases
3. A call to action
Keep the tone appropriate for a premium lumber buyer. The
dimensions — those are handled by the template. Focus on the beauty and
versatility of the slab.
Return JSON: { "prose": "..." }
```
### Template assembly (server-side, after LLM returns)
The server assembles the final title and description from templates with
deterministic measurements, inserting the LLM prose where appropriate.
Example title: `{species} {length_ft}ft {length_in_remainder}in × {width_avg_in}in Wood Slab — {figure}`
Example description: `{llm_prose}. Each slab is naturally shaped — width varies
along the length at {width_min_in}in to {width_max_in}in. Sold by the slab;
dimensions as measured. {geo_sentence}`
### Notes
- The LLM never touches dimensions. Templates handle all numbers.
- No numeric-accuracy guardrail needed — dimensions never pass through the LLM.
- If `content_llm_enabled` is false, the LLM call is skipped and templates
are used with a generic description paragraph.
- **Portable Call 1 context (issue #2):** default is full resend of Call 1 (user
prompt + assistant JSON). Label each taxonomy value **confirmed** (user-edited)
vs **inferred** (still from Call 1). Stateful `previous_response_id` is opt-in
after `test-inference`. Fail closed if neither path works.
---
## Tuning workflow
1. Deploy the default prompts
2. Capture a real slab, let Call 1 run
3. Review the results against your expert judgment
4. Edit `call1.txt` to improve classification accuracy
5. Re-run Call 1 via `POST /api/v1/slabs/{id}/infer-taxon` to compare
6. Iterate until results are consistently accurate
The inference_log stores each iteration's input/output so you can track
progress across prompt versions.
-253
View File
@@ -1,253 +0,0 @@
# Technical Spec: Deterministic Image Pipeline & Area → Bdft
Status: SPEC · 2026-08-27 · Gate A freeze 2026-08-31 · TyTech / SlabUploader
Scope: algorithms and test vectors for the deterministic core (client-authoritative).
No inference, no LLM. Everything here is a pure function of (pixels, user inputs) → outputs.
Inference, Woo payload, API, and schema live in other docs.
---
## 1. Invariants
1. **Determinism** — same inputs → bit-identical outputs. No randomness, no timestamps in math, no network calls for the math.
2. **Manual entry is authoritative** — user-entered length, thickness, SKU, and price always win over any computed value.
3. **Fallback chain is explicit** — every computed value has a defined fallback; the system never silently guesses.
- BG removal: chroma-key / threshold → four knobs (sheet, sensitivity, edge offset, feather) live on capture → retake. U2Net last-resort is deferred from POC; the contract stays in the architecture.
- Length axis: min-area bounding rect → user rotate/confirm → retake if the photo is unusable.
- Area: requires a single contiguous slab mask; broken mask → flag and retake.
4. **Units** — inches in 1/8" steps; sqft and bdft to 2 decimals; price half-up to 2 decimals. Those rounded values are what get stored. No sqin in the UI, tests, or product copy.
5. **Client is authoritative** — all deterministic processing runs in the browser. The server stores the numbers and files the client sends, and handles Woo sync.
## 1b. Browser compatibility floor
Client processing runs in the browser on phones and PCs. Ty lock 2026-09-06 PT: the
compatibility matrix includes PC browsers; this is not a mobile-only app.
Supported families:
- Phone: iOS Safari, Android Chrome
- PC: desktop Chrome, desktop Edge, desktop Firefox (Windows and macOS at minimum)
Exact minimum version pins remain issue #4. Unsupported clients get a hard-stop message with an
update / switch link. No polyfill strategy in POC.
Load-bearing client APIs for the deterministic path include canvas (or OffscreenCanvas where used)
for mask overlay and knob re-run, image decode/crop/encode for 3:4 transparent PNG prep, and
standard fetch to the app API. Only APIs listed here are used; update this section before adding new ones.
## 2. Units and rounding
| Quantity | Source | Stored / displayed |
|---|---|---|
| Length | user, 1/8" steps | nearest 1/8" |
| Thickness | user pick, 1/8" steps | that pick (used in math and copy) |
| Thickness Woo attribute | same pick, rounded **up** into a Woo range | Woo term, not the 1/8" value |
| sqft | computed from mask | 2 decimals |
| bdft | sqft × thickness (inches) | 2 decimals |
| Price | species $/bdft × bdft, or override | 2 decimals, half-up |
- bdft is never rounded up to whole board feet.
- Pixel→inch scale is an implementation detail. Users never see pixels.
## 3. Background removal (load-bearing)
Background removal is the **load-bearing phase** of the image pipeline. The mask
defines the slab's pixel footprint. Length axis, 6" width samples, sqft, and bdft
all derive from that footprint. A clipped or over-inclusive mask silently shifts
the bounding rectangle and width samples with no later numeric check to catch it.
The user's eye on the overlay is the only validator. There is no confidence score
and no auto-gate on mask quality.
### 3.1 Auto-detect sheet
1. Sample a 2–5% strip on all four borders.
2. Average HSV per side.
3. Hue in [35, 85] and saturation ≥ 40 → green.
4. Else value ≤ 30 and saturation ≤ 20 → black.
5. Else prompt: pick green or black.
### 3.2 Visual feedback (required)
- Overlay the mask on the **source photo** (included vs excluded pixels), not only
a cropped result.
- Show the slab edge clearly. That edge is the measurement boundary.
- User confirms the edge before length / area run.
### 3.3 Capture knobs (inline, live, persisted)
Factory values live in code. If the user changes them, the new values persist in
localStorage until reset-to-default.
All four knobs are **on the capture screen next to the overlay**, not behind a
Settings navigation. Changing any knob **immediately re-runs** §3.4 on the current
photo and refreshes the overlay on the source image. No apply/save step. No server
round trip for mask tuning in POC.
1. **Sheet** — auto / green / black.
2. **Sensitivity** — one slider; tighter vs looser detection (green: HSV range width; black: brightness cutoff).
3. **Edge offset** — pull the mask in or out a few pixels so the cut sits on the wood, not in the sheet or into the grain.
4. **Feather** — hard cut vs a couple of pixels of alpha blend.
### 3.4 Algorithms
- **Green:** chroma-key in HSV. Border flood-fill so only sheet pixels connected to the image edge are removed (protects green-ish grain inside the slab).
- **Black:** grayscale threshold. Same flood-fill (protects dark grain).
- **POC path:** client-side only (sheet detect + four knobs). If the edge is still
wrong after tuning, **retake**.
- **Post-POC fallback (deferred, contract preserved):** U2Net matting on one photo via
FastAPI. Mask returns; knobs still apply on the client. The U2Net control is not
shipped in Gate C / first listing. The contract stays in the architecture for post-POC.
- Morphological close, then feather per the setting.
### 3.5 Edge quality
- The mask must be one contiguous slab contour.
- If the user cannot get a clean edge with knobs, retake is the POC resolution.
## 4. Length axis, widths, sqft, bdft
### 4.1 Contour and length axis
1. Binary mask M from §3.
2. Largest contour → convex hull.
3. Minimum-area bounding rectangle on the hull.
4. Long side = length axis; short side = width axis.
This follows the **prevailing** length, not a diagonal cut on one end.
### 4.2 Visual feedback (required)
- Overlay the bounding rectangle and the length axis.
- Width sample lines drawn perpendicular to that axis.
- User confirms the axis matches the slab’s prevailing length.
- **Rotate axis** if it is skewed; samples and sqft scale update live.
- Nearly square slabs: user says which axis is length.
### 4.3 Scale
User length L (inches, 1/8") is authoritative.
```
scale = longest_axis_px / L
```
### 4.4 Widths (listing only, not bdft)
- Sample every **6"** along the confirmed length axis, perpendicular to it.
- Report min, max, and average width for the description.
- Auto-dimension overlay on the photo is **v1.5**, out of this spec.
### 4.5 sqft
Projected top-down area of the mask. Live-edge thickness and the underside are not in the area.
```
sqft = (mask_pixel_count / scale²) / 144
```
Round to 2 decimals.
### 4.6 bdft
```
bdft = sqft × thickness_in
```
Round to 2 decimals. Identity: 1 sqft at 1" thick = 1 bdft.
## 5. Photo normalization
Applies to every inventory photo of the slab (first photo and the rest).
- Crop aspect: **3:4 portrait** (default; matches the WooCommerce template;
configurable in settings).
- Transparent **PNG only**.
- Slab centered. **80% fill at the extremes** (widest and tallest points of the slab). Extra margin where the slab is narrower.
- After crop, if the source has enough pixels, shorter side ≥ **1600 px**. If it cannot, warn and ask for a retake. The source must supply enough pixels.
- Original + processed kept while draft/retry; both purged after successful publish (server storage; see Data Model).
## 6. Pricing
- Settings: sync **species** from Woo; user sets **$/bdft per species**.
- Capture: `recommendation = bdft × species.price_per_bdft`, pre-fills price.
- User may override. Override sticks for that slab.
- No rule for that species → empty price; user types it. Publish still allowed.
- Stored price: half-up to 2 decimals.
- Figure- or category-weighted price is **v1.5**.
## 7. Constants
### 7.1 Code (not in Settings)
```
FILL_TARGET = 0.80
ASPECT_W, ASPECT_H = 3, 4
OUTPUT_PX_MIN = 1600
WIDTH_SAMPLE_IN = 6
INCH_STEP = 0.125
AREA_DECIMALS = 2
BDFT_DECIMALS = 2
PRICE_DECIMALS = 2
```
### 7.2 Factory defaults for persisted BG settings
```
SHEET = auto
GREEN_HUE_LO/HI = 35, 85
GREEN_SAT_MIN = 40
GREEN_VAL_MIN = 40
BLACK_THRESH = 30
```
Sensitivity, edge offset, and feather map onto these at runtime. Users interact with the knobs, not the raw HSV numbers.
## 8. Test vectors
Users think in inches, sqft, and bdft. Pixels are only how the computer gets there.
### TV-1 Green sheet
Synthetic: green border, wood in the center. Interior green-ish patch that does not touch the border stays. Coverage enough that U2Net does not run.
### TV-2 Black sheet
Same layout, black border, mid-tone wood. Dark interior wood that does not touch the border stays.
### TV-3 Scale, sqft, bdft
Slab **96" long**, **1.5" thick**. Mask measures **0.64 sqft**.
bdft = 0.64 × 1.5 = **0.96**.
### TV-4 Width samples
96" length axis, stations every 6". Widths perpendicular to the confirmed axis. Listing gets min, max, avg.
### TV-5 Angled end
One square end, one 45° cut. Length axis follows prevailing length, not the diagonal. Widths stay perpendicular after user confirm.
### TV-6 3:4 crop, 80% at extremes
Slab centered in a 3:4 frame. At the widest and tallest points, fill = 0.80. PNG with alpha. Shorter side ≥ 1600 when the source allows.
### TV-7 Too-small source
After 80% crop, shorter side would be below 1600 and the source cannot supply it. Warn; no upscaling from nothing. That photo is not publishable until retake.
### TV-8 Pricing
bdft 0.96, species $12.50/bdft → rec **12.00**.
Override **150.00** stored as 150.00.
No rule → rec empty; manual 99.99 stored as 99.99.
### TV-9 Thickness → Woo range
User pick **1"** stored as 1". Attribute bucket is the Woo range that 1" rounds **up** into (e.g. `1"–1 1/2"`). Exact range labels come from the synced Woo attribute, not this file.
### TV-10 Rounding
Length 96.04" → **96"** (nearest 1/8").
sqft 0.641 → **0.64**.
bdft 11.525 → **11.53**.
Price 12.345 → **12.35**.
## 9. Assumptions
1. The first photo is top-down, lens parallel to the broad face. Tilted shots make sqft/bdft wrong; retake is the fix.
2. User length is the prevailing length of that face, in 1/8". The bounding-box axis is confirmed in the UI.
3. Thickness is the declared 1/8" pick, not measured from any photo.
4. sqft is the projected top-down area of the mask. Live-edge thickness and underside are not in the area.
5. bdft = sqft × thickness (inches). Not rounded up to whole board feet.
6. Sheet is uniform green or black. Odd colors → user picks sheet mode or retakes.
7. 3:4 portrait is the PIP crop, configurable in settings.
8. Client does all of this math. Server stores the numbers the client sends.
## 10. Cross-reference to other docs
| Topic | Depth doc(s) |
|---|---|
| Call 1 / Call 2 prompts, taxonomy mapping | PROMPTS, CONTENT-WOO |
| Portable Call 1→Call 2 context (full resend default) | ARCHITECTURE §9, PROMPTS |
| Woo payload, publish, 409/422 recovery | CONTENT-WOO, OPENAPI |
| SQLite tables, status machine | DATA-MODEL |
| HTTP contract, taxonomy `taxonomy_anchor` | OPENAPI |
| Client vs server topology, validation module | ARCHITECTURE |
| Auto-dimension overlay, figure-weighted price | IMPL-PLAN (v1.5) |
| Online-only capture (offline deferred) | AGENTS §2, ARCHITECTURE §4 |
-441
View File
@@ -1,441 +0,0 @@
# TEST-SPEC — Engineer Test Specification
Status: SPEC · engineer bar · SoT gitea-atd main · 2026-09-07
This document defines every affirmative test case for the SlabUploader, from Phase 0 through production. Each case states **what must happen**, **where the rule lives**, and **how it is verified**. The human walkable practice script is at `docs/UAT-PRACTICE.md` and is left untouched by this file.
---
## 1. Case ID naming convention
Case IDs follow the pattern `<prefix>-<number>`. The prefix identifies the test layer or gate:
| Prefix | Meaning | Examples |
|---|---|---|
| `TV` | Test Vector from `docs/TECH-SPEC-PIPELINE.md` §8 | `TV-1`, `TV-10` |
| `V` | Validation rule (shared validation module) | `V-1`, `V-3` |
| `AES` | AES-GCM encryption / decryption | `AES-1`, `AES-2` |
| `H` | Health endpoint | `H-1` |
| `D` | Draft store (slab creation / persistence) | `D-1` |
| `GC` | Gate C case (early Phase 1, claimable draft listing) | `GC-1`, `GC-5` |
| `W` | WooCommerce mock integration | `W-1`, `W-5` |
| `INF` | Inference endpoint probe / toggle | `INF-1`, `INF-4` |
| `UI` | UI behavior (capture, knobs, overlay, ready gates) | `UI-1`, `UI-5` |
| `UIE` | UI end-to-end (review, publish, settings, full flow) | `UIE-1`, `UIE-10` |
| `API` | API contract (routes, concurrency, error responses) | `API-1`, `API-10` |
| `TAX` | Taxonomy sync / anchor / species cache | `TAX-1`, `TAX-3` |
| `C1` | Call 1 (vision) inference call | `C1-1`, `C1-3` |
| `C2` | Call 2 (content/text) inference call | `C2-1`, `C2-4` |
| `OFF` | Inference OFF path (full suite without inference) | `OFF-1`, `OFF-2` |
| `OPS` | Operations / deployment / backup | `OPS-1`, `OPS-5` |
| `INS` | Instrumentation / observability | `INS-1`, `INS-4` |
| `E2E` | End-to-end browser test (full user flow) | `E2E-1`, `E2E-5` |
| `FUND` | Fundamentals (cross-cutting dependency bar) | `FUND-1`, `FUND-25` |
Other abbreviations used in this document:
- **sqft**: square feet
- **bdft**: board feet
- **U2Net**: Universal 2 Network, a background-removal model (deferred from the proof of concept)
- **API**: application programming interface
- **E2E**: end-to-end
- **UI**: user interface
- **POC**: proof of concept
- **SKU**: stock keeping unit
- **Woo**: WooCommerce, the WordPress e-commerce plugin
- **HTTP/HTTPS**: Hypertext Transfer Protocol (plain / secure)
- **AES-GCM**: Advanced Encryption Standard in Galois/Counter Mode
- **UUID**: universally unique identifier
- **JSON**: JavaScript Object Notation
- **LLM**: large language model
---
## 2. How cases are executed
Test automation lives in the repo under `backend/tests/` and `frontend/e2e/`. The harness uses:
- **Unit tests**: `backend/tests/unit/` (pytest) and `frontend/src/__tests__/` (Vitest). These run against pure modules with no network calls.
- **API contract tests**: `backend/tests/contract/` (pytest + `httpx` TestClient). These hit the FastAPI app through its test client, asserting request/response shape, status codes, and revision handling.
- **Integration tests**: `backend/tests/integration/` (pytest + `httpx` TestClient + `respx` WooCommerce mock). These verify Woo create, duplicate SKU, taxonomy sync, stale-field recovery, and settings encryption round-trips without touching a real store.
- **UI end-to-end tests**: `frontend/e2e/` (Playwright). These exercise the full browser flow: capture, mask knobs, axis confirm, numbers entry, review, and publish. They run against a started Docker Compose stack with the FastAPI test server and mocked Woo endpoints.
- **Ops / deployment tests**: `deploy/tests/` (shell scripts). These verify compose health, backup/restore, and Caddy routing.
Test dependencies are pinned in `backend/tests/requirements-test.txt` and `frontend/package.json` (devDependencies). CI runs the full suite before any merge; the suite must pass with inference disabled.
---
## Results recording & report-out
Every report maps to named case IDs from this spec. Allowed results only: `pass`, `fail`, `not run`, and optionally `blocked` with a blocker pointer. Never invent pass.
Evidence is required for every `pass` or `fail`: a path or paste of real runner output (pytest, httpx, compose logs, curl). No evidence → `not run`. Report table columns are: case id · result · evidence pointer · blocker (if fail).
Gitea issues are the only mechanism for reporting issues found during a test pass. Chat, Slack, and PR comments are not the bug log. On fail, open or update a Gitea issue that includes the case id and evidence pointer; the report table's blocker column links that issue. Do not invent issues that lack runner evidence.
The Test Bar may only summarize what runners printed. Ty also reads raw results and owns gate exit. Gate or phase exit evidence in the Gates section still requires Ty confirmation where IMPL-PLAN mandates it — bots never declare Gate B or Gate C green.
When code does not exist yet, Phase 0 and earlier cases stay `not run`. Do not speculate.
---
## 3. Test pyramid overview
Each row states the test layer, when tests in that layer are written, and what document drives the expected behavior.
| Layer | When written | Primary source of truth |
|---|---|---|
| Unit | TDD: unit tests written before the feature code exists | `docs/TECH-SPEC-PIPELINE.md`, `docs/AGENTS.md` |
| API / contract | Alongside the backend feature code | `docs/OPENAPI.md`, `docs/DATA-MODEL.md` |
| Integration | Alongside the backend feature code | `docs/CONTENT-WOO.md`, `docs/ARCHITECTURE.md` |
| UI / E2E | Alongside the frontend feature code | `docs/UX.md`, `docs/TECH-SPEC-PIPELINE.md` |
| Ops / deployment | Alongside deployment configuration | `docs/DEPLOYMENT.md`, `docs/IMPL-PLAN.md` Phase 6 |
**Test-driven development (TDD)**: write the failing unit test first, then write the minimum code to pass it. This applies to all deterministic core functions: bdft math, pricing, rounding, image crop, and validation rules.
**Tests-with-code**: API contract tests, integration tests, and UI end-to-end tests are written in the same commit that implements the feature. Each feature commit includes its tests and shown execution output in the commit message.
---
## 4. Fundamentals — cross-cutting bar
These cases are the white-box bar for every dependency that touches the product. They run across all phases.
### SvelteKit / Vitest (frontend/src/__tests__/)
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| FUND-1 | Pure logic tests have zero browser, DOM, or network dependencies | SvelteKit/Vitest convention | Vitest unit test: `vi.mock` any runtime import, assert no browser globals |
| FUND-2 | Component/browser tests use semantic `getByRole` selectors; class or data-testid alone is not sufficient | SvelteKit testing-library convention | Vitest component test: assert role-based query succeeds |
| FUND-3 | Real Tab key navigates focus; click-only tests are not sufficient for keyboard paths | UX.md §Browser compatibility | Playwright E2E: `page.keyboard.press('Tab')` followed by `toBeFocused` |
| FUND-4 | Shared rune/state changes flush before DOM assertion; stale store values do not pass | Svelte rune reactivity | Vitest component test: flush/store tick before `expect` |
### Playwright (frontend/e2e/)
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| FUND-5 | Tab order: press Tab, assert `toBeFocused` after each stop; no keyboard trap | Playwright convention; UX.md §Browser compatibility | Playwright E2E: sequential `keyboard.press('Tab')` + `toBeFocused` |
| FUND-6 | Viewport resize/reflow at ~320 px and phone/PC sizes: layout does not clip, overlap, or trap content | UX.md §Browser compatibility | Playwright E2E: `setViewportSize` then assert no clip/overlap |
| FUND-7 | Focus ring visible on touch and keyboard; focus ring is not hidden by `outline: none` on interactive elements | Playwright convention; WCAG 2.4.7 | Playwright E2E: assert focus ring CSS present on focused interactive element |
### FastAPI / pytest TestClient (backend/tests/)
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| FUND-8 | App factory pattern creates a fresh app instance per test; no shared mutable state between tests | FastAPI testing convention | pytest TestClient: each test calls the factory, not a module-level app |
| FUND-9 | `with TestClient(app)` manages lifespan; startup and shutdown hooks run and clean up | FastAPI testing convention | pytest TestClient: context manager exits with clean lifespan |
| FUND-10 | Clear `dependency_overrides` after every test; no override bleeds to the next test | FastAPI testing convention | pytest TestClient: assert `dependency_overrides` empty after each test |
| FUND-11 | Override Woo/inference dependencies with mocks; no real network call leaks | FastAPI testing convention | pytest TestClient: assert zero HTTP calls to real Woo/inference endpoints |
### SQLite + Alembic (backend/tests/)
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| FUND-12 | `PRAGMA foreign_keys=ON` enforced in every test database; FK violation rejected | SQLite testing convention; DATA-MODEL.md | pytest + SQLite: insert orphan row, assert IntegrityError |
| FUND-13 | Unique and check constraints enforced; duplicate or out-of-range values rejected | SQLite testing convention; DATA-MODEL.md | pytest + SQLite: insert violating row, assert IntegrityError |
| FUND-14 | Concurrent poll / WAL stale-read risk handled; WAL mode with proper isolation level prevents stale reads | SQLite WAL convention; DATA-MODEL.md | pytest + SQLite: concurrent reader/writer, assert no stale read |
| FUND-15 | Illegal status transitions rejected by the application layer; status machine enforced | AGENTS.md §7; DATA-MODEL.md slabs | pytest TestClient: attempt illegal transition, assert 422 |
| FUND-16 | Migrations must not silently drop integrity indexes or constraints; post-migration assertions verify schema integrity | Alembic convention; DATA-MODEL.md | pytest + SQLite: run migration, assert indexes/constraints preserved |
### AES-GCM (settings)
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| FUND-17 | Fresh nonce per encrypt; tampered ciphertext or wrong key/nonce raises authentication failure | AES-GCM specification; AGENTS.md §4 | Unit test: tamper ciphertext, assert auth failure; encrypt twice, assert nonces differ |
| FUND-18 | Ciphertext never appears in any GET response; only the configured username and `woo_credentials_configured` boolean returned | OPENAPI.md §settings; DATA-MODEL.md settings | API contract test: assert `woo_app_password` absent from GET /api/v1/settings |
| FUND-19 | Missing `SLAB_AES_KEY` refuses startup; no fallback to plaintext storage | AGENTS.md §4; DATA-MODEL.md settings | Unit test: unset env var, assert startup rejection |
### Woo REST client (httpx + App Passwords over HTTPS)
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| FUND-20 | Basic Auth with App Passwords over HTTPS; consumer keys not implemented | AGENTS.md §4; DEPLOYMENT.md §3; OPENAPI.md §settings | Unit test: assert HTTP Basic header, HTTPS-only URL |
| FUND-21 | 401/400/404 response shapes handled; server maps to actionable error, not raw passthrough | Woo REST convention; CONTENT-WOO.md §2.6 | Integration test with respx: mock 401/400/404, assert mapped error response |
| FUND-22 | Pre-create SKU lookup mandatory; Woo concurrent duplicate-SKU race handled by checking before create | AGENTS.md §5; CONTENT-WOO.md §2.5 | Integration test with respx: create duplicate SKU, assert 409 before create |
| FUND-23 | Timeouts and network errors handled gracefully; server returns actionable error, not stack trace | Woo REST convention; CONTENT-WOO.md §2.6 | Integration test with respx: mock timeout/connection error, assert graceful error |
| FUND-24 | Secrets redacted in logs; no Woo username/password, inference key, or AES key in any log output | AGENTS.md §4; ARCHITECTURE.md §5 | Unit test: assert log output contains no secret material |
### Compose / Caddy (deploy/tests/)
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| FUND-25 | HTTPS-only `WOO_BASE_URL`; health through proxy; inventory/port collision checked at deploy time | DEPLOYMENT.md §3; AGENTS.md §9 | Shell script: assert HTTPS, health through Caddy, port conflict detection |
---
## Phase 0 / Gate B — Hybrid skeleton + deterministic core
**Exit evidence**: Ty confirms TV-3, TV-6, TV-7, and TV-10 output on real fixtures; health returns 200; AES round-trip passes; draft store stub persists and retrieves; unit and API cases automated.
### Unit — deterministic core (test-driven)
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| TV-1 | Green-sheet synthetic photo: interior green-ish patch that does not touch the border stays after chroma-key; U2Net is not invoked | `docs/TECH-SPEC-PIPELINE.md` §3.1, §3.4 | Unit test with synthetic image fixture |
| TV-2 | Black-sheet synthetic photo: dark interior wood that does not touch the border stays after threshold; flood-fill isolates border-connected pixels only | `docs/TECH-SPEC-PIPELINE.md` §3.1, §3.4 | Unit test with synthetic image fixture |
| TV-3 | Slab 96" long, 1.5" thick, mask 0.64 square feet → bdft = 0.96. Identity: 1 square foot at 1" thick equals 1 bdft. No divide-by-12. | `docs/TECH-SPEC-PIPELINE.md` §4.6 | Unit test, shown output on real fixtures |
| TV-4 | Width samples at 6" stations on a 96" length axis report min, max, and average perpendicular to the confirmed axis | `docs/TECH-SPEC-PIPELINE.md` §4.4 | Unit test with fixture mask |
| TV-5 | Slab with one square end and one 45° cut: length axis follows prevailing length; widths stay perpendicular after user confirm | `docs/TECH-SPEC-PIPELINE.md` §4.1, §4.2 | Unit test with angled-end fixture |
| TV-6 | 3:4 crop, slab centered, 80 percent fill at extremes, transparent PNG, shorter side ≥ 1600 when source allows | `docs/TECH-SPEC-PIPELINE.md` §5, §7.1 | Unit test, shown output on real fixtures |
| TV-7 | Undersized source: after 80 percent crop shorter side would be below 1600 and source cannot supply it → warn, no upscaling, photo not publishable until retake | `docs/TECH-SPEC-PIPELINE.md` §5, §7.1 | Unit test, shown output on real fixtures |
| TV-8 | Pricing: bdft 0.96, species $12.50/bdft → recommended price 12.00; override 150.00 stored as 150.00; no rule → recommended price empty, manual 99.99 stored | `docs/TECH-SPEC-PIPELINE.md` §6, §8 TV-8 | Unit test with pricing rules |
| TV-9 | Thickness 1" → Woo range rounds up (for example 1"–1 1/2") using synced attribute term, not a hardcoded label | `docs/TECH-SPEC-PIPELINE.md` §8 TV-9, `docs/DATA-MODEL.md` slabs | Unit test with mock taxonomy |
| TV-10 | Rounding: 96.04" → 96"; square feet 0.641 → 0.64; bdft 11.525 → 11.53; price 12.345 → 12.35. Half-up to 2 decimals. | `docs/TECH-SPEC-PIPELINE.md` §8 TV-10 | Unit test, shown output on real fixtures |
### Unit — shared validation
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| V-1 | SKU charset `[A-Z0-9-]{3,24}` accepted; values outside the charset rejected | `docs/TECH-SPEC-PIPELINE.md` §2, issue #17 | Unit test with valid and invalid SKU strings |
| V-2 | Title, short title, description: UTF-8 within WooCommerce maxLength enforced at field exit and at submit | `docs/TECH-SPEC-PIPELINE.md` §2, issue #17 | Unit test with boundary-length strings |
| V-3 | Validation module version hash: client caches module; submit carries hash; mismatch returns 412 with fresh module, not 409 | `docs/OPENAPI.md` §validation, issue #17 | Unit test of validation module hash comparison |
### Unit — AES-GCM settings
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| AES-1 | Encrypt then decrypt round-trips for woo_wp_username and woo_app_password; ciphertext never appears in GET settings | `docs/ARCHITECTURE.md` §5, issue #5 | Unit test with round-trip encryption |
| AES-2 | Missing SLAB_AES_KEY environment variable at startup: app refuses to start; no fallback to plaintext | `docs/AGENTS.md` §4, `docs/DATA-MODEL.md` settings | Unit test with missing env var |
### API / contract — health + draft store stub
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| H-1 | `GET /api/health` returns 200 `{ "status":"ok" }` with `woo_reachable` false when credentials are not configured | `docs/OPENAPI.md` §health, `docs/IMPL-PLAN.md` Phase 0 | API contract test via httpx TestClient |
| D-1 | `POST /api/v1/slabs` accepts multipart with data JSON + files + metadata; returns 201 with `status: calibrated` and `server_rev` | `docs/OPENAPI.md` §slabs, `docs/DATA-MODEL.md` slabs | API contract test via httpx TestClient |
---
## Gate C — Early Phase 1 (first draft listing, inference disabled)
**Exit evidence**: Ty opens one `SLAB-UAT-*` WooCommerce draft listing in the real store admin; inference OFF; mocked-store automation is not Gate C exit.
### API / contract — create + draft
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| GC-1 | `POST /api/v1/slabs` with `SLAB-UAT-*` SKU creates a WooCommerce product with `status: "draft"` regardless of the `woo_create_status` setting | `docs/AGENTS.md` §5, `docs/CONTENT-WOO.md` §2.4 | API contract test with mocked Woo |
| GC-2 | Duplicate SKU before create: `GET /products?sku={sku}` finds existing → 409 `duplicate_sku` with `{ field:"sku", actions:["edit_sku","open_existing"] }` | `docs/CONTENT-WOO.md` §2.5, `docs/OPENAPI.md` §slabs, issue #3 | API contract test with pre-existing SKU in mock |
| GC-3 | `POST /api/v1/settings/test-woo` returns ok with populated taxonomy; always resyncs taxonomy on success | `docs/OPENAPI.md` §settings, issue #14 | API contract test with mocked Woo taxonomy |
| GC-4 | `WOO_BASE_URL` is compose-only HTTPS; Settings GET returns it read-only; PUT rejects write attempts with 422 | `docs/AGENTS.md` §5, issue #11 | API contract test with PUT attempt |
| GC-5 | FastAPI refuses to start when `WOO_BASE_URL` environment variable is missing or set to `http://` | `docs/AGENTS.md` §4, `docs/DEPLOYMENT.md` §3 | Unit test for startup config validation |
### Integration — WooCommerce mock (draft create, SLAB-UAT-*, duplicate SKU, taxonomy)
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| W-1 | Woo mock returns a new product with status draft; server stores `woo_product_id` and purges images | `docs/CONTENT-WOO.md` §2.4, `docs/IMPL-PLAN.md` Phase 4 | Integration test with respx mock |
| W-2 | Woo mock returns 409 for duplicate SKU; server maps to `{ field:"sku", actions:["edit_sku","open_existing"] }`; draft retained | `docs/OPENAPI.md` §slabs, issue #3 | Integration test with respx mock returning 409 |
| W-3 | Taxonomy sync returns cached data; anchor stays unchanged on no-op sync; anchor bumps only when stored-subset hash changes | `docs/ARCHITECTURE.md` §7, issue #14 | Integration test with taxonomy mock |
| W-4 | `test-woo` always runs taxonomy resync after successful connection test | `docs/ARCHITECTURE.md` §7, issue #14 | Integration test: assert taxonomy resync call |
| W-5 | Failed publish: slab status `failed`, photos retained, sync_log written; retry from same screen without re-photographing → success → photos purged | `docs/CONTENT-WOO.md` §2.6, `docs/TECH-SPEC-PIPELINE.md` §5, `docs/DATA-MODEL.md` slabs | Integration test with retryable mock failure |
### Integration — inference disabled path + test-inference probe (issue #2 substance)
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| INF-1 | With `inference_enabled: false`: slab create skips Call 1; `inference_status` is null; full suite passes end-to-end with no inference network calls | `docs/AGENTS.md` §6, `docs/IMPL-PLAN.md` Phase 5 | Integration test asserting zero inference calls |
| INF-2 | `POST /api/v1/settings/test-inference` returns `{ ok: true, mode: "stateful", vision_capable: true }` on a stateful provider | `docs/OPENAPI.md` §settings, issue #2 | Integration test with mocked inference endpoint |
| INF-3 | `test-inference` returns `{ ok: true, mode: "stateless", vision_capable: true }` on a stateless provider; Call 2 uses full resend | `docs/OPENAPI.md` §settings, issue #2 | Integration test with mocked inference endpoint |
| INF-4 | `test-inference` returns `{ ok: false, mode: "fail" }`: Call 2 enablement blocked; Gate C path remains green with inference disabled | `docs/OPENAPI.md` §settings, issue #2 | Integration test: assert Call 2 blocked |
### UI end-to-end — capture knobs, mask, axis, ready gates (phone + PC)
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| UI-1 | Four inline knobs (sheet, sensitivity, edge offset, feather) on capture screen: changing any knob immediately re-runs mask and refreshes overlay without leaving the screen | `docs/TECH-SPEC-PIPELINE.md` §3.3, `docs/UX.md` §Capture, issue #15 | Playwright E2E test: knob change → overlay update, no navigation |
| UI-2 | Mask overlay on source photo: user confirms edge; below-threshold edge after tuning → retake; no U2Net control in the proof of concept | `docs/TECH-SPEC-PIPELINE.md` §3.2, §3.5, `docs/UX.md` §Capture | Playwright E2E test: mask overlay visible, confirm/retake paths |
| UI-3 | Length axis overlay: user rotates if skewed; samples and square feet update live; nearly-square slab: user picks length direction | `docs/TECH-SPEC-PIPELINE.md` §4.2, `docs/UX.md` §Capture | Playwright E2E test: axis rotation, live number update |
| UI-4 | Numbers entry: length 1/8" steps, thickness pick, SKU typed; computed square feet/bdft/widths displayed | `docs/TECH-SPEC-PIPELINE.md` §4, `docs/UX.md` §Capture | Playwright E2E test: type inputs, assert computed output |
| UI-5 | Ready-set gates: slab cannot reach `ready` until full named set is filled (SKU, length, thickness, square feet/bdft/widths, ≥1 PNG, species, wood category, edge, figure, grade, thickness band, moisture, price); inline nudges per empty required field, not a submit-time list | `docs/AGENTS.md` §7, `docs/UX.md` §Review, issue #9 | Playwright E2E test: attempt ready with missing fields, assert nudges |
### Ops — compose health
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| OPS-1 | `GET https://${APP_HOSTNAME}/api/health` returns ok after compose up with filled inventory | `docs/DEPLOYMENT.md` §8, `docs/IMPL-PLAN.md` Phase 0 | Shell script: compose up → curl health endpoint |
---
## Phase 1 remainder — Full API surface
**Exit evidence**: agent-written test automation drives a full calibrated to ready cycle via the API; all OPENAPI endpoints match expected responses; revision conflict handled; taxonomy anchor logic verified.
### API / contract — all routes, concurrency, secrets redaction
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| API-1 | `PUT /api/v1/slabs/{id}` updates fields with `client_rev`; server echoes new `server_rev`; mismatch returns 409 `revision_conflict` with `current_server_rev` | `docs/OPENAPI.md` §conventions, `docs/DATA-MODEL.md` slabs | API contract test with httpx TestClient |
| API-2 | `PUT /api/v1/slabs/{id}` stores client-sent derived fields (square feet, bdft, widths); server does not recompute them as source of truth | `docs/OPENAPI.md` §slabs PUT, `docs/ARCHITECTURE.md` §3 | API contract test: assert no server-side recompute |
| API-3 | `GET /api/v1/settings` returns `SettingsView` with `woo_credentials_configured` boolean; `woo_app_password` never returned | `docs/OPENAPI.md` §settings, issue #5 | API contract test: assert password absent from response |
| API-4 | `POST /api/v1/slabs/{id}/infer-taxon` returns 202 `{ status: "inferring" }`; client polls `GET /api/v1/slabs/{id}` for results; timeout greater than 45 seconds returns 504 | `docs/OPENAPI.md` §inference, issue #8 | API contract test with mocked inference |
| API-5 | `POST /api/v1/slabs/{id}/infer-content` returns 202; requires `test-inference` ok; below-threshold Call 1 (confidence below 0.7): fields stay empty | `docs/OPENAPI.md` §inference, `docs/AGENTS.md` §6, issue #8/#9 | API contract test with confidence-gated mock |
| API-6 | `POST /api/v1/slabs/{id}/publish`: pre-condition check returns 422 with field keys for missing required fields; UI maps fields, no raw code | `docs/OPENAPI.md` §publish, issue #18 | API contract test with incomplete slab |
| API-7 | `POST /api/v1/admin/taxonomy/sync`: pulls categories/attributes/tags; rebuilds cache; anchor bumps only on stored-subset hash change; 502 retains previous cache | `docs/OPENAPI.md` §taxonomy, `docs/ARCHITECTURE.md` §7, issue #14 | Integration test with taxonomy mock |
| API-8 | `GET /api/v1/validation/module` returns hash and rules; client caches; submit mismatch returns 412 with fresh module | `docs/OPENAPI.md` §validation, issue #17 | API contract test: assert 412 on stale hash |
| API-9 | `DELETE /api/v1/slabs/{id}`: soft-delete returns 204; unpublished drafts only; published slabs undeletable | `docs/OPENAPI.md` §slabs DELETE | API contract test with published slab |
| API-10 | `test-woo` fails closed: missing credentials or non-HTTPS URL returns `{ ok: false, detail: "..." }` without crashing | `docs/OPENAPI.md` §settings test-woo | API contract test with bad credentials |
### Integration — taxonomy sync + anchor
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| TAX-1 | Sync on publish when `now - taxonomy_last_sync_at > 1 hour`; bump anchor only on real change; stale picked id returns 422 with current options | `docs/ARCHITECTURE.md` §7, `docs/CONTENT-WOO.md` §2.2, issue #14 | Integration test with time-skewed sync |
| TAX-2 | Species picker offers only WooCommerce-synced species; no hardcoded fallback; new species selectable only after sync stores it | `docs/ARCHITECTURE.md` §7, issue #12 | Integration test: assert species list matches cache |
| TAX-3 | Client reads taxonomy anchor; re-pulls full taxonomy only when anchor advances past client's last value; no-per-navigation sync | `docs/ARCHITECTURE.md` §7, `docs/OPENAPI.md` §taxonomy | Integration test with anchor versioning |
---
## Phase 3 — Frontend review + publish UI
**Exit evidence**: Ty publishes a test slab to the real store as a WooCommerce draft `SLAB-UAT-*`; automation covers UI cases; Ty is the exit.
### UI end-to-end — review, field recovery, publish outcome (phone + PC)
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| UIE-1 | Review screen: all fields editable; client-computed square feet/bdft/widths shown with manual override; typed override persists across poll and refresh | `docs/IMPL-PLAN.md` Phase 3, `docs/UX.md` §Review | Playwright E2E test: edit, poll, refresh, assert persistence |
| UIE-2 | Call 1 prefill at or above 0.7 confidence: fields pre-filled and mutable; user override sticks; below 0.7 fields empty; inline nudges for every still-required control | `docs/AGENTS.md` §6, issue #8/#9, `docs/UX.md` §Review | Playwright E2E test with mocked Call 1 results |
| UIE-3 | Duplicate SKU at publish: under SKU field, "This SKU already exists in the store (any status)"; edit SKU or open existing; draft retained; no raw 409 | `docs/UX.md` §Publish, `docs/CONTENT-WOO.md` §2.5, `docs/AGENTS.md` §5, issue #3/#18 | Playwright E2E test with pre-existing SKU |
| UIE-4 | Stale field at publish: field shows "This value is no longer valid. Pick from the current list"; draft retained; no raw 422 | `docs/CONTENT-WOO.md` §2.6, issue #18 | Playwright E2E test with removed taxonomy item |
| UIE-5 | Publish success: screen shows listing created, `woo_product_id` when available; local draft and photos gone; slab status `published` | `docs/CONTENT-WOO.md` §2.6, `docs/DATA-MODEL.md` slabs | Playwright E2E test: assert published state and cleanup |
| UIE-6 | Publish failure: plain message, no status number, no stack; retry from same screen without re-photographing | `docs/CONTENT-WOO.md` §2.6, issue #18 | Playwright E2E test: assert retry path preserves state |
| UIE-7 | Inference disabled: full manual taxonomy + content path works; no inference network calls; Generate text disabled; templates still work | `docs/IMPL-PLAN.md` Phase 3, `docs/UX.md` §Review | Playwright E2E test with inference flag off |
| UIE-8 | Settings UI: WordPress username + application password + test-woo; inference endpoint + test; pricing rules; brand voice/GEO; `woo_create_status`; store URL read-only | `docs/IMPL-PLAN.md` Phase 3, `docs/OPENAPI.md` §settings, issue #11 | Playwright E2E test: settings form and test buttons |
| UIE-9 | Changing sensitivity slider immediately refreshes mask overlay without leaving screen or server round trip | `docs/TECH-SPEC-PIPELINE.md` §3.3, issue #15, `docs/UX.md` §Capture | Playwright E2E test: slider → overlay update, no HTTP call |
| UIE-10 | Changing edge offset pulls cut in/out; feather changes alpha blend; sheet switch (auto/green/black) re-runs; all persisted in localStorage until reset | `docs/TECH-SPEC-PIPELINE.md` §3.3, issue #15 | Playwright E2E test: knob changes, persist, reset |
---
## Phase 5 — Inference (after Gate C is green)
**Exit evidence**: Ty runs species detection on 3 real slabs with judgment on acceptance; automation covers Call 1/2 cases; full inference-disabled path green.
### Integration — Call 1/2, portable context, confidence gating
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| C1-1 | Call 1 sends all inventory photos at 1024px + WooCommerce taxonomy only + SKU/length/thickness; model constrained to cached taxonomy from WooCommerce cache | `docs/IMPL-PLAN.md` Phase 5, issue #12 | Integration test: inspect Call 1 request payload |
| C1-2 | Confidence at or above 0.7: species, wood categories, edge, figure, grade, feat-* pre-filled and mutable; user override wins | `docs/AGENTS.md` §6, issue #8/#9 | Integration test with high-confidence mock response |
| C1-3 | Confidence below 0.7: those fields stay empty; ready blocked until full named set is filled; species plus one figure is not the gate | `docs/AGENTS.md` §6, issue #8/#9 | Integration test with low-confidence mock response |
| C2-1 | Call 2 triggered only by user tap; portable Call 1 context: full resend default; confirmed versus inferred labels carried | `docs/ARCHITECTURE.md` §9, issue #2 | Integration test: assert no auto-trigger, full resend |
| C2-2 | Test-inference stateful mode: `previous_response_id` used when available; stateless mode: full resend; fail mode: Call 2 blocked | `docs/OPENAPI.md` §settings, issue #2 | Integration test with three probe modes |
| C2-3 | LLM does not invent dimensions; templates inject deterministic numbers into title and description | `docs/PROMPTS.md` §Call 2, `docs/AGENTS.md` §6 | Integration test: inspect Call 2 response for invented numbers |
| C2-4 | Audit: inference_log stores request_payload and response_payload per call; prompt file edits apply without restart | `docs/DATA-MODEL.md` inference_log, `docs/PROMPTS.md` §Management | Integration test: verify log entry, edit prompt file |
### UI end-to-end — inference disabled path
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| OFF-1 | Full suite (calibrated to ready to publish to success) passes with `inference_enabled: false`; zero calls to inference endpoint asserted | `docs/AGENTS.md` §6, `docs/IMPL-PLAN.md` Phase 5 | Playwright E2E test with network assertion for zero inference calls |
| OFF-2 | `test-inference` fail mode blocks Call 2 enablement only; Gate C inference-disabled path unaffected | `docs/OPENAPI.md` §settings, issue #2 | Playwright E2E test: assert Call 2 disabled, full suite passes |
---
## Phase 6 / Ops — Deployment, user acceptance, hardening
**Exit evidence**: deployment smoke automated; Ty walks `docs/UAT-PRACTICE.md` and signs off on UAT results; v1 declared done.
### Ops — compose health, deploy path, backup/restore
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| OPS-2 | INVENTORY.md filled: APP_HOST, APP_HOSTNAME, ports verified free, Caddy location confirmed, DNS reachable from phone on LAN/Tailscale | `docs/DEPLOYMENT.md` §1, `docs/IMPL-PLAN.md` Phase 6 | Shell script: port scan, Caddy check, DNS resolve |
| OPS-3 | Compose health: `GET https://${APP_HOSTNAME}/api/health` ok; `test-woo` ok with species populated; `woo_create_status=draft`; inference disabled for early gates | `docs/DEPLOYMENT.md` §8, `docs/UAT-PRACTICE.md` §1 | Shell script: curl health + test-woo endpoints |
| OPS-4 | Backup: `deploy/backup.sh` creates WAL-safe `.backup` of slab.db and tar of images volume; retention 7 daily + 4 weekly | `docs/DEPLOYMENT.md` §6 | Shell script: run backup, verify files and retention |
| OPS-5 | Restore: stop compose → restore DB + untar images → start compose → health ok; tested at least once before declaring backup done | `docs/DEPLOYMENT.md` §6, `docs/IMPL-PLAN.md` Phase 6 | Shell script: full restore cycle with health assertion |
### Ops — instrumentation (issue #6 substance)
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| INS-1 | Health non-200 on database or volume failure; `woo_reachable` false on WooCommerce unreachable | `docs/OPENAPI.md` §health, issue #6 | Unit test with simulated DB/volume failure |
| INS-2 | Request ID logged on every server request | issue #6 | Unit test: assert request ID in log output |
| INS-3 | Inference request_payload and response_payload recorded in inference_log; payloads contain model name and confidence data | `docs/DATA-MODEL.md` inference_log, issue #6 | Integration test: assert log entry after inference call |
| INS-4 | Sync_log written with payload_hash on every publish attempt; retains success and failure | `docs/DATA-MODEL.md` sync_log, issue #6 | Integration test: assert sync_log entries for success and failure |
### Ops — end-to-end on all target browsers
| Case | What must happen | Where the rule lives | Verified by |
|---|---|---|---|
| E2E-1 | Capture to mask/axis confirm to calibrated upload to review to publish to WooCommerce draft `SLAB-UAT-*` works on iOS Safari (phone) | `docs/UX.md` §Browser compatibility, `docs/IMPL-PLAN.md` Phase 6 | Playwright E2E on iOS Safari |
| E2E-2 | Same flow works on Android Chrome (phone) | `docs/UX.md` §Browser compatibility, `docs/IMPL-PLAN.md` Phase 6 | Playwright E2E on Android Chrome |
| E2E-3 | Same flow works on desktop Chrome, Edge, Firefox (PC) | `docs/UX.md` §Browser compatibility, `docs/IMPL-PLAN.md` Phase 6 | Playwright E2E on desktop browsers |
| E2E-4 | Manual length override recalculates widths/square feet/bdft correctly on all three browser families | `docs/TECH-SPEC-PIPELINE.md` §4.3, `docs/IMPL-PLAN.md` Phase 6 | Playwright E2E: override length, assert recalculation |
| E2E-5 | Client crop: slab approximately 80 percent frame; shorter side ≥ 1600 when source allows; undersized source warns and requests retake | `docs/TECH-SPEC-PIPELINE.md` §5, `docs/IMPL-PLAN.md` Phase 6 | Playwright E2E: inspect crop output dimensions |
---
## When tests are written
**Deterministic core** (TV-1 through TV-10, validation, AES): test-driven development. Unit tests written before any user interface consumes the functions. Property checks: bdft monotonic in thickness and square feet; fill band; no upscale path.
**User interface, FastAPI, WooCommerce/inference adapters**: tests-with-code. Each feature commit includes its test and shown execution output.
**Integration tests**: httpx TestClient with a respx WooCommerce mock covering success, error, duplicate, stale-field, and taxonomy-anchor paths.
**Full suite must pass with inference disabled.** Call 1/Call 2 cases are gated after Gate C is green.
bdft equals square feet times thickness in inches (no divide-by-12). TV-3 proves the identity. Gate B requires TV-3, TV-6, TV-7, and TV-10 to show output on real fixtures.
---
## Cross-reference
| These cases | Source of truth document(s) |
|---|---|
| TV-1 through TV-10 | `docs/TECH-SPEC-PIPELINE.md` §8 |
| V-1 through V-3 | `docs/TECH-SPEC-PIPELINE.md` §2, `docs/OPENAPI.md` §validation |
| AES-1 through AES-2 | `docs/ARCHITECTURE.md` §5, `docs/AGENTS.md` §4 |
| GC-1 through GC-5, W-1 through W-5 | `docs/CONTENT-WOO.md` §2.4–2.6, `docs/OPENAPI.md` §slabs/§settings, `docs/DEPLOYMENT.md` §3 |
| INF-1 through INF-4 | `docs/OPENAPI.md` §settings, `docs/AGENTS.md` §6 |
| UI-1 through UI-5 | `docs/TECH-SPEC-PIPELINE.md` §3–§4, `docs/UX.md` §Capture/§Review |
| UIE-1 through UIE-10 | `docs/UX.md` §Review/§Publish, `docs/CONTENT-WOO.md` §2.5–2.6, `docs/IMPL-PLAN.md` Phase 3 |
| C1-1 through C2-4 | `docs/AGENTS.md` §6–§7, `docs/PROMPTS.md` §Call 1/2 |
| OPS-1 through OPS-5, E2E-1 through E2E-5 | `docs/DEPLOYMENT.md` §1–§8, `docs/IMPL-PLAN.md` Phase 6 |
| INS-1 | `docs/OPENAPI.md` §health, `docs/AGENTS.md` §6 |
| INS-2 | issue #6 |
| INS-3 through INS-4 | `docs/DATA-MODEL.md` §inference_log/sync_log, `docs/AGENTS.md` §6 |
| FUND-1 through FUND-25 | `docs/AGENTS.md` §1–§9, `docs/ARCHITECTURE.md` §5, `docs/OPENAPI.md`, `docs/DATA-MODEL.md`, `docs/CONTENT-WOO.md`, `docs/DEPLOYMENT.md` |
---
## Issue #19 mapping
This spec folds affirmative case substance from issue #19 where the rule exists in a live doc. Issue #19 is not closed by this work.
| Issue #19 item | Cases | Source of truth document(s) |
|---|---|---|
| #2 portable multi-turn | INF-2, INF-3, INF-4, C2-1, C2-2 | `docs/OPENAPI.md` §settings, `docs/ARCHITECTURE.md` §9 |
| #3 duplicate SKU wording | GC-2, W-2, UIE-3 | `docs/OPENAPI.md` §slabs, `docs/CONTENT-WOO.md` §2.5 |
| #5 Application Passwords | AES-1, AES-2, API-3 | `docs/ARCHITECTURE.md` §5, `docs/DATA-MODEL.md` settings |
| #6 instrumentation | INS-1, INS-2, INS-3, INS-4 | `docs/DATA-MODEL.md` sync_log/inference_log, issue #6 |
| #8/#9 Call 1 prefill + 0.7 | UIE-2, C1-2, C1-3 | `docs/AGENTS.md` §6, `docs/PROMPTS.md` §Call 1 |
| #11 WOO_BASE_URL | GC-4, UIE-8 | `docs/AGENTS.md` §5, `docs/DEPLOYMENT.md` §3 |
| #12 synced-species-only | C1-1, TAX-2 | `docs/ARCHITECTURE.md` §7, `docs/CONTENT-WOO.md` §2.2 |
| #14 taxonomy_anchor | TAX-1, W-3, W-4, API-7 | `docs/ARCHITECTURE.md` §7, `docs/OPENAPI.md` §taxonomy |
| #15 four inline knobs | UI-1, UIE-9, UIE-10 | `docs/TECH-SPEC-PIPELINE.md` §3.3, `docs/UX.md` §Capture |
| #17 shared validation | V-1, V-2, V-3, API-8 | `docs/OPENAPI.md` §validation |
| #18 409/422 recovery | UIE-3, UIE-4, UIE-5, UIE-6 | `docs/CONTENT-WOO.md` §2.5–2.6, `docs/OPENAPI.md` §slabs |
---
## Gates and phase map
| Phase / Gate | Cases | Exit evidence |
|---|---|---|
| Phase 0 / Gate B | TV-1 through TV-10, V-1 through V-3, AES-1 through AES-2, H-1, D-1, OPS-1, GC-5 | Ty confirms TV-3, TV-6, TV-7, TV-10 on real fixtures; health up; AES round-trip; draft store; unit/API automated |
| Gate C (early Phase 1) | GC-1 through GC-4, W-1 through W-5, INF-1 through INF-4, UI-1 through UI-5 | Ty opens one `SLAB-UAT-*` WooCommerce draft in real store admin; inference OFF; mocked-store not exit |
| Phase 1 remainder | API-1 through API-10, TAX-1, TAX-2, TAX-3 | Agent-written test automation drives full calibrated to ready cycle; OPENAPI matches; revision and taxonomy green |
| Phase 3 | UIE-1 through UIE-10 | Ty publishes test slab as Woo draft `SLAB-UAT-*`; automation UI cases; Ty is exit |
| Phase 5 | C1-1 through C2-4, OFF-1, OFF-2 | Ty runs species detection on 3 real slabs with judgment on acceptance; automation Call 1/2 cases; inference disabled path green |
| Phase 6 / production | OPS-2 through OPS-5, INS-1 through INS-4, E2E-1 through E2E-5 | Deployment smoke automated; Ty walks `docs/UAT-PRACTICE.md` and signs off on UAT; v1 done |
---
## Rules that do not change
- Inference is optional. The full suite passes with inference disabled. Call 1/Call 2 cases are gated after Gate C.
- bdft equals square feet times thickness in inches. No divide-by-12. TV-3 proves the identity.
- Client is authoritative for deterministic math; server stores client-sent numbers.
- No new product locks in this document. All rules reference existing live docs or issue #19 substance.
-227
View File
@@ -1,227 +0,0 @@
# UAT Practice Walk: one `SLAB-UAT-*` listing
Status: WALK · for Ty to run · SlabUploader
This is the walkable practice plan. It proves one listing end to end without touching a live product.
Follow the sections in order. Each one names what you do, what you should see, and where the rule
lives.
**Inference is OFF for this walk.** The optional ON path is only valid after Gate C is green and
the inference endpoint is already configured. Inference stays off here.
---
## 1. Host and deploy preconditions
Before this walk, the app must already be on the inventoried host. This section only checks that.
Host IPs and hostnames come from `deploy/INVENTORY.md`.
1. **Inventory is filled.** `deploy/INVENTORY.md` has `APP_HOST`, `APP_HOSTNAME`, ports, Caddy
location, and the smoke results. It is the only source for what runs where on this host.
See `docs/DEPLOYMENT.md` §1 for the worksheet rules.
2. **Reachable over LAN/Tailscale.** Your phone reaches `https://${APP_HOSTNAME}` on the same
network (LAN or Tailscale). No public exposure. Verify with a browser, not `curl`.
3. **HTTPS only.** The URL is `https://`. The browser shows a valid certificate. If the phone
warns, the Caddy TLS trust is not set up yet. That is a deploy problem, not a listing problem.
4. **Health passes.** In a browser on the phone, open `https://${APP_HOSTNAME}/api/health`.
You should see an ok response. This is the same check in `docs/DEPLOYMENT.md` §8 step 1.
5. **Store URL is set.** `WOO_BASE_URL` is in the host `.env` and points at the store over
`https://`. It is not something you type in the app. See `docs/DEPLOYMENT.md` §3 and §5.
If any of these fail, fix the deploy before continuing. This walk does not cover Gate B host work.
It assumes the app is up and reachable.
---
## 2. WordPress Application Password setup
You do this once per store, in the store's WordPress admin. Do it before you open the app's
Settings.
1. **Store is on HTTPS.** WordPress only offers Application Passwords over HTTPS. The store must
already be on TLS. If it is not, stop and fix the store first.
2. **Dedicated low-privilege user.** Create or use a WordPress user that can create and edit
products and upload media. The store admin login is not reused. A shop manager role or a custom
role with product create/edit plus media upload is enough.
3. **Generate the password.** Sign in as that user. Go to **Users → Profile → Application
Passwords**. Generate a password and label it "SlabUploader". Copy the password. WordPress
shows it once.
4. **Enter it in the app.** Open the app's Settings on the phone. Enter the WordPress username and
the application password. The server stores them encrypted. The browser does not keep them.
5. **Run `test-woo`.** In Settings, tap the test. It should report ok. This also resyncs the
store's species, categories, tags, and attributes into the app. If it fails, the username or
password is wrong, or the store is unreachable.
Rules: this is a WordPress Application Password, not WooCommerce consumer keys (`ck_`/`cs_`).
The app never calls the store from the browser. FastAPI is the only caller. Rotate by revoking
the old password in the WP profile and entering a new one in Settings, then re-running
`test-woo`. Full lock: `AGENTS.md` §4 and §5, `docs/DEPLOYMENT.md` §5.
---
## 3. Practice build rules
These rules keep practice runs invisible to customers. They are locked. Changes are not made for
the walk.
- **SKU prefix `SLAB-UAT-*`.** Every practice listing uses a SKU that starts with `SLAB-UAT-`.
Pick a unique one each time, for example `SLAB-UAT-001`.
- **Always a Woo draft.** A `SLAB-UAT-*` SKU creates a WooCommerce draft even if Settings say
publish. Customers cannot open it. This is hard rule in `AGENTS.md` §5.
- **`woo_create_status` defaults to draft.** The Settings field that controls create status
defaults to `draft`. Practice uses the default. If it is `publish`, the
`SLAB-UAT-*` rule still forces a draft.
- **Customers never see practice listings.** A Woo draft is hidden from the storefront. If you
can see the product on the live store, something is wrong.
If a practice SKU is not `SLAB-UAT-*`, it is not a practice run. Real SKUs are not published in
this walk.
---
## 4. Prove one listing end to end
This is the main walk. Run it on a phone browser first, then repeat on a PC browser. Both are in
the signed compatibility matrix (`docs/UX.md`, signed 2026-09-06).
Supported browsers: iOS Safari, Android Chrome on phones; desktop Chrome, Edge, Firefox on PC.
Exact version pins are tracked under issue #4. If the browser is not supported, the app shows a
hard stop. Switch to a supported browser.
### 4.1 Capture
1. Open the app on the phone. Start a new slab.
2. Take 1 to 5 photos of the slab. The first should be top-down, lens parallel to the broad
face. A tilted shot makes the numbers wrong. Retake if it is tilted.
3. **Mask overlay and four knobs.** The app draws a mask over the photo. You see which pixels are
slab and which are not. Tune the four knobs: **Sheet** (auto/green/black), **Sensitivity**,
**Edge offset**, **Feather**. Each change re-runs the mask immediately. Look at the edge
against the real wood. If it is still off, retake the photo.
4. **Confirm the mask.** Tap confirm.
5. **Length axis.** The app draws the bounding rectangle and the length axis. Confirm it follows
the slab's long direction. Rotate if it is skewed. On a nearly square slab, you say which way
is length.
6. **Enter numbers by hand.** Length in 1/8" steps. Thickness as a 1/8" pick. SKU: type
`SLAB-UAT-001` (or your chosen practice SKU).
7. **Check the computed numbers.** The browser shows square feet, board feet, and width samples.
Board feet = square feet × thickness in inches. No divide-by-12. If the numbers look wrong,
go back and fix the mask or the length.
8. **Continue.** This uploads the originals, the processed PNGs, and the numbers to the server.
The slab status becomes `calibrated`.
### 4.2 Review
1. You are on the review screen. Fill every required field. Inference is OFF, so everything starts
empty.
2. **Species.** Pick exactly one from the synced store list. The list came from `test-woo`.
Only species in the list may be typed.
3. **Wood categories.** Pick at least one from the synced list.
4. **Edge type, figure, grade.** Pick from the synced lists. At least one figure, at least one
grade.
5. **Thickness band.** Pick the Woo band that the measured thickness rounds up into.
6. **Moisture.** Keep the default (kiln-dried) or change it.
7. **fig-* tags.** Pick at least one.
8. **feat-* tags.** Zero or more. Only pick existing `feat-*` tags.
9. **Price.** A recommendation fills from the species $/bdft rule times board feet. You can
override it. If there is no rule for the species, the price starts empty. Type it. Publish
is still allowed with a manual price.
10. **Title and description.** You can type them, or leave them for templates at publish.
Templates inject the deterministic numbers. Generate text is OFF for this walk.
Every empty required field shows an inline nudge where it sits. The slab cannot reach `ready`
until the full set is filled.
### 4.3 Publish
1. Tap **Publish**.
2. The server checks the SKU against the store. If `SLAB-UAT-001` is new, it creates the
product.
3. **What you should see:** a success message on the screen. The local draft and its photos are
gone from the app. The slab status in the app is `published`.
4. **What that does NOT mean:** the product is not live in the store. It is a WooCommerce draft.
The app's "published" means the store create succeeded and the local row was cleaned up.
### 4.4 Confirm in the store
1. Open the store's WooCommerce admin.
2. Find the product by SKU `SLAB-UAT-001`.
3. **It must be a draft.** Status is draft, not published.
4. **Check the fields:** SKU, price, category (species), tags (fig-*, feat-*), attributes
(Edge Type, Figure, Grade, Thickness, Moisture), and images (the processed transparent PNGs).
5. **Open the live storefront.** The product must not appear. A draft is invisible to customers.
### 4.5 Repeat on a PC browser
Repeat 4.1 through 4.4 on a desktop browser (Chrome, Edge, or Firefox). Use a different
practice SKU, for example `SLAB-UAT-002`. The flow must work the same way. This is the signed
PC-browser compatibility check.
---
## 5. Pass and fail checks
You can see all of these without reading code.
| Check | Where | Pass looks like |
|---|---|---|
| Health endpoint | Phone browser, `https://${APP_HOSTNAME}/api/health` | ok response |
| `test-woo` ok | App Settings | ok; species list is populated |
| `woo_create_status` is draft | App Settings | shows `draft` (or `publish`, but `SLAB-UAT-*` forces draft anyway) |
| Slab reaches `calibrated` | App, after capture | status is `calibrated` |
| Slab reaches `ready` | App, after review | no empty required fields; inline nudges gone |
| Publish succeeds | App, after Publish | success message; local draft is gone |
| Woo product exists as draft | Store admin, products | SKU `SLAB-UAT-*`, status draft |
| SKU prefix correct | Store admin | starts with `SLAB-UAT-` |
| Store not live | Live storefront URL | product does not appear |
| Board feet identity | App review screen, or a fixture | bdft = sqft × thickness in inches; no divide-by-12 |
| Images are processed PNGs | Store admin, product images | transparent PNGs, not the original JPEGs |
### Duplicate SKU recovery
If you publish the same SKU twice, the second time the app stops before creating a second product.
Under the SKU field you see: "This SKU already exists in the store (any status)." Two paths:
edit the SKU to a new value, or open the existing listing. The draft stays in the app. Nothing is
lost. This is the expected behavior, not a bug. See `docs/CONTENT-WOO.md` §2.5.
### What a fail looks like
- **No success message after Publish.** The app shows a plain message that the listing could not
be created. No status number, no stack trace. The server kept a log. You can retry from the
same screen without re-photographing.
- **A value is no longer valid.** If a category, attribute, or price was removed from the store
between sync and publish, that field shows "This value is no longer valid. Pick from the
current list." Re-pick and retry.
- **Store unreachable.** A plain message says the store could not be reached. Check the network
and retry.
---
## 6. Cleanup
After the walk, decide what to do with the Woo draft UAT product.
- **Leave it or delete it.** Both are fine. It is a draft. Customers cannot see it. If you delete
it, the store admin is the place to do it. The app does not delete store products.
- **Never customer-visible.** If the product is visible on the live storefront, it is not a
draft. That is a bug. Stop and report it.
**Real live publish is a separate step.** It is not part of this walk. A real product uses a
non-UAT SKU (no `SLAB-UAT-` prefix) and is published only after you review it. That is a
different decision. That step is not run here. The name of that step is **final POC publish**, and it
is gated on your review of one real listing.
---
## Where each rule lives
| Rule | Source |
|---|---|
| Practice SKU forces draft | `AGENTS.md` §5 |
| `woo_create_status` default draft | `AGENTS.md` §5, `docs/CONTENT-WOO.md` §2.4 |
| App Password setup, not consumer keys | `AGENTS.md` §4, `docs/DEPLOYMENT.md` §5 |
| Host inventory before deploy | `docs/DEPLOYMENT.md` §1, `deploy/INVENTORY.md` |
| Capture → review → publish flow | `docs/UX.md` (SIGNED 2026-09-06) |
| Board feet identity | `docs/TECH-SPEC-PIPELINE.md` |
| Duplicate SKU recovery | `docs/CONTENT-WOO.md` §2.5, `docs/UX.md` Publish |
| PC browser compatibility | `docs/UX.md` Browser compatibility |
| Gate C = early Phase 1 | `docs/IMPL-PLAN.md` Phase 1, `AGENTS.md` §0b |
-486
View File
@@ -1,486 +0,0 @@
# UX Design — SlabUploader Phone App
Status: DESIGN · 2026-09-03 · SlabUploader
Screens for the online-only POC flow. Mobile-first, 375px viewport.
Functional rules live in `docs/UX.md`. Confidence gating: `AGENTS.md` §6.
Data model and status machine: `docs/DATA-MODEL.md`.
---
## Screen inventory
1. Settings (once)
2. First-run guidance (once per device)
3. Capture
4. Length axis
5. Type values
6. Review
7. Title / Description
8. Publish
9. Error states
---
## 1. Settings
One-time setup. All screen. Back to home after save.
```
┌─────────────────────────────────────┐
│ Settings │
├─────────────────────────────────────┤
│ Store URL │
│ https://www.whidbeywoodstore.com │
│ │
│ WP Username │
│ [ slab-uploader ] │
│ Application Password │
│ [ •••••••••••••••••••• ] │
│ [ Test Connection ] │
│ │
│ Inference │
│ Endpoint: [ http://192.168.x.x:v1 ]│
│ API Key: [ •••••••••••••••••••• ]│
│ [ Test Connection ] │
│ [ Enable Vision ] │
│ [ Enable Content ] │
│ │
│ Pricing Rules │
│ [+ Add Rule] [Edit] │
│ │
│ Publish Status: [ Draft ▼ ] │
│ Brand Voice: [ Premium lumber... ]│
│ GEO Context: [ Locally milled... ]│
│ │
│ [ Reset Capture Knobs ] │
│ [ Refresh Store Lists ] │
└─────────────────────────────────────┘
```
Interaction:
- Test Connection (WP): attempts REST v3 auth, shows green check or red error. Always pulls fresh taxonomy on success.
- Test Connection (Inference): two-turn probe. Shows stateful/stateless/fail.
- Enable Vision: feature flag for Call 1. Defaults off.
- Enable Content: feature flag for Call 2. Defaults off.
- Publish Status: dropdown, default Draft.
---
## 2. First-run guidance
One short card shown on first launch. Dismissed via swipe or tap.
```
┌─────────────────────────────────────┐
│ │
│ First run on the floor │
│ │
│ Lay a green or black sheet │
│ under the slab. │
│ │
│ Shoot from above with the lens │
│ parallel to the face. │
│ │
│ Put a tape measure in the shot │
│ so you can type the length later. │
│ │
│ ────────────────────────────────── │
│ [ Got it ] │
│ │
└─────────────────────────────────────┘
```
---
## 3. Capture
Camera view. Source photo on screen. Mask overlay draws on the source.
Four knobs sit next to the overlay.
```
┌─────────────────────────────────────┐
│ Capture [R] │
│ ┌─────────────────────────────────┐ │
│ │ │ │
│ │ [ SOURCE PHOTO ] │ │
│ │ │ │
│ │ ~ mask overlay ~ │ │
│ │ │ │
│ └─────────────────────────────────┘ │
│ │
│ Sheet: [ Auto ▼ ] │
│ Sensitivity: [◄─────●───►] │
│ Edge Offset: [◄───●───►] │
│ Feather: [◄─────●───►] │
│ │
│ [ Retake ] [ Confirm ] │
└─────────────────────────────────────┘
R = retake current photo (new shot, same knobs)
```
Interaction:
- Moving any knob immediately re-runs background removal on the current photo.
- The overlay refreshes on the source image. No apply/save step. No server round-trip.
- Confirm moves to length axis. Retake takes a new photo.
- Knobs persist in localStorage until reset-to-default in Settings.
---
## 4. Length axis
Bounding rectangle and length axis drawn over the confirmed mask.
Width sample lines every 6 inches.
```
┌─────────────────────────────────────┐
│ Length Axis │
│ ┌─────────────────────────────────┐ │
│ │ │ │
│ │ ┌───────────────┐ │ │
│ │ │ SLAB MASK │ │ │
│ │ │ ──── AXIS ── │ │ │
│ │ │ ┌──┐ ┌──┐ ┌──┐ │ │
│ │ │ │ 6"│ │6"│ │6"│ │ │
│ │ └───────────────┘ │ │
│ │ │ │
│ └─────────────────────────────────┘ │
│ │
│ [ Rotate ↻ ] [ Confirm ] │
└─────────────────────────────────────┘
```
Interaction:
- Rotate adjusts the axis. Width samples and sqft update live.
- On nearly square slabs, user picks which side is length.
- Confirm moves to type values.
---
## 5. Type values
Manual values win. Phone computes sqft, bdft, widths.
```
┌─────────────────────────────────────┐
│ Type Values │
│ │
│ SKU │
│ [ BW-0042 ] │
│ │
│ Length (inches) │
│ [ 96.0 ] │
│ │
│ Thickness (inches) │
│ [ 1.5 ] │
│ │
│ Computed (read-only) │
│ sqft: 0.64 bdft: 0.96 │
│ widths: 14.0 — 22.0 (avg 18.2) │
│ │
│ [ Done ] │
└─────────────────────────────────────┘
```
Interaction:
- SKU: `[A-Z0-9-]{3,24}`. Field-exit check against validation rules.
- Length: 1/8" step. Typing recalculates widths/sqft/bdft live.
- Thickness: 1/8" step pick.
- Done moves to review screen. Draft uploads, status → calibrated.
---
## 6. Review
All store fields. Per-field nudges for missing mandatory fields.
Vision pre-populates when confidence ≥ 0.7. Empty when below.
```
┌─────────────────────────────────────┐
│ Review [X]│
│ ────────────────────────────────── │
│ Photos │
│ [ ▢ ] [ ▢ ] [ ▢ ] [ ▢ ] [ ▢ ] │
│ (processed PNG thumbnails) │
│ ────────────────────────────────── │
│ SKU: BW-0042 │
│ Length: 96.0" Thickness: 1.5" │
│ sqft: 0.64 bdft: 0.96 │
│ Widths: 14.0 — 22.0 (avg 18.2) │
│ ────────────────────────────────── │
│ Species [ Black Walnut ▼ ] │
│ Wood Cat [ Live edge ▼ ] │
│ Edge Type [ Live Edge ▼ ] │
│ Figure [ Cathedral ▼ ] │
│ Grade [ Premium ▼ ] │
│ Fig Tags [ Cathedral ▼ ] │
│ Feat Tags [ None ▼ ] │
│ ────────────────────────────────── │
│ Thickness Band: [ 1"–1 1/2" ▼ ] │
│ Moisture: [ Kiln-dried ▼ ] │
│ ────────────────────────────────── │
│ Price: [ $12.00 ] (rec $12.00) │
│ ────────────────────────────────── │
│ [ Review Title / Desc ] [ Publish ]│
└─────────────────────────────────────┘
X = exit review, returns to calibrated draft
```
Per-field gating:
- Each missing mandatory field shows an inline empty state as the user works.
- Below-threshold Call 1 leaves taxonomy fields empty. The user sees the empty
field with a nudge: "Select species" or "Select a figure type".
- Below-threshold leaves taxonomy fields empty. The user must manually fill species, wood
category, edge type, figure, grade, fig-* tags, and grade to reach ready.
- Submit-time validation only fires after all fields are filled.
Pre-populated field appearance:
- Filled by Call 1: field shows the value with a small "AI" badge. User can
tap to change. Badge disappears on edit.
- User-filled: no badge.
Gating details:
- Mandatory: exactly one species, ≥1 wood category, 1 edge type, ≥1 figure,
≥1 fig-* tag, ≥1 grade, thickness band, moisture, price, SKU, length,
thickness, sqft/bdft/widths, ≥1 inventory PNG.
- Optional: feat-* tags (zero is fine).
- Publish button is disabled until all mandatory fields are filled.
---
## 7. Title / Description
Type or generate. Generate text is user-initiated.
```
┌─────────────────────────────────────┐
│ Title & Description │
│ ────────────────────────────────── │
│ Title │
│ [ Black Walnut 8ft × 18.2in Slab... │
│ ────────────────────────────────── │
│ Short Title │
│ [ Black Walnut Slab — Cathedral ] │
│ ────────────────────────────────── │
│ Description │
│ [ A one-of-a-one cathedral black... │
│ ────────────────────────────────── │
│ [ Generate Text ] [ Done ] │
└─────────────────────────────────────┘
```
Interaction:
- Generate Text: triggers Call 2. Button disabled if content LLM is off or
inference endpoint unreachable. LLM writes prose only. Templates inject
deterministic numbers. User can always edit the result.
- Done: returns to review. Title/description stored on the slab.
---
## 8. Publish
Status polling. Result shown inline.
```
┌─────────────────────────────────────┐
│ Publishing... │
│ │
│ ──────── ● ──────── │
│ │
│ Creating store listing... │
│ Please wait. │
│ │
└─────────────────────────────────────┘
```
Success:
```
┌─────────────────────────────────────┐
│ Published! │
│ │
│ Listing created as draft. │
│ SKU: BW-0042 │
│ Store product ID: 1042 │
│ │
│ [ Open in Store ] [ Done ] │
└─────────────────────────────────────┘
```
Failed:
```
┌─────────────────────────────────────┐
│ Publish Failed │
│ │
│ The store rejected the listing. │
│ Error shown inline on the field. │
│ │
│ [ Retry ] [ Back to Review ] │
└─────────────────────────────────────┘
```
---
## 9. Error and empty states
### 9.1 Mask failure
```
┌─────────────────────────────────────┐
│ Mask Quality │
│ ────────────────────────────────── │
│ Cannot isolate the slab edge. │
│ Adjust the knobs or retake. │
│ ────────────────────────────────── │
│ [ Retake ] │
└─────────────────────────────────────┘
```
### 9.2 Axis misalignment
```
┌─────────────────────────────────────┐
│ Axis Check │
│ ────────────────────────────────── │
│ Rotate the axis to match the │
│ prevailing length of the slab. │
│ ────────────────────────────────── │
│ [ Rotate ↻ ] │
└─────────────────────────────────────┘
```
### 9.3 Source too small after crop
```
┌─────────────────────────────────────┐
│ Photo Quality │
│ ────────────────────────────────── │
│ Photo will be too small after │
│ cropping. Please retake with a │
│ closer shot. │
│ ────────────────────────────────── │
│ [ Retake ] │
└─────────────────────────────────────┘
```
### 9.4 SKU duplicate
```
┌─────────────────────────────────────┐
│ SKU Check │
│ ────────────────────────────────── │
│ This SKU already exists in the │
│ store (any status). │
│ ────────────────────────────────── │
│ [ Edit SKU ] [ Open Existing ] │
└─────────────────────────────────────┘
```
### 9.5 Stale taxonomy value
```
┌─────────────────────────────────────┐
│ Field Check │
│ ────────────────────────────────── │
│ This value is no longer valid. │
│ Pick from the current list. │
│ ────────────────────────────────── │
│ [ Refresh Store Lists ] │
└─────────────────────────────────────┘
```
### 9.6 Store unreachable
```
┌─────────────────────────────────────┐
│ Connection │
│ ────────────────────────────────── │
│ Cannot reach the store. Check your │
│ connection and settings. │
│ ────────────────────────────────── │
│ [ Retry ] [ Open Settings ] │
└─────────────────────────────────────┘
```
### 9.7 Vision off or below threshold
```
┌─────────────────────────────────────┐
│ Review (vision off) │
│ ────────────────────────────────── │
│ Species [ Select ▼ ] ◉ Select species
│ Wood Cat [ Select ▼ ] ◉ Select category
│ Edge Type [ Select ▼ ] ◉ Select edge
│ Figure [ Select ▼ ] ◉ Select figure
│ ────────────────────────────────── │
└─────────────────────────────────────┘
◉ = inline nudge (per-field)
```
---
## Interaction patterns
### Per-field gating (review screen)
- Each mandatory field that is empty shows an inline nudge as the user works.
- The nudge is a small text hint to the right of the field.
- Below-threshold Call 1 leaves fields empty with nudges visible.
- Fill the field to dismiss the nudge.
- Publish button stays disabled until all mandatory fields are filled.
### Pre-populated field state
- Fields filled by Call 1 show the value with an "AI" badge.
- User can tap the field to change it. The badge disappears on edit.
- User-filled fields have no badge.
### Knob interaction (capture screen)
- All four knobs are on the capture screen next to the overlay.
- Moving a knob immediately re-runs background removal.
- No apply/save step. No server round-trip for mask tuning.
### Axis rotation
- Drag or tap to rotate the axis. Width samples and sqft update live.
- Confirm locks the axis for measurement.
### Generate text
- Button only appears if content LLM is enabled and inference is reachable.
- Disabled if the text service is down.
- Never runs automatically. User taps it.
### Publish flow
- Tap Publish. Status moves to publishing. Poll for result.
- Success: show result, offer to open in store.
- Failed: show error detail, keep draft and photos, allow retry.
- SLAB-UAT-* SKUs always create as Woo draft regardless of settings.
---
## Browser compatibility gate
Shown on load if browser lacks required APIs.
```
┌─────────────────────────────────────┐
│ Browser Update │
│ ────────────────────────────────── │
│ This app requires a recent browser. │
│ Please update Safari or Chrome, │
│ then try again. │
│ ────────────────────────────────── │
│ [ Update Browser ] │
└─────────────────────────────────────┘
```
---
## UAT test cases (derived from wireframes)
1. **Settings once**: enter WP credentials, test connection, taxonomy syncs.
2. **First-run guidance**: card shows and dismisses.
3. **Capture**: take photo, mask overlays, adjust knob, overlay refreshes live, confirm.
4. **Length axis**: bounding rect draws, rotate axis, confirm, widths update.
5. **Type values**: enter SKU/length/thickness, computed values appear, done.
6. **Review — vision on, ≥ 0.7**: taxonomy fields pre-filled with AI badge, editable.
7. **Review — vision on, < 0.7**: taxonomy fields empty, per-field nudges visible, user fills manually.
8. **Review — vision off**: all taxonomy fields empty, per-field nudges visible, user fills manually.
9. **Publish — success**: draft created, product ID stored, images purged.
10. **Publish — duplicate SKU**: error on SKU field, edit SKU or open existing.
11. **Publish — stale taxonomy**: error on field, refresh store lists, pick current option.
12. **Publish — SLAB-UAT-***: always creates as draft regardless of settings.
13. **Generate text**: button visible when enabled, disabled when service down, LLM prose injected.
14. **Retake paths**: mask failure → retake, source too small → retake.
-235
View File
@@ -1,235 +0,0 @@
# Mill-owner UX — phone and PC browsers
Status: SIGNED · 2026-09-06 PT · Ty approved with PC browsers in the compatibility matrix · SlabUploader
This is the presentation spec for the mill-owner flow. It says what a mill owner sees and does, in the
order they do it. The rules behind each screen live elsewhere: `AGENTS.md` locks the product
decisions, `docs/TECH-SPEC-PIPELINE.md` owns the math and image prep, `docs/DATA-MODEL.md` owns
the store row and its statuses, `docs/CONTENT-WOO.md` owns listing copy and the Woo payload,
and `docs/OPENAPI.md` owns the wire. This file names what shows up on screen; it does not restate
those rules.
The reader is a mill owner photographing one slab at a time, online, from a supported browser on a
phone or a PC. The app is a single column of screens, top to bottom: capture, then review, then
publish. There is no dashboard and no batch view in this version. Capture often starts on a phone
camera; the same flow must also run on a PC browser.
## Jobs
Five jobs cover the whole flow. Each section below names what the owner does, what they see, and
the lock that governs it.
1. **Phone photo to a store listing.** Photograph the slab, confirm the cut and the numbers on
the browser, review the listing, create the WooCommerce product. The happy path stays in the
browser until the owner confirms the mask and the numbers.
2. **Practice drafts customers never see.** A practice run creates a WooCommerce draft with an SKU
that starts `SLAB-UAT-`. Customers cannot open it. It is always a draft, even when Settings say
publish.
3. **Retake when the overlay cut looks wrong.** The mask overlay on the source photo is the only
quality check. If the edge is off after tuning the four knobs, the owner retakes the photo.
4. **Fill or override store fields.** On review, the owner fills every required field by hand, or
keeps what vision filled when it was confident enough. Typed values always win.
5. **Publish.** The owner taps publish. The server creates the product in the store and reports the
result back on the same screen.
## Capture: photo to numbers
The capture flow is one continuous screen with a few confirmations, not separate pages. The owner
stays on it from first photo through confirmed mask and axis.
### Photos
The owner takes 1 to 5 inventory photos of the slab. The first should be top-down, lens parallel
to the broad face; a tilted shot makes square feet and board feet wrong, and retake is the fix.
There are no calibration photos in this design. Only inventory photos exist.
### Mask overlay and four knobs
The app removes the background sheet and draws the mask as an overlay on the source photo, showing
which pixels count as slab and which do not. The owner reviews that edge against the real wood.
This is the only quality check in the pipeline. There is no confidence score, no auto-gate, and no
photo-quality checker. A clipped or over-inclusive mask shifts every downstream number with nothing
later to catch it, so the eye on the overlay is what stands behind the measurement.
Four knobs sit on this same screen, next to the overlay:
- **Sheet** — auto, green, or black. Auto samples the borders and picks; the owner overrides when
the sheet is an odd color.
- **Sensitivity** — one slider from tighter to looser detection.
- **Edge offset** — pulls the cut in or out a few pixels so it sits on the wood, not in the sheet
or into the grain.
- **Feather** — hard edge versus a couple of pixels of blend.
Changing any knob re-runs background removal immediately and refreshes the overlay. There is no
apply step and no server round trip for mask tuning in this version. The four values persist on the
browser until reset to default; they are not Settings fields.
If the edge still looks wrong after tuning, the owner retakes the photo. That is the resolution in
this version. A server-side matting path exists in the architecture for awkward backgrounds later,
but it is deferred and has no control here.
### Length axis
After the mask is confirmed, the app draws the bounding rectangle and the length axis over the slab,
with width sample lines perpendicular to that axis. The owner confirms the axis follows the
slab's prevailing length. If it is skewed, they rotate it; samples and square feet update live. On a
nearly square slab the owner says which way is length.
### Numbers
The owner enters length (in 1/8" steps), thickness (a 1/8" pick), and the SKU by hand. The browser
then computes square feet, board feet, and width samples from the confirmed mask and axis:
- Board feet = square feet × thickness in inches. One square foot at one inch thick is one board
foot. There is no divide-by-12.
- Widths are sampled every 6" along the length axis; the listing carries min, max, and average.
- Square feet and board feet show to two decimals.
These numbers are computed in the browser and stored as sent. The server does not recompute them.
### Photo prep
Each inventory photo is cropped to a 3:4 portrait frame with the slab centered at 80% fill, saved as
a transparent PNG. If the source has enough pixels, the shorter side lands at 1600 or more after
crop. If it cannot reach that, the app warns and asks for a retake; it does not invent pixels. The
owner sees the processed result alongside the original while the draft is retained.
### Continue
When the mask, axis, length, thickness, and SKU are set, the owner continues. That uploads the
originals plus the processed PNGs plus the numbers to the server as a calibrated draft, and moves to
review. The slab status becomes `calibrated`.
## Review: fill or override store fields
Review is where the listing row gets filled. Every field below maps to a column in the `slabs` table
in `docs/DATA-MODEL.md`. The owner can type any of them; vision may have pre-filled some, but typed
values always win and every value stays editable.
### What vision fills, and when
When inference is on, Call 1 runs after the calibrated draft uploads. It sends all inventory photos
downscaled to 1024 plus the store's synced species and attribute lists, and returns a guess
with a confidence per field. The threshold is 0.7 by default:
- A field at or above 0.7 pre-fills on review. It stays editable; the owner can change or clear it.
- A field below 0.7 starts empty. The app does not show the model's low-confidence guess as a
default, and an empty start is not the same as a finished listing.
With inference off, every field starts empty and the owner fills all of them by hand. Inference
never blocks publish and never auto-publishes. Call 2 (Generate text) does not run on its own; it
fires only when the owner taps it.
### The fields
The required set for a list-ready slab is the full store row, not species plus one figure:
- **SKU** — `[A-Z0-9-]{3,24}`. Practice runs use `SLAB-UAT-*`.
- **Length and thickness** — from capture; still editable here.
- **Square feet, board feet, widths** — shown as the client-computed values, with a manual override
path. The owner's typed number wins over the computed one.
- **Species** — exactly one leaf category from the synced store list. No hardcoded or invented
species; a new store species appears only after the next sync.
- **Wood categories** — at least one, from the synced list.
- **Edge type** — one term from the synced attributes.
- **Figure** — at least one term.
- **Grade** — at least one term.
- **Thickness band** — the Woo range that the measured thickness rounds up into (for example, a 1"
pick lands in the `1"–1 1/2"` band). The exact labels come from the synced store attribute.
- **Moisture** — one term, defaulting to kiln-dried. It is never inferred; the owner sets or keeps it.
- **fig-* tags** — at least one.
- **feat-* tags** — zero or more (character, inclusions, voids, checks map to existing `feat-*`
tags only).
- **Price** — a recommendation pre-fills from the species $/bdft rule times board feet; the owner may
override and that sticks. With no rule for the species, the price starts empty and the owner types
it. Publish is still allowed with a manual price.
Title, short title, and description are not required to reach ready. They can be typed by hand,
generated from templates at publish, or written by Generate text (Call 2) when enabled. Templates
always run; they inject the deterministic numbers so the model never touches dimensions.
### How missing fields show up
A field that is still empty and required shows its nudge inline, in place, the moment it is empty.
The owner sees each gap where it sits rather than learning about a problem after scrolling past it.
There is no single submit-time check that lists everything at once; the nudges are per-field as the
owner works. The slab cannot reach `ready` until the full set above is filled, whether by hand or by
a confident Call 1 the owner kept.
### Generate text
When content generation is enabled, a **Generate text** button runs Call 2 and fills title, short
title, and description with model prose plus template numbers. The owner can edit the result freely.
If the endpoint is missing or down, the button is disabled; templates still work and publish is never
blocked by a failed Generate text.
## Publish: create the store listing
The owner taps **Publish** when review is complete. What happens next depends on the SKU and Settings.
### Draft versus live
- A normal SKU publishes according to the `woo_create_status` setting, which defaults to draft.
- Any SKU matching `SLAB-UAT-*` always creates a WooCommerce draft, even if Settings say publish.
That is how practice runs stay invisible to customers.
The app's "published" means the store create succeeded and the local row plus photos were cleaned up.
That is not the same as the product being live in the store; a draft is created but hidden until Ty
promotes it.
### What the owner sees on each outcome
- **Success.** The screen shows that the listing was created, with the store's product reference when
available. The local draft and its photos are gone from the app.
- **SKU already exists.** Under the SKU field: "This SKU already exists in the store (any status)."
Two paths appear: edit the SKU to a new value, or open the existing listing. This version does not
update the other product in place. The draft stays in the browser; nothing is lost.
- **A value no longer valid.** If a category, attribute, or price was removed from the store between
sync and publish, that field shows "This value is no longer valid. Pick from the current list," with
the current options. The owner re-picks and retries.
- **Store unreachable or other failure.** A plain message on the screen says the listing could not be
created and to try again. No status number, no stack trace, no raw error code reaches the owner.
The server keeps a log of every attempt either way, so a failed publish can be retried from the same
screen without re-photographing.
## Browser compatibility
Ty signed this walk on 2026-09-06 PT with one amendment: the compatibility matrix includes PC
browsers as well as phones. This app is not mobile-only.
Supported families (matrix):
- **Phone:** iOS Safari, Android Chrome
- **PC:** desktop Chrome, desktop Edge, desktop Firefox (Windows and macOS at minimum)
Exact minimum version pins are still tracked under issue #4. The matrix above is the product lock
for which classes of client are in scope.
Unsupported browser behavior: hard stop. Show a clear message that this browser is not supported,
with a link to update or switch to a supported browser. No polyfill
strategy in this version.
Load-bearing client surfaces that must remain: canvas-based mask overlay and live knob re-run,
image crop/prep to 3:4 transparent PNG, file/photo intake for inventory shots, and the online API
calls for draft upload, review, and publish. Depth for APIs stays in `docs/TECH-SPEC-PIPELINE.md`
and `docs/OPENAPI.md`.
## Deferred features
Photo quality, OCR, ruler detection, server-side measuring, U2Net control, and offline capture are
deferred post-POC. The overlay edge plus the owner's eye is the only quality gate. SKU is typed by
hand. Length is entered by hand; the browser derives its own pixel-to-inch scale. The browser owns
the happy path for measuring and cropping. The U2Net one-photo contract stays in the architecture
for later. Capture is online only.
## Where each job lives
| Job | Screen(s) | Governing lock |
|---|---|---|
| Photo to listing | Capture through review to publish | AGENTS §1, TECH-SPEC, ARCHITECTURE swimlane |
| Practice drafts (`SLAB-UAT-*`) | Review (SKU field), Publish outcome | AGENTS §5, CONTENT-WOO payload status |
| Retake on bad cut | Capture mask overlay | TECH-SPEC §3.4–3.5, issue #15 |
| Fill or override fields | Review | DATA-MODEL `slabs`, AGENTS §6/7, issue #9 |
| Publish and recovery | Publish outcome states | CONTENT-WOO §2.5–2.6, OPENAPI 409/422, issue #18 |
+17
View File
@@ -0,0 +1,17 @@
# Archived specs
The previous live doc pile was removed from this branch so agents stop implementing from it.
Full prior text is on `main` at commit `13bfa792`. That includes ARCHITECTURE, CONTENT-WOO, DATA-MODEL, DEPLOYMENT, IMPL-PLAN, OPENAPI, PROMPTS, TECH-SPEC-PIPELINE, TEST-SPEC, UAT-PRACTICE, UX, UX-DESIGN.
`PRD-2026-08.txt` in this folder was already archive before this branch.
Do not implement from those files.
Live spec on this branch:
- `README.md`
- `AGENTS.md`
- `docs/PRODUCT.md`
- `docs/CAPTURE.md`
- `deploy/` for hosting only
+10
View File
@@ -0,0 +1,10 @@
node_modules
/build
/.svelte-kit
/package
.env
.env.*
!.env.example
vite.config.js.timestamp-*
playwright-report
test-results
+18
View File
@@ -0,0 +1,18 @@
# SlabUploader M1 — frontend only (no FastAPI/Woo). Multi-stage: build then serve.
FROM node:22-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
FROM node:22-alpine AS run
WORKDIR /app
ENV NODE_ENV=production
COPY package*.json ./
RUN npm install --omit=dev
COPY --from=build /app/build ./build
COPY --from=build /app/node_modules ./node_modules
EXPOSE 80
ENV PORT=80
CMD ["node", "build/index.js"]
+20
View File
@@ -0,0 +1,20 @@
import { keySheet } from './src/lib/core/mask.js';
import { sampleWidthsPx } from './src/lib/core/measure.js';
const W = 200, H = 150;
function slabPhoto(slabW, slabH, ox, oy) {
const data = new Uint8ClampedArray(W * H * 4);
for (let y = 0; y < H; y++)
for (let x = 0; x < W; x++) {
const i = (y * W + x) * 4;
const inSlab = x >= ox && x < ox + slabW && y >= oy && y < oy + slabH;
if (inSlab) { data[i] = 139; data[i + 1] = 90; data[i + 2] = 43; }
else { data[i] = 34; data[i + 1] = 139; data[i + 2] = 34; }
data[i + 3] = 255;
}
return data;
}
const d = slabPhoto(10, 10, 0, 0);
const m = keySheet(d, { sheet: 'green', sensitivity: 50 });
let kept = 0;
for (let i = 0; i < m.length; i++) kept += m[i];
console.log('kept:', kept, 'of', m.length);
+17
View File
@@ -0,0 +1,17 @@
import { sampleWidthsPx } from './src/lib/core/measure.js';
const W = 200, H = 150;
const mask = new Uint8Array(W * H);
// slab 336 x 192 px at (0,0) — extends beyond photo bounds (200x150)
for (let y = 0; y < H; y++)
for (let x = 0; x < W; x++)
mask[y * W + x] = (x < 336 && y < 192) ? 1 : 0;
const axis = { origin: {x:0, y:0}, dir: {x:1, y:0}, lengthPx: 336 };
const w = sampleWidthsPx(mask, W, H, axis, 160, 6);
console.log('widths:', w);
// sample points at t=0, 96, 192, 288 px
// perpendicular dir: (0,1) — scan down
// at x=0: y from 0..149 all in slab (y<192) → width 150 (clamped by photo)
// at x=96: same → 150
// at x=192: same → 150
// at x=288: x=288 > 200 (photo width) → out of bounds → 0? or skipped?
console.log('expected: [150, 150, 150] or [150, 150, 150, 0]');
+11
View File
@@ -0,0 +1,11 @@
import { sampleWidthsPx } from './src/lib/core/measure.js';
const W = 400, H = 250;
const mask = new Uint8Array(W * H);
for (let y = 0; y < H; y++)
for (let x = 0; x < W; x++)
mask[y * W + x] = 1; // whole photo is slab
const axis = { origin: {x:0, y:0}, dir: {x:1, y:0}, lengthPx: 336 };
const w = sampleWidthsPx(mask, W, H, axis, 160, 6);
console.log('widths (full photo):', w);
console.log('expected: [250, 250, 250] (t=0,96,192; t=288>336? no, 288<336 → also 250)');
console.log('samples at t=0,96,192,288 → 4 samples, each width=250');
+10
View File
@@ -0,0 +1,10 @@
import { keySheet } from './src/lib/core/mask.js';
const data = new Uint8ClampedArray(10 * 4);
// slab brown
data[0] = 139; data[1] = 90; data[2] = 43; data[3] = 255;
// sheet green
data[4] = 34; data[5] = 139; data[6] = 34; data[7] = 255;
data[8] = 34; data[9] = 139; data[10] = 34; data[11] = 255;
data[12] = 34; data[13] = 139; data[14] = 34; data[15] = 255;
const m = keySheet(data, { sheet: 'green', sensitivity: 50 });
console.log('mask for 4 pixels (1 slab + 3 sheet):', Array.from(m));
+8
View File
@@ -0,0 +1,8 @@
import { keySheet } from './src/lib/core/mask.js';
const data = new Uint8ClampedArray(4 * 4);
data[0]=139; data[1]=90; data[2]=43; data[3]=255;
data[4]=34; data[5]=139; data[6]=34; data[7]=255;
data[8]=34; data[9]=139; data[10]=34; data[11]=255;
data[12]=34; data[13]=139; data[14]=34; data[15]=255;
const m = keySheet(data, { sheet:'green', sensitivity:50 });
console.log('mask for 4 px (1 slab, 3 sheet):', Array.from(m));
+29
View File
@@ -0,0 +1,29 @@
const data = new Uint8ClampedArray(4 * 4);
data[0]=139; data[1]=90; data[2]=43; data[3]=255;
data[4]=34; data[5]=139; data[6]=34; data[7]=255;
data[8]=34; data[9]=139; data[10]=34; data[11]=255;
data[12]=34; data[13]=139; data[14]=34; data[15]=255;
const SHEET_GREEN = { r: 0, g: 255, b: 0 };
function greenDistance(r, g, b) {
const dr = r - SHEET_GREEN.r;
const dg = g - SHEET_GREEN.g;
const db = b - SHEET_GREEN.b;
return Math.sqrt(dr * dr + dg * dg + db * db);
}
function greenThreshold(s) { return 150 - s; }
function blackCutoff(s) { return 40 + (s / 100) * 100; }
const BLACK_SAT_CAP = 120;
const sensitivity = 50;
const n = data.length / 4;
const mask = new Uint8Array(n);
for (let i = 0; i < n; i++) {
const j = i * 4;
const r = data[j], g = data[j + 1], b = data[j + 2];
const d = greenDistance(r, g, b);
const t = greenThreshold(sensitivity);
mask[i] = d > t ? 1 : 0;
console.log(`px ${i}: r=${r} g=${g} b=${b} dist=${d.toFixed(1)} thresh=${t} kept=${mask[i]}`);
}
console.log('mask:', Array.from(mask));
+20
View File
@@ -0,0 +1,20 @@
import { keySheet } from './src/lib/core/mask.js';
import { readFileSync } from 'fs';
const fileSrc = readFileSync('./src/lib/core/mask.js', 'utf8');
const match = fileSrc.match(/const SHEET_GREEN = \{([^}]*)\}/);
console.log('SHEET_GREEN in file:', match ? match[0] : 'NOT FOUND');
console.log('keySheet source:', keySheet.toString());
const W = 20, H = 10;
const data = new Uint8ClampedArray(W * H * 4);
for (let y = 0; y < H; y++)
for (let x = 0; x < W; x++) {
const i = (y * W + x) * 4;
const inSlab = x >= 5 && x < 15 && y >= 2 && y < 8;
if (inSlab) { data[i]=139; data[i+1]=90; data[i+2]=43; }
else { data[i]=34; data[i+1]=139; data[i+2]=34; }
data[i+3] = 255;
}
const maskResult = keySheet(data, { sheet: 'green', sensitivity: 50 });
console.log('row 5:', Array.from(maskResult.slice(5*W, 6*W)));
let kept = 0; for (let i = 0; i < maskResult.length; i++) kept += maskResult[i];
console.log('kept:', kept, 'expected: 60');
+10
View File
@@ -0,0 +1,10 @@
const SHEET_GREEN = { r: 0, g: 255, b: 0 };
function greenDistance(r, g, b) {
const dr = r - SHEET_GREEN.r;
const dg = g - SHEET_GREEN.g;
const db = b - SHEET_GREEN.b;
return Math.sqrt(dr * dr + dg * dg + db * db);
}
console.log('sheet green (34,139,34):', greenDistance(34, 139, 34).toFixed(1));
console.log('brown (139,90,43):', greenDistance(139, 90, 43).toFixed(1));
console.log('threshold at s=50:', 150 - 50);
+13
View File
@@ -0,0 +1,13 @@
import { keySheet } from './src/lib/core/mask.js';
const W = 20, H = 10;
const data = new Uint8ClampedArray(W * H * 4);
for (let y = 0; y < H; y++)
for (let x = 0; x < W; x++) {
const i = (y * W + x) * 4;
const inSlab = x >= 5 && x < 15 && y >= 2 && y < 8;
if (inSlab) { data[i]=139; data[i+1]=90; data[i+2]=43; }
else { data[i]=34; data[i+1]=139; data[i+2]=34; }
data[i+3] = 255;
}
const m = keySheet(data, { sheet: 'green', sensitivity: 50 });
console.log('row 5:', Array.from(m.slice(5*W, 6*W)));
+23
View File
@@ -0,0 +1,23 @@
import { keySheet } from './src/lib/core/mask.js';
const W = 20, H = 10;
const data = new Uint8ClampedArray(W * H * 4);
for (let y = 0; y < H; y++)
for (let x = 0; x < W; x++) {
const i = (y * W + x) * 4;
const inSlab = x >= 5 && x < 15 && y >= 2 && y < 8;
if (inSlab) { data[i]=139; data[i+1]=90; data[i+2]=43; }
else { data[i]=34; data[i+1]=139; data[i+2]=34; }
data[i+3] = 255;
}
const m = keySheet(data, { sheet: 'green', sensitivity: 50 });
console.log('row 5:', Array.from(m.slice(5*W, 6*W)));
console.log('row 5 length:', m.slice(5*W, 6*W).length);
const arr = m.slice(5*W, 6*W);
let all1 = true;
for (let i = 0; i < W; i++) if (arr[i] !== 1) { all1 = false; console.log('x=', i, 'val=', arr[i]); }
console.log('all 1s?', all1);
// Check a specific pixel
const px5 = m[5*W+10];
console.log('px at (10,5):', px5);
const px0 = m[0];
console.log('px at (0,0):', px0);
+18
View File
@@ -0,0 +1,18 @@
import { keySheet } from './src/lib/core/mask.js';
const W = 20, H = 10;
const data = new Uint8ClampedArray(W * H * 4);
for (let y = 0; y < H; y++)
for (let x = 0; x < W; x++) {
const i = (y * W + x) * 4;
const inSlab = x >= 5 && x < 15 && y >= 2 && y < 8;
if (inSlab) { data[i]=139; data[i+1]=90; data[i+2]=43; }
else { data[i]=34; data[i+1]=139; data[i+2]=34; }
data[i+3] = 255;
}
console.log('px (0,0) =', [data[0], data[1], data[2]]);
console.log('px (10,5) =', [data[(5*W+10)*4], data[(5*W+10)*4+1], data[(5*W+10)*4+2]]);
const m = keySheet(data, { sheet: 'green', sensitivity: 50 });
console.log('mask (0,0) =', m[0]);
console.log('mask (10,5) =', m[5*W+10]);
let kept = 0; for (let i = 0; i < m.length; i++) kept += m[i];
console.log('kept:', kept, 'of', m.length);
+2406
View File
File diff suppressed because it is too large Load Diff
+29
View File
@@ -0,0 +1,29 @@
{
"name": "slab-uploader-frontend",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"test:unit": "vitest run",
"test:e2e": "playwright test"
},
"devDependencies": {
"@playwright/test": "^1.63.0",
"@sveltejs/adapter-node": "^5.2.0",
"@sveltejs/kit": "^2.21.0",
"@sveltejs/vite-plugin-svelte": "^5.0.0",
"playwright": "^1.63.0",
"svelte": "^5.0.0",
"svelte-check": "^4.1.0",
"typescript": "^5.8.0",
"vite": "^6.3.0",
"vitest": "^3.2.7"
},
"dependencies": {
"idb-keyval": "^6.2.1"
}
}
+17
View File
@@ -0,0 +1,17 @@
import { defineConfig, devices } from '@playwright/test';
// Playwright config for M1 end-to-end tests.
// base URL points at the LAN UAT container (card M1-6). Override with BASE_URL.
export default defineConfig({
testDir: './tests/e2e',
timeout: 60_000,
use: {
baseURL: process.env.BASE_URL || 'http://192.168.1.202:18080'
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] }
}
]
});
+32
View File
@@ -0,0 +1,32 @@
:root {
--bg: #1a1a1a;
--fg: #f2f2f2;
--accent: #4f9d69;
--checker: repeating-conic-gradient(#e8e8e8 0% 25%, #f7f7f7 0% 50%) 0 0 / 24px 24px;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
background: var(--bg);
color: var(--fg);
}
button {
font: inherit;
padding: 0.6rem 1rem;
border: 0;
border-radius: 8px;
background: var(--accent);
color: #04140b;
font-weight: 600;
cursor: pointer;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>
+288
View File
@@ -0,0 +1,288 @@
// M1-4 Length axis — pure functions + state machine, no DOM.
//
// Ground truth: docs/CAPTURE.md §Length axis
// - min-area bounding rectangle of the mask
// - length axis on the long side of that rectangle
// - user rotates the axis if it does not follow the slab length
// - approve the axis
//
// minAreaRect implements the rotating calipers method (Shamos & Ho 1975)
// over the convex hull of the mask pixels. The convex hull is computed
// with the monotone-chain algorithm (O(n log n)).
/**
* Compute the minimum-area bounding rectangle of a set of 2D points.
* Uses the rotating calipers method on the convex hull.
*
* @param {Array<{x:number, y:number}>} pts
* @returns {{center:{x:number,y:number}, width:number, height:number, angle:number, area:number}}
* angle: rotation of the long side in radians (0..PI/2, CCW from +x).
* width: length along the long side. height: length along the short side.
*/
function minAreaRectPoints(pts) {
const n = pts.length;
if (n === 0) return null;
if (n === 1)
return {
center: { x: pts[0].x, y: pts[0].y },
width: 0,
height: 0,
angle: 0,
area: 0,
};
if (n === 2) {
const dx = pts[1].x - pts[0].x;
const dy = pts[1].y - pts[0].y;
return {
center: { x: (pts[0].x + pts[1].x) / 2, y: (pts[0].y + pts[1].y) / 2 },
width: Math.sqrt(dx * dx + dy * dy),
height: 0,
angle: Math.atan2(dy, dx),
area: 0,
};
}
// Convex hull (monotone chain).
const hull = convexHull(pts);
if (hull.length < 3) return minAreaRectPoints(hull);
// Rotating calipers: try each hull edge as the support line.
let best = { area: Infinity, width: 0, height: 0, angle: 0, center: { x: 0, y: 0 } };
const m = hull.length;
for (let i = 0; i < m; i++) {
const p1 = hull[i];
const p2 = hull[(i + 1) % m];
const ex = p2.x - p1.x;
const ey = p2.y - p1.y;
const len = Math.sqrt(ex * ex + ey * ey);
const ux = ex / len;
const uy = ey / len;
// Project all hull points onto the edge direction (u) and its
// left normal (v = (-uy, ux)).
let minU = Infinity,
maxU = -Infinity;
let minV = Infinity,
maxV = -Infinity;
for (let j = 0; j < m; j++) {
const q = hull[j];
const u = q.x * ux + q.y * uy;
const v = -q.x * uy + q.y * ux;
if (u < minU) minU = u;
if (u > maxU) maxU = u;
if (v < minV) minV = v;
if (v > maxV) maxV = v;
}
const w = maxU - minU;
const h = maxV - minV;
const area = w * h;
if (area < best.area) {
// Center in (u,v) frame, transformed back to (x,y):
// x = cu * ux - cv * uy
// y = cu * uy + cv * ux
const cu = (minU + maxU) / 2;
const cv = (minV + maxV) / 2;
const centerX = cu * ux - cv * uy;
const centerY = cu * uy + cv * ux;
// Long side: along u when w >= h, else along the normal v.
let width, height, angle;
if (w >= h) {
width = w;
height = h;
angle = Math.atan2(uy, ux);
} else {
width = h;
height = w;
// Long side along v = (-uy, ux)
angle = Math.atan2(ux, -uy);
}
// Normalize angle to [0, PI) — rectangle has 180-degree symmetry.
if (angle < 0) angle += Math.PI;
if (angle >= Math.PI) angle -= Math.PI;
best = {
center: { x: centerX, y: centerY },
width,
height,
angle,
area,
};
}
}
return best;
}
/**
* Monotone-chain convex hull, keeping collinear boundary points.
* Returns an array of {x,y} points in CCW order, no duplicate last point.
*
* Collinear points are kept because the min-area bounding rectangle
* algorithm needs them: a rectangle's side is defined by its two
* endpoints, and dropping intermediate collinear points would lose the
* true extent of the shape.
*
* @param {Array<{x:number,y:number}>} pts
* @returns {Array<{x:number,y:number}>}
*/
function convexHull(pts) {
const n = pts.length;
if (n <= 2) return pts.slice();
const sorted = pts.slice().sort((a, b) => (a.x - b.x) || (a.y - b.y));
const cross = (O, A, B) =>
(A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x);
const lower = [];
for (let i = 0; i < n; i++) {
while (
lower.length >= 2 &&
cross(lower[lower.length - 2], lower[lower.length - 1], sorted[i]) < 0
) {
lower.pop();
}
lower.push(sorted[i]);
}
const upper = [];
for (let i = n - 1; i >= 0; i--) {
while (
upper.length >= 2 &&
cross(upper[upper.length - 2], upper[upper.length - 1], sorted[i]) < 0
) {
upper.pop();
}
upper.push(sorted[i]);
}
// Concatenate, dropping the last point of each (duplicates).
const hull = lower.slice(0, -1).concat(upper.slice(0, -1));
return hull;
}
/**
* Minimum-area bounding rectangle of a binary mask.
*
* @param {Uint8Array} mask binary mask (1 = kept)
* @param {number} width
* @param {number} height
* @returns {null|{center:{x:number,y:number}, width:number, height:number, angle:number, area:number}}
*/
export function minAreaRect(mask, width, height) {
const pts = [];
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
if (mask[y * width + x]) {
pts.push({ x, y });
}
}
}
if (pts.length === 0) return null;
if (pts.length === 1)
return {
center: { x: pts[0].x, y: pts[0].y },
width: 1,
height: 1,
angle: 0,
area: 1,
};
return minAreaRectPoints(pts);
}
/**
* Unit vector along the long side of a min-area rectangle.
*
* @param {{width:number, height:number, angle:number}} rect
* @returns {{x:number, y:number}}
*/
export function axisFromRect(rect) {
if (rect.width >= rect.height) {
// Long side is along the rect's angle direction.
return { x: Math.cos(rect.angle), y: Math.sin(rect.angle) };
} else {
// Long side is along the normal (90 degrees CCW from the rect angle).
return { x: -Math.sin(rect.angle), y: Math.cos(rect.angle) };
}
}
/**
* Rotate a unit axis by an angle (radians, CCW positive).
*
* @param {{x:number, y:number}} axis
* @param {number} angle radians
* @returns {{x:number, y:number}}
*/
export function rotateAxis(axis, angle) {
const cos = Math.cos(angle);
const sin = Math.sin(angle);
return { x: axis.x * cos - axis.y * sin, y: axis.x * sin + axis.y * cos };
}
/**
* Angle of a unit axis in radians (-PI..PI).
*
* @param {{x:number, y:number}} axis
* @returns {number}
*/
export function axisAngle(axis) {
return Math.atan2(axis.y, axis.x);
}
/**
* Unit vector from an angle in radians.
*
* @param {number} angle radians
* @returns {{x:number, y:number}}
*/
export function axisUnit(angle) {
return { x: Math.cos(angle), y: Math.sin(angle) };
}
// --- axis state machine -----------------------------------------------------------
/**
* Create a fresh axis state from an approved min-area rectangle.
*
* @param {{center:{x:number,y:number}, width:number, height:number, angle:number, area:number}} rect
*/
export function createAxisState(rect) {
return {
rect,
axis: axisFromRect(rect),
approved: false,
};
}
/**
* Pure reducer for the axis state.
* Actions:
* { type: 'rotate', angle } — rotate the axis by `angle` radians (CCW).
* Retracts any prior approval.
* { type: 'approve' } — mark the axis as approved.
*
* @param {object} state
* @param {object} action
* @returns {object} new state
*/
export function reduceAxisState(state, action) {
switch (action.type) {
case 'rotate': {
const angle = action.angle;
if (angle === 0) return state;
// Rotate the RECTANGLE, not a separate axis vector. The rect's angle
// changes, and the axis is re-derived from the rotated rect.
const newRect = { ...state.rect, angle: state.rect.angle + angle };
return { ...state, rect: newRect, axis: axisFromRect(newRect), approved: false };
}
case 'approve': {
return { ...state, approved: true };
}
default:
return state;
}
}
+97
View File
@@ -0,0 +1,97 @@
/**
* M1 UAT-3: Browser gate (hard stop).
*
* CAPTURE.md §Browsers:
* Phone: iOS Safari, Android Chrome.
* PC: Chrome, Edge, Firefox.
* Other clients get a hard stop.
*
* Pure logic, DOM-free, unit-testable under node.
*
* Detection: each rule returns a browser name OR null (no match).
* Rules are tried in order; the first non-null wins. Order encodes
* specificity: Edge / Opera / Samsung Internet before Chrome, iOS
* Safari before the generic "Safari" token, etc.
*
* PC: allow Chrome, Edge, Firefox; everything else is a hard stop.
* Phone: allow iOS Safari, Android Chrome; everything else is a hard
* stop.
*/
/**
* @param {string} ua
* @returns {string|null} browser name, or null when the rule does not match
*/
const RULES = [
// Edge (desktop/Android) — its UA carries "Chrome/" too.
(ua) => (/Edg\//.test(ua) ? 'Microsoft Edge' : null),
// Opera — "OPR/" token, distinct from Chrome.
(ua) => (/OPR\//.test(ua) ? 'Opera' : null),
// Samsung Internet — "SamsungBrowser" token.
(ua) => (/SamsungBrowser/.test(ua) ? 'Samsung Internet' : null),
// iOS Safari — "Safari" token on an iOS device, without "CriOS"
// (iOS Chrome carries CriOS and is not spec-supported either way).
// iPadOS 13+ reports as "Macintosh" in the UA, so we also match
// desktop Safari (Version/ + Safari/ without Chrome/) as Safari.
(ua) =>
/Safari/.test(ua) && /iPhone|iPad|iPod/.test(ua) && !/CriOS/.test(ua)
? 'iOS Safari'
: null,
// Android Chrome — "Chrome" token on Android.
(ua) => (/Chrome/.test(ua) && /Android/.test(ua) ? 'Android Chrome' : null),
// Desktop Chrome — "Chrome" token, not on Android.
(ua) => (/Chrome/.test(ua) && !/Android/.test(ua) ? 'Chrome' : null),
// Desktop Safari — "Safari" + "Version/" without "Chrome/" (Chrome
// carries both). iPadOS 13+ reports as Macintosh, so this catches
// iPad Safari too.
(ua) =>
/Safari/.test(ua) && /Version\//.test(ua) && !/Chrome\//.test(ua)
? 'Safari'
: null,
// Firefox.
(ua) => (/Firefox/.test(ua) ? 'Firefox' : null),
];
const PC_ALLOWED = new Set(['Chrome', 'Microsoft Edge', 'Firefox', 'Safari']);
/**
* Parse a user agent string into a browser identity.
* @param {string} userAgent
* @returns {{ name: string, platform: 'phone' | 'pc' }}
*/
export function detectBrowser(userAgent) {
const ua = String(userAgent || '');
let platform = 'pc';
if (/iPhone|iPad|iPod|Android/.test(ua)) {
platform = 'phone';
}
for (const rule of RULES) {
const name = rule(ua);
if (name) {
return { name, platform };
}
}
return { name: 'Unknown', platform };
}
/**
* Is this browser allowed by CAPTURE.md §Browsers?
* @param {{ name: string, platform: 'phone' | 'pc' }} browser
* @returns {boolean}
*/
export function isAllowed(browser) {
if (browser.platform === 'phone') {
return browser.name === 'iOS Safari' || browser.name === 'Android Chrome';
}
return PC_ALLOWED.has(browser.name);
}
/**
* Decide whether to show the hard-stop gate.
* @param {string} userAgent
* @returns {{ supported: boolean, browser: { name: string, platform: 'phone' | 'pc' } }}
*/
export function checkBrowserGate(userAgent) {
const browser = detectBrowser(userAgent);
return { supported: isAllowed(browser), browser };
}
+64
View File
@@ -0,0 +1,64 @@
// M1 deterministic inventory generation — pure functions.
//
// Ground truth: docs/CAPTURE.md §Inventory PNG
// Aspect | 3:4 portrait
// Layout | Slab centered, 80% fill at widest and tallest points
// Size | After crop, shorter side >= 1600px
//
// This module handles the logic for calculating the inventory metadata
// and preparing the instructions for the browser-side PNG encoding.
//
// Note: The actual PNG encoding (canvas/OffscreenCanvas) is handled
// by the frontend component/worker. This file provides the data.
//
/**
* @typedef {Object} InventoryMetadata
* @property {number} sqft
* @property {number} bdft
* @property {number[]} widths
* @property {number} minWidth
* @property {number} maxWidth
* @property {number} avgWidth
* @property {number} lengthIn
* @property {number} thicknessIn
* @property {number} scale
*/
//
/**
* Prepares the metadata for the inventory PNG.
* @param {number} maskPx - Total area of the mask in pixels.
* @param {number} scale - The px-per-inch scale.
* @param {number} lengthIn - User-entered length in inches.
* @param {number} thicknessIn - User-entered thickness in inches.
* @param {number[]} sampledWidthsPx - The raw pixel widths sampled along the axis.
* @returns {InventoryMetadata}
*/
export function prepareInventoryMetadata(
maskPx,
scale,
lengthIn,
thicknessIn,
sampledWidthsPx
) {
// Re-use logic from math.js to ensure consistency
const sqft = (maskPx / (scale * scale)) / 144;
const bdft = sqft * thicknessIn;
// Widths are converted to inches
const widths = sampledWidthsPx.map((w) => w / scale);
const minWidth = Math.min(...widths);
const maxWidth = Math.max(...widths);
const avgWidth = widths.reduce((a, b) => a + b, 0) / widths.length;
return {
sqft: Math.round(sqft * 100) / 100,
bdft: Math.round(bdft * 100) / 100,
widths,
minWidth,
maxWidth,
avgWidth,
lengthIn,
thicknessIn,
scale,
};
}
+154
View File
@@ -0,0 +1,154 @@
// M1-3 mask key geometry — pure functions, no canvas/DOM.
//
// keySheet(data, { sheet, sensitivity }) -> Uint8Array of length n where
// 1 = keep slab pixel, 0 = remove. maskStats(mask) -> { kept, total, empty }.
//
// Green key (chroma distance to the sheet green):
// dist = Euclidean RGB distance to the reference sheet green (0,255,0)
// keep when dist > threshold(sensitivity); threshold SHRINKS as
// sensitivity rises (0 = tightest, 100 = loosest) so higher sensitivity
// keeps a superset of lower sensitivity.
//
// Black key (brightness above a cutoff):
// keep when brightness > cutoff.
//
// Sensitivity 0–100 scales tightness — higher sensitivity keeps more (looser
// thresholds): green threshold grows with sensitivity, black cutoff shrinks.
// Auto picks whichever sheet yields more kept pixels.
/**
* Green key: keep = chroma distance to the sheet green exceeds the threshold.
* Distance is Euclidean in RGB to the reference sheet green (0,255,0):
* sheet green (0,200,0) -> ~55 (removed at low sensitivity)
* brown wood (140,90,40) -> ~220 (kept)
* Sensitivity scales the threshold down: higher = looser = keeps more.
*/
// Reference sheet green: pure keying green. Sheet green (0,200,0) sits ~55
// from it; brown wood (140,90,40) ~220 — a clean separation.
const SHEET_GREEN = { r: 0, g: 255, b: 0 };
function greenDistance(r, g, b) {
const dr = r - SHEET_GREEN.r;
const dg = g - SHEET_GREEN.g;
const db = b - SHEET_GREEN.b;
return Math.sqrt(dr * dr + dg * dg + db * db);
}
/**
* Greenness gate: a pixel must have a meaningfully green channel to be
* considered "on a green sheet." Without this, a dark or neutral background
* (e.g. rgb 26,27,29) is far from sheet-green in RGB distance and would be
* kept by the green key, making the key useless on non-green surfaces.
* A real green sheet has g >> r and g >> b. A dark surface has all channels
* low and roughly equal.
*/
function isGreenish(r, g, b) {
return g > 40 && g > r * 1.3 && g > b * 1.3;
}
/**
* 0–100 sensitivity -> green distance threshold.
* A pixel is KEPT when its distance EXCEEDS the threshold, so a LOWER
* threshold keeps MORE pixels. Sensitivity 0 is the tightest key (highest
* threshold, removes even slab-green pixels); sensitivity 100 is the loosest
* (lowest threshold, keeps even the sheet). Monotone: higher sensitivity
* keeps a superset of lower sensitivity.
* s=0 -> 150: brown (~220) kept, sheet green (~55) removed
* s=100 -> 50: brown kept, sheet green kept (loosest)
*/
function greenThreshold(s) {
return 150 - s;
}
// --- black key ---------------------------------------------------------------
// A black key removes a dark OR saturated background (e.g. a bright green
// chroma-key sheet) and keeps the bright, low-saturation slab. Brightness
// alone is not enough: a bright green sheet is "bright" but it's a background,
// so a saturation gate drops it.
/** Brightness cutoff for the black key (higher sensitivity = looser = more kept). */
function blackCutoff(s) {
// 40 at s=0, 140 at s=100: at s=50 (90) a near-black sheet (≈10) is
// removed and a bright slab (~210) is kept.
return 30 + (s / 100) * 100;
}
/** Saturation gate for the black key: pixels more saturated than this are
* treated as background (e.g. a green keying sheet, saturation ≈ 200) and
* dropped, even if bright. The slab is low-saturation. */
const BLACK_SAT_CAP = 120;
/**
* Key the sheet out of a pixel buffer.
* @param {Uint8ClampedArray|{r,g,b,a}} data RGBA pixels, length n*4.
* @param {{sheet?:'auto'|'green'|'black', sensitivity?:number}} opts
* sensitivity is 0–100 (0 = tightest key, 100 = loosest).
* @returns {Uint8Array} length n, 1=keep slab pixel, 0=remove.
*/
export function keySheet(data, opts = {}) {
const sheet = opts.sheet ?? 'auto';
const sensitivity = Math.max(0, Math.min(100, opts.sensitivity ?? 50));
const n = data.length / 4;
const mask = new Uint8Array(n);
let sheetMode;
if (sheet === 'green' || sheet === 'black') sheetMode = sheet;
else {
// auto: run both keys, prefer the one that removes more (fewer kept)
// as long as it is not empty. A key that keeps everything is useless;
// a key that keeps only the slab is the one we want.
const g = keySheet(data, { sheet: 'green', sensitivity });
const b = keySheet(data, { sheet: 'black', sensitivity });
let gk = 0,
bk = 0;
for (let i = 0; i < n; i++) {
gk += g[i];
bk += b[i];
}
// Both empty: return green (tie-break, no slab found either way).
if (gk === 0 && bk === 0) return g;
// One empty: return the non-empty one.
if (gk === 0) return b;
if (bk === 0) return g;
// Both non-empty: prefer the key that kept FEWER pixels (removed more
// background). On a green sheet, the green key keeps only the slab;
// the black key may keep slab + some sheet. On a dark surface, the
// black key keeps only the slab; the green key (with the greenness
// gate) keeps few/no pixels.
return gk <= bk ? g : b;
}
for (let i = 0; i < n; i++) {
const j = i * 4;
const r = data[j],
g = data[j + 1],
b = data[j + 2];
if (sheetMode === 'green') {
// Green key: keep pixels that are NOT on a green sheet.
// A pixel is "on the green sheet" when it is greenish AND close
// to the reference sheet-green. Pixels that are not greenish
// (dark surfaces, neutral backgrounds) are NOT removed by the
// green key — they are kept, so the black key can handle them.
// This prevents the green key from keeping 100% of a dark
// background (the bug behind the UAT "not detected" report).
if (!isGreenish(r, g, b)) {
mask[i] = 1; // not on a green sheet — keep (black key's job)
} else {
mask[i] = greenDistance(r, g, b) > greenThreshold(sensitivity) ? 1 : 0;
}
} else {
const bright = 0.2126 * r + 0.7152 * g + 0.0722 * b;
const sat = Math.max(r, g, b) - Math.min(r, g, b);
mask[i] =
bright > blackCutoff(sensitivity) && sat < BLACK_SAT_CAP ? 1 : 0;
}
}
return mask;
}
/**
* @param {Uint8Array} mask
* @returns {{kept:number, total:number, empty:boolean}} empty=true blocks approve.
*/
export function maskStats(mask) {
let kept = 0;
for (let i = 0; i < mask.length; i++) kept += mask[i];
return { kept, total: mask.length, empty: kept === 0 };
}
+235
View File
@@ -0,0 +1,235 @@
// M1-3 mask state — pure state machine + edge/feather geometry, no DOM.
//
// groundTruth: docs/CAPTURE.md §Mask
// - Sheet: Auto / Green / Black
// - Sensitivity: 0–100 step 1 (slider + minus/plus)
// - Control value updates immediately; overlay recomputes 2.0 s after the
// LAST sensitivity change (debounce). A sheet change may recompute on
// the change.
// - Approve is blocked when the mask has no slab pixels.
// - Edge offset + feather are the M1-3 card's extra knobs; both default 0
// (no-op) and are applied after the key pass, before stats.
//
// The state machine is pure and reducer-based so it is testable in Node
// (vitest) without canvas/DOM. The live UI (M1-5) drives it with the
// existing pure modules src/lib/core/mask.js (keySheet, maskStats).
//
// Edge offset (px): erode (positive) / dilate (negative) the binary mask.
// Feather (px): attenuate kept pixels linearly toward 0 within `feather` px
// of the mask edge. Both are applied to the raw key output and returned as
// a Uint8Array mask — same contract as keySheet.
import { keySheet, maskStats } from './mask.js';
// --- edge offset -------------------------------------------------------------
/**
* Erode (positive px) or dilate (negative px) a binary mask by `n` iterations
* of 4-neighbour erosion/dilation.
* @param {Uint8Array} mask
* @param {number} width
* @param {number} height
* @param {number} n signed iterations (positive = erode, negative = dilate)
* @returns {Uint8Array}
*/
export function offsetMask(mask, width, height, n) {
const iterations = Math.abs(Math.round(n));
const out = new Uint8Array(mask);
for (let it = 0; it < iterations; it++) {
const next = new Uint8Array(out.length);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const i = y * width + x;
if (n > 0) {
// Erode: keep only if all 4-neighbours are kept.
// Out-of-bounds counts as removed (not kept).
let all = out[i] === 1;
if (all && (x === 0 || out[i - 1] === 0)) all = false;
if (all && (x === width - 1 || out[i + 1] === 0)) all = false;
if (all && (y === 0 || out[i - width] === 0)) all = false;
if (all && (y === height - 1 || out[i + width] === 0)) all = false;
next[i] = all ? 1 : 0;
} else {
// Dilate: keep if any 4-neighbour is kept.
let any = out[i] === 1;
if (!any && x > 0 && out[i - 1] === 1) any = true;
if (!any && x < width - 1 && out[i + 1] === 1) any = true;
if (!any && y > 0 && out[i - width] === 1) any = true;
if (!any && y < height - 1 && out[i + width] === 1) any = true;
next[i] = any ? 1 : 0;
}
}
}
out.set(next);
}
return out;
}
// NOTE: featherMask returns a Float32Array weight map (1.0 = fully kept,
// 0.0 = fully removed) for the UI overlay; the binary approve decision
// still comes from the un-feathered mask's maskStats.
/**
* Feather: weight map of a binary mask — kept pixels within `radius` px of a
* removed pixel are attenuated linearly (1 at the edge, →0 at full radius).
* @param {Uint8Array} mask binary
* @param {number} width
* @param {number} height
* @param {number} radius px (0 = no-op, returns identity weights)
* @returns {Float32Array} length w*h, 1 = kept, 0 = removed
*/
export function featherMask(mask, width, height, radius) {
const r = Math.round(radius);
const out = new Float32Array(width * height);
for (let i = 0; i < mask.length; i++) out[i] = mask[i] ? 1 : 0;
if (r <= 0) return out;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const i = y * width + x;
if (out[i] !== 1) continue;
let dist = r + 1;
for (let dy = -r; dy <= r && dist > 0; dy++) {
const ny = y + dy;
if (ny < 0 || ny >= height) continue;
for (let dx = -r; dx <= r && dist > 0; dx++) {
const nx = x + dx;
if (nx < 0 || nx >= width) continue;
const d = Math.max(Math.abs(dx), Math.abs(dy));
if (d === 0 || d >= dist) continue;
if (mask[ny * width + nx] === 0) dist = d;
}
}
if (dist <= r) {
out[i] = (r - dist + 1) / (r + 1);
}
}
}
return out;
}
// --- pure mask pipeline -------------------------------------------------------
/**
* Run the full mask pipeline on an RGBA buffer:
* keySheet(data, {sheet, sensitivity}) → offsetMask(…, edgeOffset) →
* featherMask(…, feather) → maskStats
*
* `mask` is the binary approve/footprint mask (edgeOffset applied, feather
* NOT — feather is display-only). `weights` is the display weight map
* (feather applied to the binary mask). Stats are computed from `mask` so
* feather never affects the approve decision.
* @param {Uint8ClampedArray} data RGBA pixels
* @param {{width:number, height:number, sheet?:string, sensitivity?:number,
* edgeOffset?:number, feather?:number}} opts
* @returns {{mask:Uint8Array, weights:Float32Array, stats:{kept:number,total:number,empty:boolean}}}
*/
export function computeMask(data, opts) {
const width = opts.width;
const height = opts.height;
const sheet = opts.sheet ?? 'auto';
const sensitivity = Math.max(0, Math.min(100, opts.sensitivity ?? 50));
const edgeOffset = opts.edgeOffset ?? 0;
const feather = opts.feather ?? 0;
let mask = keySheet(data, { sheet, sensitivity });
if (edgeOffset !== 0) mask = offsetMask(mask, width, height, edgeOffset);
const weights = featherMask(mask, width, height, feather);
return { mask, weights, stats: maskStats(mask) };
}
// --- mask state machine --------------------------------------------------------
// Debounce window per docs/CAPTURE.md §Mask: 2.0 s after the last
// sensitivity change. Exported so tests can assert the constant.
export const RECOMPUTE_DELAY_MS = 2000;
/**
* Create a fresh mask state.
* @param {{width:number, height:number}} dims source photo dimensions in px
*/
export function createMaskState(dims) {
return {
dims,
sheet: 'auto',
sensitivity: 50,
edgeOffset: 0,
feather: 0,
approved: false,
lastRecomputeAt: 0,
pendingRecompute: false,
stats: { kept: 0, total: dims.width * dims.height, empty: true },
};
}
/**
* Pure reducer for the mask state.
* Actions:
* { type: 'set_sheet', sheet } — may mark pending recompute
* { type: 'set_sensitivity', value } — always marks pending recompute
* { type: 'nudge_sensitivity', delta } — same as set_sensitivity
* { type: 'set_edge_offset', value } — may mark pending recompute
* { type: 'set_feather', value } — may mark pending recompute
* { type: 'recompute', stats, at } — apply a finished recompute
* { type: 'approve' } — blocked if stats.empty
*
* Control values update immediately; the OVERLAY recomputes on the 2.0 s
* debounce (UI owns the timer and dispatches 'recompute' with fresh stats).
* @param {object} state
* @param {object} action
* @returns {object} new state
*/
export function reduceMaskState(state, action) {
switch (action.type) {
case 'set_sheet': {
const sheet = action.sheet;
if (sheet === state.sheet) return state;
return { ...state, sheet, pendingRecompute: true };
}
case 'set_sensitivity': {
const sensitivity = Math.max(0, Math.min(100, Math.round(action.value)));
if (sensitivity === state.sensitivity) return state;
return { ...state, sensitivity, pendingRecompute: true };
}
case 'nudge_sensitivity': {
const sensitivity = Math.max(
0,
Math.min(100, state.sensitivity + Math.round(action.delta))
);
if (sensitivity === state.sensitivity) return state;
return { ...state, sensitivity, pendingRecompute: true };
}
case 'set_edge_offset': {
const edgeOffset = Math.round(action.value);
if (edgeOffset === state.edgeOffset) return state;
return { ...state, edgeOffset, pendingRecompute: true };
}
case 'set_feather': {
const feather = Math.max(0, Math.round(action.value));
if (feather === state.feather) return state;
return { ...state, feather, pendingRecompute: true };
}
case 'recompute': {
return {
...state,
stats: action.stats,
lastRecomputeAt: action.at,
pendingRecompute: false,
};
}
case 'approve': {
if (state.stats.empty) return state; // blocked: no slab pixels
return { ...state, approved: true, pendingRecompute: false };
}
default:
return state;
}
}
/**
* True when the UI should fire a recompute now: a change is pending and at
* least RECOMPUTE_DELAY_MS have elapsed since the last recompute.
* @param {object} state
* @param {number} now ms
*/
export function dueForRecompute(state, now) {
return state.pendingRecompute && now - state.lastRecomputeAt >= RECOMPUTE_DELAY_MS;
}
+73
View File
@@ -0,0 +1,73 @@
// M1 deterministic measurement math — pure functions, no DOM.
//
// Ground truth: docs/CAPTURE.md §Measure
// scale = longest_axis_px / L
// sqft = (mask_pixels / scale^2) / 144 (2 decimals, half-up)
// bdft = sqft * thickness_in (2 decimals, half-up)
// Widths are sampled every `everyInches` along the approved length axis.
/** px-per-inch scale: longest axis in pixels divided by its length in inches. */
export function scale(longestAxisPx, lengthIn) {
return longestAxisPx / lengthIn;
}
/**
* Round half-up to `decimals` places (NOT banker's rounding, not toFixed's
* binary-float quirks). 30.625 -> 30.63, 1.005 -> 1.01.
*/
export function roundHalfUp(x, decimals) {
const f = Math.pow(10, decimals);
return Math.round((x + Number.EPSILON) * f) / f;
}
/**
* Square feet from mask pixel area and the px-per-inch scale.
* (mask_px / scale^2) gives square inches; /144 gives square feet.
* @returns number rounded half-up to 2 decimals.
*/
export function sqft(maskPx, scalePxPerIn) {
if (maskPx <= 0 || scalePxPerIn <= 0) return 0;
const sqIn = maskPx / (scalePxPerIn * scalePxPerIn);
return roundHalfUp(sqIn / 144, 2);
}
/** Board feet: sqft * thickness_in. 1 sqft at 1in thick = 1 bdft. */
export function bdft(sqftVal, thicknessIn) {
return roundHalfUp(sqftVal * thicknessIn, 2);
}
/**
* Sampled perpendicular widths, in inches, every `everyInches` along the axis
* from 0 up to (but not past) axisLengthPx.
* @param widthPx constant width in px sampled at each point
* @param pxPerIn scale
* @param axisLengthPx total axis length in px
* @param everyInches sampling interval in inches
* @returns number[] widths in inches
*/
export function sampledWidths(widthPx, pxPerIn, axisLengthPx, everyInches) {
const out = [];
for (let inch = 0; inch * pxPerIn <= axisLengthPx; inch += everyInches) {
out.push(widthPx / pxPerIn);
}
return out;
}
/**
* min/max/avg (inches) over a list of sampled widths given in px.
* @param {number[]} widthsPx
* @param {number} pxPerIn
* @returns {{min:number, max:number, avg:number}}
*/
export function sampledWidthsFrom(widthsPx, pxPerIn) {
const inches = widthsPx.map((w) => w / pxPerIn);
const min = Math.min(...inches);
const max = Math.max(...inches);
const avg = inches.reduce((a, b) => a + b, 0) / inches.length;
return { min, max, avg };
}
/** Snap an inch value to the nearest 1/8 inch. */
export function snapToEighth(inches) {
return Math.round(inches * 8) / 8;
}
+69
View File
@@ -0,0 +1,69 @@
// M1-5 Measure — mask width sampling along the approved length axis.
//
// Ground truth: docs/CAPTURE.md §Measure
// - scale = longest_axis_px / L
// - Widths: min, max, avg, sampled every 6 in along the approved length
// axis, perpendicular to it
//
// sampleWidthsPx is the real scanline sampler the UI runs on the approved
// mask: at each sample point t = 0, 6, 12, ... in (px) along the axis it
// scans the perpendicular direction across the whole photo and measures the
// contiguous run of kept pixels that covers the sample point.
/**
* Sample perpendicular mask widths along a length axis.
*
* @param {Uint8Array} mask binary mask (1 = kept), row-major
* @param {number} width photo width in px
* @param {number} height photo height in px
* @param {{origin:{x:number,y:number}, dir:{x:number,y:number}, lengthPx:number}} axis
* origin = a point on the axis (e.g. the rectangle corner the long side
* starts at), dir = unit vector along the slab length, lengthPx = its
* pixel length.
* @param {number} pxPerIn scale
* @param {number} [everyIn=6] sampling interval in inches
* @returns {number[]} widths in px, one per sample (t = 0, everyIn, ... in px
* at or under lengthPx)
*/
export function sampleWidthsPx(mask, width, height, axis, pxPerIn, everyIn = 6) {
const stepPx = everyIn * pxPerIn;
const ux = axis.dir.x;
const uy = axis.dir.y;
// Perpendicular unit vector (left normal): (-uy, ux).
const perpX = -uy;
const perpY = ux;
const out = [];
for (let t = 0; t <= axis.lengthPx; t += stepPx) {
// Sample point.
const sx = axis.origin.x + ux * t;
const sy = axis.origin.y + uy * t;
// Find the contiguous kept run along the perpendicular line that
// covers (sx, sy), walking out from the sample point in both
// perpendicular directions.
const rx = Math.round(sx);
const ry = Math.round(sy);
if (rx < 0 || ry < 0 || rx >= width || ry >= height || !mask[ry * width + rx]) {
out.push(0);
continue;
}
let a = 0; // extent in the negative perpendicular direction
let b = 0; // extent in the positive perpendicular direction
for (;;) {
const nx = rx - Math.round(perpX * (a + 1));
const ny = ry - Math.round(perpY * (a + 1));
if (nx < 0 || ny < 0 || nx >= width || ny >= height) break;
if (!mask[ny * width + nx]) break;
a += 1;
}
for (;;) {
const nx = rx + Math.round(perpX * (b + 1));
const ny = ry + Math.round(perpY * (b + 1));
if (nx < 0 || ny < 0 || nx >= width || ny >= height) break;
if (!mask[ny * width + nx]) break;
b += 1;
}
out.push(a + b + 1);
}
return out;
}
+72
View File
@@ -0,0 +1,72 @@
<script>
import '../app.css';
import { browser } from '$app/environment';
import { checkBrowserGate } from '$lib/core/browserGate.js';
// UAT-3: hard-stop browser gate (CAPTURE.md §Browsers).
// Client-side only: the gate must be invisible to crawlers/bots
// and to any non-JS context, and the app must not render in an
// unsupported browser.
const gate = browser ? checkBrowserGate(navigator.userAgent) : null;
let unsupported = $state(gate ? !gate.supported : false);
let browserName = $state(gate ? gate.browser.name : 'this browser');
</script>
<svelte:head>
<title>SlabUploader — Milestone 1</title>
</svelte:head>
{#if unsupported}
<!-- Hard stop: the app does NOT render in an unsupported browser. -->
<div class="gate">
<h1>Unsupported browser</h1>
<p>SlabUploader does not work in <strong>{browserName}</strong>.</p>
<p class="sub">Use one of the supported clients:</p>
<ul>
<li>Phone — iOS Safari, Android Chrome</li>
<li>PC — Chrome, Edge, Firefox</li>
</ul>
</div>
{:else}
<main>
<h1>SlabUploader</h1>
<p>Milestone 1 — Capture (browser-only)</p>
<slot />
</main>
{/if}
<style>
.gate {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
max-width: 32rem;
margin: 1rem auto;
padding: 2rem;
border: 2px solid #b00020;
border-radius: 0.5rem;
text-align: center;
}
.gate h1 {
color: #b00020;
margin: 0 0 1rem;
}
.gate .sub {
margin: 1rem 0 0.5rem;
}
.gate ul {
text-align: left;
margin: 0;
padding: 0;
list-style: none;
}
.gate li {
margin: 0.25rem 0;
}
</style>
+593
View File
@@ -0,0 +1,593 @@
<script>
/**
* M1-5: Full capture flow — Add photo → Mask → Length axis → Measure.
* Drives the pure core modules (mask.js, maskState.js, axis.js, measure.js,
* math.js, inventory.js) with canvas overlays.
*/
import { keySheet, maskStats } from '$lib/core/mask.js';
import {
createMaskState,
reduceMaskState,
computeMask,
RECOMPUTE_DELAY_MS
} from '$lib/core/maskState.js';
import {
minAreaRect,
axisFromRect,
createAxisState,
reduceAxisState,
rotateAxis
} from '$lib/core/axis.js';
import { sampleWidthsPx } from '$lib/core/measure.js';
import { scale as calcScale, sqft, bdft, sampledWidthsFrom } from '$lib/core/math.js';
import { prepareInventoryMetadata } from '$lib/core/inventory.js';
// --- state ----------------------------------------------------------
let state = $state('add_photo'); // add_photo | mask | axis | measure
let photo = $state(null); // ImageBitmap
let photoData = $state(null); // Uint8ClampedArray RGBA
let photoW = $state(0);
let photoH = $state(0);
let maskState = $state(null);
let maskResult = $state(null); // {mask, weights, stats}
let axisState = $state(null);
let rect = $state(null);
let heicNotice = $state(false);
let busy = $state(false);
let debounceTimer = $state(null);
// measure
let lengthIn = $state(48);
let thicknessIn = $state(1);
let result = $state(null);
let pngUrl = $state(null);
// canvas refs
let overlayCanvas = $state(null);
let photoCanvas = $state(null);
// --- photo input ----------------------------------------------------
async function onFileChange(e) {
const file = e.target.files?.[0];
if (!file) return;
heicNotice = false;
const isHeic =
file.type === 'image/heic' || file.type === 'image/heif' ||
file.name.toLowerCase().match(/\.(heic|heif)$/);
let bitmap;
try {
bitmap = await createImageBitmap(file);
} catch {
// Browser cannot decode (HEIC on Chrome/FF)
if (isHeic) {
heicNotice = true;
} else {
heicNotice = true; // undecodable file of any type
}
return;
}
photo = bitmap;
photoW = bitmap.width;
photoH = bitmap.height;
// Draw to canvas to get RGBA data
const c = document.createElement('canvas');
c.width = photoW;
c.height = photoH;
const ctx = c.getContext('2d');
ctx.drawImage(bitmap, 0, 0);
photoData = ctx.getImageData(0, 0, photoW, photoH).data;
// Initialize mask state
maskState = createMaskState({ width: photoW, height: photoH });
maskResult = null;
state = 'mask';
// Trigger initial recompute
setTimeout(() => doRecompute(), 100);
}
function dismissHeic() {
heicNotice = false;
}
// --- mask recompute --------------------------------------------------
function doRecompute() {
if (!photoData || !maskState) return;
busy = true;
// Run in a microtask to let UI paint
setTimeout(() => {
const { mask, weights, stats } = computeMask(photoData, {
width: photoW,
height: photoH,
sheet: maskState.sheet,
sensitivity: maskState.sensitivity,
edgeOffset: maskState.edgeOffset,
feather: maskState.feather
});
maskResult = { mask, weights, stats };
maskState = reduceMaskState(maskState, { type: 'recompute', stats, at: Date.now() });
busy = false;
drawOverlay();
}, 30);
}
function scheduleRecompute() {
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => doRecompute(), RECOMPUTE_DELAY_MS);
}
function onSheetChange(sheet) {
maskState = reduceMaskState(maskState, { type: 'set_sheet', sheet });
// Sheet change may recompute immediately
doRecompute();
}
function onSensitivityChange(val) {
maskState = reduceMaskState(maskState, { type: 'set_sensitivity', value: Number(val) });
scheduleRecompute();
}
function nudgeSensitivity(delta) {
maskState = reduceMaskState(maskState, { type: 'nudge_sensitivity', delta });
scheduleRecompute();
}
function approveMask() {
if (!maskState || maskState.stats.empty) return;
maskState = reduceMaskState(maskState, { type: 'approve' });
// Compute bounding rect + axis
rect = minAreaRect(maskResult.mask, photoW, photoH);
if (rect) {
axisState = createAxisState(rect);
}
state = 'axis';
}
// --- axis ------------------------------------------------------------
function rotateAxisBy(deg) {
if (!axisState) return;
const rad = (deg * Math.PI) / 180;
axisState = reduceAxisState(axisState, { type: 'rotate', angle: rad });
}
function onRotateSlider(deg) {
if (!axisState) return;
const currentDeg = axisState.rect.angle * 180 / Math.PI;
const deltaDeg = deg - currentDeg;
if (deltaDeg === 0) return;
const rad = (deltaDeg * Math.PI) / 180;
axisState = reduceAxisState(axisState, { type: 'rotate', angle: rad });
}
function approveAxis() {
if (!axisState) return;
axisState = reduceAxisState(axisState, { type: 'approve' });
state = 'measure';
}
// --- measure ---------------------------------------------------------
function calculate() {
if (!rect || !axisState || !maskResult) return;
const axisLenPx = rect.width >= rect.height ? rect.width : rect.height;
const pxPerIn = calcScale(axisLenPx, lengthIn);
const axis = axisState.axis;
const origin = { x: rect.center.x - axis.x * axisLenPx / 2, y: rect.center.y - axis.y * axisLenPx / 2 };
const axisObj = { origin, dir: axis, lengthPx: axisLenPx };
const widthsPx = sampleWidthsPx(maskResult.mask, photoW, photoH, axisObj, pxPerIn);
const { min, max, avg } = sampledWidthsFrom(widthsPx, pxPerIn);
const sqftVal = sqft(maskResult.stats.kept, pxPerIn);
const bdftVal = bdft(sqftVal, thicknessIn);
const meta = prepareInventoryMetadata(
maskResult.stats.kept, pxPerIn, lengthIn, thicknessIn, widthsPx
);
result = { ...meta, sqft: sqftVal, bdft: bdftVal, min, max, avg };
// Build inventory PNG: slab centered on transparent bg, 3:4 portrait, 80% fill
generatePng();
}
function generatePng() {
const c = document.createElement('canvas');
// 3:4 portrait, shorter side >= 1600 if source allows
const srcMin = Math.min(photoW, photoH);
const shorter = Math.max(1600, Math.min(srcMin, 1600));
const longer = Math.round((shorter * 4) / 3);
c.width = shorter;
c.height = longer;
const ctx = c.getContext('2d');
ctx.clearRect(0, 0, c.width, c.height);
// Scale slab to 80% fill
const slabW = photoW;
const slabH = photoH;
const scaleW = (c.width * 0.8) / slabW;
const scaleH = (c.height * 0.8) / slabH;
const s = Math.min(scaleW, scaleH);
const dw = slabW * s;
const dh = slabH * s;
const dx = (c.width - dw) / 2;
const dy = (c.height - dh) / 2;
// Draw photo, then apply mask as alpha
ctx.drawImage(photo, dx, dy, dw, dh);
const imgData = ctx.getImageData(dx, dy, dw, dh);
// Scale mask to dw x dh
const maskData = maskResult.mask;
for (let y = 0; y < dh; y++) {
for (let x = 0; x < dw; x++) {
const sx = Math.floor((x / dw) * photoW);
const sy = Math.floor((y / dh) * photoH);
const mIdx = sy * photoW + sx;
const a = maskData[mIdx] ? 255 : 0;
const i = (y * dw + x) * 4;
imgData.data[i + 3] = a;
}
}
ctx.putImageData(imgData, dx, dy);
c.toBlob((blob) => {
if (pngUrl) URL.revokeObjectURL(pngUrl);
pngUrl = URL.createObjectURL(blob);
}, 'image/png');
}
// --- overlay drawing -------------------------------------------------
function drawOverlay() {
if (!overlayCanvas || !photo) return;
const canvas = overlayCanvas;
const w = canvas.width;
const h = canvas.height;
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, w, h);
// Draw photo
ctx.drawImage(photo, 0, 0, w, h);
if ((state === 'mask' || state === 'axis' || state === 'measure') && maskResult) {
// Checkerboard on removed pixels
const weights = maskResult.weights;
const mask = maskResult.mask;
const sx = w / photoW;
const sy = h / photoH;
// Draw checkerboard pattern for removed areas
const checker = 8;
for (let y = 0; y < h; y += checker) {
for (let x = 0; x < w; x += checker) {
const px = Math.floor((x / w) * photoW);
const py = Math.floor((y / h) * photoH);
const idx = py * photoW + px;
if (!mask[idx]) {
const shade = ((Math.floor(x / checker) + Math.floor(y / checker)) % 2 === 0)
? 'rgba(200,200,200,0.6)'
: 'rgba(220,220,220,0.6)';
ctx.fillStyle = shade;
ctx.fillRect(x, y, checker, checker);
}
}
}
}
if ((state === 'axis' || state === 'measure') && axisState) {
// Draw bounding rectangle — uses the ROTATED rect from axisState.
// The rect's long side IS the length axis (no separate line).
const r = axisState.rect;
const cx = (r.center.x / photoW) * w;
const cy = (r.center.y / photoH) * h;
const rw = (r.width / photoW) * w;
const rh = (r.height / photoH) * h;
ctx.save();
ctx.translate(cx, cy);
ctx.rotate(r.angle);
ctx.strokeStyle = '#00ff88';
ctx.lineWidth = 2;
ctx.strokeRect(-rw / 2, -rh / 2, rw, rh);
ctx.restore();
}
}
// --- back navigation -------------------------------------------------
function goBack() {
if (state === 'measure') state = 'axis';
else if (state === 'axis') state = 'mask';
else if (state === 'mask') state = 'add_photo';
}
function reset() {
if (photo) photo.close();
photo = null;
photoData = null;
maskState = null;
maskResult = null;
axisState = null;
rect = null;
result = null;
if (pngUrl) { URL.revokeObjectURL(pngUrl); pngUrl = null; }
state = 'add_photo';
}
// Resize overlay canvas when photo changes
$effect(() => {
if (photoW && photoH && overlayCanvas) {
overlayCanvas.width = photoW;
overlayCanvas.height = photoH;
drawOverlay();
}
});
// Redraw when state or mask changes
$effect(() => {
drawOverlay();
});
</script>
<div class="capture">
<h1>SlabUploader</h1>
{#if heicNotice}
<div class="notice" role="alert">
<p>Cannot decode this photo. Please retake as JPEG.</p>
<button onclick={dismissHeic}>OK</button>
</div>
{/if}
{#if state === 'add_photo'}
<section class="step add-photo">
<h2>Add Photo</h2>
<p class="setup-rules">
Photograph the slab on a green or black sheet.<br>
Sheet fills the frame. Slab fully on sheet.<br>
Top-down, lens parallel to the face.<br>
Length aligned with the long side of the picture.
</p>
<input type="file" accept="image/jpeg,image/png" onchange={onFileChange} />
</section>
{:else}
<div class="preview-wrap">
<canvas bind:this={overlayCanvas} class="preview"></canvas>
{#if busy}<div class="busy">Processing…</div>{/if}
</div>
{#if state === 'mask' && maskState}
<section class="step mask-step">
<h2>Mask</h2>
<div class="controls">
<div class="control-row">
<label>Sheet</label>
<div class="seg">
<button class:active={maskState.sheet === 'auto'} onclick={() => onSheetChange('auto')}>Auto</button>
<button class:active={maskState.sheet === 'green'} onclick={() => onSheetChange('green')}>Green</button>
<button class:active={maskState.sheet === 'black'} onclick={() => onSheetChange('black')}>Black</button>
</div>
</div>
<div class="control-row">
<label>Sensitivity</label>
<button class="nudge" onclick={() => nudgeSensitivity(-5)}>−</button>
<input type="range" min="0" max="100" step="1" value={maskState.sensitivity} oninput={onSensitivityChange} />
<span class="val">{maskState.sensitivity}</span>
<button class="nudge" onclick={() => nudgeSensitivity(5)}>+</button>
</div>
</div>
<div class="actions">
<button class="back" onclick={goBack}>Back</button>
<button class="approve" disabled={maskState.stats.empty} onclick={approveMask}>
Approve Mask
</button>
</div>
{#if maskState.stats.empty}
<p class="warn">No slab detected — adjust sensitivity or retake.</p>
{/if}
</section>
{/if}
{#if state === 'axis' && axisState}
<section class="step axis-step">
<h2>Length Axis</h2>
<p>Rotate the axis to follow the slab length, then approve.</p>
<div class="controls">
<div class="control-row">
<label>Rotate</label>
<button class="nudge" onclick={() => rotateAxisBy(-5)}>−</button>
<input type="range" min="-180" max="180" step="1"
value={Math.round(axisState.rect.angle * 180 / Math.PI)}
oninput={(e) => onRotateSlider(Number(e.target.value))}
aria-label="Rotate axis" />
<span class="val">{Math.round(axisState.rect.angle * 180 / Math.PI)}°</span>
<button class="nudge" onclick={() => rotateAxisBy(5)}>+</button>
</div>
</div>
<div class="actions">
<button class="back" onclick={goBack}>Back</button>
<button class="approve" onclick={approveAxis}>Approve Axis</button>
</div>
</section>
{/if}
{#if state === 'measure'}
<section class="step measure-step">
<h2>Measure</h2>
<div class="controls">
<div class="control-row">
<label>Length (in)</label>
<input type="number" min="1" step="0.125" value={lengthIn} oninput={(e) => lengthIn = parseFloat(e.target.value) || 0} />
</div>
<div class="control-row">
<label>Thickness (in)</label>
<input type="number" min="0.125" step="0.125" value={thicknessIn} oninput={(e) => thicknessIn = parseFloat(e.target.value) || 0} />
</div>
</div>
<div class="actions">
<button class="back" onclick={goBack}>Back</button>
<button class="approve" onclick={calculate}>Calculate</button>
</div>
{#if result}
<div class="results">
<h3>Results</h3>
<dl>
<dt>Width (min)</dt><dd>{result.min?.toFixed(2)} in</dd>
<dt>Width (max)</dt><dd>{result.max?.toFixed(2)} in</dd>
<dt>Width (avg)</dt><dd>{result.avg?.toFixed(2)} in</dd>
<dt>Length</dt><dd>{result.lengthIn} in</dd>
<dt>Thickness</dt><dd>{result.thicknessIn} in</dd>
<dt>Scale</dt><dd>{result.scale?.toFixed(2)} px/in</dd>
<dt>Sq Ft</dt><dd>{result.sqft} ft²</dd>
<dt>Board Feet</dt><dd>{result.bdft} bdft</dd>
</dl>
{#if pngUrl}
<h3>Inventory PNG</h3>
<img src={pngUrl} alt="Inventory PNG" class="png-preview" />
{/if}
<button class="reset" onclick={reset}>Start New Slab</button>
</div>
{/if}
</section>
{/if}
{/if}
</div>
<style>
.capture {
max-width: 720px;
margin: 0 auto;
padding: 1rem;
font-family: system-ui, sans-serif;
}
h1 { text-align: center; font-size: 1.4rem; margin-bottom: 1rem; }
h2 { font-size: 1.1rem; margin-bottom: 0.5rem; }
.preview-wrap {
position: relative;
width: 100%;
max-height: 50vh;
overflow: hidden;
border-radius: 8px;
border: 1px solid #ddd;
background: #f5f5f5;
display: flex;
align-items: center;
justify-content: center;
}
.preview {
max-width: 100%;
max-height: 50vh;
width: auto;
height: auto;
display: block;
object-fit: contain;
}
.busy {
position: absolute;
top: 8px;
right: 8px;
background: rgba(0,0,0,0.6);
color: #fff;
padding: 4px 10px;
border-radius: 4px;
font-size: 0.8rem;
}
.step { margin-top: 1rem; }
.setup-rules { font-size: 0.9rem; color: #555; margin-bottom: 1rem; line-height: 1.5; }
.controls { display: flex; flex-direction: column; gap: 0.75rem; margin: 0.5rem 0; }
.control-row {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
}
.control-row label { min-width: 100px; font-weight: 600; font-size: 0.9rem; }
.control-row input[type="range"] { flex: 1; min-width: 120px; }
.control-row input[type="number"] { width: 80px; padding: 6px; }
.val { min-width: 40px; text-align: center; font-size: 0.9rem; }
.seg { display: flex; gap: 0; }
.seg button {
padding: 8px 16px;
border: 1px solid #ccc;
background: #fff;
cursor: pointer;
font-size: 0.9rem;
}
.seg button:first-child { border-radius: 6px 0 0 6px; }
.seg button:last-child { border-radius: 0 6px 6px 0; }
.seg button.active { background: #333; color: #fff; border-color: #333; }
.nudge {
width: 44px;
height: 44px;
border-radius: 50%;
border: 1px solid #ccc;
background: #fff;
font-size: 1rem;
cursor: pointer;
}
.nudge:active { background: #eee; }
.actions {
display: flex;
gap: 0.75rem;
margin-top: 1rem;
}
.actions button {
padding: 12px 24px;
border-radius: 8px;
border: none;
font-size: 1rem;
cursor: pointer;
}
.back { background: #eee; }
.approve { background: #22c55e; color: #fff; }
.approve:disabled { background: #aaa; cursor: not-allowed; }
.warn { color: #dc2626; font-size: 0.9rem; margin-top: 0.5rem; }
.notice {
background: #fef3cd;
border: 1px solid #ffc107;
padding: 1rem;
border-radius: 8px;
margin: 1rem 0;
}
.notice button {
margin-top: 0.5rem;
padding: 8px 16px;
border: none;
border-radius: 6px;
background: #333;
color: #fff;
}
.results { margin-top: 1.5rem; }
.results h3 { font-size: 1rem; margin-top: 1rem; }
.results dl {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.25rem 1rem;
}
.results dt { font-weight: 600; font-size: 0.9rem; }
.results dd { font-size: 0.9rem; color: #333; }
.png-preview {
max-width: 100%;
max-height: 400px;
border: 1px solid #ddd;
border-radius: 8px;
margin-top: 0.5rem;
background: repeating-conic-gradient(#f0f0f0 0% 25%, #fff 0% 50%) 0 0 / 20px 20px;
}
.reset {
margin-top: 1rem;
padding: 12px 24px;
border-radius: 8px;
border: none;
background: #6366f1;
color: #fff;
font-size: 1rem;
cursor: pointer;
}
</style>
@@ -0,0 +1,6 @@
// Minimal health route so the UAT container has a non-SPA probe target.
import { json } from '@sveltejs/kit';
export function GET() {
return json({ ok: true, milestone: 1, app: 'slab-uploader' });
}
+10
View File
@@ -0,0 +1,10 @@
import adapter from '@sveltejs/adapter-node';
/** @type {import('@sveltejs/kit').Config} */
const config = {
kit: {
adapter: adapter()
}
};
export default config;
+77
View File
@@ -0,0 +1,77 @@
import { test, expect } from '@playwright/test';
// M1-4: Playwright tests for the Length axis state.
// RED first — the live UI lands in M1-5. These tests describe the
// contract the UI must honour once the Mask state approves.
//
// Spec ground truth (docs/CAPTURE.md §Length axis):
// - min-area bounding rectangle of the mask
// - length axis on the long side of that rectangle
// - user rotates the axis if it does not follow the slab length
// - approve the axis
const SLAB_FIXTURE = 'tests/fixtures/slab-green.jpg';
test.describe('Length axis state (M1-5 live UI)', () => {
test('advances to Length axis after approving the mask', async ({ page }) => {
await page.goto('/');
await page.locator('input[type="file"]').setInputFiles(SLAB_FIXTURE);
// Wait for the initial mask recompute.
await page.waitForTimeout(2200);
// Approve the mask.
await page.getByRole('button', { name: /approve/i }).tap();
// The Length axis state is now visible.
await expect(page.getByText(/length axis/i)).toBeVisible();
});
test('shows the bounding rectangle and the proposed length axis', async ({
page,
}) => {
await page.goto('/');
await page.locator('input[type="file"]').setInputFiles(SLAB_FIXTURE);
await page.waitForTimeout(2200);
await page.getByRole('button', { name: /approve/i }).tap();
// The bounding rectangle is drawn on the photo.
await expect(
page.locator('[data-testid="bounding-rect"]'),
).toBeVisible();
// The proposed length axis is drawn along the long side.
await expect(
page.locator('[data-testid="length-axis"]'),
).toBeVisible();
});
test('rotate control adjusts the axis', async ({ page }) => {
await page.goto('/');
await page.locator('input[type="file"]').setInputFiles(SLAB_FIXTURE);
await page.waitForTimeout(2200);
await page.getByRole('button', { name: /approve/i }).tap();
// The rotate control is present.
const rotate = page.getByRole('slider', { name: /rotate axis/i });
await expect(rotate).toBeVisible();
// Rotating changes the axis angle.
const before = await page
.locator('[data-testid="length-axis"]')
.getAttribute('data-angle');
await rotate.fill('90');
const after = await page
.locator('[data-testid="length-axis"]')
.getAttribute('data-angle');
expect(before).not.toBe(after);
});
test('approve the axis advances to Measure', async ({ page }) => {
await page.goto('/');
await page.locator('input[type="file"]').setInputFiles(SLAB_FIXTURE);
await page.waitForTimeout(2200);
// Approve the mask -> Length axis.
await page.getByRole('button', { name: /approve/i }).tap();
// Approve the axis -> Measure.
const approveAxis = page.getByRole('button', {
name: /approve axis/i,
});
await expect(approveAxis).toBeVisible();
await approveAxis.tap();
await expect(page.getByText(/measure/i)).toBeVisible();
});
});
+109
View File
@@ -0,0 +1,109 @@
import { test, expect, devices } from '@playwright/test';
// UAT-3: Browser gate (hard stop) — e2e.
// Spec (CAPTURE.md §Browsers):
// Phone: iOS Safari, Android Chrome.
// PC: Chrome, Edge, Firefox.
// Other clients get a hard stop.
//
// Acceptance: opening in an unsupported browser (e.g. Opera, Samsung
// Internet) shows a hard-stop message, NOT the app.
//
// The app itself must not render (no <slot> content, no "Milestone 1
// — Capture" text) in an unsupported browser; the hard-stop page lists
// the spec browsers instead.
const DESKTOP_CHROME_UA =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36';
const DESKTOP_OPERA_UA =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 OPR/110.0.0.0';
const DESKTOP_EDGE_UA =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0';
const DESKTOP_FIREFOX_UA =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:125.0) Gecko/20100101 Firefox/125.0';
const IOS_SAFARI_UA =
'Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Mobile/15E148 Safari/605.1.15';
const ANDROID_CHROME_UA =
'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.6331.115 Mobile Safari/537.36';
const SAMSUNG_INTERNET_UA =
'Mozilla/5.0 (Linux; Android 14; SM-S918B) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/24.0 Chrome/124.0.0.0 Mobile Safari/537.36';
async function openApp(page, ua) {
await page.setExtraHTTPHeaders({ 'User-Agent': ua });
await page.goto('/');
// The gate runs on client hydration; wait a beat for the DOM to
// settle on whichever branch rendered.
await page.waitForTimeout(300);
}
// The app renders when the gate passes: the layout's <main> is present
// and the capture UI (Add Photo heading) is inside it.
async function expectApp(page) {
await expect(page.locator('main')).toBeVisible();
await expect(page.locator('main')).toContainText('Add Photo');
// No hard-stop page.
await expect(page.locator('.gate')).toHaveCount(0);
}
// The hard stop renders when the gate fails: the .gate box is present,
// the app's <main> is NOT, and the spec browsers are listed.
async function expectHardStop(page) {
await expect(page.locator('.gate h1')).toHaveText('Unsupported browser');
await expect(page.locator('main')).toHaveCount(0);
const gate = page.locator('.gate');
await expect(gate).toContainText('iOS Safari');
await expect(gate).toContainText('Android Chrome');
await expect(gate).toContainText('Chrome');
await expect(gate).toContainText('Edge');
await expect(gate).toContainText('Firefox');
}
test('UAT-3: app renders in desktop Chrome (supported)', async ({ page }) => {
await openApp(page, DESKTOP_CHROME_UA);
await expectApp(page);
});
test('UAT-3: app renders in desktop Edge (supported)', async ({ page }) => {
await openApp(page, DESKTOP_EDGE_UA);
await expectApp(page);
});
test('UAT-3: app renders in desktop Firefox (supported)', async ({ page }) => {
await openApp(page, DESKTOP_FIREFOX_UA);
await expectApp(page);
});
test('UAT-3: app renders in iOS Safari (supported)', async ({ page, context }) => {
await context.setExtraHTTPHeaders({ 'User-Agent': IOS_SAFARI_UA });
await page.goto('/');
await page.waitForTimeout(300);
await expectApp(page);
});
test('UAT-3: app renders in Android Chrome (supported)', async ({ page, context }) => {
await context.setExtraHTTPHeaders({ 'User-Agent': ANDROID_CHROME_UA });
await page.goto('/');
await page.waitForTimeout(300);
await expectApp(page);
});
test('UAT-3: hard stop in desktop Opera (unsupported)', async ({ page }) => {
await openApp(page, DESKTOP_OPERA_UA);
await expect(page.locator('.gate h1')).toHaveText('Unsupported browser');
// The app must NOT render.
await expect(page.locator('main')).toHaveCount(0);
// The hard-stop page lists the spec browsers.
await expect(page.locator('.gate')).toContainText('iOS Safari');
await expect(page.locator('.gate')).toContainText('Android Chrome');
await expect(page.locator('.gate')).toContainText('Chrome');
await expect(page.locator('.gate')).toContainText('Edge');
await expect(page.locator('.gate')).toContainText('Firefox');
});
test('UAT-3: hard stop in Samsung Internet (unsupported)', async ({ page, context }) => {
await context.setExtraHTTPHeaders({ 'User-Agent': SAMSUNG_INTERNET_UA });
await page.goto('/');
await page.waitForTimeout(300);
await expect(page.locator('.gate h1')).toHaveText('Unsupported browser');
await expect(page.locator('main')).toHaveCount(0);
});
+93
View File
@@ -0,0 +1,93 @@
import { test, expect } from '@playwright/test';
// M1-3: Playwright tests for the Mask state (RED first — the live Mask UI
// lands in M1-5; the pure state machine + geometry are unit-tested in
// tests/unit/maskState.test.js).
//
// Spec ground truth (docs/CAPTURE.md):
// - "Approve is blocked when the mask has no slab pixels. User retakes."
// - "If the file is HEIC and the browser cannot decode it, show a one-tap
// notice to retake the photo as JPEG."
// - 2 knobs: sheet Auto/Green/Black, sensitivity 0–100 (slider + minus/plus).
// Edge offset and feather are NOT user-exposed in M1 (core params only).
// - Sensitivity slider updates immediately; overlay recomputes 2.0 s after
// the last change.
const SLAB_FIXTURE = 'tests/fixtures/slab-green.jpg';
const SHEET_ONLY_FIXTURE = 'tests/fixtures/sheet-only-green.jpg';
const HEIC_FIXTURE = 'tests/fixtures/slab.heic';
test.describe('Mask state (M1-5 live UI)', () => {
test('HEIC input that the browser cannot decode shows a one-tap retake notice', async ({ page }) => {
// 1. Land on Add photo.
await page.goto('/');
// 2. Provide an HEIC file the browser cannot decode.
const input = page.locator('input[type="file"]');
await input.setInputFiles(HEIC_FIXTURE);
// 3. The app must surface a one-tap 'retake as JPEG' notice — never a
// silent crash, never a server-side decode.
const notice = page.getByRole('alert', { name: /retake/i });
await expect(notice).toBeVisible();
await expect(notice).toHaveText(/retake as JPEG/i);
// 4. Tapping it returns to Add photo.
await notice.tap();
await expect(page.getByRole('button', { name: /add photo/i })).toBeVisible();
});
test('Approve is blocked while the mask has no slab pixels', async ({ page }) => {
// 1. Load a photo of the sheet only (no slab).
await page.goto('/');
const input = page.locator('input[type="file"]');
await input.setInputFiles(SHEET_ONLY_FIXTURE);
// 2. The Mask state opens with the overlay visible.
await expect(page.getByText(/mask/i)).toBeVisible();
// 3. Approve must be disabled — the mask has no slab pixels.
const approve = page.getByRole('button', { name: /approve/i });
await expect(approve).toBeDisabled();
// 4. Retake and load a photo with a real slab -> approve enables.
await page.getByRole('button', { name: /retake/i }).tap();
await page.locator('input[type="file"]').setInputFiles(SLAB_FIXTURE);
await expect(approve).toBeEnabled();
});
test('keys the green sheet and shows the 2 spec knobs', async ({ page }) => {
await page.goto('/');
await page.locator('input[type="file"]').setInputFiles(SLAB_FIXTURE);
// Sheet control with Auto/Green/Black.
const sheet = page.getByRole('radiogroup', { name: /sheet/i });
await expect(sheet.getByRole('radio', { name: /auto/i })).toBeChecked();
await expect(sheet.getByRole('radio', { name: /green/i })).toBeVisible();
await expect(sheet.getByRole('radio', { name: /black/i })).toBeVisible();
// Sensitivity slider 0–100 with minus/plus.
const slider = page.getByRole('slider', { name: /sensitivity/i });
await expect(slider).toBeVisible();
await expect(slider).toHaveAttribute('min', '0');
await expect(slider).toHaveAttribute('max', '100');
await expect(page.getByRole('button', { name: /decrease sensitivity/i })).toBeVisible();
await expect(page.getByRole('button', { name: /increase sensitivity/i })).toBeVisible();
// Edge offset and feather are NOT in the spec — they must not be
// user-exposed in the Mask UI.
await expect(page.getByRole('slider', { name: /edge offset/i })).not.toBeVisible();
await expect(page.getByRole('slider', { name: /feather/i })).not.toBeVisible();
// Overlay visible (photo with checkerboard on removed px).
await expect(page.locator('[data-testid="mask-overlay"]')).toBeVisible();
});
test('sensitivity slider updates the control immediately', async ({ page }) => {
await page.goto('/');
await page.locator('input[type="file"]').setInputFiles(SLAB_FIXTURE);
const slider = page.getByRole('slider', { name: /sensitivity/i });
await slider.fill('80');
// The control value is reflected immediately, not after the 2 s debounce.
await expect(slider).toHaveValue('80');
});
test('approve advances to Length axis after a non-empty mask', async ({ page }) => {
await page.goto('/');
await page.locator('input[type="file"]').setInputFiles(SLAB_FIXTURE);
// Let the initial recompute land so stats are non-empty.
await page.waitForTimeout(2200);
await page.getByRole('button', { name: /approve/i }).tap();
await expect(page.getByText(/length axis/i)).toBeVisible();
});
});
+45
View File
@@ -0,0 +1,45 @@
import { test, expect } from '@playwright/test';
const SLAB_FIXTURE = 'tests/fixtures/slab-green.jpg';
// E2E smoke: the app serves and the health route responds.
test('M1-1 harness smoke: app serves + health ok', async ({ page, request }) => {
await page.goto('/');
await expect(page).toHaveTitle(/SlabUploader/);
const res = await request.get('/api/health');
expect(res.ok()).toBeTruthy();
const body = await res.json();
expect(body.ok).toBe(true);
});
// Regression: the preview canvas must fit the full photo within the
// viewport without cropping. Spec: "Preview fits the device width.
// Height is capped so Mask and Measure controls stay on screen."
test('preview canvas fits full photo without cropping', async ({ page }) => {
await page.goto('/');
await page.locator('input[type="file"]').setInputFiles(SLAB_FIXTURE);
await page.waitForTimeout(2500); // mask recompute
const canvas = page.locator('canvas.preview');
await expect(canvas).toBeVisible();
// Get the canvas's rendered (CSS) size and its intrinsic (pixel) size.
const box = await canvas.boundingBox();
const intrinsic = await canvas.evaluate((c) => ({ w: c.width, h: c.height }));
// The rendered size must fit within the viewport.
const vp = page.viewportSize();
expect(box.width).toBeLessThanOrEqual(vp.width);
expect(box.height).toBeLessThanOrEqual(vp.height * 0.55); // 50vh cap + tolerance
// Aspect ratio must be preserved (no distortion).
const renderedRatio = box.width / box.height;
const intrinsicRatio = intrinsic.w / intrinsic.h;
expect(renderedRatio).toBeCloseTo(intrinsicRatio, 1);
// The canvas must not be clipped by its container.
const wrap = page.locator('.preview-wrap');
const wrapBox = await wrap.boundingBox();
expect(box.width).toBeLessThanOrEqual(wrapBox.width + 1);
expect(box.height).toBeLessThanOrEqual(wrapBox.height + 1);
});
Binary file not shown.

After

Width:  |  Height:  |  Size: 904 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1020 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 988 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 996 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 744 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 464 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 473 B

Binary file not shown.
+377
View File
@@ -0,0 +1,377 @@
import { describe, it, expect } from 'vitest';
import {
minAreaRect,
axisFromRect,
rotateAxis,
axisAngle,
axisUnit,
createAxisState,
reduceAxisState,
} from '../../src/lib/core/axis.js';
// M1-4 Length axis — unit tests (RED first, per strict TDD).
//
// Ground truth: docs/CAPTURE.md §Length axis
// - min-area bounding rectangle of the mask
// - length axis on the long side of that rectangle
// - user rotates the axis if it does not follow the slab length
// - approve the axis
//
// All functions are pure (no DOM) so the state is unit-testable in Node.
// --- helpers --------------------------------------------------------------------
/**
* Build a binary mask (Uint8Array) of w x h with a filled axis-aligned
* rectangle of size rw x rh at (rx, ry).
*/
function rectMask(w, h, rx, ry, rw, rh) {
const mask = new Uint8Array(w * h);
for (let y = ry; y < ry + rh; y++) {
for (let x = rx; x < rx + rw; x++) {
mask[y * w + x] = 1;
}
}
return mask;
}
/**
* Build a binary mask of a rotated rectangle.
* Center at (cx, cy), half-lengths (hl, hw), rotation in radians.
*/
function rotatedRectMask(w, h, cx, cy, hl, hw, rot) {
const mask = new Uint8Array(w * h);
const cos = Math.cos(rot);
const sin = Math.sin(rot);
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const dx = x - cx;
const dy = y - cy;
// Transform to rect-local coords
const lx = cos * dx + sin * dy;
const ly = -sin * dx + cos * dy;
if (Math.abs(lx) <= hl && Math.abs(ly) <= hw) {
mask[y * w + x] = 1;
}
}
}
return mask;
}
// --- minAreaRect ------------------------------------------------------------------
describe('minAreaRect', () => {
it('returns a tight axis-aligned rectangle for an axis-aligned mask', () => {
// 8x4 rectangle at (2,2) on a 12x8 canvas.
// Pixels at x=2..9 (8 cols), y=2..5 (4 rows).
// Center-to-center span: width 7, height 3. Center (5.5, 3.5).
const mask = rectMask(12, 8, 2, 2, 8, 4);
const rect = minAreaRect(mask, 12, 8);
// The min-area rect of an axis-aligned pixel block is tight:
// width = (cols-1), height = (rows-1) in center-to-center units.
expect(rect.width).toBeCloseTo(7, 2);
expect(rect.height).toBeCloseTo(3, 2);
expect(rect.angle).toBeCloseTo(0, 3);
expect(rect.center.x).toBeCloseTo(5.5, 2); // (2+9)/2
expect(rect.center.y).toBeCloseTo(3.5, 2); // (2+5)/2
});
it('handles a single pixel', () => {
const mask = new Uint8Array(10 * 10);
mask[5 * 10 + 5] = 1; // pixel at (5,5)
const rect = minAreaRect(mask, 10, 10);
expect(rect.area).toBe(1);
});
it('returns null for an empty mask', () => {
const mask = new Uint8Array(10 * 10);
const rect = minAreaRect(mask, 10, 10);
expect(rect).toBeNull();
});
it('detects a rotated rectangle', () => {
// 45-degree rotated rectangle: 20 units long, 4 units wide, centered
const w = 40,
h = 40,
cx = 20,
cy = 20,
hl = 10,
hw = 2;
const mask = rotatedRectMask(w, h, cx, cy, hl, hw, Math.PI / 4);
const rect = minAreaRect(mask, w, h);
// Pixel rasterization of a 20x4 rect at 45 degrees: the convex hull
// of the kept pixels approximates the true rect within ~1px per side.
// The angle should be close to 45 degrees.
expect(rect.angle).toBeCloseTo(Math.PI / 4, 1);
// Long side ~20 (within 2px for rasterization)
const longSide = Math.max(rect.width, rect.height);
expect(longSide).toBeGreaterThanOrEqual(18);
expect(longSide).toBeLessThanOrEqual(22);
});
it('handles a horizontal bar (wider than tall)', () => {
// 16x2 bar on a 20x10 canvas
const mask = rectMask(20, 10, 2, 4, 16, 2);
const rect = minAreaRect(mask, 20, 10);
// 16 cols x 2 rows: width ~15-16, height ~1-2 (pixel rasterization)
expect(rect.width).toBeGreaterThanOrEqual(14);
expect(rect.width).toBeLessThanOrEqual(17);
expect(rect.height).toBeGreaterThanOrEqual(1);
expect(rect.height).toBeLessThanOrEqual(3);
expect(rect.angle).toBeCloseTo(0, 1);
});
it('handles a vertical bar (taller than wide)', () => {
// 2x16 bar on a 10x20 canvas
const mask = rectMask(10, 20, 4, 2, 2, 16);
const rect = minAreaRect(mask, 10, 20);
// Long side ~16, short side ~2
const longSide = Math.max(rect.width, rect.height);
const shortSide = Math.min(rect.width, rect.height);
expect(longSide).toBeGreaterThanOrEqual(14);
expect(longSide).toBeLessThanOrEqual(17);
expect(shortSide).toBeGreaterThanOrEqual(1);
expect(shortSide).toBeLessThanOrEqual(3);
});
});
// --- axisFromRect ------------------------------------------------------------------
describe('axisFromRect', () => {
it('returns a unit vector along the long side of an axis-aligned rect', () => {
// 8x4 rect: long side is horizontal (width=8 > height=4)
const rect = {
center: { x: 6, y: 4 },
width: 8,
height: 4,
angle: 0,
area: 32,
};
const axis = axisFromRect(rect);
// Long side is width (8), so axis is along +x
expect(axis.x).toBeCloseTo(1, 6);
expect(axis.y).toBeCloseTo(0, 6);
});
it('returns a unit vector along the long side when height > width', () => {
// 4x8 rect: long side is vertical (height=8 > width=4)
const rect = {
center: { x: 6, y: 4 },
width: 4,
height: 8,
angle: 0,
area: 32,
};
const axis = axisFromRect(rect);
// Long side is height, so axis is along +y
expect(axis.x).toBeCloseTo(0, 6);
expect(axis.y).toBeCloseTo(1, 6);
});
it('rotates the axis with the rect angle', () => {
// 8x4 rect rotated 90 degrees: long side becomes vertical
const rect = {
center: { x: 6, y: 4 },
width: 8,
height: 4,
angle: Math.PI / 2,
area: 32,
};
const axis = axisFromRect(rect);
// The long side (width=8) is now along +y after 90-degree rotation
expect(axis.x).toBeCloseTo(0, 6);
expect(axis.y).toBeCloseTo(1, 6);
});
it('returns the axis at 45 degrees for a rotated rect', () => {
const rect = {
center: { x: 20, y: 20 },
width: 20,
height: 4,
angle: Math.PI / 4,
area: 80,
};
const axis = axisFromRect(rect);
// Long side at 45 degrees
expect(axis.x).toBeCloseTo(Math.SQRT1_2, 3);
expect(axis.y).toBeCloseTo(Math.SQRT1_2, 3);
});
});
// --- rotateAxis --------------------------------------------------------------------
describe('rotateAxis', () => {
it('rotates by 0 degrees is a no-op', () => {
const axis = { x: 1, y: 0 };
const rot = rotateAxis(axis, 0);
expect(rot.x).toBeCloseTo(1, 6);
expect(rot.y).toBeCloseTo(0, 6);
});
it('rotates by 90 degrees', () => {
const axis = { x: 1, y: 0 };
const rot = rotateAxis(axis, Math.PI / 2);
expect(rot.x).toBeCloseTo(0, 6);
expect(rot.y).toBeCloseTo(1, 6);
});
it('rotates by -90 degrees', () => {
const axis = { x: 1, y: 0 };
const rot = rotateAxis(axis, -Math.PI / 2);
expect(rot.x).toBeCloseTo(0, 6);
expect(rot.y).toBeCloseTo(-1, 6);
});
it('rotates a 45-degree axis by 45 degrees -> 90 degrees (vertical)', () => {
const axis = { x: Math.SQRT1_2, y: Math.SQRT1_2 };
const rot = rotateAxis(axis, Math.PI / 4);
expect(rot.x).toBeCloseTo(0, 3);
expect(rot.y).toBeCloseTo(1, 3);
});
});
// --- axisAngle -------------------------------------------------------------------
describe('axisAngle', () => {
it('returns 0 for +x axis', () => {
expect(axisAngle({ x: 1, y: 0 })).toBeCloseTo(0, 6);
});
it('returns PI/2 for +y axis', () => {
expect(axisAngle({ x: 0, y: 1 })).toBeCloseTo(Math.PI / 2, 6);
});
it('returns -PI/2 for -y axis', () => {
expect(axisAngle({ x: 0, y: -1 })).toBeCloseTo(-Math.PI / 2, 6);
});
it('returns PI for -x axis', () => {
expect(axisAngle({ x: -1, y: 0 })).toBeCloseTo(Math.PI, 6);
});
it('returns 45 degrees for diagonal', () => {
expect(axisAngle({ x: Math.SQRT1_2, y: Math.SQRT1_2 })).toBeCloseTo(
Math.PI / 4,
3,
);
});
});
// --- axisUnit --------------------------------------------------------------------
describe('axisUnit', () => {
it('creates a unit vector from an angle', () => {
expect(axisUnit(0).x).toBeCloseTo(1, 6);
expect(axisUnit(0).y).toBeCloseTo(0, 6);
expect(axisUnit(Math.PI / 2).x).toBeCloseTo(0, 6);
expect(axisUnit(Math.PI / 2).y).toBeCloseTo(1, 6);
expect(axisUnit(-Math.PI / 2).x).toBeCloseTo(0, 6);
expect(axisUnit(-Math.PI / 2).y).toBeCloseTo(-1, 6);
expect(axisUnit(Math.PI).x).toBeCloseTo(-1, 6);
expect(axisUnit(Math.PI).y).toBeCloseTo(0, 6);
});
});
// --- createAxisState -----------------------------------------------------------------
describe('createAxisState', () => {
it('starts with the proposed axis from the rect, not approved', () => {
const rect = {
center: { x: 6, y: 4 },
width: 8,
height: 4,
angle: 0,
area: 32,
};
const state = createAxisState(rect);
expect(state.rect).toBe(rect);
expect(state.axis.x).toBeCloseTo(1, 6); // long side is horizontal
expect(state.axis.y).toBeCloseTo(0, 6);
expect(state.approved).toBe(false);
});
it('proposed axis follows the rect angle', () => {
const rect = {
center: { x: 20, y: 20 },
width: 20,
height: 4,
angle: Math.PI / 4,
area: 80,
};
const state = createAxisState(rect);
expect(state.axis.x).toBeCloseTo(Math.SQRT1_2, 3);
expect(state.axis.y).toBeCloseTo(Math.SQRT1_2, 3);
});
});
// --- reduceAxisState -----------------------------------------------------------------
describe('reduceAxisState', () => {
const rect = {
center: { x: 6, y: 4 },
width: 8,
height: 4,
angle: 0,
area: 32,
};
it('rotate updates the axis immediately', () => {
let s = createAxisState(rect);
s = reduceAxisState(s, { type: 'rotate', angle: Math.PI / 2 });
// +x rotated by 90 degrees -> +y
expect(s.axis.x).toBeCloseTo(0, 6);
expect(s.axis.y).toBeCloseTo(1, 6);
});
it('rotate changes the rect angle (not just a separate axis vector)', () => {
let s = createAxisState(rect);
const originalAngle = s.rect.angle;
s = reduceAxisState(s, { type: 'rotate', angle: Math.PI / 4 });
// The rect itself must have rotated
expect(s.rect.angle).toBeCloseTo(originalAngle + Math.PI / 4, 6);
// And the axis is re-derived from the rotated rect
expect(s.axis).toEqual(axisFromRect(s.rect));
});
it('rotate by 90 deg: rect angle changes, axis is perpendicular to original', () => {
let s = createAxisState(rect);
s = reduceAxisState(s, { type: 'rotate', angle: Math.PI / 2 });
expect(s.rect.angle).toBeCloseTo(Math.PI / 2, 6);
// Original axis was +x (1,0). After 90 deg rect rotation, axis is +y (0,1)
expect(s.axis.x).toBeCloseTo(0, 6);
expect(s.axis.y).toBeCloseTo(1, 6);
});
it('rotate composes (rotates from current axis)', () => {
let s = createAxisState(rect);
s = reduceAxisState(s, { type: 'rotate', angle: Math.PI / 2 });
s = reduceAxisState(s, { type: 'rotate', angle: Math.PI / 2 });
// Two 90-degree rotations -> -x
expect(s.axis.x).toBeCloseTo(-1, 6);
expect(s.axis.y).toBeCloseTo(0, 6);
});
it('rotate by 0 is a no-op', () => {
let s = createAxisState(rect);
const before = s;
s = reduceAxisState(s, { type: 'rotate', angle: 0 });
expect(s).toBe(before);
});
it('approve sets approved=true', () => {
let s = createAxisState(rect);
s = reduceAxisState(s, { type: 'approve' });
expect(s.approved).toBe(true);
});
it('retract approval on rotate after approval', () => {
let s = createAxisState(rect);
s = reduceAxisState(s, { type: 'approve' });
expect(s.approved).toBe(true);
// Rotate after approval: axis changes, approval is retracted
// (user is adjusting the axis, so it is no longer approved)
s = reduceAxisState(s, { type: 'rotate', angle: Math.PI / 4 });
expect(s.approved).toBe(false);
});
it('unknown actions return the same state', () => {
const s = createAxisState(rect);
expect(reduceAxisState(s, { type: 'bogus' })).toBe(s);
});
});
+201
View File
@@ -0,0 +1,201 @@
/**
* UAT-3: Browser gate (hard stop) — unit tests for the pure logic in
* src/lib/core/browserGate.js.
*
* CAPTURE.md §Browsers:
* Phone: iOS Safari, Android Chrome.
* PC: Chrome, Edge, Firefox.
* Other clients get a hard stop.
*/
import { describe, it, expect } from 'vitest';
import { detectBrowser, isAllowed, checkBrowserGate } from '$lib/core/browserGate.js';
// --- representative user agents ------------------------------------
const UAs = {
iosSafari:
'Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Mobile/15E148 Safari/605.1.15',
ipadSafari:
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Safari/605.1.15',
iosChrome:
'Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/124.0.6336.69 Mobile/15E148 Safari/605.1.15',
androidChrome:
'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.6331.115 Mobile Safari/537.36',
desktopChrome:
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
desktopEdge:
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0',
desktopFirefox:
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:125.0) Gecko/20100101 Firefox/125.0',
desktopOpera:
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 OPR/110.0.0.0',
androidOpera:
'Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Mobile Safari/537.36 OPR/110.0.0.0',
androidSamsung:
'Mozilla/5.0 (Linux; Android 14; SM-S918B) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/24.0 Chrome/124.0.0.0 Mobile Safari/537.36',
iosSamsung:
'Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/124.0.0.0 Mobile/15E148 SamsungBrowser/124.0.0.0',
androidBrave:
'Mozilla/5.0 (Linux; Android 14; SM-A546E) AppleWebKit/537.36 (KHTML, like Gecko) Version/14.0.0.5336 Mobile Safari/537.36',
unknown:
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) CustomBrowser/9.9.0 Safari/537.36',
blank: '',
};
describe('detectBrowser', () => {
it('identifies iOS Safari on iPhone', () => {
const b = detectBrowser(UAs.iosSafari);
expect(b.name).toBe('iOS Safari');
expect(b.platform).toBe('phone');
});
it('identifies iPad Safari (iPadOS 13+ reports as Macintosh)', () => {
const b = detectBrowser(UAs.ipadSafari);
expect(b.name).toBe('Safari');
expect(b.platform).toBe('pc');
});
it('identifies Android Chrome', () => {
const b = detectBrowser(UAs.androidChrome);
expect(b.name).toBe('Android Chrome');
expect(b.platform).toBe('phone');
});
it('identifies desktop Chrome', () => {
const b = detectBrowser(UAs.desktopChrome);
expect(b.name).toBe('Chrome');
expect(b.platform).toBe('pc');
});
it('identifies desktop Edge (not Chrome)', () => {
const b = detectBrowser(UAs.desktopEdge);
expect(b.name).toBe('Microsoft Edge');
expect(b.platform).toBe('pc');
});
it('identifies desktop Firefox', () => {
const b = detectBrowser(UAs.desktopFirefox);
expect(b.name).toBe('Firefox');
expect(b.platform).toBe('pc');
});
it('identifies desktop Opera as its own browser (not Chrome)', () => {
const b = detectBrowser(UAs.desktopOpera);
expect(b.name).toBe('Opera');
expect(b.platform).toBe('pc');
});
it('identifies Android Opera (OPR beats Chrome)', () => {
const b = detectBrowser(UAs.androidOpera);
expect(b.name).toBe('Opera');
expect(b.platform).toBe('phone');
});
it('identifies Samsung Internet (SamsungBrowser beats Chrome)', () => {
const b = detectBrowser(UAs.androidSamsung);
expect(b.name).toBe('Samsung Internet');
expect(b.platform).toBe('phone');
});
it('identifies iOS Samsung Internet as unsupported', () => {
const b = detectBrowser(UAs.iosSamsung);
expect(b.name).toBe('Samsung Internet');
expect(b.platform).toBe('phone');
});
it('treats an unrecognized UA as Unknown', () => {
const b = detectBrowser(UAs.unknown);
expect(b.name).toBe('Unknown');
expect(b.platform).toBe('pc');
});
it('handles blank / undefined user agents without throwing', () => {
expect(detectBrowser(UAs.blank).name).toBe('Unknown');
expect(detectBrowser(undefined).name).toBe('Unknown');
});
});
describe('isAllowed', () => {
it('allows iOS Safari on phone', () => {
expect(isAllowed({ name: 'iOS Safari', platform: 'phone' })).toBe(true);
});
it('allows Android Chrome on phone', () => {
expect(isAllowed({ name: 'Android Chrome', platform: 'phone' })).toBe(true);
});
it('allows Chrome on PC', () => {
expect(isAllowed({ name: 'Chrome', platform: 'pc' })).toBe(true);
});
it('allows Edge on PC', () => {
expect(isAllowed({ name: 'Microsoft Edge', platform: 'pc' })).toBe(true);
});
it('allows Firefox on PC', () => {
expect(isAllowed({ name: 'Firefox', platform: 'pc' })).toBe(true);
});
it('rejects Opera', () => {
expect(isAllowed({ name: 'Opera', platform: 'pc' })).toBe(false);
});
it('rejects Android Opera', () => {
expect(isAllowed({ name: 'Opera', platform: 'phone' })).toBe(false);
});
it('rejects Samsung Internet', () => {
expect(isAllowed({ name: 'Samsung Internet', platform: 'phone' })).toBe(false);
});
it('rejects Samsung Internet on iOS', () => {
expect(isAllowed({ name: 'Samsung Internet', platform: 'phone' })).toBe(false);
});
it('rejects Brave', () => {
expect(isAllowed({ name: 'Brave', platform: 'phone' })).toBe(false);
});
it('rejects Unknown', () => {
expect(isAllowed({ name: 'Unknown', platform: 'pc' })).toBe(false);
});
it('rejects phone browsers on PC (impossible but rejected)', () => {
expect(isAllowed({ name: 'iOS Safari', platform: 'pc' })).toBe(false);
expect(isAllowed({ name: 'Android Chrome', platform: 'pc' })).toBe(false);
});
});
describe('checkBrowserGate', () => {
it('supports exactly the five spec browsers + Safari (iPad)', () => {
for (const ua of [
UAs.iosSafari,
UAs.ipadSafari,
UAs.androidChrome,
UAs.desktopChrome,
UAs.desktopEdge,
UAs.desktopFirefox,
]) {
expect(checkBrowserGate(ua).supported).toBe(true);
}
});
it('hard-stops Opera, Samsung Internet, unknown, blank', () => {
for (const ua of [
UAs.desktopOpera,
UAs.androidOpera,
UAs.androidSamsung,
UAs.iosSamsung,
UAs.androidBrave,
UAs.unknown,
UAs.blank,
]) {
expect(checkBrowserGate(ua).supported).toBe(false);
}
});
it('returns the detected browser for the UI', () => {
const r = checkBrowserGate(UAs.desktopOpera);
expect(r.browser.name).toBe('Opera');
expect(r.browser.platform).toBe('pc');
});
});
+35
View File
@@ -0,0 +1,35 @@
import { describe, it, expect } from 'vitest';
import * as m from '../../src/lib/core/math.js';
import { prepareInventoryMetadata } from '../../src/lib/core/inventory.js';
describe('prepareInventoryMetadata', () => {
it('calculates correct metadata for a 21in x 12in slab at 1.75in thick', () => {
const Lpx = 3360, L = 21, scale = 160, thickness = 1.75;
const widthPx = 1920; // 12in
const maskPx = Lpx * widthPx; // 6,451,200
const result = prepareInventoryMetadata(
maskPx,
scale,
L,
thickness,
[1600, 1920, 2080, 1600]
);
// sqft = (6,451,200 / 160^2) / 144 = 1.75
expect(result.sqft).toBe(1.75);
// bdft = 1.75 * 1.75 = 3.0625 -> 3.06
expect(result.bdft).toBe(3.06);
expect(result.lengthIn).toBe(21);
expect(result.thicknessIn).toBe(1.75);
expect(result.minWidth).toBe(10);
expect(result.maxWidth).toBe(13);
expect(result.avgWidth).toBe(11.25);
});
it('handles zero area', () => {
const result = prepareInventoryMetadata(0, 160, 21, 1.75, []);
expect(result.sqft).toBe(0);
expect(result.bdft).toBe(0);
});
});
+156
View File
@@ -0,0 +1,156 @@
import { describe, it, expect } from 'vitest';
import {
keySheet,
maskStats,
} from '../../src/lib/core/mask.js';
// M1-3 mask key geometry — unit tests (RED first, per strict TDD).
//
// Ground truth: docs/CAPTURE.md §Mask
// - 4 knobs: sheet Auto/Green/Black, sensitivity 0–100, edge offset, feather
// - Control value updates IMMEDIATELY; overlay recomputes 2.0 s after the
// last sensitivity change (debounce).
// - Approve blocked when maskStats is empty.
//
// All functions here are pure (no DOM) so the state is unit-testable in Node;
// the live UI (M1-5) drives this machine.
//
// --- synthetic photo helpers (no DOM) -----------------------------------------\n//
function solid(w, h, r, g, b) {
const data = new Uint8ClampedArray(w * h * 4);
for (let i = 0; i < w * h; i++) {
data[i * 4 + 0] = r;
data[i * 4 + 1] = g;
data[i * 4 + 2] = b;
data[i * 4 + 3] = 255;
}
return data;
}
function withRect(data, width, x0, y0, w, h, r, g, b) {
for (let y = y0; y < y0 + h; y++) {
for (let x = x0; x < x0 + w; x++) {
const i = (y * width + x) * 4;
data[i + 0] = r;
data[i + 1] = g;
data[i + 2] = b;
data[i + 3] = 255;
}
}
return data;
}
// 12 x 8 green sheet with an 8 x 4 brown slab at (2,2).
const GREEN_PHOTO = () => withRect(solid(12, 8, 0, 200, 0), 12, 2, 2, 8, 4, 140, 90, 40);
const DIMS = { width: 12, height: 8 };
// --- keySheet ---------------------------------------------------------------------
//
describe('keySheet', () => {
it('keeps the slab in a green sheet photo', () => {
const mask = keySheet(GREEN_PHOTO(), {
sheet: 'green',
sensitivity: 50,
});
// 8x4 = 32 pixels
expect(maskStats(mask).kept).toBe(32);
});
it('keeps the slab in a black sheet photo', () => {
const blackPhoto = withRect(solid(12, 8, 10, 10, 10), 12, 2, 2, 8, 4, 220, 210, 190);
const mask = keySheet(blackPhoto, {
sheet: 'black',
sensitivity: 50,
});
expect(maskStats(mask).kept).toBe(32);
});
it('auto-selects the better key', () => {
// A photo that works well for both should return the green one
const mask = keySheet(GREEN_PHOTO(), {
sheet: 'auto',
sensitivity: 50,
});
expect(maskStats(mask).kept).toBe(32);
});
it('handles sensitivity 0 (tightest)', () => {
const mask = keySheet(GREEN_PHOTO(), {
sheet: 'green',
sensitivity: 0,
});
// At s=0, threshold is 150.
// brown wood (140,90,40) dist = sqrt(140^2 + (90-255)^2 + 40^2) = sqrt(19600 + 27225 + 1600) = ~218.
// 218 > 150, so kept.
expect(maskStats(mask).kept).toBe(32);
});
it('handles sensitivity 100 (loosest)', () => {
const mask = keySheet(GREEN_PHOTO(), {
sheet: 'green',
sensitivity: 100,
});
// At s=100, threshold is 50.
// Sheet green (0,200,0) dist = 55.
// 55 > 50, so sheet is kept too!
// 12x8 = 96 pixels
expect(maskStats(mask).kept).toBe(96);
});
it('green key passes non-green pixels through (black key handles them)', () => {
// Real slab photos (sample_01..06) have a dark blue-gray background
// (e.g. rgb 26,27,29) with a bright warm slab (e.g. rgb 250,200,140).
// The green key is designed to key out a GREEN sheet only. On a dark
// (non-green) surface it passes pixels through (keeps them) so that
// the black key can remove them. The green key alone does NOT remove
// a dark background — that is the black key's job. Auto selects the
// black key in this case (see the auto test below).
const darkBg = solid(12, 8, 26, 27, 29);
withRect(darkBg, 12, 2, 2, 8, 4, 250, 200, 140);
const mask = keySheet(darkBg, { sheet: 'green', sensitivity: 50 });
const stats = maskStats(mask);
// Green key on dark bg: all pixels are non-greenish, so all are kept.
// This is BY DESIGN — the green key is a no-op on non-green surfaces,
// and auto will select the black key instead.
expect(stats.kept).toBe(96);
});
it('auto selects black key over green key on a dark-background photo', () => {
// Real photo: dark bg + bright slab. Green key keeps ~everything (bad).
// Black key keeps only the slab (good). Auto must pick black.
const darkBg = solid(12, 8, 26, 27, 29);
withRect(darkBg, 12, 2, 2, 8, 4, 250, 200, 140);
const mask = keySheet(darkBg, { sheet: 'auto', sensitivity: 50 });
const stats = maskStats(mask);
// Should keep only the slab (32 px), not the whole frame (96 px).
expect(stats.kept).toBe(32);
});
it('auto selects green key over black key on a green-sheet photo', () => {
// Green sheet + brown slab. Green key keeps slab only. Black key may
// keep slab + some sheet. Auto must pick green (fewer kept = better).
const photo = GREEN_PHOTO();
const mask = keySheet(photo, { sheet: 'auto', sensitivity: 50 });
const stats = maskStats(mask);
expect(stats.kept).toBe(32);
});
});
// --- maskStats -------------------------------------------------------------------
//
describe('maskStats', () => {
it('correctly reports kept count and empty status', () => {
const mask = new Uint8Array([1, 0, 1, 0]);
const stats = maskStats(mask);
expect(stats.kept).toBe(2);
expect(stats.total).toBe(4);
expect(stats.empty).toBe(false);
});
it('reports empty=true when no pixels kept', () => {
const mask = new Uint8Array([0, 0, 0, 0]);
const stats = maskStats(mask);
expect(stats.kept).toBe(0);
expect(stats.empty).toBe(true);
});
});
+316
View File
@@ -0,0 +1,316 @@
import { describe, it, expect, vi } from 'vitest';
import {
offsetMask,
featherMask,
computeMask,
createMaskState,
reduceMaskState,
dueForRecompute,
RECOMPUTE_DELAY_MS,
} from '../../src/lib/core/maskState.js';
// M1-3 Mask state — RED first (strict TDD).
//
// Ground truth: docs/CAPTURE.md §Mask
// - 4 knobs: sheet Auto/Green/Black, sensitivity 0–100, edge offset, feather
// - Control value updates IMMEDIATELY; overlay recomputes 2.0 s after the
// last sensitivity change (debounce).
// - Approve blocked when maskStats is empty.
//
// All functions here are pure (no DOM) so the state is unit-testable in Node;
// the live UI (M1-5) drives this machine.
//
// --- synthetic photo helpers (no DOM) -----------------------------------------\
//
function solid(w, h, r, g, b) {
const data = new Uint8ClampedArray(w * h * 4);
for (let i = 0; i < w * h; i++) {
data[i * 4 + 0] = r;
data[i * 4 + 1] = g;
data[i * 4 + 2] = b;
data[i * 4 + 3] = 255;
}
return data;
}
function withRect(data, width, x0, y0, w, h, r, g, b) {
for (let y = y0; y < y0 + h; y++) {
for (let x = x0; x < x0 + w; x++) {
const i = (y * width + x) * 4;
data[i + 0] = r;
data[i + 1] = g;
data[i + 2] = b;
data[i + 3] = 255;
}
}
return data;
}
// 12 x 8 green sheet with an 8 x 4 brown slab at (2,2).
const GREEN_PHOTO = () => withRect(solid(12, 8, 0, 200, 0), 12, 2, 2, 8, 4, 140, 90, 40);
const DIMS = { width: 12, height: 8 };
// --- offsetMask ------------------------------------------------------------------
//
describe('offsetMask (edge offset)', () => {
it('offset 0 is a no-op', () => {
const mask = new Uint8Array([1, 1, 1, 0, 0, 0]);
expect(offsetMask(mask, 3, 2, 0)).toEqual(new Uint8Array([1, 1, 1, 0, 0, 0]));
});
it('positive offset erodes the mask boundary', () => {
// 1 kept ring of 1s on a 5x1 row: erode 1 -> the single kept pixel
// loses its kept neighbours' protection and is removed.
const mask = new Uint8Array([0, 0, 1, 0, 0]);
const eroded = offsetMask(mask, 5, 1, 1);
expect(eroded).toEqual(new Uint8Array([0, 0, 0, 0, 0]));
});
it('positive offset erodes a filled block by 1 px ring', () => {
// 4x4 all-kept block -> 2x2 after one erosion.
const mask = new Uint8Array(16).fill(1);
const eroded = offsetMask(mask, 4, 4, 1);
// corners + outer ring gone, inner 2x2 kept.
expect(eroded[0]).toBe(0);
expect(eroded[3]).toBe(0);
expect(eroded[4]).toBe(0);
expect(eroded[7]).toBe(0);
expect(eroded[5]).toBe(1);
expect(eroded[6]).toBe(1);
expect(eroded[9]).toBe(1);
expect(eroded[10]).toBe(1);
});
it('negative offset dilates the mask', () => {
// single kept pixel grows to a plus shape after one dilation.
const mask = new Uint8Array(9);
mask[4] = 1;
const dilated = offsetMask(mask, 3, 3, -1);
expect(dilated[1]).toBe(1); // up
expect(dilated[3]).toBe(1); // left
expect(dilated[4]).toBe(1); // center
expect(dilated[5]).toBe(1); // right
expect(dilated[7]).toBe(1); // down
expect(dilated[0]).toBe(0); // corners untouched by 4-neighbour dilate
});
it('multiple iterations compound', () => {
// 6x6 block eroded twice -> 2x2 core.
const mask = new Uint8Array(36).fill(1);
const twice = offsetMask(mask, 6, 6, 2);
let kept = 0;
for (let i = 0; i < 36; i++) kept += twice[i];
expect(kept).toBe(4);
});
});
// --- featherMask ------------------------------------------------------------------
//
describe('featherMask (feather)', () => {
it('radius 0 returns identity weights (1 kept, 0 removed)', () => {
const mask = new Uint8Array([1, 0, 1]);
expect(featherMask(mask, 3, 1, 0)).toEqual(new Float32Array([1, 0, 1]));
});
it('interior pixels away from the edge stay fully weighted', () => {
// 5x1 row, all kept, feather 1: interior pixel (2,0) has min distance
// 2 to any 0 (out-of-bounds is not 0, but row ends are boundary —
// boundary pixels have no removed neighbour, so weight stays 1).
const mask = new Uint8Array([1, 1, 1, 1, 1]);
const w = featherMask(mask, 5, 1, 1);
expect(w[2]).toBe(1);
});
it('attenuates kept pixels adjacent to removed pixels', () => {
// 3x1 row: [0,1,0], feather 1: the kept middle pixel is 1 px from a
// removed pixel -> weight (r - dist + 1)/(r + 1) = (1-1+1)/(1+1) = 0.5.
const mask = new Uint8Array([0, 1, 0]);
const w = featherMask(mask, 3, 1, 1);
expect(w[1]).toBeCloseTo(0.5);
});
it('attenuation scales with distance (farther = heavier)', () => {
// 5x1: [0,1,1,1,0], feather 2:
// x=1 dist 1 -> (2-1+1)/3 = 2/3
// x=2 dist 2 -> (2-2+1)/3 = 1/3
// x=3 dist 1 -> 2/3
const mask = new Uint8Array([0, 1, 1, 1, 0]);
const w = featherMask(mask, 5, 1, 2);
expect(w[1]).toBeCloseTo(2 / 3);
expect(w[2]).toBeCloseTo(1 / 3);
expect(w[3]).toBeCloseTo(2 / 3);
});
});
// --- computeMask --------------------------------------------------------------------
//
describe('computeMask (pipeline)', () => {
it('keys green and black sheets end-to-end', () => {
const green = computeMask(GREEN_PHOTO(), {
...DIMS,
sheet: 'green',
sensitivity: 50,
});
expect(green.stats.kept).toBe(32);
expect(green.stats.empty).toBe(false);
const blackPhoto = withRect(solid(12, 8, 10, 10, 10), 12, 2, 2, 8, 4, 220, 210, 190);
const black = computeMask(blackPhoto, {
...DIMS,
sheet: 'black',
sensitivity: 50,
});
expect(black.stats.kept).toBe(32);
});
it('edge offset erodes the kept count', () => {
const base = computeMask(GREEN_PHOTO(), {
...DIMS,
sheet: 'green',
sensitivity: 50,
});
const eroded = computeMask(GREEN_PHOTO(), {
...DIMS,
sheet: 'green',
sensitivity: 50,
edgeOffset: 1,
});
expect(eroded.stats.kept).toBeLessThan(base.stats.kept);
});
it('feather does not change the approve stats', () => {
const base = computeMask(GREEN_PHOTO(), {
...DIMS,
sheet: 'green',
sensitivity: 50,
});
const feath = computeMask(GREEN_PHOTO(), {
...DIMS,
sheet: 'green',
sensitivity: 50,
feather: 2,
});
expect(feath.stats).toEqual(base.stats);
});
it('reports empty stats for a sheet-only photo (approve must block)', () => {
const res = computeMask(solid(12, 8, 0, 200, 0), {
...DIMS,
sheet: 'green',
sensitivity: 50,
});
expect(res.stats.empty).toBe(true);
});
});
// --- state machine --------------------------------------------------------------------
//
describe('mask state machine', () => {
const fresh = () => createMaskState(DIMS);
it('starts with sheet auto, sensitivity 50, knobs 0, not approved, empty stats', () => {
const s = fresh();
expect(s.sheet).toBe('auto');
expect(s.sensitivity).toBe(50);
expect(s.edgeOffset).toBe(0);
expect(s.feather).toBe(0);
expect(s.approved).toBe(false);
expect(s.stats.empty).toBe(true);
});
it('set_sheet updates immediately and flags a pending recompute', () => {
let s = fresh();
s = reduceMaskState(s, { type: 'set_sheet', sheet: 'green' });
expect(s.sheet).toBe('green');
expect(s.pendingRecompute).toBe(true);
});
it('sheet change to the same value is a no-op', () => {
const s = fresh();
expect(reduceMaskState(s, { type: 'set_sheet', sheet: 'auto' })).toBe(s);
});
it('set_sensitivity updates immediately, clamps 0–100, flags recompute', () => {
let s = fresh();
s = reduceMaskState(s, { type: 'set_sensitivity', value: 80 });
expect(s.sensitivity).toBe(80);
expect(s.pendingRecompute).toBe(true);
s = reduceMaskState(s, { type: 'set_sensitivity', value: 250 });
expect(s.sensitivity).toBe(100);
s = reduceMaskState(s, { type: 'set_sensitivity', value: -10 });
expect(s.sensitivity).toBe(0);
});
it('nudge_sensitivity steps by delta and clamps', () => {
let s = fresh();
s = reduceMaskState(s, { type: 'nudge_sensitivity', delta: -5 });
expect(s.sensitivity).toBe(45);
s = reduceMaskState(s, { type: 'nudge_sensitivity', delta: 5 });
expect(s.sensitivity).toBe(50);
s = reduceMaskState(s, { type: 'nudge_sensitivity', delta: -999 });
expect(s.sensitivity).toBe(0);
});
it('edge offset and feather update immediately and flag recompute', () => {
let s = fresh();
s = reduceMaskState(s, { type: 'set_edge_offset', value: 2 });
expect(s.edgeOffset).toBe(2);
expect(s.pendingRecompute).toBe(true);
s = reduceMaskState(s, { type: 'set_feather', value: 3 });
expect(s.feather).toBe(3);
expect(s.pendingRecompute).toBe(true);
});
it('recompute stores stats, clears pending, records time', () => {
let s = fresh();
s = reduceMaskState(s, { type: 'set_sensitivity', value: 60 });
s = reduceMaskState(s, {
type: 'recompute',
stats: { kept: 32, total: 96, empty: false },
at: 1234,
});
expect(s.stats).toEqual({ kept: 32, total: 96, empty: false });
expect(s.pendingRecompute).toBe(false);
expect(s.lastRecomputeAt).toBe(1234);
});
it('approve is blocked while the mask is empty', () => {
let s = fresh(); // stats empty by default
const before = s;
s = reduceMaskState(s, { type: 'approve' });
expect(s.approved).toBe(false);
expect(s).toBe(before); // no change at all
});
it('approve succeeds once the mask has slab pixels', () => {
let s = fresh();
s = reduceMaskState(s, {
type: 'recompute',
stats: { kept: 32, total: 96, empty: false },
at: 1,
});
s = reduceMaskState(s, { type: 'approve' });
expect(s.approved).toBe(true);
});
it('debounce: recompute is due only after 2.0 s of idle', () => {
let s = fresh();
s = reduceMaskState(s, { type: 'set_sensitivity', value: 51 });
expect(dueForRecompute(s, s.lastRecomputeAt)).toBe(false);
expect(dueForRecompute(s, s.lastRecomputeAt + 1999)).toBe(false);
expect(RECOMPUTE_DELAY_MS).toBe(2000);
expect(dueForRecompute(s, s.lastRecomputeAt + 2000)).toBe(true);
});
it('debounce resets on every sensitivity change (timer restarts)', () => {
let s = fresh();
s = reduceMaskState(s, { type: 'set_sensitivity', value: 51 });
// User keeps nudging: at t=1999 the earlier change would be due, but
// a new change at t=1999 resets the window.
s = reduceMaskState(s, { type: 'recompute', stats: s.stats, at: 0 });
s = reduceMaskState(s, { type: 'set_sensitivity', value: 52 });
// 1.9 s after the latest change -> not due; 2.0 s -> due.
expect(dueForRecompute(s, 1999)).toBe(false);
expect(dueForRecompute(s, 2000)).toBe(true);
});
});
+89
View File
@@ -0,0 +1,89 @@
import { describe, it, expect } from 'vitest';
import * as m from '../../src/lib/core/math.js';
// M1 deterministic core — unit tests (RED first, per TDD).
// Ground truth for the math identities is the spec (docs/CAPTURE.md):
// scale = longest_axis_px / L
// sqft = (mask_px / scale^2) / 144
// bdft = sqft * thickness_in
// Widths are sampled every `everyInches` along the approved axis.
describe('scale', () => {
it('scale = longest_axis_px / L', () => {
expect(m.scale(3360, 84)).toBe(40);
});
it('scale for fixture-b geometry (21 in)', () => {
// 21 in represented as 3360 px -> 160 px/in
expect(m.scale(3360, 21)).toBeCloseTo(160, 6);
});
});
describe('sqft', () => {
it('sqft = (mask_px / scale^2) / 144, 2 decimals', () => {
// scale=40 -> scale^2=1600; 1,000,000/1600=625; /144=4.3403 -> 4.34
expect(m.sqft(1_000_000, 40)).toBe(4.34);
});
it('zero-area mask -> 0', () => {
expect(m.sqft(0, 40)).toBe(0);
});
});
describe('bdft', () => {
it('bdft = sqft * thickness_in, 2 decimals (identity 1 sqft @ 1in = 1 bdft)', () => {
expect(m.bdft(4.34, 1)).toBeCloseTo(4.34, 6);
expect(m.bdft(4.34, 2.5)).toBe(10.85);
});
});
describe('e2e fixture math (cand_b: 21in x 1.75in)', () => {
// If the slab were a clean rectangle exactly 21in long, at 160px/in that is
// 3360 px long. Pick a width of 12in -> 1920px -> area 6,451,200 px.
const Lpx = 3360, L = 21, scale = 160, thickness = 1.75;
const widthPx = 1920; // 12in
const maskPx = Lpx * widthPx; // 6,451,200
it('sqft of a 21in x 12in slab = 1.75', () => {
expect(m.sqft(maskPx, scale)).toBe(1.75);
});
it('bdft of that slab at 1.75in = 3.06', () => {
const sqft = m.sqft(maskPx, scale);
expect(m.bdft(sqft, thickness)).toBe(3.06); // 1.75*1.75=3.0625 -> 3.06 (half-up)
});
});
describe('width sampling', () => {
it('samples perpendicular widths at 0,6,12,... in along the axis', () => {
// pxPerIn=160. axisLengthPx = 3360 (21in). widthsAt samples every 6in.
// Provide a constant width of 1920px (12in) at every sample point.
const pxPerIn = 160;
const axisLengthPx = 3360;
const constantWidthPx = 1920;
const out = m.sampledWidths(constantWidthPx, pxPerIn, axisLengthPx, 6);
// 21in / 6 = 3.5 -> sample points at 0,6,12,18 (and not 24>21). 4 samples.
expect(out.length).toBe(4);
for (const w of out) expect(w).toBe(12); // 1920px/160 = 12in
});
it('min/max/avg of sampled widths', () => {
const pxPerIn = 160;
const widths = m.sampledWidthsFrom(
// widths at px positions 0,960,1920,2880 (=0,6,12,18 in)
[1600, 1920, 2080, 1600],
pxPerIn
);
expect(widths.min).toBeCloseTo(10, 6);
expect(widths.max).toBeCloseTo(13, 6);
expect(widths.avg).toBeCloseTo(11.25, 6); // (10+12+13+10)/4 = 11.25
});
});
describe('1/8 inch stepping + rounding', () => {
it('snaps a length to the nearest 1/8 inch', () => {
expect(m.snapToEighth(10.1)).toBeCloseTo(10.125, 6); // 10 1/8
expect(m.snapToEighth(10.2)).toBeCloseTo(10.25, 6); // 10 2/8=1/4
expect(m.snapToEighth(10.0)).toBe(10);
});
it('rounds half-up to 2 decimals', () => {
expect(m.roundHalfUp(30.625, 2)).toBe(30.63);
expect(m.roundHalfUp(4.345, 2)).toBe(4.35);
expect(m.roundHalfUp(1.005, 2)).toBe(1.01);
});
});
+74
View File
@@ -0,0 +1,74 @@
import { describe, it, expect } from 'vitest';
import { sampleWidthsPx } from '../../src/lib/core/measure.js';
// M1-5 Measure — pure geometry tests.
//
// Ground truth: docs/CAPTURE.md §Measure
// - Widths: min, max, avg, sampled every 6 in along the approved length
// axis, perpendicular to it
// - scale = longest_axis_px / L
//
// sampleWidthsPx runs the real scanline mask sampling that the UI uses on
// the approved mask, so these tests pin the exact pixel widths the e2e
// fixture math is computed from.
/**
* Build a binary mask directly (no keySheet dependency): 1 inside the slab
* rectangle, 0 elsewhere. This keeps the test self-contained and focused on
* sampleWidthsPx geometry, which is what the test suite is for.
*/
function buildMask(width, height, slabW, slabH, ox, oy) {
const mask = new Uint8Array(width * height);
for (let y = 0; y < height; y++)
for (let x = 0; x < width; x++)
mask[y * width + x] =
x >= ox && x < ox + slabW && y >= oy && y < oy + slabH ? 1 : 0;
return { mask, width, height };
}
describe('sampleWidthsPx (M1-5 Measure geometry)', () => {
it('samples perpendicular widths every 6in along a horizontal axis', () => {
// 16 px/in. Photo 400x300. Slab 288x96 px (18in x 6in) at (0,0).
// Axis along x at slab center y=48, from x=0, length 288 px.
// stepPx = 6*16 = 96. Samples at t=0,96,192,288.
// t=288 lands on the slab boundary (x=288, slab is x<288) -> width 0.
const { mask, width, height } = buildMask(400, 300, 288, 96, 0, 0);
const axis = { origin: { x: 0, y: 48 }, dir: { x: 1, y: 0 }, lengthPx: 288 };
const widths = sampleWidthsPx(mask, width, height, axis, 16);
expect(widths.length).toBe(4);
expect(widths[0]).toBeCloseTo(96, 0);
expect(widths[1]).toBeCloseTo(96, 0);
expect(widths[2]).toBeCloseTo(96, 0);
expect(widths[3]).toBe(0);
});
it('returns widths perpendicular to a vertical axis', () => {
// Slab 96x288 px (6in x 18in) at (0,0). Axis along y at x=48, length 288.
const { mask, width, height } = buildMask(400, 300, 96, 288, 0, 0);
const axis = { origin: { x: 48, y: 0 }, dir: { x: 0, y: 1 }, lengthPx: 288 };
const widths = sampleWidthsPx(mask, width, height, axis, 16);
expect(widths.length).toBe(4);
expect(widths[0]).toBeCloseTo(96, 0);
expect(widths[1]).toBeCloseTo(96, 0);
expect(widths[2]).toBeCloseTo(96, 0);
expect(widths[3]).toBe(0);
});
it('samples only up to the axis length, not beyond', () => {
// Slab 80 px (5in) wide: 2nd sample at 96 px > lengthPx=80.
const { mask, width, height } = buildMask(200, 150, 80, 80, 0, 0);
const axis = { origin: { x: 0, y: 0 }, dir: { x: 1, y: 0 }, lengthPx: 80 };
const widths = sampleWidthsPx(mask, width, height, axis, 16);
expect(widths.length).toBe(1);
});
it('reports the real mask extent, not the photo extent', () => {
// Slab 80 px tall at y=35: the perpendicular sample must be 80,
// never the 150 px photo height.
const { mask, width, height } = buildMask(200, 150, 80, 80, 0, 35);
const axis = { origin: { x: 0, y: 35 }, dir: { x: 1, y: 0 }, lengthPx: 80 };
const widths = sampleWidthsPx(mask, width, height, axis, 16);
expect(widths.length).toBe(1);
expect(widths[0]).toBeCloseTo(80, 0);
});
});
+10
View File
@@ -0,0 +1,10 @@
import { describe, it, expect } from 'vitest';
// Smoke test for the M1-1 harness: proves the JS unit runner works end-to-end.
// This is deliberately trivial — later cards (M1-2+) replace it with the
// deterministic-core suite. It must pass to certify the harness is GREEN.
describe('M1 harness smoke', () => {
it('adds numbers (harness is live)', () => {
expect(1 + 1).toBe(2);
});
});
+14
View File
@@ -0,0 +1,14 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": false,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": false,
"moduleResolution": "bundler"
}
}
+11
View File
@@ -0,0 +1,11 @@
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [sveltekit()],
test: {
environment: 'node',
include: ['tests/unit/**/*.test.js'],
exclude: ['tests/e2e/**', 'node_modules/**', 'build/**']
}
});
+6
View File
@@ -0,0 +1,6 @@
{
"name": "SlabUploader",
"lockfileVersion": 3,
"requires": true,
"packages": {}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 988 KiB

@@ -0,0 +1,11 @@
{
"fixture": "dji_mimo_20260109_152422_20260109152421_1771310617476_photo.JPG",
"label": "cand_a",
"source": "\\\\truenas.local\\Business\\Samples",
"orientation": "irregular",
"sheet": "black",
"image_px": [4000, 2256],
"length_in": 28.0,
"thickness_in": 2.25,
"notes": "Organic/irregular slab shape; stress-test for min-area bounding rectangle + length-axis. Length is the longest axis of the slab."
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 604 KiB

@@ -0,0 +1,11 @@
{
"fixture": "dji_mimo_20260109_155754_20260109155755_1771310617107_photo.JPG",
"label": "cand_c",
"source": "\\\\truenas.local\\Business\\Samples",
"orientation": "horizontal",
"sheet": "black",
"image_px": [4000, 2256],
"length_in": 21.0,
"thickness_in": 1.75,
"notes": "Clean elongated slab, length runs horizontally. Second clean-case fixture."
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 592 KiB

@@ -0,0 +1,11 @@
{
"fixture": "dji_mimo_20260109_155818_20260109155817_1771310617082_photo.JPG",
"label": "cand_b",
"source": "\\\\truenas.local\\Business\\Samples",
"orientation": "horizontal",
"sheet": "black",
"image_px": [4000, 2256],
"length_in": 21.0,
"thickness_in": 1.75,
"notes": "Clean elongated slab, length runs horizontally. Primary clean-case fixture for expected sqft/bdft/widths."
}