roster
CLAUDE.md18 starsChanged 3 months agoMITView on GitHub
First time opening this repo in Claude Code? You'll see a one-time prompt asking permission to load .forge/CONTEXT.md. Accept it — without that approval, Claude Code silently skips the import and the methodology context won't be available. @.forge/CONTEXT.md The import below pulls in THIS project's spec — the synthesized BRIEF/PRD/SPEC (the "what", vs. the methodology "how" above). It is committed and generated by /ingest-spec (a stub until you run it), so it travels with the repo. @spec/CONTEXT.md <!-- <<< forge-managed…
- Installs packages
In this repositoryOne other file it gives its agents.
- AGENTS.mdAGENTS.md
The file
We split this CLAUDE.md into the rules it gives an agent
7 rules. About 0 are common, 3 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈3
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 96
Add the tool's config-dir constant to src/lib/tools.ts (e.g., ~/.somewhere/skills/).
- Very specific: line 97
Add a Tool entry to detectTools() returning the key + name + targets.
- Very specific: line 99
Add a test case in test/install.test.ts exercising the new target.
- Distinctive: line 100
Update README.md install matrix.
- Distinctive: line 106
Prefer hand-rolled argv parsing over commander/yargs to keep tarball small.
- Distinctive: line 107
No comments unless behavior is non-obvious.
- Very specific: line 117
Start here, then check .forge/CONTEXT.md for build methodology and tracker/phase rules, then README.md and docs/HOWTO.md.
≈ “Common” is an estimate: at least 1 in 5 of the 29,248 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
<!-- >>> forge-managed (do not edit between markers) >>> -->This project uses Forge. The methodology below is imported from a local file regenerated by
forge upgrade. New collaborator? Install Forge with:npm install -g @firatcand/forge forge upgradeFirst time opening this repo in Claude Code? You'll see a one-time prompt asking permission to load
.forge/CONTEXT.md. Accept it — without that approval, Claude Code silently skips the import and the methodology context won't be available.
@.forge/CONTEXT.md
The import below pulls in THIS project's spec — the synthesized BRIEF/PRD/SPEC (the "what", vs. the methodology "how" above). It is committed and generated by
/ingest-spec(a stub until you run it), so it travels with the repo.
@spec/CONTEXT.md
<!-- <<< forge-managed <<< -->roster — CLI Contributor Guide
This repo builds and ships @firatcand/roster, an npm CLI that installs/scaffolds the agent-team pattern across Claude Code, Codex CLI, and Gemini. See README.md for the user-facing pitch; this file is for contributors working on the CLI itself.
Working on Roster? This file describes Roster the product — what it is, where things live, how it builds and ships.
For the Forge methodology we use to build Roster (principles, planning workflow, branch strategy, GitHub-Issues-as-source-of-truth, worktree/PR rules), see
.forge/CONTEXT.md. Keep the two sets of rules separate so they do not bleed into each other.
Repo layout
src/ CLI source (TypeScript, ESM, Node ^22.18 || >=24)
bin/ roster.ts — argv parsing, subcommand dispatch
commands/ init.ts, (doctor.ts coming Phase 2)
lib/ tools.ts (detection + install), paths.ts (ROSTER_ROOT, getPackageVersion)
bin/ Build output — bin/roster.js is the executable entry. Gitignored.
lib/ Build output for library exports. Gitignored.
templates/ Files copied into a user's workspace by `roster init`.
scaffold/ Directory tree mirrored verbatim into the user's CWD.
CLAUDE.project.template.md, env.example, gitignore-defaults.txt
skills/ Skills shipped to AI tools by `roster install`. One dir per skill.
agents/ Agent .md files shipped alongside skills (Claude Code only).
test/ Node test runner specs + smoke.sh integration test.
docs/ Public docs. docs/adr/ contains historical implementation records, not active product-spec decisions.
.forge/ Forge methodology rules + worktree harness state (not shipped).
spec/ Tracked durable product authority — BRIEF, PRD, SPEC, CONTEXT, and ephemeral decisions.
plans/ Tracked design/decomposition snapshot — GitHub owns live execution state.GitHub Issues owns live task status, assignment, sequencing, and blockers. Query GitHub for routine tracker-state reads and use read-only/dry-run reconciliation. Run a non-dry forge orchestrate reconcile --pull only when its resulting plans/phases.yaml snapshot will be committed, including the one-time post-bootstrap refresh that replaces the dangling spec_revision.
Shipped to npm (verified via npm pack --dry-run): bin/, lib/, skills/, agents/, templates/, data/, README.md, LICENSE. This is the exact package.json#files allowlist; tracked .forge/, spec/, and plans/ artifacts never ship.
Build & verify
pnpm install # node 22+
pnpm typecheck # tsc --noEmit
pnpm build # tsdown → bin/roster.js with shebang
pnpm test # node --test on test/**/*.test.ts
pnpm smoke # bash test/smoke.sh — pack, install, init end-to-end
pnpm perf # bash test/perf.sh — measure install/init/doctor + tarball against SPEC budgets (dev-machine only)
pnpm test:scaffold-scripts # test/new-agent-slash-only.sh + test/audit-agent-guideline-refs.sh — exercises templates/scaffold/scripts/
npm pack --dry-run # confirm tarball stays clean (~554 kB packed, 86 files after `pnpm build`; -2 retired v1 dreamer templates #359)The Phase gate command (run before opening a PR): pnpm typecheck && pnpm build && pnpm test && pnpm test:scaffold-scripts && pnpm smoke.
Where things live in the CLI
- Subcommand entry:
src/bin/roster.ts— hand-rolled argv parsing; subcommandsinstall,init,update,upgrade,doctor,schedule,review,skills,hooks,pending,migrate,brain,task,ops.--help,--version, exit codes (0/1/2/3). - V2 workspace update:
src/commands/update.ts(roster update) preflights the sparse workspace, synchronizes only unedited generated host activation, and regenerates the deterministic.roster/vendor-skill-map.jsonfrom complete secret-free tool-use definitions. It never installs global vendor skills or probes host caches. Invalid/incomplete tool guidance fails before any update write.src/lib/update-args.tsparses--cwd/--json. - Host adapter contract:
src/lib/generated-artifacts.ts#HOST_ADAPTER_LIFECYCLE_CAPABILITIESis the single capability catalog and renderer for the host-neutralROSTER.mdlifecycle and thin Claude Code/Codex activation pointers.src/lib/context-trust.tsowns the ordered trust classes shared by generated guidance and context results. Keep lifecycle policy out of host-specific wrappers. Drift is split by the hash chain (#365): a hash-valid generated file diverging from the current render isstale-generated/GENERATED_FILE_STALE(safe to regenerate), a hash-broken one is edited/GENERATED_FILE_EDITED(refused), anddetectGeneratedShadows— one detector feeding update, validate, and doctor — scansCLAUDE.md/CLAUDE.local.md/GEMINI.md/AGENTS.override.mdplus a bounded recursive.claude/rules/**walk (256 entries / depth 8, both exhaustions blocking) for copied generated contracts a host would auto-load (GENERATED_SHADOW, report-only — Roster never writes at shadow paths). - Tool detection:
src/lib/tools.ts—detectTools()checks~/.claude/,~/.codex/,~/.gemini/. EachToolhaskey,name,skillsTarget,agentsTarget. Override viaROSTER_CLAUDE_HOMEetc. for tests. - Install logic:
installToTool()insrc/lib/tools.ts— copiesskills/*andagents/*.mdinto the tool's config dir. Idempotent. Handles symlinks (prompts before clobber). Handles EACCES with a sudo hint. - Scaffold logic:
src/commands/init.ts— copiestemplates/scaffold/**into CWD, substitutes{{PROJECT_NAME}}inCLAUDE.project.template.md, appends gitignore-defaults idempotently. - Schedule schema:
src/lib/schedule-schema.ts— Zod-validatedscheduleEntrySchema(name, agent, plan, cron, tool, install_mode, status). Requiredstatusenum ispending-ui-install | installed.validateCronExpression()for cron syntax. - Schedule install (Claude):
src/lib/schedule-install.ts—installClaudeSchedule()renders.roster/schedule-specs/<name>.claude.fields.md(markdown, NOT JSON — Spike 2) and upsertsroster/<function>/schedules.yamlatomically. UI hand-off only; tracked under anthropics/claude-code#41364. - Schedule install (Codex):
src/lib/codex-install.ts—installCodexSchedule()with two modes:ui-handoff(default; renders<name>.codex.fields.mdfor the Codex desktop app) andvia-cron(--via cron; renders a hardened crontab line wrapped byenv -i, installed viasrc/lib/codex-cron.tsmarker-block upsert). All entries include asubscription_attestationblock (auth_mode/env_policy/codex_home) verified bysrc/lib/codex-preflight.ts. Marker ids are function-scoped (<function>/<schedule>); the pre-#323 BARE<schedule>marker is adopted only when BOTH guards hold — the name is registered by exactly one function in the workspace (functionsRegisteringSchedule→legacyMarkerIsAmbiguous) AND the block's own rendered channel path proves that function (legacyMarkerOwnedBy). install/remove refuse an ambiguous block; doctor reports it asambiguous-legacy-marker. - Shared YAML helpers:
src/lib/schedule-yaml.ts—atomicWriteFile,readExistingSchedulesDoc,upsertEntryInDoc. The upsert refuses to overwrite an existing entry with a differenttoolvalue to prevent silent same-name cross-tool collisions. - Schedule commands:
src/commands/schedule.ts—executeScheduleValidate()andexecuteScheduleInstall(). The install command preflights--cloud-routine(not-yet-implemented), Linux +--tool claude(no Desktop Scheduled Tasks on Linux),--via cron(codex-only; refused on Windows),--tool codexdefault mode (refused on Linux — no Codex Desktop). - Failure observability (ROS-42):
src/lib/cron-exit-log.tsreads siblinglogs/cron/<name>.exit/.events.jsonlfiles written by therenderCronLinewrap (create-only underset -Cnoclobber after anrm -f— a planted symlink at the exit path is never followed; a failed create means NO exit file, which the stale path surfaces). Every read of an agent-writable evidence/registry/correlation file —<fireId>.exit,<fireId>.run-id(list AND the create-only conflict arbitration),roster/<fn>/state.md,roster/<fn>/schedules.yaml(ALL readers: schedule list/resolve, the install/remove upsert inschedule-yaml.ts,schedule-validate.ts, doctor's entry listing), androster/<fn>/pending/*.md— goes through the leaf modulesrc/lib/evidence-read.ts#readEvidenceFileSync(O_NOFOLLOW + O_NONBLOCK + fstat regular-file + read-to-EOF under amaxBytes+1bound;schedule-state.tsre-exports it, and the local ops ledger imports it directly — the split exists so the ledger can share one hardened reader without an import cycle), so a planted FIFO/symlink/oversized file is reported as malformed by each caller's own error path and can never block or divert a reader, and a concurrent append tostate.mdcan never truncate a complete line into a false STALE. A symlinkedschedules.yamlis refused, not followed.O_NOFOLLOWcovers only a path's FINAL component, so every DIRECTORY walk over the workspace tree (scanPending,listFunctionDirs/loadSchedules/readScheduleEntries,findScheduleFiles,listExitRecords/listScheduleRuns, doctor's entry listing) and every mutation (atomicWriteFile,readExistingSchedulesDoc,approveItem/rejectItem) is confined through ONE primitive insrc/lib/workspace-path.ts—resolveConfinedPath(path, boundary), which walks EVERY path component strictly below the boundary withlstatand refuses ANY symlink component regardless of where it points, plus a realpath belt that can only ever add a refusal. Earlier rounds used realpath CONTAINMENT (accept if the resolved chain lands inside the workspace), which by construction blessed an IN-WORKSPACE symlinked ancestor:roster/gtm/pending/acknowledged -> <ws>/archive/ackssuppressed a real failed fire, androster/ops -> gtmaliased two function identities onto one registry. Both of the primitive's inputs are ABSOLUTE by contract (assertAbsolutePath): it used to resolve a RELATIVE target beneath a RELATIVE boundary, so--cwd repo(process cwd/parent) made a caller's already-prefixedrepo/roster/…become/parent/repo/repo/roster/…— confinement inspected a phantom path while every caller afterwards opened the real one (run listreported no runs,run startreplaced the ledger's producer identity, and a symlinked component on the REAL path was never walked). Every--cwdparse site now normalizes withresolve()and a relative input THROWS instead of being re-prefixed; the one caller-authored workspace-RELATIVE input (pending front-mattertarget_on_approve) goes through the explicitresolveWorkspaceRelativePath.targetWithinWorkspace,confinedWorkspaceDir,confinedFunctionDir/resolveFunctionDir,functionDirWithinRosterandconfinedProbeSyncare all thin wrappers over that primitive;ancestorsConfinedis the flavor for readers that own their final component throughO_NOFOLLOW(readWorkspaceEvidenceFileSyncfolds a refusal into the existingmalformedtaxonomy asoutside-workspace, so a symlinked evidence FILE keeps its precisenot-a-regular-filereason). So a symlinkedroster/gtmorroster/gtm/pendingcan never divert a read, a rewrite, or an unlink — to another repository or to another directory of the same workspace. The workspace is not the innermost boundary: a function name is a caller-supplied path segment (--function, the<function>/<agent>positional), and../archive— or an in-workspaceroster/gtm -> ../archive— satisfies the workspace check while leaving the registry, soschedule remove --function ../archiverewrote a siblingschedules.yaml. Function names are now validated by ONE strict kebab rule at every argument boundary (workspace-path.ts#isFunctionName, used byschedule-args,run-args,review-args) and every resolved function directory is confined beneath<workspace>/roster/—confinedFunctionDirfor reads (listFunctionDirs/loadSchedules/readScheduleEntries/findScheduleFiles/scanPending/pending-sync/review) andfunctionDirWithinRosterfor the create-on-first-use write path (assertFunctionDirWithinRoster, shared by both installers). Existence probes over agent-writable paths (theacknowledged/sentinels, both pending destinations, the approve target) use the tri-stateconfinedProbeSyncinstead ofexistsSync, so a symlinkedacknowledged/can no longer classify a failed fire as acknowledged and silently suppress its decision item.src/lib/schedule-state.ts#detectStaleanswers "is the agent self-report older than expected next-fire + grace?".src/lib/pending-sync.tssynthesizesroster/<fn>/pending/error-<id>.mditems from non-zero.exit+ STALE — idempotent viasha1(scheduleName + signalKey).slice(0,8).src/commands/pending-sync.tsis the CLI;src/lib/doctor-scheduling-drift.ts#auditStaleFiresis the doctor cross-reference.templates/hooks/banner.shv3 invokesroster pending sync --silent(withtimeout 5) on SessionStart before counting items, so failures from between sessions surface in the next chat; the banner reads⚠ You have N unread decision(s) awaiting — run /inbox. - HITL review / inbox (ROS-132):
roster reviewis the engine.src/lib/pending-apply.tsholds the shared apply logic (approveItem/rejectItem, both re-confining the item path before rename/unlink; the boundary itself —targetWithinWorkspace/confinedWorkspaceDir/workspaceRelative— lives in the leaf modulesrc/lib/workspace-path.ts) pluscomputeItemId(sha1(function/filename).slice(0,8)) andresolveItemBySelector(path-then-id).roster review --jsonlists items with anid;--approve/--reject <id|path>apply one headlessly (before the TTY guard).skills/inbox/SKILL.mdis the cross-tool/inboxfront door — a chat-driven router over those verbs (no TTY). "Unread" is a rebrand of the pending count; no read/seen state. - Task state machine (ROS-147, v1.5.0):
src/lib/tasks/—machine.ts(pure canonical transition table:ready → claimed → active → review → done,blocked/cancelledbranches),context.ts(tracker.yaml load,deriveCurrentStateincl. assigned-Ready→claimed overlay,planVerbcollapse over unmapped stages,resolveSelector),tracker-schema.ts(Zod config),setup.ts(board introspection wizard),adapters/(types.tsgenericTrackerAdapter,notion.tsv1 impl — sole layer touching Notion). Verbs + reports live insrc/commands/task.ts(applyVerb,composeReport= stable flatlist,composeDigest=statusstage digest + attention).skills/tasks/SKILL.mdis the/taskschat front door (never writes the tracker directly). Interactive only — no autonomous pickup. - Expert-route drift guard (ROS-129):
src/lib/founder-skills/expert-routes.ts—parseExpertRoutes+ theKNOWN_FOUNDER_SKILLSallowlist (+BUILTIN_SKILL_EXCEPTIONS, e.g.frontend-design). Guard pair:test/expert-routes.test.tspinstemplates/scaffold/*/EXPERT.mdroutes to the allowlist (hermetic;ROSTER_NETWORK_SMOKE=1adds a live GitHub-catalog verify), andsrc/lib/doctor-expert-routes.ts#auditExpertRouteswarns inroster doctorwhen a workspace EXPERT route isn't covered byfounder-skills.yaml(expert_routesin--json) — warning-only, never flips the exit code; not-applicable without (or with an invalid) manifest, drift.ts owns the fail-loud path. - Ops persistence boundary (#318):
src/lib/persistence/—contracts.ts(store interfaces + error taxonomy +committed|queuedwrite outcomes),config-schema.ts(roster/persistence.yaml, credential-free),local/(append-only JSONL ledger + stores; the READ side is confined byconfinedLedgerDir— the read-only sibling ofensureOwnedDirover the same component-wise no-follow primitive, creating nothing and repairing no mode — soscan/meta/readLedgerMetarefuse a symlinked.roster/ops/<workspaceId>instead of reconstructing (and locking, recovering, sealing) a FOREIGN ledger tree;meta.json, the seal sidecars,persistence.yamland the setup journal are read through the hardened bounded reader, and the lock + segment reads openO_NOFOLLOW|O_NONBLOCKwith an fstat regular-file re-proof; create-once publication islink(2)→O_CREAT|O_EXCL-at-the-final-name → refuse, never a replacing rename, andgetArtifact/headshare one descriptor-verified (O_NOFOLLOW+ regular-file) digest-checked blob read),outbox.ts(durable spool: fold-over-events, backlog barrier, poison parking; the spool + checkpoint READS are confined too —spool/and the outbox namespace dir go throughconfinedLedgerDir, spooled bytes through the descriptor-verifiedreadRegularFileSync(digest-bounded, the artifact/blob policy) andoutbox/checkpoint.jsonthrough the hardened bounded reader at the 64 KiB sidecar cap, so a symlinkedspool/can neither divert nor chmod a foreign file and a FIFO atcheckpoint.jsoncan no longer hang a drain after its remote commits),postgres/(binding.tsstrict 1:1 workspace↔DB stamp verified per connection,roles.tsleast-privilege gate,stores.ts),objects.ts(dedicated-bucket create-only store +roster-workspace.jsonmarker +listPrefixfor repair/doctor),resolve.ts(resolveOpsBackend(cwd)— the seam #320/#321 consume; legacy/local/postgres-s3/degraded/setup-incomplete;resolveObjectAdmin= the list-capable admin/read object resolver repair/doctor use),setup.ts+setup-journal.ts(roll-forwardroster ops setup),capabilities.ts(per-component version negotiation). CLI:src/commands/ops.ts+src/lib/ops-args.ts. Schemas ship fromdata/ops/schema/{hitl,roster_ops}/. Env:ROSTER_OPS_URL/ROSTER_OPS_ADMIN_URL(dedicated) or the brain pair (brain reuse). Protocol reference:docs/adr/0004-operations-ledger-contracts.md. - Run + artifact ledger (#323):
src/commands/run.ts(roster run) +src/lib/run-args.ts— verbsstart/end(source=cli),event(generic; refuses lifecycle/tool-result/report/artifact-declared viaassertGenericEventKind, requires--correlation-id),report(source=agent,--file/--stdin+ a 128 KiB PORTABLE raw cap enforced BY the read vialib/bounded-read.ts— a multi-GiB file is refused from its stat, an unbounded pipe is abandoned at cap+1, and a file that GROWS past the cap mid-read reportssize: nullrather than its stale pre-read stat — stored through the sanitizer; 128 KiB is derived from the local ledger's 1 MiB record limit minus worst-case 6× JSON escaping + the sanitized projection + the envelope, so the advertised cap is achievable end-to-end on every backend),declare-artifact(--digest+--fileinternal viaputArtifact(meta,bytes,decl)with--role produced|used, or--external provider:id --urlviaputExternal),show(composeRunovergetRun+getByRun+headblob resolver),list(--task/--agent/--limit),doctor,repair --fill-version-ids(both admin verbs assertruns.doctor/runs.repaircapabilities BEFORE resolving admin creds or issuing SQL — a v1 backend gets aVersionSkewError, never a raw SQL error). Pure model:run-events.ts(sealed provenance + source trust taxonomyhost-attested/cli/agent/unverified),run-compose.ts(composeRun— lifecycle promoted only from trusted sources, duration derived at read),sanitize-index.ts(write-time redaction → therun_index/artifact_indexviews),artifact-declarations.ts(identity split: blob vs declaration; id coversrole). Repair:run-repair.ts—diagnoseRunLedgeris read-only (incl.declaration-version-unverified: a declaration still unverified while its blob records a version);fillVersionIdsis the SOLE updater ofobject_version_id/version_state(admin creds; runtime holds no UPDATE grant). An artifact spooled during an outage marks its declaration version-PENDING, and ordered drain materialization derivesversion_state='verified'from the committed blob row — a healed outage self-converges; the direct path's committed-ROW verdict is never re-derived. Migrationdata/ops/schema/roster_ops/002_run_ledger.sql(v2). All verbs resolve viaresolveOpsBackend, close the PG pool infinally, and are opt-in — legacy workspaces withoutpersistence.yamlare unaffected. The bin entry flushes stdout/stderr beforeprocess.exitso a large--jsonpayload is never truncated into invalid JSON on a pipe. - HITL state machine (#319):
src/lib/persistence/hitl-machine.tsis the ONE shared machine both backends route through — closedEDITORIAL_ACTIONSallowlist (unknown action ⇒execution, fail-safe), the length-prefixedrequestKeyOf/targetHashOf/packetHashOfframing the SQL reproduces byte-for-byte (Node↔SQL vectors),TRANSITIONS/canDecide/canAuthorizeExecution/validateApproval/planSubmission/deriveRequestState. Around it:hitl-store.ts(pre-backend layer — server-side content-hash verification, >8 KiB offload through #323's object port, expiry clamp, decision normalization, deterministicsystemExpiryId),hitl-sweep.ts(bounded + throttled bookkeeping),hitl-local-migrate.ts+hitl-local-records.ts(local v1→v2), migrationdata/ops/schema/hitl/002_state_machine.sql(component v2, capabilitystate-machine). Identity is the request GROUP:request_key = sha256(functionName, action, target),request_id = sha256(workspaceId, request_key)— content is deliberately NOT in the key, so a revision is version N+1 of the same group;generation/versionare allocated synchronously under the per-group advisory lock (hashtext(request_key) # 1212765260—0x4849544C, deliberately not a schema-migration key since the mask IS the lock id whenhashtext()returns 0 — / the localhitlnamespace lock) and(request_id, generation, version)is the decision + FK identity. The DB owns canonical identity: the fill trigger RECOMPUTESaction_kind/request_key/target_hash/canonicalization_versionfrom the row's own inputs on every insert — filling what a writer omitted, REFUSING what it asserted differently (a caller that asserts a derivation it did not compute is a bug or an attack: assertingaction_kind='editorial'for an execution action bought an expiry-free approval thatauthoritative/canAuthorizeExecutionaccepted) — and derivesid = sha256(workspace_id, request_key), RE-KEYING a v1-shaped/legacy-drain insert onto it (old value →legacy_id) or REFUSING a v2-shaped insert whose id disagrees with its own key. The fill trigger also validates ALLOCATION, not only derivation — under the SAME per-group advisory lock (both groups in sorted key order for a supersession row, re-entrant inside a store txn) it refuses an insert that extends a group whose current head is superseded (permanent closure at the DB level), claims a(generation, version)that is not the legal next step (no gaps, no reuse, no revision in a sealed generation, no G+1 while G is open — sealing judged by the DURABLE terminal decision, never the clock, since every path that opens G+1 materializes the expired head's decision first), names a supersession target that is not the current, not-already-superseded head of the group it replaces OR one that is effectively expired with no durable terminal decision, or REVISES an effectively-expired head. Those last two are judged by the CLOCK on purpose, and together with the decision-judged G+1 rule they close an expired generation: a rawG1/V2over an expired-but-unswept head became the actionable head and HID V1 from every future sweep, so its expiry was never recorded at all — while G+1 stays decision-judged so a deadline crossing mid-write cannot refuse a legal allocation. It costs the store nothing (sealedalready counts the clock, so no store path ever plans a revision of an expired head), both rules are monotone (a decision is never un-recorded, a deadline never un-passes), and the one window left — a deadline crossed between plan and insert — is the same synchronousConflictErrorthe decision trigger's expiry-direction check raises. Like the decisions trigger it lock-then-reads, so it carries the SAME contract and RAISEs above READ COMMITTED: a snapshot taken before the lock reads the group as it was before a concurrent supersession and allocates a head beside it. The anti-join is written once ashitl.head_supersededand called by the projection, the decision trigger and this gate. OnlyexpectedHead/intentandpacket_hashstay application-enforced (the DB cannot know what a caller observed, and cannot reproduce JS canonical JSON). The key being derived is what makes the id check meaningful, so onerequest_keycan never own two groups and no separateUNIQUE (request_key)is needed.canonicalization_versionis likewise derived-and-verified per CHANNEL — inline:payload->'body'must be a JSON string whose sha256 equalscontent_hash(an EMPTY body hashing tosha256('')counts, matching the TS conversion); payload_ref:payload_ref->>'digest'must equalcontent_hash, the bytes being re-hashed against it by every reader that materializes them — because without it a plain INSERT storedbody='benign text'besidecontent_hash=sha256('executable text')at version 1 and, once approved, wasauthoritativeandvalidateApproval-authorized for the packet the approver never saw. The check is EQUALITY with the derived value in both directions (1iff verified, else0), so an understated 0 over verified content and a forward-compatible2the schema cannot verify are refused exactly like an overstated 1 — the TS side ships one canonicalization version, and a second is a schema change that teaches the trigger to derive it. Version 0 stays the legacy exemption (D8: never authoritative). One functionName rule everywhere: functionName has no column of its own, sohitl.function_name()(fill trigger + backfill + the PG list/count FILTER),functionNameOf/identityFieldsOf(PG projection), the local projection at read and the local v1→v2 conversion all apply the same normalization — anything not a NON-EMPTY string isunknown, inline channel first thenpayload_ref.meta; comparing the RAW payload value in the PG filter hid a migratedfunctionName: 5/''/absent row from the veryunknownquery its own envelope advertised. Optimistic concurrency:expectedHeadis REQUIRED and carries{generation, version, packetHash, sealed}—sealedis mandatory because a terminal decision changes nothing else about a head, so without it a submission composed against an open request would open G+1 behind an approval the caller never saw;null= 'no history at all' (also honored idempotently when the head is an OPEN byte-identical packet — an at-least-once retry).replacesvalidates BOTH expected heads and is idempotent over the (packet, supersession) PAIR, so it never reports success with the source still authoritative; it also materializes BOTH closed heads' owed expiries — the destination's generation boundary AND the SOURCE's — inside the same two-lock transaction/batch, in sortedrequest_keyorder, before the destination row lands, because a supersession pointer closes the source permanently and an un-materialized expiry under it could never be written by anyone afterwards. A superseded group is CLOSED: the supersession pointer lives on the DESTINATION row, so being replaced leaves the source head's fingerprint byte-identical (same generation/version/packetHash/sealed) andexpectedHeadalone can never detect it — so the SAME anti-join that denies authority is read inside the group lock during PLANNING (HitlObservedHead.superseded) and refuses every WRITING plan (revise/open-generation) withsuperseded-head, on both backends and on the pre-#319 spool drain; the source side ofreplacesis refused the same way. Without it a caller that observed S beforereplaces(S → D)submitted its unchanged fingerprint and minted an S head no supersession row points at — authoritative alongside D, two live approvals for one replaced decision. Only a byte-identical packet against an open head stays idempotent (it writes nothing) — and because areplacesstill owes its supersession link, such a no-write DESTINATION plan is UPGRADED to a writing revision when the head does not already record that link, so closure is re-checked against the FINAL plan:A→B, thenB→C, thenX→Bwith B's own fingerprint and packet committed a B v2 that C's pointer at B v1 does not cover.hitl-store.ts#finalizeSubmissionPlanis the ONE place a plan's kind may change afterplanSubmissionreturned, and it owns both the upgrade and the re-check. Same closure downstream: a superseded head leaves the DEFAULT actionable list/count workset (deriveRequestState().actionable/NOT s.supersededin the PG filter; an explicitstatusfilter still reaches it — that is history, not the queue) and is never an expiry candidate,insertSystemExpiryreportingconflicton both backends rather than writing (local) or raising (PG, whose decision trigger refuses every decision on a superseded version). The packet hash covers every approval-VISIBLE field includingtitle,originRunId,originTaskId,requestingAgent(canonicalization version stays 1 — nothing has ever shipped a packet hash). Sealed generations: any terminal decision seals a generation and a later same-key submission opens G+1 (an independent approval) — but sealing ≠ authority:canAuthorizeExecutionis the HIGHEST generation's current, unsuperseded, unexpired,canonicalization_version > 0head with effective statusapproved, so an approved TERMINAL head IS authoritative (the normal approve-then-execute path) and authority never falls back to an older generation. Insert-only, no UPDATE grant anywhere: supersession is derived from row existence (supersedes_*+ anti-join), and the admin-owned BEFORE INSERT triggers onhitl.decisionsandhitl.requests(advisory-lock FIRST, READ COMMITTED-only — both RAISE under a higher isolation whose snapshot predates the lock —clock_timestamp()for every expiry comparison) make the invariants true against a raw runtime INSERT. Expiry is enforced sweep-INDEPENDENTLY:effective_statusdrops an expired request out of authority and out of the actionable count before any sweep runs; the sweep only materializes the durableexpireddecision (deterministic id ⇒ concurrent sweeps converge; on PG it is stamped with the DB clock read inside the locked txn — the same clock that decided eligibility — so a skewed app clock can never record an expiry at a moment the request had not yet expired; PG USER decisions read that samehitl.now_ms()after the group lock for their prevalidation and stamp, so an app clock running ahead cannot refuse a decision the DB considers decidable), andhitl.expiryinpersistence.yaml(24h default, clamped to 1h…7d with a warning onHitlWriteOutcome.warnings) is the policy — RESOLVED on PG against the DB clock under the group lock, with the packet re-sealed around the result (resealExpiry), becauseexpiresAtis packet-visible and every expiry CONSUMER readshitl.now_ms(): resolving it on the application clock made a 24h request BORN expired when the app ran two days behind the database, and pushed the expiry past the DB-relative 7-day maximum when it ran ten days ahead. Live-store-only (owner decision 6):createRequest/replaces/appendDecisionall require the authoritative store, the ENTIREhitlnamespace is refused atLocalOutbox.enqueue(structural, not by convention), degraded HITL reads throw and honor noallowPartial, and for a database-less workspace the local JSONL ledger IS the live store (physical record id is composite so a revision never dedups against its base). Migration: PG partitions legacy generations at terminal boundaries and re-keysid(old value kept inlegacy_id), refusing an ambiguous history in preflight — every preflight/partition/remap join is keyed by the FULL v1 identity(workspace_id, id, request_version), since v1's unique allows several versions per legacy id. Local converts under the SAMEhitl/.lockv1 writers respect, in BOUNDED CHUNKS (one compound record would blow the ledger's 1 MiB limit and make a large history unmigratable), with a durable CONVERTING marker + epoch revalidation making a re-run idempotent; the marker is also a FORMAT FENCE the ledger's append primitive enforces (local/format-fence.ts), so a v1 writer that resolved before the conversion cannot append a v1-format record AFTER it and have the v2 projection ignore it forever. Each converted version carries its legacycreatedAtas an observation, so the projection reports the ORIGINAL creation time (parity with the PG backfill, which leavescreated_atalone). A legacy row with an absent or non-string body converts tobody: null, not''— postgres keeps the v1 payload jsonb verbatim and projects a non-string body as null, so the same row must not report two different bodies in an audit. Because a conversion chunk is ONE compound envelope, its children share a ledger seq: local pagination orders by the tuple(seq, pos)(pos= index within the envelope, assigned byexpandLedgerRecords, carried onCursor.committedPos) — a scalar seq cursor made every batch sibling but one permanently unreachable. Both backends anchor HITL pagination on the GROUP's creation position (the lowest seq its versions hold), never the head's — a head moves on every revision, so projecting the latest head and then applyingseq <= watermarkdropped a request revised mid-traversal out of the whole listing. CLI verbs are #320. Protocol:docs/adr/0004-operations-ledger-contracts.md§HITL state machine.
Adding a new AI-tool target
- Add the tool's config-dir constant to
src/lib/tools.ts(e.g.,~/.somewhere/skills/). - Add a
Toolentry todetectTools()returning the key + name + targets. - Extend
installToTool()to handle that tool's layout (skills-only vs skills+agents). - Add a test case in
test/install.test.tsexercising the new target. - Update
README.mdinstall matrix.
Code conventions
- TypeScript, ESM, strict mode. No CommonJS.
- File names: lowercase kebab-case.
- Prefer hand-rolled argv parsing over commander/yargs to keep tarball small.
- No comments unless behavior is non-obvious. No docstrings.
(Build conventions — GitHub issue numbers in commits/branches, phase gates, worktree/PR rules, never auto-commit — live in .forge/CONTEXT.md. Roadmap is docs/roadmap.md; work items tracked in GitHub Issues.)
Dogfooding
There is no in-repo agent-team workspace anymore. To exercise the workspace pattern shipped by roster init (/sdr, /chief-of-staff, /dreamer, etc.), scaffold a workspace outside this repo with roster init and report regressions back here. The shipped scaffold is exercised in-CI by pnpm smoke (roster init into a tmpdir) and pnpm test:scaffold-scripts (the new-agent.sh --slash-only and audit-agent.sh guideline-refs regression suites).
When in doubt
Start here, then check .forge/CONTEXT.md for build methodology and tracker/phase rules, then README.md and docs/HOWTO.md. If a CLI convention isn't clear, ask before guessing — this is going on npm and inconsistent UX propagates to everyone who installs it.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

