pi-better-server 0.2.4 → 0.3.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/package.json +3 -3
- package/scripts/measure-shared-reads/daemon.mjs +7 -0
- package/scripts/measure-shared-reads/probe.mjs +10 -0
- package/scripts/measure-shared-reads.mjs +145 -0
- package/scripts/test-on-pi.sh +19 -2
- package/src/cli.ts +39 -2
- package/src/client.ts +9 -4
- package/src/daemon-owner.ts +47 -6
- package/src/handshake.ts +8 -7
- package/src/lifecycle-config.ts +4 -0
- package/src/paths.ts +1 -11
- package/src/protocol.ts +5 -0
- package/src/registry.ts +2 -1
- package/src/runtime/background-history.ts +241 -0
- package/src/runtime/background.ts +173 -0
- package/src/runtime/cancellation.ts +95 -0
- package/src/runtime/client.ts +111 -0
- package/src/runtime/domain/assignment-observation.d.mts +1 -0
- package/src/runtime/domain/assignment-observation.mjs +103 -0
- package/src/runtime/domain/assignment-projection.d.mts +1 -0
- package/src/runtime/domain/assignment-projection.mjs +245 -0
- package/src/runtime/domain/background/conditions.mjs +93 -0
- package/src/runtime/domain/background/process-identity.mjs +110 -0
- package/src/runtime/domain/background/process.mjs +511 -0
- package/src/runtime/domain/background/registry.mjs +374 -0
- package/src/runtime/domain/background/snapshot.mjs +73 -0
- package/src/runtime/domain/background/supervisor/identity.mjs +92 -0
- package/src/runtime/domain/background/supervisor/invocation.mjs +29 -0
- package/src/runtime/domain/background/supervisor/store.mjs +604 -0
- package/src/runtime/domain/background/supervisor/supervisor.mjs +720 -0
- package/src/runtime/domain/background/supervisor/types.mjs +47 -0
- package/src/runtime/domain/background/terminal-publication.mjs +58 -0
- package/src/runtime/domain/background/types.mjs +3 -0
- package/src/runtime/domain/coordinator/index.mjs +50 -0
- package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +160 -0
- package/src/runtime/domain/coordinator/src/discovery.mjs +85 -0
- package/src/runtime/domain/coordinator/src/errors.mjs +12 -0
- package/src/runtime/domain/coordinator/src/operations.mjs +299 -0
- package/src/runtime/domain/coordinator/src/outbox.mjs +282 -0
- package/src/runtime/domain/coordinator/src/recovery.mjs +51 -0
- package/src/runtime/domain/coordinator/src/rows.mjs +277 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +351 -0
- package/src/runtime/domain/coordinator/src/sqlite.mjs +193 -0
- package/src/runtime/domain/coordinator/src/store.mjs +235 -0
- package/src/runtime/domain/coordinator/src/task-cancellation.mjs +187 -0
- package/src/runtime/domain/coordinator/src/types.mjs +24 -0
- package/src/runtime/domain/coordinator/src/validate.mjs +233 -0
- package/src/runtime/domain/coordinator/src/waits.mjs +850 -0
- package/src/runtime/domain/health-observation.d.mts +3 -0
- package/src/runtime/domain/health-observation.mjs +613 -0
- package/src/runtime/domain/health-surface.mjs +279 -0
- package/src/runtime/domain/log-cursor.mjs +148 -0
- package/src/runtime/domain/log-paths.mjs +13 -0
- package/src/runtime/domain/parse.d.mts +2 -0
- package/src/runtime/domain/parse.mjs +1173 -0
- package/src/runtime/domain/process-status.d.mts +1 -0
- package/src/runtime/domain/process-status.mjs +25 -0
- package/src/runtime/domain/session-store.d.mts +2 -0
- package/src/runtime/domain/session-store.mjs +489 -0
- package/src/runtime/domain/shared-harness-settings.d.mts +1 -0
- package/src/runtime/domain/shared-harness-settings.mjs +126 -0
- package/src/runtime/domain/shared-log-utils.mjs +1223 -0
- package/src/runtime/domain/shared-stall-detector.mjs +37 -0
- package/src/runtime/domain/widget.d.mts +1 -0
- package/src/runtime/domain/widget.mjs +250 -0
- package/src/runtime/guardian.ts +189 -0
- package/src/runtime/health-config.ts +27 -0
- package/src/runtime/local-client.ts +34 -0
- package/src/runtime/queries.ts +76 -0
- package/src/runtime/query-executor.ts +228 -0
- package/src/runtime/query-worker.mjs +118 -0
- package/src/runtime/read-model.ts +357 -0
- package/src/runtime/root.ts +29 -0
- package/src/runtime/socket.ts +10 -0
- package/src/runtime/status-cli.ts +11 -0
- package/src/runtime/work-client.d.mts +13 -0
- package/src/runtime/work-client.mjs +88 -0
- package/src/server.ts +136 -12
- package/src/session-activity.ts +22 -2
- package/src/startup/activation.ts +32 -5
- package/src/startup/ensure.ts +13 -1
- package/src/startup/install.ts +2 -0
- package/src/version.ts +4 -0
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable records and public result types for the detached local supervisor.
|
|
3
|
+
*
|
|
4
|
+
* Scope: local processes and local command watches only. The supervisor is the
|
|
5
|
+
* slice-2 runtime from [ADR 0020](../../../../docs/adr/0020-observed-waits-retain-an-owner.md)
|
|
6
|
+
* and [the observed-waits design](../../../../docs/plans/observed-waits-design.md):
|
|
7
|
+
* execution and terminal evidence survive the process that launched them. It
|
|
8
|
+
* does not implement the coordinator store, dependency waits, continuation or
|
|
9
|
+
* any remote adapter, and it never widens permission: callers pass a command
|
|
10
|
+
* that was already admitted and confined.
|
|
11
|
+
*
|
|
12
|
+
* Environment values are never written to a durable record. A record may name
|
|
13
|
+
* that the launch environment is inherited, and only the runner process carries
|
|
14
|
+
* the actual values.
|
|
15
|
+
*/
|
|
16
|
+
/** Bumped when a record shape changes in a way an older reader must refuse. */
|
|
17
|
+
export const SUPERVISOR_RECORD_VERSION = 1;
|
|
18
|
+
/** Bumped with the runner's own behaviour, not the record schema. */
|
|
19
|
+
export const SUPERVISOR_RUNNER_VERSION = "2";
|
|
20
|
+
export const SUPERVISOR_TASK_ID_PREFIX = "bgs_";
|
|
21
|
+
export const SUPERVISOR_TASK_ID_PATTERN = /^bgs_[0-9a-f]{20}$/;
|
|
22
|
+
/** Mirror of the Background tasks watch defaults, so a supervised watch keeps them. */
|
|
23
|
+
export const DEFAULT_WATCH_INTERVAL_MS = 30_000;
|
|
24
|
+
export const DEFAULT_WATCH_TIMEOUT_MS = 15 * 60_000;
|
|
25
|
+
/** Per-stream log cap; mirrors the Background tasks task-log retention default. */
|
|
26
|
+
export const DEFAULT_MAX_LOG_BYTES = 4 * 1024 * 1024;
|
|
27
|
+
/** How much of the last check/output is kept in the durable terminal record. */
|
|
28
|
+
export const DEFAULT_TERMINAL_TAIL_BYTES = 8 * 1024;
|
|
29
|
+
/** How long a launch may exist before an unclaimed launch is reported lost. */
|
|
30
|
+
export const DEFAULT_CLAIM_GRACE_MS = 30_000;
|
|
31
|
+
/** How long `start` waits for the runner's durable claim before returning. */
|
|
32
|
+
export const DEFAULT_CLAIM_WAIT_MS = 2_000;
|
|
33
|
+
/** How long `stop` waits for runner-attested evidence before escalating. */
|
|
34
|
+
export const DEFAULT_STOP_WAIT_MS = 5_000;
|
|
35
|
+
/** Poll cadence for stop requests, in the runner and in the caller's wait loops. */
|
|
36
|
+
export const SUPERVISOR_POLL_MS = 50;
|
|
37
|
+
/** SIGTERM-to-SIGKILL grace for a timed-out or stopped command group. */
|
|
38
|
+
export const SUPERVISOR_TERMINATION_GRACE_MS = 2_000;
|
|
39
|
+
/** How long group cleanup may run before it must be reported as unproven. */
|
|
40
|
+
export const SUPERVISOR_GROUP_CLEANUP_DEADLINE_MS = 7_000;
|
|
41
|
+
/** Cross-process state fence: how long a waiter holds on before erroring (never steals). */
|
|
42
|
+
export const SUPERVISOR_FENCE_WAIT_MS = 5_000;
|
|
43
|
+
/**
|
|
44
|
+
* `inspect` is an observation path: it waits only briefly for the fence and then
|
|
45
|
+
* reports `fenceBusy` rather than blocking a status loop on a wedged holder.
|
|
46
|
+
*/
|
|
47
|
+
export const SUPERVISOR_INSPECT_FENCE_WAIT_MS = 250;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// Generated canonical terminal publication. Do not edit directly.
|
|
2
|
+
import { existsSync, statSync } from "node:fs";
|
|
3
|
+
function terminalOutcome(status) {
|
|
4
|
+
switch (status) {
|
|
5
|
+
case "succeeded": return "succeeded";
|
|
6
|
+
case "cancelled": return "cancelled";
|
|
7
|
+
case "lost": return "lost";
|
|
8
|
+
default: return "failed";
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
function evidenceFor(inspection) {
|
|
12
|
+
const paths = inspection.logs;
|
|
13
|
+
const evidence = [];
|
|
14
|
+
const result = inspection.result;
|
|
15
|
+
const lost = inspection.lost;
|
|
16
|
+
const terminalRef = result ? "result.json" : "lost.json";
|
|
17
|
+
const summary = result
|
|
18
|
+
? `status=${result.status} exit=${result.exitCode ?? "null"} timedOut=${result.timedOut ? "true" : "false"}${result.groupCleanup ? ` groupCleanup=${result.groupCleanup}` : ""}`
|
|
19
|
+
: `status=lost detailLost=true`;
|
|
20
|
+
evidence.push({
|
|
21
|
+
operationId: "",
|
|
22
|
+
terminalRevision: 0,
|
|
23
|
+
kind: "terminal-record",
|
|
24
|
+
ref: terminalRef,
|
|
25
|
+
summary,
|
|
26
|
+
detailLost: !result,
|
|
27
|
+
});
|
|
28
|
+
for (const [label, path] of [["stdout", paths.stdout], ["stderr", paths.stderr]]) {
|
|
29
|
+
try {
|
|
30
|
+
const size = existsSync(path) ? statSync(path).size : 0;
|
|
31
|
+
if (size <= 0)
|
|
32
|
+
continue;
|
|
33
|
+
evidence.push({
|
|
34
|
+
operationId: "",
|
|
35
|
+
terminalRevision: 0,
|
|
36
|
+
kind: "log",
|
|
37
|
+
ref: path,
|
|
38
|
+
summary: `${label} retained (${size} bytes)`,
|
|
39
|
+
detailLost: false,
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
catch { /* a reclaimed log costs detail, never the outcome */ }
|
|
43
|
+
}
|
|
44
|
+
return evidence;
|
|
45
|
+
}
|
|
46
|
+
/** Shared terminal publication contract for the host and fixed server cancel adapter. */
|
|
47
|
+
export function supervisorTerminalPublication(operation, inspection, refs = evidenceFor(inspection)) {
|
|
48
|
+
const status = inspection.status;
|
|
49
|
+
const outcome = terminalOutcome(status);
|
|
50
|
+
return {
|
|
51
|
+
operationId: operation.operationId,
|
|
52
|
+
eventId: `${operation.taskId}:${inspection.result?.endedAt ?? inspection.lost?.recordedAt ?? inspection.observedAt}:${status}`,
|
|
53
|
+
outcome, owner: operation.owner,
|
|
54
|
+
evidence: refs.map(ref => ({ kind: ref.kind, ref: ref.ref, ...(ref.summary ? { summary: ref.summary } : {}), detailLost: ref.detailLost })),
|
|
55
|
+
...(outcome === "lost" ? { detailLost: true } : {}),
|
|
56
|
+
reason: inspection.result ? `supervisor ${status} exit=${inspection.result.exitCode ?? "null"}` : "supervisor lost: no terminal evidence",
|
|
57
|
+
};
|
|
58
|
+
}
|
|
@@ -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,85 @@
|
|
|
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
|
+
export function tryClaimDiscovery(ctx, input) {
|
|
36
|
+
const scope = requireId("scope", input.scope);
|
|
37
|
+
const hostId = requireId("hostId", input.hostId);
|
|
38
|
+
const token = requireId("token", input.token);
|
|
39
|
+
if (token.length > DISCOVERY_TOKEN_LIMIT) {
|
|
40
|
+
throw new StoreError("validation", `Invalid token: must be at most ${DISCOVERY_TOKEN_LIMIT} characters`);
|
|
41
|
+
}
|
|
42
|
+
const expectedHostId = input.expected === null ? null : requireId("expected.hostId", input.expected.hostId);
|
|
43
|
+
const expectedToken = input.expected === null ? null : requireId("expected.token", input.expected.token);
|
|
44
|
+
return ctx.transaction(() => {
|
|
45
|
+
const current = readClaim(ctx, scope);
|
|
46
|
+
if (input.expected === null) {
|
|
47
|
+
if (current)
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
else if (!current || current.hostId !== expectedHostId || current.token !== expectedToken) {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
const at = ctx.now();
|
|
54
|
+
run(ctx, `INSERT INTO discovery_claims (scope, host_id, token, claimed_at, updated_at)
|
|
55
|
+
VALUES (?, ?, ?, ?, ?)
|
|
56
|
+
ON CONFLICT(scope) DO UPDATE SET
|
|
57
|
+
host_id = excluded.host_id,
|
|
58
|
+
token = excluded.token,
|
|
59
|
+
claimed_at = excluded.claimed_at,
|
|
60
|
+
updated_at = excluded.updated_at`, scope, hostId, token, at, at);
|
|
61
|
+
return readClaim(ctx, scope);
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
export function releaseDiscoveryClaim(ctx, input) {
|
|
65
|
+
const scope = requireId("scope", input.scope);
|
|
66
|
+
const hostId = requireId("hostId", input.hostId);
|
|
67
|
+
const token = requireId("token", input.token);
|
|
68
|
+
return ctx.transaction(() => run(ctx, "DELETE FROM discovery_claims WHERE scope = ? AND host_id = ? AND token = ?", scope, hostId, token) > 0);
|
|
69
|
+
}
|
|
70
|
+
/** Monotonic revision for registration, authority changes and terminal publication. */
|
|
71
|
+
export function getChangeRevision(ctx) {
|
|
72
|
+
const row = getRow(ctx, "SELECT value FROM coordinator_state WHERE key = ?", CHANGE_REVISION_KEY);
|
|
73
|
+
if (!row)
|
|
74
|
+
return 0;
|
|
75
|
+
const revision = Number(columnText(row, "value"));
|
|
76
|
+
if (!Number.isSafeInteger(revision) || revision < 0) {
|
|
77
|
+
throw new StoreError("store-corruption", "The coordinator change revision is not a non-negative integer.");
|
|
78
|
+
}
|
|
79
|
+
return revision;
|
|
80
|
+
}
|
|
81
|
+
/** Called only inside an existing store transaction. */
|
|
82
|
+
export function bumpChangeRevision(ctx) {
|
|
83
|
+
run(ctx, `INSERT INTO coordinator_state (key, value) VALUES (?, '1')
|
|
84
|
+
ON CONFLICT(key) DO UPDATE SET value = CAST(CAST(value AS INTEGER) + 1 AS TEXT)`, CHANGE_REVISION_KEY);
|
|
85
|
+
}
|
|
@@ -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
|
+
}
|