agentleFS
firatcandfiratcand/roster/CLAUDE.md

roster

CLAUDE.md19 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

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
  1. Very specific:

    Add the tool's config-dir constant to src/lib/tools.ts (e.g., ~/.somewhere/skills/).

    line 96
  2. Very specific:

    Add a Tool entry to detectTools() returning the key + name + targets.

    line 97
  3. Very specific:

    Add a test case in test/install.test.ts exercising the new target.

    line 99
  4. Distinctive:

    Update README.md install matrix.

    line 100
  5. Distinctive:

    Prefer hand-rolled argv parsing over commander/yargs to keep tarball small.

    line 106
  6. Distinctive:

    No comments unless behavior is non-obvious.

    line 107
  7. Very specific:

    Start here, then check .forge/CONTEXT.md for build methodology and tracker/phase rules, then README.md and docs/HOWTO.md.

    line 117

≈ “Common” is an estimate: at least 1 in 5 of the 12,729 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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md
<!-- >>> 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 upgrade

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 <<< -->

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; subcommands install, 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.json from 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.ts parses --cwd/--json.
  • Host adapter contract: src/lib/generated-artifacts.ts#HOST_ADAPTER_LIFECYCLE_CAPABILITIES is the single capability catalog and renderer for the host-neutral ROSTER.md lifecycle and thin Claude Code/Codex activation pointers. src/lib/context-trust.ts owns 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 is stale-generated/GENERATED_FILE_STALE (safe to regenerate), a hash-broken one is edited/GENERATED_FILE_EDITED (refused), and detectGeneratedShadows — one detector feeding update, validate, and doctor — scans CLAUDE.md/CLAUDE.local.md/GEMINI.md/AGENTS.override.md plus 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/. Each Tool has key, name, skillsTarget, agentsTarget. Override via ROSTER_CLAUDE_HOME etc. for tests.
  • Install logic: installToTool() in src/lib/tools.ts — copies skills/* and agents/*.md into the tool's config dir. Idempotent. Handles symlinks (prompts before clobber). Handles EACCES with a sudo hint.
  • Scaffold logic: src/commands/init.ts — copies templates/scaffold/** into CWD, substitutes {{PROJECT_NAME}} in CLAUDE.project.template.md, appends gitignore-defaults idempotently.
  • Schedule schema: src/lib/schedule-schema.ts — Zod-validated scheduleEntrySchema (name, agent, plan, cron, tool, install_mode, status). Required status enum is pending-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 upserts roster/<function>/schedules.yaml atomically. 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.md for the Codex desktop app) and via-cron (--via cron; renders a hardened crontab line wrapped by env -i, installed via src/lib/codex-cron.ts marker-block upsert). All entries include a subscription_attestation block (auth_mode/env_policy/codex_home) verified by src/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 as ambiguous-legacy-marker.
  • Shared YAML helpers: src/lib/schedule-yaml.ts — atomicWriteFile, readExistingSchedulesDoc, upsertEntryInDoc. The upsert refuses to overwrite an existing entry with a different tool value to prevent silent same-name cross-tool collisions.
  • Schedule commands: src/commands/schedule.ts — executeScheduleValidate() and executeScheduleInstall(). 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 codex default mode (refused on Linux — no Codex Desktop).
  • Failure observability (ROS-42): src/lib/cron-exit-log.ts reads sibling logs/cron/<name>.exit / .events.jsonl files written by the renderCronLine wrap (create-only under set -C noclobber after an rm -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 in schedule-yaml.ts, schedule-validate.ts, doctor's entry listing), and roster/<fn>/pending/*.md — goes through the leaf module src/lib/evidence-read.ts#readEvidenceFileSync (O_NOFOLLOW + O_NONBLOCK + fstat regular-file + read-to-EOF under a maxBytes+1 bound; schedule-state.ts re-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 to state.md can never truncate a complete line into a false STALE. A symlinked schedules.yaml is refused, not followed. O_NOFOLLOW covers 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 in src/lib/workspace-path.ts — resolveConfinedPath(path, boundary), which walks EVERY path component strictly below the boundary with lstat and 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/acks suppressed a real failed fire, and roster/ops -> gtm aliased 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-prefixed repo/roster/… become /parent/repo/repo/roster/… — confinement inspected a phantom path while every caller afterwards opened the real one (run list reported no runs, run start replaced the ledger's producer identity, and a symlinked component on the REAL path was never walked). Every --cwd parse site now normalizes with resolve() and a relative input THROWS instead of being re-prefixed; the one caller-authored workspace-RELATIVE input (pending front-matter target_on_approve) goes through the explicit resolveWorkspaceRelativePath. targetWithinWorkspace, confinedWorkspaceDir, confinedFunctionDir/resolveFunctionDir, functionDirWithinRoster and confinedProbeSync are all thin wrappers over that primitive; ancestorsConfined is the flavor for readers that own their final component through O_NOFOLLOW (readWorkspaceEvidenceFileSync folds a refusal into the existing malformed taxonomy as outside-workspace, so a symlinked evidence FILE keeps its precise not-a-regular-file reason). So a symlinked roster/gtm or roster/gtm/pending can 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-workspace roster/gtm -> ../archive — satisfies the workspace check while leaving the registry, so schedule remove --function ../archive rewrote a sibling schedules.yaml. Function names are now validated by ONE strict kebab rule at every argument boundary (workspace-path.ts#isFunctionName, used by schedule-args, run-args, review-args) and every resolved function directory is confined beneath <workspace>/roster/ — confinedFunctionDir for reads (listFunctionDirs/loadSchedules/readScheduleEntries/findScheduleFiles/scanPending/pending-sync/review) and functionDirWithinRoster for the create-on-first-use write path (assertFunctionDirWithinRoster, shared by both installers). Existence probes over agent-writable paths (the acknowledged/ sentinels, both pending destinations, the approve target) use the tri-state confinedProbeSync instead of existsSync, so a symlinked acknowledged/ can no longer classify a failed fire as acknowledged and silently suppress its decision item. src/lib/schedule-state.ts#detectStale answers "is the agent self-report older than expected next-fire + grace?". src/lib/pending-sync.ts synthesizes roster/<fn>/pending/error-<id>.md items from non-zero .exit + STALE — idempotent via sha1(scheduleName + signalKey).slice(0,8). src/commands/pending-sync.ts is the CLI; src/lib/doctor-scheduling-drift.ts#auditStaleFires is the doctor cross-reference. templates/hooks/banner.sh v3 invokes roster pending sync --silent (with timeout 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 review is the engine. src/lib/pending-apply.ts holds 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 module src/lib/workspace-path.ts) plus computeItemId (sha1(function/filename).slice(0,8)) and resolveItemBySelector (path-then-id). roster review --json lists items with an id; --approve/--reject <id|path> apply one headlessly (before the TTY guard). skills/inbox/SKILL.md is the cross-tool /inbox front 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/cancelled branches), context.ts (tracker.yaml load, deriveCurrentState incl. assigned-Ready→claimed overlay, planVerb collapse over unmapped stages, resolveSelector), tracker-schema.ts (Zod config), setup.ts (board introspection wizard), adapters/ (types.ts generic TrackerAdapter, notion.ts v1 impl — sole layer touching Notion). Verbs + reports live in src/commands/task.ts (applyVerb, composeReport = stable flat list, composeDigest = status stage digest + attention). skills/tasks/SKILL.md is the /tasks chat 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 + the KNOWN_FOUNDER_SKILLS allowlist (+ BUILTIN_SKILL_EXCEPTIONS, e.g. frontend-design). Guard pair: test/expert-routes.test.ts pins templates/scaffold/*/EXPERT.md routes to the allowlist (hermetic; ROSTER_NETWORK_SMOKE=1 adds a live GitHub-catalog verify), and src/lib/doctor-expert-routes.ts#auditExpertRoutes warns in roster doctor when a workspace EXPERT route isn't covered by founder-skills.yaml (expert_routes in --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|queued write outcomes), config-schema.ts (roster/persistence.yaml, credential-free), local/ (append-only JSONL ledger + stores; the READ side is confined by confinedLedgerDir — the read-only sibling of ensureOwnedDir over the same component-wise no-follow primitive, creating nothing and repairing no mode — so scan/meta/readLedgerMeta refuse a symlinked .roster/ops/<workspaceId> instead of reconstructing (and locking, recovering, sealing) a FOREIGN ledger tree; meta.json, the seal sidecars, persistence.yaml and the setup journal are read through the hardened bounded reader, and the lock + segment reads open O_NOFOLLOW|O_NONBLOCK with an fstat regular-file re-proof; create-once publication is link(2) → O_CREAT|O_EXCL-at-the-final-name → refuse, never a replacing rename, and getArtifact/head share 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 through confinedLedgerDir, spooled bytes through the descriptor-verified readRegularFileSync (digest-bounded, the artifact/blob policy) and outbox/checkpoint.json through the hardened bounded reader at the 64 KiB sidecar cap, so a symlinked spool/ can neither divert nor chmod a foreign file and a FIFO at checkpoint.json can no longer hang a drain after its remote commits), postgres/ (binding.ts strict 1:1 workspace↔DB stamp verified per connection, roles.ts least-privilege gate, stores.ts), objects.ts (dedicated-bucket create-only store + roster-workspace.json marker + listPrefix for 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-forward roster ops setup), capabilities.ts (per-component version negotiation). CLI: src/commands/ops.ts + src/lib/ops-args.ts. Schemas ship from data/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 — verbs start/end (source=cli), event (generic; refuses lifecycle/tool-result/report/artifact-declared via assertGenericEventKind, requires --correlation-id), report (source=agent, --file/--stdin + a 128 KiB PORTABLE raw cap enforced BY the read via lib/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 reports size: null rather 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+--file internal via putArtifact(meta,bytes,decl) with --role produced|used, or --external provider:id --url via putExternal), show (composeRun over getRun+getByRun+head blob resolver), list (--task/--agent/--limit), doctor, repair --fill-version-ids (both admin verbs assert runs.doctor/runs.repair capabilities BEFORE resolving admin creds or issuing SQL — a v1 backend gets a VersionSkewError, never a raw SQL error). Pure model: run-events.ts (sealed provenance + source trust taxonomy host-attested/cli/agent/unverified), run-compose.ts (composeRun — lifecycle promoted only from trusted sources, duration derived at read), sanitize-index.ts (write-time redaction → the run_index/artifact_index views), artifact-declarations.ts (identity split: blob vs declaration; id covers role). Repair: run-repair.ts — diagnoseRunLedger is read-only (incl. declaration-version-unverified: a declaration still unverified while its blob records a version); fillVersionIds is the SOLE updater of object_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 derives version_state='verified' from the committed blob row — a healed outage self-converges; the direct path's committed-ROW verdict is never re-derived. Migration data/ops/schema/roster_ops/002_run_ledger.sql (v2). All verbs resolve via resolveOpsBackend, close the PG pool in finally, and are opt-in — legacy workspaces without persistence.yaml are unaffected. The bin entry flushes stdout/stderr before process.exit so a large --json payload is never truncated into invalid JSON on a pipe.
  • HITL state machine (#319): src/lib/persistence/hitl-machine.ts is the ONE shared machine both backends route through — closed EDITORIAL_ACTIONS allowlist (unknown action ⇒ execution, fail-safe), the length-prefixed requestKeyOf/targetHashOf/packetHashOf framing 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, deterministic systemExpiryId), hitl-sweep.ts (bounded + throttled bookkeeping), hitl-local-migrate.ts + hitl-local-records.ts (local v1→v2), migration data/ops/schema/hitl/002_state_machine.sql (component v2, capability state-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/version are 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 when hashtext() returns 0 — / the local hitl namespace lock) and (request_id, generation, version) is the decision + FK identity. The DB owns canonical identity: the fill trigger RECOMPUTES action_kind/request_key/target_hash/canonicalization_version from 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: asserting action_kind='editorial' for an execution action bought an expiry-free approval that authoritative/canAuthorizeExecution accepted) — and derives id = 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 raw G1/V2 over 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 (sealed already 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 synchronous ConflictError the 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 as hitl.head_superseded and called by the projection, the decision trigger and this gate. Only expectedHead/intent and packet_hash stay 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 one request_key can never own two groups and no separate UNIQUE (request_key) is needed. canonicalization_version is likewise derived-and-verified per CHANNEL — inline: payload->'body' must be a JSON string whose sha256 equals content_hash (an EMPTY body hashing to sha256('') counts, matching the TS conversion); payload_ref: payload_ref->>'digest' must equal content_hash, the bytes being re-hashed against it by every reader that materializes them — because without it a plain INSERT stored body='benign text' beside content_hash=sha256('executable text') at version 1 and, once approved, was authoritative and validateApproval-authorized for the packet the approver never saw. The check is EQUALITY with the derived value in both directions (1 iff verified, else 0), so an understated 0 over verified content and a forward-compatible 2 the 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, so hitl.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 is unknown, inline channel first then payload_ref.meta; comparing the RAW payload value in the PG filter hid a migrated functionName: 5/''/absent row from the very unknown query its own envelope advertised. Optimistic concurrency: expectedHead is REQUIRED and carries {generation, version, packetHash, sealed} — sealed is 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). replaces validates 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 sorted request_key order, 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) and expectedHead alone 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) with superseded-head, on both backends and on the pre-#319 spool drain; the source side of replaces is refused the same way. Without it a caller that observed S before replaces(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 a replaces still 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, then B→C, then X→B with B's own fingerprint and packet committed a B v2 that C's pointer at B v1 does not cover. hitl-store.ts#finalizeSubmissionPlan is the ONE place a plan's kind may change after planSubmission returned, 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.superseded in the PG filter; an explicit status filter still reaches it — that is history, not the queue) and is never an expiry candidate, insertSystemExpiry reporting conflict on 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 including title, 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: canAuthorizeExecution is the HIGHEST generation's current, unsuperseded, unexpired, canonicalization_version > 0 head with effective status approved, 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 on hitl.decisions and hitl.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_status drops an expired request out of authority and out of the actionable count before any sweep runs; the sweep only materializes the durable expired decision (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 same hitl.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), and hitl.expiry in persistence.yaml (24h default, clamped to 1h…7d with a warning on HitlWriteOutcome.warnings) is the policy — RESOLVED on PG against the DB clock under the group lock, with the packet re-sealed around the result (resealExpiry), because expiresAt is packet-visible and every expiry CONSUMER reads hitl.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/appendDecision all require the authoritative store, the ENTIRE hitl namespace is refused at LocalOutbox.enqueue (structural, not by convention), degraded HITL reads throw and honor no allowPartial, 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-keys id (old value kept in legacy_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 SAME hitl/.lock v1 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 legacy createdAt as an observation, so the projection reports the ORIGINAL creation time (parity with the PG backfill, which leaves created_at alone). A legacy row with an absent or non-string body converts to body: 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 by expandLedgerRecords, carried on Cursor.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 applying seq <= watermark dropped 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

  1. Add the tool's config-dir constant to src/lib/tools.ts (e.g., ~/.somewhere/skills/).
  2. Add a Tool entry to detectTools() returning the key + name + targets.
  3. Extend installToTool() to handle that tool's layout (skills-only vs skills+agents).
  4. Add a test case in test/install.test.ts exercising the new target.
  5. Update README.md install 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.

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.