hiveagents-runtime 0.0.0-stage → 0.1.0-beta.3
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/LICENSE +202 -0
- package/README.md +89 -2
- package/dist/adapter-kit.d.ts +37 -0
- package/dist/adapter-kit.js +34 -0
- package/dist/adapter-kit.js.map +1 -0
- package/dist/agent-Bj5YPrO7.d.ts +169 -0
- package/dist/agent-D6OXR7UF.js +24 -0
- package/dist/agent-D6OXR7UF.js.map +1 -0
- package/dist/agent-readiness-KSGNKTGK.js +19 -0
- package/dist/agent-readiness-KSGNKTGK.js.map +1 -0
- package/dist/capture-runtime-GP6NZ2ee.d.ts +54 -0
- package/dist/chunk-2RK74GCA.js +2397 -0
- package/dist/chunk-2RK74GCA.js.map +1 -0
- package/dist/chunk-3TIYA3K5.js +55 -0
- package/dist/chunk-3TIYA3K5.js.map +1 -0
- package/dist/chunk-6FIXXWNM.js +1 -0
- package/dist/chunk-6FIXXWNM.js.map +1 -0
- package/dist/chunk-6XIJW65Q.js +52 -0
- package/dist/chunk-6XIJW65Q.js.map +1 -0
- package/dist/chunk-7LDQKJKI.js +248 -0
- package/dist/chunk-7LDQKJKI.js.map +1 -0
- package/dist/chunk-CPN4DOXH.js +115 -0
- package/dist/chunk-CPN4DOXH.js.map +1 -0
- package/dist/chunk-DAXPAV2L.js +810 -0
- package/dist/chunk-DAXPAV2L.js.map +1 -0
- package/dist/chunk-DQEMIGKC.js +291 -0
- package/dist/chunk-DQEMIGKC.js.map +1 -0
- package/dist/chunk-DZFFGUIA.js +81 -0
- package/dist/chunk-DZFFGUIA.js.map +1 -0
- package/dist/chunk-EEUYQFCP.js +106 -0
- package/dist/chunk-EEUYQFCP.js.map +1 -0
- package/dist/chunk-G6JV7WV6.js +521 -0
- package/dist/chunk-G6JV7WV6.js.map +1 -0
- package/dist/chunk-GFVYNPLS.js +118 -0
- package/dist/chunk-GFVYNPLS.js.map +1 -0
- package/dist/chunk-GS5U3KUN.js +201 -0
- package/dist/chunk-GS5U3KUN.js.map +1 -0
- package/dist/chunk-HB7FBSH2.js +960 -0
- package/dist/chunk-HB7FBSH2.js.map +1 -0
- package/dist/chunk-HZFZX5A3.js +21 -0
- package/dist/chunk-HZFZX5A3.js.map +1 -0
- package/dist/chunk-J7VAYJKM.js +595 -0
- package/dist/chunk-J7VAYJKM.js.map +1 -0
- package/dist/chunk-NCNSHOF7.js +52 -0
- package/dist/chunk-NCNSHOF7.js.map +1 -0
- package/dist/chunk-RH5A5U7G.js +202 -0
- package/dist/chunk-RH5A5U7G.js.map +1 -0
- package/dist/chunk-RX3XZENU.js +385 -0
- package/dist/chunk-RX3XZENU.js.map +1 -0
- package/dist/chunk-RXU2Q2HF.js +49 -0
- package/dist/chunk-RXU2Q2HF.js.map +1 -0
- package/dist/chunk-TG7NTMTR.js +208 -0
- package/dist/chunk-TG7NTMTR.js.map +1 -0
- package/dist/chunk-TWGEYWMO.js +1217 -0
- package/dist/chunk-TWGEYWMO.js.map +1 -0
- package/dist/chunk-UZPDDQVJ.js +2910 -0
- package/dist/chunk-UZPDDQVJ.js.map +1 -0
- package/dist/chunk-WMKO5XOE.js +601 -0
- package/dist/chunk-WMKO5XOE.js.map +1 -0
- package/dist/chunk-WOQBVJH5.js +175 -0
- package/dist/chunk-WOQBVJH5.js.map +1 -0
- package/dist/chunk-WVT5SEKC.js +581 -0
- package/dist/chunk-WVT5SEKC.js.map +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +26 -0
- package/dist/cli.js.map +1 -0
- package/dist/errors-BNHvvjn9.d.ts +98 -0
- package/dist/execution-halt-B8G0fOKS.d.ts +12 -0
- package/dist/execution-types-ClYYqPQP.d.ts +239 -0
- package/dist/host-ledger-VPRWVVOS.js +25 -0
- package/dist/host-ledger-VPRWVVOS.js.map +1 -0
- package/dist/hosted-runtime.d.ts +168 -0
- package/dist/hosted-runtime.js +858 -0
- package/dist/hosted-runtime.js.map +1 -0
- package/dist/index-B86C6VAD.d.ts +41 -0
- package/dist/index.d.ts +344 -0
- package/dist/index.js +8825 -0
- package/dist/index.js.map +1 -0
- package/dist/memory-items-BSTC0_R0.d.ts +28 -0
- package/dist/memory-tools.d.ts +222 -0
- package/dist/memory-tools.js +923 -0
- package/dist/memory-tools.js.map +1 -0
- package/dist/orchestration/dynamic.d.ts +854 -0
- package/dist/orchestration/dynamic.js +3150 -0
- package/dist/orchestration/dynamic.js.map +1 -0
- package/dist/orchestration/graph.d.ts +11 -0
- package/dist/orchestration/graph.js +9 -0
- package/dist/orchestration/graph.js.map +1 -0
- package/dist/orchestration/index.d.ts +2385 -0
- package/dist/orchestration/index.js +6409 -0
- package/dist/orchestration/index.js.map +1 -0
- package/dist/orchestration/log.d.ts +301 -0
- package/dist/orchestration/log.js +3058 -0
- package/dist/orchestration/log.js.map +1 -0
- package/dist/orchestration/memory.d.ts +711 -0
- package/dist/orchestration/memory.js +27 -0
- package/dist/orchestration/memory.js.map +1 -0
- package/dist/provider-DX5Mf0uq.d.ts +151 -0
- package/dist/routing/index.d.ts +29 -0
- package/dist/routing/index.js +386 -0
- package/dist/routing/index.js.map +1 -0
- package/dist/routing/learning/index.d.ts +433 -0
- package/dist/routing/learning/index.js +2502 -0
- package/dist/routing/learning/index.js.map +1 -0
- package/dist/runtime-BSjrnxeF.d.ts +283 -0
- package/dist/runtime-OISPXS4I.js +19 -0
- package/dist/runtime-OISPXS4I.js.map +1 -0
- package/dist/store-types-2YdceOMy.d.ts +78 -0
- package/dist/types-BB7KqceP.d.ts +52 -0
- package/dist/types-CIqkKXix.d.ts +86 -0
- package/dist/types-DTFc1qO6.d.ts +1065 -0
- package/dist/types-DYex3p7_.d.ts +88 -0
- package/docs/licenses/ruflo-memory-MIT.txt +21 -0
- package/docs/releases/0.1.0-beta.3.md +13 -0
- package/package.json +114 -4
|
@@ -0,0 +1,3058 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AGENT_METADATA_SCHEMA,
|
|
3
|
+
CAPTURE_OPERATION_SCHEMA,
|
|
4
|
+
LogStoreError,
|
|
5
|
+
MAX_EVENT_BYTES,
|
|
6
|
+
boundedDataArray,
|
|
7
|
+
boundedInteger,
|
|
8
|
+
capture,
|
|
9
|
+
captureIdentity,
|
|
10
|
+
captureLogCommit,
|
|
11
|
+
createRequiredLogCapture,
|
|
12
|
+
decodeCaptureMetadata,
|
|
13
|
+
decodeEntry,
|
|
14
|
+
digest,
|
|
15
|
+
entryBody,
|
|
16
|
+
genesis,
|
|
17
|
+
invalidCapture,
|
|
18
|
+
isLogStoreError,
|
|
19
|
+
logError,
|
|
20
|
+
safeFailure
|
|
21
|
+
} from "../chunk-J7VAYJKM.js";
|
|
22
|
+
import {
|
|
23
|
+
decisionHash,
|
|
24
|
+
sameDecisionBinding,
|
|
25
|
+
snapshotBinding,
|
|
26
|
+
validateDecisionRecord
|
|
27
|
+
} from "../chunk-WOQBVJH5.js";
|
|
28
|
+
import {
|
|
29
|
+
cloneSteps,
|
|
30
|
+
identity,
|
|
31
|
+
validateCheckpoint
|
|
32
|
+
} from "../chunk-CPN4DOXH.js";
|
|
33
|
+
import "../chunk-GS5U3KUN.js";
|
|
34
|
+
import {
|
|
35
|
+
canonical,
|
|
36
|
+
freeze,
|
|
37
|
+
hash,
|
|
38
|
+
identifier,
|
|
39
|
+
method,
|
|
40
|
+
object,
|
|
41
|
+
ownObject
|
|
42
|
+
} from "../chunk-EEUYQFCP.js";
|
|
43
|
+
import {
|
|
44
|
+
ExecutionHaltedError,
|
|
45
|
+
isExecutionHalted,
|
|
46
|
+
rethrowExecutionHalt
|
|
47
|
+
} from "../chunk-NCNSHOF7.js";
|
|
48
|
+
import "../chunk-TG7NTMTR.js";
|
|
49
|
+
import {
|
|
50
|
+
dependencyWaves
|
|
51
|
+
} from "../chunk-DZFFGUIA.js";
|
|
52
|
+
|
|
53
|
+
// src/orchestration/log/sqlite-store.ts
|
|
54
|
+
import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
|
|
55
|
+
|
|
56
|
+
// src/orchestration/log/configuration.ts
|
|
57
|
+
import { types as types2 } from "node:util";
|
|
58
|
+
|
|
59
|
+
// src/orchestration/log/sqlite-storage.ts
|
|
60
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
61
|
+
import { closeSync, fsyncSync, linkSync, lstatSync, openSync, realpathSync, unlinkSync } from "node:fs";
|
|
62
|
+
import { dirname, isAbsolute, resolve } from "node:path";
|
|
63
|
+
import { DatabaseSync } from "node:sqlite";
|
|
64
|
+
import { types } from "node:util";
|
|
65
|
+
|
|
66
|
+
// src/orchestration/log/sqlite-schema.ts
|
|
67
|
+
import { randomUUID } from "node:crypto";
|
|
68
|
+
var LOG_APPLICATION_ID = 1329680972;
|
|
69
|
+
var LOG_SCHEMA_VERSION = 1;
|
|
70
|
+
var integer = "BETWEEN 1 AND 9007199254740991";
|
|
71
|
+
var LOG_DDL = Object.freeze([
|
|
72
|
+
`CREATE TABLE oar_log_meta (id INTEGER PRIMARY KEY CHECK(id=1), descriptor_json TEXT NOT NULL,
|
|
73
|
+
descriptor_digest TEXT NOT NULL, head_sequence INTEGER NOT NULL CHECK(head_sequence BETWEEN 0 AND 9007199254740991),
|
|
74
|
+
head_digest TEXT NOT NULL) STRICT`,
|
|
75
|
+
`CREATE TABLE oar_log_requests (request_id TEXT PRIMARY KEY NOT NULL, commit_digest TEXT NOT NULL,
|
|
76
|
+
first_sequence INTEGER NOT NULL CHECK(first_sequence ${integer}), last_sequence INTEGER NOT NULL CHECK(last_sequence ${integer}),
|
|
77
|
+
count INTEGER NOT NULL CHECK(count BETWEEN 1 AND 256 AND last_sequence=first_sequence+count-1),
|
|
78
|
+
receipt_json TEXT NOT NULL, receipt_digest TEXT NOT NULL) STRICT`,
|
|
79
|
+
`CREATE TABLE oar_log_events (sequence INTEGER PRIMARY KEY CHECK(sequence ${integer}),
|
|
80
|
+
request_id TEXT NOT NULL REFERENCES oar_log_requests(request_id), ordinal INTEGER NOT NULL CHECK(ordinal BETWEEN 1 AND 256),
|
|
81
|
+
source_id TEXT NOT NULL, system_id TEXT NOT NULL, generation INTEGER NOT NULL CHECK(generation ${integer}),
|
|
82
|
+
run_id TEXT NOT NULL, agent_id TEXT NOT NULL, schema_id TEXT NOT NULL, schema_version INTEGER NOT NULL,
|
|
83
|
+
previous_digest TEXT NOT NULL, digest TEXT NOT NULL, body_json TEXT NOT NULL CHECK(json_valid(body_json)
|
|
84
|
+
AND source_id IS json_extract(body_json,'$.sourceId') AND sequence IS json_extract(body_json,'$.sequence')
|
|
85
|
+
AND request_id IS json_extract(body_json,'$.requestId') AND ordinal IS json_extract(body_json,'$.ordinal')
|
|
86
|
+
AND previous_digest IS json_extract(body_json,'$.previousDigest')
|
|
87
|
+
AND system_id IS json_extract(body_json,'$.record.identity.systemId')
|
|
88
|
+
AND generation IS json_extract(body_json,'$.record.identity.generation')
|
|
89
|
+
AND run_id IS json_extract(body_json,'$.record.identity.runId') AND agent_id IS json_extract(body_json,'$.record.identity.agentId')
|
|
90
|
+
AND schema_id IS json_extract(body_json,'$.record.schema.id') AND schema_version IS json_extract(body_json,'$.record.schema.version')),
|
|
91
|
+
UNIQUE(request_id,ordinal)) STRICT`,
|
|
92
|
+
`CREATE TABLE oar_log_payloads (sequence INTEGER PRIMARY KEY REFERENCES oar_log_events(sequence),
|
|
93
|
+
reference_json TEXT NOT NULL, reference_digest TEXT NOT NULL) STRICT`,
|
|
94
|
+
...["events", "requests", "payloads"].flatMap((table) => ["UPDATE", "DELETE"].map((operation) => `CREATE TRIGGER oar_log_${table}_${operation.toLowerCase()} BEFORE ${operation} ON oar_log_${table} BEGIN SELECT RAISE(ABORT,'immutable execution log'); END`)),
|
|
95
|
+
`CREATE TRIGGER oar_log_meta_delete BEFORE DELETE ON oar_log_meta BEGIN SELECT RAISE(ABORT,'immutable execution log'); END`,
|
|
96
|
+
`CREATE TRIGGER oar_log_meta_descriptor BEFORE UPDATE OF descriptor_json,descriptor_digest,id ON oar_log_meta BEGIN SELECT RAISE(ABORT,'immutable execution log'); END`
|
|
97
|
+
]);
|
|
98
|
+
var expected = new Map(LOG_DDL.map((sql) => [sql.match(/^CREATE (?:TABLE|TRIGGER) (\w+)/)[1], sql]));
|
|
99
|
+
expected.set("sqlite_autoindex_oar_log_requests_1", "");
|
|
100
|
+
expected.set("sqlite_autoindex_oar_log_events_1", "");
|
|
101
|
+
function installLogSchema(db, systemId) {
|
|
102
|
+
const existing = db.prepare("SELECT name FROM main.sqlite_schema WHERE name GLOB 'oar_log_*'").all();
|
|
103
|
+
if (existing.length) return validateLogSchema(db, systemId);
|
|
104
|
+
for (const sql of LOG_DDL) db.exec(sql);
|
|
105
|
+
const source = Object.freeze({ format: 1, sourceId: randomUUID(), systemId });
|
|
106
|
+
const encoded = canonical(source);
|
|
107
|
+
db.prepare("INSERT INTO main.oar_log_meta VALUES(1,?,?,0,?)").run(encoded, digest(encoded), genesis(source));
|
|
108
|
+
return source;
|
|
109
|
+
}
|
|
110
|
+
function validateLogSchema(db, systemId, standalone = false, full = true) {
|
|
111
|
+
const rows = db.prepare(`SELECT name,tbl_name,sql FROM main.sqlite_schema ${standalone ? "" : "WHERE name GLOB 'oar_log_*' OR tbl_name GLOB 'oar_log_*'"}`).all();
|
|
112
|
+
if (rows.length !== expected.size || rows.some((row) => !expected.has(String(row.name)) || (row.sql ?? "") !== expected.get(String(row.name)))) logError("INTEGRITY");
|
|
113
|
+
if (standalone && (db.prepare("PRAGMA main.application_id").get().application_id !== LOG_APPLICATION_ID || db.prepare("PRAGMA main.user_version").get().user_version !== LOG_SCHEMA_VERSION)) logError("INTEGRITY");
|
|
114
|
+
if (full && (db.prepare("PRAGMA main.quick_check").all().some((row) => row.quick_check !== "ok") || db.prepare("PRAGMA main.foreign_key_check(oar_log_events)").all().length || db.prepare("PRAGMA main.foreign_key_check(oar_log_payloads)").all().length)) logError("INTEGRITY");
|
|
115
|
+
const meta = db.prepare("SELECT descriptor_json,descriptor_digest FROM main.oar_log_meta WHERE id=1").get();
|
|
116
|
+
if (!meta || typeof meta.descriptor_json !== "string" || meta.descriptor_json.length > 2048 || digest(meta.descriptor_json) !== meta.descriptor_digest) logError("INTEGRITY");
|
|
117
|
+
try {
|
|
118
|
+
const source = JSON.parse(meta.descriptor_json);
|
|
119
|
+
if (!source || canonical(source) !== meta.descriptor_json || Object.keys(source).sort().join(",") !== "format,sourceId,systemId" || source.format !== 1 || typeof source.sourceId !== "string" || !/^[\da-f-]{36}$/.test(source.sourceId) || source.systemId !== systemId) logError("INTEGRITY");
|
|
120
|
+
return Object.freeze(source);
|
|
121
|
+
} catch {
|
|
122
|
+
return logError("INTEGRITY");
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// src/orchestration/log/sqlite-storage.ts
|
|
127
|
+
function validPath(path) {
|
|
128
|
+
if (typeof path !== "string" || !isAbsolute(path) || path.includes("\0") || resolve(path) !== path) logError("INVALID_INPUT");
|
|
129
|
+
}
|
|
130
|
+
function stat(path) {
|
|
131
|
+
const value = lstatSync(path, { bigint: true });
|
|
132
|
+
if (!value.isFile() || value.isSymbolicLink()) logError("INTEGRITY");
|
|
133
|
+
return value;
|
|
134
|
+
}
|
|
135
|
+
var checkedRuntime = false;
|
|
136
|
+
var nativeTransactionGetter;
|
|
137
|
+
function transactionGetter(db, required) {
|
|
138
|
+
if (!checkedRuntime) {
|
|
139
|
+
const sample = new DatabaseSync(":memory:");
|
|
140
|
+
try {
|
|
141
|
+
nativeTransactionGetter = Object.getOwnPropertyDescriptor(sample, "isTransaction")?.get;
|
|
142
|
+
checkedRuntime = true;
|
|
143
|
+
} finally {
|
|
144
|
+
sample.close();
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (!nativeTransactionGetter) {
|
|
148
|
+
if (required) logError("UNSUPPORTED_RUNTIME");
|
|
149
|
+
return void 0;
|
|
150
|
+
}
|
|
151
|
+
const getter = nativeTransactionGetter.bind(db);
|
|
152
|
+
getter();
|
|
153
|
+
return getter;
|
|
154
|
+
}
|
|
155
|
+
function publishLog(path, systemId) {
|
|
156
|
+
try {
|
|
157
|
+
lstatSync(path);
|
|
158
|
+
return;
|
|
159
|
+
} catch (error) {
|
|
160
|
+
if (error.code !== "ENOENT") throw error;
|
|
161
|
+
}
|
|
162
|
+
const temporary = `${path}.${randomUUID2()}.initializing`;
|
|
163
|
+
closeSync(openSync(temporary, "wx", 384));
|
|
164
|
+
let db;
|
|
165
|
+
try {
|
|
166
|
+
db = new DatabaseSync(temporary);
|
|
167
|
+
db.exec("PRAGMA foreign_keys=ON; PRAGMA synchronous=FULL; BEGIN IMMEDIATE");
|
|
168
|
+
installLogSchema(db, systemId);
|
|
169
|
+
db.exec(`PRAGMA application_id=${LOG_APPLICATION_ID}; PRAGMA user_version=${LOG_SCHEMA_VERSION}; COMMIT`);
|
|
170
|
+
db.close();
|
|
171
|
+
db = void 0;
|
|
172
|
+
const fd = openSync(temporary, "r");
|
|
173
|
+
try {
|
|
174
|
+
fsyncSync(fd);
|
|
175
|
+
} finally {
|
|
176
|
+
closeSync(fd);
|
|
177
|
+
}
|
|
178
|
+
try {
|
|
179
|
+
linkSync(temporary, path);
|
|
180
|
+
} catch (error) {
|
|
181
|
+
if (error.code !== "EEXIST") throw error;
|
|
182
|
+
}
|
|
183
|
+
const parent = openSync(dirname(path), "r");
|
|
184
|
+
try {
|
|
185
|
+
fsyncSync(parent);
|
|
186
|
+
} finally {
|
|
187
|
+
closeSync(parent);
|
|
188
|
+
}
|
|
189
|
+
} finally {
|
|
190
|
+
db?.close();
|
|
191
|
+
unlinkSync(temporary);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
var sdkOwnedConnections = /* @__PURE__ */ new WeakSet();
|
|
195
|
+
function markSdkOwnedConnection(db) {
|
|
196
|
+
sdkOwnedConnections.add(db);
|
|
197
|
+
}
|
|
198
|
+
var LogConnection = class {
|
|
199
|
+
constructor(db, path, systemId, standalone, enroll = false) {
|
|
200
|
+
this.db = db;
|
|
201
|
+
this.path = path;
|
|
202
|
+
this.systemId = systemId;
|
|
203
|
+
this.standalone = standalone;
|
|
204
|
+
this.#alwaysFull = enroll && !sdkOwnedConnections.has(db);
|
|
205
|
+
try {
|
|
206
|
+
validPath(path);
|
|
207
|
+
if (types.isProxy(db) || !(db instanceof DatabaseSync)) logError("INVALID_INPUT");
|
|
208
|
+
this.#transactionGetter = transactionGetter(db, !standalone);
|
|
209
|
+
if (enroll && !this.inTransaction()) logError("TRANSACTION_REQUIRED");
|
|
210
|
+
const info = stat(path);
|
|
211
|
+
this.#dev = info.dev;
|
|
212
|
+
this.#ino = info.ino;
|
|
213
|
+
this.#canonicalPath = realpathSync(path);
|
|
214
|
+
const actual = db.prepare("PRAGMA database_list").all().find((row) => row.name === "main");
|
|
215
|
+
if (!actual || realpathSync(String(actual.file)) !== this.#canonicalPath) logError("INTEGRITY");
|
|
216
|
+
const dataVersion = Number(db.prepare("PRAGMA main.data_version").get().data_version);
|
|
217
|
+
if (enroll) {
|
|
218
|
+
let began = false;
|
|
219
|
+
try {
|
|
220
|
+
db.exec("SAVEPOINT oar_log_enroll");
|
|
221
|
+
began = true;
|
|
222
|
+
installLogSchema(db, systemId);
|
|
223
|
+
this.source = validateLogSchema(db, systemId, standalone);
|
|
224
|
+
db.exec("RELEASE oar_log_enroll");
|
|
225
|
+
began = false;
|
|
226
|
+
} catch (error) {
|
|
227
|
+
if (began) {
|
|
228
|
+
try {
|
|
229
|
+
db.exec("ROLLBACK TO oar_log_enroll; RELEASE oar_log_enroll");
|
|
230
|
+
} catch {
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
throw error;
|
|
234
|
+
}
|
|
235
|
+
} else this.source = validateLogSchema(db, systemId, standalone);
|
|
236
|
+
this.#dataVersion = dataVersion;
|
|
237
|
+
this.storageDigest = digest(`oar-log-storage-v1
|
|
238
|
+
${this.#canonicalPath}
|
|
239
|
+
${info.dev}
|
|
240
|
+
${info.ino}`);
|
|
241
|
+
} catch (error) {
|
|
242
|
+
safeFailure(error);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
db;
|
|
246
|
+
path;
|
|
247
|
+
systemId;
|
|
248
|
+
standalone;
|
|
249
|
+
source;
|
|
250
|
+
storageDigest;
|
|
251
|
+
#dev;
|
|
252
|
+
#ino;
|
|
253
|
+
#canonicalPath;
|
|
254
|
+
#transactionGetter;
|
|
255
|
+
#closed = false;
|
|
256
|
+
#dataVersion;
|
|
257
|
+
#ownedTransaction = false;
|
|
258
|
+
// Enrolled (caller-owned) connections run application SQL on this same
|
|
259
|
+
// connection, and data_version never reports same-connection commits: a caller
|
|
260
|
+
// can disable foreign keys, commit an orphan and re-enable them unseen. Those
|
|
261
|
+
// connections keep the full check on every assert.
|
|
262
|
+
#alwaysFull;
|
|
263
|
+
inTransaction() {
|
|
264
|
+
return this.#ownedTransaction || (this.#transactionGetter?.() ?? false);
|
|
265
|
+
}
|
|
266
|
+
assert(insideTransaction = false) {
|
|
267
|
+
if (this.#closed) logError("CLOSED");
|
|
268
|
+
try {
|
|
269
|
+
const info = stat(this.path);
|
|
270
|
+
if (info.dev !== this.#dev || info.ino !== this.#ino || realpathSync(this.path) !== this.#canonicalPath) logError("INTEGRITY");
|
|
271
|
+
const dataVersion = Number(this.db.prepare("PRAGMA main.data_version").get().data_version);
|
|
272
|
+
const source = validateLogSchema(this.db, this.systemId, this.standalone, this.#alwaysFull || dataVersion !== this.#dataVersion);
|
|
273
|
+
if (source.sourceId !== this.source.sourceId) logError("INTEGRITY");
|
|
274
|
+
if (!insideTransaction && !this.inTransaction()) this.#dataVersion = dataVersion;
|
|
275
|
+
} catch (error) {
|
|
276
|
+
safeFailure(error);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
close() {
|
|
280
|
+
if (!this.#closed) {
|
|
281
|
+
this.#closed = true;
|
|
282
|
+
if (this.standalone) this.db.close();
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
/** Only rolls back a transaction that this invocation successfully began. */
|
|
286
|
+
transaction(body, write2 = false) {
|
|
287
|
+
this.assert();
|
|
288
|
+
if (this.inTransaction()) {
|
|
289
|
+
const result = body();
|
|
290
|
+
this.assert();
|
|
291
|
+
return result;
|
|
292
|
+
}
|
|
293
|
+
let began = false;
|
|
294
|
+
try {
|
|
295
|
+
this.db.exec(write2 ? "BEGIN IMMEDIATE" : "BEGIN");
|
|
296
|
+
began = true;
|
|
297
|
+
this.#ownedTransaction = true;
|
|
298
|
+
const result = body();
|
|
299
|
+
this.assert();
|
|
300
|
+
this.db.exec("COMMIT");
|
|
301
|
+
return result;
|
|
302
|
+
} catch (error) {
|
|
303
|
+
if (began) {
|
|
304
|
+
try {
|
|
305
|
+
if (!this.#transactionGetter || this.inTransaction()) this.db.exec("ROLLBACK");
|
|
306
|
+
} catch {
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
return safeFailure(error);
|
|
310
|
+
} finally {
|
|
311
|
+
if (began) this.#ownedTransaction = false;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
};
|
|
315
|
+
|
|
316
|
+
// src/orchestration/log/configuration.ts
|
|
317
|
+
function configuration(input2) {
|
|
318
|
+
try {
|
|
319
|
+
input2 = ownObject(input2, ["databasePath", "systemId", "busyTimeoutMs", "maxPending", "supportedSchemas", "payloadVerifier"]);
|
|
320
|
+
validPath(input2.databasePath);
|
|
321
|
+
identifier(input2.systemId);
|
|
322
|
+
const busyTimeoutMs = input2.busyTimeoutMs ?? 5e3, maxPending = input2.maxPending ?? 2;
|
|
323
|
+
if (!Number.isSafeInteger(busyTimeoutMs) || busyTimeoutMs < 0 || busyTimeoutMs > 6e4 || !Number.isSafeInteger(maxPending) || maxPending < 1 || maxPending > 64) logError("INVALID_INPUT");
|
|
324
|
+
const schemas = /* @__PURE__ */ new Set(), supported = input2.supportedSchemas ?? [];
|
|
325
|
+
if (types2.isProxy(supported) || !Array.isArray(supported) || Object.getPrototypeOf(supported) !== Array.prototype || supported.length > 256 || Object.getOwnPropertySymbols(supported).length || Object.keys(supported).length !== supported.length) logError("INVALID_INPUT");
|
|
326
|
+
for (let index = 0; index < supported.length; index++) {
|
|
327
|
+
const descriptor = Object.getOwnPropertyDescriptor(supported, String(index));
|
|
328
|
+
if (!descriptor || !Object.hasOwn(descriptor, "value")) logError("INVALID_INPUT");
|
|
329
|
+
const schema = ownObject(descriptor.value, ["id", "version"]);
|
|
330
|
+
object(schema);
|
|
331
|
+
identifier(schema.id);
|
|
332
|
+
if (Object.keys(schema).length !== 2 || !Number.isSafeInteger(schema.version) || Number(schema.version) < 1) logError("INVALID_INPUT");
|
|
333
|
+
schemas.add(canonical(schema));
|
|
334
|
+
}
|
|
335
|
+
const verify = input2.payloadVerifier === void 0 ? void 0 : method(input2.payloadVerifier, "verify");
|
|
336
|
+
return Object.freeze({ databasePath: input2.databasePath, systemId: input2.systemId, busyTimeoutMs, maxPending, schemas, verify });
|
|
337
|
+
} catch {
|
|
338
|
+
return logError("INVALID_INPUT");
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
async function verifyReference(verify, ref, source, signal) {
|
|
342
|
+
if (!verify) return "unverified";
|
|
343
|
+
try {
|
|
344
|
+
const result = await verify(ref, signal ? { signal } : {});
|
|
345
|
+
object(result, ["kind", "reference"]);
|
|
346
|
+
if (Object.keys(result).length !== 2 || !["verified", "missing", "corrupt"].includes(result.kind)) return "corrupt";
|
|
347
|
+
const checked = capture({ requestId: "verify", records: [{ identity: { systemId: ref.systemId, generation: ref.generation, runId: "verify", agentId: "verify", harness: { id: "verify", version: "1", digest: "0".repeat(64) } }, schema: { id: "verify", version: 1 }, type: "verify", causal: [], payload: { artifact: result.reference } }] }, source);
|
|
348
|
+
if (canonical(checked.records[0].payload) !== canonical({ artifact: ref })) return "corrupt";
|
|
349
|
+
return result.kind;
|
|
350
|
+
} catch {
|
|
351
|
+
return "unverified";
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
async function verifyCommit(commit, config, source, signal) {
|
|
355
|
+
for (const record of commit.records) if ("artifact" in record.payload) {
|
|
356
|
+
if (await verifyReference(config.verify, record.payload.artifact, source, signal) !== "verified") logError("PAYLOAD_UNAVAILABLE");
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// src/orchestration/log/records.ts
|
|
361
|
+
function readHead(db, source) {
|
|
362
|
+
const meta = db.prepare("SELECT head_sequence,head_digest FROM main.oar_log_meta WHERE id=1").get();
|
|
363
|
+
const rows = db.prepare("SELECT COUNT(*) AS count,MIN(sequence) AS first,MAX(sequence) AS last FROM main.oar_log_events").get();
|
|
364
|
+
if (!meta || !Number.isSafeInteger(meta.head_sequence) || Number(meta.head_sequence) < 0 || rows.count !== meta.head_sequence || Number(rows.count) > 0 && (rows.first !== 1 || rows.last !== meta.head_sequence)) logError("INTEGRITY");
|
|
365
|
+
try {
|
|
366
|
+
hash(meta.head_digest);
|
|
367
|
+
} catch {
|
|
368
|
+
return logError("INTEGRITY");
|
|
369
|
+
}
|
|
370
|
+
const expected3 = meta.head_sequence === 0 ? genesis(source) : db.prepare("SELECT digest FROM main.oar_log_events WHERE sequence=?").get(Number(meta.head_sequence))?.digest;
|
|
371
|
+
if (meta.head_digest !== expected3) logError("INTEGRITY");
|
|
372
|
+
if (db.prepare(`SELECT 1 FROM main.oar_log_requests r WHERE r.count !=
|
|
373
|
+
(SELECT COUNT(*) FROM main.oar_log_events e WHERE e.request_id=r.request_id)
|
|
374
|
+
OR r.first_sequence != (SELECT MIN(sequence) FROM main.oar_log_events e WHERE e.request_id=r.request_id)
|
|
375
|
+
OR r.last_sequence != (SELECT MAX(sequence) FROM main.oar_log_events e WHERE e.request_id=r.request_id) LIMIT 1`).get()) logError("INTEGRITY");
|
|
376
|
+
return Object.freeze({ sourceId: source.sourceId, sequence: Number(meta.head_sequence), digest: meta.head_digest });
|
|
377
|
+
}
|
|
378
|
+
function readRequestMetadata(db, requestId, source) {
|
|
379
|
+
const row = db.prepare(`SELECT commit_digest,first_sequence,last_sequence,count,receipt_digest,
|
|
380
|
+
CASE WHEN length(receipt_json)<4096 THEN receipt_json END AS receipt_json FROM main.oar_log_requests WHERE request_id=?`).get(requestId);
|
|
381
|
+
if (!row) return void 0;
|
|
382
|
+
try {
|
|
383
|
+
if (typeof row.receipt_json !== "string" || digest(row.receipt_json) !== row.receipt_digest || !Number.isSafeInteger(row.count) || Number(row.count) < 1 || Number(row.count) > 256 || !Number.isSafeInteger(row.first_sequence) || Number(row.first_sequence) < 1 || row.last_sequence !== Number(row.first_sequence) + Number(row.count) - 1) logError("INTEGRITY");
|
|
384
|
+
hash(row.commit_digest);
|
|
385
|
+
const first = db.prepare("SELECT digest FROM main.oar_log_events WHERE sequence=?").get(Number(row.first_sequence));
|
|
386
|
+
const last = db.prepare("SELECT digest FROM main.oar_log_events WHERE sequence=?").get(Number(row.last_sequence));
|
|
387
|
+
if (!first || !last) logError("INTEGRITY");
|
|
388
|
+
const receipt = {
|
|
389
|
+
first: { sourceId: source.sourceId, sequence: Number(row.first_sequence), digest: first.digest },
|
|
390
|
+
head: { sourceId: source.sourceId, sequence: Number(row.last_sequence), digest: last.digest },
|
|
391
|
+
count: Number(row.count)
|
|
392
|
+
};
|
|
393
|
+
if (canonical(receipt) !== row.receipt_json) logError("INTEGRITY");
|
|
394
|
+
return {
|
|
395
|
+
first_sequence: Number(row.first_sequence),
|
|
396
|
+
last_sequence: Number(row.last_sequence),
|
|
397
|
+
count: Number(row.count),
|
|
398
|
+
commit_digest: row.commit_digest,
|
|
399
|
+
receipt_json: row.receipt_json,
|
|
400
|
+
receipt: freeze(receipt)
|
|
401
|
+
};
|
|
402
|
+
} catch {
|
|
403
|
+
return logError("INTEGRITY");
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
function readEntry(db, sequence, source) {
|
|
407
|
+
const row = db.prepare(`SELECT sequence,request_id,ordinal,source_id,system_id,generation,run_id,agent_id,schema_id,schema_version,
|
|
408
|
+
previous_digest,digest,CASE WHEN length(CAST(body_json AS BLOB))<=? THEN body_json END AS body_json
|
|
409
|
+
FROM main.oar_log_events WHERE sequence=?`).get(MAX_EVENT_BYTES, sequence);
|
|
410
|
+
if (!row || typeof row.body_json !== "string") logError("INTEGRITY");
|
|
411
|
+
const entry = decodeEntry(row.body_json, row.digest, source), identity2 = entry.record.identity;
|
|
412
|
+
if (row.sequence !== entry.sequence || row.request_id !== entry.requestId || row.ordinal !== entry.ordinal || row.source_id !== entry.sourceId || row.previous_digest !== entry.previousDigest || row.system_id !== identity2.systemId || row.generation !== identity2.generation || row.run_id !== identity2.runId || row.agent_id !== identity2.agentId || row.schema_id !== entry.record.schema.id || row.schema_version !== entry.record.schema.version) logError("INTEGRITY");
|
|
413
|
+
const request = readRequestMetadata(db, entry.requestId, source);
|
|
414
|
+
if (!request || entry.sequence !== Number(request.first_sequence) + entry.ordinal - 1 || entry.ordinal > Number(request.count)) logError("INTEGRITY");
|
|
415
|
+
const pin = db.prepare(`SELECT CASE WHEN length(reference_json)<2048 THEN reference_json END AS reference_json,reference_digest
|
|
416
|
+
FROM main.oar_log_payloads WHERE sequence=?`).get(sequence);
|
|
417
|
+
if ("artifact" in entry.record.payload) {
|
|
418
|
+
const encoded = canonical(entry.record.payload.artifact);
|
|
419
|
+
if (!pin || pin.reference_json !== encoded || pin.reference_digest !== digest(encoded)) logError("INTEGRITY");
|
|
420
|
+
} else if (pin) logError("INTEGRITY");
|
|
421
|
+
return entry;
|
|
422
|
+
}
|
|
423
|
+
function position(entry) {
|
|
424
|
+
return { sourceId: entry.sourceId, sequence: entry.sequence, digest: entry.digest };
|
|
425
|
+
}
|
|
426
|
+
function lookupReceipt(db, requestId, source) {
|
|
427
|
+
const row = readRequestMetadata(db, requestId, source);
|
|
428
|
+
if (!row) return void 0;
|
|
429
|
+
const entries = [];
|
|
430
|
+
const before = Number(row.first_sequence) - 1;
|
|
431
|
+
let previous = before === 0 ? genesis(source) : db.prepare("SELECT digest FROM main.oar_log_events WHERE sequence=?").get(before)?.digest;
|
|
432
|
+
for (let i = 0; i < Number(row.count); i++) {
|
|
433
|
+
const entry = readEntry(db, Number(row.first_sequence) + i, source);
|
|
434
|
+
if (entry.requestId !== requestId || entry.ordinal !== i + 1 || entry.previousDigest !== previous) logError("INTEGRITY");
|
|
435
|
+
entries.push(entry);
|
|
436
|
+
previous = entry.digest;
|
|
437
|
+
}
|
|
438
|
+
const receipt = freeze({ first: position(entries[0]), head: position(entries.at(-1)), count: entries.length });
|
|
439
|
+
const input2 = capture({ requestId, records: entries.map((entry) => entry.record) }, source);
|
|
440
|
+
if (canonical(receipt) !== row.receipt_json || digest(canonical(input2)) !== row.commit_digest) logError("INTEGRITY");
|
|
441
|
+
return { receipt, commitDigest: row.commit_digest };
|
|
442
|
+
}
|
|
443
|
+
function appendRecords(db, commit, source) {
|
|
444
|
+
const head = readHead(db, source), existing = lookupReceipt(db, commit.requestId, source), commitDigest = digest(canonical(commit));
|
|
445
|
+
if (existing) {
|
|
446
|
+
if (existing.commitDigest !== commitDigest) logError("REQUEST_CONFLICT");
|
|
447
|
+
return existing.receipt;
|
|
448
|
+
}
|
|
449
|
+
if (!Number.isSafeInteger(head.sequence + commit.records.length)) logError("INTEGRITY");
|
|
450
|
+
const entries = [];
|
|
451
|
+
let previous = head.digest;
|
|
452
|
+
for (let index = 0; index < commit.records.length; index++) {
|
|
453
|
+
const record = commit.records[index];
|
|
454
|
+
for (const causal of record.causal) if (causal.sourceId === source.sourceId) {
|
|
455
|
+
const known = entries.find((entry2) => entry2.sequence === causal.sequence) ?? db.prepare("SELECT digest FROM main.oar_log_events WHERE sequence=?").get(causal.sequence);
|
|
456
|
+
if (!known || known.digest !== causal.digest) logError("INVALID_INPUT");
|
|
457
|
+
}
|
|
458
|
+
const body = entryBody(source, head.sequence + index + 1, commit.requestId, index + 1, previous, record);
|
|
459
|
+
const entry = { ...body, digest: digest(canonical(body)) };
|
|
460
|
+
entries.push(entry);
|
|
461
|
+
previous = entry.digest;
|
|
462
|
+
}
|
|
463
|
+
const receipt = freeze({ first: position(entries[0]), head: position(entries.at(-1)), count: entries.length }), encodedReceipt = canonical(receipt);
|
|
464
|
+
db.prepare("INSERT INTO main.oar_log_requests VALUES(?,?,?,?,?,?,?)").run(commit.requestId, commitDigest, receipt.first.sequence, receipt.head.sequence, receipt.count, encodedReceipt, digest(encodedReceipt));
|
|
465
|
+
const insert = db.prepare("INSERT INTO main.oar_log_events VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)");
|
|
466
|
+
for (const entry of entries) {
|
|
467
|
+
const identity2 = entry.record.identity, { digest: _, ...body } = entry;
|
|
468
|
+
insert.run(
|
|
469
|
+
entry.sequence,
|
|
470
|
+
entry.requestId,
|
|
471
|
+
entry.ordinal,
|
|
472
|
+
entry.sourceId,
|
|
473
|
+
identity2.systemId,
|
|
474
|
+
identity2.generation,
|
|
475
|
+
identity2.runId,
|
|
476
|
+
identity2.agentId,
|
|
477
|
+
entry.record.schema.id,
|
|
478
|
+
entry.record.schema.version,
|
|
479
|
+
entry.previousDigest,
|
|
480
|
+
entry.digest,
|
|
481
|
+
canonical(body)
|
|
482
|
+
);
|
|
483
|
+
if ("artifact" in entry.record.payload) {
|
|
484
|
+
const ref = canonical(entry.record.payload.artifact);
|
|
485
|
+
db.prepare("INSERT INTO main.oar_log_payloads VALUES(?,?,?)").run(entry.sequence, ref, digest(ref));
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
const update = db.prepare("UPDATE main.oar_log_meta SET head_sequence=?,head_digest=? WHERE id=1 AND head_sequence=? AND head_digest=?").run(receipt.head.sequence, receipt.head.digest, head.sequence, head.digest);
|
|
489
|
+
if (update.changes !== 1) logError("INTEGRITY");
|
|
490
|
+
return receipt;
|
|
491
|
+
}
|
|
492
|
+
function requestIdentifier(value) {
|
|
493
|
+
try {
|
|
494
|
+
identifier(value);
|
|
495
|
+
} catch {
|
|
496
|
+
logError("INVALID_INPUT");
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
// src/orchestration/log/paging.ts
|
|
501
|
+
function captureQuery(input2 = {}) {
|
|
502
|
+
try {
|
|
503
|
+
input2 = ownObject(input2, ["generation", "runId", "agentId", "limit", "cursor"]);
|
|
504
|
+
const output = {};
|
|
505
|
+
for (const key of ["runId", "agentId"]) if (input2[key] !== void 0) {
|
|
506
|
+
identifier(input2[key]);
|
|
507
|
+
output[key] = input2[key];
|
|
508
|
+
}
|
|
509
|
+
if (input2.generation !== void 0) {
|
|
510
|
+
if (!Number.isSafeInteger(input2.generation) || Number(input2.generation) < 1) logError("INVALID_INPUT");
|
|
511
|
+
output.generation = input2.generation;
|
|
512
|
+
}
|
|
513
|
+
const limit = input2.limit ?? 64;
|
|
514
|
+
if (!Number.isSafeInteger(limit) || Number(limit) < 1 || Number(limit) > 256) logError("INVALID_INPUT");
|
|
515
|
+
output.limit = limit;
|
|
516
|
+
if (input2.cursor !== void 0) {
|
|
517
|
+
const cursor = input2.cursor;
|
|
518
|
+
object(cursor, ["format", "filterDigest", "after", "through"]);
|
|
519
|
+
if (Object.keys(cursor).length !== 4 || cursor.format !== 1) logError("INVALID_INPUT");
|
|
520
|
+
hash(cursor.filterDigest);
|
|
521
|
+
const positions = [cursor.after, cursor.through].map((value) => {
|
|
522
|
+
object(value, ["sourceId", "sequence", "digest"]);
|
|
523
|
+
identifier(value.sourceId);
|
|
524
|
+
hash(value.digest);
|
|
525
|
+
if (Object.keys(value).length !== 3 || !Number.isSafeInteger(value.sequence) || Number(value.sequence) < 0) logError("INVALID_INPUT");
|
|
526
|
+
return { sourceId: value.sourceId, sequence: value.sequence, digest: value.digest };
|
|
527
|
+
});
|
|
528
|
+
output.cursor = { format: 1, filterDigest: cursor.filterDigest, after: positions[0], through: positions[1] };
|
|
529
|
+
}
|
|
530
|
+
return freeze(output);
|
|
531
|
+
} catch {
|
|
532
|
+
return logError("INVALID_INPUT");
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
function pageRecords(db, source, storageDigest, query) {
|
|
536
|
+
const { cursor, limit = 64, ...filter } = query;
|
|
537
|
+
const filterDigest = digest(canonical({ purpose: "oar-log-page-v1", source, storageDigest, filter }));
|
|
538
|
+
const head = readHead(db, source), through = cursor?.through ?? head;
|
|
539
|
+
const after = cursor?.after ?? { sourceId: source.sourceId, sequence: 0, digest: genesis(source) };
|
|
540
|
+
if (cursor && cursor.filterDigest !== filterDigest || through.sourceId !== source.sourceId || after.sourceId !== source.sourceId || after.sequence > through.sequence || through.sequence > head.sequence) logError("INVALID_INPUT");
|
|
541
|
+
for (const position2 of [after, through]) {
|
|
542
|
+
const known = position2.sequence === 0 ? genesis(source) : db.prepare("SELECT digest FROM main.oar_log_events WHERE sequence=?").get(position2.sequence)?.digest;
|
|
543
|
+
if (known !== position2.digest) logError("INTEGRITY");
|
|
544
|
+
}
|
|
545
|
+
const ids = db.prepare("SELECT sequence FROM main.oar_log_events WHERE sequence>? AND sequence<=? ORDER BY sequence LIMIT ?").all(after.sequence, through.sequence, limit + 1);
|
|
546
|
+
const items = [];
|
|
547
|
+
let previous = after.digest, last = after;
|
|
548
|
+
const scanned = Math.min(ids.length, limit);
|
|
549
|
+
for (let index = 0; index < scanned; index++) {
|
|
550
|
+
const entry = readEntry(db, Number(ids[index].sequence), source);
|
|
551
|
+
if (entry.sequence !== after.sequence + index + 1 || entry.previousDigest !== previous) logError("INTEGRITY");
|
|
552
|
+
previous = entry.digest;
|
|
553
|
+
last = { sourceId: source.sourceId, sequence: entry.sequence, digest: entry.digest };
|
|
554
|
+
const identity2 = entry.record.identity;
|
|
555
|
+
if ((filter.generation === void 0 || identity2.generation === filter.generation) && (filter.runId === void 0 || identity2.runId === filter.runId) && (filter.agentId === void 0 || identity2.agentId === filter.agentId)) items.push(entry);
|
|
556
|
+
}
|
|
557
|
+
const nextCursor = ids.length > limit ? { format: 1, filterDigest, after: last, through } : void 0;
|
|
558
|
+
return freeze({ source, through, items, scanned, ...nextCursor ? { nextCursor } : {} });
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
// src/orchestration/log/reconstruction.ts
|
|
562
|
+
import { setImmediate as setImmediate2 } from "node:timers/promises";
|
|
563
|
+
function captureIdentity2(input2) {
|
|
564
|
+
try {
|
|
565
|
+
return captureLogCommit({ requestId: "inspect", records: [{ identity: input2, schema: { id: "inspect", version: 1 }, type: "inspect", causal: [], payload: { inline: null } }] }).records[0].identity;
|
|
566
|
+
} catch {
|
|
567
|
+
return logError("INVALID_INPUT");
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
async function reconstruct(identity2, source, config, page, causal, signal) {
|
|
571
|
+
const issues2 = /* @__PURE__ */ new Set();
|
|
572
|
+
let count = 0, through, cursor;
|
|
573
|
+
try {
|
|
574
|
+
do {
|
|
575
|
+
const batch = page(cursor ? { cursor } : {});
|
|
576
|
+
through = batch.through;
|
|
577
|
+
cursor = batch.nextCursor;
|
|
578
|
+
for (const entry of batch.items) {
|
|
579
|
+
if (canonical(entry.record.identity) !== canonical(identity2)) continue;
|
|
580
|
+
count++;
|
|
581
|
+
if (!config.schemas.has(canonical(entry.record.schema))) issues2.add("UNKNOWN_SCHEMA");
|
|
582
|
+
for (const ref of entry.record.causal) if (ref.sourceId !== source.sourceId || ref.sequence >= entry.sequence || !causal(ref)) issues2.add("UNRESOLVED_CAUSAL_REFERENCE");
|
|
583
|
+
if ("artifact" in entry.record.payload) {
|
|
584
|
+
const result = await verifyReference(config.verify, entry.record.payload.artifact, source, signal);
|
|
585
|
+
if (result !== "verified") issues2.add(result === "missing" ? "PAYLOAD_MISSING" : result === "corrupt" ? "PAYLOAD_CORRUPT" : "PAYLOAD_UNVERIFIED");
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
if (cursor) await setImmediate2();
|
|
589
|
+
} while (cursor);
|
|
590
|
+
if (!count) issues2.add("RUN_NOT_FOUND");
|
|
591
|
+
return freeze({ scope: "captured-history", kind: issues2.size ? "incomplete" : "complete", identity: identity2, ...through ? { through } : {}, eventCount: count, issues: [...issues2].sort() });
|
|
592
|
+
} catch (error) {
|
|
593
|
+
if (!isLogStoreError(error) || error.code !== "INTEGRITY") throw error;
|
|
594
|
+
return freeze({ scope: "captured-history", kind: "corrupt", identity: identity2, ...through ? { through } : {}, eventCount: count, issues: ["LOG_CORRUPT"] });
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
// src/orchestration/log/sqlite-store.ts
|
|
599
|
+
var SqliteRunLogStore = class {
|
|
600
|
+
descriptor;
|
|
601
|
+
sourceId;
|
|
602
|
+
#connection;
|
|
603
|
+
#config;
|
|
604
|
+
#abort = new AbortController();
|
|
605
|
+
#tail = Promise.resolve();
|
|
606
|
+
#pending = 0;
|
|
607
|
+
#closed = false;
|
|
608
|
+
constructor(options) {
|
|
609
|
+
this.#config = configuration(options);
|
|
610
|
+
let db;
|
|
611
|
+
try {
|
|
612
|
+
publishLog(this.#config.databasePath, this.#config.systemId);
|
|
613
|
+
db = new DatabaseSync2(this.#config.databasePath);
|
|
614
|
+
db.exec(`PRAGMA busy_timeout=${this.#config.busyTimeoutMs}; PRAGMA foreign_keys=ON; PRAGMA synchronous=FULL`);
|
|
615
|
+
this.#connection = new LogConnection(db, this.#config.databasePath, this.#config.systemId, true);
|
|
616
|
+
this.descriptor = this.#connection.source;
|
|
617
|
+
this.sourceId = this.descriptor.sourceId;
|
|
618
|
+
this.#connection.transaction(() => readHead(db, this.descriptor));
|
|
619
|
+
for (const key of ["descriptor", "sourceId"]) Object.defineProperty(this, key, { writable: false, configurable: false });
|
|
620
|
+
} catch (error) {
|
|
621
|
+
db?.close();
|
|
622
|
+
safeFailure(error);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
#enqueue(captureInput) {
|
|
626
|
+
if (this.#closed) return Promise.reject(new LogStoreError("CLOSED"));
|
|
627
|
+
if (this.#pending >= this.#config.maxPending) return Promise.reject(new LogStoreError("BUSY"));
|
|
628
|
+
let body;
|
|
629
|
+
try {
|
|
630
|
+
body = captureInput();
|
|
631
|
+
} catch (error) {
|
|
632
|
+
return Promise.reject(error);
|
|
633
|
+
}
|
|
634
|
+
this.#pending++;
|
|
635
|
+
const operation = this.#tail.then(async () => {
|
|
636
|
+
if (this.#closed) logError("CLOSED");
|
|
637
|
+
return body();
|
|
638
|
+
});
|
|
639
|
+
this.#tail = operation.catch(() => {
|
|
640
|
+
});
|
|
641
|
+
return operation.catch(safeFailure).finally(() => {
|
|
642
|
+
this.#pending--;
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
append(input2) {
|
|
646
|
+
return this.#enqueue(() => {
|
|
647
|
+
const commit = capture(input2, this.descriptor);
|
|
648
|
+
return async () => {
|
|
649
|
+
this.#connection.assert();
|
|
650
|
+
const existing = this.#connection.transaction(() => lookupReceipt(this.#connection.db, commit.requestId, this.descriptor));
|
|
651
|
+
if (!existing) await verifyCommit(commit, this.#config, this.descriptor, this.#abort.signal);
|
|
652
|
+
this.#connection.assert();
|
|
653
|
+
return this.#connection.transaction(() => appendRecords(this.#connection.db, commit, this.descriptor), true);
|
|
654
|
+
};
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
lookupRequest(requestId) {
|
|
658
|
+
return this.#enqueue(() => {
|
|
659
|
+
requestIdentifier(requestId);
|
|
660
|
+
return () => this.#connection.transaction(() => {
|
|
661
|
+
readHead(this.#connection.db, this.descriptor);
|
|
662
|
+
return lookupReceipt(this.#connection.db, requestId, this.descriptor)?.receipt;
|
|
663
|
+
});
|
|
664
|
+
});
|
|
665
|
+
}
|
|
666
|
+
readPage(query = {}) {
|
|
667
|
+
return this.#enqueue(() => {
|
|
668
|
+
const captured = captureQuery(query);
|
|
669
|
+
return () => this.#page(captured);
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
#page(query) {
|
|
673
|
+
return this.#connection.transaction(() => pageRecords(this.#connection.db, this.descriptor, this.#connection.storageDigest, query));
|
|
674
|
+
}
|
|
675
|
+
inspectRun(input2) {
|
|
676
|
+
return this.#enqueue(() => {
|
|
677
|
+
const identity2 = captureIdentity2(input2);
|
|
678
|
+
return async () => {
|
|
679
|
+
const result = await reconstruct(identity2, this.descriptor, this.#config, (query) => this.#page(query), (ref) => this.#connection.transaction(() => this.#connection.db.prepare("SELECT digest FROM main.oar_log_events WHERE sequence=?").get(ref.sequence)?.digest === ref.digest), this.#abort.signal);
|
|
680
|
+
this.#connection.assert();
|
|
681
|
+
return result;
|
|
682
|
+
};
|
|
683
|
+
});
|
|
684
|
+
}
|
|
685
|
+
close() {
|
|
686
|
+
if (!this.#closed) {
|
|
687
|
+
this.#closed = true;
|
|
688
|
+
this.#abort.abort();
|
|
689
|
+
this.#connection.close();
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
};
|
|
693
|
+
|
|
694
|
+
// src/orchestration/log/sqlite-binding.ts
|
|
695
|
+
var prepared = /* @__PURE__ */ new WeakMap();
|
|
696
|
+
var SqliteLogBinding = class {
|
|
697
|
+
descriptor;
|
|
698
|
+
sourceId;
|
|
699
|
+
#connection;
|
|
700
|
+
#config;
|
|
701
|
+
#abort = new AbortController();
|
|
702
|
+
#pending = 0;
|
|
703
|
+
constructor(db, options) {
|
|
704
|
+
this.#config = configuration(options);
|
|
705
|
+
try {
|
|
706
|
+
this.#connection = new LogConnection(db, this.#config.databasePath, this.#config.systemId, false, true);
|
|
707
|
+
this.descriptor = this.#connection.source;
|
|
708
|
+
this.sourceId = this.descriptor.sourceId;
|
|
709
|
+
readHead(db, this.descriptor);
|
|
710
|
+
for (const key of ["descriptor", "sourceId"]) Object.defineProperty(this, key, { writable: false, configurable: false });
|
|
711
|
+
} catch (error) {
|
|
712
|
+
safeFailure(error);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
async prepare(input2) {
|
|
716
|
+
this.#connection.assert();
|
|
717
|
+
if (this.#connection.inTransaction()) logError("TRANSACTION_REQUIRED");
|
|
718
|
+
if (this.#pending >= this.#config.maxPending) logError("BUSY");
|
|
719
|
+
const commit = capture(input2, this.descriptor);
|
|
720
|
+
this.#pending++;
|
|
721
|
+
try {
|
|
722
|
+
await verifyCommit(commit, this.#config, this.descriptor, this.#abort.signal);
|
|
723
|
+
this.#connection.assert();
|
|
724
|
+
if (this.#connection.inTransaction()) logError("TRANSACTION_REQUIRED");
|
|
725
|
+
const handle = Object.freeze({});
|
|
726
|
+
prepared.set(handle, { binding: this, commit });
|
|
727
|
+
return handle;
|
|
728
|
+
} catch (error) {
|
|
729
|
+
return safeFailure(error);
|
|
730
|
+
} finally {
|
|
731
|
+
this.#pending--;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
appendInTransaction(input2) {
|
|
735
|
+
this.#connection.assert();
|
|
736
|
+
if (!this.#connection.inTransaction()) logError("TRANSACTION_REQUIRED");
|
|
737
|
+
const saved = input2 && typeof input2 === "object" ? prepared.get(input2) : void 0;
|
|
738
|
+
if (saved && saved.binding !== this) logError("INVALID_INPUT");
|
|
739
|
+
const commit = saved?.commit ?? capture(input2, this.descriptor);
|
|
740
|
+
if (!saved && commit.records.some((record) => "artifact" in record.payload)) logError("PAYLOAD_UNAVAILABLE");
|
|
741
|
+
const db = this.#connection.db;
|
|
742
|
+
let began = false;
|
|
743
|
+
try {
|
|
744
|
+
db.exec("SAVEPOINT oar_log_append");
|
|
745
|
+
began = true;
|
|
746
|
+
const receipt = appendRecords(db, commit, this.descriptor);
|
|
747
|
+
this.#connection.assert();
|
|
748
|
+
db.exec("RELEASE oar_log_append");
|
|
749
|
+
began = false;
|
|
750
|
+
return receipt;
|
|
751
|
+
} catch (error) {
|
|
752
|
+
if (began) {
|
|
753
|
+
try {
|
|
754
|
+
db.exec("ROLLBACK TO oar_log_append; RELEASE oar_log_append");
|
|
755
|
+
} catch {
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
return safeFailure(error);
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
lookupRequest(requestId) {
|
|
762
|
+
requestIdentifier(requestId);
|
|
763
|
+
return this.#connection.transaction(() => {
|
|
764
|
+
readHead(this.#connection.db, this.descriptor);
|
|
765
|
+
return lookupReceipt(this.#connection.db, requestId, this.descriptor)?.receipt;
|
|
766
|
+
});
|
|
767
|
+
}
|
|
768
|
+
readPage(query = {}) {
|
|
769
|
+
const captured = captureQuery(query);
|
|
770
|
+
return this.#connection.transaction(() => pageRecords(this.#connection.db, this.descriptor, this.#connection.storageDigest, captured));
|
|
771
|
+
}
|
|
772
|
+
close() {
|
|
773
|
+
this.#abort.abort();
|
|
774
|
+
this.#connection.close();
|
|
775
|
+
}
|
|
776
|
+
};
|
|
777
|
+
|
|
778
|
+
// src/orchestration/log/artifacts-validation.ts
|
|
779
|
+
import { isAbsolute as isAbsolute2, resolve as resolve2 } from "node:path";
|
|
780
|
+
import { types as types3 } from "node:util";
|
|
781
|
+
|
|
782
|
+
// src/orchestration/log/artifacts-types.ts
|
|
783
|
+
var LogArtifactError = class extends Error {
|
|
784
|
+
constructor(code, cause) {
|
|
785
|
+
super("Execution log artifact operation failed", cause === void 0 ? void 0 : { cause });
|
|
786
|
+
this.code = code;
|
|
787
|
+
this.name = "LogArtifactError";
|
|
788
|
+
}
|
|
789
|
+
code;
|
|
790
|
+
};
|
|
791
|
+
var LOG_ARTIFACT_LIMITS = Object.freeze({ chunkBytes: 65536, maxBytes: 128 * 1024 * 1024, maxPending: 2 });
|
|
792
|
+
|
|
793
|
+
// src/orchestration/log/artifacts-validation.ts
|
|
794
|
+
var lengthGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "byteLength").get;
|
|
795
|
+
var bufferGetter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "buffer").get;
|
|
796
|
+
var abortedGetter = Object.getOwnPropertyDescriptor(AbortSignal.prototype, "aborted").get;
|
|
797
|
+
var reasonGetter = Object.getOwnPropertyDescriptor(AbortSignal.prototype, "reason").get;
|
|
798
|
+
function exact(input2, keys, optional = []) {
|
|
799
|
+
object(input2, keys);
|
|
800
|
+
if (keys.some((key) => !optional.includes(key) && !Object.hasOwn(input2, key))) throw new LogArtifactError("INVALID");
|
|
801
|
+
return Object.fromEntries(Object.entries(Object.getOwnPropertyDescriptors(input2)).map(([key, value]) => [key, value.value]));
|
|
802
|
+
}
|
|
803
|
+
var text = (input2) => {
|
|
804
|
+
identifier(input2);
|
|
805
|
+
if (Buffer.from(input2).toString("utf8") !== input2) throw new LogArtifactError("INVALID");
|
|
806
|
+
return input2;
|
|
807
|
+
};
|
|
808
|
+
function integer2(input2, minimum, maximum = Number.MAX_SAFE_INTEGER) {
|
|
809
|
+
if (typeof input2 !== "number" || !Number.isSafeInteger(input2) || input2 < minimum || input2 > maximum) throw new LogArtifactError("INVALID");
|
|
810
|
+
return input2;
|
|
811
|
+
}
|
|
812
|
+
function artifactOptions(input2) {
|
|
813
|
+
try {
|
|
814
|
+
const r = exact(input2, ["directory", "binding", "maxBytes", "maxPending"], ["maxBytes", "maxPending"]), b = exact(r.binding, ["sourceId", "systemId", "generation"]);
|
|
815
|
+
if (typeof r.directory !== "string" || !isAbsolute2(r.directory) || resolve2(r.directory) !== r.directory || r.directory.includes("\0") || Buffer.byteLength(r.directory) > 4096) throw Error();
|
|
816
|
+
return Object.freeze({
|
|
817
|
+
directory: r.directory,
|
|
818
|
+
binding: Object.freeze({ sourceId: text(b.sourceId), systemId: text(b.systemId), generation: integer2(b.generation, 1) }),
|
|
819
|
+
maxBytes: integer2(r.maxBytes === void 0 ? LOG_ARTIFACT_LIMITS.maxBytes : r.maxBytes, 1, LOG_ARTIFACT_LIMITS.maxBytes),
|
|
820
|
+
maxPending: integer2(r.maxPending === void 0 ? 2 : r.maxPending, 1, 2)
|
|
821
|
+
});
|
|
822
|
+
} catch {
|
|
823
|
+
throw new LogArtifactError("INVALID");
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
function artifactIoOptions(input2, write2 = false) {
|
|
827
|
+
try {
|
|
828
|
+
const r = exact(input2, write2 ? ["signal", "mediaType"] : ["signal"], ["signal"]), signal = r.signal;
|
|
829
|
+
if (signal !== void 0) {
|
|
830
|
+
if (!signal || typeof signal !== "object" || types3.isProxy(signal)) throw Error();
|
|
831
|
+
Reflect.apply(abortedGetter, signal, []);
|
|
832
|
+
}
|
|
833
|
+
if (write2 && r.mediaType !== "application/json" && r.mediaType !== "application/octet-stream") throw Error();
|
|
834
|
+
return Object.freeze({ signal, mediaType: r.mediaType });
|
|
835
|
+
} catch {
|
|
836
|
+
throw new LogArtifactError("INVALID");
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
function artifactReference(input2, binding, maximum) {
|
|
840
|
+
try {
|
|
841
|
+
const r = exact(input2, ["sourceId", "systemId", "generation", "digest", "bytes", "mediaType"]);
|
|
842
|
+
if (r.sourceId !== binding.sourceId || r.systemId !== binding.systemId || r.generation !== binding.generation || r.mediaType !== "application/json" && r.mediaType !== "application/octet-stream") throw Error();
|
|
843
|
+
hash(r.digest);
|
|
844
|
+
return Object.freeze({ ...binding, digest: r.digest, bytes: integer2(r.bytes, 0, maximum), mediaType: r.mediaType });
|
|
845
|
+
} catch {
|
|
846
|
+
throw new LogArtifactError("INVALID");
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
function artifactInputSize(input2, maximum) {
|
|
850
|
+
if (typeof input2 === "string") {
|
|
851
|
+
const size2 = Buffer.byteLength(input2);
|
|
852
|
+
if (size2 > maximum) throw new LogArtifactError("LIMIT");
|
|
853
|
+
return size2;
|
|
854
|
+
}
|
|
855
|
+
if (!input2 || typeof input2 !== "object" || types3.isProxy(input2) || !types3.isUint8Array(input2)) throw new LogArtifactError("INVALID");
|
|
856
|
+
const size = Reflect.apply(lengthGetter, input2, []), backing = Reflect.apply(bufferGetter, input2, []);
|
|
857
|
+
if (types3.isSharedArrayBuffer(backing)) throw new LogArtifactError("INVALID");
|
|
858
|
+
if (size > maximum) throw new LogArtifactError("LIMIT");
|
|
859
|
+
return size;
|
|
860
|
+
}
|
|
861
|
+
function captureArtifactInput(input2, length) {
|
|
862
|
+
if (typeof input2 === "string") return input2;
|
|
863
|
+
try {
|
|
864
|
+
const bytes = Buffer.allocUnsafe(length);
|
|
865
|
+
Uint8Array.prototype.set.call(bytes, input2);
|
|
866
|
+
return bytes;
|
|
867
|
+
} catch {
|
|
868
|
+
throw new LogArtifactError("INVALID");
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
function checkArtifactAbort(signal) {
|
|
872
|
+
if (signal && Reflect.apply(abortedGetter, signal, [])) throw new LogArtifactError("ABORTED", Reflect.apply(reasonGetter, signal, []));
|
|
873
|
+
}
|
|
874
|
+
function* artifactChunks(input2) {
|
|
875
|
+
if (typeof input2 !== "string") {
|
|
876
|
+
for (let offset = 0; offset < input2.length; offset += LOG_ARTIFACT_LIMITS.chunkBytes) yield input2.subarray(offset, offset + LOG_ARTIFACT_LIMITS.chunkBytes);
|
|
877
|
+
return;
|
|
878
|
+
}
|
|
879
|
+
for (let offset = 0; offset < input2.length; ) {
|
|
880
|
+
let end = Math.min(input2.length, offset + 16384);
|
|
881
|
+
const tail = input2.charCodeAt(end - 1);
|
|
882
|
+
if (end < input2.length && tail >= 55296 && tail <= 56319) end--;
|
|
883
|
+
if (end === offset) end++;
|
|
884
|
+
const slice = input2.slice(offset, end), bytes = Buffer.from(slice);
|
|
885
|
+
if (bytes.toString("utf8") !== slice) throw new LogArtifactError("INVALID");
|
|
886
|
+
yield bytes;
|
|
887
|
+
offset = end;
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
var artifactFailure = (cause) => cause instanceof LogArtifactError ? cause : new LogArtifactError("IO", cause);
|
|
891
|
+
var artifactYield = () => new Promise((resolve3) => setImmediate(resolve3));
|
|
892
|
+
|
|
893
|
+
// src/orchestration/log/artifacts-files.ts
|
|
894
|
+
import fs from "node:fs";
|
|
895
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
896
|
+
import { dirname as dirname2, join } from "node:path";
|
|
897
|
+
var same = (a, b) => a.dev === b.dev && a.ino === b.ino;
|
|
898
|
+
var uid = () => {
|
|
899
|
+
if (!process.getuid) throw new LogArtifactError("IO");
|
|
900
|
+
return BigInt(process.getuid());
|
|
901
|
+
};
|
|
902
|
+
var directory = (path, expected3) => {
|
|
903
|
+
const s = fs.lstatSync(path, { bigint: true });
|
|
904
|
+
if (!s.isDirectory() || s.isSymbolicLink() || s.uid !== uid() || (s.mode & 0o777n) !== 0o700n || fs.realpathSync(path) !== path || expected3 && !same(s, expected3)) throw new LogArtifactError("CORRUPT");
|
|
905
|
+
return s;
|
|
906
|
+
};
|
|
907
|
+
var file = (path, length) => {
|
|
908
|
+
const s = fs.lstatSync(path, { bigint: true });
|
|
909
|
+
if (!s.isFile() || s.isSymbolicLink() || s.uid !== uid() || (s.mode & 0o777n) !== 0o600n || s.nlink !== 1n || s.size !== BigInt(length) || fs.realpathSync(path) !== path) throw new LogArtifactError("CORRUPT");
|
|
910
|
+
return s;
|
|
911
|
+
};
|
|
912
|
+
var fsync = (fd) => new Promise((resolve3, reject) => fs.fsync(fd, (error) => error ? reject(error) : resolve3()));
|
|
913
|
+
var rename = (from, to) => new Promise((resolve3, reject) => fs.rename(from, to, (error) => error ? reject(error) : resolve3()));
|
|
914
|
+
var link = (from, to) => new Promise((resolve3, reject) => fs.link(from, to, (error) => error ? reject(error) : resolve3()));
|
|
915
|
+
var unlink = (path) => new Promise((resolve3, reject) => fs.unlink(path, (error) => error ? reject(error) : resolve3()));
|
|
916
|
+
var write = (fd, bytes, offset) => new Promise((resolve3, reject) => fs.write(fd, bytes, offset, bytes.length - offset, null, (error, count) => error ? reject(error) : resolve3(count)));
|
|
917
|
+
var read = (fd, bytes, count, position2) => new Promise((resolve3, reject) => fs.read(fd, bytes, 0, count, position2, (error, used) => error ? reject(error) : resolve3(used)));
|
|
918
|
+
async function syncDirectory(context, path, expected3) {
|
|
919
|
+
context?.check();
|
|
920
|
+
const before = directory(path, expected3), fd = fs.openSync(path, fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | fs.constants.O_NOFOLLOW);
|
|
921
|
+
let owned = true;
|
|
922
|
+
try {
|
|
923
|
+
if (!same(before, fs.fstatSync(fd, { bigint: true }))) {
|
|
924
|
+
if (context) {
|
|
925
|
+
owned = false;
|
|
926
|
+
context.quarantine(fd);
|
|
927
|
+
}
|
|
928
|
+
throw new LogArtifactError("CORRUPT");
|
|
929
|
+
}
|
|
930
|
+
await fsync(fd);
|
|
931
|
+
context?.check();
|
|
932
|
+
directory(path, before);
|
|
933
|
+
} finally {
|
|
934
|
+
if (owned) fs.closeSync(fd);
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
async function createArtifactFiles(root, binding) {
|
|
938
|
+
try {
|
|
939
|
+
fs.lstatSync(root);
|
|
940
|
+
} catch (error) {
|
|
941
|
+
if (error.code !== "ENOENT") throw error;
|
|
942
|
+
directory(dirname2(root));
|
|
943
|
+
try {
|
|
944
|
+
fs.mkdirSync(root, { mode: 448 });
|
|
945
|
+
} catch (cause) {
|
|
946
|
+
if (cause.code !== "EEXIST") throw cause;
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
await syncDirectory(void 0, dirname2(root));
|
|
950
|
+
const rootIdentity = directory(root), scope = join(root, createHash("sha256").update(canonical(binding)).digest("hex"));
|
|
951
|
+
try {
|
|
952
|
+
fs.mkdirSync(scope, { mode: 448 });
|
|
953
|
+
} catch (error) {
|
|
954
|
+
if (error.code !== "EEXIST") throw error;
|
|
955
|
+
}
|
|
956
|
+
const scopeIdentity = directory(scope);
|
|
957
|
+
let faulted = false, quarantined;
|
|
958
|
+
const context = Object.freeze({
|
|
959
|
+
scope,
|
|
960
|
+
check() {
|
|
961
|
+
if (faulted) throw new LogArtifactError("CORRUPT");
|
|
962
|
+
directory(root, rootIdentity);
|
|
963
|
+
directory(scope, scopeIdentity);
|
|
964
|
+
},
|
|
965
|
+
quarantine(fd) {
|
|
966
|
+
faulted = true;
|
|
967
|
+
if (quarantined === void 0) quarantined = fd;
|
|
968
|
+
},
|
|
969
|
+
snapshot: () => ({ faulted, quarantined: Number(quarantined !== void 0) })
|
|
970
|
+
});
|
|
971
|
+
await syncDirectory(context, root, rootIdentity);
|
|
972
|
+
await syncDirectory(context, scope, scopeIdentity);
|
|
973
|
+
return context;
|
|
974
|
+
}
|
|
975
|
+
async function scanArtifact(context, reference2, signal, retain = false) {
|
|
976
|
+
context.check();
|
|
977
|
+
checkArtifactAbort(signal);
|
|
978
|
+
const path = join(context.scope, `${reference2.digest}.blob`);
|
|
979
|
+
let before;
|
|
980
|
+
try {
|
|
981
|
+
before = file(path, reference2.bytes);
|
|
982
|
+
} catch (error) {
|
|
983
|
+
if (error.code === "ENOENT") throw new LogArtifactError("MISSING");
|
|
984
|
+
throw error;
|
|
985
|
+
}
|
|
986
|
+
const fd = fs.openSync(path, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
|
987
|
+
let owned = true;
|
|
988
|
+
const chunks = [], buffer = Buffer.allocUnsafe(LOG_ARTIFACT_LIMITS.chunkBytes), hash2 = createHash("sha256");
|
|
989
|
+
let used = 0;
|
|
990
|
+
try {
|
|
991
|
+
let pinned;
|
|
992
|
+
try {
|
|
993
|
+
pinned = fs.fstatSync(fd, { bigint: true });
|
|
994
|
+
} catch (cause) {
|
|
995
|
+
owned = false;
|
|
996
|
+
context.quarantine(fd);
|
|
997
|
+
throw new LogArtifactError("CORRUPT", cause);
|
|
998
|
+
}
|
|
999
|
+
if (!same(before, pinned) || !pinned.isFile() || pinned.size !== before.size || pinned.nlink !== 1n || pinned.uid !== uid() || (pinned.mode & 0o777n) !== 0o600n) {
|
|
1000
|
+
owned = false;
|
|
1001
|
+
context.quarantine(fd);
|
|
1002
|
+
throw new LogArtifactError("CORRUPT");
|
|
1003
|
+
}
|
|
1004
|
+
while (used < reference2.bytes) {
|
|
1005
|
+
context.check();
|
|
1006
|
+
checkArtifactAbort(signal);
|
|
1007
|
+
const count = await read(fd, buffer, Math.min(buffer.length, reference2.bytes - used), used);
|
|
1008
|
+
if (count < 1) throw new LogArtifactError("CORRUPT");
|
|
1009
|
+
hash2.update(buffer.subarray(0, count));
|
|
1010
|
+
if (retain) chunks.push(Buffer.from(buffer.subarray(0, count)));
|
|
1011
|
+
used += count;
|
|
1012
|
+
await artifactYield();
|
|
1013
|
+
}
|
|
1014
|
+
checkArtifactAbort(signal);
|
|
1015
|
+
const after = file(path, reference2.bytes), current = fs.fstatSync(fd, { bigint: true });
|
|
1016
|
+
if (!same(before, after) || !same(before, current) || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs || current.size !== before.size || hash2.digest("hex") !== reference2.digest) throw new LogArtifactError("CORRUPT");
|
|
1017
|
+
await fsync(fd);
|
|
1018
|
+
await syncDirectory(context, context.scope);
|
|
1019
|
+
checkArtifactAbort(signal);
|
|
1020
|
+
const last = file(path, reference2.bytes);
|
|
1021
|
+
if (!same(before, last) || before.mtimeNs !== last.mtimeNs || before.ctimeNs !== last.ctimeNs) throw new LogArtifactError("CORRUPT");
|
|
1022
|
+
return retain ? Buffer.concat(chunks, used) : void 0;
|
|
1023
|
+
} finally {
|
|
1024
|
+
buffer.fill(0);
|
|
1025
|
+
for (const chunk of chunks) chunk.fill(0);
|
|
1026
|
+
if (owned) fs.closeSync(fd);
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
async function verifyPublishedDescriptor(context, fd, reference2, path, signal) {
|
|
1030
|
+
context.check();
|
|
1031
|
+
const before = fs.fstatSync(fd, { bigint: true }), named = file(path, reference2.bytes), hash2 = createHash("sha256"), buffer = Buffer.allocUnsafe(LOG_ARTIFACT_LIMITS.chunkBytes);
|
|
1032
|
+
let used = 0;
|
|
1033
|
+
if (!same(before, named) || before.size !== BigInt(reference2.bytes)) throw new LogArtifactError("CORRUPT");
|
|
1034
|
+
try {
|
|
1035
|
+
while (used < reference2.bytes) {
|
|
1036
|
+
context.check();
|
|
1037
|
+
checkArtifactAbort(signal);
|
|
1038
|
+
const count = await read(fd, buffer, Math.min(buffer.length, reference2.bytes - used), used);
|
|
1039
|
+
if (count < 1) throw new LogArtifactError("CORRUPT");
|
|
1040
|
+
hash2.update(buffer.subarray(0, count));
|
|
1041
|
+
used += count;
|
|
1042
|
+
await artifactYield();
|
|
1043
|
+
}
|
|
1044
|
+
const after = file(path, reference2.bytes), pinned = fs.fstatSync(fd, { bigint: true });
|
|
1045
|
+
if (!same(before, after) || !same(before, pinned) || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs || pinned.size !== before.size || hash2.digest("hex") !== reference2.digest) throw new LogArtifactError("CORRUPT");
|
|
1046
|
+
return after;
|
|
1047
|
+
} finally {
|
|
1048
|
+
buffer.fill(0);
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
async function removeOwned(path, identity2) {
|
|
1052
|
+
let s;
|
|
1053
|
+
try {
|
|
1054
|
+
s = fs.lstatSync(path, { bigint: true });
|
|
1055
|
+
} catch (error) {
|
|
1056
|
+
if (error.code === "ENOENT") return;
|
|
1057
|
+
throw error;
|
|
1058
|
+
}
|
|
1059
|
+
if (!s.isFile() || s.isSymbolicLink() || !same(s, identity2)) throw new LogArtifactError("CORRUPT");
|
|
1060
|
+
await unlink(path);
|
|
1061
|
+
}
|
|
1062
|
+
async function publishArtifact(context, binding, input2, length, mediaType, signal) {
|
|
1063
|
+
context.check();
|
|
1064
|
+
checkArtifactAbort(signal);
|
|
1065
|
+
const temporary = join(context.scope, `.${randomBytes(32).toString("hex")}.tmp`), ready = join(context.scope, `.${randomBytes(32).toString("hex")}.ready`);
|
|
1066
|
+
const fd = fs.openSync(temporary, fs.constants.O_RDWR | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 384);
|
|
1067
|
+
let identity2;
|
|
1068
|
+
let renamed = false, failure;
|
|
1069
|
+
const hash2 = createHash("sha256");
|
|
1070
|
+
let bytes = 0;
|
|
1071
|
+
try {
|
|
1072
|
+
identity2 = fs.fstatSync(fd, { bigint: true });
|
|
1073
|
+
fs.fchmodSync(fd, 384);
|
|
1074
|
+
for (const chunk of artifactChunks(input2)) {
|
|
1075
|
+
context.check();
|
|
1076
|
+
checkArtifactAbort(signal);
|
|
1077
|
+
let offset = 0;
|
|
1078
|
+
while (offset < chunk.length) {
|
|
1079
|
+
const count = await write(fd, chunk, offset);
|
|
1080
|
+
if (count < 1) throw new LogArtifactError("IO");
|
|
1081
|
+
offset += count;
|
|
1082
|
+
}
|
|
1083
|
+
hash2.update(chunk);
|
|
1084
|
+
bytes += chunk.length;
|
|
1085
|
+
if (bytes > length) throw new LogArtifactError("LIMIT");
|
|
1086
|
+
await artifactYield();
|
|
1087
|
+
}
|
|
1088
|
+
if (bytes !== length) throw new LogArtifactError("CORRUPT");
|
|
1089
|
+
await fsync(fd);
|
|
1090
|
+
checkArtifactAbort(signal);
|
|
1091
|
+
context.check();
|
|
1092
|
+
try {
|
|
1093
|
+
fs.lstatSync(ready);
|
|
1094
|
+
throw new LogArtifactError("CORRUPT");
|
|
1095
|
+
} catch (error) {
|
|
1096
|
+
if (error.code !== "ENOENT") throw error;
|
|
1097
|
+
}
|
|
1098
|
+
await rename(temporary, ready);
|
|
1099
|
+
renamed = true;
|
|
1100
|
+
const staged = fs.lstatSync(ready, { bigint: true });
|
|
1101
|
+
if (!same(identity2, staged) || !staged.isFile() || staged.isSymbolicLink()) throw new LogArtifactError("CORRUPT");
|
|
1102
|
+
const reference2 = Object.freeze({ ...binding, digest: hash2.digest("hex"), bytes, mediaType }), final = join(context.scope, `${reference2.digest}.blob`);
|
|
1103
|
+
let created = false, duplicate;
|
|
1104
|
+
try {
|
|
1105
|
+
await link(ready, final);
|
|
1106
|
+
created = true;
|
|
1107
|
+
} catch (error) {
|
|
1108
|
+
if (error.code !== "EEXIST") throw error;
|
|
1109
|
+
duplicate = file(final, reference2.bytes);
|
|
1110
|
+
await scanArtifact(context, reference2, signal);
|
|
1111
|
+
}
|
|
1112
|
+
await removeOwned(ready, identity2);
|
|
1113
|
+
renamed = false;
|
|
1114
|
+
context.check();
|
|
1115
|
+
const published = file(final, reference2.bytes);
|
|
1116
|
+
if (created && !same(published, identity2) || duplicate && (!same(published, duplicate) || duplicate.mtimeNs !== published.mtimeNs || duplicate.ctimeNs !== published.ctimeNs)) throw new LogArtifactError("CORRUPT");
|
|
1117
|
+
const verified = created ? await verifyPublishedDescriptor(context, fd, reference2, final, signal) : published;
|
|
1118
|
+
await syncDirectory(context, context.scope);
|
|
1119
|
+
checkArtifactAbort(signal);
|
|
1120
|
+
const last = file(final, reference2.bytes);
|
|
1121
|
+
if (!same(verified, last) || verified.mtimeNs !== last.mtimeNs || verified.ctimeNs !== last.ctimeNs) throw new LogArtifactError("CORRUPT");
|
|
1122
|
+
return reference2;
|
|
1123
|
+
} catch (error) {
|
|
1124
|
+
failure = error;
|
|
1125
|
+
throw error;
|
|
1126
|
+
} finally {
|
|
1127
|
+
fs.closeSync(fd);
|
|
1128
|
+
if (identity2) try {
|
|
1129
|
+
await removeOwned(renamed ? ready : temporary, identity2);
|
|
1130
|
+
} catch (error) {
|
|
1131
|
+
if (failure === void 0) throw error;
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
// src/orchestration/log/artifacts.ts
|
|
1137
|
+
var observed = (promise) => {
|
|
1138
|
+
void promise.catch(() => {
|
|
1139
|
+
});
|
|
1140
|
+
return promise;
|
|
1141
|
+
};
|
|
1142
|
+
async function createLogArtifactStore(input2) {
|
|
1143
|
+
const options = artifactOptions(input2);
|
|
1144
|
+
let files;
|
|
1145
|
+
try {
|
|
1146
|
+
files = await createArtifactFiles(options.directory, options.binding);
|
|
1147
|
+
} catch (cause) {
|
|
1148
|
+
throw artifactFailure(cause);
|
|
1149
|
+
}
|
|
1150
|
+
let pending = 0;
|
|
1151
|
+
const reserve = () => {
|
|
1152
|
+
files.check();
|
|
1153
|
+
if (pending >= options.maxPending) throw new LogArtifactError("BUSY");
|
|
1154
|
+
pending++;
|
|
1155
|
+
};
|
|
1156
|
+
const run = (work) => observed((async () => {
|
|
1157
|
+
try {
|
|
1158
|
+
return await work();
|
|
1159
|
+
} catch (cause) {
|
|
1160
|
+
throw artifactFailure(cause);
|
|
1161
|
+
} finally {
|
|
1162
|
+
pending--;
|
|
1163
|
+
}
|
|
1164
|
+
})());
|
|
1165
|
+
return Object.freeze({
|
|
1166
|
+
write(input3, operation) {
|
|
1167
|
+
let owned;
|
|
1168
|
+
try {
|
|
1169
|
+
const io = artifactIoOptions(operation, true), length = artifactInputSize(input3, options.maxBytes);
|
|
1170
|
+
checkArtifactAbort(io.signal);
|
|
1171
|
+
reserve();
|
|
1172
|
+
try {
|
|
1173
|
+
owned = captureArtifactInput(input3, length);
|
|
1174
|
+
} catch (error) {
|
|
1175
|
+
pending--;
|
|
1176
|
+
throw error;
|
|
1177
|
+
}
|
|
1178
|
+
return run(async () => {
|
|
1179
|
+
try {
|
|
1180
|
+
return await publishArtifact(files, options.binding, owned, length, io.mediaType, io.signal);
|
|
1181
|
+
} finally {
|
|
1182
|
+
if (typeof owned !== "string") owned.fill(0);
|
|
1183
|
+
}
|
|
1184
|
+
});
|
|
1185
|
+
} catch (cause) {
|
|
1186
|
+
return observed(Promise.reject(artifactFailure(cause)));
|
|
1187
|
+
}
|
|
1188
|
+
},
|
|
1189
|
+
verify(input3, operation = {}) {
|
|
1190
|
+
let reference2;
|
|
1191
|
+
try {
|
|
1192
|
+
reference2 = artifactReference(input3, options.binding, options.maxBytes);
|
|
1193
|
+
const io = artifactIoOptions(operation);
|
|
1194
|
+
checkArtifactAbort(io.signal);
|
|
1195
|
+
try {
|
|
1196
|
+
reserve();
|
|
1197
|
+
} catch (cause) {
|
|
1198
|
+
if (cause instanceof LogArtifactError && cause.code === "CORRUPT") return Promise.resolve(Object.freeze({ kind: "corrupt", reference: reference2 }));
|
|
1199
|
+
throw cause;
|
|
1200
|
+
}
|
|
1201
|
+
return run(async () => {
|
|
1202
|
+
try {
|
|
1203
|
+
await scanArtifact(files, reference2, io.signal);
|
|
1204
|
+
return Object.freeze({ kind: "verified", reference: reference2 });
|
|
1205
|
+
} catch (cause) {
|
|
1206
|
+
if (cause instanceof LogArtifactError && (cause.code === "MISSING" || cause.code === "CORRUPT")) return Object.freeze({ kind: cause.code === "MISSING" ? "missing" : "corrupt", reference: reference2 });
|
|
1207
|
+
throw cause;
|
|
1208
|
+
}
|
|
1209
|
+
});
|
|
1210
|
+
} catch (cause) {
|
|
1211
|
+
return observed(Promise.reject(artifactFailure(cause)));
|
|
1212
|
+
}
|
|
1213
|
+
},
|
|
1214
|
+
read(input3, operation = {}) {
|
|
1215
|
+
try {
|
|
1216
|
+
const reference2 = artifactReference(input3, options.binding, options.maxBytes), io = artifactIoOptions(operation);
|
|
1217
|
+
checkArtifactAbort(io.signal);
|
|
1218
|
+
reserve();
|
|
1219
|
+
return run(async () => await scanArtifact(files, reference2, io.signal, true));
|
|
1220
|
+
} catch (cause) {
|
|
1221
|
+
return observed(Promise.reject(artifactFailure(cause)));
|
|
1222
|
+
}
|
|
1223
|
+
},
|
|
1224
|
+
snapshot: () => Object.freeze({ pending, maxPending: options.maxPending, maxBytes: options.maxBytes, ...files.snapshot() })
|
|
1225
|
+
});
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
// src/orchestration/log/execution-database.ts
|
|
1229
|
+
import { DatabaseSync as DatabaseSync4 } from "node:sqlite";
|
|
1230
|
+
|
|
1231
|
+
// src/orchestration/log/execution-storage.ts
|
|
1232
|
+
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
1233
|
+
import { closeSync as closeSync2, fsyncSync as fsyncSync2, linkSync as linkSync2, lstatSync as lstatSync2, openSync as openSync2, unlinkSync as unlinkSync2 } from "node:fs";
|
|
1234
|
+
import { dirname as dirname3 } from "node:path";
|
|
1235
|
+
import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
|
|
1236
|
+
|
|
1237
|
+
// src/orchestration/log/execution-types.ts
|
|
1238
|
+
var failures = ["INVALID_STATE", "STORAGE_UNCERTAIN", "INTEGRITY", "RUN_OWNED", "EFFECT_BINDING_CONFLICT", "OUTCOME_UNKNOWN", "CLOSED", "PAYLOAD_CODEC_REQUIRED", "PAYLOAD_UNAVAILABLE", "CODEC_LIMIT", "CODEC_BUSY"];
|
|
1239
|
+
var genuine = /* @__PURE__ */ new WeakSet();
|
|
1240
|
+
var LogExecutionError = class extends ExecutionHaltedError {
|
|
1241
|
+
reason;
|
|
1242
|
+
constructor(reason) {
|
|
1243
|
+
const safe = failures.includes(reason) ? reason : "INVALID_STATE";
|
|
1244
|
+
super({ sanitizedDiagnostics: Object.freeze({ reason: safe }) });
|
|
1245
|
+
this.reason = safe;
|
|
1246
|
+
genuine.add(this);
|
|
1247
|
+
Object.freeze(this);
|
|
1248
|
+
}
|
|
1249
|
+
};
|
|
1250
|
+
function executionFailure(reason) {
|
|
1251
|
+
throw new LogExecutionError(reason);
|
|
1252
|
+
}
|
|
1253
|
+
function safeExecutionFailure(error) {
|
|
1254
|
+
rethrowExecutionHalt(error);
|
|
1255
|
+
if (error && typeof error === "object" && genuine.has(error)) throw error;
|
|
1256
|
+
return executionFailure("STORAGE_UNCERTAIN");
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
// src/orchestration/log/execution-schema.ts
|
|
1260
|
+
var EXECUTION_APPLICATION_ID = 1329680965;
|
|
1261
|
+
var EXECUTION_DDL = Object.freeze([
|
|
1262
|
+
`CREATE TABLE oar_execution_leases (kind TEXT NOT NULL CHECK(kind IN ('decision','workflow')),run_key TEXT NOT NULL,
|
|
1263
|
+
owner_json TEXT NOT NULL CHECK(json_valid(owner_json) AND kind IS json_extract(owner_json,'$.kind') AND run_key IS json_extract(owner_json,'$.runKey')),
|
|
1264
|
+
owner_digest TEXT NOT NULL,PRIMARY KEY(kind,run_key)) STRICT`,
|
|
1265
|
+
`CREATE TABLE oar_execution_effects (effect_id TEXT PRIMARY KEY NOT NULL,run_key TEXT NOT NULL,step_id TEXT NOT NULL,
|
|
1266
|
+
generation INTEGER NOT NULL,decision_id TEXT NOT NULL,association_json TEXT NOT NULL CHECK(json_valid(association_json)
|
|
1267
|
+
AND step_id IS json_extract(association_json,'$.stepId') AND generation IS json_extract(association_json,'$.identity.generation')),
|
|
1268
|
+
association_digest TEXT NOT NULL,UNIQUE(generation,decision_id)) STRICT`,
|
|
1269
|
+
`CREATE TABLE oar_execution_states (kind TEXT NOT NULL CHECK(kind IN ('decision','workflow')),state_key TEXT NOT NULL,
|
|
1270
|
+
identity_json TEXT NOT NULL CHECK(json_valid(identity_json)),identity_digest TEXT NOT NULL,
|
|
1271
|
+
revision INTEGER NOT NULL CHECK(revision BETWEEN 1 AND 9007199254740991),record_json TEXT NOT NULL CHECK(json_valid(record_json)),record_digest TEXT NOT NULL,
|
|
1272
|
+
sequence INTEGER NOT NULL REFERENCES oar_log_events(sequence),event_digest TEXT NOT NULL,request_id TEXT NOT NULL REFERENCES oar_log_requests(request_id),
|
|
1273
|
+
PRIMARY KEY(kind,state_key)) STRICT`,
|
|
1274
|
+
`CREATE TRIGGER oar_execution_effects_update BEFORE UPDATE ON oar_execution_effects BEGIN SELECT RAISE(ABORT,'immutable managed association'); END`,
|
|
1275
|
+
`CREATE TRIGGER oar_execution_effects_delete BEFORE DELETE ON oar_execution_effects BEGIN SELECT RAISE(ABORT,'immutable managed association'); END`,
|
|
1276
|
+
`CREATE TRIGGER oar_execution_states_delete BEFORE DELETE ON oar_execution_states BEGIN SELECT RAISE(ABORT,'immutable managed state'); END`,
|
|
1277
|
+
`CREATE TRIGGER oar_execution_states_key BEFORE UPDATE OF kind,state_key,identity_json,identity_digest ON oar_execution_states BEGIN SELECT RAISE(ABORT,'immutable managed state'); END`
|
|
1278
|
+
]);
|
|
1279
|
+
var expected2 = new Map([...LOG_DDL, ...EXECUTION_DDL].map((sql) => [sql.match(/^CREATE (?:TABLE|TRIGGER) (\w+)/)[1], sql]));
|
|
1280
|
+
for (const table of ["oar_log_requests", "oar_log_events", "oar_execution_leases", "oar_execution_effects", "oar_execution_states"]) expected2.set(`sqlite_autoindex_${table}_1`, "");
|
|
1281
|
+
expected2.set("sqlite_autoindex_oar_execution_effects_2", "");
|
|
1282
|
+
function installExecutionSchema(db) {
|
|
1283
|
+
for (const sql of EXECUTION_DDL) db.exec(sql);
|
|
1284
|
+
db.exec(`PRAGMA application_id=${EXECUTION_APPLICATION_ID}; PRAGMA user_version=1`);
|
|
1285
|
+
}
|
|
1286
|
+
function validateExecutionSchema(db, full = true) {
|
|
1287
|
+
if (db.prepare("PRAGMA main.application_id").get()?.application_id !== EXECUTION_APPLICATION_ID || db.prepare("PRAGMA main.user_version").get()?.user_version !== 1) executionFailure("INTEGRITY");
|
|
1288
|
+
const objects = db.prepare("SELECT name,sql FROM main.sqlite_schema").all();
|
|
1289
|
+
if (objects.length !== expected2.size || objects.some((row) => !expected2.has(String(row.name)) || (row.sql ?? "") !== expected2.get(String(row.name)))) executionFailure("INTEGRITY");
|
|
1290
|
+
if (full && db.prepare("PRAGMA main.foreign_key_check").all().length) executionFailure("INTEGRITY");
|
|
1291
|
+
}
|
|
1292
|
+
|
|
1293
|
+
// src/orchestration/log/execution-storage.ts
|
|
1294
|
+
function publishExecutionDatabase(path, systemId, busyTimeoutMs) {
|
|
1295
|
+
try {
|
|
1296
|
+
lstatSync2(path);
|
|
1297
|
+
return;
|
|
1298
|
+
} catch (error) {
|
|
1299
|
+
if (error.code !== "ENOENT") throw error;
|
|
1300
|
+
}
|
|
1301
|
+
const temporary = `${path}.${randomUUID3()}.initializing`;
|
|
1302
|
+
let db;
|
|
1303
|
+
try {
|
|
1304
|
+
publishLog(temporary, systemId);
|
|
1305
|
+
db = new DatabaseSync3(temporary);
|
|
1306
|
+
db.exec(`PRAGMA foreign_keys=ON; PRAGMA synchronous=FULL; PRAGMA busy_timeout=${busyTimeoutMs}; BEGIN IMMEDIATE`);
|
|
1307
|
+
installExecutionSchema(db);
|
|
1308
|
+
db.exec("COMMIT");
|
|
1309
|
+
db.close();
|
|
1310
|
+
db = void 0;
|
|
1311
|
+
const file2 = openSync2(temporary, "r");
|
|
1312
|
+
try {
|
|
1313
|
+
fsyncSync2(file2);
|
|
1314
|
+
} finally {
|
|
1315
|
+
closeSync2(file2);
|
|
1316
|
+
}
|
|
1317
|
+
try {
|
|
1318
|
+
linkSync2(temporary, path);
|
|
1319
|
+
} catch (error) {
|
|
1320
|
+
if (error.code !== "EEXIST") throw error;
|
|
1321
|
+
}
|
|
1322
|
+
const parent = openSync2(dirname3(path), "r");
|
|
1323
|
+
try {
|
|
1324
|
+
fsyncSync2(parent);
|
|
1325
|
+
} finally {
|
|
1326
|
+
closeSync2(parent);
|
|
1327
|
+
}
|
|
1328
|
+
} finally {
|
|
1329
|
+
db?.close();
|
|
1330
|
+
try {
|
|
1331
|
+
unlinkSync2(temporary);
|
|
1332
|
+
} catch (error) {
|
|
1333
|
+
if (error.code !== "ENOENT") throw error;
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
// src/orchestration/log/execution-validation.ts
|
|
1339
|
+
var neutral = { systemId: "validation", generation: 1, runId: "validation", agentId: "validation", harness: { id: "sdk", version: "1", digest: "0".repeat(64) } };
|
|
1340
|
+
function captureExecutionValue(input2) {
|
|
1341
|
+
try {
|
|
1342
|
+
return captureLogCommit({ requestId: "capture", records: [{ identity: neutral, schema: { id: "capture", version: 1 }, type: "capture", causal: [], payload: { inline: input2 } }] }).records[0].payload.inline;
|
|
1343
|
+
} catch {
|
|
1344
|
+
return executionFailure("PAYLOAD_CODEC_REQUIRED");
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
function runKey(sourceId, identity2) {
|
|
1348
|
+
return digest(canonical({ sourceId, identity: identity2 }));
|
|
1349
|
+
}
|
|
1350
|
+
function effectId(association) {
|
|
1351
|
+
return digest(canonical({ sourceId: association.sourceId, systemId: association.identity.systemId, generation: association.identity.generation, effectKey: association.effectKey }));
|
|
1352
|
+
}
|
|
1353
|
+
function captureAssociation(input2, sourceId, systemId) {
|
|
1354
|
+
try {
|
|
1355
|
+
const next = captureExecutionValue(input2);
|
|
1356
|
+
object(next, ["identity", "stepId", "effectKey", "operation", "parentEffectKey"]);
|
|
1357
|
+
const identity2 = captureIdentity2(next.identity);
|
|
1358
|
+
if (identity2.systemId !== systemId) executionFailure("INVALID_STATE");
|
|
1359
|
+
identifier(next.stepId);
|
|
1360
|
+
identifier(next.effectKey);
|
|
1361
|
+
if (next.parentEffectKey !== void 0) identifier(next.parentEffectKey);
|
|
1362
|
+
const operation = next.operation;
|
|
1363
|
+
object(operation, ["id", "version", "targetDigest", "contentDigest", "provider", "model"]);
|
|
1364
|
+
identifier(operation.id);
|
|
1365
|
+
identifier(operation.version);
|
|
1366
|
+
hash(operation.targetDigest);
|
|
1367
|
+
hash(operation.contentDigest);
|
|
1368
|
+
if (operation.provider !== void 0) identifier(operation.provider);
|
|
1369
|
+
if (operation.model !== void 0) identifier(operation.model);
|
|
1370
|
+
if (Object.keys(next).length < 4 || Object.keys(operation).length < 4 || next.parentEffectKey === next.effectKey) executionFailure("INVALID_STATE");
|
|
1371
|
+
return freeze({ ...next, sourceId, identity: identity2 });
|
|
1372
|
+
} catch {
|
|
1373
|
+
return executionFailure("INVALID_STATE");
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
function decodeExecutionValue(text2, expectedDigest) {
|
|
1377
|
+
try {
|
|
1378
|
+
if (typeof text2 !== "string" || Buffer.byteLength(text2) > 6e4 || digest(text2) !== expectedDigest) executionFailure("INTEGRITY");
|
|
1379
|
+
const value = captureExecutionValue(JSON.parse(text2));
|
|
1380
|
+
if (JSON.stringify(value) !== text2) executionFailure("INTEGRITY");
|
|
1381
|
+
return value;
|
|
1382
|
+
} catch {
|
|
1383
|
+
return executionFailure("INTEGRITY");
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
// src/orchestration/log/leases.ts
|
|
1388
|
+
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
1389
|
+
var active = /* @__PURE__ */ new Set();
|
|
1390
|
+
function activeKey(context, ownerId) {
|
|
1391
|
+
return `${context.storageDigest}:${ownerId}`;
|
|
1392
|
+
}
|
|
1393
|
+
function inspectOwner(context, kind, key) {
|
|
1394
|
+
const row = context.db.prepare("SELECT owner_json,owner_digest FROM main.oar_execution_leases WHERE kind=? AND run_key=?").get(kind, key);
|
|
1395
|
+
if (!row) return void 0;
|
|
1396
|
+
try {
|
|
1397
|
+
if (typeof row.owner_json !== "string" || row.owner_json.length > 4096 || digest(row.owner_json) !== row.owner_digest) executionFailure("INTEGRITY");
|
|
1398
|
+
const owner = JSON.parse(row.owner_json);
|
|
1399
|
+
object(owner, ["format", "sourceId", "kind", "runKey", "identity", "ownerId"]);
|
|
1400
|
+
if (Object.keys(owner).length !== 6 || canonical(owner) !== row.owner_json || owner.format !== 1 || owner.sourceId !== context.source.sourceId || owner.kind !== kind || owner.runKey !== key || typeof owner.ownerId !== "string" || !/^[\da-f-]{36}$/.test(owner.ownerId)) executionFailure("INTEGRITY");
|
|
1401
|
+
const identity2 = captureIdentity2(owner.identity);
|
|
1402
|
+
if (identity2.systemId !== context.source.systemId || runKey(context.source.sourceId, identity2) !== key) executionFailure("INTEGRITY");
|
|
1403
|
+
return freeze(owner);
|
|
1404
|
+
} catch {
|
|
1405
|
+
return executionFailure("INTEGRITY");
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
function ownerEvent(context, owner, type) {
|
|
1409
|
+
context.binding.appendInTransaction({ requestId: `owner:${type}:${owner.ownerId}`, records: [{ identity: owner.identity, schema: { id: "oar.execution.ownership", version: 1 }, type: `ownership.${type}`, causal: [], payload: { inline: owner } }] });
|
|
1410
|
+
}
|
|
1411
|
+
function acquireOwner(context, kind, identity2) {
|
|
1412
|
+
const key = runKey(context.source.sourceId, identity2);
|
|
1413
|
+
if (inspectOwner(context, kind, key)) executionFailure("RUN_OWNED");
|
|
1414
|
+
const owner = freeze({ format: 1, sourceId: context.source.sourceId, kind, runKey: key, identity: identity2, ownerId: randomUUID4() });
|
|
1415
|
+
const encoded = canonical(owner);
|
|
1416
|
+
context.db.prepare("INSERT INTO main.oar_execution_leases VALUES(?,?,?,?)").run(kind, key, encoded, digest(encoded));
|
|
1417
|
+
ownerEvent(context, owner, "acquired");
|
|
1418
|
+
return owner;
|
|
1419
|
+
}
|
|
1420
|
+
function markOwnerActive(context, owner) {
|
|
1421
|
+
active.add(activeKey(context, owner.ownerId));
|
|
1422
|
+
}
|
|
1423
|
+
function markOwnerDrained(context, owner) {
|
|
1424
|
+
active.delete(activeKey(context, owner.ownerId));
|
|
1425
|
+
}
|
|
1426
|
+
function assertOwner(context, owner) {
|
|
1427
|
+
context.assert();
|
|
1428
|
+
const actual = inspectOwner(context, owner.kind, owner.runKey);
|
|
1429
|
+
if (!actual || canonical(actual) !== canonical(owner)) executionFailure("RUN_OWNED");
|
|
1430
|
+
}
|
|
1431
|
+
function releaseOwner(context, owner) {
|
|
1432
|
+
assertOwner(context, owner);
|
|
1433
|
+
ownerEvent(context, owner, "released");
|
|
1434
|
+
if (context.db.prepare("DELETE FROM main.oar_execution_leases WHERE kind=? AND run_key=? AND owner_digest=?").run(owner.kind, owner.runKey, digest(canonical(owner))).changes !== 1) executionFailure("RUN_OWNED");
|
|
1435
|
+
}
|
|
1436
|
+
function recoverOwner(context, expected3) {
|
|
1437
|
+
try {
|
|
1438
|
+
object(expected3, ["format", "sourceId", "kind", "runKey", "identity", "ownerId"]);
|
|
1439
|
+
if (!["decision", "workflow"].includes(expected3.kind) || typeof expected3.runKey !== "string") executionFailure("INVALID_STATE");
|
|
1440
|
+
const owner = inspectOwner(context, expected3.kind, expected3.runKey);
|
|
1441
|
+
if (!owner || canonical(owner) !== canonical(expected3) || active.has(activeKey(context, owner.ownerId))) executionFailure("RUN_OWNED");
|
|
1442
|
+
ownerEvent(context, owner, "operator-recovered");
|
|
1443
|
+
context.db.prepare("DELETE FROM main.oar_execution_leases WHERE kind=? AND run_key=? AND owner_digest=?").run(owner.kind, owner.runKey, digest(canonical(owner)));
|
|
1444
|
+
} catch {
|
|
1445
|
+
return executionFailure("RUN_OWNED");
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
|
|
1449
|
+
// src/orchestration/log/record-codec.ts
|
|
1450
|
+
import { types as types5 } from "node:util";
|
|
1451
|
+
|
|
1452
|
+
// src/orchestration/log/record-json.ts
|
|
1453
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
1454
|
+
import { types as types4 } from "node:util";
|
|
1455
|
+
import { setImmediate as setImmediate3 } from "node:timers/promises";
|
|
1456
|
+
var MAX_NODES = 65536;
|
|
1457
|
+
var MAX_DEPTH = 64;
|
|
1458
|
+
var CHUNK = 65536;
|
|
1459
|
+
async function pause(check) {
|
|
1460
|
+
await setImmediate3();
|
|
1461
|
+
check();
|
|
1462
|
+
}
|
|
1463
|
+
async function captureRecordJson(input2, limits, check) {
|
|
1464
|
+
let nodes = 0, bytes = 0;
|
|
1465
|
+
const ancestors = /* @__PURE__ */ new Set();
|
|
1466
|
+
async function visit(value, depth) {
|
|
1467
|
+
if (++nodes > MAX_NODES || depth > MAX_DEPTH) executionFailure("CODEC_LIMIT");
|
|
1468
|
+
if (nodes % 256 === 0) await pause(check);
|
|
1469
|
+
if (typeof value === "string") {
|
|
1470
|
+
if (/[\ud800-\udfff]/u.test(value)) executionFailure("INVALID_STATE");
|
|
1471
|
+
bytes += Buffer.byteLength(value);
|
|
1472
|
+
if (bytes > limits.maxBytes) executionFailure("CODEC_LIMIT");
|
|
1473
|
+
return value;
|
|
1474
|
+
}
|
|
1475
|
+
if (value === null || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) return value;
|
|
1476
|
+
if (!value || typeof value !== "object" || types4.isProxy(value) || ancestors.has(value) || Object.getOwnPropertySymbols(value).length) executionFailure("INVALID_STATE");
|
|
1477
|
+
const array = Array.isArray(value), prototype = Object.getPrototypeOf(value);
|
|
1478
|
+
if (array ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) executionFailure("INVALID_STATE");
|
|
1479
|
+
const names = Object.getOwnPropertyNames(value);
|
|
1480
|
+
if (names.length > MAX_NODES + 1 || array && names.length !== value.length + 1) executionFailure("CODEC_LIMIT");
|
|
1481
|
+
const captured2 = array ? [] : /* @__PURE__ */ Object.create(null);
|
|
1482
|
+
ancestors.add(value);
|
|
1483
|
+
let index = 0;
|
|
1484
|
+
try {
|
|
1485
|
+
for (const key of names) {
|
|
1486
|
+
if (array && key === "length") continue;
|
|
1487
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
1488
|
+
if (array && key !== String(index++) || !Object.hasOwn(descriptor, "value") || !descriptor.enumerable) executionFailure("INVALID_STATE");
|
|
1489
|
+
if (/[\ud800-\udfff]/u.test(key)) executionFailure("INVALID_STATE");
|
|
1490
|
+
bytes += Buffer.byteLength(key);
|
|
1491
|
+
if (bytes > limits.maxBytes) executionFailure("CODEC_LIMIT");
|
|
1492
|
+
const child = await visit(descriptor.value, depth + 1);
|
|
1493
|
+
check();
|
|
1494
|
+
Object.defineProperty(captured2, key, { value: child, enumerable: true });
|
|
1495
|
+
}
|
|
1496
|
+
return Object.freeze(captured2);
|
|
1497
|
+
} finally {
|
|
1498
|
+
ancestors.delete(value);
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
check();
|
|
1502
|
+
const captured = await visit(input2, 1);
|
|
1503
|
+
check();
|
|
1504
|
+
return captured;
|
|
1505
|
+
}
|
|
1506
|
+
function* quoted(value) {
|
|
1507
|
+
if (/[\ud800-\udfff]/u.test(value)) executionFailure("INVALID_STATE");
|
|
1508
|
+
yield '"';
|
|
1509
|
+
for (let start = 0; start < value.length; ) {
|
|
1510
|
+
let end = Math.min(value.length, start + 4096);
|
|
1511
|
+
if (end < value.length && value.charCodeAt(end - 1) >= 55296 && value.charCodeAt(end - 1) <= 56319 && value.charCodeAt(end) >= 56320 && value.charCodeAt(end) <= 57343) end--;
|
|
1512
|
+
yield JSON.stringify(value.slice(start, end)).slice(1, -1);
|
|
1513
|
+
start = end;
|
|
1514
|
+
}
|
|
1515
|
+
yield '"';
|
|
1516
|
+
}
|
|
1517
|
+
function* fragments(value) {
|
|
1518
|
+
if (typeof value === "string") {
|
|
1519
|
+
yield* quoted(value);
|
|
1520
|
+
return;
|
|
1521
|
+
}
|
|
1522
|
+
if (value === null || typeof value !== "object") {
|
|
1523
|
+
yield JSON.stringify(value);
|
|
1524
|
+
return;
|
|
1525
|
+
}
|
|
1526
|
+
const array = Array.isArray(value);
|
|
1527
|
+
yield array ? "[" : "{";
|
|
1528
|
+
let first = true;
|
|
1529
|
+
for (const key of Object.keys(value)) {
|
|
1530
|
+
if (!first) yield ",";
|
|
1531
|
+
first = false;
|
|
1532
|
+
if (!array) {
|
|
1533
|
+
yield* quoted(key);
|
|
1534
|
+
yield ":";
|
|
1535
|
+
}
|
|
1536
|
+
yield* fragments(value[key]);
|
|
1537
|
+
}
|
|
1538
|
+
yield array ? "]" : "}";
|
|
1539
|
+
}
|
|
1540
|
+
async function encode(value, limits, check, retain) {
|
|
1541
|
+
const chunks = [], hash2 = createHash2("sha256");
|
|
1542
|
+
let total = 0, buffer = Buffer.allocUnsafe(CHUNK), used = 0;
|
|
1543
|
+
for (const text2 of fragments(value)) {
|
|
1544
|
+
const bytes = Buffer.from(text2);
|
|
1545
|
+
total += bytes.length;
|
|
1546
|
+
if (total > limits.maxBytes) executionFailure("CODEC_LIMIT");
|
|
1547
|
+
for (let offset = 0; offset < bytes.length; ) {
|
|
1548
|
+
const copied = Math.min(bytes.length - offset, CHUNK - used);
|
|
1549
|
+
bytes.copy(buffer, used, offset, offset + copied);
|
|
1550
|
+
used += copied;
|
|
1551
|
+
offset += copied;
|
|
1552
|
+
if (used === CHUNK) {
|
|
1553
|
+
hash2.update(buffer);
|
|
1554
|
+
if (retain) chunks.push(buffer);
|
|
1555
|
+
await pause(check);
|
|
1556
|
+
buffer = Buffer.allocUnsafe(CHUNK);
|
|
1557
|
+
used = 0;
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
if (used) {
|
|
1562
|
+
hash2.update(buffer.subarray(0, used));
|
|
1563
|
+
if (retain) chunks.push(buffer.subarray(0, used));
|
|
1564
|
+
await pause(check);
|
|
1565
|
+
}
|
|
1566
|
+
return { digest: hash2.digest("hex"), bytes: retain ? Buffer.concat(chunks, total) : void 0, length: total };
|
|
1567
|
+
}
|
|
1568
|
+
async function encodeRecordJson(value, limits, check) {
|
|
1569
|
+
const encoded = await encode(value, limits, check, true);
|
|
1570
|
+
return { digest: encoded.digest, bytes: encoded.bytes };
|
|
1571
|
+
}
|
|
1572
|
+
async function preflight(text2, check) {
|
|
1573
|
+
let depth = 0, tokens = 0, string = false, escaped = false, literal = false;
|
|
1574
|
+
for (let index = 0; index < text2.length; index++) {
|
|
1575
|
+
const char = text2[index];
|
|
1576
|
+
if (string) {
|
|
1577
|
+
if (escaped) escaped = false;
|
|
1578
|
+
else if (char === "\\") escaped = true;
|
|
1579
|
+
else if (char === '"') string = false;
|
|
1580
|
+
} else if (char === '"') {
|
|
1581
|
+
string = true;
|
|
1582
|
+
literal = false;
|
|
1583
|
+
tokens++;
|
|
1584
|
+
} else if (char === "{" || char === "[") {
|
|
1585
|
+
if (++depth > MAX_DEPTH) executionFailure("CODEC_LIMIT");
|
|
1586
|
+
tokens++;
|
|
1587
|
+
literal = false;
|
|
1588
|
+
} else if (char === "}" || char === "]") {
|
|
1589
|
+
if (--depth < 0) executionFailure("INVALID_STATE");
|
|
1590
|
+
literal = false;
|
|
1591
|
+
} else if (char === "," || char === ":" || char === " " || char === "\r" || char === "\n" || char === " ") literal = false;
|
|
1592
|
+
else if (!literal) {
|
|
1593
|
+
tokens++;
|
|
1594
|
+
literal = true;
|
|
1595
|
+
}
|
|
1596
|
+
if (tokens > MAX_NODES * 2) executionFailure("CODEC_LIMIT");
|
|
1597
|
+
if (index && index % CHUNK === 0) await pause(check);
|
|
1598
|
+
}
|
|
1599
|
+
if (depth || string || escaped) executionFailure("INVALID_STATE");
|
|
1600
|
+
}
|
|
1601
|
+
async function decodeRecordJson(bytes, expectedDigest, limits, check) {
|
|
1602
|
+
if (types4.isProxy(bytes) || !types4.isUint8Array(bytes)) executionFailure("PAYLOAD_UNAVAILABLE");
|
|
1603
|
+
const length = Reflect.apply(Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "byteLength").get, bytes, []);
|
|
1604
|
+
if (length > limits.maxBytes) executionFailure("CODEC_LIMIT");
|
|
1605
|
+
let text2;
|
|
1606
|
+
try {
|
|
1607
|
+
text2 = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
|
|
1608
|
+
} catch {
|
|
1609
|
+
return executionFailure("PAYLOAD_UNAVAILABLE");
|
|
1610
|
+
}
|
|
1611
|
+
await preflight(text2, check);
|
|
1612
|
+
check();
|
|
1613
|
+
let parsed;
|
|
1614
|
+
try {
|
|
1615
|
+
parsed = JSON.parse(text2);
|
|
1616
|
+
} catch {
|
|
1617
|
+
return executionFailure("PAYLOAD_UNAVAILABLE");
|
|
1618
|
+
}
|
|
1619
|
+
const captured = await captureRecordJson(parsed, limits, check), encoded = await encode(captured, limits, check, false);
|
|
1620
|
+
if (encoded.digest !== expectedDigest || encoded.length !== length) executionFailure("PAYLOAD_UNAVAILABLE");
|
|
1621
|
+
return captured;
|
|
1622
|
+
}
|
|
1623
|
+
|
|
1624
|
+
// src/orchestration/log/record-codec.ts
|
|
1625
|
+
function captureRecordBody(input2, sourceId, identity2, maxBytes) {
|
|
1626
|
+
try {
|
|
1627
|
+
object(input2, ["codec", "version", "reference"]);
|
|
1628
|
+
if (Object.keys(input2).length !== 3 || input2.codec !== "oar.execution.record-json" || input2.version !== 1) executionFailure("PAYLOAD_UNAVAILABLE");
|
|
1629
|
+
const checked = captureLogCommit({ requestId: "reference", records: [{ identity: identity2, schema: { id: "reference", version: 1 }, type: "reference", causal: [], payload: { artifact: input2.reference } }] });
|
|
1630
|
+
const reference2 = checked.records[0].payload.artifact;
|
|
1631
|
+
if (reference2.sourceId !== sourceId || reference2.bytes > maxBytes || reference2.mediaType !== "application/json") executionFailure("PAYLOAD_UNAVAILABLE");
|
|
1632
|
+
return Object.freeze({ codec: "oar.execution.record-json", version: 1, reference: reference2 });
|
|
1633
|
+
} catch {
|
|
1634
|
+
return executionFailure("PAYLOAD_UNAVAILABLE");
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
var RecordCodec = class {
|
|
1638
|
+
maxBytes;
|
|
1639
|
+
port;
|
|
1640
|
+
#controller = new AbortController();
|
|
1641
|
+
#pending = 0;
|
|
1642
|
+
constructor(input2, maxBytes = 128 * 1024 * 1024) {
|
|
1643
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 65536 || maxBytes > 128 * 1024 * 1024) executionFailure("INVALID_STATE");
|
|
1644
|
+
this.maxBytes = maxBytes;
|
|
1645
|
+
try {
|
|
1646
|
+
this.port = input2 ? Object.freeze({ write: method(input2, "write"), read: method(input2, "read"), verify: method(input2, "verify") }) : void 0;
|
|
1647
|
+
} catch {
|
|
1648
|
+
return executionFailure("INVALID_STATE");
|
|
1649
|
+
}
|
|
1650
|
+
}
|
|
1651
|
+
close() {
|
|
1652
|
+
this.#controller.abort();
|
|
1653
|
+
}
|
|
1654
|
+
async operation(body) {
|
|
1655
|
+
if (this.#controller.signal.aborted) executionFailure("CLOSED");
|
|
1656
|
+
if (this.#pending >= 2) executionFailure("CODEC_BUSY");
|
|
1657
|
+
this.#pending++;
|
|
1658
|
+
try {
|
|
1659
|
+
return await body();
|
|
1660
|
+
} finally {
|
|
1661
|
+
this.#pending--;
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
capture(input2, check) {
|
|
1665
|
+
return captureRecordJson(input2, { maxBytes: this.maxBytes }, check);
|
|
1666
|
+
}
|
|
1667
|
+
encode(input2, check) {
|
|
1668
|
+
return encodeRecordJson(input2, { maxBytes: this.maxBytes }, check);
|
|
1669
|
+
}
|
|
1670
|
+
async stage(bytes, digest2, sourceId, identity2, check) {
|
|
1671
|
+
if (!this.port) executionFailure("PAYLOAD_CODEC_REQUIRED");
|
|
1672
|
+
try {
|
|
1673
|
+
const reference2 = await this.port.write(bytes, { mediaType: "application/json", signal: this.#controller.signal });
|
|
1674
|
+
check();
|
|
1675
|
+
const body = captureRecordBody({ codec: "oar.execution.record-json", version: 1, reference: reference2 }, sourceId, identity2, this.maxBytes);
|
|
1676
|
+
if (body.reference.bytes !== bytes.length || body.reference.digest !== digest2) executionFailure("PAYLOAD_UNAVAILABLE");
|
|
1677
|
+
return body;
|
|
1678
|
+
} catch (error) {
|
|
1679
|
+
return this.#failure(error, check);
|
|
1680
|
+
}
|
|
1681
|
+
}
|
|
1682
|
+
async hydrate(body, digest2, check) {
|
|
1683
|
+
if (!this.port) executionFailure("PAYLOAD_CODEC_REQUIRED");
|
|
1684
|
+
hash(digest2);
|
|
1685
|
+
if (body.reference.digest !== digest2) executionFailure("PAYLOAD_UNAVAILABLE");
|
|
1686
|
+
let owned;
|
|
1687
|
+
try {
|
|
1688
|
+
const bytes = await this.port.read(body.reference, { signal: this.#controller.signal });
|
|
1689
|
+
check();
|
|
1690
|
+
if (types5.isProxy(bytes) || !types5.isUint8Array(bytes)) executionFailure("PAYLOAD_UNAVAILABLE");
|
|
1691
|
+
const length = Reflect.apply(Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), "byteLength").get, bytes, []);
|
|
1692
|
+
if (length !== body.reference.bytes || length > this.maxBytes) executionFailure("CODEC_LIMIT");
|
|
1693
|
+
owned = Buffer.allocUnsafe(length);
|
|
1694
|
+
Reflect.apply(Uint8Array.prototype.set, owned, [bytes]);
|
|
1695
|
+
const record = await decodeRecordJson(owned, digest2, { maxBytes: this.maxBytes }, check);
|
|
1696
|
+
check();
|
|
1697
|
+
return record;
|
|
1698
|
+
} catch (error) {
|
|
1699
|
+
return this.#failure(error, check);
|
|
1700
|
+
} finally {
|
|
1701
|
+
owned?.fill(0);
|
|
1702
|
+
}
|
|
1703
|
+
}
|
|
1704
|
+
async verify(reference2, options) {
|
|
1705
|
+
if (!this.port) executionFailure("PAYLOAD_CODEC_REQUIRED");
|
|
1706
|
+
return this.port.verify(reference2, options);
|
|
1707
|
+
}
|
|
1708
|
+
#failure(error, check) {
|
|
1709
|
+
try {
|
|
1710
|
+
check();
|
|
1711
|
+
} catch (secondary) {
|
|
1712
|
+
if (isExecutionHalted(error)) throw new AggregateError([error, secondary], "Execution halted during body validation", { cause: error });
|
|
1713
|
+
throw secondary;
|
|
1714
|
+
}
|
|
1715
|
+
if (isExecutionHalted(error)) throw error;
|
|
1716
|
+
return executionFailure("PAYLOAD_UNAVAILABLE");
|
|
1717
|
+
}
|
|
1718
|
+
};
|
|
1719
|
+
|
|
1720
|
+
// src/orchestration/log/execution-capture.ts
|
|
1721
|
+
function executionCaptureStore(context) {
|
|
1722
|
+
let pending = 0;
|
|
1723
|
+
return Object.freeze({ async append(input2) {
|
|
1724
|
+
context.assert();
|
|
1725
|
+
if (pending >= 2) executionFailure("CODEC_BUSY");
|
|
1726
|
+
let commit;
|
|
1727
|
+
try {
|
|
1728
|
+
commit = capture(input2, context.source);
|
|
1729
|
+
for (const record of commit.records) {
|
|
1730
|
+
if (record.schema.version !== 1 || ![AGENT_METADATA_SCHEMA, CAPTURE_OPERATION_SCHEMA].includes(record.schema.id) || !("inline" in record.payload)) executionFailure("INVALID_STATE");
|
|
1731
|
+
decodeCaptureMetadata(record.schema.id, record.type, record.payload.inline);
|
|
1732
|
+
}
|
|
1733
|
+
} catch {
|
|
1734
|
+
return executionFailure("INVALID_STATE");
|
|
1735
|
+
}
|
|
1736
|
+
pending++;
|
|
1737
|
+
try {
|
|
1738
|
+
const prepared2 = await context.binding.prepare(commit);
|
|
1739
|
+
return context.transaction(() => context.binding.appendInTransaction(prepared2), true);
|
|
1740
|
+
} catch (error) {
|
|
1741
|
+
return safeExecutionFailure(error);
|
|
1742
|
+
} finally {
|
|
1743
|
+
pending--;
|
|
1744
|
+
}
|
|
1745
|
+
} });
|
|
1746
|
+
}
|
|
1747
|
+
|
|
1748
|
+
// src/orchestration/log/execution-database.ts
|
|
1749
|
+
var contexts = /* @__PURE__ */ new WeakMap();
|
|
1750
|
+
function executionContext(database) {
|
|
1751
|
+
const context = contexts.get(database);
|
|
1752
|
+
if (!context) executionFailure("INVALID_STATE");
|
|
1753
|
+
context.assert();
|
|
1754
|
+
return context;
|
|
1755
|
+
}
|
|
1756
|
+
var LogExecutionDatabase = class {
|
|
1757
|
+
sourceId;
|
|
1758
|
+
descriptor;
|
|
1759
|
+
captureStore;
|
|
1760
|
+
#db;
|
|
1761
|
+
#binding;
|
|
1762
|
+
#pin;
|
|
1763
|
+
#codec;
|
|
1764
|
+
#closed = false;
|
|
1765
|
+
#dataVersion;
|
|
1766
|
+
#ownedTransaction = false;
|
|
1767
|
+
constructor(options) {
|
|
1768
|
+
let db;
|
|
1769
|
+
try {
|
|
1770
|
+
options = ownObject(options, ["databasePath", "systemId", "busyTimeoutMs", "artifactStore", "maxRecordBytes"]);
|
|
1771
|
+
const config = configuration({ databasePath: options.databasePath, systemId: options.systemId, ...options.busyTimeoutMs !== void 0 ? { busyTimeoutMs: options.busyTimeoutMs } : {} });
|
|
1772
|
+
this.#codec = new RecordCodec(options.artifactStore, options.maxRecordBytes);
|
|
1773
|
+
publishExecutionDatabase(config.databasePath, config.systemId, config.busyTimeoutMs);
|
|
1774
|
+
db = new DatabaseSync4(config.databasePath);
|
|
1775
|
+
markSdkOwnedConnection(db);
|
|
1776
|
+
db.exec(`PRAGMA busy_timeout=${config.busyTimeoutMs}; PRAGMA foreign_keys=ON; PRAGMA synchronous=FULL`);
|
|
1777
|
+
const dataVersion = Number(db.prepare("PRAGMA main.data_version").get().data_version);
|
|
1778
|
+
validateExecutionSchema(db);
|
|
1779
|
+
this.#dataVersion = dataVersion;
|
|
1780
|
+
db.exec("BEGIN IMMEDIATE");
|
|
1781
|
+
this.#binding = new SqliteLogBinding(db, {
|
|
1782
|
+
databasePath: config.databasePath,
|
|
1783
|
+
systemId: config.systemId,
|
|
1784
|
+
...this.#codec.port ? { payloadVerifier: { verify: this.#codec.verify.bind(this.#codec) } } : {}
|
|
1785
|
+
});
|
|
1786
|
+
db.exec("COMMIT");
|
|
1787
|
+
this.#db = db;
|
|
1788
|
+
this.#pin = new LogConnection(db, config.databasePath, config.systemId, false);
|
|
1789
|
+
this.descriptor = this.#binding.descriptor;
|
|
1790
|
+
this.sourceId = this.descriptor.sourceId;
|
|
1791
|
+
for (const key of ["descriptor", "sourceId"]) Object.defineProperty(this, key, { writable: false, configurable: false });
|
|
1792
|
+
const context = {
|
|
1793
|
+
db,
|
|
1794
|
+
binding: this.#binding,
|
|
1795
|
+
source: this.descriptor,
|
|
1796
|
+
storageDigest: this.#pin.storageDigest,
|
|
1797
|
+
codec: this.#codec,
|
|
1798
|
+
assert: () => this.#assert(),
|
|
1799
|
+
transaction: (body, write2) => this.#transaction(body, write2)
|
|
1800
|
+
};
|
|
1801
|
+
contexts.set(this, context);
|
|
1802
|
+
this.captureStore = executionCaptureStore(context);
|
|
1803
|
+
Object.defineProperty(this, "captureStore", { writable: false, configurable: false });
|
|
1804
|
+
this.#assert();
|
|
1805
|
+
} catch (error) {
|
|
1806
|
+
db?.close();
|
|
1807
|
+
safeExecutionFailure(error);
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
#assert() {
|
|
1811
|
+
if (this.#closed) executionFailure("CLOSED");
|
|
1812
|
+
try {
|
|
1813
|
+
this.#pin.assert(this.#ownedTransaction);
|
|
1814
|
+
const dataVersion = Number(this.#db.prepare("PRAGMA main.data_version").get().data_version);
|
|
1815
|
+
validateExecutionSchema(this.#db, dataVersion !== this.#dataVersion);
|
|
1816
|
+
if (!this.#ownedTransaction && !this.#pin.inTransaction()) this.#dataVersion = dataVersion;
|
|
1817
|
+
} catch (error) {
|
|
1818
|
+
safeExecutionFailure(error);
|
|
1819
|
+
}
|
|
1820
|
+
}
|
|
1821
|
+
#transaction(body, write2 = false) {
|
|
1822
|
+
this.#assert();
|
|
1823
|
+
let began = false;
|
|
1824
|
+
try {
|
|
1825
|
+
this.#db.exec(write2 ? "BEGIN IMMEDIATE" : "BEGIN");
|
|
1826
|
+
began = true;
|
|
1827
|
+
this.#ownedTransaction = true;
|
|
1828
|
+
const result = body();
|
|
1829
|
+
this.#assert();
|
|
1830
|
+
this.#db.exec("COMMIT");
|
|
1831
|
+
return result;
|
|
1832
|
+
} catch (error) {
|
|
1833
|
+
if (began) {
|
|
1834
|
+
try {
|
|
1835
|
+
if (this.#db.isTransaction) this.#db.exec("ROLLBACK");
|
|
1836
|
+
} catch {
|
|
1837
|
+
}
|
|
1838
|
+
}
|
|
1839
|
+
return safeExecutionFailure(error);
|
|
1840
|
+
} finally {
|
|
1841
|
+
if (began) this.#ownedTransaction = false;
|
|
1842
|
+
}
|
|
1843
|
+
}
|
|
1844
|
+
async readPage(query = {}) {
|
|
1845
|
+
const captured = captureQuery(query);
|
|
1846
|
+
return this.#transaction(() => pageRecords(this.#db, this.descriptor, this.#pin.storageDigest, captured));
|
|
1847
|
+
}
|
|
1848
|
+
inspectOwnership(kind, input2) {
|
|
1849
|
+
const identity2 = captureIdentity2(input2);
|
|
1850
|
+
if (identity2.systemId !== this.descriptor.systemId || !["decision", "workflow"].includes(kind)) executionFailure("INVALID_STATE");
|
|
1851
|
+
return this.#transaction(() => inspectOwner(executionContext(this), kind, runKey(this.sourceId, identity2)));
|
|
1852
|
+
}
|
|
1853
|
+
/** Trusted standalone operator acknowledgement. No PID/age inference and no Host stopped-work proof. */
|
|
1854
|
+
recoverAbandoned(expected3, acknowledgement) {
|
|
1855
|
+
const captured = captureExecutionValue(expected3), ack = captureExecutionValue(acknowledgement);
|
|
1856
|
+
if (!ack || typeof ack !== "object" || Array.isArray(ack) || Object.keys(ack).length !== 1 || ack.ownerStopped !== true) executionFailure("INVALID_STATE");
|
|
1857
|
+
this.#transaction(() => recoverOwner(executionContext(this), captured), true);
|
|
1858
|
+
}
|
|
1859
|
+
close() {
|
|
1860
|
+
if (!this.#closed) {
|
|
1861
|
+
this.#closed = true;
|
|
1862
|
+
this.#codec.close();
|
|
1863
|
+
this.#binding.close();
|
|
1864
|
+
this.#pin.close();
|
|
1865
|
+
this.#db.close();
|
|
1866
|
+
}
|
|
1867
|
+
}
|
|
1868
|
+
};
|
|
1869
|
+
|
|
1870
|
+
// src/orchestration/log/run-history-codec.ts
|
|
1871
|
+
var RUN_HISTORY_SCHEMA = "oar.system.run";
|
|
1872
|
+
function decodeRunMarker(type, input2) {
|
|
1873
|
+
object(input2, ["inputDigest", "outputDigest", "reason"]);
|
|
1874
|
+
hash(input2.inputDigest);
|
|
1875
|
+
if (type === "run.started") {
|
|
1876
|
+
if (Object.keys(input2).length !== 1) throw Error();
|
|
1877
|
+
} else if (type === "run.completed") {
|
|
1878
|
+
if (input2.reason !== void 0 || Object.hasOwn(input2, "reason")) throw Error();
|
|
1879
|
+
if (Object.hasOwn(input2, "outputDigest")) hash(input2.outputDigest);
|
|
1880
|
+
} else if (type === "run.interrupted") {
|
|
1881
|
+
if (Object.keys(input2).length !== 2 || typeof input2.reason !== "string" || !["aborted", "failed", "stopped", "halted"].includes(input2.reason)) throw Error();
|
|
1882
|
+
} else throw Error();
|
|
1883
|
+
return freeze({
|
|
1884
|
+
inputDigest: input2.inputDigest,
|
|
1885
|
+
...input2.outputDigest === void 0 ? {} : { outputDigest: input2.outputDigest },
|
|
1886
|
+
...input2.reason === void 0 ? {} : { reason: input2.reason }
|
|
1887
|
+
});
|
|
1888
|
+
}
|
|
1889
|
+
function capturePublicRunMarker(input2) {
|
|
1890
|
+
object(input2, ["stage", "inputDigest", "outputDigest", "reason"]);
|
|
1891
|
+
if (typeof input2.stage !== "string") throw Error();
|
|
1892
|
+
const { stage, ...body } = input2;
|
|
1893
|
+
return freeze({ stage, ...decodeRunMarker(`run.${stage}`, body) });
|
|
1894
|
+
}
|
|
1895
|
+
|
|
1896
|
+
// src/orchestration/log/run-history-storage.ts
|
|
1897
|
+
function scanRuns(context, maxEntries) {
|
|
1898
|
+
const runs = /* @__PURE__ */ new Map();
|
|
1899
|
+
let cursor, scanned = 0;
|
|
1900
|
+
do {
|
|
1901
|
+
const page = pageRecords(context.db, context.source, context.storageDigest, { limit: Math.min(256, maxEntries - scanned + 1), ...cursor ? { cursor } : {} });
|
|
1902
|
+
scanned += page.scanned;
|
|
1903
|
+
if (scanned > maxEntries) executionFailure("CODEC_LIMIT");
|
|
1904
|
+
cursor = page.nextCursor;
|
|
1905
|
+
for (const entry of page.items) {
|
|
1906
|
+
if (entry.record.schema.id !== RUN_HISTORY_SCHEMA) continue;
|
|
1907
|
+
try {
|
|
1908
|
+
if (entry.record.schema.version !== 1 || !("inline" in entry.record.payload)) executionFailure("INTEGRITY");
|
|
1909
|
+
const metadata = decodeRunMarker(entry.record.type, entry.record.payload.inline), identity2 = entry.record.identity;
|
|
1910
|
+
const position2 = { sourceId: entry.sourceId, sequence: entry.sequence, digest: entry.digest }, prior = runs.get(identity2.runId);
|
|
1911
|
+
if (entry.record.type === "run.started") {
|
|
1912
|
+
if (prior || entry.record.causal.length) executionFailure("INTEGRITY");
|
|
1913
|
+
runs.set(identity2.runId, freeze({ schemaVersion: 1, sourceId: entry.sourceId, identity: identity2, inputDigest: metadata.inputDigest, status: "unknown", started: position2 }));
|
|
1914
|
+
} else {
|
|
1915
|
+
if (!prior || prior.status !== "unknown" || canonical(prior.identity) !== canonical(identity2) || prior.inputDigest !== metadata.inputDigest || canonical(entry.record.causal) !== canonical([prior.started])) executionFailure("INTEGRITY");
|
|
1916
|
+
runs.set(identity2.runId, freeze({
|
|
1917
|
+
...prior,
|
|
1918
|
+
status: entry.record.type === "run.completed" ? "completed" : "interrupted",
|
|
1919
|
+
terminal: position2,
|
|
1920
|
+
...metadata.outputDigest === void 0 ? {} : { outputDigest: metadata.outputDigest },
|
|
1921
|
+
...metadata.reason === void 0 ? {} : { reason: metadata.reason }
|
|
1922
|
+
}));
|
|
1923
|
+
}
|
|
1924
|
+
} catch {
|
|
1925
|
+
executionFailure("INTEGRITY");
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1928
|
+
} while (cursor);
|
|
1929
|
+
return { runs, scanned };
|
|
1930
|
+
}
|
|
1931
|
+
function matchingRun(runs, identity2) {
|
|
1932
|
+
const record = runs.get(identity2.runId);
|
|
1933
|
+
if (record && canonical(record.identity) !== canonical(identity2)) executionFailure("INVALID_STATE");
|
|
1934
|
+
return record;
|
|
1935
|
+
}
|
|
1936
|
+
|
|
1937
|
+
// src/orchestration/log/run-history.ts
|
|
1938
|
+
function input(value, keys) {
|
|
1939
|
+
try {
|
|
1940
|
+
return ownObject(value, keys);
|
|
1941
|
+
} catch {
|
|
1942
|
+
return executionFailure("INVALID_STATE");
|
|
1943
|
+
}
|
|
1944
|
+
}
|
|
1945
|
+
function id(value) {
|
|
1946
|
+
try {
|
|
1947
|
+
identifier(value);
|
|
1948
|
+
} catch {
|
|
1949
|
+
executionFailure("INVALID_STATE");
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1952
|
+
function sha(value) {
|
|
1953
|
+
try {
|
|
1954
|
+
hash(value);
|
|
1955
|
+
} catch {
|
|
1956
|
+
executionFailure("INVALID_STATE");
|
|
1957
|
+
}
|
|
1958
|
+
}
|
|
1959
|
+
function createRunHistory(options) {
|
|
1960
|
+
options = input(options, ["database", "maxEntries"]);
|
|
1961
|
+
const context = executionContext(options.database), maxEntries = options.maxEntries ?? 4096;
|
|
1962
|
+
if (!Number.isSafeInteger(maxEntries) || maxEntries < 1 || maxEntries > 65536) executionFailure("INVALID_STATE");
|
|
1963
|
+
const handles = /* @__PURE__ */ new WeakMap();
|
|
1964
|
+
const identity2 = (value) => {
|
|
1965
|
+
let captured;
|
|
1966
|
+
try {
|
|
1967
|
+
captured = captureIdentity2(value);
|
|
1968
|
+
} catch {
|
|
1969
|
+
return executionFailure("INVALID_STATE");
|
|
1970
|
+
}
|
|
1971
|
+
if (captured.systemId !== context.source.systemId) executionFailure("INVALID_STATE");
|
|
1972
|
+
return captured;
|
|
1973
|
+
};
|
|
1974
|
+
const finish = async (handle, raw, status) => {
|
|
1975
|
+
const saved = handle && typeof handle === "object" ? handles.get(handle) : void 0;
|
|
1976
|
+
if (!saved) executionFailure("INVALID_STATE");
|
|
1977
|
+
const command = input(raw, status === "completed" ? ["requestId", "outputDigest"] : ["requestId", "reason"]);
|
|
1978
|
+
id(command.requestId);
|
|
1979
|
+
const outputDigest = "outputDigest" in command ? command.outputDigest : void 0, reason = "reason" in command ? command.reason : void 0;
|
|
1980
|
+
if (outputDigest !== void 0) sha(outputDigest);
|
|
1981
|
+
if (status === "interrupted" && (typeof reason !== "string" || !["aborted", "failed", "stopped", "halted"].includes(reason))) executionFailure("INVALID_STATE");
|
|
1982
|
+
return context.transaction(() => {
|
|
1983
|
+
const { runs, scanned } = scanRuns(context, maxEntries);
|
|
1984
|
+
const prior = matchingRun(runs, saved.identity);
|
|
1985
|
+
if (!prior || canonical(prior.started) !== canonical(saved.started) || prior.inputDigest !== saved.inputDigest) executionFailure("INTEGRITY");
|
|
1986
|
+
if (prior.status !== "unknown") {
|
|
1987
|
+
if (prior.status !== status || prior.outputDigest !== outputDigest || prior.reason !== reason) executionFailure("INVALID_STATE");
|
|
1988
|
+
return prior;
|
|
1989
|
+
}
|
|
1990
|
+
if (scanned >= maxEntries) executionFailure("CODEC_LIMIT");
|
|
1991
|
+
const receipt = context.binding.appendInTransaction({ requestId: command.requestId, records: [{
|
|
1992
|
+
identity: saved.identity,
|
|
1993
|
+
schema: { id: RUN_HISTORY_SCHEMA, version: 1 },
|
|
1994
|
+
type: `run.${status}`,
|
|
1995
|
+
causal: [prior.started],
|
|
1996
|
+
payload: { inline: { inputDigest: prior.inputDigest, ...outputDigest === void 0 ? {} : { outputDigest }, ...reason === void 0 ? {} : { reason } } }
|
|
1997
|
+
}] });
|
|
1998
|
+
return freeze({ ...prior, status, terminal: receipt.first, ...outputDigest === void 0 ? {} : { outputDigest }, ...reason === void 0 ? {} : { reason } });
|
|
1999
|
+
}, true);
|
|
2000
|
+
};
|
|
2001
|
+
return Object.freeze({
|
|
2002
|
+
async begin(raw) {
|
|
2003
|
+
const command = input(raw, ["identity", "requestId", "inputDigest"]), captured = identity2(command.identity);
|
|
2004
|
+
id(command.requestId);
|
|
2005
|
+
sha(command.inputDigest);
|
|
2006
|
+
const result = context.transaction(() => {
|
|
2007
|
+
const { runs, scanned } = scanRuns(context, maxEntries);
|
|
2008
|
+
const prior = matchingRun(runs, captured);
|
|
2009
|
+
if (prior) {
|
|
2010
|
+
if (prior.inputDigest !== command.inputDigest) executionFailure("INVALID_STATE");
|
|
2011
|
+
return { kind: "existing", record: prior };
|
|
2012
|
+
}
|
|
2013
|
+
let reserved = 2;
|
|
2014
|
+
for (const run2 of runs.values()) if (run2.status === "unknown") reserved++;
|
|
2015
|
+
if (scanned + reserved > maxEntries) executionFailure("CODEC_LIMIT");
|
|
2016
|
+
const receipt = context.binding.appendInTransaction({ requestId: command.requestId, records: [{ identity: captured, schema: { id: RUN_HISTORY_SCHEMA, version: 1 }, type: "run.started", causal: [], payload: { inline: { inputDigest: command.inputDigest } } }] });
|
|
2017
|
+
return { kind: "started", record: freeze({ schemaVersion: 1, sourceId: context.source.sourceId, identity: captured, inputDigest: command.inputDigest, status: "unknown", started: receipt.first }) };
|
|
2018
|
+
}, true);
|
|
2019
|
+
if (result.kind === "existing") return Object.freeze(result);
|
|
2020
|
+
const run = Object.freeze({});
|
|
2021
|
+
handles.set(run, result.record);
|
|
2022
|
+
return Object.freeze({ ...result, run });
|
|
2023
|
+
},
|
|
2024
|
+
complete: (handle, command) => finish(handle, command, "completed"),
|
|
2025
|
+
interrupt: (handle, command) => finish(handle, command, "interrupted"),
|
|
2026
|
+
async recover(raw) {
|
|
2027
|
+
const captured = identity2(raw);
|
|
2028
|
+
return context.transaction(() => matchingRun(scanRuns(context, maxEntries).runs, captured));
|
|
2029
|
+
},
|
|
2030
|
+
async list(raw = {}) {
|
|
2031
|
+
const command = input(raw, ["generation", "limit"]), limit = command.limit ?? 64;
|
|
2032
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 256 || command.generation !== void 0 && (!Number.isSafeInteger(command.generation) || command.generation < 1)) executionFailure("INVALID_STATE");
|
|
2033
|
+
return context.transaction(() => freeze([...scanRuns(context, maxEntries).runs.values()].filter((record) => command.generation === void 0 || record.identity.generation === command.generation).sort((a, b) => b.started.sequence - a.started.sequence).slice(0, limit)));
|
|
2034
|
+
}
|
|
2035
|
+
});
|
|
2036
|
+
}
|
|
2037
|
+
|
|
2038
|
+
// src/orchestration/log/materialized.ts
|
|
2039
|
+
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
2040
|
+
|
|
2041
|
+
// src/orchestration/log/state-history.ts
|
|
2042
|
+
function latestStatePosition(context, kind, key) {
|
|
2043
|
+
let cursor, latest;
|
|
2044
|
+
do {
|
|
2045
|
+
const page = pageRecords(context.db, context.source, context.storageDigest, cursor ? { cursor, limit: 64 } : { limit: 64 });
|
|
2046
|
+
cursor = page.nextCursor;
|
|
2047
|
+
for (const entry of page.items) {
|
|
2048
|
+
if (entry.record.schema.id !== `oar.execution.${kind}`) continue;
|
|
2049
|
+
if (entry.record.schema.version !== 1 && entry.record.schema.version !== 2) executionFailure("INTEGRITY");
|
|
2050
|
+
const payload = "inline" in entry.record.payload ? entry.record.payload.inline : void 0;
|
|
2051
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) executionFailure("INTEGRITY");
|
|
2052
|
+
if (payload.kind === kind && payload.key === key) latest = { sourceId: entry.sourceId, sequence: entry.sequence, digest: entry.digest };
|
|
2053
|
+
}
|
|
2054
|
+
} while (cursor);
|
|
2055
|
+
return latest;
|
|
2056
|
+
}
|
|
2057
|
+
|
|
2058
|
+
// src/orchestration/log/execution-metadata.ts
|
|
2059
|
+
function captureExecutionMetadata(kind, input2) {
|
|
2060
|
+
try {
|
|
2061
|
+
const next = captureExecutionValue(input2);
|
|
2062
|
+
if (kind === "decision") {
|
|
2063
|
+
object(next, ["kind", "decisionIdDigest", "status", "attempts", "intentIdDigest", "inputHash", "authorityHash", "inputVersionDigest", "authorityVersionDigest", "resultHash"]);
|
|
2064
|
+
if (next.kind !== kind || !["waiting", "denied", "intent", "dispatched", "verified", "needs-owner"].includes(next.status) || !Number.isSafeInteger(next.attempts) || Number(next.attempts) < 0) executionFailure("INTEGRITY");
|
|
2065
|
+
for (const key of ["decisionIdDigest", "inputHash", "authorityHash", "inputVersionDigest", "authorityVersionDigest"]) hash(next[key]);
|
|
2066
|
+
for (const key of ["intentIdDigest", "resultHash"]) if (next[key] !== void 0) hash(next[key]);
|
|
2067
|
+
if (["intent", "dispatched", "verified"].includes(next.status) && (!next.intentIdDigest || Number(next.attempts) < 1) || next.status === "verified" && !next.resultHash) executionFailure("INTEGRITY");
|
|
2068
|
+
} else {
|
|
2069
|
+
object(next, ["kind", "workflowIdDigest", "workflowVersionDigest", "fingerprint", "status", "steps"]);
|
|
2070
|
+
if (next.kind !== kind || Object.keys(next).length !== 6 || !["running", "completed", "failed", "cancelled", "halted"].includes(next.status) || !Array.isArray(next.steps) || next.steps.length > 1024) executionFailure("INTEGRITY");
|
|
2071
|
+
for (const key of ["workflowIdDigest", "workflowVersionDigest", "fingerprint"]) hash(next[key]);
|
|
2072
|
+
const ids = /* @__PURE__ */ new Set();
|
|
2073
|
+
for (const step of next.steps) {
|
|
2074
|
+
object(step, ["stepIdDigest", "status", "attempts"]);
|
|
2075
|
+
hash(step.stepIdDigest);
|
|
2076
|
+
if (Object.keys(step).length !== 3 || ids.has(step.stepIdDigest) || !["pending", "running", "completed", "failed", "interrupted", "blocked"].includes(step.status) || !Number.isSafeInteger(step.attempts) || Number(step.attempts) < 0) executionFailure("INTEGRITY");
|
|
2077
|
+
ids.add(step.stepIdDigest);
|
|
2078
|
+
}
|
|
2079
|
+
}
|
|
2080
|
+
return next;
|
|
2081
|
+
} catch {
|
|
2082
|
+
return executionFailure("INTEGRITY");
|
|
2083
|
+
}
|
|
2084
|
+
}
|
|
2085
|
+
function executionMetadata(kind, input2) {
|
|
2086
|
+
if (kind === "decision") {
|
|
2087
|
+
const raw = input2, record2 = validateDecisionRecord(input2, raw.id);
|
|
2088
|
+
return freeze({
|
|
2089
|
+
kind,
|
|
2090
|
+
decisionIdDigest: digest(record2.id),
|
|
2091
|
+
status: record2.status,
|
|
2092
|
+
attempts: record2.attempts,
|
|
2093
|
+
...record2.intentId ? { intentIdDigest: digest(record2.intentId) } : {},
|
|
2094
|
+
inputHash: record2.binding.inputHash,
|
|
2095
|
+
authorityHash: record2.binding.authorityHash,
|
|
2096
|
+
inputVersionDigest: digest(record2.binding.inputVersion),
|
|
2097
|
+
authorityVersionDigest: digest(record2.binding.authorityVersion),
|
|
2098
|
+
...record2.receipt ? { resultHash: record2.receipt.resultHash } : {}
|
|
2099
|
+
});
|
|
2100
|
+
}
|
|
2101
|
+
const record = input2;
|
|
2102
|
+
if (!record || !record.workflow || !record.steps) executionFailure("INTEGRITY");
|
|
2103
|
+
return freeze({
|
|
2104
|
+
kind,
|
|
2105
|
+
workflowIdDigest: digest(record.workflow.id),
|
|
2106
|
+
workflowVersionDigest: digest(record.workflow.version),
|
|
2107
|
+
fingerprint: record.workflow.fingerprint,
|
|
2108
|
+
status: record.status,
|
|
2109
|
+
steps: Object.entries(record.steps).map(([stepId, step]) => ({ stepIdDigest: digest(stepId), status: step.status, attempts: step.attempts }))
|
|
2110
|
+
});
|
|
2111
|
+
}
|
|
2112
|
+
|
|
2113
|
+
// src/orchestration/log/materialized.ts
|
|
2114
|
+
function readState(context, kind, key, identity2) {
|
|
2115
|
+
const latest = latestStatePosition(context, kind, key);
|
|
2116
|
+
const row = context.db.prepare(`SELECT identity_json,identity_digest,revision,record_digest,sequence,event_digest,request_id,
|
|
2117
|
+
CASE WHEN length(CAST(record_json AS BLOB))<=60000 THEN record_json END AS record_json FROM main.oar_execution_states WHERE kind=? AND state_key=?`).get(kind, key);
|
|
2118
|
+
if (!row) {
|
|
2119
|
+
if (latest) executionFailure("INTEGRITY");
|
|
2120
|
+
return void 0;
|
|
2121
|
+
}
|
|
2122
|
+
if (!latest || latest.sequence !== row.sequence || latest.digest !== row.event_digest || row.identity_json !== canonical(identity2) || row.identity_digest !== digest(canonical(identity2)) || !Number.isSafeInteger(row.revision) || Number(row.revision) < 1) executionFailure("INTEGRITY");
|
|
2123
|
+
const event = readEntry(context.db, Number(row.sequence), context.source);
|
|
2124
|
+
if (event.digest !== row.event_digest || event.requestId !== row.request_id || canonical(event.record.identity) !== canonical(identity2) || event.record.schema.id !== `oar.execution.${kind}`) executionFailure("INTEGRITY");
|
|
2125
|
+
let record, body, metadata, expected3;
|
|
2126
|
+
if (event.record.schema.version === 1) {
|
|
2127
|
+
record = decodeExecutionValue(row.record_json, row.record_digest);
|
|
2128
|
+
metadata = executionMetadata(kind, record);
|
|
2129
|
+
expected3 = { kind, key, revision: row.revision, recordJson: row.record_json, recordDigest: row.record_digest, metadata };
|
|
2130
|
+
} else if (event.record.schema.version === 2) {
|
|
2131
|
+
if (typeof row.record_json !== "string") executionFailure("INTEGRITY");
|
|
2132
|
+
let raw;
|
|
2133
|
+
try {
|
|
2134
|
+
raw = JSON.parse(row.record_json);
|
|
2135
|
+
} catch {
|
|
2136
|
+
return executionFailure("INTEGRITY");
|
|
2137
|
+
}
|
|
2138
|
+
body = captureRecordBody(raw, context.source.sourceId, identity2, context.codec.maxBytes);
|
|
2139
|
+
if (canonical(body) !== row.record_json || body.reference.digest !== row.record_digest || !("inline" in event.record.payload)) executionFailure("INTEGRITY");
|
|
2140
|
+
metadata = captureExecutionMetadata(kind, event.record.payload.inline.metadata);
|
|
2141
|
+
expected3 = { kind, key, revision: row.revision, recordDigest: row.record_digest, body, metadata };
|
|
2142
|
+
const original = readEntry(context.db, event.sequence - 1, context.source);
|
|
2143
|
+
const range = context.db.prepare("SELECT count,first_sequence,last_sequence FROM main.oar_log_requests WHERE request_id=?").get(event.requestId);
|
|
2144
|
+
if (event.ordinal !== 2 || original.ordinal !== 1 || original.requestId !== event.requestId || original.record.schema.id !== "oar.execution.body" || original.record.schema.version !== 1 || original.record.type !== `${kind}.body` || canonical(original.record.identity) !== canonical(identity2) || canonical(original.record.payload) !== canonical({ artifact: body.reference }) || range?.count !== 2 || range.first_sequence !== original.sequence || range.last_sequence !== event.sequence) executionFailure("INTEGRITY");
|
|
2145
|
+
} else return executionFailure("PAYLOAD_UNAVAILABLE");
|
|
2146
|
+
if (event.record.type !== `${kind}.${metadata.status}` || canonical(event.record.payload) !== canonical({ inline: expected3 })) executionFailure("INTEGRITY");
|
|
2147
|
+
return freeze({
|
|
2148
|
+
revision: Number(row.revision),
|
|
2149
|
+
...record !== void 0 ? { record } : {},
|
|
2150
|
+
recordJson: row.record_json,
|
|
2151
|
+
recordDigest: row.record_digest,
|
|
2152
|
+
metadata,
|
|
2153
|
+
...body ? { body } : {}
|
|
2154
|
+
});
|
|
2155
|
+
}
|
|
2156
|
+
async function hydrateState(context, kind, state, check) {
|
|
2157
|
+
if (!state.body) {
|
|
2158
|
+
if (state.record === void 0) executionFailure("INTEGRITY");
|
|
2159
|
+
return state.record;
|
|
2160
|
+
}
|
|
2161
|
+
const record = await context.codec.hydrate(state.body, state.recordDigest, check);
|
|
2162
|
+
check();
|
|
2163
|
+
if (canonical(executionMetadata(kind, record)) !== canonical(state.metadata)) executionFailure("INTEGRITY");
|
|
2164
|
+
return record;
|
|
2165
|
+
}
|
|
2166
|
+
async function prepareState(context, kind, key, identity2, record, expectedRevision, type, check) {
|
|
2167
|
+
const revision = expectedRevision + 1;
|
|
2168
|
+
if (!Number.isSafeInteger(revision)) executionFailure("INTEGRITY");
|
|
2169
|
+
const metadata = executionMetadata(kind, record), requestId = `state:${randomUUID5()}`;
|
|
2170
|
+
return (async () => {
|
|
2171
|
+
const encoded = await context.codec.encode(record, check);
|
|
2172
|
+
check();
|
|
2173
|
+
try {
|
|
2174
|
+
const recordDigest = encoded.digest;
|
|
2175
|
+
if (encoded.bytes.length <= 6e4) {
|
|
2176
|
+
const recordJson = encoded.bytes.toString("utf8");
|
|
2177
|
+
try {
|
|
2178
|
+
const commit2 = captureLogCommit({ requestId, records: [{
|
|
2179
|
+
identity: identity2,
|
|
2180
|
+
schema: { id: `oar.execution.${kind}`, version: 1 },
|
|
2181
|
+
type,
|
|
2182
|
+
causal: [],
|
|
2183
|
+
payload: { inline: { kind, key, revision, recordJson, recordDigest, metadata } }
|
|
2184
|
+
}] });
|
|
2185
|
+
return { revision, record, recordJson, recordDigest, metadata, commit: commit2 };
|
|
2186
|
+
} catch {
|
|
2187
|
+
}
|
|
2188
|
+
}
|
|
2189
|
+
const body = await context.codec.stage(encoded.bytes, recordDigest, context.source.sourceId, identity2, check);
|
|
2190
|
+
check();
|
|
2191
|
+
const commit = await context.binding.prepare({ requestId, records: [
|
|
2192
|
+
{ identity: identity2, schema: { id: "oar.execution.body", version: 1 }, type: `${kind}.body`, causal: [], payload: { artifact: body.reference } },
|
|
2193
|
+
{ identity: identity2, schema: { id: `oar.execution.${kind}`, version: 2 }, type, causal: [], payload: { inline: { kind, key, revision, recordDigest, body, metadata } } }
|
|
2194
|
+
] });
|
|
2195
|
+
check();
|
|
2196
|
+
return { revision, record, recordJson: canonical(body), recordDigest, metadata, commit };
|
|
2197
|
+
} finally {
|
|
2198
|
+
encoded.bytes.fill(0);
|
|
2199
|
+
}
|
|
2200
|
+
})();
|
|
2201
|
+
}
|
|
2202
|
+
function commitState(context, kind, key, identity2, prepared2) {
|
|
2203
|
+
const current = readState(context, kind, key, identity2), { revision, recordJson, recordDigest, metadata } = prepared2;
|
|
2204
|
+
if ((current?.revision ?? 0) !== revision - 1) executionFailure("OUTCOME_UNKNOWN");
|
|
2205
|
+
if (current?.recordDigest === recordDigest && current.recordJson === recordJson) return current;
|
|
2206
|
+
const receipt = context.binding.appendInTransaction(prepared2.commit);
|
|
2207
|
+
context.db.prepare(`INSERT INTO main.oar_execution_states VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT(kind,state_key)
|
|
2208
|
+
DO UPDATE SET revision=excluded.revision,record_json=excluded.record_json,record_digest=excluded.record_digest,sequence=excluded.sequence,event_digest=excluded.event_digest,request_id=excluded.request_id`).run(
|
|
2209
|
+
kind,
|
|
2210
|
+
key,
|
|
2211
|
+
canonical(identity2),
|
|
2212
|
+
digest(canonical(identity2)),
|
|
2213
|
+
revision,
|
|
2214
|
+
recordJson,
|
|
2215
|
+
recordDigest,
|
|
2216
|
+
receipt.head.sequence,
|
|
2217
|
+
receipt.head.digest,
|
|
2218
|
+
readEntry(context.db, receipt.head.sequence, context.source).requestId
|
|
2219
|
+
);
|
|
2220
|
+
return freeze({ revision, record: prepared2.record, recordJson, recordDigest, metadata });
|
|
2221
|
+
}
|
|
2222
|
+
|
|
2223
|
+
// src/orchestration/log/effects.ts
|
|
2224
|
+
function readEffect(context, id2) {
|
|
2225
|
+
const row = context.db.prepare(`SELECT run_key,step_id,generation,decision_id,association_digest,
|
|
2226
|
+
CASE WHEN length(CAST(association_json AS BLOB))<8192 THEN association_json END AS association_json FROM main.oar_execution_effects WHERE effect_id=?`).get(id2);
|
|
2227
|
+
if (!row) {
|
|
2228
|
+
if (lookupReceipt(context.db, `effect:${id2}`, context.source)) executionFailure("INTEGRITY");
|
|
2229
|
+
return void 0;
|
|
2230
|
+
}
|
|
2231
|
+
try {
|
|
2232
|
+
if (typeof row.association_json !== "string" || digest(row.association_json) !== row.association_digest) executionFailure("INTEGRITY");
|
|
2233
|
+
const raw = JSON.parse(row.association_json), { sourceId, ...input2 } = raw;
|
|
2234
|
+
const association = captureAssociation(input2, context.source.sourceId, context.source.systemId);
|
|
2235
|
+
if (sourceId !== context.source.sourceId || canonical(association) !== row.association_json || effectId(association) !== id2 || runKey(context.source.sourceId, association.identity) !== row.run_key || row.step_id !== association.stepId || row.generation !== association.identity.generation) executionFailure("INTEGRITY");
|
|
2236
|
+
const origin = lookupReceipt(context.db, `effect:${id2}`, context.source);
|
|
2237
|
+
if (!origin || origin.receipt.count !== 1) executionFailure("INTEGRITY");
|
|
2238
|
+
const event = readEntry(context.db, origin.receipt.first.sequence, context.source);
|
|
2239
|
+
if (event.record.schema.id !== "oar.execution.association" || event.record.schema.version !== 1 || event.record.type !== "effect.associated" || canonical(event.record.identity) !== canonical(association.identity) || canonical(event.record.payload) !== canonical({ inline: { effectId: id2, decisionId: row.decision_id, association } })) executionFailure("INTEGRITY");
|
|
2240
|
+
identifier(row.decision_id);
|
|
2241
|
+
const state = readState(context, "decision", id2, association.identity);
|
|
2242
|
+
const record = state && !state.body ? validateDecisionRecord(state.record, row.decision_id) : void 0;
|
|
2243
|
+
if (state && (state.metadata.kind !== "decision" || state.metadata.decisionIdDigest !== digest(row.decision_id))) executionFailure("INTEGRITY");
|
|
2244
|
+
return freeze({
|
|
2245
|
+
association,
|
|
2246
|
+
decisionId: row.decision_id,
|
|
2247
|
+
...record ? { record } : {},
|
|
2248
|
+
...state ? { metadata: state.metadata, bodyState: state.body ? "requires-body" : "inline" } : {}
|
|
2249
|
+
});
|
|
2250
|
+
} catch {
|
|
2251
|
+
return executionFailure("INTEGRITY");
|
|
2252
|
+
}
|
|
2253
|
+
}
|
|
2254
|
+
function associateEffect(context, association, decisionId) {
|
|
2255
|
+
identifier(decisionId);
|
|
2256
|
+
const id2 = effectId(association), existing = readEffect(context, id2);
|
|
2257
|
+
if (existing) {
|
|
2258
|
+
if (existing.decisionId !== decisionId || canonical(existing.association) !== canonical(association)) executionFailure("EFFECT_BINDING_CONFLICT");
|
|
2259
|
+
return;
|
|
2260
|
+
}
|
|
2261
|
+
if (readState(context, "decision", id2, association.identity)) executionFailure("INTEGRITY");
|
|
2262
|
+
const encoded = canonical(association);
|
|
2263
|
+
context.db.prepare("INSERT INTO main.oar_execution_effects VALUES(?,?,?,?,?,?,?)").run(
|
|
2264
|
+
id2,
|
|
2265
|
+
runKey(context.source.sourceId, association.identity),
|
|
2266
|
+
association.stepId,
|
|
2267
|
+
association.identity.generation,
|
|
2268
|
+
decisionId,
|
|
2269
|
+
encoded,
|
|
2270
|
+
digest(encoded)
|
|
2271
|
+
);
|
|
2272
|
+
context.binding.appendInTransaction({ requestId: `effect:${id2}`, records: [{
|
|
2273
|
+
identity: association.identity,
|
|
2274
|
+
schema: { id: "oar.execution.association", version: 1 },
|
|
2275
|
+
type: "effect.associated",
|
|
2276
|
+
causal: [],
|
|
2277
|
+
payload: { inline: { effectId: id2, decisionId, association } }
|
|
2278
|
+
}] });
|
|
2279
|
+
}
|
|
2280
|
+
function visitEffects(context, visit) {
|
|
2281
|
+
let after = null;
|
|
2282
|
+
for (; ; ) {
|
|
2283
|
+
const ids = context.db.prepare("SELECT effect_id FROM main.oar_execution_effects WHERE (? IS NULL OR effect_id>?) ORDER BY effect_id LIMIT 256").all(after, after);
|
|
2284
|
+
for (const row of ids) {
|
|
2285
|
+
if (typeof row.effect_id !== "string") executionFailure("INTEGRITY");
|
|
2286
|
+
const effect = readEffect(context, row.effect_id);
|
|
2287
|
+
if (!effect) executionFailure("INTEGRITY");
|
|
2288
|
+
visit(row.effect_id, effect);
|
|
2289
|
+
}
|
|
2290
|
+
if (ids.length < 256) return;
|
|
2291
|
+
after = String(ids.at(-1).effect_id);
|
|
2292
|
+
}
|
|
2293
|
+
}
|
|
2294
|
+
function unresolved(record) {
|
|
2295
|
+
return !!record && ["intent", "dispatched", "needs-owner"].includes(record.status);
|
|
2296
|
+
}
|
|
2297
|
+
function assertResolvedRun(context, identity2, except) {
|
|
2298
|
+
const key = runKey(context.source.sourceId, identity2);
|
|
2299
|
+
visitEffects(context, (id2, effect) => {
|
|
2300
|
+
if (id2 !== except && runKey(context.source.sourceId, effect.association.identity) === key && unresolved(effect.metadata)) executionFailure("OUTCOME_UNKNOWN");
|
|
2301
|
+
});
|
|
2302
|
+
}
|
|
2303
|
+
function inspectManagedEffect(database, input2) {
|
|
2304
|
+
const context = executionContext(database), association = captureAssociation(input2, context.source.sourceId, context.source.systemId);
|
|
2305
|
+
return context.transaction(() => {
|
|
2306
|
+
const effect = readEffect(context, effectId(association));
|
|
2307
|
+
if (effect && canonical(effect.association) !== canonical(association)) executionFailure("EFFECT_BINDING_CONFLICT");
|
|
2308
|
+
return effect;
|
|
2309
|
+
});
|
|
2310
|
+
}
|
|
2311
|
+
|
|
2312
|
+
// src/orchestration/log/decision-reconciliation.ts
|
|
2313
|
+
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
2314
|
+
function halted(error) {
|
|
2315
|
+
return isExecutionHalted(error) ? error : new ExecutionHaltedError({ sanitizedDiagnostics: { reason: "ORIGINAL_EFFECT_UNVERIFIED" } }, { cause: error });
|
|
2316
|
+
}
|
|
2317
|
+
async function reconcileOriginalDecision(database, association, input2) {
|
|
2318
|
+
const options = ownObject(input2, ["id", "intentId", "binding", "verifyApplied"]);
|
|
2319
|
+
identifier(options.id);
|
|
2320
|
+
identifier(options.intentId);
|
|
2321
|
+
const verifyApplied = method(options, "verifyApplied");
|
|
2322
|
+
const context = executionContext(database), key = effectId(association);
|
|
2323
|
+
const initial = context.transaction(() => {
|
|
2324
|
+
const effect = readEffect(context, key), state = readState(context, "decision", key, association.identity);
|
|
2325
|
+
if (!effect || effect.decisionId !== options.id || canonical(effect.association) !== canonical(association) || !state || state.metadata.kind !== "decision" || !["intent", "dispatched", "needs-owner", "verified"].includes(state.metadata.status)) executionFailure("OUTCOME_UNKNOWN");
|
|
2326
|
+
return { state, owner: acquireOwner(context, "decision", association.identity) };
|
|
2327
|
+
}, true);
|
|
2328
|
+
markOwnerActive(context, initial.owner);
|
|
2329
|
+
let failed = false, failure, uncertainCommit = false;
|
|
2330
|
+
const checkBody = () => {
|
|
2331
|
+
assertOwner(context, initial.owner);
|
|
2332
|
+
const effect = readEffect(context, key), state = readState(context, "decision", key, association.identity);
|
|
2333
|
+
if (!effect || effect.decisionId !== options.id || canonical(effect.association) !== canonical(association) || !state || state.revision !== initial.state.revision || state.recordDigest !== initial.state.recordDigest || state.recordJson !== initial.state.recordJson) executionFailure("OUTCOME_UNKNOWN");
|
|
2334
|
+
};
|
|
2335
|
+
const check = () => context.transaction(checkBody);
|
|
2336
|
+
const position2 = () => {
|
|
2337
|
+
const row = context.db.prepare("SELECT sequence,event_digest FROM main.oar_execution_states WHERE kind='decision' AND state_key=?").get(key);
|
|
2338
|
+
if (!row || !Number.isSafeInteger(row.sequence) || typeof row.event_digest !== "string") executionFailure("INTEGRITY");
|
|
2339
|
+
return Object.freeze({ sourceId: context.source.sourceId, sequence: Number(row.sequence), digest: row.event_digest });
|
|
2340
|
+
};
|
|
2341
|
+
try {
|
|
2342
|
+
return await context.codec.operation(async () => {
|
|
2343
|
+
const capturedBinding = await context.codec.capture(options.binding, check);
|
|
2344
|
+
check();
|
|
2345
|
+
const binding = snapshotBinding(capturedBinding);
|
|
2346
|
+
const original = validateDecisionRecord(await hydrateState(context, "decision", initial.state, check), options.id);
|
|
2347
|
+
check();
|
|
2348
|
+
if (original.intentId !== options.intentId || !sameDecisionBinding(original.binding, binding)) executionFailure("EFFECT_BINDING_CONFLICT");
|
|
2349
|
+
if (original.status === "verified") return original;
|
|
2350
|
+
if (!original.authorization || original.authorization.decision !== "allow" || original.attempts < 1) executionFailure("OUTCOME_UNKNOWN");
|
|
2351
|
+
const originalPosition = context.transaction(() => {
|
|
2352
|
+
checkBody();
|
|
2353
|
+
return position2();
|
|
2354
|
+
});
|
|
2355
|
+
const verdict = await verifyApplied(freeze({ association, record: freeze(original) }));
|
|
2356
|
+
check();
|
|
2357
|
+
object(verdict, ["verified", "result", "evidence"]);
|
|
2358
|
+
if (typeof verdict.verified !== "boolean") executionFailure("OUTCOME_UNKNOWN");
|
|
2359
|
+
if (!verdict.verified) return original;
|
|
2360
|
+
if (!Object.hasOwn(verdict, "result") || !Array.isArray(verdict.evidence) || verdict.evidence.length < 1 || verdict.evidence.length > 64) executionFailure("OUTCOME_UNKNOWN");
|
|
2361
|
+
const captured = await context.codec.capture({ result: verdict.result, evidence: verdict.evidence }, check);
|
|
2362
|
+
check();
|
|
2363
|
+
object(captured, ["result", "evidence"]);
|
|
2364
|
+
const evidence = captured.evidence;
|
|
2365
|
+
if (evidence.some((value) => typeof value !== "string" || !value.trim() || value.length > 1024)) executionFailure("OUTCOME_UNKNOWN");
|
|
2366
|
+
const result = captured.result, resultHash = decisionHash(result), now = Date.now();
|
|
2367
|
+
if (!Number.isSafeInteger(now) || now < 0) executionFailure("OUTCOME_UNKNOWN");
|
|
2368
|
+
const next = { ...original, status: "verified", result, reason: "Original-target postcondition reconciled by owner", receipt: {
|
|
2369
|
+
intentId: original.intentId,
|
|
2370
|
+
inputHash: original.binding.inputHash,
|
|
2371
|
+
authorityHash: original.binding.authorityHash,
|
|
2372
|
+
inputVersion: original.binding.inputVersion,
|
|
2373
|
+
authorityVersion: original.binding.authorityVersion,
|
|
2374
|
+
approval: original.authorization,
|
|
2375
|
+
resultHash,
|
|
2376
|
+
evidence,
|
|
2377
|
+
verifiedAt: now
|
|
2378
|
+
} };
|
|
2379
|
+
validateDecisionRecord(next, options.id);
|
|
2380
|
+
const prepared2 = await prepareState(context, "decision", key, association.identity, next, initial.state.revision, "decision.verified", check);
|
|
2381
|
+
check();
|
|
2382
|
+
uncertainCommit = true;
|
|
2383
|
+
context.transaction(() => {
|
|
2384
|
+
checkBody();
|
|
2385
|
+
commitState(context, "decision", key, association.identity, prepared2);
|
|
2386
|
+
const verifiedPosition = position2();
|
|
2387
|
+
const metadata = {
|
|
2388
|
+
kind: "decision-reconciliation",
|
|
2389
|
+
status: "verified",
|
|
2390
|
+
decisionIdDigest: digest(options.id),
|
|
2391
|
+
intentIdDigest: digest(options.intentId),
|
|
2392
|
+
associationDigest: digest(canonical(association)),
|
|
2393
|
+
inputHash: original.binding.inputHash,
|
|
2394
|
+
authorityHash: original.binding.authorityHash,
|
|
2395
|
+
inputVersionDigest: digest(original.binding.inputVersion),
|
|
2396
|
+
authorityVersionDigest: digest(original.binding.authorityVersion),
|
|
2397
|
+
resultHash,
|
|
2398
|
+
evidenceDigests: evidence.map(digest),
|
|
2399
|
+
original: { ...originalPosition },
|
|
2400
|
+
verified: { ...verifiedPosition }
|
|
2401
|
+
};
|
|
2402
|
+
context.binding.appendInTransaction({ requestId: `reconciliation:${randomUUID6()}`, records: [{
|
|
2403
|
+
identity: association.identity,
|
|
2404
|
+
schema: { id: "oar.execution.reconciliation", version: 1 },
|
|
2405
|
+
type: "decision.reconciled",
|
|
2406
|
+
causal: [originalPosition, verifiedPosition],
|
|
2407
|
+
payload: { inline: metadata }
|
|
2408
|
+
}] });
|
|
2409
|
+
}, true);
|
|
2410
|
+
uncertainCommit = false;
|
|
2411
|
+
return next;
|
|
2412
|
+
});
|
|
2413
|
+
} catch (error) {
|
|
2414
|
+
failed = true;
|
|
2415
|
+
failure = halted(error);
|
|
2416
|
+
throw failure;
|
|
2417
|
+
} finally {
|
|
2418
|
+
try {
|
|
2419
|
+
if (uncertainCommit) executionFailure("OUTCOME_UNKNOWN");
|
|
2420
|
+
context.transaction(() => releaseOwner(context, initial.owner), true);
|
|
2421
|
+
} catch (secondary) {
|
|
2422
|
+
throw failed ? new AggregateError([failure, secondary], "Original effect reconciliation is uncertain", { cause: failure }) : halted(secondary);
|
|
2423
|
+
} finally {
|
|
2424
|
+
markOwnerDrained(context, initial.owner);
|
|
2425
|
+
}
|
|
2426
|
+
}
|
|
2427
|
+
}
|
|
2428
|
+
|
|
2429
|
+
// src/orchestration/log/decision-store.ts
|
|
2430
|
+
function validateTransition(previous, next) {
|
|
2431
|
+
if (!previous) {
|
|
2432
|
+
if (!["waiting", "denied", "intent"].includes(next.status) || next.attempts !== (next.status === "intent" ? 1 : 0)) executionFailure("INVALID_STATE");
|
|
2433
|
+
return;
|
|
2434
|
+
}
|
|
2435
|
+
if (!sameDecisionBinding(previous.binding, next.binding)) executionFailure("EFFECT_BINDING_CONFLICT");
|
|
2436
|
+
if (canonical(previous) === canonical(next)) return;
|
|
2437
|
+
const allowed = { waiting: ["waiting", "denied", "intent", "needs-owner"], denied: [], intent: ["dispatched", "needs-owner"], dispatched: ["dispatched", "verified", "needs-owner"], verified: [], "needs-owner": [] };
|
|
2438
|
+
if (!allowed[previous.status].includes(next.status) || next.attempts !== previous.attempts + (next.status === "intent" ? 1 : 0) || previous.intentId && next.intentId !== previous.intentId) executionFailure("INVALID_STATE");
|
|
2439
|
+
}
|
|
2440
|
+
var LogDecisionStore = class {
|
|
2441
|
+
#database;
|
|
2442
|
+
#association;
|
|
2443
|
+
constructor(options) {
|
|
2444
|
+
try {
|
|
2445
|
+
object(options, ["database", "association", "requireResolvedRun"]);
|
|
2446
|
+
if (options.requireResolvedRun !== void 0 && options.requireResolvedRun !== true) executionFailure("INVALID_STATE");
|
|
2447
|
+
const context = executionContext(options.database);
|
|
2448
|
+
this.#database = options.database;
|
|
2449
|
+
this.#association = captureAssociation(options.association, context.source.sourceId, context.source.systemId);
|
|
2450
|
+
} catch {
|
|
2451
|
+
return executionFailure("INVALID_STATE");
|
|
2452
|
+
}
|
|
2453
|
+
}
|
|
2454
|
+
reconcile(options) {
|
|
2455
|
+
return reconcileOriginalDecision(this.#database, this.#association, options);
|
|
2456
|
+
}
|
|
2457
|
+
async acquire(id2) {
|
|
2458
|
+
const context = executionContext(this.#database), association = this.#association, key = effectId(association);
|
|
2459
|
+
const acquired = context.transaction(() => {
|
|
2460
|
+
associateEffect(context, association, id2);
|
|
2461
|
+
assertResolvedRun(context, association.identity, key);
|
|
2462
|
+
const owner2 = acquireOwner(context, "decision", association.identity), state = readState(context, "decision", key, association.identity);
|
|
2463
|
+
return { owner: owner2, revision: state?.revision ?? 0 };
|
|
2464
|
+
}, true);
|
|
2465
|
+
const owner = acquired.owner;
|
|
2466
|
+
markOwnerActive(context, owner);
|
|
2467
|
+
let revision = acquired.revision, released = false, poisoned = false, busy = false;
|
|
2468
|
+
const assert = () => {
|
|
2469
|
+
if (released || poisoned) executionFailure("OUTCOME_UNKNOWN");
|
|
2470
|
+
assertOwner(context, owner);
|
|
2471
|
+
};
|
|
2472
|
+
const captureSnapshot = () => context.transaction(() => {
|
|
2473
|
+
assert();
|
|
2474
|
+
return readState(context, "decision", key, association.identity);
|
|
2475
|
+
});
|
|
2476
|
+
const checkSnapshot = (snapshot) => context.transaction(() => {
|
|
2477
|
+
assert();
|
|
2478
|
+
const effect = readEffect(context, key), current = readState(context, "decision", key, association.identity);
|
|
2479
|
+
if (!effect || canonical(effect.association) !== canonical(association) || (current?.revision ?? 0) !== revision || current?.recordDigest !== snapshot?.recordDigest || current?.recordJson !== snapshot?.recordJson) executionFailure("OUTCOME_UNKNOWN");
|
|
2480
|
+
});
|
|
2481
|
+
return {
|
|
2482
|
+
async load() {
|
|
2483
|
+
if (busy) executionFailure("CODEC_BUSY");
|
|
2484
|
+
busy = true;
|
|
2485
|
+
try {
|
|
2486
|
+
return await context.codec.operation(async () => {
|
|
2487
|
+
const snapshot = captureSnapshot();
|
|
2488
|
+
if (!snapshot) return void 0;
|
|
2489
|
+
const record = await hydrateState(context, "decision", snapshot, () => checkSnapshot(snapshot));
|
|
2490
|
+
checkSnapshot(snapshot);
|
|
2491
|
+
return validateDecisionRecord(record, id2);
|
|
2492
|
+
});
|
|
2493
|
+
} catch (error) {
|
|
2494
|
+
poisoned = true;
|
|
2495
|
+
return safeExecutionFailure(error);
|
|
2496
|
+
} finally {
|
|
2497
|
+
busy = false;
|
|
2498
|
+
}
|
|
2499
|
+
},
|
|
2500
|
+
async save(input2) {
|
|
2501
|
+
if (busy) executionFailure("CODEC_BUSY");
|
|
2502
|
+
busy = true;
|
|
2503
|
+
try {
|
|
2504
|
+
await context.codec.operation(async () => {
|
|
2505
|
+
const snapshot = captureSnapshot(), check = () => checkSnapshot(snapshot);
|
|
2506
|
+
const captured = await context.codec.capture(input2, check);
|
|
2507
|
+
check();
|
|
2508
|
+
const next = validateDecisionRecord(captured, id2);
|
|
2509
|
+
const previous = snapshot ? await hydrateState(context, "decision", snapshot, check) : void 0;
|
|
2510
|
+
check();
|
|
2511
|
+
validateTransition(previous ? validateDecisionRecord(previous, id2) : void 0, next);
|
|
2512
|
+
const prepared2 = await prepareState(context, "decision", key, association.identity, next, revision, `decision.${next.status}`, check);
|
|
2513
|
+
check();
|
|
2514
|
+
const saved = context.transaction(() => {
|
|
2515
|
+
assert();
|
|
2516
|
+
assertResolvedRun(context, association.identity, key);
|
|
2517
|
+
return commitState(context, "decision", key, association.identity, prepared2);
|
|
2518
|
+
}, true);
|
|
2519
|
+
revision = saved.revision;
|
|
2520
|
+
});
|
|
2521
|
+
} catch (error) {
|
|
2522
|
+
poisoned = true;
|
|
2523
|
+
safeExecutionFailure(error);
|
|
2524
|
+
} finally {
|
|
2525
|
+
busy = false;
|
|
2526
|
+
}
|
|
2527
|
+
},
|
|
2528
|
+
async release() {
|
|
2529
|
+
if (released) return;
|
|
2530
|
+
if (busy) executionFailure("OUTCOME_UNKNOWN");
|
|
2531
|
+
try {
|
|
2532
|
+
if (poisoned) executionFailure("OUTCOME_UNKNOWN");
|
|
2533
|
+
context.transaction(() => releaseOwner(context, owner), true);
|
|
2534
|
+
released = true;
|
|
2535
|
+
} finally {
|
|
2536
|
+
markOwnerDrained(context, owner);
|
|
2537
|
+
}
|
|
2538
|
+
}
|
|
2539
|
+
};
|
|
2540
|
+
}
|
|
2541
|
+
};
|
|
2542
|
+
|
|
2543
|
+
// src/orchestration/log/workflow-store.ts
|
|
2544
|
+
import { types as types6 } from "node:util";
|
|
2545
|
+
function captureDefinition(input2) {
|
|
2546
|
+
try {
|
|
2547
|
+
input2 = ownObject(input2, ["id", "version", "steps"]);
|
|
2548
|
+
identifier(input2.id);
|
|
2549
|
+
identifier(input2.version);
|
|
2550
|
+
if (types6.isProxy(input2.steps) || !Array.isArray(input2.steps) || input2.steps.length > 1024) executionFailure("INVALID_STATE");
|
|
2551
|
+
const steps = [];
|
|
2552
|
+
for (let index = 0; index < input2.steps.length; index++) {
|
|
2553
|
+
const descriptor = Object.getOwnPropertyDescriptor(input2.steps, String(index));
|
|
2554
|
+
if (!descriptor || !Object.hasOwn(descriptor, "value")) executionFailure("INVALID_STATE");
|
|
2555
|
+
const step = ownObject(descriptor.value, ["id", "execute", "dependencies", "maxAttempts", "replaySafe"]);
|
|
2556
|
+
object(step);
|
|
2557
|
+
identifier(step.id);
|
|
2558
|
+
if (types6.isProxy(step.execute) || typeof step.execute !== "function") executionFailure("INVALID_STATE");
|
|
2559
|
+
const dependencies = captureExecutionValue(step.dependencies ?? []);
|
|
2560
|
+
if (!Array.isArray(dependencies)) executionFailure("INVALID_STATE");
|
|
2561
|
+
for (const dependency of dependencies) identifier(dependency);
|
|
2562
|
+
const maxAttempts = step.maxAttempts ?? 1, replaySafe = step.replaySafe ?? false;
|
|
2563
|
+
if (!Number.isSafeInteger(maxAttempts) || Number(maxAttempts) < 1 || typeof replaySafe !== "boolean") executionFailure("INVALID_STATE");
|
|
2564
|
+
steps.push({ id: step.id, execute: step.execute, dependencies, maxAttempts: Number(maxAttempts), replaySafe });
|
|
2565
|
+
}
|
|
2566
|
+
const definition = { id: input2.id, version: input2.version, steps: cloneSteps(steps) };
|
|
2567
|
+
identity(definition);
|
|
2568
|
+
dependencyWaves(definition.steps);
|
|
2569
|
+
return definition;
|
|
2570
|
+
} catch {
|
|
2571
|
+
return executionFailure("INVALID_STATE");
|
|
2572
|
+
}
|
|
2573
|
+
}
|
|
2574
|
+
function guardCheckpoint(context, identity2, next, previous) {
|
|
2575
|
+
const key = runKey(context.source.sourceId, identity2);
|
|
2576
|
+
visitEffects(context, (_id, effect) => {
|
|
2577
|
+
if (!unresolved(effect.metadata) || runKey(context.source.sourceId, effect.association.identity) !== key) return;
|
|
2578
|
+
const step = next.steps[effect.association.stepId], before = previous?.steps[effect.association.stepId];
|
|
2579
|
+
if (!step || ["pending", "completed"].includes(step.status) || step.status === "running" && (before?.status !== "running" || before.attempts !== step.attempts)) executionFailure("OUTCOME_UNKNOWN");
|
|
2580
|
+
});
|
|
2581
|
+
}
|
|
2582
|
+
var LogWorkflowStore = class {
|
|
2583
|
+
#database;
|
|
2584
|
+
#identity;
|
|
2585
|
+
#definition;
|
|
2586
|
+
constructor(options) {
|
|
2587
|
+
try {
|
|
2588
|
+
options = ownObject(options, ["database", "identity", "definition"]);
|
|
2589
|
+
const context = executionContext(options.database);
|
|
2590
|
+
this.#identity = captureIdentity2(options.identity);
|
|
2591
|
+
if (this.#identity.systemId !== context.source.systemId) executionFailure("INVALID_STATE");
|
|
2592
|
+
this.#database = options.database;
|
|
2593
|
+
this.#definition = captureDefinition(options.definition);
|
|
2594
|
+
} catch {
|
|
2595
|
+
return executionFailure("INVALID_STATE");
|
|
2596
|
+
}
|
|
2597
|
+
}
|
|
2598
|
+
async acquire(runId) {
|
|
2599
|
+
if (runId !== this.#identity.runId) executionFailure("INVALID_STATE");
|
|
2600
|
+
const context = executionContext(this.#database), identity2 = this.#identity, key = runKey(context.source.sourceId, identity2), definition = this.#definition;
|
|
2601
|
+
const acquired = context.transaction(() => ({ owner: acquireOwner(context, "workflow", identity2), revision: readState(context, "workflow", key, identity2)?.revision ?? 0 }), true);
|
|
2602
|
+
const owner = acquired.owner;
|
|
2603
|
+
markOwnerActive(context, owner);
|
|
2604
|
+
let revision = acquired.revision, poisoned = false, released = false, busy = false;
|
|
2605
|
+
const assert = () => {
|
|
2606
|
+
if (released || poisoned) executionFailure("OUTCOME_UNKNOWN");
|
|
2607
|
+
assertOwner(context, owner);
|
|
2608
|
+
};
|
|
2609
|
+
const captureSnapshot = () => context.transaction(() => {
|
|
2610
|
+
assert();
|
|
2611
|
+
return readState(context, "workflow", key, identity2);
|
|
2612
|
+
});
|
|
2613
|
+
const checkSnapshot = (snapshot) => context.transaction(() => {
|
|
2614
|
+
assert();
|
|
2615
|
+
const current = readState(context, "workflow", key, identity2);
|
|
2616
|
+
if ((current?.revision ?? 0) !== revision || current?.recordDigest !== snapshot?.recordDigest || current?.recordJson !== snapshot?.recordJson) executionFailure("OUTCOME_UNKNOWN");
|
|
2617
|
+
});
|
|
2618
|
+
return {
|
|
2619
|
+
async load() {
|
|
2620
|
+
if (busy) executionFailure("CODEC_BUSY");
|
|
2621
|
+
busy = true;
|
|
2622
|
+
try {
|
|
2623
|
+
return await context.codec.operation(async () => {
|
|
2624
|
+
const snapshot = captureSnapshot();
|
|
2625
|
+
if (!snapshot) return void 0;
|
|
2626
|
+
const record = await hydrateState(context, "workflow", snapshot, () => checkSnapshot(snapshot));
|
|
2627
|
+
checkSnapshot(snapshot);
|
|
2628
|
+
const checkpoint = validateCheckpoint(record, definition, runId);
|
|
2629
|
+
context.transaction(() => {
|
|
2630
|
+
assert();
|
|
2631
|
+
guardCheckpoint(context, identity2, checkpoint, checkpoint);
|
|
2632
|
+
});
|
|
2633
|
+
return checkpoint;
|
|
2634
|
+
});
|
|
2635
|
+
} catch (error) {
|
|
2636
|
+
poisoned = true;
|
|
2637
|
+
return safeExecutionFailure(error);
|
|
2638
|
+
} finally {
|
|
2639
|
+
busy = false;
|
|
2640
|
+
}
|
|
2641
|
+
},
|
|
2642
|
+
async save(input2) {
|
|
2643
|
+
if (busy) executionFailure("CODEC_BUSY");
|
|
2644
|
+
busy = true;
|
|
2645
|
+
try {
|
|
2646
|
+
await context.codec.operation(async () => {
|
|
2647
|
+
const snapshot = captureSnapshot(), check = () => checkSnapshot(snapshot);
|
|
2648
|
+
const captured = await context.codec.capture(input2, check);
|
|
2649
|
+
check();
|
|
2650
|
+
const next = validateCheckpoint(captured, definition, runId);
|
|
2651
|
+
const original = snapshot ? await hydrateState(context, "workflow", snapshot, check) : void 0;
|
|
2652
|
+
check();
|
|
2653
|
+
const previous = original ? validateCheckpoint(original, definition, runId) : void 0;
|
|
2654
|
+
const prepared2 = await prepareState(context, "workflow", key, identity2, next, revision, `workflow.${next.status}`, check);
|
|
2655
|
+
check();
|
|
2656
|
+
const result = context.transaction(() => {
|
|
2657
|
+
assert();
|
|
2658
|
+
guardCheckpoint(context, identity2, next, previous);
|
|
2659
|
+
return commitState(context, "workflow", key, identity2, prepared2);
|
|
2660
|
+
}, true);
|
|
2661
|
+
revision = result.revision;
|
|
2662
|
+
});
|
|
2663
|
+
} catch (error) {
|
|
2664
|
+
poisoned = true;
|
|
2665
|
+
safeExecutionFailure(error);
|
|
2666
|
+
} finally {
|
|
2667
|
+
busy = false;
|
|
2668
|
+
}
|
|
2669
|
+
},
|
|
2670
|
+
async release() {
|
|
2671
|
+
if (released) return;
|
|
2672
|
+
if (busy) executionFailure("OUTCOME_UNKNOWN");
|
|
2673
|
+
try {
|
|
2674
|
+
if (poisoned) executionFailure("OUTCOME_UNKNOWN");
|
|
2675
|
+
context.transaction(() => releaseOwner(context, owner), true);
|
|
2676
|
+
released = true;
|
|
2677
|
+
} finally {
|
|
2678
|
+
markOwnerDrained(context, owner);
|
|
2679
|
+
}
|
|
2680
|
+
}
|
|
2681
|
+
};
|
|
2682
|
+
}
|
|
2683
|
+
};
|
|
2684
|
+
|
|
2685
|
+
// src/orchestration/log/projection.ts
|
|
2686
|
+
import { types as types7 } from "node:util";
|
|
2687
|
+
|
|
2688
|
+
// src/orchestration/log/projection-reconciliation.ts
|
|
2689
|
+
var digests = ["decisionIdDigest", "intentIdDigest", "associationDigest", "inputHash", "authorityHash", "inputVersionDigest", "authorityVersionDigest", "resultHash"];
|
|
2690
|
+
var fields = ["kind", "status", ...digests, "evidenceDigests", "original", "verified"];
|
|
2691
|
+
function reference(input2) {
|
|
2692
|
+
object(input2, ["sourceIdDigest", "sequence", "digest"]);
|
|
2693
|
+
if (Object.keys(input2).length !== 3) throw Error();
|
|
2694
|
+
hash(input2.sourceIdDigest);
|
|
2695
|
+
hash(input2.digest);
|
|
2696
|
+
boundedInteger(input2.sequence, 1, Number.MAX_SAFE_INTEGER);
|
|
2697
|
+
return { sourceIdDigest: input2.sourceIdDigest, sequence: input2.sequence, digest: input2.digest };
|
|
2698
|
+
}
|
|
2699
|
+
function capturePublicReconciliation(input2) {
|
|
2700
|
+
object(input2, fields);
|
|
2701
|
+
if (Object.keys(input2).length !== fields.length || input2.kind !== "decision-reconciliation" || input2.status !== "verified") throw Error();
|
|
2702
|
+
for (const key of digests) hash(input2[key]);
|
|
2703
|
+
const evidenceDigests = boundedDataArray(input2.evidenceDigests, 64);
|
|
2704
|
+
for (const value of evidenceDigests) hash(value);
|
|
2705
|
+
const original = reference(input2.original), verified = reference(input2.verified);
|
|
2706
|
+
if (original.sequence >= verified.sequence) throw Error();
|
|
2707
|
+
return freeze({ ...input2, evidenceDigests: [...evidenceDigests], original, verified });
|
|
2708
|
+
}
|
|
2709
|
+
function projectReconciliation(entry, input2) {
|
|
2710
|
+
object(input2, fields);
|
|
2711
|
+
if (entry.record.type !== "decision.reconciled") throw Error();
|
|
2712
|
+
const transform = (raw) => {
|
|
2713
|
+
object(raw, ["sourceId", "sequence", "digest"]);
|
|
2714
|
+
if (raw.sourceId !== entry.sourceId || Object.keys(raw).length !== 3) throw Error();
|
|
2715
|
+
hash(raw.digest);
|
|
2716
|
+
boundedInteger(raw.sequence, 1, entry.sequence - 1);
|
|
2717
|
+
return { sourceIdDigest: digest(entry.sourceId), sequence: raw.sequence, digest: raw.digest };
|
|
2718
|
+
};
|
|
2719
|
+
if (canonical(entry.record.causal) !== canonical([input2.original, input2.verified])) throw Error();
|
|
2720
|
+
return capturePublicReconciliation({ ...input2, original: transform(input2.original), verified: transform(input2.verified) });
|
|
2721
|
+
}
|
|
2722
|
+
function coherentReconciliation(item2, items, sourceId) {
|
|
2723
|
+
const m = item2.metadata, original = reference(m.original), verified = reference(m.verified);
|
|
2724
|
+
if (original.sourceIdDigest !== digest(sourceId) || verified.sourceIdDigest !== digest(sourceId) || verified.sequence >= item2.position.sequence || canonical(item2.causal) !== canonical([original, verified])) return false;
|
|
2725
|
+
const before = items.get(original.sequence), after = items.get(verified.sequence);
|
|
2726
|
+
if (before?.position.digest !== original.digest || after?.position.digest !== verified.digest || before.category !== "decision" || after.category !== "decision") return false;
|
|
2727
|
+
const b = before.metadata, a = after.metadata;
|
|
2728
|
+
return ["intent", "dispatched", "needs-owner"].includes(b.status) && a.status === "verified" && a.resultHash === m.resultHash && ["decisionIdDigest", "intentIdDigest", "inputHash", "authorityHash", "inputVersionDigest", "authorityVersionDigest"].every((key) => b[key] === m[key] && a[key] === m[key]);
|
|
2729
|
+
}
|
|
2730
|
+
|
|
2731
|
+
// src/orchestration/log/projection-codecs.ts
|
|
2732
|
+
function executionMetadata2(entry, input2) {
|
|
2733
|
+
object(input2, entry.record.schema.version === 1 ? ["kind", "key", "revision", "recordJson", "recordDigest", "metadata"] : ["kind", "key", "revision", "recordDigest", "body", "metadata"]);
|
|
2734
|
+
if (entry.record.schema.version === 1) {
|
|
2735
|
+
if (typeof input2.recordJson !== "string") throw Error();
|
|
2736
|
+
} else {
|
|
2737
|
+
const body = captureRecordBody(input2.body, entry.sourceId, entry.record.identity, 128 * 1024 * 1024);
|
|
2738
|
+
if (body.reference.digest !== input2.recordDigest) throw Error();
|
|
2739
|
+
}
|
|
2740
|
+
hash(input2.key);
|
|
2741
|
+
hash(input2.recordDigest);
|
|
2742
|
+
boundedInteger(input2.revision, 1, Number.MAX_SAFE_INTEGER);
|
|
2743
|
+
const kind = entry.record.schema.id === "oar.execution.decision" ? "decision" : "workflow";
|
|
2744
|
+
if (input2.kind !== kind) throw Error();
|
|
2745
|
+
const metadata = decodeExecutionMetadata(kind, input2.metadata);
|
|
2746
|
+
if (entry.record.type !== `${kind}.${metadata.status}`) throw Error();
|
|
2747
|
+
return metadata;
|
|
2748
|
+
}
|
|
2749
|
+
function decodeExecutionMetadata(kind, metadata) {
|
|
2750
|
+
if (kind === "workflow") {
|
|
2751
|
+
object(metadata);
|
|
2752
|
+
boundedDataArray(metadata.steps, 256);
|
|
2753
|
+
}
|
|
2754
|
+
return captureExecutionMetadata(kind, metadata);
|
|
2755
|
+
}
|
|
2756
|
+
function projectCommittedEntry(entry) {
|
|
2757
|
+
const position2 = { sourceId: entry.sourceId, sequence: entry.sequence, digest: entry.digest }, issues2 = [];
|
|
2758
|
+
const base = { id: `${entry.sourceId}:${entry.sequence}:${entry.digest}`, position: position2, causal: entry.record.causal.map((ref) => ({ sourceIdDigest: digest(ref.sourceId), sequence: ref.sequence, digest: ref.digest })) };
|
|
2759
|
+
if ("artifact" in entry.record.payload) return freeze({ ...base, category: "unprojected", issues: ["PRIVATE_PAYLOAD"] });
|
|
2760
|
+
const schema = entry.record.schema;
|
|
2761
|
+
try {
|
|
2762
|
+
if (schema.id === RUN_HISTORY_SCHEMA && schema.version === 1) return freeze({ ...base, category: "run", metadata: { stage: entry.record.type.slice(4), ...decodeRunMarker(entry.record.type, entry.record.payload.inline) }, issues: issues2 });
|
|
2763
|
+
else if (schema.id === "oar.execution.reconciliation" && schema.version === 1) return freeze({ ...base, category: "reconciliation", metadata: projectReconciliation(entry, entry.record.payload.inline), issues: issues2 });
|
|
2764
|
+
else if (["oar.execution.decision", "oar.execution.workflow"].includes(schema.id) && [1, 2].includes(schema.version)) {
|
|
2765
|
+
if (schema.version === 2) issues2.push("PRIVATE_PAYLOAD");
|
|
2766
|
+
return freeze({ ...base, category: schema.id === "oar.execution.decision" ? "decision" : "workflow", metadata: executionMetadata2(entry, entry.record.payload.inline), issues: issues2 });
|
|
2767
|
+
} else if (schema.version !== 1) issues2.push("UNKNOWN_SCHEMA");
|
|
2768
|
+
else if ([AGENT_METADATA_SCHEMA, CAPTURE_OPERATION_SCHEMA].includes(schema.id)) return freeze({ ...base, category: schema.id === AGENT_METADATA_SCHEMA ? "agent-event" : "capture-operation", metadata: decodeCaptureMetadata(schema.id, entry.record.type, entry.record.payload.inline), issues: issues2 });
|
|
2769
|
+
else issues2.push(["oar.execution.association", "oar.execution.ownership"].includes(schema.id) ? "PRIVATE_PAYLOAD" : "UNKNOWN_SCHEMA");
|
|
2770
|
+
} catch {
|
|
2771
|
+
issues2.push("INVALID_METADATA");
|
|
2772
|
+
}
|
|
2773
|
+
return freeze({ ...base, category: "unprojected", issues: issues2 });
|
|
2774
|
+
}
|
|
2775
|
+
|
|
2776
|
+
// src/orchestration/log/projection-data.ts
|
|
2777
|
+
var sameProjectionData = (a, b) => canonical(a) === canonical(b);
|
|
2778
|
+
var issueCodes = ["UNKNOWN_SCHEMA", "PRIVATE_PAYLOAD", "INVALID_METADATA", "UNRESOLVED_CAUSAL_REFERENCE", "LOG_CORRUPT", "SOURCE_UNAVAILABLE", "PROJECTION_LIMIT", "HISTORY_GAP", "RUN_NOT_FOUND", "INVOCATION_UNSETTLED", "INCOMPLETE_ORIGIN"];
|
|
2779
|
+
var dataArray = boundedDataArray;
|
|
2780
|
+
function projectionPosition(input2, source) {
|
|
2781
|
+
object(input2, ["sourceId", "sequence", "digest"]);
|
|
2782
|
+
if (input2.sourceId !== source.sourceId) invalidCapture();
|
|
2783
|
+
boundedInteger(input2.sequence, 0, Number.MAX_SAFE_INTEGER);
|
|
2784
|
+
hash(input2.digest);
|
|
2785
|
+
if (input2.sequence === 0 && input2.digest !== genesis(source)) invalidCapture();
|
|
2786
|
+
return freeze({ sourceId: input2.sourceId, sequence: input2.sequence, digest: input2.digest });
|
|
2787
|
+
}
|
|
2788
|
+
function projectionSource(input2) {
|
|
2789
|
+
object(input2, ["format", "sourceId", "systemId"]);
|
|
2790
|
+
if (input2.format !== 1 || typeof input2.sourceId !== "string" || !input2.sourceId || input2.sourceId.length > 128 || typeof input2.systemId !== "string" || !input2.systemId || input2.systemId.length > 128) invalidCapture();
|
|
2791
|
+
return freeze({ format: 1, sourceId: input2.sourceId, systemId: input2.systemId });
|
|
2792
|
+
}
|
|
2793
|
+
function projectionCursor(input2, purpose, identityDigest, source) {
|
|
2794
|
+
object(input2, ["format", "purpose", "identityDigest", "source", "underlying"]);
|
|
2795
|
+
if (input2.format !== 1 || input2.purpose !== purpose || input2.identityDigest !== identityDigest || !sameProjectionData(projectionSource(input2.source), source)) invalidCapture();
|
|
2796
|
+
object(input2.underlying, ["format", "filterDigest", "after", "through"]);
|
|
2797
|
+
const raw = input2.underlying;
|
|
2798
|
+
if (raw.format !== 1) invalidCapture();
|
|
2799
|
+
hash(raw.filterDigest);
|
|
2800
|
+
const after = projectionPosition(raw.after, source), through = projectionPosition(raw.through, source);
|
|
2801
|
+
if (after.sequence > through.sequence) invalidCapture();
|
|
2802
|
+
return freeze({ format: 1, purpose, identityDigest, source, underlying: { format: 1, filterDigest: raw.filterDigest, after, through } });
|
|
2803
|
+
}
|
|
2804
|
+
function issues(input2) {
|
|
2805
|
+
const result = dataArray(input2, issueCodes.length);
|
|
2806
|
+
if (new Set(result).size !== result.length || result.some((code) => !issueCodes.includes(code))) invalidCapture();
|
|
2807
|
+
return [...result];
|
|
2808
|
+
}
|
|
2809
|
+
function item(input2, source) {
|
|
2810
|
+
object(input2, ["id", "position", "causal", "category", "metadata", "issues"]);
|
|
2811
|
+
const position2 = projectionPosition(input2.position, source);
|
|
2812
|
+
if (!position2.sequence || input2.id !== `${source.sourceId}:${position2.sequence}:${position2.digest}`) invalidCapture();
|
|
2813
|
+
const causal = dataArray(input2.causal, 64).map((ref) => {
|
|
2814
|
+
object(ref, ["sourceIdDigest", "sequence", "digest"]);
|
|
2815
|
+
hash(ref.sourceIdDigest);
|
|
2816
|
+
hash(ref.digest);
|
|
2817
|
+
boundedInteger(ref.sequence, 1, Number.MAX_SAFE_INTEGER);
|
|
2818
|
+
return { sourceIdDigest: ref.sourceIdDigest, sequence: ref.sequence, digest: ref.digest };
|
|
2819
|
+
});
|
|
2820
|
+
const category = input2.category;
|
|
2821
|
+
let metadata;
|
|
2822
|
+
if (category === "agent-event") {
|
|
2823
|
+
object(input2.metadata);
|
|
2824
|
+
object(input2.metadata.event);
|
|
2825
|
+
const type = input2.metadata.event.type;
|
|
2826
|
+
if (typeof type !== "string") invalidCapture();
|
|
2827
|
+
metadata = decodeCaptureMetadata(AGENT_METADATA_SCHEMA, type, input2.metadata);
|
|
2828
|
+
} else if (category === "capture-operation") {
|
|
2829
|
+
object(input2.metadata);
|
|
2830
|
+
metadata = decodeCaptureMetadata(CAPTURE_OPERATION_SCHEMA, `capture.${input2.metadata.stage}`, input2.metadata);
|
|
2831
|
+
} else if (category === "decision" || category === "workflow") metadata = decodeExecutionMetadata(category, input2.metadata);
|
|
2832
|
+
else if (category === "reconciliation") metadata = capturePublicReconciliation(input2.metadata);
|
|
2833
|
+
else if (category === "run") metadata = capturePublicRunMarker(input2.metadata);
|
|
2834
|
+
else if (category !== "unprojected" || input2.metadata !== void 0) invalidCapture();
|
|
2835
|
+
return freeze({ id: input2.id, position: position2, causal, category, ...metadata ? { metadata } : {}, issues: issues(input2.issues) });
|
|
2836
|
+
}
|
|
2837
|
+
function captureProjectionPage(input2) {
|
|
2838
|
+
object(input2, ["format", "purpose", "identityDigest", "source", "from", "through", "links", "items", "issues", "nextCursor"]);
|
|
2839
|
+
if (input2.format !== 1 || !["trace", "audit"].includes(input2.purpose)) invalidCapture();
|
|
2840
|
+
hash(input2.identityDigest);
|
|
2841
|
+
const purpose = input2.purpose, source = projectionSource(input2.source), from = projectionPosition(input2.from, source), through = projectionPosition(input2.through, source);
|
|
2842
|
+
if (from.sequence > through.sequence) invalidCapture();
|
|
2843
|
+
const links = dataArray(input2.links, 256).map((raw) => {
|
|
2844
|
+
object(raw, ["position", "previousDigest"]);
|
|
2845
|
+
hash(raw.previousDigest);
|
|
2846
|
+
return { position: projectionPosition(raw.position, source), previousDigest: raw.previousDigest };
|
|
2847
|
+
});
|
|
2848
|
+
let previous = from;
|
|
2849
|
+
for (const link2 of links) {
|
|
2850
|
+
if (link2.position.sequence !== previous.sequence + 1 || link2.previousDigest !== previous.digest || link2.position.sequence > through.sequence) invalidCapture();
|
|
2851
|
+
previous = link2.position;
|
|
2852
|
+
}
|
|
2853
|
+
const items = dataArray(input2.items, 256).map((raw) => item(raw, source));
|
|
2854
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2855
|
+
for (const entry of items) {
|
|
2856
|
+
if (seen.has(entry.position.sequence) || !links.some((link2) => sameProjectionData(link2.position, entry.position))) invalidCapture();
|
|
2857
|
+
seen.add(entry.position.sequence);
|
|
2858
|
+
}
|
|
2859
|
+
const nextCursor = input2.nextCursor === void 0 ? void 0 : projectionCursor(input2.nextCursor, purpose, input2.identityDigest, source);
|
|
2860
|
+
if (nextCursor && (!sameProjectionData(nextCursor.underlying.after, previous) || !sameProjectionData(nextCursor.underlying.through, through))) invalidCapture();
|
|
2861
|
+
const result = freeze({ format: 1, purpose, identityDigest: input2.identityDigest, source, from, through, links, items, issues: issues(input2.issues), ...nextCursor ? { nextCursor } : {} });
|
|
2862
|
+
if (Buffer.byteLength(canonical(result)) > 4 * 1024 * 1024) invalidCapture();
|
|
2863
|
+
return result;
|
|
2864
|
+
}
|
|
2865
|
+
|
|
2866
|
+
// src/orchestration/log/projection.ts
|
|
2867
|
+
var MAX_LINKS = 32768;
|
|
2868
|
+
var MAX_BYTES = 4 * 1024 * 1024;
|
|
2869
|
+
function checkedEntry(input2, source) {
|
|
2870
|
+
object(input2, ["format", "sourceId", "sequence", "digest", "requestId", "ordinal", "previousDigest", "record"]);
|
|
2871
|
+
const commit = capture({ requestId: input2.requestId, records: [input2.record] }, source);
|
|
2872
|
+
hash(input2.digest);
|
|
2873
|
+
hash(input2.previousDigest);
|
|
2874
|
+
if (input2.format !== 1 || input2.sourceId !== source.sourceId) invalidCapture();
|
|
2875
|
+
boundedInteger(input2.sequence, 1, Number.MAX_SAFE_INTEGER);
|
|
2876
|
+
boundedInteger(input2.ordinal, 1, 256);
|
|
2877
|
+
return decodeEntry(canonical(entryBody(source, input2.sequence, commit.requestId, input2.ordinal, input2.previousDigest, commit.records[0])), input2.digest, source);
|
|
2878
|
+
}
|
|
2879
|
+
function createLogProjector(purpose, options) {
|
|
2880
|
+
object(options, ["reader", "identity", "maxPages", "maxEntries"]);
|
|
2881
|
+
const identity2 = captureIdentity(options.identity), identityDigest = digest(canonical(identity2));
|
|
2882
|
+
if (!options.reader || typeof options.reader !== "object" || types7.isProxy(options.reader)) invalidCapture();
|
|
2883
|
+
const sourceDescriptor = Object.getOwnPropertyDescriptor(options.reader, "descriptor");
|
|
2884
|
+
if (!sourceDescriptor || !Object.hasOwn(sourceDescriptor, "value")) invalidCapture();
|
|
2885
|
+
const source = projectionSource(sourceDescriptor.value);
|
|
2886
|
+
if (source.systemId !== identity2.systemId) invalidCapture();
|
|
2887
|
+
const readPage = method(options.reader, "readPage");
|
|
2888
|
+
const maxPages = boundedInteger(options.maxPages ?? 128, 1, 128), maxEntries = boundedInteger(options.maxEntries ?? 1e4, 1, 1e4);
|
|
2889
|
+
async function read2(input2 = {}) {
|
|
2890
|
+
object(input2, ["cursor", "limit"]);
|
|
2891
|
+
const limit = Math.min(boundedInteger(input2.limit ?? 32, 1, 256), 32);
|
|
2892
|
+
const saved = input2.cursor === void 0 ? void 0 : projectionCursor(input2.cursor, purpose, identityDigest, source);
|
|
2893
|
+
const from = saved?.underlying.after ?? { sourceId: source.sourceId, sequence: 0, digest: genesis(source) };
|
|
2894
|
+
let through = saved?.underlying.through ?? from;
|
|
2895
|
+
const links = [], items = [], issues2 = [];
|
|
2896
|
+
let nextCursor;
|
|
2897
|
+
try {
|
|
2898
|
+
const page = await readPage({ limit, ...saved ? { cursor: saved.underlying } : {} });
|
|
2899
|
+
object(page, ["source", "through", "items", "scanned", "nextCursor"]);
|
|
2900
|
+
if (!sameProjectionData(projectionSource(page.source), source)) invalidCapture();
|
|
2901
|
+
through = projectionPosition(page.through, source);
|
|
2902
|
+
if (saved && !sameProjectionData(through, saved.underlying.through) || through.sequence < from.sequence) invalidCapture();
|
|
2903
|
+
const entries = dataArray(page.items, limit);
|
|
2904
|
+
if (page.scanned !== entries.length) invalidCapture();
|
|
2905
|
+
let previous = from;
|
|
2906
|
+
for (const raw of entries) {
|
|
2907
|
+
const entry = checkedEntry(raw, source);
|
|
2908
|
+
if (entry.sequence !== previous.sequence + 1 || entry.previousDigest !== previous.digest || entry.sequence > through.sequence) invalidCapture();
|
|
2909
|
+
const at = { sourceId: entry.sourceId, sequence: entry.sequence, digest: entry.digest };
|
|
2910
|
+
links.push({ position: at, previousDigest: entry.previousDigest });
|
|
2911
|
+
previous = at;
|
|
2912
|
+
if (sameProjectionData(entry.record.identity, identity2)) items.push(projectCommittedEntry(entry));
|
|
2913
|
+
}
|
|
2914
|
+
if (page.nextCursor !== void 0) {
|
|
2915
|
+
nextCursor = projectionCursor({ format: 1, purpose, identityDigest, source, underlying: page.nextCursor }, purpose, identityDigest, source);
|
|
2916
|
+
if (!sameProjectionData(nextCursor.underlying.after, previous) || !sameProjectionData(nextCursor.underlying.through, through) || previous.sequence >= through.sequence || !links.length) invalidCapture();
|
|
2917
|
+
} else if (!sameProjectionData(previous, through)) invalidCapture();
|
|
2918
|
+
} catch (error) {
|
|
2919
|
+
const code = error && typeof error === "object" && !types7.isProxy(error) ? Object.getOwnPropertyDescriptor(error, "code") : void 0;
|
|
2920
|
+
issues2.push(code && Object.hasOwn(code, "value") && ["STORAGE", "CLOSED", "BUSY"].includes(code.value) ? "SOURCE_UNAVAILABLE" : "LOG_CORRUPT");
|
|
2921
|
+
nextCursor = void 0;
|
|
2922
|
+
}
|
|
2923
|
+
return freeze({ format: 1, purpose, identityDigest, source, from, through, links, items, issues: issues2, ...nextCursor ? { nextCursor } : {} });
|
|
2924
|
+
}
|
|
2925
|
+
async function rebuild(input2 = {}) {
|
|
2926
|
+
object(input2, ["limit"]);
|
|
2927
|
+
const requestedLimit = boundedInteger(input2.limit ?? 32, 1, 256);
|
|
2928
|
+
const pages = [];
|
|
2929
|
+
let next, bytes = 0, entries = 0;
|
|
2930
|
+
for (let count = 0; count < maxPages; count++) {
|
|
2931
|
+
const page = await read2({ limit: Math.min(requestedLimit, maxEntries - entries), ...next ? { cursor: next } : {} });
|
|
2932
|
+
const pageBytes = Buffer.byteLength(canonical(page));
|
|
2933
|
+
if (pages.length && bytes + pageBytes > MAX_BYTES) break;
|
|
2934
|
+
pages.push(page);
|
|
2935
|
+
next = page.nextCursor;
|
|
2936
|
+
bytes += pageBytes;
|
|
2937
|
+
entries += page.items.length;
|
|
2938
|
+
if (!next || entries >= maxEntries || bytes >= MAX_BYTES) break;
|
|
2939
|
+
}
|
|
2940
|
+
const result = mergeLogProjectionPages(pages);
|
|
2941
|
+
if (!next) return result;
|
|
2942
|
+
return freeze({ ...result, kind: result.kind === "corrupt" ? "corrupt" : "incomplete", issues: [.../* @__PURE__ */ new Set([...result.issues, "PROJECTION_LIMIT"])] });
|
|
2943
|
+
}
|
|
2944
|
+
return Object.freeze({ read: read2, rebuild });
|
|
2945
|
+
}
|
|
2946
|
+
function mergeLogProjectionPages(pages) {
|
|
2947
|
+
const captured = [];
|
|
2948
|
+
let bytes = 0;
|
|
2949
|
+
for (const input2 of dataArray(pages, 256)) {
|
|
2950
|
+
const page = captureProjectionPage(input2);
|
|
2951
|
+
bytes += Buffer.byteLength(canonical(page));
|
|
2952
|
+
if (bytes > MAX_BYTES) invalidCapture();
|
|
2953
|
+
captured.push(page);
|
|
2954
|
+
}
|
|
2955
|
+
pages = captured;
|
|
2956
|
+
if (!pages.length) invalidCapture();
|
|
2957
|
+
const first = pages[0], links = /* @__PURE__ */ new Map(), items = /* @__PURE__ */ new Map(), issues2 = /* @__PURE__ */ new Set();
|
|
2958
|
+
for (const page of pages) {
|
|
2959
|
+
if (page.purpose !== first.purpose || page.identityDigest !== first.identityDigest || !sameProjectionData(page.source, first.source) || !sameProjectionData(page.through, first.through)) invalidCapture();
|
|
2960
|
+
for (const issue of page.issues) issues2.add(issue);
|
|
2961
|
+
for (const link2 of page.links) {
|
|
2962
|
+
const old = links.get(link2.position.sequence);
|
|
2963
|
+
if (old && !sameProjectionData(old, link2)) issues2.add("LOG_CORRUPT");
|
|
2964
|
+
else links.set(link2.position.sequence, link2);
|
|
2965
|
+
}
|
|
2966
|
+
for (const item2 of page.items) {
|
|
2967
|
+
const old = items.get(item2.position.sequence);
|
|
2968
|
+
if (old && !sameProjectionData(old, item2)) issues2.add("LOG_CORRUPT");
|
|
2969
|
+
else items.set(item2.position.sequence, item2);
|
|
2970
|
+
for (const issue of item2.issues) issues2.add(issue);
|
|
2971
|
+
}
|
|
2972
|
+
if (links.size > MAX_LINKS || items.size > 1e4) invalidCapture();
|
|
2973
|
+
}
|
|
2974
|
+
let coveredThrough = { sourceId: first.source.sourceId, sequence: 0, digest: genesis(first.source) };
|
|
2975
|
+
for (const link2 of [...links.values()].sort((a, b) => a.position.sequence - b.position.sequence)) {
|
|
2976
|
+
if (link2.position.sequence !== coveredThrough.sequence + 1 || link2.previousDigest !== coveredThrough.digest) {
|
|
2977
|
+
issues2.add("HISTORY_GAP");
|
|
2978
|
+
break;
|
|
2979
|
+
}
|
|
2980
|
+
coveredThrough = link2.position;
|
|
2981
|
+
}
|
|
2982
|
+
if (!sameProjectionData(coveredThrough, first.through)) issues2.add("HISTORY_GAP");
|
|
2983
|
+
const sorted = [...items.values()].sort((a, b) => a.position.sequence - b.position.sequence);
|
|
2984
|
+
if (!sorted.length) issues2.add("RUN_NOT_FOUND");
|
|
2985
|
+
const invocation = /* @__PURE__ */ new Map(), decisions = /* @__PURE__ */ new Map(), workflows = /* @__PURE__ */ new Map();
|
|
2986
|
+
let runStart, runStage;
|
|
2987
|
+
for (const item2 of sorted) {
|
|
2988
|
+
if (item2.category === "reconciliation" && !coherentReconciliation(item2, items, first.source.sourceId)) issues2.add("INCOMPLETE_ORIGIN");
|
|
2989
|
+
for (const causal of item2.causal) if (causal.sourceIdDigest !== digest(first.source.sourceId) || links.get(causal.sequence)?.position.digest !== causal.digest) issues2.add("UNRESOLVED_CAUSAL_REFERENCE");
|
|
2990
|
+
const m = item2.metadata;
|
|
2991
|
+
if (!m) continue;
|
|
2992
|
+
if (item2.category === "run") {
|
|
2993
|
+
if (m.stage === "started") {
|
|
2994
|
+
if (runStart || item2.causal.length) issues2.add("INCOMPLETE_ORIGIN");
|
|
2995
|
+
runStart = item2;
|
|
2996
|
+
runStage = "started";
|
|
2997
|
+
} else {
|
|
2998
|
+
if (!runStart || runStage !== "started" || runStart.metadata.inputDigest !== m.inputDigest || item2.causal.length !== 1 || item2.causal[0].sequence !== runStart.position.sequence || item2.causal[0].digest !== runStart.position.digest) issues2.add("INCOMPLETE_ORIGIN");
|
|
2999
|
+
runStage = m.stage;
|
|
3000
|
+
}
|
|
3001
|
+
}
|
|
3002
|
+
if (item2.category === "capture-operation" || item2.category === "agent-event") {
|
|
3003
|
+
const known = invocation.get(m.invocationDigest);
|
|
3004
|
+
if (item2.category === "capture-operation" && m.stage === "started") {
|
|
3005
|
+
if (known) issues2.add("INCOMPLETE_ORIGIN");
|
|
3006
|
+
invocation.set(m.invocationDigest, { stage: "started", actual: m.actual });
|
|
3007
|
+
} else if (!known || known.stage !== "started" || !sameProjectionData(known.actual, m.actual)) issues2.add("INCOMPLETE_ORIGIN");
|
|
3008
|
+
else if (item2.category === "capture-operation") invocation.set(m.invocationDigest, { ...known, stage: m.stage });
|
|
3009
|
+
}
|
|
3010
|
+
if (item2.category === "decision") decisions.set(m.decisionIdDigest, m.status);
|
|
3011
|
+
if (item2.category === "workflow") workflows.set(m.workflowIdDigest, m.status);
|
|
3012
|
+
}
|
|
3013
|
+
if ([...invocation.values()].some((value) => value.stage !== "settled")) issues2.add("INVOCATION_UNSETTLED");
|
|
3014
|
+
if (runStage && runStage !== "completed") issues2.add("INVOCATION_UNSETTLED");
|
|
3015
|
+
const awaiting = [...decisions.values()].some((status) => ["intent", "dispatched", "needs-owner", "waiting"].includes(status)) || [...workflows.values()].some((status) => status === "halted");
|
|
3016
|
+
return freeze({
|
|
3017
|
+
format: 1,
|
|
3018
|
+
purpose: first.purpose,
|
|
3019
|
+
identityDigest: first.identityDigest,
|
|
3020
|
+
scope: "captured-metadata",
|
|
3021
|
+
textReconstruction: "unavailable",
|
|
3022
|
+
qualityAssessment: "not-derived",
|
|
3023
|
+
source: first.source,
|
|
3024
|
+
through: first.through,
|
|
3025
|
+
coveredThrough,
|
|
3026
|
+
kind: issues2.has("LOG_CORRUPT") ? "corrupt" : issues2.size ? "incomplete" : awaiting ? "awaiting-owner" : "observed",
|
|
3027
|
+
items: sorted,
|
|
3028
|
+
issues: [...issues2].sort()
|
|
3029
|
+
});
|
|
3030
|
+
}
|
|
3031
|
+
|
|
3032
|
+
// src/orchestration/log/trace-projector.ts
|
|
3033
|
+
function createLogTraceProjector(options) {
|
|
3034
|
+
return createLogProjector("trace", options);
|
|
3035
|
+
}
|
|
3036
|
+
|
|
3037
|
+
// src/orchestration/log/audit-projector.ts
|
|
3038
|
+
function createLogAuditProjector(options) {
|
|
3039
|
+
return createLogProjector("audit", options);
|
|
3040
|
+
}
|
|
3041
|
+
export {
|
|
3042
|
+
LogDecisionStore,
|
|
3043
|
+
LogExecutionDatabase,
|
|
3044
|
+
LogExecutionError,
|
|
3045
|
+
LogStoreError,
|
|
3046
|
+
LogWorkflowStore,
|
|
3047
|
+
SqliteLogBinding,
|
|
3048
|
+
SqliteRunLogStore,
|
|
3049
|
+
createLogArtifactStore,
|
|
3050
|
+
createLogAuditProjector,
|
|
3051
|
+
createLogTraceProjector,
|
|
3052
|
+
createRequiredLogCapture,
|
|
3053
|
+
createRunHistory,
|
|
3054
|
+
inspectManagedEffect,
|
|
3055
|
+
isLogStoreError,
|
|
3056
|
+
mergeLogProjectionPages
|
|
3057
|
+
};
|
|
3058
|
+
//# sourceMappingURL=log.js.map
|