@goah/cli 0.11.5 → 0.13.1
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/dist/LICENSE +201 -0
- package/dist/THIRD-PARTY-NOTICES.md +2319 -0
- package/dist/anthropic-messages-WBFOHES5.js +7214 -0
- package/dist/azure-openai-responses-NZFH3PO6.js +253 -0
- package/dist/chunk-25XSBFX6.js +639 -0
- package/dist/chunk-2QBQZGXF.js +110 -0
- package/dist/chunk-2ZP2NBW3.js +345 -0
- package/dist/chunk-4KA63VNZ.js +2 -0
- package/dist/chunk-4M6TXTT5.js +86 -0
- package/dist/chunk-4US7ZHT3.js +20 -0
- package/dist/chunk-6M3OOCKO.js +11809 -0
- package/dist/chunk-7AXAFDPG.js +17 -0
- package/dist/chunk-BXA47DTF.js +548 -0
- package/dist/chunk-FSBUS2BI.js +26 -0
- package/dist/chunk-GKDRAHLI.js +4787 -0
- package/dist/chunk-H462EFJP.js +89 -0
- package/dist/chunk-IIJQ3DW4.js +35 -0
- package/dist/chunk-JQD5EWJY.js +34 -0
- package/dist/chunk-K26BVR6O.js +61 -0
- package/dist/chunk-KAO7WIXG.js +31 -0
- package/dist/chunk-LBKI23CC.js +9810 -0
- package/dist/chunk-LKBKZEHT.js +41 -0
- package/dist/chunk-MD7TLTXZ.js +18 -0
- package/dist/chunk-MPXK7QBL.js +868 -0
- package/dist/chunk-NRLGWZJC.js +11 -0
- package/dist/chunk-PFEV3HWI.js +1178 -0
- package/dist/chunk-QBD6EJ2Z.js +1746 -0
- package/dist/chunk-R6I3VKME.js +132 -0
- package/dist/chunk-TJON22J4.js +87 -0
- package/dist/chunk-ULY36ME4.js +33097 -0
- package/dist/chunk-VWEV4LTH.js +25 -0
- package/dist/chunk-X7UWW2PN.js +883 -0
- package/dist/chunk-XALZLRYK.js +9221 -0
- package/dist/chunk-XPQKM3L7.js +57 -0
- package/dist/chunk-YH6YJ2IB.js +1773 -0
- package/dist/cli.d.ts +0 -2
- package/dist/cli.js +13148 -506
- package/dist/console/assets/index-3sYrDMmt.css +1 -0
- package/dist/console/assets/index-B1vGMXKr.js +52 -0
- package/dist/console/assets/index-B1vGMXKr.js.map +1 -0
- package/dist/console/index.html +2 -2
- package/dist/dist-65MDQA4Q.js +1126 -0
- package/dist/dist-KNR2XL6J.js +39 -0
- package/dist/execution.d.ts +557 -2
- package/dist/execution.js +37 -2
- package/dist/faux-runner-worker.js +128 -0
- package/dist/google-generative-ai-YMHXZSFE.js +422 -0
- package/dist/google-vertex-X6DB3ZQ6.js +471 -0
- package/dist/index.d.ts +855 -44
- package/dist/index.js +84 -257
- package/dist/kernel.d.ts +39 -2
- package/dist/kernel.js +21 -2
- package/dist/mistral-conversations-TY3MMD6G.js +718 -0
- package/dist/multipart-parser-F6M4NJZU.js +373 -0
- package/dist/openai-codex-responses-BRDUMLN5.js +1374 -0
- package/dist/openai-completions-CX634XN3.js +1139 -0
- package/dist/openai-responses-HMCXJIHT.js +300 -0
- package/dist/openrouter-images-KTWET2H2.js +148 -0
- package/dist/pi-messages-XL5OEC4K.js +307 -0
- package/dist/pi-worker.js +671 -0
- package/dist/runner-pi.d.ts +342 -2
- package/dist/runner-pi.js +46 -2
- package/dist/runner-registry-M776E3SE.js +22 -0
- package/dist/sqlite.d.ts +446 -2
- package/dist/sqlite.js +15 -2
- package/dist/src-F2KBSV4T.js +1398 -0
- package/dist/supervisor.d.ts +625 -2
- package/dist/supervisor.js +39 -2
- package/dist/testkit.d.ts +564 -2
- package/dist/testkit.js +127 -2
- package/dist/transcript.d.ts +84 -0
- package/dist/transcript.js +25 -0
- package/dist/verification-worker.js +72 -0
- package/package.json +3 -28
- package/dist/cli.d.ts.map +0 -1
- package/dist/cli.js.map +0 -1
- package/dist/console/assets/index-BJTGvlCH.js +0 -52
- package/dist/console/assets/index-BJTGvlCH.js.map +0 -1
- package/dist/console/assets/index-msBn41Cl.css +0 -1
- package/dist/control.d.ts +0 -106
- package/dist/control.d.ts.map +0 -1
- package/dist/control.js +0 -215
- package/dist/control.js.map +0 -1
- package/dist/execution.d.ts.map +0 -1
- package/dist/execution.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/inspect.d.ts +0 -61
- package/dist/inspect.d.ts.map +0 -1
- package/dist/inspect.js +0 -110
- package/dist/inspect.js.map +0 -1
- package/dist/kernel.d.ts.map +0 -1
- package/dist/kernel.js.map +0 -1
- package/dist/live-config.d.ts +0 -10
- package/dist/live-config.d.ts.map +0 -1
- package/dist/live-config.js +0 -44
- package/dist/live-config.js.map +0 -1
- package/dist/metrics.d.ts +0 -2
- package/dist/metrics.d.ts.map +0 -1
- package/dist/metrics.js +0 -2
- package/dist/metrics.js.map +0 -1
- package/dist/prompt-queue.d.ts +0 -13
- package/dist/prompt-queue.d.ts.map +0 -1
- package/dist/prompt-queue.js +0 -30
- package/dist/prompt-queue.js.map +0 -1
- package/dist/runner-pi.d.ts.map +0 -1
- package/dist/runner-pi.js.map +0 -1
- package/dist/runner-registry.d.ts +0 -8
- package/dist/runner-registry.d.ts.map +0 -1
- package/dist/runner-registry.js +0 -12
- package/dist/runner-registry.js.map +0 -1
- package/dist/searchable-select.d.ts +0 -24
- package/dist/searchable-select.d.ts.map +0 -1
- package/dist/searchable-select.js +0 -61
- package/dist/searchable-select.js.map +0 -1
- package/dist/secret-input.d.ts +0 -8
- package/dist/secret-input.d.ts.map +0 -1
- package/dist/secret-input.js +0 -14
- package/dist/secret-input.js.map +0 -1
- package/dist/session.d.ts +0 -2
- package/dist/session.d.ts.map +0 -1
- package/dist/session.js +0 -2
- package/dist/session.js.map +0 -1
- package/dist/setup-wizard.d.ts +0 -11
- package/dist/setup-wizard.d.ts.map +0 -1
- package/dist/setup-wizard.js +0 -130
- package/dist/setup-wizard.js.map +0 -1
- package/dist/sqlite.d.ts.map +0 -1
- package/dist/sqlite.js.map +0 -1
- package/dist/supervisor.d.ts.map +0 -1
- package/dist/supervisor.js.map +0 -1
- package/dist/testkit.d.ts.map +0 -1
- package/dist/testkit.js.map +0 -1
- package/dist/tui-theme.d.ts +0 -16
- package/dist/tui-theme.d.ts.map +0 -1
- package/dist/tui-theme.js +0 -18
- package/dist/tui-theme.js.map +0 -1
- package/dist/tui.d.ts +0 -18
- package/dist/tui.d.ts.map +0 -1
- package/dist/tui.js +0 -583
- package/dist/tui.js.map +0 -1
- package/dist/update.d.ts +0 -15
- package/dist/update.d.ts.map +0 -1
- package/dist/update.js +0 -59
- package/dist/update.js.map +0 -1
- package/dist/web-console.d.ts +0 -33
- package/dist/web-console.d.ts.map +0 -1
- package/dist/web-console.js +0 -252
- package/dist/web-console.js.map +0 -1
- package/dist/welcome.d.ts +0 -30
- package/dist/welcome.d.ts.map +0 -1
- package/dist/welcome.js +0 -81
- package/dist/welcome.js.map +0 -1
- package/node_modules/goah-ledger-contract/dist/execution.d.ts +0 -402
- package/node_modules/goah-ledger-contract/dist/execution.d.ts.map +0 -1
- package/node_modules/goah-ledger-contract/dist/execution.js +0 -40
- package/node_modules/goah-ledger-contract/dist/execution.js.map +0 -1
- package/node_modules/goah-ledger-contract/dist/index.d.ts +0 -5
- package/node_modules/goah-ledger-contract/dist/index.d.ts.map +0 -1
- package/node_modules/goah-ledger-contract/dist/index.js +0 -5
- package/node_modules/goah-ledger-contract/dist/index.js.map +0 -1
- package/node_modules/goah-ledger-contract/dist/kernel.d.ts +0 -37
- package/node_modules/goah-ledger-contract/dist/kernel.d.ts.map +0 -1
- package/node_modules/goah-ledger-contract/dist/kernel.js +0 -8
- package/node_modules/goah-ledger-contract/dist/kernel.js.map +0 -1
- package/node_modules/goah-ledger-contract/dist/metrics.d.ts +0 -40
- package/node_modules/goah-ledger-contract/dist/metrics.d.ts.map +0 -1
- package/node_modules/goah-ledger-contract/dist/metrics.js +0 -25
- package/node_modules/goah-ledger-contract/dist/metrics.js.map +0 -1
- package/node_modules/goah-ledger-contract/dist/session.d.ts +0 -63
- package/node_modules/goah-ledger-contract/dist/session.d.ts.map +0 -1
- package/node_modules/goah-ledger-contract/dist/session.js +0 -115
- package/node_modules/goah-ledger-contract/dist/session.js.map +0 -1
- package/node_modules/goah-ledger-contract/package.json +0 -29
- package/node_modules/goah-ledger-sqlite/dist/index.d.ts +0 -77
- package/node_modules/goah-ledger-sqlite/dist/index.d.ts.map +0 -1
- package/node_modules/goah-ledger-sqlite/dist/index.js +0 -884
- package/node_modules/goah-ledger-sqlite/dist/index.js.map +0 -1
- package/node_modules/goah-ledger-sqlite/package.json +0 -26
- package/node_modules/goah-runner-pi/dist/configurator.d.ts +0 -20
- package/node_modules/goah-runner-pi/dist/configurator.d.ts.map +0 -1
- package/node_modules/goah-runner-pi/dist/configurator.js +0 -267
- package/node_modules/goah-runner-pi/dist/configurator.js.map +0 -1
- package/node_modules/goah-runner-pi/dist/credential-store.d.ts +0 -12
- package/node_modules/goah-runner-pi/dist/credential-store.d.ts.map +0 -1
- package/node_modules/goah-runner-pi/dist/credential-store.js +0 -69
- package/node_modules/goah-runner-pi/dist/credential-store.js.map +0 -1
- package/node_modules/goah-runner-pi/dist/env-spec.d.ts +0 -17
- package/node_modules/goah-runner-pi/dist/env-spec.d.ts.map +0 -1
- package/node_modules/goah-runner-pi/dist/env-spec.js +0 -95
- package/node_modules/goah-runner-pi/dist/env-spec.js.map +0 -1
- package/node_modules/goah-runner-pi/dist/index.d.ts +0 -64
- package/node_modules/goah-runner-pi/dist/index.d.ts.map +0 -1
- package/node_modules/goah-runner-pi/dist/index.js +0 -241
- package/node_modules/goah-runner-pi/dist/index.js.map +0 -1
- package/node_modules/goah-runner-pi/dist/model-provider.d.ts +0 -30
- package/node_modules/goah-runner-pi/dist/model-provider.d.ts.map +0 -1
- package/node_modules/goah-runner-pi/dist/model-provider.js +0 -96
- package/node_modules/goah-runner-pi/dist/model-provider.js.map +0 -1
- package/node_modules/goah-runner-pi/dist/pi-worker.d.ts +0 -29
- package/node_modules/goah-runner-pi/dist/pi-worker.d.ts.map +0 -1
- package/node_modules/goah-runner-pi/dist/pi-worker.js +0 -428
- package/node_modules/goah-runner-pi/dist/pi-worker.js.map +0 -1
- package/node_modules/goah-runner-pi/dist/test-helpers.d.ts +0 -4
- package/node_modules/goah-runner-pi/dist/test-helpers.d.ts.map +0 -1
- package/node_modules/goah-runner-pi/dist/test-helpers.js +0 -11
- package/node_modules/goah-runner-pi/dist/test-helpers.js.map +0 -1
- package/node_modules/goah-runner-pi/dist/verification-worker.d.ts +0 -2
- package/node_modules/goah-runner-pi/dist/verification-worker.d.ts.map +0 -1
- package/node_modules/goah-runner-pi/dist/verification-worker.js +0 -48
- package/node_modules/goah-runner-pi/dist/verification-worker.js.map +0 -1
- package/node_modules/goah-runner-pi/package.json +0 -28
- package/node_modules/goah-supervisor/dist/context-view.d.ts +0 -31
- package/node_modules/goah-supervisor/dist/context-view.d.ts.map +0 -1
- package/node_modules/goah-supervisor/dist/context-view.js +0 -71
- package/node_modules/goah-supervisor/dist/context-view.js.map +0 -1
- package/node_modules/goah-supervisor/dist/index.d.ts +0 -94
- package/node_modules/goah-supervisor/dist/index.d.ts.map +0 -1
- package/node_modules/goah-supervisor/dist/index.js +0 -888
- package/node_modules/goah-supervisor/dist/index.js.map +0 -1
- package/node_modules/goah-supervisor/dist/roles.d.ts +0 -3
- package/node_modules/goah-supervisor/dist/roles.d.ts.map +0 -1
- package/node_modules/goah-supervisor/dist/roles.js +0 -14
- package/node_modules/goah-supervisor/dist/roles.js.map +0 -1
- package/node_modules/goah-supervisor/dist/verification.d.ts +0 -82
- package/node_modules/goah-supervisor/dist/verification.d.ts.map +0 -1
- package/node_modules/goah-supervisor/dist/verification.js +0 -110
- package/node_modules/goah-supervisor/dist/verification.js.map +0 -1
- package/node_modules/goah-supervisor/package.json +0 -26
- package/node_modules/goah-testkit/dist/faux-runner-worker.d.ts +0 -2
- package/node_modules/goah-testkit/dist/faux-runner-worker.d.ts.map +0 -1
- package/node_modules/goah-testkit/dist/faux-runner-worker.js +0 -75
- package/node_modules/goah-testkit/dist/faux-runner-worker.js.map +0 -1
- package/node_modules/goah-testkit/dist/index.d.ts +0 -52
- package/node_modules/goah-testkit/dist/index.d.ts.map +0 -1
- package/node_modules/goah-testkit/dist/index.js +0 -113
- package/node_modules/goah-testkit/dist/index.js.map +0 -1
- package/node_modules/goah-testkit/dist/mock-connector-worker.d.ts +0 -2
- package/node_modules/goah-testkit/dist/mock-connector-worker.d.ts.map +0 -1
- package/node_modules/goah-testkit/dist/mock-connector-worker.js +0 -29
- package/node_modules/goah-testkit/dist/mock-connector-worker.js.map +0 -1
- package/node_modules/goah-testkit/package.json +0 -29
|
@@ -1,884 +0,0 @@
|
|
|
1
|
-
import { DatabaseSync } from "node:sqlite";
|
|
2
|
-
import { assertActionRequest, assertActionTransition, assertGoalSnapshot, assertGoalTransition, controlStream, goalStream, wakeStream, workRecordStream, } from "goah-ledger-contract";
|
|
3
|
-
export const SQLITE_SCHEMA_VERSION = 9;
|
|
4
|
-
const createGoals = `CREATE TABLE IF NOT EXISTS goals (
|
|
5
|
-
id TEXT PRIMARY KEY,
|
|
6
|
-
parent_id TEXT REFERENCES goals(id),
|
|
7
|
-
objective TEXT NOT NULL,
|
|
8
|
-
observation_method TEXT CHECK(observation_method IS NULL OR length(trim(observation_method)) > 0),
|
|
9
|
-
verification_method TEXT CHECK(verification_method IS NULL OR length(trim(verification_method)) > 0),
|
|
10
|
-
owner TEXT NOT NULL,
|
|
11
|
-
phase TEXT NOT NULL CHECK(phase IN ('active','paused','blocked','complete')),
|
|
12
|
-
revision INTEGER NOT NULL CHECK(revision >= 0)
|
|
13
|
-
) STRICT;`;
|
|
14
|
-
const createWorkRecords = `CREATE TABLE IF NOT EXISTS work_records (
|
|
15
|
-
goal_id TEXT PRIMARY KEY REFERENCES goals(id),
|
|
16
|
-
record_revision INTEGER NOT NULL CHECK(record_revision >= 0),
|
|
17
|
-
goal_revision INTEGER NOT NULL CHECK(goal_revision >= 0),
|
|
18
|
-
content TEXT NOT NULL CHECK(length(trim(content)) > 0),
|
|
19
|
-
updated_by TEXT NOT NULL,
|
|
20
|
-
updated_in_turn TEXT NOT NULL,
|
|
21
|
-
updated_in_wake TEXT,
|
|
22
|
-
updated_at TEXT NOT NULL,
|
|
23
|
-
reason TEXT NOT NULL CHECK(length(trim(reason)) > 0),
|
|
24
|
-
evidence TEXT NOT NULL CHECK(json_valid(evidence)),
|
|
25
|
-
last_event_seq INTEGER NOT NULL REFERENCES events(seq)
|
|
26
|
-
) STRICT;`;
|
|
27
|
-
const createWakes = `CREATE TABLE IF NOT EXISTS wakes (
|
|
28
|
-
id TEXT PRIMARY KEY,
|
|
29
|
-
agent TEXT NOT NULL,
|
|
30
|
-
trigger_ref TEXT NOT NULL,
|
|
31
|
-
status TEXT NOT NULL CHECK(status IN ('queued','leased','running','done','abnormal','merge_blocked')),
|
|
32
|
-
lease_until TEXT,
|
|
33
|
-
attempt INTEGER NOT NULL CHECK(attempt >= 0),
|
|
34
|
-
started_at TEXT,
|
|
35
|
-
ended_at TEXT,
|
|
36
|
-
enqueued_seq INTEGER NOT NULL CHECK(enqueued_seq > 0),
|
|
37
|
-
lease_token TEXT,
|
|
38
|
-
runner_pid INTEGER,
|
|
39
|
-
UNIQUE(agent, trigger_ref),
|
|
40
|
-
CHECK((status IN ('leased','running') AND lease_until IS NOT NULL AND lease_token IS NOT NULL) OR status NOT IN ('leased','running')),
|
|
41
|
-
CHECK((status IN ('done','abnormal','merge_blocked') AND ended_at IS NOT NULL) OR status NOT IN ('done','abnormal','merge_blocked'))
|
|
42
|
-
) STRICT;`;
|
|
43
|
-
const createActions = `CREATE TABLE IF NOT EXISTS actions (
|
|
44
|
-
id TEXT PRIMARY KEY,
|
|
45
|
-
agent TEXT NOT NULL,
|
|
46
|
-
kind TEXT NOT NULL,
|
|
47
|
-
connector TEXT NOT NULL,
|
|
48
|
-
payload TEXT NOT NULL CHECK(json_valid(payload)),
|
|
49
|
-
reason TEXT NOT NULL CHECK(length(trim(reason)) > 0),
|
|
50
|
-
evidence TEXT NOT NULL CHECK(json_valid(evidence) AND json_array_length(evidence) > 0),
|
|
51
|
-
gated INTEGER NOT NULL CHECK(gated IN (0,1)),
|
|
52
|
-
status TEXT NOT NULL CHECK(status IN ('requested','approved','dispatching','confirmed','failed','unknown')),
|
|
53
|
-
reconciled_at TEXT,
|
|
54
|
-
external_ref TEXT,
|
|
55
|
-
audit_advice TEXT CHECK(audit_advice IS NULL OR json_valid(audit_advice)),
|
|
56
|
-
advice_acked INTEGER NOT NULL CHECK(advice_acked IN (0,1)),
|
|
57
|
-
CHECK(reconciled_at IS NULL OR status IN ('confirmed','failed'))
|
|
58
|
-
) STRICT;`;
|
|
59
|
-
const indexesAndTriggers = `
|
|
60
|
-
CREATE UNIQUE INDEX IF NOT EXISTS wakes_one_active_agent ON wakes(agent) WHERE status IN ('leased','running');
|
|
61
|
-
CREATE INDEX IF NOT EXISTS wakes_queue_order ON wakes(status, enqueued_seq);
|
|
62
|
-
CREATE INDEX IF NOT EXISTS schedule_due ON schedule(next_wake_at);
|
|
63
|
-
CREATE INDEX IF NOT EXISTS events_actor_type_seq ON events(actor, type, seq DESC);
|
|
64
|
-
CREATE INDEX IF NOT EXISTS events_stream_seq ON events(stream_id, stream_seq);
|
|
65
|
-
CREATE INDEX IF NOT EXISTS events_coalesced_trigger ON events(json_extract(data,'$.triggerRef'), stream_id) WHERE type='wake.trigger_coalesced';
|
|
66
|
-
CREATE INDEX IF NOT EXISTS actions_agent_status ON actions(agent, status);
|
|
67
|
-
CREATE VIRTUAL TABLE IF NOT EXISTS events_fts USING fts5(actor, type, data, content='events', content_rowid='seq');
|
|
68
|
-
|
|
69
|
-
CREATE TRIGGER IF NOT EXISTS events_no_update BEFORE UPDATE ON events
|
|
70
|
-
BEGIN SELECT RAISE(ABORT, 'events are append-only'); END;
|
|
71
|
-
CREATE TRIGGER IF NOT EXISTS events_no_delete BEFORE DELETE ON events
|
|
72
|
-
BEGIN SELECT RAISE(ABORT, 'events are append-only'); END;
|
|
73
|
-
CREATE TRIGGER IF NOT EXISTS events_fts_insert AFTER INSERT ON events
|
|
74
|
-
BEGIN INSERT INTO events_fts(rowid,actor,type,data) VALUES (new.seq,new.actor,new.type,new.data); END;
|
|
75
|
-
|
|
76
|
-
CREATE TRIGGER IF NOT EXISTS wakes_valid_transition BEFORE UPDATE OF status ON wakes
|
|
77
|
-
WHEN OLD.status <> NEW.status AND NOT (
|
|
78
|
-
(OLD.status = 'queued' AND NEW.status IN ('leased','abnormal')) OR
|
|
79
|
-
(OLD.status = 'leased' AND NEW.status IN ('queued','running','abnormal')) OR
|
|
80
|
-
(OLD.status = 'running' AND NEW.status IN ('done','abnormal','merge_blocked'))
|
|
81
|
-
)
|
|
82
|
-
BEGIN SELECT RAISE(ABORT, 'invalid wake transition'); END;
|
|
83
|
-
|
|
84
|
-
CREATE TRIGGER IF NOT EXISTS actions_valid_transition BEFORE UPDATE OF status ON actions
|
|
85
|
-
WHEN OLD.status <> NEW.status AND NOT (
|
|
86
|
-
(OLD.status = 'requested' AND NEW.status IN ('approved','failed')) OR
|
|
87
|
-
(OLD.status = 'approved' AND NEW.status IN ('dispatching','failed')) OR
|
|
88
|
-
(OLD.status = 'dispatching' AND NEW.status IN ('confirmed','failed','unknown')) OR
|
|
89
|
-
(OLD.status = 'unknown' AND NEW.status IN ('dispatching','confirmed','failed'))
|
|
90
|
-
)
|
|
91
|
-
BEGIN SELECT RAISE(ABORT, 'invalid action transition'); END;
|
|
92
|
-
|
|
93
|
-
CREATE TRIGGER IF NOT EXISTS goals_valid_transition BEFORE UPDATE OF phase ON goals
|
|
94
|
-
WHEN OLD.phase <> NEW.phase AND NOT (
|
|
95
|
-
(OLD.phase = 'active' AND NEW.phase IN ('paused','blocked','complete')) OR
|
|
96
|
-
(OLD.phase = 'paused' AND NEW.phase IN ('active','complete')) OR
|
|
97
|
-
(OLD.phase = 'blocked' AND NEW.phase IN ('active','complete'))
|
|
98
|
-
)
|
|
99
|
-
BEGIN SELECT RAISE(ABORT, 'invalid goal transition'); END;
|
|
100
|
-
`;
|
|
101
|
-
const schema = `
|
|
102
|
-
CREATE TABLE IF NOT EXISTS events (
|
|
103
|
-
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
104
|
-
stream_id TEXT NOT NULL,
|
|
105
|
-
stream_seq INTEGER NOT NULL CHECK(stream_seq > 0),
|
|
106
|
-
ts TEXT NOT NULL,
|
|
107
|
-
actor TEXT NOT NULL,
|
|
108
|
-
type TEXT NOT NULL,
|
|
109
|
-
data TEXT NOT NULL CHECK(json_valid(data)),
|
|
110
|
-
ignorable INTEGER CHECK(ignorable IS NULL OR ignorable = 1),
|
|
111
|
-
UNIQUE(stream_id, stream_seq)
|
|
112
|
-
) STRICT;
|
|
113
|
-
${createGoals}
|
|
114
|
-
${createWorkRecords}
|
|
115
|
-
CREATE TABLE IF NOT EXISTS schedule (
|
|
116
|
-
id TEXT PRIMARY KEY,
|
|
117
|
-
agent TEXT NOT NULL,
|
|
118
|
-
next_wake_at TEXT NOT NULL,
|
|
119
|
-
reason TEXT NOT NULL,
|
|
120
|
-
set_by TEXT NOT NULL
|
|
121
|
-
) STRICT;
|
|
122
|
-
${createWakes}
|
|
123
|
-
CREATE TABLE IF NOT EXISTS mailbox (
|
|
124
|
-
id TEXT PRIMARY KEY,
|
|
125
|
-
to_agent TEXT NOT NULL,
|
|
126
|
-
from_agent TEXT NOT NULL,
|
|
127
|
-
level TEXT NOT NULL CHECK(level IN ('fyi','decision','emergency')),
|
|
128
|
-
body TEXT NOT NULL CHECK(json_valid(body)),
|
|
129
|
-
read_at TEXT
|
|
130
|
-
) STRICT;
|
|
131
|
-
${createActions}
|
|
132
|
-
${indexesAndTriggers}`;
|
|
133
|
-
class SystemClock {
|
|
134
|
-
now() { return new Date(); }
|
|
135
|
-
}
|
|
136
|
-
export class SqliteLedger {
|
|
137
|
-
db;
|
|
138
|
-
#faultInjector;
|
|
139
|
-
#clock;
|
|
140
|
-
constructor(path = ":memory:", options = {}) {
|
|
141
|
-
this.db = new DatabaseSync(path);
|
|
142
|
-
this.db.exec(`PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = ${options.busyTimeoutMs ?? 5_000};`);
|
|
143
|
-
this.#faultInjector = options.faultInjector;
|
|
144
|
-
this.#clock = options.clock ?? new SystemClock();
|
|
145
|
-
const version = Number(this.db.prepare("PRAGMA user_version").get().user_version);
|
|
146
|
-
if (version > SQLITE_SCHEMA_VERSION) {
|
|
147
|
-
this.db.close();
|
|
148
|
-
throw new Error(`ledger schema ${version} is newer than supported schema ${SQLITE_SCHEMA_VERSION}`);
|
|
149
|
-
}
|
|
150
|
-
if (version === 0) {
|
|
151
|
-
this.db.exec(schema);
|
|
152
|
-
this.db.exec(`PRAGMA user_version = ${SQLITE_SCHEMA_VERSION}`);
|
|
153
|
-
}
|
|
154
|
-
else if (version < SQLITE_SCHEMA_VERSION) {
|
|
155
|
-
this.#migrateLegacy();
|
|
156
|
-
}
|
|
157
|
-
else {
|
|
158
|
-
this.db.exec(schema);
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
close() { this.db.close(); }
|
|
162
|
-
appendEvent(input) { return this.#transaction(() => this.#insertEvent(input)); }
|
|
163
|
-
appendEvents(inputs) { return this.#transaction(() => inputs.map((input) => this.#insertEvent(input))); }
|
|
164
|
-
readStream(streamId, fromStreamSeq = 1) {
|
|
165
|
-
return this.db.prepare("SELECT * FROM events WHERE stream_id=? AND stream_seq>=? ORDER BY stream_seq").all(streamId, fromStreamSeq).map(mapEvent);
|
|
166
|
-
}
|
|
167
|
-
putGoal(goal, actor, wakeId) {
|
|
168
|
-
const normalized = normalizeGoal(goal);
|
|
169
|
-
assertGoalSnapshot(normalized);
|
|
170
|
-
const current = this.#getGoal(normalized.id);
|
|
171
|
-
if (current) {
|
|
172
|
-
if (normalized.revision !== current.revision + 1)
|
|
173
|
-
throw new Error("goal revision CAS failed");
|
|
174
|
-
if (current.phase === "complete")
|
|
175
|
-
throw new Error("completed goal cannot be modified");
|
|
176
|
-
if (normalized.parentId !== current.parentId)
|
|
177
|
-
throw new Error("goal reparenting is not supported");
|
|
178
|
-
if (normalized.phase === "complete")
|
|
179
|
-
throw new Error("goal completion requires reason and evidence");
|
|
180
|
-
if (normalized.objective !== current.objective && ((current.observationMethod !== null && normalized.observationMethod === current.observationMethod) || (current.verificationMethod !== null && normalized.verificationMethod === current.verificationMethod)))
|
|
181
|
-
throw new Error("objective revision must replace or invalidate observation and verification methods");
|
|
182
|
-
assertGoalTransition(current.phase, normalized.phase);
|
|
183
|
-
this.#assertGoalAuthority(current.parentId, actor);
|
|
184
|
-
}
|
|
185
|
-
else {
|
|
186
|
-
if (normalized.revision !== 0)
|
|
187
|
-
throw new Error("new goal revision must be 0");
|
|
188
|
-
this.#assertGoalAuthority(normalized.parentId, actor);
|
|
189
|
-
}
|
|
190
|
-
return this.#transaction(() => {
|
|
191
|
-
const event = this.#recordProjection("goals", normalized, actor, "goal.put", wakeId, undefined, undefined, goalStream(normalized.id));
|
|
192
|
-
if (!current)
|
|
193
|
-
this.#createWorkRecord(normalized, actor, wakeId ?? `goal:create:${normalized.id}`, wakeId);
|
|
194
|
-
return event;
|
|
195
|
-
});
|
|
196
|
-
}
|
|
197
|
-
updateWorkRecord(request, actor) {
|
|
198
|
-
if (!request.turnId.trim() || !request.reason.trim() || !request.content.trim())
|
|
199
|
-
throw new Error("work record turn, reason and content are required");
|
|
200
|
-
this.#assertEvidenceExists(request.evidence);
|
|
201
|
-
const goal = this.#getGoal(request.goalId);
|
|
202
|
-
if (!goal)
|
|
203
|
-
throw new Error("work record goal does not exist");
|
|
204
|
-
if (goal.revision !== request.goalRevision)
|
|
205
|
-
throw new Error("work record goal revision is stale");
|
|
206
|
-
this.#assertWorkRecordAuthority(goal, actor);
|
|
207
|
-
const current = this.workRecord(goal.id);
|
|
208
|
-
if (!current)
|
|
209
|
-
throw new Error("work record does not exist");
|
|
210
|
-
if (current.recordRevision !== request.expectedRevision)
|
|
211
|
-
throw new Error("work record revision CAS failed");
|
|
212
|
-
if (current.content === request.content)
|
|
213
|
-
throw new Error("work record content is unchanged");
|
|
214
|
-
return this.#transaction(() => this.#recordWorkRecord({
|
|
215
|
-
...current,
|
|
216
|
-
recordRevision: current.recordRevision + 1,
|
|
217
|
-
goalRevision: goal.revision,
|
|
218
|
-
content: request.content,
|
|
219
|
-
updatedBy: actor,
|
|
220
|
-
updatedInTurn: request.turnId,
|
|
221
|
-
updatedInWake: request.wakeId ?? null,
|
|
222
|
-
updatedAt: this.#now(),
|
|
223
|
-
reason: request.reason,
|
|
224
|
-
evidence: request.evidence,
|
|
225
|
-
}, "work_record.updated"));
|
|
226
|
-
}
|
|
227
|
-
commitDelegation(request, actor, wakeId) {
|
|
228
|
-
const existing = this.#delegationResult(request.id);
|
|
229
|
-
if (existing) {
|
|
230
|
-
if (existing.goal.id !== request.childGoal.id || existing.goal.parentId !== request.parentGoalId || existing.goal.objective !== request.childGoal.objective || existing.goal.observationMethod !== request.childGoal.observationMethod || existing.goal.verificationMethod !== request.childGoal.verificationMethod || existing.goal.owner !== request.childGoal.owner)
|
|
231
|
-
throw new Error("delegation id was reused with a different child goal");
|
|
232
|
-
return existing;
|
|
233
|
-
}
|
|
234
|
-
if (!request.id.trim() || !request.reason.trim())
|
|
235
|
-
throw new Error("delegation id and reason are required");
|
|
236
|
-
if (request.childGoal.owner === actor)
|
|
237
|
-
throw new Error("delegate to a distinct worker agent; use goal.put for self-owned subgoals");
|
|
238
|
-
if (!request.childGoal.id.trim() || !request.childGoal.objective.trim() || !request.childGoal.observationMethod.trim() || !request.childGoal.verificationMethod.trim() || !request.childGoal.owner.trim())
|
|
239
|
-
throw new Error("delegation child goal is incomplete");
|
|
240
|
-
this.#assertEvidenceExists(request.evidence);
|
|
241
|
-
const parent = this.#getGoal(request.parentGoalId);
|
|
242
|
-
if (!parent)
|
|
243
|
-
throw new Error("delegation parent goal does not exist");
|
|
244
|
-
if (parent.owner !== actor)
|
|
245
|
-
throw new Error("only the parent goal owner may delegate");
|
|
246
|
-
if (parent.phase !== "active")
|
|
247
|
-
throw new Error("delegation parent goal must be active");
|
|
248
|
-
if (this.#getGoal(request.childGoal.id))
|
|
249
|
-
throw new Error("delegation child goal already exists");
|
|
250
|
-
return this.#transaction(() => {
|
|
251
|
-
const goal = normalizeGoal({ ...request.childGoal, parentId: request.parentGoalId, phase: "active", revision: 0 });
|
|
252
|
-
const mail = {
|
|
253
|
-
id: `delegation-mail:${request.id}`,
|
|
254
|
-
to: goal.owner,
|
|
255
|
-
from: actor,
|
|
256
|
-
level: "decision",
|
|
257
|
-
body: { type: "delegation", delegationId: request.id, goalId: goal.id, parentGoalId: request.parentGoalId, objective: goal.objective, observationMethod: goal.observationMethod, verificationMethod: goal.verificationMethod ?? null, brief: request.brief, reason: request.reason, evidence: request.evidence },
|
|
258
|
-
readAt: null,
|
|
259
|
-
};
|
|
260
|
-
const wakeBase = {
|
|
261
|
-
id: `delegation-wake:${request.id}`,
|
|
262
|
-
agent: goal.owner,
|
|
263
|
-
triggerRef: `delegation:${request.id}`,
|
|
264
|
-
status: "queued",
|
|
265
|
-
leaseUntil: null,
|
|
266
|
-
attempt: 0,
|
|
267
|
-
startedAt: null,
|
|
268
|
-
endedAt: null,
|
|
269
|
-
enqueuedSeq: 0,
|
|
270
|
-
leaseToken: null,
|
|
271
|
-
runnerPid: null,
|
|
272
|
-
};
|
|
273
|
-
this.#insertEvent({
|
|
274
|
-
streamId: wakeId ? wakeStream(wakeId) : controlStream("delegations"),
|
|
275
|
-
ts: this.#now(),
|
|
276
|
-
actor,
|
|
277
|
-
type: "delegation.created",
|
|
278
|
-
data: { delegationId: request.id, parentGoalId: request.parentGoalId, goalId: goal.id, mailId: mail.id, wakeId: wakeBase.id, reason: request.reason, evidence: request.evidence },
|
|
279
|
-
});
|
|
280
|
-
this.#faultInjector?.("after_delegation_event");
|
|
281
|
-
this.#recordProjection("goals", goal, actor, "goal.put", wakeId, undefined, undefined, goalStream(goal.id));
|
|
282
|
-
this.#createWorkRecord(goal, actor, wakeId ?? `delegation:${request.id}`, wakeId);
|
|
283
|
-
this.#recordProjection("mailbox", mail, actor, "mail.put", wakeId);
|
|
284
|
-
const wake = { ...wakeBase, enqueuedSeq: this.#nextEventSeq() };
|
|
285
|
-
this.#recordProjection("wakes", wake, "supervisor", "wake.enqueued", wake.id, undefined, wake.enqueuedSeq);
|
|
286
|
-
return { delegationId: request.id, goal, mail, wake };
|
|
287
|
-
});
|
|
288
|
-
}
|
|
289
|
-
commitReassignment(request, actor, wakeId) {
|
|
290
|
-
const existing = this.#reassignmentResult(request.id);
|
|
291
|
-
if (existing) {
|
|
292
|
-
if (existing.goal.id !== request.goalId || existing.goal.owner !== request.newOwner)
|
|
293
|
-
throw new Error("reassignment id was reused with a different target");
|
|
294
|
-
return existing;
|
|
295
|
-
}
|
|
296
|
-
if (!request.id.trim() || !request.newOwner.trim() || !request.reason.trim())
|
|
297
|
-
throw new Error("reassignment id, owner and reason are required");
|
|
298
|
-
this.#assertEvidenceExists(request.evidence);
|
|
299
|
-
const current = this.#getGoal(request.goalId);
|
|
300
|
-
if (!current)
|
|
301
|
-
throw new Error("reassignment goal does not exist");
|
|
302
|
-
if (!current.parentId)
|
|
303
|
-
throw new Error("root goals cannot be reassigned by CEO");
|
|
304
|
-
this.#assertGoalAuthority(current.parentId, actor);
|
|
305
|
-
if (current.phase === "complete")
|
|
306
|
-
throw new Error("completed goals cannot be reassigned");
|
|
307
|
-
if (current.owner === request.newOwner)
|
|
308
|
-
throw new Error("reassignment owner is unchanged");
|
|
309
|
-
return this.#transaction(() => {
|
|
310
|
-
const goal = { ...current, owner: request.newOwner, revision: current.revision + 1 };
|
|
311
|
-
const mail = [
|
|
312
|
-
{ id: `reassignment-old-mail:${request.id}`, to: current.owner, from: actor, level: "fyi", body: { type: "reassignment", reassignmentId: request.id, goalId: goal.id, role: "previous_owner", reason: request.reason, evidence: request.evidence }, readAt: null },
|
|
313
|
-
{ id: `reassignment-new-mail:${request.id}`, to: goal.owner, from: actor, level: "decision", body: { type: "reassignment", reassignmentId: request.id, goalId: goal.id, role: "new_owner", brief: request.brief, reason: request.reason, evidence: request.evidence }, readAt: null },
|
|
314
|
-
];
|
|
315
|
-
const wakeBase = { id: `reassignment-wake:${request.id}`, agent: goal.owner, triggerRef: `reassignment:${request.id}`, status: "queued", leaseUntil: null, attempt: 0, startedAt: null, endedAt: null, enqueuedSeq: 0, leaseToken: null, runnerPid: null };
|
|
316
|
-
this.#insertEvent({ streamId: wakeId ? wakeStream(wakeId) : controlStream("reassignments"), ts: this.#now(), actor, type: "goal.reassigned", data: { reassignmentId: request.id, goalId: goal.id, oldOwner: current.owner, newOwner: goal.owner, mailIds: mail.map((item) => item.id), wakeId: wakeBase.id, reason: request.reason, evidence: request.evidence } });
|
|
317
|
-
this.#faultInjector?.("after_reassignment_event");
|
|
318
|
-
this.#recordProjection("goals", goal, actor, "goal.put", wakeId, undefined, undefined, goalStream(goal.id));
|
|
319
|
-
const oldWake = this.queuedWakeForAgent(current.owner);
|
|
320
|
-
if (oldWake)
|
|
321
|
-
this.#recordProjection("wakes", { ...oldWake, status: "abnormal", endedAt: this.#now() }, "supervisor", "wake.suppressed", oldWake.id);
|
|
322
|
-
for (const item of mail)
|
|
323
|
-
this.#recordProjection("mailbox", item, actor, "mail.put", wakeId);
|
|
324
|
-
const wake = { ...wakeBase, enqueuedSeq: this.#nextEventSeq() };
|
|
325
|
-
this.#recordProjection("wakes", wake, "supervisor", "wake.enqueued", wake.id, undefined, wake.enqueuedSeq);
|
|
326
|
-
return { reassignmentId: request.id, goal, mail, wake };
|
|
327
|
-
});
|
|
328
|
-
}
|
|
329
|
-
completeGoal(request, actor, wakeId) {
|
|
330
|
-
if (!request.reason.trim())
|
|
331
|
-
throw new Error("goal completion reason is required");
|
|
332
|
-
this.#assertEvidenceExists(request.evidence);
|
|
333
|
-
const current = this.#getGoal(request.goalId);
|
|
334
|
-
if (!current)
|
|
335
|
-
throw new Error("goal does not exist");
|
|
336
|
-
if (request.revision !== current.revision)
|
|
337
|
-
throw new Error("goal completion revision is stale");
|
|
338
|
-
if (current.phase === "complete")
|
|
339
|
-
return current;
|
|
340
|
-
if (current.observationMethod === null)
|
|
341
|
-
throw new Error("goal completion requires an observation method");
|
|
342
|
-
if (current.verificationMethod === null || current.verificationMethod === undefined)
|
|
343
|
-
throw new Error("goal completion requires a verification method");
|
|
344
|
-
this.#assertGoalAuthority(current.parentId, actor);
|
|
345
|
-
if (current.parentId === null && this.#hasNonCompleteDescendant(current.id))
|
|
346
|
-
throw new Error("root goal cannot complete while descendants remain non-complete");
|
|
347
|
-
const source = this.db.prepare("SELECT seq FROM events WHERE stream_id=? AND type='goal.put' AND json_extract(data,'$.snapshot.revision')=? ORDER BY seq DESC LIMIT 1").get(goalStream(current.id), current.revision);
|
|
348
|
-
if (!source)
|
|
349
|
-
throw new Error("goal revision has no source event");
|
|
350
|
-
if (request.evidence.some((seq) => seq <= source.seq))
|
|
351
|
-
throw new Error("goal completion evidence predates the current revision");
|
|
352
|
-
return this.#transaction(() => {
|
|
353
|
-
this.#insertEvent({ streamId: goalStream(current.id), ts: this.#now(), actor, type: "goal.completion_decided", data: { goalId: current.id, revision: current.revision, observationMethod: current.observationMethod, verificationMethod: current.verificationMethod ?? null, reason: request.reason, evidence: request.evidence } });
|
|
354
|
-
const next = { ...current, phase: "complete", revision: current.revision + 1 };
|
|
355
|
-
this.#recordProjection("goals", next, actor, "goal.put", wakeId, undefined, undefined, goalStream(current.id));
|
|
356
|
-
return next;
|
|
357
|
-
});
|
|
358
|
-
}
|
|
359
|
-
putSchedule(value, actor, wakeId) {
|
|
360
|
-
if (actor !== "supervisor" && actor !== value.agent)
|
|
361
|
-
throw new Error("schedule may only be set by its agent or supervisor");
|
|
362
|
-
return this.#project("schedule", value, actor, "schedule.put", wakeId);
|
|
363
|
-
}
|
|
364
|
-
enqueueWake(input, actor) {
|
|
365
|
-
if (actor !== "supervisor")
|
|
366
|
-
throw new Error("only supervisor may enqueue wakes");
|
|
367
|
-
if (input.status !== "queued" || input.attempt !== 0 || input.leaseUntil || input.startedAt || input.endedAt || input.leaseToken || input.runnerPid) {
|
|
368
|
-
throw new Error("new wake must be pristine and queued");
|
|
369
|
-
}
|
|
370
|
-
const duplicate = this.wakeByTrigger(input.agent, input.triggerRef);
|
|
371
|
-
if (duplicate) {
|
|
372
|
-
const row = this.db.prepare("SELECT * FROM events WHERE type='wake.enqueued' AND json_extract(data, '$.snapshot.id')=? ORDER BY seq DESC LIMIT 1").get(duplicate.id);
|
|
373
|
-
if (!row)
|
|
374
|
-
throw new Error("wake projection has no source event");
|
|
375
|
-
return { event: mapEvent(row), created: false };
|
|
376
|
-
}
|
|
377
|
-
return this.#transaction(() => {
|
|
378
|
-
const enqueuedSeq = this.#nextEventSeq();
|
|
379
|
-
const wake = { ...input, enqueuedSeq };
|
|
380
|
-
const event = this.#recordProjection("wakes", wake, actor, "wake.enqueued", wake.id, undefined, enqueuedSeq);
|
|
381
|
-
return { event, created: true };
|
|
382
|
-
});
|
|
383
|
-
}
|
|
384
|
-
claimNextWake(now, leaseUntil, leaseToken) {
|
|
385
|
-
return this.#transaction(() => {
|
|
386
|
-
const row = this.db.prepare(`SELECT * FROM wakes w WHERE status='queued' AND NOT EXISTS (
|
|
387
|
-
SELECT 1 FROM wakes active WHERE active.agent=w.agent AND active.status IN ('leased','running')
|
|
388
|
-
) ORDER BY CASE WHEN trigger_ref LIKE 'interaction:%' THEN 0 ELSE 1 END,enqueued_seq LIMIT 1`).get();
|
|
389
|
-
if (!row)
|
|
390
|
-
return null;
|
|
391
|
-
const current = mapWake(row);
|
|
392
|
-
const next = { ...current, status: "leased", leaseUntil, leaseToken, runnerPid: null, attempt: current.attempt + 1 };
|
|
393
|
-
this.#recordProjection("wakes", next, "supervisor", "wake.leased", next.id, now);
|
|
394
|
-
return next;
|
|
395
|
-
});
|
|
396
|
-
}
|
|
397
|
-
markWakeRunning(id, now, leaseToken) {
|
|
398
|
-
const current = this.#requiredWake(id);
|
|
399
|
-
this.#assertLease(current, leaseToken);
|
|
400
|
-
const next = { ...current, status: "running", startedAt: now };
|
|
401
|
-
this.#project("wakes", next, "supervisor", "wake.running", id, now);
|
|
402
|
-
return next;
|
|
403
|
-
}
|
|
404
|
-
attachWakeProcess(id, leaseToken, pid, now) {
|
|
405
|
-
const current = this.#requiredWake(id);
|
|
406
|
-
this.#assertLease(current, leaseToken);
|
|
407
|
-
if (current.status !== "running")
|
|
408
|
-
throw new Error("runner pid may only be attached to a running wake");
|
|
409
|
-
const next = { ...current, runnerPid: pid };
|
|
410
|
-
this.#project("wakes", next, "supervisor", "wake.runner_attached", id, now);
|
|
411
|
-
return next;
|
|
412
|
-
}
|
|
413
|
-
renewWakeLease(id, leaseToken, leaseUntil, now) {
|
|
414
|
-
const current = this.#requiredWake(id);
|
|
415
|
-
this.#assertLease(current, leaseToken);
|
|
416
|
-
if (current.status !== "leased" && current.status !== "running")
|
|
417
|
-
throw new Error("only an active wake lease may be renewed");
|
|
418
|
-
if (leaseUntil <= now)
|
|
419
|
-
throw new Error("renewed lease must expire in the future");
|
|
420
|
-
const next = { ...current, leaseUntil };
|
|
421
|
-
this.#project("wakes", next, "supervisor", "wake.lease_renewed", id, now);
|
|
422
|
-
return next;
|
|
423
|
-
}
|
|
424
|
-
finishWake(id, status, now) {
|
|
425
|
-
const current = this.#requiredWake(id);
|
|
426
|
-
const next = { ...current, status, leaseUntil: null, leaseToken: null, runnerPid: null, endedAt: now };
|
|
427
|
-
this.#project("wakes", next, "supervisor", `wake.${status}`, id, now);
|
|
428
|
-
return next;
|
|
429
|
-
}
|
|
430
|
-
expiredWakes(now) {
|
|
431
|
-
return this.db.prepare("SELECT * FROM wakes WHERE status IN ('leased','running') AND lease_until <= ? ORDER BY enqueued_seq").all(now).map(mapWake);
|
|
432
|
-
}
|
|
433
|
-
recoverExpiredWake(id, now) {
|
|
434
|
-
const current = this.#requiredWake(id);
|
|
435
|
-
if (current.status !== "leased" && current.status !== "running")
|
|
436
|
-
throw new Error("wake is not recoverable");
|
|
437
|
-
if (!current.leaseUntil || current.leaseUntil > now)
|
|
438
|
-
throw new Error("wake lease has not expired");
|
|
439
|
-
const running = current.status === "running";
|
|
440
|
-
const next = { ...current, status: running ? "abnormal" : "queued", leaseUntil: null, leaseToken: null, runnerPid: null, endedAt: running ? now : null };
|
|
441
|
-
this.#project("wakes", next, "supervisor", running ? "wake.expired_abnormal" : "wake.lease_expired", id, now);
|
|
442
|
-
return next;
|
|
443
|
-
}
|
|
444
|
-
appendRunnerEvent(input, leaseToken) {
|
|
445
|
-
return this.#transaction(() => {
|
|
446
|
-
if (!input.streamId.startsWith("wake:"))
|
|
447
|
-
throw new Error("runner event requires a wake stream");
|
|
448
|
-
const wake = this.#requiredWake(input.streamId.slice("wake:".length));
|
|
449
|
-
this.#assertLease(wake, leaseToken);
|
|
450
|
-
if (wake.status !== "running" || !wake.leaseUntil || input.ts > wake.leaseUntil)
|
|
451
|
-
throw new Error("stale runner event rejected");
|
|
452
|
-
return this.#insertEvent(input);
|
|
453
|
-
});
|
|
454
|
-
}
|
|
455
|
-
requestAction(action, actor, wakeId) {
|
|
456
|
-
assertActionRequest(action);
|
|
457
|
-
if (actor !== action.agent)
|
|
458
|
-
throw new Error("action actor does not match action agent");
|
|
459
|
-
this.#assertEvidenceExists(action.evidence);
|
|
460
|
-
return this.#project("actions", action, actor, "action.requested", wakeId);
|
|
461
|
-
}
|
|
462
|
-
approveAction(id, approver, reason, evidence) {
|
|
463
|
-
return this.#decideAction(id, "approved", approver, reason, evidence);
|
|
464
|
-
}
|
|
465
|
-
rejectAction(id, approver, reason, evidence) {
|
|
466
|
-
return this.#decideAction(id, "failed", approver, reason, evidence);
|
|
467
|
-
}
|
|
468
|
-
transitionAction(id, status, patch = {}) {
|
|
469
|
-
const current = this.#requiredAction(id);
|
|
470
|
-
assertActionTransition(current.status, status);
|
|
471
|
-
if (current.status === "unknown" && (status === "confirmed" || status === "failed") && !patch.reconciledAt)
|
|
472
|
-
throw new Error("unknown action requires a reconciliation timestamp");
|
|
473
|
-
if (patch.reconciledAt && current.status !== "unknown")
|
|
474
|
-
throw new Error("reconciledAt is only written after unknown is queried");
|
|
475
|
-
if (patch.reconciledAt && status !== "confirmed" && status !== "failed")
|
|
476
|
-
throw new Error("reconciliation must resolve to a final state");
|
|
477
|
-
const next = { ...current, ...patch, status };
|
|
478
|
-
this.#project("actions", next, "supervisor", `action.${status}`);
|
|
479
|
-
return next;
|
|
480
|
-
}
|
|
481
|
-
recoverDispatchingActions() {
|
|
482
|
-
const rows = this.db.prepare("SELECT id FROM actions WHERE status='dispatching' ORDER BY id").all();
|
|
483
|
-
return rows.map(({ id }) => this.transitionAction(id, "unknown"));
|
|
484
|
-
}
|
|
485
|
-
putAuditAdvice(id, input, wakeId) {
|
|
486
|
-
const advice = { ...input, at: this.#now() };
|
|
487
|
-
this.#assertEvidenceExists(advice.evidence);
|
|
488
|
-
const current = this.#requiredAction(id);
|
|
489
|
-
const next = { ...current, auditAdvice: advice, adviceAcked: false };
|
|
490
|
-
this.#project("actions", next, advice.by, "action.audit_advice", wakeId, advice.at);
|
|
491
|
-
return next;
|
|
492
|
-
}
|
|
493
|
-
ackAuditAdvice(id, agent) {
|
|
494
|
-
const current = this.#requiredAction(id);
|
|
495
|
-
if (current.agent !== agent)
|
|
496
|
-
throw new Error("only the action owner may acknowledge audit advice");
|
|
497
|
-
if (!current.auditAdvice)
|
|
498
|
-
throw new Error("action has no audit advice");
|
|
499
|
-
const next = { ...current, adviceAcked: true };
|
|
500
|
-
this.#project("actions", next, agent, "action.audit_advice_acked");
|
|
501
|
-
return next;
|
|
502
|
-
}
|
|
503
|
-
putMail(mail, actor, wakeId) {
|
|
504
|
-
if (mail.from !== actor && actor !== "supervisor")
|
|
505
|
-
throw new Error("mail sender does not match actor");
|
|
506
|
-
return this.#project("mailbox", mail, actor, "mail.put", wakeId);
|
|
507
|
-
}
|
|
508
|
-
commitHandoff(commit) {
|
|
509
|
-
return this.#transaction(() => {
|
|
510
|
-
const wake = this.#requiredWake(commit.wakeId);
|
|
511
|
-
if (wake.status !== "running" || wake.agent !== commit.agent)
|
|
512
|
-
throw new Error("handoff does not match a running wake");
|
|
513
|
-
const event = this.#insertEvent({ streamId: wakeStream(commit.wakeId), ts: commit.ts, actor: commit.agent, type: "handoff.recorded", data: commit.output.handoff });
|
|
514
|
-
for (const mail of this.unreadMail(commit.agent)) {
|
|
515
|
-
this.#recordProjection("mailbox", { ...mail, readAt: commit.ts }, "supervisor", "mail.read", commit.wakeId, commit.ts);
|
|
516
|
-
}
|
|
517
|
-
for (const mail of commit.outgoingMail) {
|
|
518
|
-
if (mail.from !== commit.agent)
|
|
519
|
-
throw new Error("handoff mail sender does not match agent");
|
|
520
|
-
this.#recordProjection("mailbox", mail, commit.agent, "mail.put", commit.wakeId, commit.ts);
|
|
521
|
-
}
|
|
522
|
-
if (commit.schedule) {
|
|
523
|
-
if (commit.schedule.agent !== commit.agent || commit.schedule.setBy !== commit.agent)
|
|
524
|
-
throw new Error("handoff schedule does not match agent");
|
|
525
|
-
this.#recordProjection("schedule", commit.schedule, commit.agent, "schedule.put", commit.wakeId, commit.ts);
|
|
526
|
-
}
|
|
527
|
-
return event;
|
|
528
|
-
});
|
|
529
|
-
}
|
|
530
|
-
commitInteraction(commit) {
|
|
531
|
-
return this.#transaction(() => {
|
|
532
|
-
const wake = this.#requiredWake(commit.wakeId);
|
|
533
|
-
if (wake.status !== "running" || wake.agent !== commit.agent)
|
|
534
|
-
throw new Error("interaction does not match a running wake");
|
|
535
|
-
const mailRow = this.db.prepare("SELECT * FROM mailbox WHERE id=?").get(commit.mailId);
|
|
536
|
-
if (!mailRow)
|
|
537
|
-
throw new Error("interaction mail does not exist");
|
|
538
|
-
const mail = mapMail(mailRow);
|
|
539
|
-
if (mail.to !== commit.agent || mail.readAt !== null)
|
|
540
|
-
throw new Error("interaction mail is not unread for the agent");
|
|
541
|
-
const event = this.#insertEvent({ streamId: wakeStream(commit.wakeId), ts: commit.ts, actor: commit.agent, type: "interaction.completed", data: { mailId: mail.id, response: commit.response } });
|
|
542
|
-
this.#recordProjection("mailbox", { ...mail, readAt: commit.ts }, "supervisor", "mail.read", commit.wakeId, commit.ts);
|
|
543
|
-
return event;
|
|
544
|
-
});
|
|
545
|
-
}
|
|
546
|
-
dueSchedules(now) { return this.db.prepare("SELECT * FROM schedule WHERE next_wake_at <= ? ORDER BY next_wake_at,id").all(now).map(mapSchedule); }
|
|
547
|
-
unreadMail(agent) { return this.db.prepare("SELECT * FROM mailbox WHERE to_agent=? AND read_at IS NULL ORDER BY rowid").all(agent).map(mapMail); }
|
|
548
|
-
unackedAuditAdvice(agent) { return this.db.prepare("SELECT * FROM actions WHERE agent=? AND audit_advice IS NOT NULL AND advice_acked=0 ORDER BY rowid").all(agent).map(mapAction); }
|
|
549
|
-
lastEvent(actor, type) { const row = this.db.prepare("SELECT * FROM events WHERE actor=? AND type=? ORDER BY seq DESC LIMIT 1").get(actor, type); return row ? mapEvent(row) : null; }
|
|
550
|
-
latestEvent() { const row = this.db.prepare("SELECT * FROM events ORDER BY seq DESC LIMIT 1").get(); return row ? mapEvent(row) : null; }
|
|
551
|
-
eventsForWake(wakeId) { return this.readStream(wakeStream(wakeId)); }
|
|
552
|
-
wake(id) { const row = this.db.prepare("SELECT * FROM wakes WHERE id=?").get(id); return row ? mapWake(row) : null; }
|
|
553
|
-
wakeByTrigger(agent, triggerRef) {
|
|
554
|
-
const direct = this.db.prepare("SELECT * FROM wakes WHERE agent=? AND trigger_ref=?").get(agent, triggerRef);
|
|
555
|
-
if (direct)
|
|
556
|
-
return mapWake(direct);
|
|
557
|
-
const coalesced = this.db.prepare(`SELECT w.* FROM events e JOIN wakes w ON e.stream_id='wake:'||w.id
|
|
558
|
-
WHERE e.type='wake.trigger_coalesced' AND json_extract(e.data,'$.triggerRef')=? AND w.agent=? LIMIT 1`).get(triggerRef, agent);
|
|
559
|
-
return coalesced ? mapWake(coalesced) : null;
|
|
560
|
-
}
|
|
561
|
-
queuedWakeForAgent(agent) { const row = this.db.prepare("SELECT * FROM wakes WHERE agent=? AND status='queued' ORDER BY enqueued_seq LIMIT 1").get(agent); return row ? mapWake(row) : null; }
|
|
562
|
-
action(id) { const row = this.db.prepare("SELECT * FROM actions WHERE id=?").get(id); return row ? mapAction(row) : null; }
|
|
563
|
-
goalsForOwner(owner) { return this.db.prepare("SELECT * FROM goals WHERE owner=? ORDER BY id").all(owner).map(mapGoal); }
|
|
564
|
-
goal(id) { return this.#getGoal(id); }
|
|
565
|
-
workRecord(goalId) { const row = this.db.prepare("SELECT * FROM work_records WHERE goal_id=?").get(goalId); return row ? mapWorkRecord(row) : null; }
|
|
566
|
-
workRecordHistory(goalId) {
|
|
567
|
-
return this.readStream(workRecordStream(goalId)).filter((event) => event.type === "work_record.created" || event.type === "work_record.updated").map((event) => mapWorkRecordEvent(event));
|
|
568
|
-
}
|
|
569
|
-
workRecordDiff(goalId, fromRevision, toRevision) {
|
|
570
|
-
const history = this.workRecordHistory(goalId);
|
|
571
|
-
const from = history.find((record) => record.recordRevision === fromRevision);
|
|
572
|
-
const to = history.find((record) => record.recordRevision === toRevision);
|
|
573
|
-
if (!from || !to)
|
|
574
|
-
throw new Error("work record diff revision does not exist");
|
|
575
|
-
return { goalId, fromRevision, toRevision, text: lineDiff(from.content, to.content) };
|
|
576
|
-
}
|
|
577
|
-
searchWorkRecords(query, limit = 50) {
|
|
578
|
-
return this.db.prepare(`SELECT e.* FROM events_fts f JOIN events e ON e.seq=f.rowid
|
|
579
|
-
WHERE events_fts MATCH ? AND e.type IN ('work_record.created','work_record.updated') ORDER BY rank LIMIT ?`).all(query, limit).map((row) => mapWorkRecordEvent(mapEvent(row)));
|
|
580
|
-
}
|
|
581
|
-
triggeringMail() { return this.db.prepare("SELECT * FROM mailbox WHERE read_at IS NULL AND level IN ('decision','emergency') ORDER BY rowid").all().map(mapMail); }
|
|
582
|
-
eventsSince(seq, types) {
|
|
583
|
-
const events = this.db.prepare("SELECT * FROM events WHERE seq>? ORDER BY seq").all(seq).map(mapEvent);
|
|
584
|
-
return types?.length ? events.filter((event) => types.includes(event.type)) : events;
|
|
585
|
-
}
|
|
586
|
-
searchEvents(query, limit = 50) {
|
|
587
|
-
return this.db.prepare("SELECT e.* FROM events_fts f JOIN events e ON e.seq=f.rowid WHERE events_fts MATCH ? ORDER BY rank LIMIT ?").all(query, limit).map(mapEvent);
|
|
588
|
-
}
|
|
589
|
-
metricSamples(goalId) {
|
|
590
|
-
return this.db.prepare("SELECT data FROM events WHERE type='metric.sampled' AND json_extract(data,'$.goalId')=? ORDER BY seq").all(goalId).map((row) => JSON.parse(row.data));
|
|
591
|
-
}
|
|
592
|
-
events() { return this.db.prepare("SELECT * FROM events ORDER BY seq").all().map(mapEvent); }
|
|
593
|
-
goals() { return this.db.prepare("SELECT * FROM goals ORDER BY id").all().map(mapGoal); }
|
|
594
|
-
workRecords() { return this.db.prepare("SELECT * FROM work_records ORDER BY goal_id").all().map(mapWorkRecord); }
|
|
595
|
-
schedules() { return this.db.prepare("SELECT * FROM schedule ORDER BY id").all().map(mapSchedule); }
|
|
596
|
-
wakes() { return this.db.prepare("SELECT * FROM wakes ORDER BY enqueued_seq").all().map(mapWake); }
|
|
597
|
-
actions() { return this.db.prepare("SELECT * FROM actions ORDER BY id").all().map(mapAction); }
|
|
598
|
-
mailbox() { return this.db.prepare("SELECT * FROM mailbox ORDER BY rowid").all().map(mapMail); }
|
|
599
|
-
rebuildProjections() {
|
|
600
|
-
const source = this.events();
|
|
601
|
-
this.#transaction(() => {
|
|
602
|
-
this.db.exec("DELETE FROM work_records; DELETE FROM actions; DELETE FROM mailbox; DELETE FROM wakes; DELETE FROM schedule; DELETE FROM goals;");
|
|
603
|
-
for (const event of source) {
|
|
604
|
-
const data = event.data;
|
|
605
|
-
if (data.projection && data.snapshot)
|
|
606
|
-
this.#applyProjection(data.projection, data.snapshot, event.seq);
|
|
607
|
-
}
|
|
608
|
-
});
|
|
609
|
-
}
|
|
610
|
-
#delegationResult(id) {
|
|
611
|
-
const row = this.db.prepare("SELECT data FROM events WHERE type='delegation.created' AND json_extract(data,'$.delegationId')=? ORDER BY seq LIMIT 1").get(id);
|
|
612
|
-
if (!row)
|
|
613
|
-
return null;
|
|
614
|
-
const data = JSON.parse(row.data);
|
|
615
|
-
const goal = this.#getGoal(data.goalId);
|
|
616
|
-
const mailRow = this.db.prepare("SELECT * FROM mailbox WHERE id=?").get(data.mailId);
|
|
617
|
-
const wake = this.wake(data.wakeId);
|
|
618
|
-
if (!goal || !mailRow || !wake)
|
|
619
|
-
throw new Error("committed delegation projections are incomplete");
|
|
620
|
-
return { delegationId: id, goal, mail: mapMail(mailRow), wake };
|
|
621
|
-
}
|
|
622
|
-
#reassignmentResult(id) {
|
|
623
|
-
const row = this.db.prepare("SELECT data FROM events WHERE type='goal.reassigned' AND json_extract(data,'$.reassignmentId')=? ORDER BY seq LIMIT 1").get(id);
|
|
624
|
-
if (!row)
|
|
625
|
-
return null;
|
|
626
|
-
const data = JSON.parse(row.data);
|
|
627
|
-
const goal = this.#getGoal(data.goalId);
|
|
628
|
-
const mail = data.mailIds.map((mailId) => {
|
|
629
|
-
const mailRow = this.db.prepare("SELECT * FROM mailbox WHERE id=?").get(mailId);
|
|
630
|
-
if (!mailRow)
|
|
631
|
-
throw new Error("committed reassignment mail is missing");
|
|
632
|
-
return mapMail(mailRow);
|
|
633
|
-
});
|
|
634
|
-
const wake = this.wake(data.wakeId);
|
|
635
|
-
if (!goal || !wake)
|
|
636
|
-
throw new Error("committed reassignment projections are incomplete");
|
|
637
|
-
return { reassignmentId: id, goal, mail, wake };
|
|
638
|
-
}
|
|
639
|
-
#decideAction(id, status, approver, reason, evidence) {
|
|
640
|
-
if (!reason.trim())
|
|
641
|
-
throw new Error("approval reason is required");
|
|
642
|
-
this.#assertEvidenceExists(evidence);
|
|
643
|
-
return this.#transaction(() => {
|
|
644
|
-
const current = this.#requiredAction(id);
|
|
645
|
-
assertActionTransition(current.status, status);
|
|
646
|
-
this.#insertEvent({ streamId: controlStream("actions"), ts: this.#now(), actor: approver, type: `action.${status}_decision`, data: { actionId: id, reason, evidence } });
|
|
647
|
-
const next = { ...current, status };
|
|
648
|
-
this.#recordProjection("actions", next, approver, `action.${status}`);
|
|
649
|
-
return next;
|
|
650
|
-
});
|
|
651
|
-
}
|
|
652
|
-
#createWorkRecord(goal, actor, turnId, wakeId, seed) {
|
|
653
|
-
return this.#recordWorkRecord({
|
|
654
|
-
goalId: goal.id,
|
|
655
|
-
recordRevision: 0,
|
|
656
|
-
goalRevision: goal.revision,
|
|
657
|
-
content: seed?.content ?? initialWorkRecord(),
|
|
658
|
-
updatedBy: actor,
|
|
659
|
-
updatedInTurn: turnId,
|
|
660
|
-
updatedInWake: wakeId ?? null,
|
|
661
|
-
updatedAt: this.#now(),
|
|
662
|
-
reason: "Goal created",
|
|
663
|
-
evidence: seed?.evidence ?? [],
|
|
664
|
-
lastEventSeq: 0,
|
|
665
|
-
}, "work_record.created");
|
|
666
|
-
}
|
|
667
|
-
#recordWorkRecord(snapshot, type) {
|
|
668
|
-
const seq = this.#nextEventSeq();
|
|
669
|
-
const committed = { ...snapshot, lastEventSeq: seq };
|
|
670
|
-
this.#recordProjection("work_records", committed, committed.updatedBy, type, committed.updatedInWake ?? undefined, committed.updatedAt, seq, workRecordStream(committed.goalId));
|
|
671
|
-
return committed;
|
|
672
|
-
}
|
|
673
|
-
#assertWorkRecordAuthority(goal, actor) {
|
|
674
|
-
if (goal.owner === actor || (goal.parentId === null && actor === "human"))
|
|
675
|
-
return;
|
|
676
|
-
const parent = goal.parentId ? this.#getGoal(goal.parentId) : null;
|
|
677
|
-
if (parent?.owner !== actor)
|
|
678
|
-
throw new Error("only the goal owner or parent owner may update its work record");
|
|
679
|
-
}
|
|
680
|
-
#assertGoalAuthority(parentId, actor) {
|
|
681
|
-
if (parentId === null) {
|
|
682
|
-
if (actor !== "human")
|
|
683
|
-
throw new Error("only human may modify a root goal");
|
|
684
|
-
return;
|
|
685
|
-
}
|
|
686
|
-
const parent = this.#getGoal(parentId);
|
|
687
|
-
if (!parent)
|
|
688
|
-
throw new Error("parent goal does not exist");
|
|
689
|
-
if (parent.owner !== actor)
|
|
690
|
-
throw new Error("only the parent goal owner may modify a child goal");
|
|
691
|
-
}
|
|
692
|
-
#hasNonCompleteDescendant(goalId) {
|
|
693
|
-
return Boolean(this.db.prepare(`WITH RECURSIVE descendants(id) AS (
|
|
694
|
-
SELECT id FROM goals WHERE parent_id=?
|
|
695
|
-
UNION ALL SELECT g.id FROM goals g JOIN descendants d ON g.parent_id=d.id
|
|
696
|
-
) SELECT 1 FROM goals WHERE id IN (SELECT id FROM descendants) AND phase<>'complete' LIMIT 1`).get(goalId));
|
|
697
|
-
}
|
|
698
|
-
#assertEvidenceExists(evidence) {
|
|
699
|
-
const exists = this.db.prepare("SELECT 1 FROM events WHERE seq=?");
|
|
700
|
-
for (const seq of evidence)
|
|
701
|
-
if (!Number.isInteger(seq) || seq <= 0 || !exists.get(seq))
|
|
702
|
-
throw new Error(`evidence event does not exist: ${seq}`);
|
|
703
|
-
}
|
|
704
|
-
#assertLease(wake, leaseToken) {
|
|
705
|
-
if (wake.leaseToken !== leaseToken)
|
|
706
|
-
throw new Error("stale wake lease token");
|
|
707
|
-
}
|
|
708
|
-
#getGoal(id) { const row = this.db.prepare("SELECT * FROM goals WHERE id=?").get(id); return row ? mapGoal(row) : null; }
|
|
709
|
-
#requiredWake(id) { const value = this.wake(id); if (!value)
|
|
710
|
-
throw new Error(`wake not found: ${id}`); return value; }
|
|
711
|
-
#requiredAction(id) { const value = this.action(id); if (!value)
|
|
712
|
-
throw new Error(`action not found: ${id}`); return value; }
|
|
713
|
-
#project(projection, snapshot, actor, type, wakeId, ts, streamId) {
|
|
714
|
-
return this.#transaction(() => this.#recordProjection(projection, snapshot, actor, type, wakeId, ts, undefined, streamId));
|
|
715
|
-
}
|
|
716
|
-
#recordProjection(projection, snapshot, actor, type, wakeId, ts, expectedSeq, streamId) {
|
|
717
|
-
const event = this.#insertEvent({ streamId: streamId ?? (wakeId ? wakeStream(wakeId) : controlStream(projection)), ts: ts ?? this.#now(), actor, type, data: { projection, snapshot } }, expectedSeq);
|
|
718
|
-
this.#faultInjector?.("after_event_before_projection");
|
|
719
|
-
this.#applyProjection(projection, snapshot, event.seq);
|
|
720
|
-
return event;
|
|
721
|
-
}
|
|
722
|
-
#insertEvent(input, expectedSeq) {
|
|
723
|
-
if (!input.streamId.trim() || !input.actor.trim() || !input.type.trim())
|
|
724
|
-
throw new Error("event streamId, actor and type are required");
|
|
725
|
-
const streamSeq = Number(this.db.prepare("SELECT COALESCE(MAX(stream_seq),0)+1 AS next FROM events WHERE stream_id=?").get(input.streamId).next);
|
|
726
|
-
const result = expectedSeq === undefined
|
|
727
|
-
? this.db.prepare("INSERT INTO events(stream_id,stream_seq,ts,actor,type,data,ignorable) VALUES (?,?,?,?,?,json(?),?)").run(input.streamId, streamSeq, input.ts, input.actor, input.type, JSON.stringify(input.data), input.ignorable === true ? 1 : null)
|
|
728
|
-
: this.db.prepare("INSERT INTO events(seq,stream_id,stream_seq,ts,actor,type,data,ignorable) VALUES (?,?,?,?,?,?,json(?),?)").run(expectedSeq, input.streamId, streamSeq, input.ts, input.actor, input.type, JSON.stringify(input.data), input.ignorable === true ? 1 : null);
|
|
729
|
-
return { ...input, seq: Number(result.lastInsertRowid), streamSeq };
|
|
730
|
-
}
|
|
731
|
-
#nextEventSeq() {
|
|
732
|
-
const row = this.db.prepare("SELECT seq FROM sqlite_sequence WHERE name='events'").get();
|
|
733
|
-
return Number(row?.seq ?? 0) + 1;
|
|
734
|
-
}
|
|
735
|
-
#applyProjection(projection, raw, sourceSeq) {
|
|
736
|
-
if (projection === "goals") {
|
|
737
|
-
const v = normalizeGoal(raw);
|
|
738
|
-
this.db.prepare(`INSERT INTO goals VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET parent_id=excluded.parent_id,objective=excluded.objective,observation_method=excluded.observation_method,verification_method=excluded.verification_method,owner=excluded.owner,phase=excluded.phase,revision=excluded.revision`).run(v.id, v.parentId, v.objective, v.observationMethod, v.verificationMethod ?? null, v.owner, v.phase, v.revision);
|
|
739
|
-
}
|
|
740
|
-
else if (projection === "work_records") {
|
|
741
|
-
const v = raw;
|
|
742
|
-
this.db.prepare(`INSERT INTO work_records VALUES (?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(goal_id) DO UPDATE SET record_revision=excluded.record_revision,goal_revision=excluded.goal_revision,content=excluded.content,updated_by=excluded.updated_by,updated_in_turn=excluded.updated_in_turn,updated_in_wake=excluded.updated_in_wake,updated_at=excluded.updated_at,reason=excluded.reason,evidence=excluded.evidence,last_event_seq=excluded.last_event_seq`).run(v.goalId, v.recordRevision, v.goalRevision, v.content, v.updatedBy, v.updatedInTurn, v.updatedInWake, v.updatedAt, v.reason, JSON.stringify(v.evidence), v.lastEventSeq || sourceSeq);
|
|
743
|
-
}
|
|
744
|
-
else if (projection === "schedule") {
|
|
745
|
-
const v = raw;
|
|
746
|
-
this.db.prepare(`INSERT INTO schedule VALUES (?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET agent=excluded.agent,next_wake_at=excluded.next_wake_at,reason=excluded.reason,set_by=excluded.set_by`).run(v.id, v.agent, v.nextWakeAt, v.reason, v.setBy);
|
|
747
|
-
}
|
|
748
|
-
else if (projection === "wakes") {
|
|
749
|
-
const old = raw;
|
|
750
|
-
const existing = this.wake(old.id);
|
|
751
|
-
const active = old.status === "leased" || old.status === "running";
|
|
752
|
-
const v = {
|
|
753
|
-
...old,
|
|
754
|
-
enqueuedSeq: old.enqueuedSeq ?? existing?.enqueuedSeq ?? sourceSeq,
|
|
755
|
-
leaseToken: old.leaseToken !== undefined ? old.leaseToken : active ? existing?.leaseToken ?? `legacy:${old.id}:${old.attempt}` : null,
|
|
756
|
-
runnerPid: old.runnerPid !== undefined ? old.runnerPid : existing?.runnerPid ?? null,
|
|
757
|
-
};
|
|
758
|
-
this.db.prepare(`INSERT INTO wakes VALUES (?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET agent=excluded.agent,trigger_ref=excluded.trigger_ref,status=excluded.status,lease_until=excluded.lease_until,attempt=excluded.attempt,started_at=excluded.started_at,ended_at=excluded.ended_at,enqueued_seq=excluded.enqueued_seq,lease_token=excluded.lease_token,runner_pid=excluded.runner_pid`).run(v.id, v.agent, v.triggerRef, v.status, v.leaseUntil, v.attempt, v.startedAt, v.endedAt, v.enqueuedSeq, v.leaseToken, v.runnerPid);
|
|
759
|
-
}
|
|
760
|
-
else if (projection === "mailbox") {
|
|
761
|
-
const v = raw;
|
|
762
|
-
this.db.prepare(`INSERT INTO mailbox VALUES (?,?,?,?,json(?),?) ON CONFLICT(id) DO UPDATE SET to_agent=excluded.to_agent,from_agent=excluded.from_agent,level=excluded.level,body=excluded.body,read_at=excluded.read_at`).run(v.id, v.to, v.from, v.level, JSON.stringify(v.body), v.readAt);
|
|
763
|
-
}
|
|
764
|
-
else {
|
|
765
|
-
const old = raw;
|
|
766
|
-
const v = { ...old, connector: old.connector ?? "legacy" };
|
|
767
|
-
this.db.prepare(`INSERT INTO actions VALUES (?,?,?,?,json(?),?,json(?),?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET agent=excluded.agent,kind=excluded.kind,connector=excluded.connector,payload=excluded.payload,reason=excluded.reason,evidence=excluded.evidence,gated=excluded.gated,status=excluded.status,reconciled_at=excluded.reconciled_at,external_ref=excluded.external_ref,audit_advice=excluded.audit_advice,advice_acked=excluded.advice_acked`).run(v.id, v.agent, v.kind, v.connector, JSON.stringify(v.payload), v.reason, JSON.stringify(v.evidence), v.gated ? 1 : 0, v.status, v.reconciledAt, v.externalRef, v.auditAdvice === null ? null : JSON.stringify(v.auditAdvice), v.adviceAcked ? 1 : 0);
|
|
768
|
-
}
|
|
769
|
-
}
|
|
770
|
-
#legacyWorkRecord(goal) {
|
|
771
|
-
const handoff = this.lastEvent(goal.owner, "handoff.recorded");
|
|
772
|
-
const legacy = handoff?.data && typeof handoff.data === "object" && !Array.isArray(handoff.data) && !("goalId" in handoff.data) ? handoff.data : null;
|
|
773
|
-
const notes = this.readStream(`memory:${goal.owner}`).filter((event) => event.type === "memory.appended");
|
|
774
|
-
const list = (items) => items?.length ? items.map((item) => `- ${item}`).join("\n") : "None recorded.";
|
|
775
|
-
const decisions = notes.length ? notes.map((event) => `- ${String(event.data.note ?? "")} [event:${event.seq}]`).join("\n") : "None recorded.";
|
|
776
|
-
return {
|
|
777
|
-
content: `# Current State\n\nMigrated from the previous Goal continuity model.\n\n# Observations\n\n${list(legacy?.observations)}\n\n# Work Completed\n\n${list(legacy?.results)}\n\n# Decisions\n\n${decisions}\n\n# Blockers\n\n${legacy?.blocker ?? "None recorded."}\n\n# Next Steps\n\n${list(legacy?.nextSteps)}\n`,
|
|
778
|
-
evidence: [...(handoff ? [handoff.seq] : []), ...notes.map((event) => event.seq)],
|
|
779
|
-
};
|
|
780
|
-
}
|
|
781
|
-
#migrateLegacy() {
|
|
782
|
-
this.#transaction(() => {
|
|
783
|
-
const goalColumns = new Set(this.db.prepare("PRAGMA table_info(goals)").all().map((row) => row.name));
|
|
784
|
-
const observationSource = goalColumns.has("observation_method") ? "observation_method" : "NULL";
|
|
785
|
-
const verificationSource = goalColumns.has("verification_method") ? "verification_method" : observationSource;
|
|
786
|
-
this.db.exec(`PRAGMA defer_foreign_keys=ON;
|
|
787
|
-
DROP TABLE IF EXISTS work_records;
|
|
788
|
-
DROP TRIGGER IF EXISTS events_no_update; DROP TRIGGER IF EXISTS events_no_delete; DROP TRIGGER IF EXISTS events_fts_insert;
|
|
789
|
-
DROP TRIGGER IF EXISTS wakes_valid_transition; DROP TRIGGER IF EXISTS actions_valid_transition; DROP TRIGGER IF EXISTS goals_valid_transition;
|
|
790
|
-
DROP INDEX IF EXISTS events_agent_kind_seq; DROP INDEX IF EXISTS events_wake_seq; DROP INDEX IF EXISTS events_coalesced_trigger;
|
|
791
|
-
DROP INDEX IF EXISTS events_actor_type_seq; DROP INDEX IF EXISTS events_stream_seq;
|
|
792
|
-
DROP INDEX IF EXISTS wakes_one_active_agent; DROP INDEX IF EXISTS wakes_queue_order; DROP INDEX IF EXISTS schedule_due; DROP INDEX IF EXISTS actions_agent_status;
|
|
793
|
-
DROP TABLE IF EXISTS events_fts;
|
|
794
|
-
|
|
795
|
-
ALTER TABLE goals RENAME TO goals_legacy; ${createGoals}
|
|
796
|
-
INSERT INTO goals(id,parent_id,objective,observation_method,verification_method,owner,phase,revision) SELECT id,parent_id,objective,${observationSource},${verificationSource},owner,phase,revision FROM goals_legacy;
|
|
797
|
-
DROP TABLE goals_legacy;`);
|
|
798
|
-
const wakeColumns = new Set(this.db.prepare("PRAGMA table_info(wakes)").all().map((row) => row.name));
|
|
799
|
-
if (!wakeColumns.has("enqueued_seq")) {
|
|
800
|
-
this.db.exec(`ALTER TABLE wakes RENAME TO wakes_legacy; ${createWakes}
|
|
801
|
-
INSERT INTO wakes SELECT id,agent,trigger_ref,status,lease_until,attempt,started_at,ended_at,rowid,
|
|
802
|
-
CASE WHEN status IN ('leased','running') THEN 'legacy:'||id||':'||attempt ELSE NULL END,NULL FROM wakes_legacy;
|
|
803
|
-
DROP TABLE wakes_legacy;`);
|
|
804
|
-
}
|
|
805
|
-
const actionColumns = new Set(this.db.prepare("PRAGMA table_info(actions)").all().map((row) => row.name));
|
|
806
|
-
if (!actionColumns.has("connector")) {
|
|
807
|
-
this.db.exec(`ALTER TABLE actions RENAME TO actions_legacy; ${createActions}
|
|
808
|
-
INSERT INTO actions SELECT id,agent,kind,'legacy',payload,reason,evidence,gated,status,reconciled_at,external_ref,audit_advice,advice_acked FROM actions_legacy;
|
|
809
|
-
DROP TABLE actions_legacy;`);
|
|
810
|
-
}
|
|
811
|
-
const eventColumns = new Set(this.db.prepare("PRAGMA table_info(events)").all().map((row) => row.name));
|
|
812
|
-
if (!eventColumns.has("stream_id")) {
|
|
813
|
-
this.db.exec(`ALTER TABLE events RENAME TO events_legacy;
|
|
814
|
-
CREATE TABLE events (
|
|
815
|
-
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
816
|
-
stream_id TEXT NOT NULL,
|
|
817
|
-
stream_seq INTEGER NOT NULL CHECK(stream_seq > 0),
|
|
818
|
-
ts TEXT NOT NULL,
|
|
819
|
-
actor TEXT NOT NULL,
|
|
820
|
-
type TEXT NOT NULL,
|
|
821
|
-
data TEXT NOT NULL CHECK(json_valid(data)),
|
|
822
|
-
ignorable INTEGER CHECK(ignorable IS NULL OR ignorable = 1),
|
|
823
|
-
UNIQUE(stream_id, stream_seq)
|
|
824
|
-
) STRICT;
|
|
825
|
-
INSERT INTO events(seq,stream_id,stream_seq,ts,actor,type,data,ignorable)
|
|
826
|
-
SELECT seq,stream_id,ROW_NUMBER() OVER (PARTITION BY stream_id ORDER BY seq),ts,agent,kind,data,NULL FROM (
|
|
827
|
-
SELECT seq,ts,agent,kind,data,CASE WHEN wake_id IS NULL THEN 'control:'||agent ELSE 'wake:'||wake_id END AS stream_id FROM events_legacy
|
|
828
|
-
);
|
|
829
|
-
DROP TABLE events_legacy;`);
|
|
830
|
-
}
|
|
831
|
-
else if (!eventColumns.has("ignorable")) {
|
|
832
|
-
this.db.exec("ALTER TABLE events ADD COLUMN ignorable INTEGER CHECK(ignorable IS NULL OR ignorable = 1)");
|
|
833
|
-
}
|
|
834
|
-
this.db.exec(createWorkRecords);
|
|
835
|
-
for (const goal of this.goals()) {
|
|
836
|
-
if (!this.workRecord(goal.id))
|
|
837
|
-
this.#createWorkRecord(goal, "supervisor", `migration:work-record:${goal.id}`, undefined, this.#legacyWorkRecord(goal));
|
|
838
|
-
}
|
|
839
|
-
this.db.exec(`${indexesAndTriggers} INSERT INTO events_fts(events_fts) VALUES('rebuild'); PRAGMA user_version=${SQLITE_SCHEMA_VERSION};`);
|
|
840
|
-
});
|
|
841
|
-
}
|
|
842
|
-
#transaction(fn) {
|
|
843
|
-
this.db.exec("BEGIN IMMEDIATE");
|
|
844
|
-
try {
|
|
845
|
-
const result = fn();
|
|
846
|
-
this.db.exec("COMMIT");
|
|
847
|
-
return result;
|
|
848
|
-
}
|
|
849
|
-
catch (error) {
|
|
850
|
-
this.db.exec("ROLLBACK");
|
|
851
|
-
throw error;
|
|
852
|
-
}
|
|
853
|
-
}
|
|
854
|
-
#now() { return this.#clock.now().toISOString(); }
|
|
855
|
-
}
|
|
856
|
-
function mapEvent(r) { return { seq: Number(r.seq), streamId: String(r.stream_id), streamSeq: Number(r.stream_seq), ts: String(r.ts), actor: String(r.actor), type: String(r.type), data: JSON.parse(String(r.data)), ...(Number(r.ignorable) === 1 ? { ignorable: true } : {}) }; }
|
|
857
|
-
function normalizeGoal(goal) { return { ...goal, observationMethod: goal.observationMethod ?? null, verificationMethod: goal.verificationMethod === undefined ? goal.observationMethod ?? null : goal.verificationMethod }; }
|
|
858
|
-
function mapGoal(r) { return { id: String(r.id), parentId: r.parent_id === null ? null : String(r.parent_id), objective: String(r.objective), observationMethod: r.observation_method === null || r.observation_method === undefined ? null : String(r.observation_method), verificationMethod: r.verification_method === null || r.verification_method === undefined ? null : String(r.verification_method), owner: String(r.owner), phase: String(r.phase), revision: Number(r.revision) }; }
|
|
859
|
-
function mapWorkRecord(r) { return { goalId: String(r.goal_id), recordRevision: Number(r.record_revision), goalRevision: Number(r.goal_revision), content: String(r.content), updatedBy: String(r.updated_by), updatedInTurn: String(r.updated_in_turn), updatedInWake: r.updated_in_wake === null ? null : String(r.updated_in_wake), updatedAt: String(r.updated_at), reason: String(r.reason), evidence: JSON.parse(String(r.evidence)), lastEventSeq: Number(r.last_event_seq) }; }
|
|
860
|
-
function mapWorkRecordEvent(event) { const data = event.data; if (!data.snapshot)
|
|
861
|
-
throw new Error(`work record event ${event.seq} has no snapshot`); return { ...data.snapshot, lastEventSeq: event.seq }; }
|
|
862
|
-
function initialWorkRecord() { return "# Current State\n\nGoal created. Work has not started.\n\n# Observations\n\n# Work Completed\n\n# Decisions\n\n# Blockers\n\n# Next Steps\n"; }
|
|
863
|
-
function lineDiff(from, to) {
|
|
864
|
-
const before = from.split("\n");
|
|
865
|
-
const after = to.split("\n");
|
|
866
|
-
const lines = [];
|
|
867
|
-
for (let index = 0; index < Math.max(before.length, after.length); index += 1) {
|
|
868
|
-
if (before[index] === after[index]) {
|
|
869
|
-
if (before[index] !== undefined)
|
|
870
|
-
lines.push(` ${before[index]}`);
|
|
871
|
-
continue;
|
|
872
|
-
}
|
|
873
|
-
if (before[index] !== undefined)
|
|
874
|
-
lines.push(`-${before[index]}`);
|
|
875
|
-
if (after[index] !== undefined)
|
|
876
|
-
lines.push(`+${after[index]}`);
|
|
877
|
-
}
|
|
878
|
-
return lines.join("\n");
|
|
879
|
-
}
|
|
880
|
-
function mapSchedule(r) { return { id: String(r.id), agent: String(r.agent), nextWakeAt: String(r.next_wake_at), reason: String(r.reason), setBy: String(r.set_by) }; }
|
|
881
|
-
function mapWake(r) { return { id: String(r.id), agent: String(r.agent), triggerRef: String(r.trigger_ref), status: String(r.status), leaseUntil: r.lease_until === null ? null : String(r.lease_until), attempt: Number(r.attempt), startedAt: r.started_at === null ? null : String(r.started_at), endedAt: r.ended_at === null ? null : String(r.ended_at), enqueuedSeq: Number(r.enqueued_seq), leaseToken: r.lease_token === null ? null : String(r.lease_token), runnerPid: r.runner_pid === null ? null : Number(r.runner_pid) }; }
|
|
882
|
-
function mapMail(r) { return { id: String(r.id), to: String(r.to_agent), from: String(r.from_agent), level: String(r.level), body: JSON.parse(String(r.body)), readAt: r.read_at === null ? null : String(r.read_at) }; }
|
|
883
|
-
function mapAction(r) { return { id: String(r.id), agent: String(r.agent), kind: String(r.kind), connector: String(r.connector), payload: JSON.parse(String(r.payload)), reason: String(r.reason), evidence: JSON.parse(String(r.evidence)), gated: Boolean(r.gated), status: String(r.status), reconciledAt: r.reconciled_at === null ? null : String(r.reconciled_at), externalRef: r.external_ref === null ? null : String(r.external_ref), auditAdvice: r.audit_advice === null ? null : JSON.parse(String(r.audit_advice)), adviceAcked: Boolean(r.advice_acked) }; }
|
|
884
|
-
//# sourceMappingURL=index.js.map
|