pi-better-server 0.2.4 → 0.4.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.
Files changed (109) hide show
  1. package/package.json +6 -3
  2. package/scripts/measure-shared-reads/daemon.mjs +7 -0
  3. package/scripts/measure-shared-reads/probe.mjs +10 -0
  4. package/scripts/measure-shared-reads.mjs +165 -0
  5. package/scripts/test-on-pi.sh +21 -3
  6. package/src/cli.ts +39 -2
  7. package/src/client.ts +9 -4
  8. package/src/daemon-owner.ts +48 -6
  9. package/src/handshake.ts +8 -7
  10. package/src/lifecycle-config.ts +4 -0
  11. package/src/paths.ts +1 -11
  12. package/src/protocol.ts +7 -0
  13. package/src/registry.ts +2 -1
  14. package/src/runtime/background-history.ts +241 -0
  15. package/src/runtime/background.ts +182 -0
  16. package/src/runtime/cancellation.ts +99 -0
  17. package/src/runtime/catalog-admission.ts +50 -0
  18. package/src/runtime/catalog.ts +133 -0
  19. package/src/runtime/client.ts +111 -0
  20. package/src/runtime/domain/assignment-observation.d.mts +1 -0
  21. package/src/runtime/domain/assignment-observation.mjs +120 -0
  22. package/src/runtime/domain/assignment-projection.d.mts +1 -0
  23. package/src/runtime/domain/assignment-projection.mjs +245 -0
  24. package/src/runtime/domain/background/conditions.mjs +93 -0
  25. package/src/runtime/domain/background/process-identity.mjs +110 -0
  26. package/src/runtime/domain/background/process.mjs +511 -0
  27. package/src/runtime/domain/background/registry.mjs +374 -0
  28. package/src/runtime/domain/background/snapshot.mjs +73 -0
  29. package/src/runtime/domain/background/supervisor/identity.mjs +92 -0
  30. package/src/runtime/domain/background/supervisor/invocation.mjs +29 -0
  31. package/src/runtime/domain/background/supervisor/store.mjs +604 -0
  32. package/src/runtime/domain/background/supervisor/supervisor.mjs +720 -0
  33. package/src/runtime/domain/background/supervisor/types.mjs +47 -0
  34. package/src/runtime/domain/background/terminal-publication.mjs +58 -0
  35. package/src/runtime/domain/background/types.mjs +3 -0
  36. package/src/runtime/domain/catalog/agent-session-settings.d.mts +30 -0
  37. package/src/runtime/domain/catalog/agent-session-settings.mjs +112 -0
  38. package/src/runtime/domain/catalog/catalog-overlay.d.mts +3 -0
  39. package/src/runtime/domain/catalog/catalog-overlay.mjs +9 -0
  40. package/src/runtime/domain/catalog/catalog-preferences.d.mts +17 -0
  41. package/src/runtime/domain/catalog/catalog-preferences.mjs +164 -0
  42. package/src/runtime/domain/catalog/catalog-schema.d.mts +265 -0
  43. package/src/runtime/domain/catalog/catalog-schema.mjs +1331 -0
  44. package/src/runtime/domain/catalog/catalog-skill-edits.d.mts +42 -0
  45. package/src/runtime/domain/catalog/catalog-skill-edits.mjs +95 -0
  46. package/src/runtime/domain/catalog/catalog-store.d.mts +126 -0
  47. package/src/runtime/domain/catalog/catalog-store.mjs +810 -0
  48. package/src/runtime/domain/catalog/roles/role.architect.md +13 -0
  49. package/src/runtime/domain/catalog/roles/role.developer.md +16 -0
  50. package/src/runtime/domain/catalog/roles/role.explorer.md +13 -0
  51. package/src/runtime/domain/catalog/roles/role.product-manager.md +13 -0
  52. package/src/runtime/domain/catalog/roles/role.researcher.md +13 -0
  53. package/src/runtime/domain/catalog/roles/role.reviewer.md +13 -0
  54. package/src/runtime/domain/catalog/roles/role.writer.md +12 -0
  55. package/src/runtime/domain/catalog/thinking.d.mts +8 -0
  56. package/src/runtime/domain/catalog/thinking.mjs +22 -0
  57. package/src/runtime/domain/coordinator/index.mjs +50 -0
  58. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +160 -0
  59. package/src/runtime/domain/coordinator/src/discovery.mjs +94 -0
  60. package/src/runtime/domain/coordinator/src/errors.mjs +12 -0
  61. package/src/runtime/domain/coordinator/src/operations.mjs +301 -0
  62. package/src/runtime/domain/coordinator/src/outbox.mjs +282 -0
  63. package/src/runtime/domain/coordinator/src/recovery.mjs +51 -0
  64. package/src/runtime/domain/coordinator/src/result-supervision.mjs +101 -0
  65. package/src/runtime/domain/coordinator/src/rows.mjs +277 -0
  66. package/src/runtime/domain/coordinator/src/schema.mjs +367 -0
  67. package/src/runtime/domain/coordinator/src/sqlite.mjs +193 -0
  68. package/src/runtime/domain/coordinator/src/store.mjs +245 -0
  69. package/src/runtime/domain/coordinator/src/task-cancellation.mjs +187 -0
  70. package/src/runtime/domain/coordinator/src/types.mjs +24 -0
  71. package/src/runtime/domain/coordinator/src/validate.mjs +233 -0
  72. package/src/runtime/domain/coordinator/src/waits.mjs +850 -0
  73. package/src/runtime/domain/health-observation.d.mts +3 -0
  74. package/src/runtime/domain/health-observation.mjs +613 -0
  75. package/src/runtime/domain/health-surface.mjs +279 -0
  76. package/src/runtime/domain/log-cursor.mjs +148 -0
  77. package/src/runtime/domain/log-paths.mjs +13 -0
  78. package/src/runtime/domain/parse.d.mts +2 -0
  79. package/src/runtime/domain/parse.mjs +1173 -0
  80. package/src/runtime/domain/process-status.d.mts +1 -0
  81. package/src/runtime/domain/process-status.mjs +25 -0
  82. package/src/runtime/domain/session-store.d.mts +2 -0
  83. package/src/runtime/domain/session-store.mjs +489 -0
  84. package/src/runtime/domain/shared-harness-settings.d.mts +1 -0
  85. package/src/runtime/domain/shared-harness-settings.mjs +126 -0
  86. package/src/runtime/domain/shared-log-utils.mjs +1223 -0
  87. package/src/runtime/domain/shared-stall-detector.mjs +37 -0
  88. package/src/runtime/domain/widget.d.mts +1 -0
  89. package/src/runtime/domain/widget.mjs +250 -0
  90. package/src/runtime/guardian.ts +189 -0
  91. package/src/runtime/health-config.ts +27 -0
  92. package/src/runtime/local-client.ts +34 -0
  93. package/src/runtime/mutation-store.ts +34 -0
  94. package/src/runtime/queries.ts +76 -0
  95. package/src/runtime/query-executor.ts +277 -0
  96. package/src/runtime/query-worker.mjs +119 -0
  97. package/src/runtime/read-model.ts +409 -0
  98. package/src/runtime/result-supervision.ts +63 -0
  99. package/src/runtime/root.ts +29 -0
  100. package/src/runtime/socket.ts +10 -0
  101. package/src/runtime/status-cli.ts +11 -0
  102. package/src/runtime/work-client.d.mts +14 -0
  103. package/src/runtime/work-client.mjs +102 -0
  104. package/src/server.ts +199 -14
  105. package/src/session-activity.ts +22 -2
  106. package/src/startup/activation.ts +32 -5
  107. package/src/startup/ensure.ts +13 -1
  108. package/src/startup/install.ts +2 -0
  109. package/src/version.ts +4 -0
@@ -0,0 +1,13 @@
1
+ ---
2
+ schema: pi-agent/v1
3
+ kind: role
4
+ id: role.architect
5
+ name: Architect
6
+ description: Owns architecture choices and cross-module boundaries; excludes implementation and acceptance policy.
7
+ defaults:
8
+ model: openai/gpt-6-astra
9
+ effort: high
10
+ tier: frontier
11
+ ---
12
+ Own architecture choices, interfaces, and cross-module boundaries. Choose a structure that fits the existing system and name the trade-off; do not add a second execution path when the current one can carry the change.
13
+ Do not implement production code or define user-visible policy. Route implementation to Developer, acceptance policy to Product Manager, and independent evidence gathering to Researcher or code-path mapping to Explorer.
@@ -0,0 +1,16 @@
1
+ ---
2
+ schema: pi-agent/v1
3
+ kind: role
4
+ id: role.developer
5
+ name: Developer
6
+ description: Owns implementation and focused tests, including release metadata preparation; excludes delivery, publishing, architecture policy, and independent review.
7
+ defaults:
8
+ model: openai/gpt-6.1-sol
9
+ effort: high
10
+ tier: balanced
11
+ ---
12
+ Implement the requested change in the existing system and own focused tests. Preserve behavior the task did not ask to change, and record what you verified.
13
+ For a release, prepare and test metadata under the coordinator's approved plan: version files, dependency pins, lockfile, changelog, and package checks. Hand back the local changes or commit, verification evidence, and remaining blockers.
14
+ Delivery and publishing belong to the coordinator: remote pushes, PR creation and merge, queue admission, release tags, publisher dispatch, and publication verification. Do not perform those operations or take ownership of external waits. The coordinator uses background watchers for CI, merge queues, publishers, registry propagation, and deployments. If an assignment crosses this boundary, report the mismatch and hand it back before proceeding.
15
+ When a check fails, report the failing step, the error message and where the evidence is; an exit code alone is not a failure report. Keep the first failure separate from later cleanup errors. Send long command output to a file and read only the tail or the matching lines.
16
+ Do not define product policy or own broad architecture decisions; route those to Product Manager or Architect. Independent critique belongs to Reviewer, not the implementer.
@@ -0,0 +1,13 @@
1
+ ---
2
+ schema: pi-agent/v1
3
+ kind: role
4
+ id: role.explorer
5
+ name: Explorer
6
+ description: Owns repository code-path mapping; excludes external research and implementation.
7
+ defaults:
8
+ model: openai/gpt-6-luna
9
+ effort: medium
10
+ tier: efficient
11
+ ---
12
+ Own narrow repository exploration: map the code, configuration, call paths, and local conventions a task depends on. Return relevant files and open questions.
13
+ Do not edit code or decide architecture. Route implementation to Developer and boundary decisions to Architect; external documentation and source evaluation belong to Researcher.
@@ -0,0 +1,13 @@
1
+ ---
2
+ schema: pi-agent/v1
3
+ kind: role
4
+ id: role.product-manager
5
+ name: Product Manager
6
+ description: Owns user-visible requirements and acceptance criteria; excludes technical design and implementation.
7
+ defaults:
8
+ model: openai/gpt-6.1-sol
9
+ effort: medium
10
+ tier: balanced
11
+ ---
12
+ Own user-visible behavior, edge cases, and acceptance criteria. Keep business rules separate from implementation plans; do not invent policy beyond the request.
13
+ Do not choose code boundaries or implement them. Route technical design to Architect, implementation to Developer, and evidence gathering for unresolved factual claims to Researcher.
@@ -0,0 +1,13 @@
1
+ ---
2
+ schema: pi-agent/v1
3
+ kind: role
4
+ id: role.researcher
5
+ name: Researcher
6
+ description: Owns external-source evidence and factual uncertainty; excludes repo mapping and changes.
7
+ defaults:
8
+ model: openai/gpt-6.1-terra
9
+ effort: medium
10
+ tier: balanced
11
+ ---
12
+ Own evidence gathering from supplied references and external documentation. Return cited sources, what they support, and what remains uncertain.
13
+ Do not edit code, set product policy, or map internal execution paths; route repository exploration to Explorer, product decisions to Product Manager, and implementation to Developer. This role does not change tools, sandbox, or controls selected at launch.
@@ -0,0 +1,13 @@
1
+ ---
2
+ schema: pi-agent/v1
3
+ kind: role
4
+ id: role.reviewer
5
+ name: Reviewer
6
+ description: Owns independent review of changes and risk findings; excludes implementation and requirement setting.
7
+ defaults:
8
+ model: openai/gpt-6-astra
9
+ effort: medium
10
+ tier: frontier
11
+ ---
12
+ Own independent review of a change against the request, repository rules, and regression risk. Report concrete findings first, then residual risk and test gaps.
13
+ Do not rewrite the change or invent requirements unless explicitly asked. Route fixes to Developer, disputed user-visible policy to Product Manager, and boundary decisions to Architect.
@@ -0,0 +1,12 @@
1
+ ---
2
+ schema: pi-agent/v1
3
+ kind: role
4
+ id: role.writer
5
+ name: Writer
6
+ description: Owns drafting, editing, and polishing written content; excludes product policy and production code.
7
+ defaults:
8
+ model: openai/gpt-6.1-terra
9
+ effort: medium
10
+ ---
11
+ Draft, edit, and polish written content for the requested audience and purpose. Follow the supplied brief, source material, terminology, and applicable writing guidance. Preserve facts, figures, citations, and constraints; flag missing evidence instead of inventing it.
12
+ Do not define product policy or implement production code. Route product decisions to Product Manager, missing external evidence to Researcher, and code changes to Developer. This role does not change tools, sandbox, or controls selected at launch.
@@ -0,0 +1,8 @@
1
+ export declare const THINKING_LEVELS: readonly ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
2
+ export type ThinkingLevel = typeof THINKING_LEVELS[number];
3
+ export declare function assertThinkingLevel(value: unknown, label?: string): asserts value is ThinkingLevel | undefined;
4
+ /** Resolve the convenient `model@effort` shorthand used by subagent callers. */
5
+ export declare function parseModelThinking(model: string | undefined, thinking?: ThinkingLevel): {
6
+ model: string | undefined;
7
+ thinking: ThinkingLevel | undefined;
8
+ };
@@ -0,0 +1,22 @@
1
+ // Generated from packages/pi-better-subagents/thinking.ts. Do not edit directly.
2
+ export const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
3
+ const VALID_THINKING_LEVELS = new Set(THINKING_LEVELS);
4
+ export function assertThinkingLevel(value, label = "thinking") {
5
+ if (value === undefined || VALID_THINKING_LEVELS.has(String(value)))
6
+ return;
7
+ throw new Error(`${label} must be one of: ${THINKING_LEVELS.join(", ")}; got ${JSON.stringify(value)}.`);
8
+ }
9
+ /** Resolve the convenient `model@effort` shorthand used by subagent callers. */
10
+ export function parseModelThinking(model, thinking) {
11
+ if (!model)
12
+ return { model, thinking };
13
+ const separator = model.lastIndexOf("@");
14
+ if (separator <= 0 || separator === model.length - 1)
15
+ return { model, thinking };
16
+ const suffix = model.slice(separator + 1);
17
+ assertThinkingLevel(suffix, "model thinking suffix");
18
+ return {
19
+ model: model.slice(0, separator),
20
+ thinking: thinking ?? suffix,
21
+ };
22
+ }
@@ -0,0 +1,50 @@
1
+ // Generated canonical coordinator. Do not edit directly.
2
+ /**
3
+ * Durable operation coordinator.
4
+ *
5
+ * A small, reusable library that records what a harness is waiting for and who
6
+ * owns the result. It provides no provider transport, no process launch, no tool
7
+ * execution and no model call: Background Tasks, Subagents and the parent
8
+ * harness share these records instead of duplicating a journal.
9
+ *
10
+ * The contracts here implement the accepted invariant in
11
+ * `docs/adr/0020-observed-waits-retain-an-owner.md` and the record shapes in
12
+ * `docs/plans/observed-waits-design.md`.
13
+ *
14
+ * ```ts
15
+ * import { openStore } from "operation-coordinator";
16
+ *
17
+ * const store = openStore({ path: join(agentDir, "operation-coordinator.sqlite") });
18
+ * store.registerOperation({ operationId, taskId, launchToken, owner, observer });
19
+ * // later, from the supervisor:
20
+ * store.recordTerminalOutcome({ operationId, eventId, outcome: "succeeded", owner, evidence });
21
+ * // the owner interprets the evidence it read, then consumes the wait:
22
+ * store.recordEvidenceRead({ waitId, generation, owner, operationId, terminalRevision: 1 });
23
+ * store.acknowledgeResult({ waitId, generation, owner, disposition: "continue", note, terminalRevisions });
24
+ * ```
25
+ *
26
+ * Rules the store enforces by itself:
27
+ *
28
+ * - an owner, task id and launch token are immutable once registered;
29
+ * - one durable operation per background task, and one pending wait generation
30
+ * per owner identity;
31
+ * - a parked worker reaches `waiting`/`ready` only with checkpoint and writer
32
+ * exit proof, and a dependency that settled earlier is never missed;
33
+ * - duplicate terminal events and replayed reconciliation produce one terminal
34
+ * revision and one delivery per wait generation;
35
+ * - resume attempt ids and launch tokens are persisted before spawn, and one
36
+ * generation has one active claim;
37
+ * - cancellation increments a fencing epoch and invalidates the pending claim;
38
+ * - an acknowledgement requires a recorded read of the exact evidence revision by
39
+ * the owner, and only then are evidence pins released;
40
+ * - no credential, token value or environment value is stored; obvious secret
41
+ * material in a note or reference is refused.
42
+ *
43
+ * `node:sqlite` (Node 24+) is required. There is no in-memory fallback: an
44
+ * unavailable or unreadable database disables the feature instead of pretending
45
+ * to be durable.
46
+ */
47
+ export { SCHEMA_VERSION, TERMINAL_WAIT_PHASES } from "./src/types.mjs";
48
+ export { cancellationCredential } from "./src/task-cancellation.mjs";
49
+ export { StoreError, isStoreError } from "./src/errors.mjs";
50
+ export { openStore, ownerDiff } from "./src/store.mjs";
@@ -0,0 +1,160 @@
1
+ // Generated canonical coordinator. Do not edit directly.
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { StoreError } from "./errors.mjs";
4
+ import { columnText, getRow, getRows, run } from "./sqlite.mjs";
5
+ import { requireWait, readPins } from "./rows.mjs";
6
+ import { releaseGenerationPins, voidGenerationOutbox } from "./outbox.mjs";
7
+ import { normalizeOwner, requireId, requireText, sameOwner, requireCounter, requireEnum } from "./validate.mjs";
8
+ export function registerAssignment(ctx, input) {
9
+ const id = requireId("assignmentId", input.assignmentId);
10
+ const owner = normalizeOwner("owner", input.owner);
11
+ const recipient = normalizeOwner("recipient", input.recipient);
12
+ if (owner.kind !== "worker-conversation" || recipient.kind !== "parent-session")
13
+ throw new StoreError("foreign-owner", "Assignment needs a worker and recorded parent.");
14
+ ctx.transaction(() => {
15
+ const existing = getRow(ctx, "SELECT * FROM assignment_bindings WHERE assignment_id = ?", id);
16
+ if (existing) {
17
+ if (!sameOwner(JSON.parse(columnText(existing, "owner_json")), owner) || !sameOwner(JSON.parse(columnText(existing, "recipient_json")), recipient))
18
+ throw new StoreError("foreign-owner", "Assignment ownership and recipient are immutable.");
19
+ }
20
+ else {
21
+ run(ctx, "INSERT INTO assignment_bindings VALUES (?, ?, ?)", id, JSON.stringify(owner), JSON.stringify(recipient));
22
+ }
23
+ if (input.attemptId) {
24
+ const attemptId = requireId("attemptId", input.attemptId);
25
+ const attempt = getRow(ctx, "SELECT assignment_id FROM assignment_attempts WHERE attempt_id = ?", attemptId);
26
+ if (attempt && attempt.assignment_id !== id)
27
+ throw new StoreError("foreign-owner", "Attempt belongs to another assignment.");
28
+ if (!attempt && getAssignmentOutcome(ctx, id))
29
+ throw new StoreError("validation", "A terminal assignment cannot admit a new attempt.");
30
+ run(ctx, "INSERT OR IGNORE INTO assignment_attempts VALUES (?, ?)", attemptId, id);
31
+ }
32
+ });
33
+ }
34
+ export function getAssignmentOutcome(ctx, assignmentId) {
35
+ const row = getRow(ctx, "SELECT record_json FROM assignment_outcomes WHERE assignment_id = ?", requireId("assignmentId", assignmentId));
36
+ return row ? JSON.parse(columnText(row, "record_json")) : null;
37
+ }
38
+ function save(ctx, record) {
39
+ run(ctx, "UPDATE assignment_outcomes SET record_json = ? WHERE assignment_id = ?", JSON.stringify(record), record.assignmentId);
40
+ }
41
+ export function recordAssignmentOutcome(ctx, input) {
42
+ const assignmentId = requireId("assignmentId", input.assignmentId);
43
+ const owner = normalizeOwner("owner", input.owner);
44
+ const recipient = normalizeOwner("recipient", input.recipient);
45
+ if (owner.kind !== "worker-conversation" || recipient.kind !== "parent-session") {
46
+ throw new StoreError("foreign-owner", "An assignment outcome needs its worker and recorded parent in the same workspace.");
47
+ }
48
+ const revision = requireCounter("revision", input.revision);
49
+ if (revision < 1)
50
+ throw new StoreError("validation", "Outcome revision must be positive.");
51
+ const outcome = requireEnum("outcome", input.outcome, ["succeeded", "failed", "cancelled"]);
52
+ const reason = requireText("reason", input.reason, 8192);
53
+ if (typeof input.processUncertain !== "boolean" || !Array.isArray(input.evidence) || input.evidence.length > 100
54
+ || !Array.isArray(input.waits) || input.waits.length > 100)
55
+ throw new StoreError("validation", "Invalid outcome evidence or wait bounds.");
56
+ const evidence = input.evidence.map((e) => ({
57
+ kind: requireEnum("evidence.kind", e.kind, ["terminal-record", "log", "summary", "artifact"]),
58
+ ref: requireText("evidence.ref", e.ref, 1024),
59
+ ...(e.summary === undefined ? {} : { summary: requireText("evidence.summary", e.summary, 2048) }),
60
+ detailLost: e.detailLost === true,
61
+ ...(e.bytes === undefined ? {} : { bytes: requireCounter("evidence.bytes", e.bytes) }),
62
+ }));
63
+ const waits = input.waits.map((w) => ({ waitId: requireId("waitId", w.waitId), generation: requireCounter("generation", w.generation), cancelEpoch: requireCounter("cancelEpoch", w.cancelEpoch) }));
64
+ const normalized = { assignmentId, owner, recipient, revision, outcome, reason, evidence, waits, processUncertain: input.processUncertain };
65
+ return ctx.transaction(() => {
66
+ const binding = getRow(ctx, "SELECT * FROM assignment_bindings WHERE assignment_id = ?", assignmentId);
67
+ if (!binding || !sameOwner(JSON.parse(columnText(binding, "owner_json")), owner)
68
+ || !sameOwner(JSON.parse(columnText(binding, "recipient_json")), recipient))
69
+ throw new StoreError("foreign-owner", "Outcome must match the assignment's captured worker and recipient.");
70
+ const existing = getAssignmentOutcome(ctx, assignmentId);
71
+ if (existing) {
72
+ const { eventId: _event, inspectedAt: _read, disposition: _disposition, deliveryReceipt: _receipt, ...decision } = existing;
73
+ if (JSON.stringify(decision) !== JSON.stringify(normalized))
74
+ throw new StoreError("validation", "A terminal assignment cannot be rewritten or reopened.");
75
+ return existing;
76
+ }
77
+ const linked = waits.map((ref) => {
78
+ const wait = requireWait(ctx, ref.waitId, ref.generation);
79
+ if (!sameOwner(wait.owner, owner) || wait.origin?.assignmentRef !== assignmentId || wait.cancelEpoch !== ref.cancelEpoch) {
80
+ throw new StoreError("foreign-owner", "Outcome wait relationship or cancellation epoch does not match the assignment.");
81
+ }
82
+ if (outcome === "succeeded" && wait.acknowledgement === null)
83
+ throw new StoreError("wait-phase", "Success requires dependency interpretation.");
84
+ return wait;
85
+ });
86
+ // Reject omission of a known assignment wait: every dispatch path must close.
87
+ for (const row of getRows(ctx, "SELECT wait_id, generation FROM waits WHERE owner_kind = ? AND owner_session_id = ? AND owner_workspace = ? AND json_extract(origin_json, '$.assignmentRef') = ?", owner.kind, owner.sessionId, owner.workspace, assignmentId)) {
88
+ if (!waits.some((w) => w.waitId === row.wait_id && w.generation === row.generation))
89
+ throw new StoreError("validation", "Outcome omitted an assignment wait.");
90
+ }
91
+ const eventId = `assignment_${createHash("sha256").update(assignmentId).digest("hex")}`;
92
+ const record = { ...normalized, eventId, inspectedAt: null, disposition: null, deliveryReceipt: null };
93
+ const at = ctx.now();
94
+ run(ctx, "INSERT INTO assignment_outcomes VALUES (?, ?, ?)", assignmentId, eventId, JSON.stringify(record));
95
+ const retained = evidence.map((e) => ({ ...e, operationId: assignmentId, terminalRevision: revision }));
96
+ for (const wait of linked) {
97
+ run(ctx, "INSERT INTO assignment_outcome_waits VALUES (?, ?, ?)", assignmentId, wait.waitId, wait.generation);
98
+ retained.push(...readPins(ctx, wait.waitId, wait.generation, false).map((pin) => ({ operationId: pin.operationId, terminalRevision: pin.terminalRevision, kind: pin.kind, ref: pin.ref, summary: pin.summary ?? undefined, detailLost: pin.detailLost, bytes: pin.bytes ?? undefined })));
99
+ releaseGenerationPins(ctx, wait.waitId, wait.generation, `transferred:${eventId}`, at);
100
+ voidGenerationOutbox(ctx, wait.waitId, wait.generation, "assignment-terminal", at);
101
+ if (!["consumed", "cancelled"].includes(wait.phase)) {
102
+ run(ctx, "UPDATE waits SET dispatch_disarmed = 1, phase = 'held', phase_reason = ?, updated_at = ? WHERE wait_id = ? AND generation = ?", `assignment-terminal:${outcome}`, at, wait.waitId, wait.generation);
103
+ }
104
+ // A published claim may still own a writer. Keep its lease and launch identity.
105
+ run(ctx, "UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = 'assignment-terminal' WHERE wait_id = ? AND generation = ? AND state = 'claimed'", at, wait.waitId, wait.generation);
106
+ }
107
+ for (const e of retained)
108
+ run(ctx, `INSERT OR IGNORE INTO evidence_pins (pin_id, wait_id, generation, operation_id, terminal_revision, kind, ref, summary, detail_lost, bytes, pinned_at) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)`, `pin_${randomUUID()}`, eventId, e.operationId, e.terminalRevision, e.kind, e.ref, e.summary ?? null, e.detailLost ? 1 : 0, e.bytes ?? null, at);
109
+ run(ctx, `INSERT INTO outbox_events (event_id, event_type, operation_id, terminal_revision, wait_id, generation, recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id, state, created_at) VALUES (?, 'assignment-outcome', ?, ?, ?, 1, ?, ?, ?, ?, ?, 'pending', ?)`, eventId, assignmentId, revision, eventId, recipient.kind, recipient.sessionId, recipient.workspace, recipient.branchId ?? null, recipient.goalId ?? null, at);
110
+ return record;
111
+ });
112
+ }
113
+ export function inspectAssignmentOutcome(ctx, input) {
114
+ return ctx.transaction(() => {
115
+ const record = requireRecipient(ctx, input);
116
+ record.inspectedAt ??= ctx.now();
117
+ save(ctx, record);
118
+ return record;
119
+ });
120
+ }
121
+ /** Call after reconciling the stable event ID with the recipient's durable transcript. */
122
+ export function receiptAssignmentOutcome(ctx, input) {
123
+ const entryId = requireId("entryId", input.entryId);
124
+ return ctx.transaction(() => {
125
+ const record = requireRecipient(ctx, input);
126
+ if (record.deliveryReceipt)
127
+ return record;
128
+ record.deliveryReceipt = { entryId, at: ctx.now() };
129
+ save(ctx, record);
130
+ run(ctx, "UPDATE outbox_events SET state = CASE WHEN state = 'acknowledged' THEN state ELSE 'delivered' END, delivered_at = ?, dispatch_claim_json = NULL WHERE event_id = ?", ctx.now(), record.eventId);
131
+ return record;
132
+ });
133
+ }
134
+ function requireRecipient(ctx, input) {
135
+ const record = getAssignmentOutcome(ctx, input.assignmentId);
136
+ if (!record || !sameOwner(record.recipient, normalizeOwner("recipient", input.recipient)))
137
+ throw new StoreError("foreign-owner", "Outcome belongs to a different parent.");
138
+ if (record.revision !== input.revision)
139
+ throw new StoreError("stale-evidence", "Outcome revision does not match.");
140
+ return record;
141
+ }
142
+ export function consumeAssignmentOutcome(ctx, input) {
143
+ const kind = requireEnum("disposition", input.disposition, ["consumed", "dismissed"]);
144
+ const note = requireText("note", input.note, 8192);
145
+ return ctx.transaction(() => {
146
+ const record = requireRecipient(ctx, input);
147
+ if (record.inspectedAt === null)
148
+ throw new StoreError("stale-evidence", "Inspect the exact outcome before disposing it.");
149
+ if (record.disposition) {
150
+ if (record.disposition.kind !== kind || record.disposition.note !== note)
151
+ throw new StoreError("validation", "Outcome disposition already recorded.");
152
+ return record;
153
+ }
154
+ record.disposition = { kind, note, at: ctx.now() };
155
+ save(ctx, record);
156
+ releaseGenerationPins(ctx, record.eventId, 1, `outcome-${kind}`, ctx.now());
157
+ run(ctx, "UPDATE outbox_events SET state = 'acknowledged', acknowledged_at = ?, dispatch_claim_json = NULL WHERE event_id = ?", ctx.now(), record.eventId);
158
+ return record;
159
+ });
160
+ }
@@ -0,0 +1,94 @@
1
+ // Generated canonical coordinator. Do not edit directly.
2
+ /**
3
+ * Cross-process discovery coordination.
4
+ *
5
+ * Per-operation `supervision` authority decides who may inspect an operation.
6
+ * A separate discovery claim decides which process pays for the global running
7
+ * scan and sidecar directory walk. Followers read only their indexed assigned
8
+ * operations and cheap change-notification state.
9
+ *
10
+ * The claim is not a lease with elapsed-time expiry: replacement is proven by
11
+ * process identity or an exact-token release. Acquisition is compare-and-swap
12
+ * against the observed claim, so simultaneous contenders cannot both scan.
13
+ */
14
+ import { StoreError } from "./errors.mjs";
15
+ import { columnNumber, columnText, getRow, run, } from "./sqlite.mjs";
16
+ import { requireId } from "./validate.mjs";
17
+ const CHANGE_REVISION_KEY = "change_revision";
18
+ const DISCOVERY_TOKEN_LIMIT = 200;
19
+ function mapClaim(row) {
20
+ return {
21
+ scope: columnText(row, "scope"),
22
+ hostId: columnText(row, "host_id"),
23
+ token: columnText(row, "token"),
24
+ claimedAt: columnNumber(row, "claimed_at"),
25
+ updatedAt: columnNumber(row, "updated_at"),
26
+ };
27
+ }
28
+ function readClaim(ctx, scope) {
29
+ const row = getRow(ctx, "SELECT * FROM discovery_claims WHERE scope = ?", scope);
30
+ return row ? mapClaim(row) : null;
31
+ }
32
+ export function readDiscoveryClaim(ctx, scope) {
33
+ return readClaim(ctx, requireId("scope", scope));
34
+ }
35
+ /** Read scope transfer and its discovery claim from one SQLite snapshot. */
36
+ export function readDiscoveryState(ctx, scope) {
37
+ scope = requireId("scope", scope);
38
+ const row = getRow(ctx, `SELECT d.*, EXISTS(SELECT 1 FROM coordinator_state WHERE key = ?) AS managed
39
+ FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope, scope);
40
+ return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row) };
41
+ }
42
+ export function tryClaimDiscovery(ctx, input) {
43
+ const scope = requireId("scope", input.scope);
44
+ const hostId = requireId("hostId", input.hostId);
45
+ const token = requireId("token", input.token);
46
+ if (token.length > DISCOVERY_TOKEN_LIMIT) {
47
+ throw new StoreError("validation", `Invalid token: must be at most ${DISCOVERY_TOKEN_LIMIT} characters`);
48
+ }
49
+ const expectedHostId = input.expected === null ? null : requireId("expected.hostId", input.expected.hostId);
50
+ const expectedToken = input.expected === null ? null : requireId("expected.token", input.expected.token);
51
+ return ctx.transaction(() => {
52
+ if (getRow(ctx, "SELECT value FROM coordinator_state WHERE key = ?", "result-scope-v1:" + scope))
53
+ return null;
54
+ const current = readClaim(ctx, scope);
55
+ if (input.expected === null) {
56
+ if (current)
57
+ return null;
58
+ }
59
+ else if (!current || current.hostId !== expectedHostId || current.token !== expectedToken) {
60
+ return null;
61
+ }
62
+ const at = ctx.now();
63
+ run(ctx, `INSERT INTO discovery_claims (scope, host_id, token, claimed_at, updated_at)
64
+ VALUES (?, ?, ?, ?, ?)
65
+ ON CONFLICT(scope) DO UPDATE SET
66
+ host_id = excluded.host_id,
67
+ token = excluded.token,
68
+ claimed_at = excluded.claimed_at,
69
+ updated_at = excluded.updated_at`, scope, hostId, token, at, at);
70
+ return readClaim(ctx, scope);
71
+ });
72
+ }
73
+ export function releaseDiscoveryClaim(ctx, input) {
74
+ const scope = requireId("scope", input.scope);
75
+ const hostId = requireId("hostId", input.hostId);
76
+ const token = requireId("token", input.token);
77
+ return ctx.transaction(() => run(ctx, "DELETE FROM discovery_claims WHERE scope = ? AND host_id = ? AND token = ?", scope, hostId, token) > 0);
78
+ }
79
+ /** Monotonic revision for registration, authority changes and terminal publication. */
80
+ export function getChangeRevision(ctx) {
81
+ const row = getRow(ctx, "SELECT value FROM coordinator_state WHERE key = ?", CHANGE_REVISION_KEY);
82
+ if (!row)
83
+ return 0;
84
+ const revision = Number(columnText(row, "value"));
85
+ if (!Number.isSafeInteger(revision) || revision < 0) {
86
+ throw new StoreError("store-corruption", "The coordinator change revision is not a non-negative integer.");
87
+ }
88
+ return revision;
89
+ }
90
+ /** Called only inside an existing store transaction. */
91
+ export function bumpChangeRevision(ctx) {
92
+ run(ctx, `INSERT INTO coordinator_state (key, value) VALUES (?, '1')
93
+ ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(value AS INTEGER) + 1 AS TEXT)`, CHANGE_REVISION_KEY);
94
+ }
@@ -0,0 +1,12 @@
1
+ // Generated canonical coordinator. Do not edit directly.
2
+ export class StoreError extends Error {
3
+ code;
4
+ constructor(code, message) {
5
+ super(message);
6
+ this.name = "StoreError";
7
+ this.code = code;
8
+ }
9
+ }
10
+ export function isStoreError(error) {
11
+ return error instanceof StoreError;
12
+ }