pi-better-server 0.3.0 → 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 (47) hide show
  1. package/package.json +4 -1
  2. package/scripts/measure-shared-reads.mjs +25 -5
  3. package/scripts/test-on-pi.sh +3 -2
  4. package/src/daemon-owner.ts +2 -1
  5. package/src/handshake.ts +1 -1
  6. package/src/protocol.ts +2 -0
  7. package/src/runtime/background.ts +12 -3
  8. package/src/runtime/cancellation.ts +10 -6
  9. package/src/runtime/catalog-admission.ts +50 -0
  10. package/src/runtime/catalog.ts +133 -0
  11. package/src/runtime/domain/assignment-observation.d.mts +1 -1
  12. package/src/runtime/domain/assignment-observation.mjs +18 -1
  13. package/src/runtime/domain/catalog/agent-session-settings.d.mts +30 -0
  14. package/src/runtime/domain/catalog/agent-session-settings.mjs +112 -0
  15. package/src/runtime/domain/catalog/catalog-overlay.d.mts +3 -0
  16. package/src/runtime/domain/catalog/catalog-overlay.mjs +9 -0
  17. package/src/runtime/domain/catalog/catalog-preferences.d.mts +17 -0
  18. package/src/runtime/domain/catalog/catalog-preferences.mjs +164 -0
  19. package/src/runtime/domain/catalog/catalog-schema.d.mts +265 -0
  20. package/src/runtime/domain/catalog/catalog-schema.mjs +1331 -0
  21. package/src/runtime/domain/catalog/catalog-skill-edits.d.mts +42 -0
  22. package/src/runtime/domain/catalog/catalog-skill-edits.mjs +95 -0
  23. package/src/runtime/domain/catalog/catalog-store.d.mts +126 -0
  24. package/src/runtime/domain/catalog/catalog-store.mjs +810 -0
  25. package/src/runtime/domain/catalog/roles/role.architect.md +13 -0
  26. package/src/runtime/domain/catalog/roles/role.developer.md +16 -0
  27. package/src/runtime/domain/catalog/roles/role.explorer.md +13 -0
  28. package/src/runtime/domain/catalog/roles/role.product-manager.md +13 -0
  29. package/src/runtime/domain/catalog/roles/role.researcher.md +13 -0
  30. package/src/runtime/domain/catalog/roles/role.reviewer.md +13 -0
  31. package/src/runtime/domain/catalog/roles/role.writer.md +12 -0
  32. package/src/runtime/domain/catalog/thinking.d.mts +8 -0
  33. package/src/runtime/domain/catalog/thinking.mjs +22 -0
  34. package/src/runtime/domain/coordinator/src/discovery.mjs +9 -0
  35. package/src/runtime/domain/coordinator/src/operations.mjs +5 -3
  36. package/src/runtime/domain/coordinator/src/result-supervision.mjs +101 -0
  37. package/src/runtime/domain/coordinator/src/schema.mjs +17 -1
  38. package/src/runtime/domain/coordinator/src/store.mjs +11 -1
  39. package/src/runtime/mutation-store.ts +34 -0
  40. package/src/runtime/query-executor.ts +58 -9
  41. package/src/runtime/query-worker.mjs +3 -2
  42. package/src/runtime/read-model.ts +111 -59
  43. package/src/runtime/result-supervision.ts +63 -0
  44. package/src/runtime/work-client.d.mts +1 -0
  45. package/src/runtime/work-client.mjs +16 -2
  46. package/src/server.ts +66 -5
  47. package/src/version.ts +1 -1
@@ -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
+ }
@@ -32,6 +32,13 @@ function readClaim(ctx, scope) {
32
32
  export function readDiscoveryClaim(ctx, scope) {
33
33
  return readClaim(ctx, requireId("scope", scope));
34
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
+ }
35
42
  export function tryClaimDiscovery(ctx, input) {
36
43
  const scope = requireId("scope", input.scope);
37
44
  const hostId = requireId("hostId", input.hostId);
@@ -42,6 +49,8 @@ export function tryClaimDiscovery(ctx, input) {
42
49
  const expectedHostId = input.expected === null ? null : requireId("expected.hostId", input.expected.hostId);
43
50
  const expectedToken = input.expected === null ? null : requireId("expected.token", input.expected.token);
44
51
  return ctx.transaction(() => {
52
+ if (getRow(ctx, "SELECT value FROM coordinator_state WHERE key = ?", "result-scope-v1:" + scope))
53
+ return null;
45
54
  const current = readClaim(ctx, scope);
46
55
  if (input.expected === null) {
47
56
  if (current)
@@ -29,6 +29,8 @@ function normalizeSupervision(value) {
29
29
  const supervision = value;
30
30
  return {
31
31
  hostId: requireId("supervision.hostId", supervision.hostId),
32
+ ...(supervision.resultScope === undefined ? {} : { resultScope: requireId("supervision.resultScope", supervision.resultScope) }),
33
+ ...(supervision.resultAdapter === 1 ? { resultAdapter: 1 } : {}),
32
34
  runnerId: supervision.runnerId === undefined || supervision.runnerId === null
33
35
  ? null
34
36
  : requireId("supervision.runnerId", supervision.runnerId),
@@ -287,12 +289,12 @@ export function listOperations(ctx, filter = {}) {
287
289
  params.push(requireId("taskId", filter.taskId));
288
290
  }
289
291
  const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
290
- return getRows(ctx, `SELECT * FROM operations ${where} ORDER BY created_at, operation_id`, ...params)
291
- .map(mapOperation);
292
+ return getRows(ctx, `SELECT *, EXISTS(SELECT 1 FROM coordinator_state s WHERE s.key = 'result-supervision-v1:' || operations.operation_id) AS result_managed FROM operations ${where} ORDER BY created_at, operation_id`, ...params)
293
+ .map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
292
294
  }
293
295
  /** Running operations assigned to one supervising host, using the phase/host index. */
294
296
  export function listRunningSupervisedBy(ctx, hostId) {
295
- return getRows(ctx, "SELECT * FROM operations WHERE phase = 'running' AND supervision_host_id = ? ORDER BY created_at, operation_id", requireId("hostId", hostId)).map(mapOperation);
297
+ return getRows(ctx, "SELECT *, EXISTS(SELECT 1 FROM coordinator_state s WHERE s.key = 'result-supervision-v1:' || operations.operation_id) AS result_managed FROM operations WHERE phase = 'running' AND supervision_host_id = ? ORDER BY created_at, operation_id", requireId("hostId", hostId)).map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
296
298
  }
297
299
  function listOutboxForRevision(ctx, operationId, terminalRevision) {
298
300
  return getRows(ctx, "SELECT * FROM outbox_events WHERE operation_id = ? AND terminal_revision = ? ORDER BY created_at, event_id", operationId, terminalRevision).map((row) => mapOutbox(ctx, row));
@@ -0,0 +1,101 @@
1
+ // Generated canonical coordinator. Do not edit directly.
2
+ import { isDeepStrictEqual } from "node:util";
3
+ import { getRow, run } from "./sqlite.mjs";
4
+ import { getOperation, recordSupervision, recordTerminalOutcome } from "./operations.mjs";
5
+ import { requireId, requirePath } from "./validate.mjs";
6
+ const PREFIX = "result-supervision-v1:";
7
+ export function resultSupervisions(ctx, activeOnly = false) {
8
+ const rows = activeOnly
9
+ ? ctx.db.prepare("SELECT s.value FROM operations o JOIN coordinator_state s ON s.key = ? || o.operation_id WHERE o.phase = 'running'").all(PREFIX)
10
+ : ctx.db.prepare("SELECT value FROM coordinator_state WHERE key LIKE ?").all(`${PREFIX}%`);
11
+ return rows
12
+ .map(row => JSON.parse(String(row.value)));
13
+ }
14
+ export function resultSupervision(ctx, operationId) {
15
+ const row = getRow(ctx, "SELECT value FROM coordinator_state WHERE key = ?", PREFIX + requireId("operationId", operationId));
16
+ return row ? JSON.parse(String(row.value)) : null;
17
+ }
18
+ /** The admitting host has stopped its local route before this exact-owner CAS. */
19
+ export function handoffResultSupervision(ctx, input) {
20
+ const operationId = requireId("operationId", input.operationId);
21
+ const hostId = requireId("hostId", input.hostId);
22
+ const epoch = requireId("epoch", input.epoch);
23
+ const directory = requirePath("directory", input.directory);
24
+ return ctx.transaction(() => {
25
+ const previous = resultSupervision(ctx, operationId);
26
+ if (previous) {
27
+ if (previous.directory !== directory || previous.hostId !== hostId || previous.epoch !== epoch
28
+ || !isDeepStrictEqual(previous.capability, input.capability)) {
29
+ throw new Error("supervision-conflict: repeated handoff changed destination or captured authority");
30
+ }
31
+ return previous;
32
+ }
33
+ const operation = getOperation(ctx, operationId);
34
+ if (!operation || operation.supervision?.hostId !== input.expectedHostId)
35
+ throw new Error("permission-unavailable: exact supervision owner changed");
36
+ const grant = { operationId, directory, hostId, epoch, launchToken: operation.launchToken,
37
+ authorityRef: operation.authorityRef, owner: operation.owner, ...(input.capability ? { capability: input.capability } : {}) };
38
+ recordSupervision(ctx, { operationId, owner: operation.owner, expectedHostId: input.expectedHostId,
39
+ supervision: { hostId }, health: "active" });
40
+ run(ctx, "INSERT INTO coordinator_state (key, value) VALUES (?, ?)", PREFIX + operationId, JSON.stringify(grant));
41
+ return grant;
42
+ });
43
+ }
44
+ /** A wait's dependency set transfers together, or none of it does. */
45
+ export function handoffResultSupervisions(ctx, inputs) {
46
+ return ctx.transaction(() => inputs.map(input => handoffResultSupervision(ctx, input)));
47
+ }
48
+ export function resultScopeManaged(ctx, scope) {
49
+ return !!getRow(ctx, "SELECT value FROM coordinator_state WHERE key = ?", "result-scope-v1:" + requireId("scope", scope));
50
+ }
51
+ export function handoffResultScope(ctx, input) {
52
+ return ctx.transaction(() => {
53
+ const claim = getRow(ctx, "SELECT host_id, token FROM discovery_claims WHERE scope = ?", requireId("scope", input.scope));
54
+ if (claim ? !input.expectedDiscovery || claim.host_id !== input.expectedDiscovery.hostId || claim.token !== input.expectedDiscovery.token : input.expectedDiscovery !== null) {
55
+ throw new Error("supervision-conflict: discovery owner changed during handoff");
56
+ }
57
+ const grants = handoffResultSupervisions(ctx, input.grants);
58
+ // Registration precedes sidecar creation. Check durable records inside
59
+ // this transaction, including old records whose scope is unknown.
60
+ const stranded = getRow(ctx, `SELECT operation_id FROM operations o
61
+ WHERE phase = 'running' AND observer_kind = 'local-supervisor'
62
+ AND COALESCE(json_extract(supervision_json, '$.resultAdapter'), 0) != 1
63
+ AND (json_extract(supervision_json, '$.resultScope') IS NULL
64
+ OR json_extract(supervision_json, '$.resultScope') = ?)
65
+ AND NOT EXISTS (SELECT 1 FROM coordinator_state s WHERE s.key = ? || o.operation_id)
66
+ LIMIT 1`, input.scope, PREFIX);
67
+ if (stranded)
68
+ throw new Error("permission-unavailable: untransferred legacy operation prevents scope handoff");
69
+ run(ctx, "DELETE FROM discovery_claims WHERE scope = ?", input.scope);
70
+ run(ctx, "INSERT OR IGNORE INTO coordinator_state (key, value) VALUES (?, 'managed')", "result-scope-v1:" + input.scope);
71
+ return grants;
72
+ });
73
+ }
74
+ /** Called by the singleton server after proving the preceding server has exited. */
75
+ export function recoverResultSupervision(ctx, input) {
76
+ ctx.transaction(() => {
77
+ const previous = resultSupervision(ctx, input.operationId);
78
+ if (!previous || previous.launchToken !== input.launchToken || previous.directory !== input.directory
79
+ || previous.authorityRef !== input.authorityRef || JSON.stringify(previous.owner) !== JSON.stringify(input.owner)
80
+ || JSON.stringify(previous.capability) !== JSON.stringify(input.capability)) {
81
+ throw new Error("supervision-conflict: execution or captured authority changed");
82
+ }
83
+ const operation = getOperation(ctx, input.operationId);
84
+ if (operation.terminalRevision > 0)
85
+ return;
86
+ recordSupervision(ctx, { operationId: input.operationId, owner: operation.owner,
87
+ expectedHostId: previous.hostId, supervision: { hostId: input.hostId }, health: "active" });
88
+ run(ctx, "UPDATE coordinator_state SET value = ? WHERE key = ?", JSON.stringify(input), PREFIX + input.operationId);
89
+ });
90
+ }
91
+ export function publishSupervisedResult(ctx, input) {
92
+ return ctx.transaction(() => {
93
+ const grant = resultSupervision(ctx, input.operationId);
94
+ const operation = getOperation(ctx, input.operationId);
95
+ if (!grant || grant.epoch !== input.epoch || operation?.supervision?.hostId !== grant.hostId
96
+ || operation.launchToken !== grant.launchToken || input.publication.operationId !== input.operationId) {
97
+ throw new Error("stale-runtime-epoch: result supervision changed");
98
+ }
99
+ return recordTerminalOutcome(ctx, input.publication);
100
+ });
101
+ }
@@ -17,6 +17,17 @@
17
17
  import { SCHEMA_VERSION } from "./types.mjs";
18
18
  import { StoreError } from "./errors.mjs";
19
19
  import { columnText, getRow, getRows, run } from "./sqlite.mjs";
20
+ // Enforce the handoff even for an older process still using its bundled store.
21
+ // Unknown legacy scopes conservatively conflict with any managed root scope.
22
+ const RESULT_ADMISSION_FENCE = `CREATE TRIGGER IF NOT EXISTS result_scope_admission_v1
23
+ BEFORE INSERT ON operations
24
+ WHEN NEW.observer_kind = 'local-supervisor'
25
+ AND COALESCE(json_extract(NEW.supervision_json, '$.resultAdapter'), 0) != 1
26
+ AND EXISTS (SELECT 1 FROM coordinator_state
27
+ WHERE key LIKE 'result-scope-v1:%'
28
+ AND (json_extract(NEW.supervision_json, '$.resultScope') IS NULL
29
+ OR key = 'result-scope-v1:' || json_extract(NEW.supervision_json, '$.resultScope')))
30
+ BEGIN SELECT RAISE(ABORT, 'permission-unavailable: legacy launch into managed result scope'); END`;
20
31
  const DDL = [
21
32
  `CREATE TABLE task_cancellation_authorities (
22
33
  credential_hash TEXT PRIMARY KEY,
@@ -237,6 +248,7 @@ const DDL = [
237
248
  generation INTEGER NOT NULL,
238
249
  PRIMARY KEY (wait_id, generation)
239
250
  )`,
251
+ RESULT_ADMISSION_FENCE,
240
252
  ];
241
253
  const SCHEMA_VERSION_KEY = "schema_version";
242
254
  function existingTables(ctx) {
@@ -275,6 +287,7 @@ export function ensureSchema(ctx) {
275
287
  if (recorded < SCHEMA_VERSION) {
276
288
  if (recorded === 3) {
277
289
  ctx.transaction(() => {
290
+ ensureAdditiveSchema(ctx);
278
291
  ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE assignment_repairs")));
279
292
  run(ctx, "UPDATE schema_meta SET value = ? WHERE key = ?", String(SCHEMA_VERSION), SCHEMA_VERSION_KEY);
280
293
  });
@@ -315,8 +328,10 @@ function ensureAdditiveSchema(ctx) {
315
328
  && hasTable("coordinator_state")
316
329
  && hasTable("task_cancellation_requests")
317
330
  && hasTable("task_cancellation_authorities")
318
- && getRows(ctx, "PRAGMA table_info(task_cancellation_requests)").some(row => row.name === "result_json"))
331
+ && getRows(ctx, "PRAGMA table_info(task_cancellation_requests)").some(row => row.name === "result_json")) {
332
+ ctx.db.exec(RESULT_ADMISSION_FENCE);
319
333
  return;
334
+ }
320
335
  ctx.transaction(() => {
321
336
  ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE task_cancellation_requests")).replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS"));
322
337
  if (!getRows(ctx, "PRAGMA table_info(task_cancellation_requests)").some(row => row.name === "result_json"))
@@ -342,6 +357,7 @@ function ensureAdditiveSchema(ctx) {
342
357
  key TEXT PRIMARY KEY,
343
358
  value TEXT NOT NULL
344
359
  )`);
360
+ ctx.db.exec(RESULT_ADMISSION_FENCE);
345
361
  });
346
362
  }
347
363
  /** Test and diagnostic seam: read the recorded schema version without opening a store. */
@@ -8,6 +8,7 @@
8
8
  * and leaves no partial record.
9
9
  */
10
10
  import { StoreError } from "./errors.mjs";
11
+ import { resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.mjs";
11
12
  import { acceptTaskCancellation, getTaskCancellation, recordTaskStopRequested, admitTaskCancellation, authorizedTaskCancellation, finishTaskCancellation, cancellationRuntimeEpoch, acceptAuthorizedTaskCancellation, taskCancellationManaged, pendingTaskCancellations, finishTaskCancellationIntent, unknownTaskCancellation } from "./task-cancellation.mjs";
12
13
  import { repairFailedResume } from "./recovery.mjs";
13
14
  import { recordAssignmentOutcome, getAssignmentOutcome, inspectAssignmentOutcome, consumeAssignmentOutcome, registerAssignment, receiptAssignmentOutcome } from "./assignment-outcomes.mjs";
@@ -15,7 +16,7 @@ import { describeOwnerDiff, normalizeOwner, requireCounter, requireId, requirePa
15
16
  import { ensureSchema } from "./schema.mjs";
16
17
  import { createContext, openDatabase } from "./sqlite.mjs";
17
18
  import { getOperation as readOperationRecord, listOperations as readOperationRecords, listRunningSupervisedBy as readRunningSupervisedBy, releaseSupervision as writeSupervisionRelease, recordSupervision as writeSupervision, recordTerminalOutcome as writeTerminalOutcome, registerOperation as writeOperation, } from "./operations.mjs";
18
- import { getChangeRevision as readChangeRevision, readDiscoveryClaim as readClaim, releaseDiscoveryClaim as deleteDiscoveryClaim, tryClaimDiscovery as writeDiscoveryClaim, } from "./discovery.mjs";
19
+ import { getChangeRevision as readChangeRevision, readDiscoveryClaim as readClaim, readDiscoveryState, releaseDiscoveryClaim as deleteDiscoveryClaim, tryClaimDiscovery as writeDiscoveryClaim, } from "./discovery.mjs";
19
20
  import { acknowledgeResult as writeAcknowledgement, cancelWait as writeCancellation, claimResume as writeClaim, findPendingWaitForOwner, getWait as readWait, listDependencies as readDependencies, listEvidencePins as readPins, listEvidenceReads as readReads, listResumeClaims as readClaims, listUnreconciledClaims, listWaits as readWaits, publishResumeAttempt as writeAttemptPublication, recordEvidencePin as writePin, recordEvidenceRead as writeRead, registerWait as writeWait, releaseEvidencePins as writePinRelease, holdFailedResume as writeHoldFailedResume, releaseResumeClaim as writeClaimRelease, transitionWaitPhase as writePhase, } from "./waits.mjs";
20
21
  import { claimOutbox as writeOutboxClaim, listDispatchableOutboxRecipients as readDispatchableOutboxRecipients, listOutbox as readOutbox, markOutboxDelivered as writeOutboxDelivery, releaseOutbox as writeOutboxRelease, } from "./outbox.mjs";
21
22
  import { readOperationEvidence } from "./rows.mjs";
@@ -43,6 +44,14 @@ export function openStore(options) {
43
44
  }
44
45
  };
45
46
  const store = {
47
+ resultScopeManaged(scope) { alive(); return resultScopeManaged(ctx, scope); },
48
+ handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
49
+ resultSupervision(id) { alive(); return resultSupervision(ctx, id); },
50
+ resultSupervisions(activeOnly) { alive(); return resultSupervisions(ctx, activeOnly); },
51
+ handoffResultSupervision(input) { alive(); return handoffResultSupervision(ctx, input); },
52
+ handoffResultSupervisions(input) { alive(); return handoffResultSupervisions(ctx, input); },
53
+ recoverResultSupervision(input) { alive(); recoverResultSupervision(ctx, input); },
54
+ publishSupervisedResult(input) { alive(); return publishSupervisedResult(ctx, input); },
46
55
  unknownTaskCancellation(input) { alive(); return unknownTaskCancellation(ctx, input); },
47
56
  taskCancellationManaged(operationId) { alive(); return taskCancellationManaged(ctx, operationId); },
48
57
  pendingTaskCancellations() { alive(); return pendingTaskCancellations(ctx); },
@@ -98,6 +107,7 @@ export function openStore(options) {
98
107
  alive();
99
108
  return readOperationEvidence(ctx, requireId("operationId", operationId), terminalRevision === undefined ? undefined : requireCounter("terminalRevision", terminalRevision));
100
109
  },
110
+ readDiscoveryState(scope) { alive(); return readDiscoveryState(ctx, scope); },
101
111
  readDiscoveryClaim(scope) {
102
112
  alive();
103
113
  return readClaim(ctx, scope);
@@ -0,0 +1,34 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ // @ts-expect-error Generated canonical coordinator.
4
+ import { openStore } from "./domain/coordinator/index.mjs";
5
+
6
+ // Query workers own their read connection. All main-thread mutation services
7
+ // share this connection, keeping mutations within the root's two-connection budget.
8
+ const stores = new Map<string, { store: any; leases: number }>();
9
+
10
+ export function acquireMutationStore(root: string): { store: any; release(): void } {
11
+ const key = realpathSync(root);
12
+ let entry = stores.get(key);
13
+ if (!entry) {
14
+ entry = { store: openStore({ path: join(key, "operation-coordinator.sqlite") }), leases: 0 };
15
+ stores.set(key, entry);
16
+ }
17
+ entry.leases++;
18
+ const owned = entry;
19
+ let released = false;
20
+ return { store: owned.store, release() {
21
+ if (released) return;
22
+ released = true;
23
+ if (--owned.leases === 0) {
24
+ stores.delete(key);
25
+ owned.store.close();
26
+ }
27
+ } };
28
+ }
29
+
30
+ /** Main-thread connections only; read-worker connections are reported separately. */
31
+ export function mutationStoreMetrics(root: string): { active: number; leases: number } {
32
+ const entry = stores.get(realpathSync(root));
33
+ return { active: entry ? 1 : 0, leases: entry?.leases ?? 0 };
34
+ }
@@ -13,7 +13,7 @@ interface Query {
13
13
  }
14
14
  export type ReadStream = Pick<Duplex, "destroyed" | "writableLength" | "write" | "on" | "once" | "off">;
15
15
  interface Stream { socket: ReadStream; paused: boolean; generation: number; drain: () => void; close: () => void }
16
- interface WorkerMetrics { sqlite?: { opens: number; active: number; maximum: number }; [key: string]: unknown }
16
+ interface WorkerMetrics { inventories?: number; sqlite?: { opens: number; active: number; maximum: number }; [key: string]: unknown }
17
17
  export interface QueryExecutorOptions {
18
18
  capacity?: number; timeoutMs?: number; maxConnections?: number;
19
19
  workerUrl?: URL;
@@ -34,6 +34,10 @@ export class WorkQueryExecutor {
34
34
  private failure?: Error;
35
35
  private termination?: Promise<number>;
36
36
  private exited = false;
37
+ private closed = false;
38
+ private workerGeneration = 0;
39
+ private recoveryAttempts: number[] = [];
40
+ private recoveryTimer?: ReturnType<typeof setTimeout>;
37
41
  private workerMetrics: WorkerMetrics = {};
38
42
  private lastObservation: Omit<ReturnType<WorkReadModel["observation"]>, "observedAt"> & { observedAt: number | null } = {
39
43
  status: "rebuilding", reason: "Initial source inventory is rebuilding.", observedAt: null, reasons: [],
@@ -47,22 +51,63 @@ export class WorkQueryExecutor {
47
51
  private timeouts = 0;
48
52
  private durations: number[] = [];
49
53
  private options: QueryExecutorOptions;
54
+ private agentDir: string;
50
55
  readonly instanceId: string;
51
56
 
52
57
  constructor(agentDir: string, instanceId: string, options: QueryExecutorOptions = {}) {
53
- this.options = options; this.instanceId = instanceId;
58
+ this.options = options; this.instanceId = instanceId; this.agentDir = agentDir;
54
59
  this.lag.enable();
55
- this.worker = new Worker(options.workerUrl ?? new URL("./query-worker.mjs", import.meta.url), {
56
- execArgv: [], workerData: { agentDir, instanceId, modelOptions: options.modelOptions },
60
+ this.worker = this.startWorker();
61
+ }
62
+
63
+ private startWorker() {
64
+ const instanceId = this.workerGeneration ? `${this.instanceId}:reads:${this.workerGeneration}` : this.instanceId;
65
+ const worker = new Worker(this.options.workerUrl ?? new URL("./query-worker.mjs", import.meta.url), {
66
+ execArgv: [], workerData: { agentDir: this.agentDir, instanceId, modelOptions: this.options.modelOptions },
57
67
  });
58
- this.worker.on("message", message => this.receive(message));
59
- this.worker.on("error", error => this.fail(new Error(`runtime-unhealthy: read worker failed: ${String(error)}`)));
60
- this.worker.on("exit", code => {
68
+ worker.on("message", message => { if (worker === this.worker) this.receive(message); });
69
+ worker.on("error", error => { if (worker === this.worker) this.fail(new Error(`runtime-unhealthy: read worker failed: ${String(error)}`)); });
70
+ worker.on("exit", code => {
71
+ if (worker !== this.worker) return;
61
72
  this.exited = true;
62
73
  const sqlite = this.workerMetrics.sqlite;
63
74
  if (sqlite) this.workerMetrics = { ...this.workerMetrics, sqlite: { ...sqlite, active: 0 } };
64
- this.fail(new Error(`runtime-unhealthy: read worker exited (${code}); restart the runtime to rebuild reads`));
75
+ this.fail(new Error(`runtime-unhealthy: read worker exited (${code}); rebuilding reads after recovery`));
76
+ this.scheduleRecovery();
65
77
  });
78
+ return worker;
79
+ }
80
+
81
+ private scheduleRecovery() {
82
+ if (this.closed || !this.exited || this.recoveryTimer || !this.streams.size) return;
83
+ const now = Date.now();
84
+ this.recoveryAttempts = this.recoveryAttempts.filter(attempt => now - attempt < 60_000);
85
+ if (this.recoveryAttempts.length >= 2) {
86
+ if (!this.failure?.message.includes("recovery budget exhausted")) {
87
+ this.failure = new Error(`${this.failure?.message}; automatic read recovery budget exhausted`);
88
+ }
89
+ return;
90
+ }
91
+ this.recoveryTimer = setTimeout(() => {
92
+ this.recoveryTimer = undefined;
93
+ if (this.closed || !this.streams.size) return;
94
+ this.recoveryAttempts.push(Date.now());
95
+ this.workerGeneration++;
96
+ this.exited = false; this.failure = undefined; this.termination = undefined;
97
+ this.workerMetrics = {}; this.workerConnections.clear(); this.revision++;
98
+ this.lastObservation = { status: "rebuilding", reason: "Read worker is recovering its source inventory.", observedAt: null, reasons: [] };
99
+ this.lag.reset(); this.lag.enable();
100
+ try { this.worker = this.startWorker(); }
101
+ catch (error) {
102
+ this.exited = true; this.lag.disable();
103
+ this.failure = new Error(`runtime-unhealthy: read worker restart failed: ${String(error)}`);
104
+ this.scheduleRecovery();
105
+ return;
106
+ }
107
+ for (const connection of this.streams.keys()) this.event(connection, JSON.stringify({ type: "event",
108
+ event: { type: "resync_required", reason: "read-worker-recovered", instanceId: this.instanceId } }) + "\n");
109
+ }, 500);
110
+ this.recoveryTimer.unref();
66
111
  }
67
112
 
68
113
  connect(socket: ReadStream) {
@@ -77,6 +122,7 @@ export class WorkQueryExecutor {
77
122
  const close = () => this.detach(connection);
78
123
  this.streams.set(connection, { socket, paused: false, generation: 0, drain, close });
79
124
  socket.on("drain", drain); socket.once("close", close);
125
+ if (this.failure) this.scheduleRecovery();
80
126
  return { handle: (command: Record<string, unknown>) => this.request(connection, command), close };
81
127
  }
82
128
 
@@ -96,13 +142,14 @@ export class WorkQueryExecutor {
96
142
  capacity: this.options.capacity ?? 64, waitMs: [...this.waits], readMs: [...this.durations],
97
143
  eventLoopLagMs: { p50: this.lag.percentile(50) / 1e6, p95: this.lag.percentile(95) / 1e6, p99: this.lag.percentile(99) / 1e6 },
98
144
  worker: this.exited ? "stopped" : this.failure ? "stopping" : "running",
145
+ restarts: this.workerGeneration, recoveryPending: !!this.recoveryTimer,
99
146
  status: this.failure ? "degraded" : "ready" } };
100
147
  }
101
148
 
102
149
  private request(connection: number, input: Record<string, unknown>): Promise<EncodedRead> {
103
150
  if (connection !== 0 && !this.streams.has(connection)) return Promise.reject(new Error("runtime-unavailable: client disconnected"));
104
151
  if (input.type === "runtime_get_metrics") return Promise.resolve({ json: JSON.stringify(this.metrics()) });
105
- if (this.failure) return Promise.reject(this.failure);
152
+ if (this.failure) { this.scheduleRecovery(); return Promise.reject(this.failure); }
106
153
  if (!["runtime_get_snapshot", "runtime_subscribe", "runtime_unsubscribe", "runtime_get_liveness"].includes(String(input.type))) return Promise.reject(new Error("Unsupported read operation"));
107
154
  if (input.sinceSeq !== undefined && !Number.isSafeInteger(input.sinceSeq)) return Promise.reject(new Error("Invalid replay sequence"));
108
155
  if (input.instanceId !== undefined && (typeof input.instanceId !== "string" || input.instanceId.length > 256)) return Promise.reject(new Error("Invalid runtime instance"));
@@ -218,6 +265,8 @@ export class WorkQueryExecutor {
218
265
  }
219
266
 
220
267
  async close() {
268
+ this.closed = true;
269
+ if (this.recoveryTimer) { clearTimeout(this.recoveryTimer); this.recoveryTimer = undefined; }
221
270
  this.fail(new Error("runtime-unavailable: query executor closed"));
222
271
  for (const connection of this.streams.keys()) this.detach(connection);
223
272
  let timeout: ReturnType<typeof setTimeout> | undefined;
@@ -106,10 +106,11 @@ parentPort.on("message", async message => {
106
106
  return;
107
107
  }
108
108
  if (!["runtime_get_snapshot", "runtime_subscribe", "runtime_unsubscribe"].includes(command.type)) throw new Error("Unsupported read operation");
109
- if (command.type === "runtime_get_snapshot" && command.scope?.id) await model.ensureId(command.scope.id);
109
+ const indexed = command.type !== "runtime_get_snapshot" || !command.scope?.id || await model.ensureId(command.scope.id);
110
110
  const state = session(message.connection);
111
111
  state.generation = message.generation; state.pending = undefined;
112
- const value = state.queries.handle(command);
112
+ let value = state.queries.handle(command);
113
+ if (!indexed && !value.rows.length) value = { ...value, status: "rebuilding", reason: "The requested run is being indexed; retry after reconciliation." };
113
114
  parentPort.postMessage({ type: "reply", id: message.id, json: encoded.get(value) ?? JSON.stringify(value), metrics: metrics() });
114
115
  } catch (error) {
115
116
  parentPort.postMessage({ type: "reply", id: message.id, error: String(error).slice(0, 512), metrics: metrics() });