@attalabs/vinaya 0.32.0 → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/aeg-root/contracts/principal-operator.md +18 -5
- package/aeg-root/roles/operator.md +69 -16
- package/aeg-root/roles/planner/reference.md +1 -1
- package/aeg-root/roles/tranche-archivist.md +1 -0
- package/aeg-root/skills/aeg-context-packets/SKILL.md +1 -1
- package/aeg-root/skills/aeg-context-packets/examples/operator-start.md +1 -1
- package/dist/checks/bin/check-body-bare-digits.js +111 -15
- package/dist/checks/bin/check-branch-topology.js +83 -16
- package/dist/checks/bin/check-brief-shape.js +111 -15
- package/dist/checks/bin/check-changeset-coverage.js +342 -69
- package/dist/checks/bin/check-closes-n.js +83 -16
- package/dist/checks/bin/check-coherence.js +112 -16
- package/dist/checks/bin/check-dead-branch-push.js +82 -15
- package/dist/checks/bin/check-dispatch-readiness.js +112 -16
- package/dist/checks/bin/check-doc-coverage-push.js +342 -69
- package/dist/checks/bin/check-doc-coverage.js +342 -69
- package/dist/checks/bin/check-doctrine-no-procedures.js +111 -15
- package/dist/checks/bin/check-doctrine-portability.js +342 -69
- package/dist/checks/bin/check-evidence-fresh.js +343 -69
- package/dist/checks/bin/check-exec-bits.js +342 -69
- package/dist/checks/bin/check-first-push-dispatch.js +112 -16
- package/dist/checks/bin/check-issue-assignment.js +83 -16
- package/dist/checks/bin/check-issue-milestone-attach.js +82 -15
- package/dist/checks/bin/check-issue-objectives-numbering.js +82 -15
- package/dist/checks/bin/check-issue-parts-coverage.js +82 -15
- package/dist/checks/bin/check-issue-surface-globs.js +112 -16
- package/dist/checks/bin/check-issue-title-grammar.js +82 -15
- package/dist/checks/bin/check-issue-tranche-label.js +82 -15
- package/dist/checks/bin/check-main-branch-refusal.js +82 -15
- package/dist/checks/bin/check-no-disk-state.js +82 -15
- package/dist/checks/bin/check-pr-premise-reassert.js +111 -15
- package/dist/checks/bin/check-pr-report-density.js +82 -15
- package/dist/checks/bin/check-principal-test-plan-wait.js +82 -15
- package/dist/checks/bin/check-quoted-command.js +342 -69
- package/dist/checks/bin/check-reader-resolvable-prose.js +342 -69
- package/dist/checks/bin/check-registry-gates.js +82 -15
- package/dist/checks/bin/check-retired-vocabulary.js +342 -69
- package/dist/checks/bin/check-review-gate.js +179 -124
- package/dist/checks/bin/check-single-plan-pr.js +82 -15
- package/dist/checks/bin/check-surface-scope.js +83 -16
- package/dist/checks/bin/check-test-plan.js +82 -15
- package/dist/checks/bin/check-token-collection-wired.js +82 -15
- package/dist/checks/bin/check-token-report.js +82 -15
- package/dist/checks/bin/check-workspace-escape.js +342 -69
- package/dist/index.js +2495 -590
- package/dist/lib/pre-push-cache-test-run.js +317 -61
- package/dist/lib/pre-push-select-tests.js +91 -10
- package/package.json +1 -1
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/actions.ts +10 -12
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/anchored-region.ts +5 -5
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/archive-task.ts +42 -17
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/baseline-capture.ts +1 -2
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/branch-topology-gate.ts +3 -3
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/brief-render.ts +554 -95
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/brief-validation.ts +264 -44
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/claude-code-transcript.ts +9 -9
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/coherence-checks.ts +211 -30
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/consumer-enumeration.ts +2 -2
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/control-store/index.ts +75 -0
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/control-store/local.ts +961 -0
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/control-store/migration.ts +212 -0
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/control-store/outcomes.ts +135 -0
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/control-store/records.ts +394 -0
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dead-branch-push-audit.ts +1 -2
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dead-branch-push-guard.ts +1 -1
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/derive-section7.ts +2 -2
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/assess-round.ts +514 -0
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/fakes.ts +110 -0
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/index.ts +27 -0
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/journal-reconstruction.ts +123 -0
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/render-summary.ts +27 -0
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dev-review-loop/types.ts +240 -0
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/diagram-model.ts +1 -1
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/direct-main-push.ts +1 -2
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/dispatch-gate.ts +65 -22
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/doc-claim.ts +238 -0
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/doc-owners.ts +14 -1
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/docs/docs-coherence.ts +1 -1
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/docs/legacy-anchors.ts +1 -1
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/docs/node-route.ts +1 -1
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/docs/surfaced-manifest.ts +1 -1
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/doctrine-no-procedures.ts +1 -1
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/doctrine-portability.ts +5 -5
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/ensure-label.ts +1 -1
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/first-push-dispatch-gate.ts +1 -1
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/gate-audience.ts +14 -3
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/index.ts +379 -11
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/issue-assignment.ts +3 -4
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/issue-validation.ts +1450 -33
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/leftover-detection.ts +1 -2
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/local-anchor-coverage.ts +2 -2
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/envelope.ts +119 -0
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/index.ts +75 -0
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/redact.ts +87 -0
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/schema.ts +801 -0
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/log/store.ts +373 -0
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/main-branch-refusal.ts +2 -2
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/metering-io-guard.ts +1 -1
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/milestone-validation.ts +2 -3
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/no-disk-state.ts +2 -2
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/objectives.ts +288 -0
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/parse-token-report.ts +3 -3
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/parse-tranche.ts +1 -1
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/pr-report-density.ts +30 -16
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/pr-tier.ts +17 -1
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/premise-check.ts +1 -1
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/quoted-command.ts +1 -1
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/reader-resolvable-prose.ts +267 -19
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/registry-checks.ts +91 -24
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/registry-scaffold.ts +6 -6
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/report-tokens.ts +4 -4
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-gate.ts +239 -110
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-input-manifest.ts +384 -0
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-policy.ts +184 -0
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/review-status.ts +65 -18
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/ruling-ordinal.ts +76 -0
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/single-plan-pr.ts +4 -4
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/state-machine-model.ts +40 -27
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/symbol-collisions.ts +2 -2
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/task-branch-identity.ts +38 -0
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/task-tools.ts +488 -0
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/test-plan-gate.ts +7 -9
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/test-plan-section.ts +5 -5
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/types.ts +4 -4
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/verdict-extraction.ts +314 -56
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/waiver-label.ts +2 -3
- package/studio-standalone/_node_modules/@attalabs/aeg-core/src/workspace-escape.ts +3 -3
- package/studio-standalone/apps/vinaya-studio/web/.next/BUILD_ID +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/build-manifest.json +3 -3
- package/studio-standalone/apps/vinaya-studio/web/.next/prerender-manifest.json +3 -3
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.html +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.rsc +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page/server-reference-manifest.json +2 -2
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page.js.nft.json +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/api/coherence/route.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/api/coherence/route.js.nft.json +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page/server-reference-manifest.json +2 -2
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page.js.nft.json +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/page_client-reference-manifest.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page/server-reference-manifest.json +2 -2
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page.js.nft.json +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/backlog/page_client-reference-manifest.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page/server-reference-manifest.json +2 -2
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page.js.nft.json +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/page_client-reference-manifest.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page/server-reference-manifest.json +2 -2
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page.js.nft.json +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/page_client-reference-manifest.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page/server-reference-manifest.json +3 -3
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page.js +2 -2
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page.js.nft.json +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/page_client-reference-manifest.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page/server-reference-manifest.json +2 -2
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page.js.nft.json +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/[name]/tranches/[slug]/tasks/[taskId]/page_client-reference-manifest.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page/server-reference-manifest.json +2 -2
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page.js.nft.json +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/projects/page_client-reference-manifest.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page/server-reference-manifest.json +2 -2
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page.js.nft.json +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/app/studio/tranches/page_client-reference-manifest.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/{[externals]__1agj1ww._.js → [externals]__0cki-x_._.js} +2 -2
- package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/[root-of-the-server]__02a-3g8._.js +6 -6
- package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/1q96_modules_@clerk_nextjs_dist_esm_app-router_client_keyless-creator-reader_0lom2js.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__074w9nf._.js +3 -0
- package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__0ls23oh._.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/{[root-of-the-server]__0r7e54g._.js → [root-of-the-server]__18paley._.js} +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1gjqmhq._.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__1wc4-ip._.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/{[root-of-the-server]__1r47dr7._.js → _08onyya._.js} +3 -3
- package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_096f46i._.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0af2one._.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0e5tkdd._.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0kf2g72._.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0y1jv16._.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_0zf4d27._.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1-wo68i._.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_15gdg48._.js +5 -5
- package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/_1achbh9._.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/node_modules_@clerk_nextjs_dist_esm_app-router_server-actions_1x7vfhn.js +2 -2
- package/studio-standalone/apps/vinaya-studio/web/.next/server/middleware-build-manifest.js +3 -3
- package/studio-standalone/apps/vinaya-studio/web/.next/server/pages/500.html +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/server-reference-manifest.js +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/server/server-reference-manifest.json +4 -4
- package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/0bjnj-5fy4e7l.js +1 -0
- package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{1dc2_-c_gavj1.js → 1ce2dj27_cgbj.js} +4 -4
- package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/{3xg6-flovrcx-.js → 22s44f5k3ecmj.js} +1 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/34hhdtbp20krb.js +1 -0
- package/studio-standalone/apps/vinaya-studio/web/package.json +2 -2
- package/studio-standalone/apps/vinaya-studio/web/.next/server/chunks/ssr/[root-of-the-server]__0hstap0._.js +0 -3
- package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/2t_rfsztmwu6y.js +0 -1
- package/studio-standalone/apps/vinaya-studio/web/.next/static/chunks/3ua4rm5f-a9k6.js +0 -1
- /package/studio-standalone/_node_modules/@attalabs/vinaya/studio-standalone/_node_modules/@attalabs/vinaya/studio-standalone/_node_modules/@attalabs/vinaya/studio-standalone/_node_modules/@attalabs/vinaya/studio-standalone/_node_modules/@attalabs/{aeg-core → vinaya/studio-standalone/_node_modules/@attalabs/aeg-core}/bin/verify-coherence.ts +0 -0
- /package/studio-standalone/apps/vinaya-studio/web/.next/static/{e8XbZ2vlVz40KzHmlqhwP → vl7QVqELe1AQ-9kaOd9mR}/_buildManifest.js +0 -0
- /package/studio-standalone/apps/vinaya-studio/web/.next/static/{e8XbZ2vlVz40KzHmlqhwP → vl7QVqELe1AQ-9kaOd9mR}/_clientMiddlewareManifest.js +0 -0
- /package/studio-standalone/apps/vinaya-studio/web/.next/static/{e8XbZ2vlVz40KzHmlqhwP → vl7QVqELe1AQ-9kaOd9mR}/_ssgManifest.js +0 -0
|
@@ -0,0 +1,961 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one supported local storage implementation for the control-store. Two
|
|
3
|
+
* properties, demonstrated by the fault fixtures in `local.test.ts` rather
|
|
4
|
+
* than asserted in prose:
|
|
5
|
+
*
|
|
6
|
+
* **Atomic, durable transitions.** Every write — an ordinary overwrite via
|
|
7
|
+
* `atomicWriteFile`, or an exclusive claim via `exclusiveCreateFile` — lands
|
|
8
|
+
* fully-formed content on a private temp file in the same directory,
|
|
9
|
+
* `fsync`ed, before that content is ever published under its real name via
|
|
10
|
+
* `renameSync` (an overwrite) or `linkSync` (an exclusive claim). POSIX
|
|
11
|
+
* guarantees both publish operations are atomic on a shared filesystem, so
|
|
12
|
+
* a reader never observes a partial file, and a crash before the publish
|
|
13
|
+
* step simply leaves the prior state (or none) untouched. This is the
|
|
14
|
+
* "atomic files" half of the traps-to-avoid decision, recorded in
|
|
15
|
+
* `apps/cli/specs/loop.md` — a transactional database was rejected because
|
|
16
|
+
* this store's own concurrency need (one exclusive owner at a time, on one
|
|
17
|
+
* machine) is fully met by a filesystem's own `link(2)`/`rename(2)`
|
|
18
|
+
* guarantees, and pulling in a DB engine would be the "distributed
|
|
19
|
+
* coordination" the brief says not to introduce for a single-machine guard.
|
|
20
|
+
*
|
|
21
|
+
* **Exclusive ownership epochs, fenced at the mutation boundary.** Ownership
|
|
22
|
+
* is not "the recorded pid answers a liveness probe" (`isDriverPidAlive`'s
|
|
23
|
+
* old role, the trap this task exists to retire: liveness alone never
|
|
24
|
+
* proved ownership, only that some process with that pid still runs).
|
|
25
|
+
* Instead each attempted epoch is its own immutable file, published with
|
|
26
|
+
* `linkSync` from a private, fully-written temp file: two racing callers
|
|
27
|
+
* computing the same next epoch from the same observed current epoch
|
|
28
|
+
* contend for the same final name, and the filesystem — not a timestamp,
|
|
29
|
+
* not a liveness probe — decides the single winner, with no window in
|
|
30
|
+
* which either can observe the other's claim as an empty or torn file.
|
|
31
|
+
* Creating the final name directly with `O_CREAT|O_EXCL` and writing its
|
|
32
|
+
* content in a separate step would reopen exactly that window: a second
|
|
33
|
+
* claimant could open the name mid-write, read it as corrupt, and reclaim
|
|
34
|
+
* it out from under the first writer, whose own call would go on to finish
|
|
35
|
+
* successfully against its now-orphaned inode and report itself the winner
|
|
36
|
+
* regardless — two processes each believing they held the same epoch.
|
|
37
|
+
* Publishing via `linkSync` from an already-complete, already-`fsync`ed
|
|
38
|
+
* temp file closes that window: the final name transitions directly from
|
|
39
|
+
* absent to fully-formed, never through a visible partial state. A caller
|
|
40
|
+
* that already lost synchronously discovers it (the loser's `linkSync`
|
|
41
|
+
* throws `EEXIST`); every later write against a stale epoch is refused
|
|
42
|
+
* inside `assertCurrentEpoch`, never left to the caller to remember to
|
|
43
|
+
* check.
|
|
44
|
+
*/
|
|
45
|
+
|
|
46
|
+
import { randomUUID } from 'node:crypto'
|
|
47
|
+
import {
|
|
48
|
+
closeSync,
|
|
49
|
+
constants as fsConstants,
|
|
50
|
+
existsSync,
|
|
51
|
+
fsyncSync,
|
|
52
|
+
linkSync,
|
|
53
|
+
lstatSync,
|
|
54
|
+
mkdirSync,
|
|
55
|
+
openSync,
|
|
56
|
+
readdirSync,
|
|
57
|
+
readFileSync,
|
|
58
|
+
renameSync,
|
|
59
|
+
statSync,
|
|
60
|
+
unlinkSync,
|
|
61
|
+
writeSync
|
|
62
|
+
} from 'node:fs'
|
|
63
|
+
import { hostname as osHostname } from 'node:os'
|
|
64
|
+
import { dirname, join, resolve, sep } from 'node:path'
|
|
65
|
+
import {
|
|
66
|
+
type EffectRecord,
|
|
67
|
+
type EscalationRecord,
|
|
68
|
+
type InputRecord,
|
|
69
|
+
type LoopStateRecord,
|
|
70
|
+
type ManifestRecord,
|
|
71
|
+
type OwnershipRecord,
|
|
72
|
+
parseEffectRecord,
|
|
73
|
+
parseEscalationRecord,
|
|
74
|
+
parseInputRecord,
|
|
75
|
+
parseLoopStateRecord,
|
|
76
|
+
parseManifestRecord,
|
|
77
|
+
parseOwnershipRecord,
|
|
78
|
+
parseResolutionRecord,
|
|
79
|
+
parseRunRecord,
|
|
80
|
+
parseTransitionRecord,
|
|
81
|
+
type ParsedRecord,
|
|
82
|
+
type ResolutionRecord,
|
|
83
|
+
type RunRecord,
|
|
84
|
+
type TransitionRecord
|
|
85
|
+
} from './records'
|
|
86
|
+
|
|
87
|
+
export type ControlStoreDeps = {
|
|
88
|
+
root: () => string
|
|
89
|
+
now: () => Date
|
|
90
|
+
pid: () => number
|
|
91
|
+
hostname: () => string
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function defaultControlStoreDeps(root: () => string): ControlStoreDeps {
|
|
95
|
+
return {
|
|
96
|
+
root,
|
|
97
|
+
now: () => new Date(),
|
|
98
|
+
pid: () => process.pid,
|
|
99
|
+
hostname: () => osHostname()
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Thrown by every write function when the epoch the caller presents is no longer current — the caller lost ownership (or never had it) and must not have its write honored. */
|
|
104
|
+
export class StaleEpochWriteError extends Error {
|
|
105
|
+
constructor(
|
|
106
|
+
readonly task: number,
|
|
107
|
+
readonly attemptedEpoch: number,
|
|
108
|
+
readonly currentEpoch: number
|
|
109
|
+
) {
|
|
110
|
+
super(
|
|
111
|
+
`control-store: refusing a write for task ${task} at epoch ${attemptedEpoch} — the current epoch is ${currentEpoch}`
|
|
112
|
+
)
|
|
113
|
+
this.name = 'StaleEpochWriteError'
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function isErrnoException(err: unknown, code: string): boolean {
|
|
118
|
+
return typeof err === 'object' && err !== null && (err as NodeJS.ErrnoException).code === code
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function readIfExists(path: string): string | undefined {
|
|
122
|
+
try {
|
|
123
|
+
return readFileSync(path, 'utf8')
|
|
124
|
+
} catch (err) {
|
|
125
|
+
if (isErrnoException(err, 'ENOENT')) return undefined
|
|
126
|
+
// A real read failure (permissions, an unreadable special file) is not
|
|
127
|
+
// "nothing was ever written" — surface it as a corrupt read rather than
|
|
128
|
+
// silently reporting absence. Rethrown here, never swallowed — `readRecord`
|
|
129
|
+
// below is what turns this into the `'corrupt'` a caller actually reads;
|
|
130
|
+
// this function's own contract stays "the raw bytes, undefined, or throw".
|
|
131
|
+
throw err
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Every direct `parse<X>Record(readIfExists(path))` read in this file goes
|
|
137
|
+
* through here instead (round 3 review, BLOCKER): `readIfExists` rethrows a
|
|
138
|
+
* real filesystem fault (permission denied, an unreadable special file, an
|
|
139
|
+
* EIO) raw, and every one of `parseWith`'s callers sits upstream of a caller
|
|
140
|
+
* that reads that record BEFORE its own try/catch is in scope (`recoverLoopState`
|
|
141
|
+
* in `dev-review-loop.ts`, most concretely) — the exact "escapes uncaught
|
|
142
|
+
* instead of becoming a decided pause" failure class round 1's BLOCKER
|
|
143
|
+
* already named for malformed JSON, reopened here through a different
|
|
144
|
+
* trigger. A real read failure is "something is there but untrustworthy," the
|
|
145
|
+
* same fact `parseWith` already reports as `'corrupt'` for torn JSON or a
|
|
146
|
+
* schema violation — never `'absent'`, and never left to erupt uncaught out
|
|
147
|
+
* of every caller of every record kind this store has.
|
|
148
|
+
*/
|
|
149
|
+
function readRecord<T>(path: string, parse: (raw: string | undefined) => ParsedRecord<T>): ParsedRecord<T> {
|
|
150
|
+
try {
|
|
151
|
+
return parse(readIfExists(path))
|
|
152
|
+
} catch (err) {
|
|
153
|
+
return { status: 'corrupt', reason: `filesystem read failed: ${err instanceof Error ? err.message : String(err)}` }
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Whether a directory segment already sitting on disk is safe to write
|
|
159
|
+
* through — a pre-existing REAL directory (never a symlink; that is
|
|
160
|
+
* `mkdirNoSymlinks`'s own `isDirectory()` check, applied before this one)
|
|
161
|
+
* can still be a co-tenant's plant: owning it, or leaving it world-writable,
|
|
162
|
+
* hands that co-tenant the same control over its contents a symlink would
|
|
163
|
+
* (security review, round 3 — the type check alone "never followed a
|
|
164
|
+
* symlink" but said nothing about who could still tamper with a directory
|
|
165
|
+
* of the right type).
|
|
166
|
+
*
|
|
167
|
+
* Two independent properties, both required:
|
|
168
|
+
*
|
|
169
|
+
* **Owner.** Trusted when it is this process's own effective user, or root
|
|
170
|
+
* (uid `0`) — a root-owned ancestor (`/`, `/tmp` itself) predates this store
|
|
171
|
+
* and sits outside any co-tenant's control, the same trust boundary every
|
|
172
|
+
* process on the box already accepts by running at all. Any other owner
|
|
173
|
+
* sitting exactly on this store's own path is the co-tenant-plant case this
|
|
174
|
+
* check exists to catch. Skipped entirely on a platform reporting no uid at
|
|
175
|
+
* all (e.g. Windows) — the same fallback `metering-io-guard.ts`'s
|
|
176
|
+
* `isTrustedMeteringStat` already uses for the same reason.
|
|
177
|
+
*
|
|
178
|
+
* **Mode.** Refused when world-writable UNLESS the sticky bit is also set —
|
|
179
|
+
* the exact shape `/tmp` itself relies on: shared write access, but only an
|
|
180
|
+
* entry's own owner may remove or rename it, so the world-write bit alone
|
|
181
|
+
* never lets another local account delete or replace a file this store
|
|
182
|
+
* already wrote. Without that allowance, `/tmp`'s own standard `1777` would
|
|
183
|
+
* fail this check the moment a test (or a real deployment) resolves a path
|
|
184
|
+
* underneath it. Deliberately narrower than group-writable: this repo's own
|
|
185
|
+
* fixtures routinely create ancestor directories with no explicit mode at
|
|
186
|
+
* all, landing on whatever a shared-group development umask (e.g. `002`)
|
|
187
|
+
* produces — group-writable-but-still-owned-by-us is that ordinary case, not
|
|
188
|
+
* the co-tenant threat (a genuinely different account) this function exists
|
|
189
|
+
* to catch, and group is not the bit `/tmp`'s own convention polices either.
|
|
190
|
+
*
|
|
191
|
+
* Split out from `mkdirNoSymlinks` so the foreign-owner branch — not
|
|
192
|
+
* constructible as a real fixture in CI without a second local user — stays
|
|
193
|
+
* unit-testable against a faked stat, the same convention
|
|
194
|
+
* `metering-io-guard.test.ts`'s `isTrustedMeteringStat` suite already uses;
|
|
195
|
+
* the mode branch is a real, constructible fixture (`local.test.ts`).
|
|
196
|
+
*/
|
|
197
|
+
export function isTrustedDirStat(stat: { uid: number; mode: number }, ownUid: number | undefined): boolean {
|
|
198
|
+
if (typeof ownUid !== 'number') return true
|
|
199
|
+
if (stat.uid !== ownUid && stat.uid !== 0) return false
|
|
200
|
+
const worldWritable = (stat.mode & 0o002) !== 0
|
|
201
|
+
const sticky = (stat.mode & 0o1000) !== 0
|
|
202
|
+
return !worldWritable || sticky
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function currentUid(): number | undefined {
|
|
206
|
+
return typeof process.getuid === 'function' ? process.getuid() : undefined
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Creates `dir` and every missing ancestor, refusing to traverse through a
|
|
211
|
+
* pre-existing symlink — or a pre-existing real directory with an untrusted
|
|
212
|
+
* owner or mode — at or below `trustedRoot` (security review, CRITICAL then
|
|
213
|
+
* round 3; the operating-system-owned-temp-root exemption above it added
|
|
214
|
+
* once an untouched checkout's default temp root turned out to already be
|
|
215
|
+
* such a symlink).
|
|
216
|
+
* `mkdirSync(dir, { recursive: true })` treats an existing symlink-to-directory
|
|
217
|
+
* as already present and silently follows it — every writer that reaches
|
|
218
|
+
* this store's own `openSync`/`writeSync`/`renameSync`/`linkSync` next then
|
|
219
|
+
* operates inside whatever real directory that symlink resolves to. Before
|
|
220
|
+
* `runtimeDir` became a repo-configurable absolute path shared with other
|
|
221
|
+
* local accounts (`apps/cli/src/lib/run-paths.ts`'s own doc comment names
|
|
222
|
+
* `/var/lib/vinaya/runs`), this whole tree sat under a fixed, per-repository,
|
|
223
|
+
* user-owned default and a co-tenant able to pre-plant a symlink was out of
|
|
224
|
+
* scope; a shared, configurable tree makes that co-tenant a real adversary
|
|
225
|
+
* for every path this store writes.
|
|
226
|
+
*
|
|
227
|
+
* `trustedRoot` names the boundary between two zones, both walked from the
|
|
228
|
+
* filesystem root down to `dir`:
|
|
229
|
+
*
|
|
230
|
+
* - **Above `trustedRoot`** (its own ancestors) — never this store's own
|
|
231
|
+
* territory, and on the declared-supported host frequently an
|
|
232
|
+
* operating-system-owned symlink (macOS's default temp root: `/var` is
|
|
233
|
+
* itself a symlink to `/private/var`, and `os.tmpdir()` resolves through
|
|
234
|
+
* it). A symlink here is tolerated, but never blindly: its target is
|
|
235
|
+
* resolved (`statSync`, which follows the link) and that REAL directory is
|
|
236
|
+
* ownership/mode-checked exactly as a non-symlink ancestor already is —
|
|
237
|
+
* `isTrustedDirStat` never sees the symlink's own metadata, only what it
|
|
238
|
+
* points at.
|
|
239
|
+
* - **At or below `trustedRoot`** — this store's own tree, whether
|
|
240
|
+
* `trustedRoot` itself still needs creating or already exists from a prior
|
|
241
|
+
* run. A symlink here is refused unconditionally, the original check,
|
|
242
|
+
* unweakened: a co-tenant on a shared `runtimeDir` who pre-plants a symlink
|
|
243
|
+
* below it must still be caught, whether or not that plant happens to look
|
|
244
|
+
* "pre-existing" from this call's own perspective.
|
|
245
|
+
*
|
|
246
|
+
* Each path segment is created with a plain, non-recursive `mkdirSync` —
|
|
247
|
+
* one this call itself creates cannot be a pre-planted symlink, since it did
|
|
248
|
+
* not exist a moment before — then `lstatSync`-verified without following
|
|
249
|
+
* symlinks, the identical check applied to a segment that already existed.
|
|
250
|
+
*
|
|
251
|
+
* Exported (not just this module's own use) so `apps/cli`'s own run-file
|
|
252
|
+
* writers — `run-paths.ts`'s `ensureRunDir`, the one chokepoint every other
|
|
253
|
+
* run-file directory in that package already goes through — share this
|
|
254
|
+
* exact check rather than a second, independently-maintained copy of it.
|
|
255
|
+
*/
|
|
256
|
+
export function mkdirNoSymlinks(dir: string, mode: number, trustedRoot: string): void {
|
|
257
|
+
const absolute = resolve(dir)
|
|
258
|
+
const rootSegments = resolve(trustedRoot)
|
|
259
|
+
.split(sep)
|
|
260
|
+
.filter((s) => s.length > 0)
|
|
261
|
+
const segments = absolute.split(sep).filter((s) => s.length > 0)
|
|
262
|
+
const ownUid = currentUid()
|
|
263
|
+
let current = absolute.startsWith(sep) ? sep : ''
|
|
264
|
+
segments.forEach((segment, index) => {
|
|
265
|
+
current = current === '' || current === sep ? `${current}${segment}` : `${current}${sep}${segment}`
|
|
266
|
+
// `trustedRoot` itself sits at index `rootSegments.length - 1` — at or
|
|
267
|
+
// below it, refusal is unconditional; strictly above it, a symlink is
|
|
268
|
+
// resolved and its real target trust-checked instead of refused outright.
|
|
269
|
+
const atOrBelowTrustedRoot = index >= rootSegments.length - 1
|
|
270
|
+
try {
|
|
271
|
+
mkdirSync(current, { mode })
|
|
272
|
+
} catch (err) {
|
|
273
|
+
if (!isErrnoException(err, 'EEXIST')) throw err
|
|
274
|
+
}
|
|
275
|
+
const stat = lstatSync(current)
|
|
276
|
+
if (stat.isSymbolicLink()) {
|
|
277
|
+
if (atOrBelowTrustedRoot) {
|
|
278
|
+
throw new Error(
|
|
279
|
+
`control-store: refusing to create a run directory through ${current} — it already exists and is not a real directory (a symlink or a file)`
|
|
280
|
+
)
|
|
281
|
+
}
|
|
282
|
+
let real: ReturnType<typeof statSync>
|
|
283
|
+
try {
|
|
284
|
+
real = statSync(current)
|
|
285
|
+
} catch (err) {
|
|
286
|
+
throw new Error(
|
|
287
|
+
`control-store: refusing to create a run directory through ${current} — it is a symlink whose target could not be resolved: ${err instanceof Error ? err.message : String(err)}`
|
|
288
|
+
)
|
|
289
|
+
}
|
|
290
|
+
if (!real.isDirectory()) {
|
|
291
|
+
throw new Error(
|
|
292
|
+
`control-store: refusing to create a run directory through ${current} — it is a symlink that does not resolve to a real directory`
|
|
293
|
+
)
|
|
294
|
+
}
|
|
295
|
+
if (!isTrustedDirStat(real, ownUid)) {
|
|
296
|
+
throw new Error(
|
|
297
|
+
`control-store: refusing to create a run directory through ${current} — its symlink target is owned by uid ${real.uid} with mode ${(real.mode & 0o7777).toString(8)}, neither this process's own user nor a safe shared mode`
|
|
298
|
+
)
|
|
299
|
+
}
|
|
300
|
+
return
|
|
301
|
+
}
|
|
302
|
+
if (!stat.isDirectory()) {
|
|
303
|
+
throw new Error(
|
|
304
|
+
`control-store: refusing to create a run directory through ${current} — it already exists and is not a real directory (a symlink or a file)`
|
|
305
|
+
)
|
|
306
|
+
}
|
|
307
|
+
if (!isTrustedDirStat(stat, ownUid)) {
|
|
308
|
+
throw new Error(
|
|
309
|
+
`control-store: refusing to create a run directory through ${current} — it already exists, owned by uid ${stat.uid} with mode ${(stat.mode & 0o7777).toString(8)}, neither this process's own user nor a safe shared mode`
|
|
310
|
+
)
|
|
311
|
+
}
|
|
312
|
+
})
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** Whole-file write via temp-then-rename, `fsync`ed before the rename so the bytes are durable, not just visible. `trustedRoot` is this store's own root (`deps.root()`) — see `mkdirNoSymlinks`. */
|
|
316
|
+
function atomicWriteFile(path: string, contents: string, trustedRoot: string): void {
|
|
317
|
+
mkdirNoSymlinks(dirname(path), 0o700, trustedRoot)
|
|
318
|
+
const tmp = `${path}.tmp-${process.pid}-${randomUUID()}`
|
|
319
|
+
const fd = openSync(tmp, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_TRUNC, 0o600)
|
|
320
|
+
try {
|
|
321
|
+
writeSync(fd, contents, null, 'utf8')
|
|
322
|
+
fsyncSync(fd)
|
|
323
|
+
} finally {
|
|
324
|
+
closeSync(fd)
|
|
325
|
+
}
|
|
326
|
+
renameSync(tmp, path)
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Creates `path` with `contents` exclusively and atomically — `contents` is
|
|
331
|
+
* fully written and `fsync`ed to a private temp file first, then published
|
|
332
|
+
* with a single `linkSync`, which either fully succeeds (`path` now holds
|
|
333
|
+
* complete content) or fails `EEXIST` (someone else published first) with
|
|
334
|
+
* no intermediate state in which a reader can observe `path` partially
|
|
335
|
+
* written. Used for every "only one writer may ever occupy this exact
|
|
336
|
+
* name" file: an ownership epoch, a transition sequence slot. See this
|
|
337
|
+
* file's own module doc for why `O_CREAT|O_EXCL` directly at `path` is not
|
|
338
|
+
* used here. `trustedRoot` is this store's own root (`deps.root()`) — see
|
|
339
|
+
* `mkdirNoSymlinks`.
|
|
340
|
+
*/
|
|
341
|
+
function exclusiveCreateFile(
|
|
342
|
+
path: string,
|
|
343
|
+
contents: string,
|
|
344
|
+
trustedRoot: string
|
|
345
|
+
): { created: true } | { created: false } {
|
|
346
|
+
mkdirNoSymlinks(dirname(path), 0o700, trustedRoot)
|
|
347
|
+
const tmp = `${path}.claim-${process.pid}-${randomUUID()}`
|
|
348
|
+
const fd = openSync(tmp, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL, 0o600)
|
|
349
|
+
try {
|
|
350
|
+
writeSync(fd, contents, null, 'utf8')
|
|
351
|
+
fsyncSync(fd)
|
|
352
|
+
} finally {
|
|
353
|
+
closeSync(fd)
|
|
354
|
+
}
|
|
355
|
+
try {
|
|
356
|
+
linkSync(tmp, path)
|
|
357
|
+
return { created: true }
|
|
358
|
+
} catch (err) {
|
|
359
|
+
if (!isErrnoException(err, 'EEXIST')) throw err
|
|
360
|
+
return { created: false }
|
|
361
|
+
} finally {
|
|
362
|
+
// Runs on every exit from the try above — both returns AND a rethrown
|
|
363
|
+
// non-EEXIST error alike (a full disk, a permissions fault) — so the
|
|
364
|
+
// private temp file is never left behind regardless of how `linkSync`
|
|
365
|
+
// failed. The temp file already did its job by this point (its content
|
|
366
|
+
// is durably published at `path`, or it wasn't needed because someone
|
|
367
|
+
// else published first, or publishing itself failed and there is
|
|
368
|
+
// nothing left to keep it for); a failure removing it is not this
|
|
369
|
+
// call's own concern to surface, so it's swallowed here rather than
|
|
370
|
+
// thrown, and never overrides the real return/throw decided above.
|
|
371
|
+
try {
|
|
372
|
+
unlinkSync(tmp)
|
|
373
|
+
} catch {
|
|
374
|
+
// leftover temp file, harmless — never thrown from here
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// `runId` reaches `runPath`/`inputPath` from a caller-supplied value
|
|
380
|
+
// (`RunInput.runId`/`InputInput.runId`) rather than a store-generated one —
|
|
381
|
+
// unlike an epoch or a transition seq, which this module always derives
|
|
382
|
+
// itself. A `runId` carrying a path segment (`../../etc/passwd`, an
|
|
383
|
+
// absolute path) must not be spliced unchecked into a filesystem path; the
|
|
384
|
+
// same discipline `log-sink.ts`'s `isSafeRepoSegment` applies to an
|
|
385
|
+
// environment-sourced repo name, applied here to a run identifier instead.
|
|
386
|
+
const SAFE_ID_SEGMENT = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/
|
|
387
|
+
|
|
388
|
+
export class InvalidRunIdError extends Error {
|
|
389
|
+
constructor(readonly runId: string) {
|
|
390
|
+
super(`control-store: refusing an unsafe runId (must be a single path-safe segment): ${JSON.stringify(runId)}`)
|
|
391
|
+
this.name = 'InvalidRunIdError'
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
function assertSafeRunId(runId: string): void {
|
|
396
|
+
if (!SAFE_ID_SEGMENT.test(runId) || runId.includes('..')) {
|
|
397
|
+
throw new InvalidRunIdError(runId)
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/** An effect's `key` reaches `effectPath` from a caller (`EffectExecutor`'s own caller, ultimately a forge-write call site) the same way `runId` does — the identical path-safety discipline, under its own error type so a caller can tell which id was rejected. */
|
|
402
|
+
export class InvalidEffectKeyError extends Error {
|
|
403
|
+
constructor(readonly key: string) {
|
|
404
|
+
super(`control-store: refusing an unsafe effect key (must be a single path-safe segment): ${JSON.stringify(key)}`)
|
|
405
|
+
this.name = 'InvalidEffectKeyError'
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
function assertSafeEffectKey(key: string): void {
|
|
410
|
+
if (!SAFE_ID_SEGMENT.test(key) || key.includes('..')) {
|
|
411
|
+
throw new InvalidEffectKeyError(key)
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** An escalation/resolution's `escalationId` reaches its path from a caller (`pause-resume.ts`'s `escalationIdFor`, `<task>-<round>-<head>`) the same way an effect's `key` does — the identical path-safety discipline, under its own error type so a caller can tell which id was rejected. */
|
|
416
|
+
export class InvalidEscalationIdError extends Error {
|
|
417
|
+
constructor(readonly escalationId: string) {
|
|
418
|
+
super(
|
|
419
|
+
`control-store: refusing an unsafe escalationId (must be a single path-safe segment): ${JSON.stringify(escalationId)}`
|
|
420
|
+
)
|
|
421
|
+
this.name = 'InvalidEscalationIdError'
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function assertSafeEscalationId(escalationId: string): void {
|
|
426
|
+
if (!SAFE_ID_SEGMENT.test(escalationId) || escalationId.includes('..')) {
|
|
427
|
+
throw new InvalidEscalationIdError(escalationId)
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* A task's own control records: `<root>/<task>/control/`.
|
|
433
|
+
*
|
|
434
|
+
* `root` is the directory holding one folder per task — the CLI passes
|
|
435
|
+
* `<runtimeDir>/tasks-execution` (`apps/cli/src/lib/run-paths.ts`), so a
|
|
436
|
+
* task's control records sit in the `control/` subdirectory of the same
|
|
437
|
+
* folder that holds its session records, its raw output and its per-round
|
|
438
|
+
* reviewer files. The `control/` segment is what keeps those four classes
|
|
439
|
+
* from sharing one flat directory, and is why a caller passes the tasks
|
|
440
|
+
* root rather than a control-store root of its own: there is no longer a
|
|
441
|
+
* separate control-store tree to point at. No record's own filename,
|
|
442
|
+
* content or version changes — only which directory holds it.
|
|
443
|
+
*/
|
|
444
|
+
/**
|
|
445
|
+
* The subdirectory of a task's folder that holds its control records. Named
|
|
446
|
+
* and exported so the CLI's own layout constant
|
|
447
|
+
* (`apps/cli/src/lib/run-paths.ts`'s `RUN_AREA_DIRNAMES.control`) can be
|
|
448
|
+
* derived from this one rather than repeating the literal across a package
|
|
449
|
+
* boundary, where nothing would catch the two drifting apart.
|
|
450
|
+
*/
|
|
451
|
+
export const CONTROL_AREA_DIRNAME = 'control'
|
|
452
|
+
|
|
453
|
+
function taskRoot(root: string, task: number): string {
|
|
454
|
+
return join(root, String(task), CONTROL_AREA_DIRNAME)
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
function ownershipDir(root: string, task: number): string {
|
|
458
|
+
return join(taskRoot(root, task), 'ownership')
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
const EPOCH_FILENAME = /^epoch-(\d+)\.json$/
|
|
462
|
+
|
|
463
|
+
function ownershipEpochPath(root: string, task: number, epoch: number): string {
|
|
464
|
+
return join(ownershipDir(root, task), `epoch-${String(epoch).padStart(6, '0')}.json`)
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
function runPath(root: string, task: number, runId: string): string {
|
|
468
|
+
assertSafeRunId(runId)
|
|
469
|
+
return join(taskRoot(root, task), 'run', `${runId}.json`)
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function inputPath(root: string, task: number, runId: string): string {
|
|
473
|
+
assertSafeRunId(runId)
|
|
474
|
+
return join(taskRoot(root, task), 'input', `${runId}.json`)
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
function manifestPath(root: string, task: number, round: number): string {
|
|
478
|
+
return join(taskRoot(root, task), 'manifest', `round-${String(round).padStart(6, '0')}.json`)
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
function loopStatePath(root: string, task: number): string {
|
|
482
|
+
return join(taskRoot(root, task), 'loop-state.json')
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
function effectPath(root: string, task: number, key: string): string {
|
|
486
|
+
assertSafeEffectKey(key)
|
|
487
|
+
return join(taskRoot(root, task), 'effect', `${key}.json`)
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
function effectDir(root: string, task: number): string {
|
|
491
|
+
return join(taskRoot(root, task), 'effect')
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
function escalationPath(root: string, task: number, escalationId: string): string {
|
|
495
|
+
assertSafeEscalationId(escalationId)
|
|
496
|
+
return join(taskRoot(root, task), 'escalation', `${escalationId}.json`)
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
function resolutionPath(root: string, task: number, escalationId: string): string {
|
|
500
|
+
assertSafeEscalationId(escalationId)
|
|
501
|
+
return join(taskRoot(root, task), 'resolution', `${escalationId}.json`)
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
function transitionsDir(root: string, task: number, epoch: number): string {
|
|
505
|
+
return join(taskRoot(root, task), 'transitions', `epoch-${String(epoch).padStart(6, '0')}`)
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
function transitionPath(root: string, task: number, epoch: number, seq: number): string {
|
|
509
|
+
return join(transitionsDir(root, task, epoch), `${String(seq).padStart(6, '0')}.json`)
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/** The highest validly-parsing ownership epoch on disk, and every epoch number that exists but fails to parse (a corrupt or torn epoch file) — surfaced so a caller can tell "no owner yet" apart from "an owner's record is unreadable". */
|
|
513
|
+
export function readCurrentOwnership(
|
|
514
|
+
deps: Pick<ControlStoreDeps, 'root'>,
|
|
515
|
+
task: number
|
|
516
|
+
): { epoch: number; record: OwnershipRecord | null; corruptEpochs: number[] } {
|
|
517
|
+
const dir = ownershipDir(deps.root(), task)
|
|
518
|
+
if (!existsSync(dir)) return { epoch: 0, record: null, corruptEpochs: [] }
|
|
519
|
+
let bestEpoch = 0
|
|
520
|
+
let best: OwnershipRecord | null = null
|
|
521
|
+
const corruptEpochs: number[] = []
|
|
522
|
+
for (const entry of readdirSync(dir)) {
|
|
523
|
+
const match = EPOCH_FILENAME.exec(entry)
|
|
524
|
+
if (!match) continue
|
|
525
|
+
const epoch = Number.parseInt(match[1] as string, 10)
|
|
526
|
+
const parsed = parseOwnershipRecord(readIfExists(join(dir, entry)))
|
|
527
|
+
if (parsed.status === 'ok') {
|
|
528
|
+
if (epoch > bestEpoch) {
|
|
529
|
+
bestEpoch = epoch
|
|
530
|
+
best = parsed.value
|
|
531
|
+
}
|
|
532
|
+
} else if (parsed.status === 'corrupt') {
|
|
533
|
+
corruptEpochs.push(epoch)
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
return { epoch: best ? bestEpoch : 0, record: best, corruptEpochs }
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
export type AcquireResult =
|
|
540
|
+
| { acquired: true; epoch: number; record: OwnershipRecord }
|
|
541
|
+
| { acquired: false; currentEpoch: number; currentOwnerId: string | null }
|
|
542
|
+
|
|
543
|
+
/** Bounds the reclaim-a-corrupt-slot retry loop below — real contention never approaches this; it exists so a pathological repeated-corruption case fails loudly rather than spinning forever. */
|
|
544
|
+
const MAX_ACQUIRE_ATTEMPTS = 8
|
|
545
|
+
|
|
546
|
+
type ClaimOutcome =
|
|
547
|
+
| { outcome: 'won'; record: OwnershipRecord }
|
|
548
|
+
| { outcome: 'lost'; record: OwnershipRecord }
|
|
549
|
+
| { outcome: 'reclaim' }
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* The single-epoch claim primitive `acquireOwnership` loops on. Exposed on
|
|
553
|
+
* its own because it is what makes the race provable without real OS-level
|
|
554
|
+
* concurrency: two callers that independently observed the same current
|
|
555
|
+
* epoch (`readCurrentOwnership` returning the same value to both, which is
|
|
556
|
+
* exactly what "racing" means here) go on to compute the SAME next epoch
|
|
557
|
+
* and therefore reduce to two calls of THIS function with the identical
|
|
558
|
+
* `epoch` argument — `local.test.ts` calls it directly, twice, with one
|
|
559
|
+
* fixed epoch, to prove `O_EXCL` admits exactly one winner rather than
|
|
560
|
+
* trusting the guarantee unverified.
|
|
561
|
+
*/
|
|
562
|
+
export function attemptEpochClaim(deps: ControlStoreDeps, task: number, epoch: number, ownerId: string): ClaimOutcome {
|
|
563
|
+
const path = ownershipEpochPath(deps.root(), task, epoch)
|
|
564
|
+
const record: OwnershipRecord = {
|
|
565
|
+
version: 1,
|
|
566
|
+
kind: 'ownership',
|
|
567
|
+
task,
|
|
568
|
+
epoch,
|
|
569
|
+
ownerId,
|
|
570
|
+
pid: deps.pid(),
|
|
571
|
+
host: deps.hostname(),
|
|
572
|
+
acquiredAt: deps.now().toISOString()
|
|
573
|
+
}
|
|
574
|
+
const result = exclusiveCreateFile(path, JSON.stringify(record), deps.root())
|
|
575
|
+
if (result.created) return { outcome: 'won', record }
|
|
576
|
+
|
|
577
|
+
// Lost the race, or found a corpse of a crashed claim — tell them apart
|
|
578
|
+
// by re-parsing the exact file we collided on.
|
|
579
|
+
const parsed = parseOwnershipRecord(readIfExists(path))
|
|
580
|
+
if (parsed.status === 'ok') return { outcome: 'lost', record: parsed.value }
|
|
581
|
+
// 'absent' can't happen here (we just observed EEXIST); 'corrupt' means a
|
|
582
|
+
// crashed writer never completed this epoch's claim — reclaim it so the
|
|
583
|
+
// caller can retry the same epoch number.
|
|
584
|
+
try {
|
|
585
|
+
unlinkSync(path)
|
|
586
|
+
} catch (err) {
|
|
587
|
+
if (!isErrnoException(err, 'ENOENT')) throw err
|
|
588
|
+
}
|
|
589
|
+
return { outcome: 'reclaim' }
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/**
|
|
593
|
+
* Acquires the next epoch for `task`. A caller that finds a contested slot
|
|
594
|
+
* already validly held reports the real winner truthfully rather than
|
|
595
|
+
* retrying past it (see `attemptEpochClaim`'s own doc for how that race
|
|
596
|
+
* resolves); a corrupt, crash-orphaned claim is reclaimed and the same
|
|
597
|
+
* epoch retried, bounded by `MAX_ACQUIRE_ATTEMPTS`.
|
|
598
|
+
*/
|
|
599
|
+
export function acquireOwnership(deps: ControlStoreDeps, task: number, ownerId: string): AcquireResult {
|
|
600
|
+
for (let attempt = 0; attempt < MAX_ACQUIRE_ATTEMPTS; attempt++) {
|
|
601
|
+
const current = readCurrentOwnership(deps, task)
|
|
602
|
+
const nextEpoch = current.epoch + 1
|
|
603
|
+
const claim = attemptEpochClaim(deps, task, nextEpoch, ownerId)
|
|
604
|
+
if (claim.outcome === 'won') return { acquired: true, epoch: nextEpoch, record: claim.record }
|
|
605
|
+
if (claim.outcome === 'lost') {
|
|
606
|
+
return { acquired: false, currentEpoch: claim.record.epoch, currentOwnerId: claim.record.ownerId }
|
|
607
|
+
}
|
|
608
|
+
// 'reclaim' — the slot is now clear; loop retries the same nextEpoch.
|
|
609
|
+
}
|
|
610
|
+
throw new Error(`control-store: could not acquire an epoch for task ${task} after ${MAX_ACQUIRE_ATTEMPTS} attempts`)
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
function assertCurrentEpoch(deps: ControlStoreDeps, task: number, epoch: number): void {
|
|
614
|
+
const current = readCurrentOwnership(deps, task)
|
|
615
|
+
if (current.record === null || current.epoch !== epoch) {
|
|
616
|
+
throw new StaleEpochWriteError(task, epoch, current.epoch)
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
export type RunInput = Omit<RunRecord, 'version' | 'kind' | 'task'>
|
|
621
|
+
|
|
622
|
+
/** Refuses (`StaleEpochWriteError`) unless `epoch` is still the task's current epoch — a run record can only be written by whoever currently owns the task. */
|
|
623
|
+
export function writeRun(deps: ControlStoreDeps, task: number, epoch: number, input: RunInput): RunRecord {
|
|
624
|
+
assertCurrentEpoch(deps, task, epoch)
|
|
625
|
+
const record: RunRecord = { version: 1, kind: 'run', task, ...input }
|
|
626
|
+
atomicWriteFile(runPath(deps.root(), task, input.runId), JSON.stringify(record), deps.root())
|
|
627
|
+
return record
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
export function readRun(deps: Pick<ControlStoreDeps, 'root'>, task: number, runId: string): ParsedRecord<RunRecord> {
|
|
631
|
+
return readRecord(runPath(deps.root(), task, runId), parseRunRecord)
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
export type InputInput = Omit<InputRecord, 'version' | 'kind' | 'task'>
|
|
635
|
+
|
|
636
|
+
export function writeInput(deps: ControlStoreDeps, task: number, epoch: number, input: InputInput): InputRecord {
|
|
637
|
+
assertCurrentEpoch(deps, task, epoch)
|
|
638
|
+
const record: InputRecord = { version: 1, kind: 'input', task, ...input }
|
|
639
|
+
atomicWriteFile(inputPath(deps.root(), task, input.runId), JSON.stringify(record), deps.root())
|
|
640
|
+
return record
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
export function readInput(
|
|
644
|
+
deps: Pick<ControlStoreDeps, 'root'>,
|
|
645
|
+
task: number,
|
|
646
|
+
runId: string
|
|
647
|
+
): ParsedRecord<InputRecord> {
|
|
648
|
+
return readRecord(inputPath(deps.root(), task, runId), parseInputRecord)
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
export type ManifestInput = Omit<ManifestRecord, 'version' | 'kind' | 'task'>
|
|
652
|
+
|
|
653
|
+
/**
|
|
654
|
+
* Writes the review-input manifest snapshot for `(task, round)` (O1).
|
|
655
|
+
* Deliberately NOT epoch-fenced, unlike `writeRun`/`writeInput`: this record
|
|
656
|
+
* is an IMMUTABLE per-round snapshot the parent stamps once before dispatching
|
|
657
|
+
* reviewers, not a mutable state transition two owners could race on, and the
|
|
658
|
+
* driver's own cutover to acquired-epoch ownership is separate, later adoption
|
|
659
|
+
* work (`loop.md`, "The control store … built, not yet adopted"). The atomic
|
|
660
|
+
* temp-then-rename write below still gives it the same torn-write-free
|
|
661
|
+
* durability every other record here has; what it does not require is that the
|
|
662
|
+
* caller already hold the task's current epoch, which the parent does not yet
|
|
663
|
+
* acquire. A rerun of the same round overwrites with identical content.
|
|
664
|
+
*/
|
|
665
|
+
export function writeManifest(
|
|
666
|
+
deps: ControlStoreDeps,
|
|
667
|
+
task: number,
|
|
668
|
+
round: number,
|
|
669
|
+
input: ManifestInput
|
|
670
|
+
): ManifestRecord {
|
|
671
|
+
const record: ManifestRecord = { version: 1, kind: 'manifest', task, ...input }
|
|
672
|
+
atomicWriteFile(manifestPath(deps.root(), task, round), JSON.stringify(record), deps.root())
|
|
673
|
+
return record
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
/** The manifest snapshot recorded for `(task, round)`, or `'absent'`/`'corrupt'` — the same three-way read every other record uses, never a nullable read that conflates the two. */
|
|
677
|
+
export function readManifest(
|
|
678
|
+
deps: Pick<ControlStoreDeps, 'root'>,
|
|
679
|
+
task: number,
|
|
680
|
+
round: number
|
|
681
|
+
): ParsedRecord<ManifestRecord> {
|
|
682
|
+
return readRecord(manifestPath(deps.root(), task, round), parseManifestRecord)
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
export type LoopStateInput = Omit<LoopStateRecord, 'version' | 'kind' | 'task'>
|
|
686
|
+
|
|
687
|
+
/**
|
|
688
|
+
* Writes the dev-review-loop's authoritative recovery snapshot for `task` —
|
|
689
|
+
* phase, round, budgets, held-result and delivered-findings identity.
|
|
690
|
+
* Deliberately NOT epoch-fenced, the same
|
|
691
|
+
* precedent `writeManifest` sets: see `LoopStateRecordSchema`'s own doc
|
|
692
|
+
* comment. Overwritten in place on every transition, unlike
|
|
693
|
+
* `writeRun`/`writeInput`.
|
|
694
|
+
*/
|
|
695
|
+
export function writeLoopState(deps: ControlStoreDeps, task: number, input: LoopStateInput): LoopStateRecord {
|
|
696
|
+
const record: LoopStateRecord = { version: 1, kind: 'loop_state', task, ...input }
|
|
697
|
+
atomicWriteFile(loopStatePath(deps.root(), task), JSON.stringify(record), deps.root())
|
|
698
|
+
return record
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
/** The loop-state snapshot recorded for `task`, or `'absent'`/`'corrupt'` — the same three-way read every other record uses, never a nullable read that conflates the two (O3: a caller must be able to tell "nothing recovered yet" apart from "something recorded but untrustworthy," since the latter must never be read as license to reset budgets). */
|
|
702
|
+
export function readLoopState(deps: Pick<ControlStoreDeps, 'root'>, task: number): ParsedRecord<LoopStateRecord> {
|
|
703
|
+
return readRecord(loopStatePath(deps.root(), task), parseLoopStateRecord)
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
export type TransitionInput = Omit<TransitionRecord, 'version' | 'kind' | 'task' | 'epoch' | 'seq'>
|
|
707
|
+
|
|
708
|
+
/**
|
|
709
|
+
* Appends the next transition for `epoch` — refused (`StaleEpochWriteError`)
|
|
710
|
+
* unless `epoch` is still current. The sequence number is itself claimed
|
|
711
|
+
* with `O_EXCL`, incrementing past any slot already taken, rather than
|
|
712
|
+
* trusted from a count the caller computed — two writers (which should
|
|
713
|
+
* never both hold the current epoch, since `assertCurrentEpoch` gates
|
|
714
|
+
* entry, but a crash-and-resume can still leave a partial sequence) never
|
|
715
|
+
* collide on one seq number.
|
|
716
|
+
*/
|
|
717
|
+
export function appendTransition(
|
|
718
|
+
deps: ControlStoreDeps,
|
|
719
|
+
task: number,
|
|
720
|
+
epoch: number,
|
|
721
|
+
input: TransitionInput
|
|
722
|
+
): TransitionRecord {
|
|
723
|
+
assertCurrentEpoch(deps, task, epoch)
|
|
724
|
+
const root = deps.root()
|
|
725
|
+
const dir = transitionsDir(root, task, epoch)
|
|
726
|
+
let seq = existsSync(dir) ? readdirSync(dir).length : 0
|
|
727
|
+
for (let attempt = 0; attempt < MAX_ACQUIRE_ATTEMPTS; attempt++) {
|
|
728
|
+
const record: TransitionRecord = { version: 1, kind: 'transition', task, epoch, seq, ...input }
|
|
729
|
+
const result = exclusiveCreateFile(transitionPath(root, task, epoch, seq), JSON.stringify(record), root)
|
|
730
|
+
if (result.created) return record
|
|
731
|
+
seq++
|
|
732
|
+
}
|
|
733
|
+
throw new Error(`control-store: could not claim a transition seq for task ${task} epoch ${epoch}`)
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/** Every transition recorded for `epoch`, in `seq` order — a corrupt entry is surfaced as its own `'corrupt'` element, never dropped and never conflated with "no more transitions". */
|
|
737
|
+
export function readTransitions(
|
|
738
|
+
deps: Pick<ControlStoreDeps, 'root'>,
|
|
739
|
+
task: number,
|
|
740
|
+
epoch: number
|
|
741
|
+
): ParsedRecord<TransitionRecord>[] {
|
|
742
|
+
const dir = transitionsDir(deps.root(), task, epoch)
|
|
743
|
+
if (!existsSync(dir)) return []
|
|
744
|
+
return readdirSync(dir)
|
|
745
|
+
.filter((name) => /^\d+\.json$/.test(name))
|
|
746
|
+
.sort()
|
|
747
|
+
.map((name) => readRecord(join(dir, name), parseTransitionRecord))
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
export type EffectInput = Omit<EffectRecord, 'version' | 'kind' | 'task' | 'key'>
|
|
751
|
+
|
|
752
|
+
/**
|
|
753
|
+
* Writes (or overwrites — unlike `writeRun`/`writeInput`, an effect record
|
|
754
|
+
* advances through `'started'` → `'verified'`/`'uncertain'` in place, one
|
|
755
|
+
* file per `key`) an effect record, fenced by `epoch` the same as every
|
|
756
|
+
* other write here: refused (`StaleEpochWriteError`) the instant the caller
|
|
757
|
+
* no longer holds `task`'s current epoch.
|
|
758
|
+
*/
|
|
759
|
+
export function writeEffect(
|
|
760
|
+
deps: ControlStoreDeps,
|
|
761
|
+
task: number,
|
|
762
|
+
epoch: number,
|
|
763
|
+
key: string,
|
|
764
|
+
input: EffectInput
|
|
765
|
+
): EffectRecord {
|
|
766
|
+
assertCurrentEpoch(deps, task, epoch)
|
|
767
|
+
const record: EffectRecord = { version: 1, kind: 'effect', task, key, ...input }
|
|
768
|
+
atomicWriteFile(effectPath(deps.root(), task, key), JSON.stringify(record), deps.root())
|
|
769
|
+
return record
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
export function readEffect(
|
|
773
|
+
deps: Pick<ControlStoreDeps, 'root'>,
|
|
774
|
+
task: number,
|
|
775
|
+
key: string
|
|
776
|
+
): ParsedRecord<EffectRecord> {
|
|
777
|
+
return readRecord(effectPath(deps.root(), task, key), parseEffectRecord)
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
/**
|
|
781
|
+
* Every effect key currently on disk for `task`, `'started'` records only —
|
|
782
|
+
* O3's "unresolved effects remain explicitly uncertain" starting point: a
|
|
783
|
+
* cancellation calls this, then `markEffectUncertain` on each key returned,
|
|
784
|
+
* so an in-flight-but-never-confirmed write is never left silently
|
|
785
|
+
* ambiguous. A corrupt effect record is skipped here (nothing safe to say
|
|
786
|
+
* about its status) rather than thrown — cancellation must not itself fail
|
|
787
|
+
* because one unrelated effect record is unreadable.
|
|
788
|
+
*/
|
|
789
|
+
export function listStartedEffectKeys(deps: Pick<ControlStoreDeps, 'root'>, task: number): string[] {
|
|
790
|
+
const dir = effectDir(deps.root(), task)
|
|
791
|
+
if (!existsSync(dir)) return []
|
|
792
|
+
const keys: string[] = []
|
|
793
|
+
for (const entry of readdirSync(dir)) {
|
|
794
|
+
if (!entry.endsWith('.json')) continue
|
|
795
|
+
const key = entry.slice(0, -'.json'.length)
|
|
796
|
+
const parsed = parseEffectRecord(readIfExists(join(dir, entry)))
|
|
797
|
+
if (parsed.status === 'ok' && parsed.value.status === 'started') keys.push(key)
|
|
798
|
+
}
|
|
799
|
+
return keys
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
/**
|
|
803
|
+
* Advances one effect record from `'started'` to `'uncertain'` — the same
|
|
804
|
+
* transition `EffectExecutor`'s own `reconcileExisting` writes when a
|
|
805
|
+
* reconciliation comes back ambiguous, applied here unconditionally rather
|
|
806
|
+
* than after a remote read: a cancellation does not attempt to reconcile a
|
|
807
|
+
* late-in-flight write against the forge, it simply refuses to let it read
|
|
808
|
+
* as either confirmed or safely retryable. Epoch-fenced like every other
|
|
809
|
+
* write here — a caller must hold the CURRENT epoch (the one cancellation
|
|
810
|
+
* itself just acquired) for this to succeed. A key that no longer parses as
|
|
811
|
+
* `'started'` (already advanced, or corrupt) is left untouched and simply
|
|
812
|
+
* omitted from the return value.
|
|
813
|
+
*/
|
|
814
|
+
export function markEffectUncertain(
|
|
815
|
+
deps: ControlStoreDeps,
|
|
816
|
+
task: number,
|
|
817
|
+
epoch: number,
|
|
818
|
+
key: string
|
|
819
|
+
): EffectRecord | null {
|
|
820
|
+
const existing = readEffect(deps, task, key)
|
|
821
|
+
if (existing.status !== 'ok' || existing.value.status !== 'started') return null
|
|
822
|
+
return writeEffect(deps, task, epoch, key, {
|
|
823
|
+
operation: existing.value.operation,
|
|
824
|
+
target: existing.value.target,
|
|
825
|
+
inputVersion: existing.value.inputVersion,
|
|
826
|
+
payloadDigest: existing.value.payloadDigest,
|
|
827
|
+
status: 'uncertain',
|
|
828
|
+
recordedAt: deps.now().toISOString()
|
|
829
|
+
})
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
export type EscalationInput = Omit<EscalationRecord, 'version' | 'kind' | 'task'>
|
|
833
|
+
|
|
834
|
+
/**
|
|
835
|
+
* True when two escalation inputs describe the SAME pause instance — every
|
|
836
|
+
* field but `recordedAt` (which always differs on a rerun) and `evidence`
|
|
837
|
+
* (best-effort, allowed to fill in on a later attempt where an earlier one
|
|
838
|
+
* had none). Used only to tell "a rerun of the identical pause" apart from
|
|
839
|
+
* "a genuinely different pause that happens to collide on the same
|
|
840
|
+
* `(task, round, head)` key" — see `writeEscalation`'s own doc comment.
|
|
841
|
+
*/
|
|
842
|
+
function sameEscalationInstance(a: EscalationInput, b: EscalationInput): boolean {
|
|
843
|
+
return (
|
|
844
|
+
a.round === b.round &&
|
|
845
|
+
a.head === b.head &&
|
|
846
|
+
a.branch === b.branch &&
|
|
847
|
+
a.pr === b.pr &&
|
|
848
|
+
a.reason === b.reason &&
|
|
849
|
+
(a.detail ?? null) === (b.detail ?? null)
|
|
850
|
+
)
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
/** Bounds the disambiguating-suffix probe below — real collisions never approach this; exists so a pathological repeated-collision case fails loudly rather than spinning forever. */
|
|
854
|
+
const MAX_ESCALATION_COLLISION_ATTEMPTS = 8
|
|
855
|
+
|
|
856
|
+
/**
|
|
857
|
+
* Refuses (`StaleEpochWriteError`) unless `epoch` is still the task's
|
|
858
|
+
* current epoch — an escalation can only be recorded by whoever currently
|
|
859
|
+
* owns the task's pause. Idempotent on a rerun of the SAME pause instance
|
|
860
|
+
* (`sameEscalationInstance` — an ordinary overwrite, like `writeManifest`).
|
|
861
|
+
*
|
|
862
|
+
* A GENUINELY DIFFERENT escalation colliding on the same `escalationId`
|
|
863
|
+
* (`<task>-<round>-<head>`) — a resumed run that hits a second, different
|
|
864
|
+
* pause condition before the head moves, most plausibly one of the
|
|
865
|
+
* self-resumed reasons (`objectives_changed`, `ruling_posted`,
|
|
866
|
+
* `stale_driver`, `brief_superseded`, `policy_changed`), which dispatch no
|
|
867
|
+
* developer and so never guarantee a new head — is never silently
|
|
868
|
+
* overwritten (code review, round 2, MEDIUM: the earlier pause's own
|
|
869
|
+
* reason/detail/evidence would otherwise become unrecoverable except
|
|
870
|
+
* through chat history, exactly what O1 exists to avoid). Instead it claims
|
|
871
|
+
* the next free `<escalationId>-<n>` suffix via the same exclusive-create
|
|
872
|
+
* discipline `attemptEpochClaim`/`appendTransition`'s own seq-slot claim
|
|
873
|
+
* uses — never `atomicWriteFile` for this branch, so two colliding writers
|
|
874
|
+
* can never both believe they won the same suffix. The record actually
|
|
875
|
+
* written (never the caller's original `input.escalationId` once a suffix
|
|
876
|
+
* was needed) is what the caller must key any later read against — see
|
|
877
|
+
* `writeEscalationRecord` (`pause-resume.ts`), which persists the real id
|
|
878
|
+
* back onto `PauseState` for exactly this reason.
|
|
879
|
+
*/
|
|
880
|
+
export function writeEscalation(
|
|
881
|
+
deps: ControlStoreDeps,
|
|
882
|
+
task: number,
|
|
883
|
+
epoch: number,
|
|
884
|
+
input: EscalationInput
|
|
885
|
+
): EscalationRecord {
|
|
886
|
+
assertCurrentEpoch(deps, task, epoch)
|
|
887
|
+
const canonicalId = input.escalationId
|
|
888
|
+
const existing = readEscalation(deps, task, canonicalId)
|
|
889
|
+
if (existing.status !== 'ok' || sameEscalationInstance(existing.value, input)) {
|
|
890
|
+
// Absent, corrupt (healed by overwrite), or a genuine rerun of the
|
|
891
|
+
// identical instance — safe to (re)write at the canonical key.
|
|
892
|
+
const record: EscalationRecord = { version: 1, kind: 'escalation', task, ...input }
|
|
893
|
+
atomicWriteFile(escalationPath(deps.root(), task, canonicalId), JSON.stringify(record), deps.root())
|
|
894
|
+
return record
|
|
895
|
+
}
|
|
896
|
+
for (let n = 2; n <= MAX_ESCALATION_COLLISION_ATTEMPTS; n++) {
|
|
897
|
+
const candidateId = `${canonicalId}-${n}`
|
|
898
|
+
const record: EscalationRecord = { version: 1, kind: 'escalation', task, ...input, escalationId: candidateId }
|
|
899
|
+
const result = exclusiveCreateFile(
|
|
900
|
+
escalationPath(deps.root(), task, candidateId),
|
|
901
|
+
JSON.stringify(record),
|
|
902
|
+
deps.root()
|
|
903
|
+
)
|
|
904
|
+
if (result.created) return record
|
|
905
|
+
const there = readEscalation(deps, task, candidateId)
|
|
906
|
+
if (there.status === 'ok' && sameEscalationInstance(there.value, input)) return there.value
|
|
907
|
+
// Slot taken by yet another distinct instance — try the next suffix.
|
|
908
|
+
}
|
|
909
|
+
throw new Error(
|
|
910
|
+
`control-store: could not claim a disambiguating escalation slot for task ${task}, key '${canonicalId}', after ${MAX_ESCALATION_COLLISION_ATTEMPTS} attempts`
|
|
911
|
+
)
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
export function readEscalation(
|
|
915
|
+
deps: Pick<ControlStoreDeps, 'root'>,
|
|
916
|
+
task: number,
|
|
917
|
+
escalationId: string
|
|
918
|
+
): ParsedRecord<EscalationRecord> {
|
|
919
|
+
return parseEscalationRecord(readIfExists(escalationPath(deps.root(), task, escalationId)))
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
export type ResolutionInput = Omit<ResolutionRecord, 'version' | 'kind' | 'task'>
|
|
923
|
+
|
|
924
|
+
export type ConsumeResolutionResult =
|
|
925
|
+
| { outcome: 'consumed'; record: ResolutionRecord }
|
|
926
|
+
| { outcome: 'already-consumed'; record: ResolutionRecord | null }
|
|
927
|
+
|
|
928
|
+
/**
|
|
929
|
+
* Claims `escalationId`'s resolution EXCLUSIVELY — the same `linkSync`
|
|
930
|
+
* discipline an ownership epoch claim uses (`exclusiveCreateFile`), never an
|
|
931
|
+
* ordinary overwrite: a second call for the SAME `escalationId`, whether a
|
|
932
|
+
* genuine replay of an already-consumed decision or a second decision
|
|
933
|
+
* racing the first, collides on the identical final name and comes back
|
|
934
|
+
* `'already-consumed'` rather than silently replacing what is already
|
|
935
|
+
* there. This is what makes "a resolution is consumed once" a storage
|
|
936
|
+
* guarantee rather than an application-level check the caller could forget.
|
|
937
|
+
* Epoch-fenced like every other write here (`StaleEpochWriteError` on a
|
|
938
|
+
* stale caller), on top of — not instead of — the exclusivity above.
|
|
939
|
+
*/
|
|
940
|
+
export function consumeResolutionOnce(
|
|
941
|
+
deps: ControlStoreDeps,
|
|
942
|
+
task: number,
|
|
943
|
+
epoch: number,
|
|
944
|
+
input: ResolutionInput
|
|
945
|
+
): ConsumeResolutionResult {
|
|
946
|
+
assertCurrentEpoch(deps, task, epoch)
|
|
947
|
+
const record: ResolutionRecord = { version: 1, kind: 'resolution', task, ...input }
|
|
948
|
+
const path = resolutionPath(deps.root(), task, input.escalationId)
|
|
949
|
+
const result = exclusiveCreateFile(path, JSON.stringify(record), deps.root())
|
|
950
|
+
if (result.created) return { outcome: 'consumed', record }
|
|
951
|
+
const existing = parseResolutionRecord(readIfExists(path))
|
|
952
|
+
return { outcome: 'already-consumed', record: existing.status === 'ok' ? existing.value : null }
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
export function readResolution(
|
|
956
|
+
deps: Pick<ControlStoreDeps, 'root'>,
|
|
957
|
+
task: number,
|
|
958
|
+
escalationId: string
|
|
959
|
+
): ParsedRecord<ResolutionRecord> {
|
|
960
|
+
return parseResolutionRecord(readIfExists(resolutionPath(deps.root(), task, escalationId)))
|
|
961
|
+
}
|