Commit Graph

801 Commits

Author SHA1 Message Date
cf3f160148 chore(deps): backfill library traces for ADR-014 cluster
Approved traces for @sentry/nextjs, @sentry/opentelemetry,
@sentry/node, and @sentry/react — all at ^10.51.0 in
packages/core-shared. Without these files the pre-commit
library-trace hook would fire retroactively on any future
package.json touch; backfill establishes the baseline.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 09:53:04 +00:00
9e7723f9a5 fix(scripts): remove broken session-resume from dispatch loop
Some checks failed
CI / typecheck + lint + boundaries + test + build (push) Has been cancelled
CI / Playwright e2e (push) Has been cancelled
CI / Storybook smoke tests + visual regression (push) Has been cancelled
Coverage snapshot / snapshot (push) Has been cancelled
Release Please / release-please (push) Has been cancelled
Sentry PII guard (R31) / pii-guard (push) Has been cancelled
Sandcastle rejects `resumeSession` when `maxIterations > 1` with
"Resume applies to iteration 1 only; multi-iteration resume
semantics are not supported." Since a TDD slice needs the full
30-iteration budget, the session-resume path we shipped in d5c0120
is dead infrastructure that breaks dispatch mid-run.

Rip it out cleanly:
- runOneSlice drops the resumeSession param + the
  context-exhaustion safety net + sessionId/usage return fields
- executeDispatch drops the currentStory/currentSession bookkeeping
  and the token-reset threshold
- helpers totalInputTokens + isContextExhaustedError go (only used
  by the resume path)
- SANDCASTLE_SESSION_TOKEN_RESET removed from .env.example

Net: -153 lines. Each slice is again an independent sandcastle
session; token cost per slice goes up (each implementer
re-discovers context) but the multi-iteration TDD shape works.
A different cross-slice context-passing mechanism (e.g. a
story-level context summary injected into each task spec) is left
as future work.
2026-05-14 11:48:32 +02:00
68426b83b0 chore(work): tick task in 08-backfill-traces 2026-05-14 11:42:09 +02:00
091cd6d593 chore(deps): backfill library traces for ADR-002 cluster
Add approved trace files for inversify ^6.2.0 and reflect-metadata
^0.2.2, both mandated by ADR-002 (InversifyJS for DI) and used across
all five feature packages. Both pass validateTrace() from schema.mjs.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 09:40:29 +00:00
543412ea42 chore(work): finish 07-generator-pre-shipped-traces 2026-05-14 11:37:37 +02:00
b1e2e8a788 feat(tooling): pre-ship approved library traces in optional core generator templates
Each of the five optional core package generators (events, realtime, audit,
trpc, ui) now copies pre-written decision: approved trace files into
docs/library-decisions/ at scaffold time, covering every direct runtime
dependency of that core package.

This prevents a pre-commit gate failure the first time a developer runs
pnpm turbo gen core-package <name> — the generator is the policy-compliant
path, so the traces land by construction.

- Added docs/library-decisions/*.md.hbs trace files under each of the five
  core-package template directories (15 files total)
- Updated generator config to emit traces into workspace docs/library-decisions/
  via a second emitTemplateTree call per core package
- Updated all five __snapshots__/core-package/*.snapshot.json to include the
  new trace file entries
- Added verify-doc-shas.test.ts to pin SHA256 hashes of all 15 trace templates
  so snapshot and file content cannot drift independently

ADR refs: events→ADR-015, realtime→ADR-016, audit→ADR-018;
trpc and ui cite closest ADR or null where no specific ADR exists.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 09:34:17 +00:00
090410e9c3 chore(work): finish 06-sandcastle-reviewer-prompt 2026-05-14 07:58:55 +02:00
26bcbb7a91 feat(scripts): add --staged-against flag to library-decisions check
Adds `--staged-against <base>` CLI flag to `check.mjs` so the reviewer
agent can compare `git diff <base>...HEAD` instead of the git index.
This gives the sandcastle reviewer a CI-compatible code path that works
in its clean sandbox where `git diff --cached` may be empty.

Appends a "Library-trace check" section to `.sandcastle/reviewer.prompt.md`
instructing the reviewer to run the command before issuing a verdict.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 05:57:10 +00:00
6890526ced chore(work): finish 05-human-guide 2026-05-14 07:53:06 +02:00
603104ca97 docs(guides): add adding-a-library.md human reading-room guide
Translates ADR-022 from decision-record density into an onboarding
narrative: why the policy exists, the tier trigger, the four enforcement
layers, a step-by-step walkthrough, and worked approved/rejected examples
(clsx pass, trpc-to-openapi named-consumer fail).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 05:52:08 +00:00
1c6e0cefaf chore(work): finish 04-evaluate-library-skill 2026-05-14 07:49:48 +02:00
b10ccba927 feat(scripts): add evaluate-library skill + supporting files
Adds the /evaluate-library skill runbook at .claude/skills/evaluate-library/
with SKILL.md (8-filter + 3-prompt protocol, collect-cheap-skip-expensive
ordering, trace-write step, skip sentinel), POLICY.md (ADR-022 summary
≤2 pages), TRACE-TEMPLATE.md (complete YAML frontmatter + 11 headings in
order), and EXAMPLES/ with one approved (clsx) and one rejected
(trpc-to-openapi, named-consumer: fail) worked trace.

Updates session-start.sh to surface the skill in session pointers.
The skill is auto-registered by the harness on SKILL.md creation.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 05:45:43 +00:00
2941122f66 chore(work): finish 03-claude-hooks 2026-05-14 07:36:45 +02:00
b0191a7cbe feat(scripts): add library-policy-nudge hook + smoke tests
Registers .claude/hooks/library-policy-nudge.sh under PreToolUse/Bash
and PostToolUse/Edit|Write|MultiEdit. The hook emits a non-blocking
system-reminder pointing at /evaluate-library before runtime deps are
added via pnpm add or via direct package.json edits, so policy
evaluation happens before the pre-commit gate fires.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 05:34:29 +00:00
22c041fe65 chore(work): finish 02-pre-commit-check-script 2026-05-14 07:29:31 +02:00
a5355ee9e7 feat(scripts): add pre-commit library-decisions check + tests
Adds scripts/library-decisions/check.mjs that walks staged package.json
diffs, derives tier from path, and fails the commit when a new runtime
dependency in a feature- or core-tier package has no sibling approved
trace staged in docs/library-decisions/.

App-tier additions and devDependency / peerDependency additions are
silently allowed. Wired into .husky/pre-commit as step 4.

check.test.mjs covers all 7 Done-when cases using temp git repo
fixtures (node:test + node:assert, same pattern as schema.test.mjs).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 05:27:12 +00:00
99c7a9f1af chore(work): finish 01-trace-schema-foundation 2026-05-14 07:13:34 +02:00
f8908e5e4b feat(scripts): add library-decisions trace schema + template
Creates the shared schema module for library evaluation traces
(ADR-022 §4): Zod-validated frontmatter with all 8 filter fields and
enum constraints, plus parseTrace/validateTrace exports and a custom
YAML frontmatter parser for the nested trace format.

Also adds docs/library-decisions/_template.md with all 11 required
headings (8 Filter + 3 Prompt) in machine-checkable ADR-022 order.

Adds zod as a root devDependency so the script is runnable directly
from the workspace root without a package context.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 05:10:06 +00:00
16a03e026b chore(work): decompose 2026-05-14-library-evaluation-policy epic
Decomposer produced 9 stories under docs/work/2026-05-14-library-
evaluation-policy/, ordered to land the schema foundation first and
the cross-referencing content (skill, guide, backfill) last:

01 - trace schema module + docs/library-decisions/ foundation
02 - pre-commit check script
03 - Claude PreToolUse / PostToolUse hooks
04 - evaluate-library skill
05 - human guide (docs/guides/adding-a-library.md)
06 - sandcastle reviewer prompt update
07 - generator pre-shipped traces for optional cores
08 - backfill traces for existing runtime deps
09 - CLAUDE.md Key Conventions bullet

Anchored by ADR-022 + the approved PRD at
docs/work/prds/2026-05-14-library-evaluation-policy.prd.md.
2026-05-14 06:52:02 +02:00
7f1a8d0212 docs: introduce library evaluation policy (ADR-022 + PRD)
- ADR-022 codifies the tiered library-evaluation policy: 8 hard
  auto-reject filters (license, types, maintenance, boundary-fit,
  shadow-check, EU residency, CVE scan, named consumer), 3
  discussion prompts, per-decision trace artifact at
  docs/library-decisions/, and a 4-layer enforcement stack
  (Claude PreToolUse/PostToolUse hook -> evaluate-library skill ->
  pre-commit hook -> sandcastle reviewer prompt). Mirrors the
  conformance-system latency pattern from ADR-012.
- PRD at docs/work/prds/2026-05-14-library-evaluation-policy.prd.md
  seeds the implementation epic; status: approved, ready for
  \`pnpm work decompose\`.
- Glossary gains "Library trace" + "Pre-shipped trace" entries
  referenced by both artifacts.

Catalyst: the 2026-05-14 grill session nearly adopted
trpc-to-openapi + zod-to-json-schema before someone asked who the
HTTP consumer was. Honest answer: none -- all callers are TS via
createCaller. This policy makes that question structurally
unavoidable for any future feature- or core-tier dep.
2026-05-14 06:41:28 +02:00
52af9f1fdd chore(work): finish epic 2026-05-13-binder-wrap-helper 2026-05-13 20:41:18 +02:00
e17d60b8ac feat(navigation): update feature generator templates to emit wireUseCase
Replace inline withSpan(withCapture(factory(deps))) form in the binder
templates with wireUseCase({...}) calls so newly scaffolded features are
consistent with the migrated production features.

Also add assertFeatureConformance to bind-dev-seed.ts.hbs (aligns with
the migrated auth/navigation pattern) and fix bind-dev-seed.test.ts.hbs
to call binders with the ctx object form (BindContext) instead of the old
two-argument (tracer, logger) form.

Verified by running turbo gen feature testfeature and confirming:
  - Generated binders use wireUseCase for use cases
  - All 5 conformance gates pass on the scaffold
  - Scaffold cleaned up post-verification

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 18:36:30 +00:00
9800fed068 chore(work): finish 02-migrate-feature-binders 2026-05-13 20:25:08 +02:00
d67a89179e fix(scripts): exempt .env template files from diff-coverage gate
.env.example and siblings are config/template files with no executable
code. The coverage:diff script now matches them via the same dotfile
pattern used for .gitignore and .npmrc.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 18:22:19 +00:00
d5c01209ea feat(work): resume implementer session across same-story slices
Wires sandcastle's native `resumeSession` into the dispatch loop so
the implementer walks into task N already knowing what task N-1
discovered — repo layout, helper signatures, gate output, prior diff.
No scratchpad / no hand-curated context file; the agent's own Claude
Code conversation log is the carrier.

Three guardrails keep it bounded:

- Story boundary reset. `currentSession` is dropped whenever
  findNextTask returns a different story id. New domain ≈ new
  context — keeps story 03 from inheriting story 02's residue.
- Token-threshold reset. After each approved slice, sum the
  implementer's last-iteration usage (inputTokens +
  cacheCreationInputTokens + cacheReadInputTokens — caching saves
  dollars but doesn't free window space). If above
  SANDCASTLE_SESSION_TOKEN_RESET (default 140000 ≈ 70% of Sonnet
  4.6's 200k), drop the session before the next task. Configurable
  via env.
- Context-exhausted safety net. If the model rejects with
  "prompt is too long" / "context_length_exceeded" / similar, the
  retry loop drops the session and re-runs the attempt fresh
  exactly once. Doesn't count against SANDCASTLE_MAX_ATTEMPTS
  (different failure mode).

Reviewer always runs fresh — each approve/reject decision should be
independent of prior tasks to keep the gate honest. Within a single
slice's reject-fixup retries, the implementer also carries forward
across attempts (so attempt 2 sees attempt 1's reasoning + the
reviewer notes), but that's per-slice cumulative, not cross-slice.

runOneSlice now returns { sessionId, usage } so executeDispatch can
make the carry-or-reset decision per slice.
2026-05-13 20:13:30 +02:00
81a791c5fd refactor(navigation): migrate binders to wireUseCase for getHeader
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 18:08:42 +00:00
57e9d9805d chore(work): tick task in 02-migrate-feature-binders 2026-05-13 20:06:21 +02:00
dcc7edcd18 refactor(marketing-pages): migrate binders to wireUseCase for both use cases
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 18:04:34 +00:00
78a561ac60 chore(work): tick task in 02-migrate-feature-binders 2026-05-13 20:01:32 +02:00
b93ce25b2a refactor(media): migrate binders to wireUseCase for all 3 use cases
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 17:59:59 +00:00
0867efbaae chore(work): tick task in 02-migrate-feature-binders 2026-05-13 19:57:28 +02:00
43d88be4bd refactor(blog): migrate binders to wireUseCase for all 3 use cases
Replace inline withSpan + withCapture blocks for getArticles,
getArticleBySlug, and createArticle in both bind-production and
bind-dev-seed with wireUseCase calls.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 17:55:43 +00:00
7406171b0b chore(work): tick task in 02-migrate-feature-binders 2026-05-13 19:53:46 +02:00
88b41798d6 refactor(auth): migrate use-case binders to wireUseCase
Replace inline withSpan + withCapture blocks for signIn, signUp, and
signOut use cases in both bind-production.ts and bind-dev-seed.ts with
wireUseCase calls. Removes 27 lines of boilerplate per binder file.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 17:51:16 +00:00
e08e0a10c0 chore(work): finish 01-wire-use-case-helper
Catches up the story's checkbox + frontmatter status to reflect that
the slice shipped in commit 1bbe866. The V1 orchestrator landed the
implementer's slice commit on main but had no state-mutation step,
so the bullet stayed unticked and `pnpm work next` would have
redundantly re-dispatched the implementer for a no-op slice.

Bookkeeping-only — no code changes.
2026-05-13 19:43:45 +02:00
edbc6a8fad feat(work): dispatch loops + auto-ticks state on approve
Previously the orchestrator ran exactly one implementer + reviewer pair,
printed "(Automatic state mutation by the orchestrator is v2.)", and
exited — the human had to tick the bullet, flip story status, rebuild
state, and re-invoke for every slice. V2 closes the loop:

- Parses the JSON the implementer + reviewer prompts ask the agents to
  emit (`parseAgentJson` — tolerates both ```json fenced and bare
  trailing { ... } shapes). The reviewer's `decision` and the
  implementer's `status` are the orchestrator's discriminators.
- On approve: ticks the bullet in `_story.md` and writes it back. If
  the story now has zero unchecked bullets, flips its frontmatter
  `status: in-progress → done`; if all sibling stories are also done,
  flips the epic's frontmatter the same way. Commits the mutation on
  the host as a separate `chore(work): tick/finish ...` commit so the
  implementer's slice commit stays clean. `_state.json` regenerates
  via the existing pre-commit `rebuild-state` hook.
- On reject: re-dispatches the implementer with the reviewer's notes
  appended to TASK_FILE_CONTENT, bounded by SANDCASTLE_MAX_ATTEMPTS
  (default 3). On the (max+1)th reject the loop exits 1 with the last
  notes printed.
- After every approved slice, calls findNextTask again and dispatches
  the next ready bullet — including across story boundaries (the
  state-builder treats any non-done story with satisfied deps as
  ready, so flipping story 01 to done unblocks story 02 automatically).
- Flags: `--once` (legacy single-slice behavior) and `--max-tasks N`
  bound the loop. Default is unlimited — matches the
  continuous-execution preference.

Auth/sandbox setup is now pulled out of the per-iteration path so the
loop reuses one sandbox across slices.
2026-05-13 19:43:11 +02:00
1bbe866a5c feat(core-shared): add wireUseCase helper to conformance barrel
Encapsulates withSpan(withCapture(withAudit?(factory(deps)))) composition
and container binding into a single helper, eliminating the structural
boilerplate clone groups repeated across every feature binder pair.

Callers pass { container, symbol, factory, deps, feature, layer, name,
tracer, logger, auditLog? } and get back a fully brand-stacked, container-
bound wired value. Idempotent: unbinds an existing symbol before rebinding.

withAudit lives in core-audit which core-shared cannot import (dependency
inversion: core-audit depends on core-shared). The audit path here replicates
the same semantics — forwarding wrapper + __audited brand — without the
circular dependency.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-13 17:28:57 +00:00
317ec518aa docs(work): re-decompose binder-wrap-helper into vertical-slice stories
Re-decomposes the approved binder-wrap-helper PRD after the previous
8-story attempt (dropped in 71c04f5) sliced horizontally — its
"write test" / "write impl" splits would have left intermediate
commits red. The new shape obeys slice = task = PR = commit:

- 01-wire-use-case-helper — 1 task: ship the wireUseCase helper
  (factory composition + container bind + brand stack) with its
  unit tests and barrel export in one green commit. Blocks 02 + 03.
- 02-migrate-feature-binders — 5 tasks, one per feature
  (auth, blog, media, marketing-pages, navigation). Each task
  migrates that feature's bind-production.ts + bind-dev-seed.ts
  together and keeps all gates green.
- 03-update-generator-templates — 1 task: update the feature
  generator's bind-*.hbs so future scaffolds emit wireUseCase
  directly instead of inline withSpan + withCapture.

Output of the now-fixed sandcastle decompose dispatch — depends on
the completionSignal + maxIterations wiring (eadbb7e, 26aa97f).
2026-05-13 19:17:10 +02:00
eadbb7ebd9 fix(work): emit completion signal to stop sandcastle agent loops
Sandcastle re-invokes agents up to maxIterations even when the work is
already done — the decomposer was looping 4x re-writing the same epic
on every dispatch. Two halves to the fix:

- Pass completionSignal: "<promise>COMPLETE</promise>" explicitly on
  all three run() calls (decompose, implementer, reviewer). Makes the
  contract visible alongside maxIterations instead of relying on
  sandcastle's default.
- Append a "Signal completion (required)" section to each prompt
  telling the agent to emit the literal marker as its final line when
  the work is genuinely done, plus a "do NOT emit if..." list to
  discourage premature signaling.
2026-05-13 19:11:44 +02:00
d6bf2f638f docs(env): document sandcastle iteration env vars in .env.example
The three SANDCASTLE_*_ITERATIONS overrides landed inline in
decompose.mjs and dispatch.mjs (commit 26aa97f) but weren't
surfaced in .env.example. Adds them with the same tuning guidance
the inline comments carry, so users discover the knobs from the
canonical env reference instead of having to grep the code.
2026-05-13 18:57:50 +02:00
26aa97f0ef fix(work): bump sandcastle maxIterations so agents finish + commit
Sandcastle's default maxIterations: 1 cut every agent off after its
first response, so files written inside the sandbox never made it
into a captured commit. The decomposer wrote 9 epic + story files,
hit the limit, and sandcastle returned 0 commits — the host saw
nothing.

decompose.mjs: maxIterations 10 (small authoring task — read
context, write files, commit). Override via env
SANDCASTLE_DECOMPOSE_ITERATIONS.

dispatch.mjs:
- Implementer: maxIterations 30 (full TDD slice — read context,
  red test, green impl, run all five gates, commit). Override via
  SANDCASTLE_IMPLEMENTER_ITERATIONS.
- Reviewer: maxIterations 10 (read diff + task spec, decide).
  Override via SANDCASTLE_REVIEWER_ITERATIONS.

Each call site documents WHY the value was picked + names the env
override inline so tuning is discoverable from the code.
2026-05-13 18:56:59 +02:00
71c04f521a docs(work): drop binder-wrap-helper epic for re-decomposition
The stories were decomposed by the previous (unconstrained)
decomposer prompt — their Tasks lists were horizontal sub-steps
(read file → write impl → write test → export → run gates) instead
of the slice = task = PR = commit rule now enforced in fd8265c.

Removing the folder clears the way for a fresh `pnpm work
decompose 2026-05-13-binder-wrap-helper --execute` run under the
updated prompt. The PRD itself (status: approved) is unchanged.
2026-05-13 18:41:37 +02:00
fd8265cd29 docs(sandcastle): decomposer + reviewer enforce vertical-slice tasks
The user surfaced that the binder-wrap-helper epic's stories
decomposed into horizontal sub-steps (read 3 files → write helper
→ write test → export → typecheck → coverage), not vertical
slices. Per the glossary's slice = task = PR = commit rule, every
checkbox should land as one green commit.

.sandcastle/decomposer.prompt.md:
  - New "The slice rule (non-negotiable)" section near the top
    defining the three constraints every task must satisfy: one
    green commit; exercises a layer; independently meaningful.
  - New "Tasks that are FORBIDDEN" list naming the anti-patterns
    the previous output exhibited (read a file as a task; write
    test without impl; standalone gate runs; standalone export;
    sub-step decomposition of a single slice).
  - New "Tasks that are CORRECT" list with examples drawn from
    this codebase (gen invocation, full use-case slice, per-feature
    binder migration, audit emission, bindAll wiring).
  - New paragraph on "Manifest-first ordering INSIDE a task" —
    the 4-step ordering (manifest → contracts → red test → green
    impl) is what the implementer does within one task, not a
    multi-checkbox decomposition.
  - Constraints section gains two new bullets:
      * Prefer FEWER but FATTER tasks (one per vertical slice)
        over MANY thinner sub-steps
      * Self-check: imagine the commit each checkbox produces;
        do all gates pass on that commit alone?

.sandcastle/reviewer.prompt.md:
  - New check #8 "Slice discipline" rejecting:
      * Multi-commit diffs where any intermediate commit has red
        gates
      * Sub-step shape that should have been separate tasks
      * Incomplete slices (use case w/o DI binding, manifest
        publish w/o publish site, controller w/o router wiring)

.gitignore: adds `.pnpm-store/` so a misconfigured pnpm install
that places the store inside the project doesn't stage thousands
of cache files.

The existing binder-wrap-helper stories were decomposed under the
old (unconstrained) prompt and need re-decomposing under the new
rule. That's a separate action — this commit fixes the prompts;
the existing epic stays as-is until you re-decompose.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 18:33:34 +02:00
52b4409d94 docs(work): refresh stale JSDoc headers in cli + prd-ship
Two stale-comment fixes surfaced after the dispatch handoff fix:

cli.mjs: the top-of-file JSDoc listed only 3 of 8 subcommands
(rebuild-state, status, next) and missed ready / blocked /
dispatch / decompose / prd-ship. Rewrote the header to describe
all 8 subcommands + their flags + the explicit-runCli routing
pattern that replaces the older side-effect-on-import approach
(established when the dispatch handoff broke and got fixed in
bb643b8).

prd-ship.mjs: the JSDoc claimed allowed transitions were
"<approved|in-review|draft> -> shipped", but the code refuses
draft (throws "still draft — flip to approved (human review)
before shipping"). Corrected the doc to "<approved|in-review>
-> shipped" + clarified that draft -> approved is the human step
deliberately kept outside the command's scope.

No behaviour change — comments only.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 18:18:42 +02:00
bb643b8635 fix(work): dispatch CLI handoff broke after import-side-effect guard
cli.mjs's `dispatch` branch called `import("./dispatch.mjs")` and
relied on dispatch.mjs's top-level CLI block running as a side
effect of the import. The earlier guard added to dispatch.mjs (to
stop the CLI firing when sibling work scripts import
`resolveClaudeAuth`) also stopped this legit handoff — so
`pnpm work dispatch` silently exited with no output.

Fix: explicit CLI entry function, called by name. Same pattern
already in use for prd-ship + decompose.

dispatch.mjs:
  - Wraps the args parsing + print/execute branch in `export async
    function runCli(args)`
  - The invokedDirectly guard now wraps `runCli(process.argv.slice(2))`
    so direct-invocation (`node scripts/work/dispatch.mjs ...`) still
    works

cli.mjs:
  - Imports runCli as runDispatch
  - The `cmd === "dispatch"` branch calls runDispatch(args) directly
    with a .catch attached (instead of import("./dispatch.mjs"))

Verified: `pnpm work dispatch` now correctly prints the dispatch
plan for the first ready task (`binder-wrap-helper /
01-wire-use-case-helper`'s first bullet); decompose tests stay 9/9.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 18:17:47 +02:00
6f18075593 docs(work): decompose binder-wrap-helper PRD into epic + 8 stories
Output from `pnpm work decompose 2026-05-13-binder-wrap-helper
--execute` — sandcastle ran the decomposer agent with subscription
auth (after the macOS keychain workaround + Dockerfile fix from
prior commits). The agent wrote files but hit `Max iterations: 1`
before committing, so this commit carries its output unchanged.

Epic: docs/work/binder-wrap-helper/
  - _epic.md links to PRD 2026-05-13-binder-wrap-helper
  - features: [core-shared, auth, blog, media, marketing-pages,
    navigation, tooling]

Stories (8 total, with dependency edges):
  01-wire-use-case-helper           prereq (blocks 02..07)
    Goal: helper at core-shared/conformance/wire-use-case.ts +
    tests covering brand stacking, span/capture/audit composition,
    idempotent bind. depends-on: [], blocks 02..07.
  02-migrate-auth-binders           depends-on [01]
  03-migrate-blog-binders           depends-on [01]
  04-migrate-media-binders          depends-on [01]
  05-migrate-marketing-pages-       depends-on [01]
    binders
  06-migrate-navigation-binders     depends-on [01]
  07-update-feature-generator       depends-on [01]
  08-holistic-validation            depends-on [02..07], blocks: []
    Final gate suite + fallow dupes check to verify the 5 binder-
    pair clone groups have disappeared.

After 01 lands, stories 02..07 are parallelisable; 08 collects them.

Pre-commit hook regenerates _state.json + re-stages it so `pnpm
work next` immediately surfaces the new ready story.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 18:10:31 +02:00
9d4b801909 fix(work): wire inline macOS keychain hint into dispatch + decompose error paths
The dispatch.mjs + decompose.mjs error handlers grew an image-not-
found hint in cd0a332 but the macOS keychain hint that the earlier
commit's message claimed wasn't actually applied (the Edit tool
required re-reading those files post-commit).

This commit applies the keychain hint to both error handlers: when
the sandcastle error matches /Not logged in|Please run \/login/ AND
process.platform === "darwin", the dispatcher prints the
`security find-generic-password ... > ~/.claude/.credentials.json`
one-liner + chmod 600 + the API-key fallback inline above the
generic "See runbook" line.

Now future agents hitting this on macOS see the fix at the failure
site, not just in docs.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 18:03:13 +02:00
7737358509 fix(sandcastle): make Dockerfile match sandcastle's expected shape + document macOS keychain quirk
Two separate sandbox blockers surfaced when the user tried
`pnpm work decompose --execute`:

1. **Container died on exec** — our Dockerfile had:
     - WORKDIR /workspace + CMD ["bash"]
     - No `agent` user (sandcastle exec's as UID:GID it built with)
     - node:22-bookworm-slim (missing some build deps the install
       script wants)
   Sandcastle expects:
     - A non-root `agent` user with home at /home/agent (sandcastle
       does `git config --global --add safe.directory /home/agent/workspace`,
       which fails if the user doesn't exist or the container exited)
     - ENTRYPOINT ["sleep", "infinity"] so the container survives
       the gap between sandcastle creating it and exec'ing in
   Replaced .sandcastle/Dockerfile with the shape `sandcastle init`
   would generate (verified against
   node_modules/@ai-hero/sandcastle/dist/InitService.js):
     - node:22-bookworm (full, not slim) for build tooling
     - apt-get installs git + curl + jq
     - corepack-pinned pnpm@9
     - ARG AGENT_UID=1000 + AGENT_GID=1000; sandcastle's
       build-image passes the host's UID/GID by default
     - `groupmod -o -g $AGENT_GID node` + `usermod -o ... node` —
       the `-o` (non-unique) flag is required because macOS hosts
       have UID:501 GID:20, and GID 20 collides with Debian's
       `dialout` group in the base image (without -o, groupmod
       fails with "GID '20' already exists")
     - USER ${AGENT_UID}:${AGENT_GID}, then install Claude Code CLI
       via the official installer
     - ENV PATH includes /home/agent/.local/bin
     - WORKDIR /home/agent (sandcastle overrides per-run anyway)
     - ENTRYPOINT ["sleep", "infinity"] keeps the container alive

2. **"Not logged in · Please run /login"** inside the container —
   Claude Code on macOS stores credentials in the Keychain, NOT in
   ~/.claude/.credentials.json. Sandcastle's bind-mount of ~/.claude
   finds nothing usable. Documented the workaround:
     - README.md "Sandcastle setup (one-time)" — macOS-specific
       block with the `security find-generic-password ... > ~/.claude/.credentials.json`
       one-liner + chmod 600 + the security trade-off (plaintext
       file vs keychain isolation)
     - docs/guides/runbook.md "Using Sandcastle → Prerequisites" —
       step 3 (Authentication) gets a "macOS quirk" subsection with
       the same extraction one-liner + the API-key fallback as the
       alternative path
     - scripts/work/{dispatch,decompose}.mjs — when the sandcastle
       error matches /Not logged in|Please run \/login/ AND we're on
       darwin, the dispatcher prints the keychain-extraction
       commands + the API-key fallback inline above the generic
       "See runbook" line, so future agents discover the fix at the
       failure site

The image rebuilds clean (`pnpm exec sandcastle docker
build-image`) at ~1.95GB and the container survives sandcastle's
exec — confirmed by reaching the "Not logged in" stage (which is
the next-layer issue, not the Dockerfile issue).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 18:02:34 +02:00
cd0a332443 docs: surface sandcastle image-build step (one-time setup)
Closes the gap the user hit running `pnpm work decompose --execute`:
sandcastle errored with `Image 'sandcastle:template-vertical' not
found locally. Build it first with 'sandcastle docker build-image'`,
but neither the README nor the runbook documented this step.

README.md: new "Sandcastle setup (one-time)" section after Quick
reference. Three commands (docker info, build-image, auth) — the
minimum needed to make dispatch work. Links to the runbook for the
full lifecycle.

docs/guides/runbook.md: Prerequisites in "Using Sandcastle" grow
from 4 to 5 items. New step 2 walks through `sandcastle docker
build-image`, quotes the exact "Image not found locally" error so
agents searching for the string land on the fix, and shows the
remove-image + rebuild flow for Dockerfile edits.

.sandcastle/README.md: new "Build the sandbox image (one-time)"
section parallel to the env section, cross-linking to the runbook.

scripts/work/decompose.mjs + scripts/work/dispatch.mjs: when the
sandcastle error message matches the "Image '.+' not found locally"
pattern, the dispatcher now prints the build-image command inline
above the generic "See runbook" line. The error stack itself remains
unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 17:51:30 +02:00
014578c9a8 feat(work): pnpm work decompose subcommand
Closes the gap surfaced by the user: `pnpm work` usage referenced
`decompose` (via docs + the to-prd skill) but the subcommand was
never built. Mirrors `pnpm work dispatch`'s shape.

scripts/work/decompose.mjs (new):
  - validatePrdForDecompose(prdPath) — refuses draft (must go
    through human review first), in-review (review incomplete),
    shipped (epic already exists); accepts only approved
  - printDecomposePlan(prdId, prdPath, frontmatter) — print-mode
    output showing the PRD's eligibility + sandcastle invocation
    plan + auth modes
  - executeDecompose(prdId, prdPath, prdText) — invokes sandcastle
    with .sandcastle/decomposer.prompt.md, passing PRD_FILE_CONTENT
    promptArg. The decomposer agent writes the epic + per-story
    files to disk on a sandcastle branch the human can review
  - runCli(args, { workRoot }) — entry point used by cli.mjs
  - Direct invocation also supported (mirrors dispatch.mjs's
    invokedDirectly guard, NEW pattern after this commit)

scripts/work/decompose.test.mjs (new, 9 tests, all green):
  - validatePrdForDecompose: accepts approved; rejects draft,
    in-review, shipped, unknown status, missing file
  - runCli: writes error + returns 1 on missing PRD; writes error
    + returns 1 on draft PRD; prints plan + returns 0 on approved

scripts/work/cli.mjs:
  - Adds `decompose` subcommand to usage + dispatch
  - Usage formatting realigned for the 3-line subcommand block

scripts/work/dispatch.mjs:
  - **Fix** the bug surfaced by the user: dispatch.mjs's CLI ran
    as a top-level side effect whenever any of its exports was
    imported. decompose.mjs imports resolveClaudeAuth from it, so
    importing decompose.mjs printed "No ready task to dispatch."
    Added an `import.meta.url === \`file://${process.argv[1]}\``
    guard so the CLI only runs when invoked directly. This unblocks
    cross-import without side effects.

Smoke-tested end-to-end:
  - `pnpm work decompose` (no id) prints usage + exits 2
  - `pnpm work decompose 2026-05-13-binder-wrap-helper` prints the
    decompose plan with status: approved (eligible)
  - 9/9 unit tests green
  - dispatch.mjs's existing direct-invocation path unchanged

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 17:46:57 +02:00