@caupulican/pi-adaptative 0.85.8 → 0.86.2
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/CHANGELOG.md +42 -0
- package/dist/core/agent-paths.d.ts +6 -3
- package/dist/core/agent-paths.d.ts.map +1 -1
- package/dist/core/agent-paths.js +10 -3
- package/dist/core/agent-paths.js.map +1 -1
- package/dist/core/agent-session.d.ts +5 -2
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +7 -1
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/autonomy/bounded-completion.d.ts.map +1 -1
- package/dist/core/autonomy/bounded-completion.js +19 -8
- package/dist/core/autonomy/bounded-completion.js.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.d.ts +11 -5
- package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.js +34 -8
- package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
- package/dist/core/autonomy/subagent-prompt.d.ts +3 -3
- package/dist/core/autonomy/subagent-prompt.js +9 -9
- package/dist/core/autonomy/subagent-prompt.js.map +1 -1
- package/dist/core/background-lane-controller.d.ts +10 -8
- package/dist/core/background-lane-controller.d.ts.map +1 -1
- package/dist/core/background-lane-controller.js +23 -13
- package/dist/core/background-lane-controller.js.map +1 -1
- package/dist/core/bash-execution-controller.d.ts +4 -0
- package/dist/core/bash-execution-controller.d.ts.map +1 -1
- package/dist/core/bash-execution-controller.js +11 -4
- package/dist/core/bash-execution-controller.js.map +1 -1
- package/dist/core/bash-executor.d.ts +2 -0
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +2 -1
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/capability-contract.d.ts +1 -1
- package/dist/core/capability-contract.d.ts.map +1 -1
- package/dist/core/capability-contract.js +0 -1
- package/dist/core/capability-contract.js.map +1 -1
- package/dist/core/default-tool-surface.d.ts +1 -0
- package/dist/core/default-tool-surface.d.ts.map +1 -1
- package/dist/core/default-tool-surface.js +3 -2
- package/dist/core/default-tool-surface.js.map +1 -1
- package/dist/core/delegation/worker-agent-control-coordinator.d.ts +27 -8
- package/dist/core/delegation/worker-agent-control-coordinator.d.ts.map +1 -1
- package/dist/core/delegation/worker-agent-control-coordinator.js +191 -33
- package/dist/core/delegation/worker-agent-control-coordinator.js.map +1 -1
- package/dist/core/delegation/worker-agent-control.d.ts +45 -6
- package/dist/core/delegation/worker-agent-control.d.ts.map +1 -1
- package/dist/core/delegation/worker-agent-control.js +110 -13
- package/dist/core/delegation/worker-agent-control.js.map +1 -1
- package/dist/core/delegation/worker-attempt-executor.d.ts.map +1 -1
- package/dist/core/delegation/worker-attempt-executor.js +177 -158
- package/dist/core/delegation/worker-attempt-executor.js.map +1 -1
- package/dist/core/delegation/worker-authority-resolver.d.ts +23 -0
- package/dist/core/delegation/worker-authority-resolver.d.ts.map +1 -0
- package/dist/core/delegation/worker-authority-resolver.js +128 -0
- package/dist/core/delegation/worker-authority-resolver.js.map +1 -0
- package/dist/core/delegation/worker-conversation-store.d.ts.map +1 -1
- package/dist/core/delegation/worker-conversation-store.js +1 -1
- package/dist/core/delegation/worker-conversation-store.js.map +1 -1
- package/dist/core/delegation/worker-delegation-controller.d.ts +7 -1
- package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
- package/dist/core/delegation/worker-delegation-controller.js +260 -87
- package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
- package/dist/core/delegation/worker-delegation-request.d.ts +25 -4
- package/dist/core/delegation/worker-delegation-request.d.ts.map +1 -1
- package/dist/core/delegation/worker-delegation-request.js +90 -1
- package/dist/core/delegation/worker-delegation-request.js.map +1 -1
- package/dist/core/delegation/worker-execution-policy.d.ts +2 -0
- package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -1
- package/dist/core/delegation/worker-execution-policy.js +22 -12
- package/dist/core/delegation/worker-execution-policy.js.map +1 -1
- package/dist/core/delegation/worker-lifecycle.d.ts +1 -0
- package/dist/core/delegation/worker-lifecycle.d.ts.map +1 -1
- package/dist/core/delegation/worker-lifecycle.js +4 -2
- package/dist/core/delegation/worker-lifecycle.js.map +1 -1
- package/dist/core/delegation/worker-profile-resolver.d.ts +0 -2
- package/dist/core/delegation/worker-profile-resolver.d.ts.map +1 -1
- package/dist/core/delegation/worker-profile-resolver.js +8 -35
- package/dist/core/delegation/worker-profile-resolver.js.map +1 -1
- package/dist/core/delegation/worker-recovery-coordinator.d.ts.map +1 -1
- package/dist/core/delegation/worker-recovery-coordinator.js +1 -0
- package/dist/core/delegation/worker-recovery-coordinator.js.map +1 -1
- package/dist/core/delegation/worker-runner.d.ts +6 -1
- package/dist/core/delegation/worker-runner.d.ts.map +1 -1
- package/dist/core/delegation/worker-runner.js +20 -6
- package/dist/core/delegation/worker-runner.js.map +1 -1
- package/dist/core/delegation/worker-tree-budget-coordinator.d.ts +47 -0
- package/dist/core/delegation/worker-tree-budget-coordinator.d.ts.map +1 -0
- package/dist/core/delegation/worker-tree-budget-coordinator.js +210 -0
- package/dist/core/delegation/worker-tree-budget-coordinator.js.map +1 -0
- package/dist/core/memory/providers/file-store.d.ts +2 -0
- package/dist/core/memory/providers/file-store.d.ts.map +1 -1
- package/dist/core/memory/providers/file-store.js +22 -20
- package/dist/core/memory/providers/file-store.js.map +1 -1
- package/dist/core/models/runtime-process.d.ts.map +1 -1
- package/dist/core/models/runtime-process.js +5 -18
- package/dist/core/models/runtime-process.js.map +1 -1
- package/dist/core/orchestration/bounded-string-array.d.ts +11 -0
- package/dist/core/orchestration/bounded-string-array.d.ts.map +1 -0
- package/dist/core/orchestration/bounded-string-array.js +17 -0
- package/dist/core/orchestration/bounded-string-array.js.map +1 -0
- package/dist/core/orchestration/capability-gateway.d.ts +16 -0
- package/dist/core/orchestration/capability-gateway.d.ts.map +1 -1
- package/dist/core/orchestration/capability-gateway.js +38 -0
- package/dist/core/orchestration/capability-gateway.js.map +1 -1
- package/dist/core/orchestration/contracts.d.ts +11 -3
- package/dist/core/orchestration/contracts.d.ts.map +1 -1
- package/dist/core/orchestration/contracts.js +0 -1
- package/dist/core/orchestration/contracts.js.map +1 -1
- package/dist/core/orchestration/delegation-ledger.d.ts +1 -0
- package/dist/core/orchestration/delegation-ledger.d.ts.map +1 -1
- package/dist/core/orchestration/delegation-ledger.js +3 -0
- package/dist/core/orchestration/delegation-ledger.js.map +1 -1
- package/dist/core/orchestration/event-store.d.ts +12 -10
- package/dist/core/orchestration/event-store.d.ts.map +1 -1
- package/dist/core/orchestration/event-store.js +94 -104
- package/dist/core/orchestration/event-store.js.map +1 -1
- package/dist/core/orchestration/lane-tool-manifests.d.ts +2 -2
- package/dist/core/orchestration/lane-tool-manifests.d.ts.map +1 -1
- package/dist/core/orchestration/lane-tool-manifests.js +4 -1
- package/dist/core/orchestration/lane-tool-manifests.js.map +1 -1
- package/dist/core/orchestration/policy-compiler.d.ts.map +1 -1
- package/dist/core/orchestration/policy-compiler.js +8 -9
- package/dist/core/orchestration/policy-compiler.js.map +1 -1
- package/dist/core/orchestration/profile-registry.d.ts.map +1 -1
- package/dist/core/orchestration/profile-registry.js +4 -10
- package/dist/core/orchestration/profile-registry.js.map +1 -1
- package/dist/core/orchestration/task-runtime.d.ts +1 -0
- package/dist/core/orchestration/task-runtime.d.ts.map +1 -1
- package/dist/core/orchestration/task-runtime.js +58 -3
- package/dist/core/orchestration/task-runtime.js.map +1 -1
- package/dist/core/orchestration/worker-execution-contract.d.ts.map +1 -1
- package/dist/core/orchestration/worker-execution-contract.js +10 -17
- package/dist/core/orchestration/worker-execution-contract.js.map +1 -1
- package/dist/core/risk-classifier.js +3 -3
- package/dist/core/risk-classifier.js.map +1 -1
- package/dist/core/runtime-builder.d.ts +4 -1
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +34 -15
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/secrets/bitwarden-credential-storage.d.ts +51 -0
- package/dist/core/secrets/bitwarden-credential-storage.d.ts.map +1 -0
- package/dist/core/secrets/bitwarden-credential-storage.js +345 -0
- package/dist/core/secrets/bitwarden-credential-storage.js.map +1 -0
- package/dist/core/secrets/credential-exposure-guard.d.ts +8 -4
- package/dist/core/secrets/credential-exposure-guard.d.ts.map +1 -1
- package/dist/core/secrets/credential-exposure-guard.js +30 -31
- package/dist/core/secrets/credential-exposure-guard.js.map +1 -1
- package/dist/core/secrets/credential-manager.d.ts +109 -0
- package/dist/core/secrets/credential-manager.d.ts.map +1 -0
- package/dist/core/secrets/credential-manager.js +384 -0
- package/dist/core/secrets/credential-manager.js.map +1 -0
- package/dist/core/secrets/credential-project.d.ts +4 -0
- package/dist/core/secrets/credential-project.d.ts.map +1 -0
- package/dist/core/secrets/credential-project.js +145 -0
- package/dist/core/secrets/credential-project.js.map +1 -0
- package/dist/core/secrets/secret-dotenv.d.ts +1 -1
- package/dist/core/secrets/secret-dotenv.js +1 -1
- package/dist/core/secrets/secret-dotenv.js.map +1 -1
- package/dist/core/settings-manager.d.ts +4 -2
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +9 -5
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +1 -0
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/system-prompt.js +1 -1
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tool-capability-policy.js +2 -2
- package/dist/core/tool-capability-policy.js.map +1 -1
- package/dist/core/tools/delegate.d.ts +29 -1
- package/dist/core/tools/delegate.d.ts.map +1 -1
- package/dist/core/tools/delegate.js +179 -28
- package/dist/core/tools/delegate.js.map +1 -1
- package/dist/core/tools/git-filter.d.ts +1 -0
- package/dist/core/tools/git-filter.d.ts.map +1 -1
- package/dist/core/tools/git-filter.js +1 -1
- package/dist/core/tools/git-filter.js.map +1 -1
- package/dist/core/tools/profile-writer.js +3 -3
- package/dist/core/tools/profile-writer.js.map +1 -1
- package/dist/core/tools/python.d.ts +2 -0
- package/dist/core/tools/python.d.ts.map +1 -1
- package/dist/core/tools/python.js +17 -12
- package/dist/core/tools/python.js.map +1 -1
- package/dist/core/tools/run-process.d.ts +2 -0
- package/dist/core/tools/run-process.d.ts.map +1 -1
- package/dist/core/tools/run-process.js +7 -3
- package/dist/core/tools/run-process.js.map +1 -1
- package/dist/core/tools/secret-store.d.ts +8 -18
- package/dist/core/tools/secret-store.d.ts.map +1 -1
- package/dist/core/tools/secret-store.js +83 -348
- package/dist/core/tools/secret-store.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/migrations.d.ts.map +1 -1
- package/dist/migrations.js +38 -1
- package/dist/migrations.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +35 -14
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +26 -3
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/secret-menu-controller.d.ts +21 -0
- package/dist/modes/interactive/secret-menu-controller.d.ts.map +1 -0
- package/dist/modes/interactive/secret-menu-controller.js +276 -0
- package/dist/modes/interactive/secret-menu-controller.js.map +1 -0
- package/dist/utils/tools-manager.d.ts +2 -1
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +43 -48
- package/dist/utils/tools-manager.js.map +1 -1
- package/dist/utils/zip-extractor.d.ts +8 -0
- package/dist/utils/zip-extractor.d.ts.map +1 -0
- package/dist/utils/zip-extractor.js +275 -0
- package/dist/utils/zip-extractor.js.map +1 -0
- package/docs/harness-architecture.md +34 -22
- package/docs/index.md +1 -1
- package/docs/resources.md +1 -1
- package/docs/settings.md +39 -103
- package/docs/usage.md +7 -5
- package/docs/worker-profiles.md +9 -7
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
- package/dist/core/secrets/secret-vault-format.d.ts +0 -112
- package/dist/core/secrets/secret-vault-format.d.ts.map +0 -1
- package/dist/core/secrets/secret-vault-format.js +0 -396
- package/dist/core/secrets/secret-vault-format.js.map +0 -1
- package/dist/core/secrets/secret-vault.d.ts +0 -72
- package/dist/core/secrets/secret-vault.d.ts.map +0 -1
- package/dist/core/secrets/secret-vault.js +0 -663
- package/dist/core/secrets/secret-vault.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
import { existsSync, statSync, unlinkSync } from "node:fs";
|
|
2
|
+
import { existsSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { orchestrationEventStoreDir } from "../agent-paths.js";
|
|
5
5
|
import { withFileLockSync, writeFileAtomicSync } from "../util/atomic-file.js";
|
|
@@ -18,7 +18,6 @@ const MAX_IDEMPOTENCY_DIRECTORY_ENTRIES = 2_048;
|
|
|
18
18
|
const MAX_SNAPSHOT_DIRECTORY_ENTRIES = 8;
|
|
19
19
|
const MAX_CURSOR_BYTES = 64 * 1024;
|
|
20
20
|
const MAX_BASELINE_BYTES = 64 * 1024;
|
|
21
|
-
const MAX_IDEMPOTENCY_MARKER_BYTES = 64 * 1024;
|
|
22
21
|
/** Full current task state plus retained idempotency evidence; intentionally above the 16MiB tail cap. */
|
|
23
22
|
const MAX_PROJECTION_SNAPSHOT_BYTES = 32 * 1024 * 1024;
|
|
24
23
|
export class OrchestrationEventStoreError extends Error {
|
|
@@ -97,10 +96,13 @@ function positiveSafeInteger(value, fallback, maximum, label) {
|
|
|
97
96
|
return resolved;
|
|
98
97
|
}
|
|
99
98
|
/**
|
|
100
|
-
* Append-only event tail with a replaceable full-state projection snapshot.
|
|
101
|
-
*
|
|
102
|
-
*
|
|
103
|
-
*
|
|
99
|
+
* Append-only event tail with a replaceable full-state projection snapshot. Each immutable event is
|
|
100
|
+
* its own commit record: idempotency data is derived directly from the bounded tail, while a small
|
|
101
|
+
* mutable cursor remains only as a corruption high-water mark. Atomic rename prevents torn event
|
|
102
|
+
* records without multiplying one transition into per-key marker files and atomic cursor rewrites.
|
|
103
|
+
* Snapshot publication is two-phase (payload, then small baseline pointer), after which covered event
|
|
104
|
+
* and legacy-index files are pruned. A crash at any point leaves either the old replay prefix or the
|
|
105
|
+
* new verified snapshot authoritative; ordinals never reset.
|
|
104
106
|
*/
|
|
105
107
|
export class OrchestrationEventStore {
|
|
106
108
|
constructor(options) {
|
|
@@ -119,10 +121,10 @@ export class OrchestrationEventStore {
|
|
|
119
121
|
}
|
|
120
122
|
append(input, options = {}) {
|
|
121
123
|
const committed = withFileLockSync(this.cursorPath, () => {
|
|
122
|
-
const
|
|
123
|
-
const actual =
|
|
124
|
+
const indexes = this.synchronizeIndexesUnlocked();
|
|
125
|
+
const actual = indexes.lastOrdinal;
|
|
124
126
|
if (input.idempotencyKey) {
|
|
125
|
-
const existing =
|
|
127
|
+
const existing = indexes.idempotencyEvents.get(input.idempotencyKey);
|
|
126
128
|
if (existing)
|
|
127
129
|
return { event: existing, appended: false };
|
|
128
130
|
}
|
|
@@ -146,19 +148,17 @@ export class OrchestrationEventStore {
|
|
|
146
148
|
payload: structuredClone(input.payload),
|
|
147
149
|
};
|
|
148
150
|
const serializedEvent = serializeBounded(next, this.maxTailBytes, "Orchestration event", "Orchestration event exceeds its configured tail byte limit.");
|
|
149
|
-
const
|
|
150
|
-
|
|
151
|
-
: undefined;
|
|
152
|
-
const serializedCursor = serializeBounded({
|
|
153
|
-
version: 1,
|
|
154
|
-
lastOrdinal: ordinal,
|
|
155
|
-
tailBytes: cursor.tailBytes + Buffer.byteLength(serializedEvent),
|
|
156
|
-
}, MAX_CURSOR_BYTES, "Orchestration cursor");
|
|
151
|
+
const nextTailBytes = indexes.tailBytes + Buffer.byteLength(serializedEvent);
|
|
152
|
+
const serializedCursor = serializeBounded({ version: 1, lastOrdinal: ordinal, tailBytes: nextTailBytes }, MAX_CURSOR_BYTES, "Orchestration cursor");
|
|
157
153
|
writeFileAtomicSync(join(this.eventsDir, eventFileName(ordinal)), serializedEvent);
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
154
|
+
indexes.lastOrdinal = ordinal;
|
|
155
|
+
indexes.tailBytes = nextTailBytes;
|
|
156
|
+
if (input.idempotencyKey)
|
|
157
|
+
indexes.idempotencyEvents.set(input.idempotencyKey, next);
|
|
158
|
+
// The immutable event is authoritative. The cursor is only a corruption high-water mark,
|
|
159
|
+
// so a lock-protected direct overwrite avoids another tmp-file creation and rename on the
|
|
160
|
+
// Windows scanner-sensitive path; a torn cursor is safely rebuilt from the event tail.
|
|
161
|
+
writeFileSync(this.cursorPath, serializedCursor, "utf-8");
|
|
162
162
|
return { event: next, appended: true };
|
|
163
163
|
});
|
|
164
164
|
if (committed.appended) {
|
|
@@ -203,11 +203,21 @@ export class OrchestrationEventStore {
|
|
|
203
203
|
}
|
|
204
204
|
/** Replace a large replay prefix with one verified current-state snapshot and a bounded tail. */
|
|
205
205
|
compactIfNeeded(throughOrdinal, projection) {
|
|
206
|
-
const baselineBeforeLock = this.readBaselineUnlocked()
|
|
206
|
+
const baselineBeforeLock = this.readBaselineUnlocked();
|
|
207
|
+
const baselineOrdinalBeforeLock = baselineBeforeLock?.throughOrdinal ?? 0;
|
|
208
|
+
const cachedIndexes = this.synchronizedIndexes;
|
|
209
|
+
if (cachedIndexes?.baselineOrdinal === baselineOrdinalBeforeLock &&
|
|
210
|
+
cachedIndexes.baselineDigest === baselineBeforeLock?.digest &&
|
|
211
|
+
cachedIndexes.lastOrdinal === throughOrdinal &&
|
|
212
|
+
throughOrdinal - baselineOrdinalBeforeLock < this.maxTailEvents &&
|
|
213
|
+
cachedIndexes.tailBytes < this.maxTailBytes) {
|
|
214
|
+
return false;
|
|
215
|
+
}
|
|
207
216
|
const cursorBeforeLock = parseCursor(this.cursorPath);
|
|
208
|
-
if (
|
|
217
|
+
if (!cachedIndexes &&
|
|
218
|
+
cursorBeforeLock?.lastOrdinal === throughOrdinal &&
|
|
209
219
|
cursorBeforeLock.tailBytes !== undefined &&
|
|
210
|
-
throughOrdinal -
|
|
220
|
+
throughOrdinal - baselineOrdinalBeforeLock < this.maxTailEvents &&
|
|
211
221
|
cursorBeforeLock.tailBytes < this.maxTailBytes) {
|
|
212
222
|
return false;
|
|
213
223
|
}
|
|
@@ -262,6 +272,14 @@ export class OrchestrationEventStore {
|
|
|
262
272
|
this.unlinkManagedFile(join(this.snapshotsDir, name));
|
|
263
273
|
}
|
|
264
274
|
writeFileAtomicSync(this.cursorPath, serializedCursor);
|
|
275
|
+
this.verifiedSnapshotBaseline = undefined;
|
|
276
|
+
this.synchronizedIndexes = {
|
|
277
|
+
baselineOrdinal: throughOrdinal,
|
|
278
|
+
baselineDigest: digest,
|
|
279
|
+
lastOrdinal: throughOrdinal,
|
|
280
|
+
tailBytes: 0,
|
|
281
|
+
idempotencyEvents: new Map(idempotencyEvents.map((event) => [event.idempotencyKey, structuredClone(event)])),
|
|
282
|
+
};
|
|
265
283
|
return true;
|
|
266
284
|
});
|
|
267
285
|
}
|
|
@@ -445,17 +463,24 @@ export class OrchestrationEventStore {
|
|
|
445
463
|
cached.signature.size === signature.size &&
|
|
446
464
|
cached.signature.mtimeMs === signature.mtimeMs &&
|
|
447
465
|
cached.signature.ctimeMs === signature.ctimeMs) {
|
|
448
|
-
return
|
|
466
|
+
return cached;
|
|
467
|
+
}
|
|
468
|
+
const snapshot = this.readProjectionSnapshotUnlocked();
|
|
469
|
+
if (!snapshot) {
|
|
470
|
+
throw new OrchestrationEventStoreError("Orchestration projection snapshot is unavailable.");
|
|
449
471
|
}
|
|
450
|
-
this.readProjectionSnapshotUnlocked();
|
|
451
472
|
const verifiedSignature = this.snapshotFileSignatureUnlocked(baseline);
|
|
452
473
|
if (verifiedSignature.size !== signature.size ||
|
|
453
474
|
verifiedSignature.mtimeMs !== signature.mtimeMs ||
|
|
454
475
|
verifiedSignature.ctimeMs !== signature.ctimeMs) {
|
|
455
476
|
throw new OrchestrationEventStoreError("Orchestration projection snapshot changed while being verified.");
|
|
456
477
|
}
|
|
457
|
-
this.verifiedSnapshotBaseline = {
|
|
458
|
-
|
|
478
|
+
this.verifiedSnapshotBaseline = {
|
|
479
|
+
baseline,
|
|
480
|
+
signature,
|
|
481
|
+
idempotencyEvents: snapshot.idempotencyEvents.map((event) => structuredClone(event)),
|
|
482
|
+
};
|
|
483
|
+
return this.verifiedSnapshotBaseline;
|
|
459
484
|
}
|
|
460
485
|
snapshotFileSignatureUnlocked(baseline) {
|
|
461
486
|
try {
|
|
@@ -492,96 +517,61 @@ export class OrchestrationEventStore {
|
|
|
492
517
|
}
|
|
493
518
|
return parsed;
|
|
494
519
|
}
|
|
495
|
-
idempotencyPath(key) {
|
|
496
|
-
return join(this.idempotencyDir, `${createHash("sha256").update(key).digest("hex")}.json`);
|
|
497
|
-
}
|
|
498
|
-
serializeIdempotencyMarker(key, ordinal) {
|
|
499
|
-
return serializeBounded({ version: 1, key, ordinal }, MAX_IDEMPOTENCY_MARKER_BYTES, "Orchestration idempotency marker");
|
|
500
|
-
}
|
|
501
|
-
writeIdempotencyMarkerUnlocked(key, serializedMarker) {
|
|
502
|
-
writeFileAtomicSync(this.idempotencyPath(key), serializedMarker);
|
|
503
|
-
}
|
|
504
|
-
readIdempotentEventUnlocked(key) {
|
|
505
|
-
const markerPath = this.idempotencyPath(key);
|
|
506
|
-
if (!existsSync(markerPath)) {
|
|
507
|
-
return this.readProjectionSnapshotUnlocked()?.idempotencyEvents.find((event) => event.idempotencyKey === key);
|
|
508
|
-
}
|
|
509
|
-
let parsed;
|
|
510
|
-
try {
|
|
511
|
-
parsed = JSON.parse(readBoundedTextFileSync(markerPath, MAX_IDEMPOTENCY_MARKER_BYTES, "Orchestration idempotency marker"));
|
|
512
|
-
}
|
|
513
|
-
catch (error) {
|
|
514
|
-
throw new OrchestrationEventStoreError(`Failed to parse orchestration idempotency marker: ${error instanceof Error ? error.message : String(error)}`);
|
|
515
|
-
}
|
|
516
|
-
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
517
|
-
throw new OrchestrationEventStoreError("Invalid orchestration idempotency marker.");
|
|
518
|
-
}
|
|
519
|
-
const marker = parsed;
|
|
520
|
-
if (marker.version !== 1 ||
|
|
521
|
-
marker.key !== key ||
|
|
522
|
-
!Number.isSafeInteger(marker.ordinal) ||
|
|
523
|
-
Number(marker.ordinal) < 1) {
|
|
524
|
-
throw new OrchestrationEventStoreError("Invalid orchestration idempotency marker.");
|
|
525
|
-
}
|
|
526
|
-
const ordinal = Number(marker.ordinal);
|
|
527
|
-
if (!existsSync(join(this.eventsDir, eventFileName(ordinal)))) {
|
|
528
|
-
const retained = this.readProjectionSnapshotUnlocked()?.idempotencyEvents.find((event) => event.idempotencyKey === key && event.ordinal === ordinal);
|
|
529
|
-
if (retained)
|
|
530
|
-
return retained;
|
|
531
|
-
}
|
|
532
|
-
const event = this.readEventFileUnlocked(eventFileName(ordinal));
|
|
533
|
-
if (event.ordinal !== ordinal || event.idempotencyKey !== key) {
|
|
534
|
-
throw new OrchestrationEventStoreError("Orchestration idempotency marker does not match its event.");
|
|
535
|
-
}
|
|
536
|
-
return event;
|
|
537
|
-
}
|
|
538
520
|
/**
|
|
539
|
-
* Reconcile
|
|
540
|
-
*
|
|
521
|
+
* Reconcile the bounded immutable tail into an in-memory index. Independent writers are detected
|
|
522
|
+
* from new ordinals while holding the shared lock, so normal same-process appends parse only events
|
|
523
|
+
* committed by other writers. A bounded mutable cursor remains derived corruption evidence; legacy
|
|
524
|
+
* per-key marker files are no longer needed or rewritten.
|
|
541
525
|
*/
|
|
542
526
|
synchronizeIndexesUnlocked() {
|
|
543
527
|
const names = this.eventFileNamesUnlocked();
|
|
544
|
-
const
|
|
528
|
+
const verifiedBaseline = this.readVerifiedSnapshotBaselineUnlocked();
|
|
529
|
+
const baselineOrdinal = verifiedBaseline?.baseline.throughOrdinal ?? 0;
|
|
530
|
+
const baselineDigest = verifiedBaseline?.baseline.digest;
|
|
545
531
|
this.assertReadableTailUnlocked(names, baselineOrdinal);
|
|
546
532
|
const highestEventOrdinal = names.length > 0 ? Number(EVENT_FILE_PATTERN.exec(names.at(-1))?.[1] ?? 0) : 0;
|
|
547
533
|
const highest = Math.max(baselineOrdinal, highestEventOrdinal);
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
534
|
+
if (this.synchronizedIndexes?.baselineOrdinal === baselineOrdinal &&
|
|
535
|
+
this.synchronizedIndexes.baselineDigest === baselineDigest &&
|
|
536
|
+
this.synchronizedIndexes.lastOrdinal > highest) {
|
|
537
|
+
throw new OrchestrationEventStoreError(`Orchestration cursor ${this.synchronizedIndexes.lastOrdinal} is ahead of the last committed event ${highest}.`);
|
|
538
|
+
}
|
|
539
|
+
const cached = this.synchronizedIndexes;
|
|
540
|
+
const canExtendCached = cached?.baselineOrdinal === baselineOrdinal &&
|
|
541
|
+
cached.baselineDigest === baselineDigest &&
|
|
542
|
+
cached.lastOrdinal >= baselineOrdinal &&
|
|
543
|
+
cached.lastOrdinal <= highest;
|
|
544
|
+
if (canExtendCached && cached.lastOrdinal === highest)
|
|
545
|
+
return cached;
|
|
546
|
+
const indexes = canExtendCached
|
|
547
|
+
? cached
|
|
548
|
+
: {
|
|
549
|
+
baselineOrdinal,
|
|
550
|
+
baselineDigest,
|
|
551
|
+
lastOrdinal: baselineOrdinal,
|
|
552
|
+
tailBytes: 0,
|
|
553
|
+
idempotencyEvents: new Map((verifiedBaseline?.idempotencyEvents ?? []).map((event) => [
|
|
554
|
+
event.idempotencyKey,
|
|
555
|
+
structuredClone(event),
|
|
556
|
+
])),
|
|
557
|
+
};
|
|
558
|
+
const scanFrom = indexes.lastOrdinal + 1;
|
|
560
559
|
for (const name of names) {
|
|
561
560
|
const ordinal = Number(EVENT_FILE_PATTERN.exec(name)?.[1] ?? 0);
|
|
562
|
-
if (ordinal <
|
|
561
|
+
if (ordinal < scanFrom || ordinal <= baselineOrdinal)
|
|
563
562
|
continue;
|
|
564
563
|
const event = this.readEventFileUnlocked(name);
|
|
565
564
|
if (event.ordinal !== ordinal) {
|
|
566
565
|
throw new OrchestrationEventStoreError(`Event ordinal does not match file name: ${name}`);
|
|
567
566
|
}
|
|
568
|
-
if (event.idempotencyKey)
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
try {
|
|
577
|
-
return total + statSync(join(this.eventsDir, name)).size;
|
|
578
|
-
}
|
|
579
|
-
catch {
|
|
580
|
-
return total;
|
|
581
|
-
}
|
|
582
|
-
}, 0);
|
|
583
|
-
writeFileAtomicSync(this.cursorPath, serializeBounded({ version: 1, lastOrdinal: highest, tailBytes }, MAX_CURSOR_BYTES, "Orchestration cursor"));
|
|
584
|
-
return { lastOrdinal: highest, tailBytes };
|
|
567
|
+
if (event.idempotencyKey)
|
|
568
|
+
indexes.idempotencyEvents.set(event.idempotencyKey, event);
|
|
569
|
+
indexes.tailBytes += statSync(join(this.eventsDir, name)).size;
|
|
570
|
+
indexes.lastOrdinal = ordinal;
|
|
571
|
+
}
|
|
572
|
+
indexes.lastOrdinal = highest;
|
|
573
|
+
this.synchronizedIndexes = indexes;
|
|
574
|
+
return indexes;
|
|
585
575
|
}
|
|
586
576
|
}
|
|
587
577
|
//# sourceMappingURL=event-store.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event-store.js","sourceRoot":"","sources":["../../../src/core/orchestration/event-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAC3D,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAE/D,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC/E,OAAO,EAAE,6BAA6B,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AACjG,OAAO,EAEN,oBAAoB,EACpB,4BAA4B,GAE5B,MAAM,gBAAgB,CAAC;AAExB,MAAM,kBAAkB,GAAG,kBAAkB,CAAC;AAC9C,MAAM,qBAAqB,GAAG,kBAAkB,CAAC;AACjD,MAAM,uBAAuB,GAAG,GAAG,CAAC;AACpC,MAAM,sBAAsB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AAC/C,MAAM,8BAA8B,GAAG,GAAG,CAAC;AAC3C,MAAM,0BAA0B,GAAG,KAAK,CAAC;AACzC,MAAM,yBAAyB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AACnD,MAAM,iCAAiC,GAAG,KAAK,CAAC;AAChD,MAAM,2BAA2B,GAAG,KAAK,CAAC;AAC1C,MAAM,iCAAiC,GAAG,KAAK,CAAC;AAChD,MAAM,8BAA8B,GAAG,CAAC,CAAC;AACzC,MAAM,gBAAgB,GAAG,EAAE,GAAG,IAAI,CAAC;AACnC,MAAM,kBAAkB,GAAG,EAAE,GAAG,IAAI,CAAC;AACrC,MAAM,4BAA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rE,gBAAgB,EAChB,sBAAsB,CACtB,CACD,CAAC;QACF,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;IAC5C,CAAC;CACD","sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport { existsSync, statSync, unlinkSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { orchestrationEventStoreDir } from \"../agent-paths.ts\";\nimport type { JsonObject } from \"../autonomy/contracts.ts\";\nimport { withFileLockSync, writeFileAtomicSync } from \"../util/atomic-file.ts\";\nimport { readBoundedDirectoryNamesSync, readBoundedTextFileSync } from \"../util/bounded-file.ts\";\nimport {\n\ttype AppendOrchestrationEventInput,\n\tisOrchestrationEvent,\n\tORCHESTRATION_SCHEMA_VERSION,\n\ttype OrchestrationEvent,\n} from \"./contracts.ts\";\n\nconst EVENT_FILE_PATTERN = /^(\\d{16})\\.json$/;\nconst SNAPSHOT_FILE_PATTERN = /^(\\d{16})\\.json$/;\nconst DEFAULT_MAX_TAIL_EVENTS = 256;\nconst DEFAULT_MAX_TAIL_BYTES = 4 * 1024 * 1024;\nconst DEFAULT_MAX_IDEMPOTENCY_EVENTS = 512;\nconst MAX_CONFIGURED_TAIL_EVENTS = 1_024;\nconst MAX_CONFIGURED_TAIL_BYTES = 16 * 1024 * 1024;\nconst MAX_CONFIGURED_IDEMPOTENCY_EVENTS = 1_024;\nconst MAX_EVENT_DIRECTORY_ENTRIES = 2_048;\nconst MAX_IDEMPOTENCY_DIRECTORY_ENTRIES = 2_048;\nconst MAX_SNAPSHOT_DIRECTORY_ENTRIES = 8;\nconst MAX_CURSOR_BYTES = 64 * 1024;\nconst MAX_BASELINE_BYTES = 64 * 1024;\nconst MAX_IDEMPOTENCY_MARKER_BYTES = 64 * 1024;\n/** Full current task state plus retained idempotency evidence; intentionally above the 16MiB tail cap. */\nconst MAX_PROJECTION_SNAPSHOT_BYTES = 32 * 1024 * 1024;\n\ninterface EventCursor {\n\tversion: 1;\n\tlastOrdinal: number;\n\ttailBytes?: number;\n}\n\ninterface SynchronizedIndexes {\n\tlastOrdinal: number;\n\ttailBytes: number;\n}\n\ninterface IdempotencyMarker {\n\tversion: 1;\n\tkey: string;\n\tordinal: number;\n}\n\ninterface ProjectionSnapshotContent {\n\tversion: 1;\n\tschemaVersion: typeof ORCHESTRATION_SCHEMA_VERSION;\n\tthroughOrdinal: number;\n\tcreatedAt: string;\n\tprojection: JsonObject;\n\tidempotencyEvents: OrchestrationEvent[];\n}\n\ninterface ProjectionSnapshot extends ProjectionSnapshotContent {\n\tdigest: string;\n}\n\ninterface SnapshotBaseline {\n\tversion: 1;\n\tthroughOrdinal: number;\n\tdigest: string;\n\tsnapshotFile: string;\n}\n\ninterface SnapshotFileSignature {\n\tsize: number;\n\tmtimeMs: number;\n\tctimeMs: number;\n}\n\ninterface VerifiedSnapshotBaseline {\n\tbaseline: SnapshotBaseline;\n\tsignature: SnapshotFileSignature;\n}\n\nexport interface OrchestrationEventStoreOptions {\n\tagentDir: string;\n\tsessionId: string;\n\tnow?: () => string;\n\tcreateEventId?: () => string;\n\tmaxTailEvents?: number;\n\tmaxTailBytes?: number;\n\tmaxIdempotencyEvents?: number;\n}\n\nexport class OrchestrationEventStoreError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"OrchestrationEventStoreError\";\n\t}\n}\n\nexport class OrchestrationConcurrencyError extends OrchestrationEventStoreError {\n\tconstructor(expected: number, actual: number) {\n\t\tsuper(`Orchestration event cursor changed: expected ${expected}, actual ${actual}.`);\n\t\tthis.name = \"OrchestrationConcurrencyError\";\n\t}\n}\n\nexport class OrchestrationSnapshotRequiredError extends OrchestrationEventStoreError {\n\treadonly throughOrdinal: number;\n\n\tconstructor(throughOrdinal: number) {\n\t\tsuper(`Orchestration projection snapshot through ordinal ${throughOrdinal} is required.`);\n\t\tthis.name = \"OrchestrationSnapshotRequiredError\";\n\t\tthis.throughOrdinal = throughOrdinal;\n\t}\n}\n\nfunction parseCursor(filePath: string): EventCursor | undefined {\n\tif (!existsSync(filePath)) return undefined;\n\tlet content: string;\n\ttry {\n\t\tcontent = readBoundedTextFileSync(filePath, MAX_CURSOR_BYTES, \"Orchestration cursor\");\n\t} catch (error) {\n\t\tthrow new OrchestrationEventStoreError(\n\t\t\t`Failed to read orchestration cursor: ${error instanceof Error ? error.message : String(error)}`,\n\t\t);\n\t}\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(content);\n\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return undefined;\n\t\tconst record = parsed as Record<string, unknown>;\n\t\tif (record.version !== 1 || !Number.isSafeInteger(record.lastOrdinal) || Number(record.lastOrdinal) < 0) {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (record.tailBytes !== undefined && (!Number.isSafeInteger(record.tailBytes) || Number(record.tailBytes) < 0)) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn {\n\t\t\tversion: 1,\n\t\t\tlastOrdinal: Number(record.lastOrdinal),\n\t\t\t...(record.tailBytes !== undefined ? { tailBytes: Number(record.tailBytes) } : {}),\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction serialize(value: unknown): string {\n\treturn `${JSON.stringify(value, null, \"\\t\")}\\n`;\n}\n\nfunction serializeBounded(\n\tvalue: unknown,\n\tmaxBytes: number,\n\tlabel: string,\n\toversizedMessage = `${label} exceeds its byte limit.`,\n): string {\n\tconst serialized = serialize(value);\n\tif (Buffer.byteLength(serialized, \"utf-8\") > maxBytes) {\n\t\tthrow new OrchestrationEventStoreError(oversizedMessage);\n\t}\n\treturn serialized;\n}\n\nfunction eventFileName(ordinal: number): string {\n\treturn `${String(ordinal).padStart(16, \"0\")}.json`;\n}\n\nfunction snapshotDigest(content: ProjectionSnapshotContent): string {\n\treturn createHash(\"sha256\").update(JSON.stringify(content)).digest(\"hex\");\n}\n\nfunction positiveSafeInteger(value: number | undefined, fallback: number, maximum: number, label: string): number {\n\tconst resolved = value ?? fallback;\n\tif (!Number.isSafeInteger(resolved) || resolved < 1) {\n\t\tthrow new OrchestrationEventStoreError(`${label} must be a positive safe integer.`);\n\t}\n\tif (resolved > maximum) throw new OrchestrationEventStoreError(`${label} must not exceed ${maximum}.`);\n\treturn resolved;\n}\n\n/**\n * Append-only event tail with a replaceable full-state projection snapshot. Atomic rename prevents\n * torn records. Snapshot publication is two-phase (payload, then small baseline pointer), after which\n * covered event/idempotency files are pruned. A crash at any point leaves either the old replay prefix\n * or the new verified snapshot authoritative; ordinals never reset.\n */\nexport class OrchestrationEventStore {\n\treadonly rootDir: string;\n\treadonly eventsDir: string;\n\treadonly idempotencyDir: string;\n\treadonly cursorPath: string;\n\treadonly snapshotsDir: string;\n\treadonly baselinePath: string;\n\tprivate readonly now: () => string;\n\tprivate readonly createEventId: () => string;\n\tprivate readonly maxTailEvents: number;\n\tprivate readonly maxTailBytes: number;\n\tprivate readonly maxIdempotencyEvents: number;\n\tprivate readonly listeners = new Set<(event: OrchestrationEvent) => void>();\n\tprivate verifiedSnapshotBaseline: VerifiedSnapshotBaseline | undefined;\n\n\tconstructor(options: OrchestrationEventStoreOptions) {\n\t\tthis.rootDir = orchestrationEventStoreDir(options.agentDir, options.sessionId);\n\t\tthis.eventsDir = join(this.rootDir, \"events\");\n\t\tthis.idempotencyDir = join(this.rootDir, \"idempotency\");\n\t\tthis.cursorPath = join(this.rootDir, \"cursor.json\");\n\t\tthis.snapshotsDir = join(this.rootDir, \"snapshots\");\n\t\tthis.baselinePath = join(this.rootDir, \"projection-baseline.json\");\n\t\tthis.now = options.now ?? (() => new Date().toISOString());\n\t\tthis.createEventId = options.createEventId ?? randomUUID;\n\t\tthis.maxTailEvents = positiveSafeInteger(\n\t\t\toptions.maxTailEvents,\n\t\t\tDEFAULT_MAX_TAIL_EVENTS,\n\t\t\tMAX_CONFIGURED_TAIL_EVENTS,\n\t\t\t\"maxTailEvents\",\n\t\t);\n\t\tthis.maxTailBytes = positiveSafeInteger(\n\t\t\toptions.maxTailBytes,\n\t\t\tDEFAULT_MAX_TAIL_BYTES,\n\t\t\tMAX_CONFIGURED_TAIL_BYTES,\n\t\t\t\"maxTailBytes\",\n\t\t);\n\t\tthis.maxIdempotencyEvents = positiveSafeInteger(\n\t\t\toptions.maxIdempotencyEvents,\n\t\t\tDEFAULT_MAX_IDEMPOTENCY_EVENTS,\n\t\t\tMAX_CONFIGURED_IDEMPOTENCY_EVENTS,\n\t\t\t\"maxIdempotencyEvents\",\n\t\t);\n\t}\n\n\tappend(input: AppendOrchestrationEventInput, options: { expectedLastOrdinal?: number } = {}): OrchestrationEvent {\n\t\tconst committed = withFileLockSync(this.cursorPath, (): { event: OrchestrationEvent; appended: boolean } => {\n\t\t\tconst cursor = this.synchronizeIndexesUnlocked();\n\t\t\tconst actual = cursor.lastOrdinal;\n\t\t\tif (input.idempotencyKey) {\n\t\t\t\tconst existing = this.readIdempotentEventUnlocked(input.idempotencyKey);\n\t\t\t\tif (existing) return { event: existing, appended: false };\n\t\t\t}\n\t\t\tif (options.expectedLastOrdinal !== undefined) {\n\t\t\t\tif (actual !== options.expectedLastOrdinal) {\n\t\t\t\t\tthrow new OrchestrationConcurrencyError(options.expectedLastOrdinal, actual);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst ordinal = actual + 1;\n\t\t\tconst next: OrchestrationEvent = {\n\t\t\t\tschemaVersion: ORCHESTRATION_SCHEMA_VERSION,\n\t\t\t\tordinal,\n\t\t\t\teventId: this.createEventId(),\n\t\t\t\ttype: input.type,\n\t\t\t\taggregateId: input.aggregateId,\n\t\t\t\tactor: input.actor,\n\t\t\t\toccurredAt: this.now(),\n\t\t\t\t...(input.correlationId ? { correlationId: input.correlationId } : {}),\n\t\t\t\t...(input.causationId ? { causationId: input.causationId } : {}),\n\t\t\t\t...(input.idempotencyKey ? { idempotencyKey: input.idempotencyKey } : {}),\n\t\t\t\tpayload: structuredClone(input.payload),\n\t\t\t};\n\t\t\tconst serializedEvent = serializeBounded(\n\t\t\t\tnext,\n\t\t\t\tthis.maxTailBytes,\n\t\t\t\t\"Orchestration event\",\n\t\t\t\t\"Orchestration event exceeds its configured tail byte limit.\",\n\t\t\t);\n\t\t\tconst serializedMarker = input.idempotencyKey\n\t\t\t\t? this.serializeIdempotencyMarker(input.idempotencyKey, ordinal)\n\t\t\t\t: undefined;\n\t\t\tconst serializedCursor = serializeBounded(\n\t\t\t\t{\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tlastOrdinal: ordinal,\n\t\t\t\t\ttailBytes: cursor.tailBytes + Buffer.byteLength(serializedEvent),\n\t\t\t\t} satisfies EventCursor,\n\t\t\t\tMAX_CURSOR_BYTES,\n\t\t\t\t\"Orchestration cursor\",\n\t\t\t);\n\t\t\twriteFileAtomicSync(join(this.eventsDir, eventFileName(ordinal)), serializedEvent);\n\t\t\tif (input.idempotencyKey && serializedMarker) {\n\t\t\t\tthis.writeIdempotencyMarkerUnlocked(input.idempotencyKey, serializedMarker);\n\t\t\t}\n\t\t\twriteFileAtomicSync(this.cursorPath, serializedCursor);\n\t\t\treturn { event: next, appended: true };\n\t\t});\n\n\t\tif (committed.appended) {\n\t\t\tfor (const listener of this.listeners) listener(structuredClone(committed.event));\n\t\t}\n\t\treturn structuredClone(committed.event);\n\t}\n\n\treadAll(): OrchestrationEvent[] {\n\t\treturn this.readAllUnlocked();\n\t}\n\n\treadAfter(ordinal: number): OrchestrationEvent[] {\n\t\tconst baseline = this.readBaselineUnlocked();\n\t\tif (baseline && ordinal < baseline.throughOrdinal) {\n\t\t\tthrow new OrchestrationSnapshotRequiredError(baseline.throughOrdinal);\n\t\t}\n\t\tconst events: OrchestrationEvent[] = [];\n\t\tconst names = this.eventFileNamesUnlocked();\n\t\tthis.assertReadableTailUnlocked(names, baseline?.throughOrdinal ?? 0);\n\t\tlet previousOrdinal = ordinal;\n\t\tfor (const name of names) {\n\t\t\tconst match = EVENT_FILE_PATTERN.exec(name);\n\t\t\tif (!match) continue;\n\t\t\tconst fileOrdinal = Number(match[1]);\n\t\t\tif (fileOrdinal <= ordinal) continue;\n\t\t\tconst event = this.readEventFileUnlocked(name);\n\t\t\tif (event.ordinal !== fileOrdinal || event.ordinal <= previousOrdinal) {\n\t\t\t\tthrow new OrchestrationEventStoreError(`Non-monotonic orchestration event ordinal in ${name}`);\n\t\t\t}\n\t\t\tpreviousOrdinal = event.ordinal;\n\t\t\tevents.push(structuredClone(event));\n\t\t}\n\t\treturn events;\n\t}\n\n\treadProjectionSnapshot(): { throughOrdinal: number; projection: JsonObject } | undefined {\n\t\tconst snapshot = this.readProjectionSnapshotUnlocked();\n\t\treturn snapshot\n\t\t\t? { throughOrdinal: snapshot.throughOrdinal, projection: structuredClone(snapshot.projection) }\n\t\t\t: undefined;\n\t}\n\n\t/** Replace a large replay prefix with one verified current-state snapshot and a bounded tail. */\n\tcompactIfNeeded(throughOrdinal: number, projection: () => JsonObject): boolean {\n\t\tconst baselineBeforeLock = this.readBaselineUnlocked()?.throughOrdinal ?? 0;\n\t\tconst cursorBeforeLock = parseCursor(this.cursorPath);\n\t\tif (\n\t\t\tcursorBeforeLock?.lastOrdinal === throughOrdinal &&\n\t\t\tcursorBeforeLock.tailBytes !== undefined &&\n\t\t\tthroughOrdinal - baselineBeforeLock < this.maxTailEvents &&\n\t\t\tcursorBeforeLock.tailBytes < this.maxTailBytes\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\treturn withFileLockSync(this.cursorPath, () => {\n\t\t\tconst cursor = this.synchronizeIndexesUnlocked();\n\t\t\tif (cursor.lastOrdinal !== throughOrdinal) return false;\n\t\t\tconst baselineOrdinal = this.readBaselineUnlocked()?.throughOrdinal ?? 0;\n\t\t\tconst tailNames = this.eventFileNamesUnlocked().filter(\n\t\t\t\t(name) => Number(EVENT_FILE_PATTERN.exec(name)?.[1] ?? 0) > baselineOrdinal,\n\t\t\t);\n\t\t\tif (tailNames.length < this.maxTailEvents && cursor.tailBytes < this.maxTailBytes) return false;\n\n\t\t\tconst retainedByKey = new Map<string, OrchestrationEvent>();\n\t\t\tfor (const event of this.readProjectionSnapshotUnlocked()?.idempotencyEvents ?? []) {\n\t\t\t\tif (event.idempotencyKey) retainedByKey.set(event.idempotencyKey, event);\n\t\t\t}\n\t\t\tfor (const name of tailNames) {\n\t\t\t\tconst event = this.readEventFileUnlocked(name);\n\t\t\t\tif (event.ordinal <= throughOrdinal && event.idempotencyKey) {\n\t\t\t\t\tretainedByKey.set(event.idempotencyKey, event);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst idempotencyEvents = [...retainedByKey.values()]\n\t\t\t\t.sort((left, right) => left.ordinal - right.ordinal)\n\t\t\t\t.slice(-this.maxIdempotencyEvents)\n\t\t\t\t.map((event) => structuredClone(event));\n\t\t\tconst content: ProjectionSnapshotContent = {\n\t\t\t\tversion: 1,\n\t\t\t\tschemaVersion: ORCHESTRATION_SCHEMA_VERSION,\n\t\t\t\tthroughOrdinal,\n\t\t\t\tcreatedAt: this.now(),\n\t\t\t\tprojection: structuredClone(projection()),\n\t\t\t\tidempotencyEvents,\n\t\t\t};\n\t\t\tconst digest = snapshotDigest(content);\n\t\t\tconst snapshotFile = eventFileName(throughOrdinal);\n\t\t\tconst serializedSnapshot = serializeBounded(\n\t\t\t\t{ ...content, digest } satisfies ProjectionSnapshot,\n\t\t\t\tMAX_PROJECTION_SNAPSHOT_BYTES,\n\t\t\t\t\"Orchestration projection snapshot\",\n\t\t\t);\n\t\t\tconst serializedBaseline = serializeBounded(\n\t\t\t\t{ version: 1, throughOrdinal, digest, snapshotFile } satisfies SnapshotBaseline,\n\t\t\t\tMAX_BASELINE_BYTES,\n\t\t\t\t\"Orchestration snapshot baseline\",\n\t\t\t);\n\t\t\tconst serializedCursor = serializeBounded(\n\t\t\t\t{ version: 1, lastOrdinal: throughOrdinal, tailBytes: 0 } satisfies EventCursor,\n\t\t\t\tMAX_CURSOR_BYTES,\n\t\t\t\t\"Orchestration cursor\",\n\t\t\t);\n\t\t\twriteFileAtomicSync(join(this.snapshotsDir, snapshotFile), serializedSnapshot);\n\t\t\twriteFileAtomicSync(this.baselinePath, serializedBaseline);\n\n\t\t\tfor (const name of this.idempotencyFileNamesUnlocked()) {\n\t\t\t\tthis.unlinkManagedFile(join(this.idempotencyDir, name));\n\t\t\t}\n\t\t\tfor (const name of this.eventFileNamesUnlocked()) {\n\t\t\t\tconst ordinal = Number(EVENT_FILE_PATTERN.exec(name)?.[1] ?? 0);\n\t\t\t\tif (ordinal <= throughOrdinal) this.unlinkManagedFile(join(this.eventsDir, name));\n\t\t\t}\n\t\t\tfor (const name of this.snapshotFileNamesUnlocked()) {\n\t\t\t\tif (name !== snapshotFile) this.unlinkManagedFile(join(this.snapshotsDir, name));\n\t\t\t}\n\t\t\twriteFileAtomicSync(this.cursorPath, serializedCursor);\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tsubscribe(listener: (event: OrchestrationEvent) => void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\tprivate readAllUnlocked(): OrchestrationEvent[] {\n\t\tconst names = this.eventFileNamesUnlocked();\n\t\tconst events: OrchestrationEvent[] = [];\n\t\tconst baselineOrdinal = this.readProjectionSnapshotUnlocked()?.throughOrdinal ?? 0;\n\t\tthis.assertReadableTailUnlocked(names, baselineOrdinal);\n\t\tlet previousOrdinal = baselineOrdinal;\n\t\tfor (const name of names) {\n\t\t\tconst match = EVENT_FILE_PATTERN.exec(name);\n\t\t\tif (!match) continue;\n\t\t\tconst fileOrdinal = Number(match[1]);\n\t\t\tif (fileOrdinal <= baselineOrdinal) continue;\n\t\t\tconst parsed = this.readEventFileUnlocked(name);\n\t\t\tif (parsed.ordinal !== fileOrdinal || parsed.ordinal <= previousOrdinal) {\n\t\t\t\tthrow new OrchestrationEventStoreError(`Non-monotonic orchestration event ordinal in ${name}`);\n\t\t\t}\n\t\t\tpreviousOrdinal = parsed.ordinal;\n\t\t\tevents.push(structuredClone(parsed));\n\t\t}\n\t\treturn events;\n\t}\n\n\tprivate eventFileNamesUnlocked(): string[] {\n\t\ttry {\n\t\t\treturn readBoundedDirectoryNamesSync(\n\t\t\t\tthis.eventsDir,\n\t\t\t\tMAX_EVENT_DIRECTORY_ENTRIES,\n\t\t\t\t\"Orchestration events directory\",\n\t\t\t)\n\t\t\t\t.filter((candidate) => EVENT_FILE_PATTERN.test(candidate))\n\t\t\t\t.sort();\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate idempotencyFileNamesUnlocked(): string[] {\n\t\ttry {\n\t\t\treturn readBoundedDirectoryNamesSync(\n\t\t\t\tthis.idempotencyDir,\n\t\t\t\tMAX_IDEMPOTENCY_DIRECTORY_ENTRIES,\n\t\t\t\t\"Orchestration idempotency directory\",\n\t\t\t).filter((candidate) => candidate.endsWith(\".json\"));\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate snapshotFileNamesUnlocked(): string[] {\n\t\ttry {\n\t\t\treturn readBoundedDirectoryNamesSync(\n\t\t\t\tthis.snapshotsDir,\n\t\t\t\tMAX_SNAPSHOT_DIRECTORY_ENTRIES,\n\t\t\t\t\"Orchestration snapshots directory\",\n\t\t\t)\n\t\t\t\t.filter((candidate) => SNAPSHOT_FILE_PATTERN.test(candidate))\n\t\t\t\t.sort();\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/** Event files are a contiguous append-only tail after the published snapshot. */\n\tprivate assertContiguousTailOrdinalsUnlocked(names: readonly string[], baselineOrdinal: number): void {\n\t\tlet expectedOrdinal = baselineOrdinal + 1;\n\t\tfor (const name of names) {\n\t\t\tconst ordinal = Number(EVENT_FILE_PATTERN.exec(name)?.[1] ?? 0);\n\t\t\t// A crash after publishing the baseline but before pruning is safe: the snapshot covers these files.\n\t\t\tif (ordinal <= baselineOrdinal) continue;\n\t\t\tif (ordinal !== expectedOrdinal) {\n\t\t\t\tthrow new OrchestrationEventStoreError(\n\t\t\t\t\t`Missing orchestration event ordinal ${expectedOrdinal} before ${name}.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\texpectedOrdinal++;\n\t\t}\n\t}\n\n\t/** A valid cursor may lag a newly published snapshot, but it must never lead its committed tail. */\n\tprivate assertReadableTailUnlocked(names: readonly string[], baselineOrdinal: number): void {\n\t\tthis.assertContiguousTailOrdinalsUnlocked(names, baselineOrdinal);\n\t\tconst highestEventOrdinal = names.length > 0 ? Number(EVENT_FILE_PATTERN.exec(names.at(-1)!)?.[1] ?? 0) : 0;\n\t\tconst highestCommittedOrdinal = Math.max(baselineOrdinal, highestEventOrdinal);\n\t\tconst cursor = parseCursor(this.cursorPath);\n\t\tif (cursor && cursor.lastOrdinal > highestCommittedOrdinal) {\n\t\t\tthrow new OrchestrationEventStoreError(\n\t\t\t\t`Orchestration cursor ${cursor.lastOrdinal} is ahead of the last committed event ${highestCommittedOrdinal}.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate readBaselineUnlocked(): SnapshotBaseline | undefined {\n\t\tif (!existsSync(this.baselinePath)) return undefined;\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(\n\t\t\t\treadBoundedTextFileSync(this.baselinePath, MAX_BASELINE_BYTES, \"Orchestration snapshot baseline\"),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow new OrchestrationEventStoreError(\n\t\t\t\t`Failed to parse orchestration snapshot baseline: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n\t\t\tthrow new OrchestrationEventStoreError(\"Invalid orchestration snapshot baseline.\");\n\t\t}\n\t\tconst baseline = parsed as Record<string, unknown>;\n\t\tif (\n\t\t\tbaseline.version !== 1 ||\n\t\t\t!Number.isSafeInteger(baseline.throughOrdinal) ||\n\t\t\tNumber(baseline.throughOrdinal) < 1 ||\n\t\t\ttypeof baseline.digest !== \"string\" ||\n\t\t\tbaseline.digest.length === 0 ||\n\t\t\ttypeof baseline.snapshotFile !== \"string\" ||\n\t\t\t!SNAPSHOT_FILE_PATTERN.test(baseline.snapshotFile) ||\n\t\t\tNumber(SNAPSHOT_FILE_PATTERN.exec(baseline.snapshotFile)?.[1] ?? 0) !== Number(baseline.throughOrdinal)\n\t\t) {\n\t\t\tthrow new OrchestrationEventStoreError(\"Invalid orchestration snapshot baseline.\");\n\t\t}\n\t\treturn {\n\t\t\tversion: 1,\n\t\t\tthroughOrdinal: Number(baseline.throughOrdinal),\n\t\t\tdigest: baseline.digest,\n\t\t\tsnapshotFile: baseline.snapshotFile,\n\t\t};\n\t}\n\n\tprivate readProjectionSnapshotUnlocked(): ProjectionSnapshot | undefined {\n\t\tconst baseline = this.readBaselineUnlocked();\n\t\tif (!baseline) return undefined;\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(\n\t\t\t\treadBoundedTextFileSync(\n\t\t\t\t\tjoin(this.snapshotsDir, baseline.snapshotFile),\n\t\t\t\t\tMAX_PROJECTION_SNAPSHOT_BYTES,\n\t\t\t\t\t\"Orchestration projection snapshot\",\n\t\t\t\t),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow new OrchestrationEventStoreError(\n\t\t\t\t`Failed to parse orchestration projection snapshot: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n\t\t\tthrow new OrchestrationEventStoreError(\"Invalid orchestration projection snapshot.\");\n\t\t}\n\t\tconst snapshot = parsed as Record<string, unknown>;\n\t\tif (\n\t\t\tsnapshot.version !== 1 ||\n\t\t\tsnapshot.schemaVersion !== ORCHESTRATION_SCHEMA_VERSION ||\n\t\t\tsnapshot.throughOrdinal !== baseline.throughOrdinal ||\n\t\t\ttypeof snapshot.createdAt !== \"string\" ||\n\t\t\t!snapshot.projection ||\n\t\t\ttypeof snapshot.projection !== \"object\" ||\n\t\t\tArray.isArray(snapshot.projection) ||\n\t\t\t!Array.isArray(snapshot.idempotencyEvents) ||\n\t\t\tsnapshot.idempotencyEvents.length > this.maxIdempotencyEvents ||\n\t\t\t!snapshot.idempotencyEvents.every(isOrchestrationEvent) ||\n\t\t\t!snapshot.idempotencyEvents.every(\n\t\t\t\t(event) => event.ordinal <= baseline.throughOrdinal && event.idempotencyKey !== undefined,\n\t\t\t) ||\n\t\t\tnew Set(snapshot.idempotencyEvents.map((event) => event.idempotencyKey)).size !==\n\t\t\t\tsnapshot.idempotencyEvents.length ||\n\t\t\ttypeof snapshot.digest !== \"string\" ||\n\t\t\tsnapshot.digest !== baseline.digest\n\t\t) {\n\t\t\tthrow new OrchestrationEventStoreError(\"Invalid orchestration projection snapshot.\");\n\t\t}\n\t\tconst content: ProjectionSnapshotContent = {\n\t\t\tversion: 1,\n\t\t\tschemaVersion: ORCHESTRATION_SCHEMA_VERSION,\n\t\t\tthroughOrdinal: baseline.throughOrdinal,\n\t\t\tcreatedAt: snapshot.createdAt,\n\t\t\tprojection: structuredClone(snapshot.projection) as JsonObject,\n\t\t\tidempotencyEvents: snapshot.idempotencyEvents.map((event) => structuredClone(event)),\n\t\t};\n\t\tif (snapshotDigest(content) !== baseline.digest) {\n\t\t\tthrow new OrchestrationEventStoreError(\"Orchestration projection snapshot digest mismatch.\");\n\t\t}\n\t\treturn { ...content, digest: baseline.digest };\n\t}\n\n\t/**\n\t * Appends need a verified snapshot baseline but must not deserialize its projection on every event.\n\t * The baseline pointer remains small and is reread each time; an immutable snapshot is reparsed only\n\t * when its pointer or filesystem identity changes.\n\t */\n\tprivate readVerifiedSnapshotBaselineUnlocked(): SnapshotBaseline | undefined {\n\t\tconst baseline = this.readBaselineUnlocked();\n\t\tif (!baseline) {\n\t\t\tthis.verifiedSnapshotBaseline = undefined;\n\t\t\treturn undefined;\n\t\t}\n\t\tconst signature = this.snapshotFileSignatureUnlocked(baseline);\n\t\tconst cached = this.verifiedSnapshotBaseline;\n\t\tif (\n\t\t\tcached &&\n\t\t\tcached.baseline.throughOrdinal === baseline.throughOrdinal &&\n\t\t\tcached.baseline.digest === baseline.digest &&\n\t\t\tcached.baseline.snapshotFile === baseline.snapshotFile &&\n\t\t\tcached.signature.size === signature.size &&\n\t\t\tcached.signature.mtimeMs === signature.mtimeMs &&\n\t\t\tcached.signature.ctimeMs === signature.ctimeMs\n\t\t) {\n\t\t\treturn baseline;\n\t\t}\n\t\tthis.readProjectionSnapshotUnlocked();\n\t\tconst verifiedSignature = this.snapshotFileSignatureUnlocked(baseline);\n\t\tif (\n\t\t\tverifiedSignature.size !== signature.size ||\n\t\t\tverifiedSignature.mtimeMs !== signature.mtimeMs ||\n\t\t\tverifiedSignature.ctimeMs !== signature.ctimeMs\n\t\t) {\n\t\t\tthrow new OrchestrationEventStoreError(\"Orchestration projection snapshot changed while being verified.\");\n\t\t}\n\t\tthis.verifiedSnapshotBaseline = { baseline, signature };\n\t\treturn baseline;\n\t}\n\n\tprivate snapshotFileSignatureUnlocked(baseline: SnapshotBaseline): SnapshotFileSignature {\n\t\ttry {\n\t\t\tconst stats = statSync(join(this.snapshotsDir, baseline.snapshotFile));\n\t\t\tif (!stats.isFile())\n\t\t\t\tthrow new OrchestrationEventStoreError(\"Orchestration projection snapshot is not a file.\");\n\t\t\treturn { size: stats.size, mtimeMs: stats.mtimeMs, ctimeMs: stats.ctimeMs };\n\t\t} catch (error) {\n\t\t\tif (error instanceof OrchestrationEventStoreError) throw error;\n\t\t\tthrow new OrchestrationEventStoreError(\n\t\t\t\t`Failed to parse orchestration projection snapshot: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate unlinkManagedFile(filePath: string): void {\n\t\ttry {\n\t\t\tunlinkSync(filePath);\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n\t\t}\n\t}\n\n\tprivate readEventFileUnlocked(name: string): OrchestrationEvent {\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(\n\t\t\t\treadBoundedTextFileSync(join(this.eventsDir, name), this.maxTailBytes, `Orchestration event ${name}`),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow new OrchestrationEventStoreError(\n\t\t\t\t`Failed to parse orchestration event ${name}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\tif (!isOrchestrationEvent(parsed)) {\n\t\t\tthrow new OrchestrationEventStoreError(`Invalid orchestration event record: ${name}`);\n\t\t}\n\t\treturn parsed;\n\t}\n\n\tprivate idempotencyPath(key: string): string {\n\t\treturn join(this.idempotencyDir, `${createHash(\"sha256\").update(key).digest(\"hex\")}.json`);\n\t}\n\n\tprivate serializeIdempotencyMarker(key: string, ordinal: number): string {\n\t\treturn serializeBounded(\n\t\t\t{ version: 1, key, ordinal } satisfies IdempotencyMarker,\n\t\t\tMAX_IDEMPOTENCY_MARKER_BYTES,\n\t\t\t\"Orchestration idempotency marker\",\n\t\t);\n\t}\n\n\tprivate writeIdempotencyMarkerUnlocked(key: string, serializedMarker: string): void {\n\t\twriteFileAtomicSync(this.idempotencyPath(key), serializedMarker);\n\t}\n\n\tprivate readIdempotentEventUnlocked(key: string): OrchestrationEvent | undefined {\n\t\tconst markerPath = this.idempotencyPath(key);\n\t\tif (!existsSync(markerPath)) {\n\t\t\treturn this.readProjectionSnapshotUnlocked()?.idempotencyEvents.find((event) => event.idempotencyKey === key);\n\t\t}\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(\n\t\t\t\treadBoundedTextFileSync(markerPath, MAX_IDEMPOTENCY_MARKER_BYTES, \"Orchestration idempotency marker\"),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow new OrchestrationEventStoreError(\n\t\t\t\t`Failed to parse orchestration idempotency marker: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n\t\t\tthrow new OrchestrationEventStoreError(\"Invalid orchestration idempotency marker.\");\n\t\t}\n\t\tconst marker = parsed as Record<string, unknown>;\n\t\tif (\n\t\t\tmarker.version !== 1 ||\n\t\t\tmarker.key !== key ||\n\t\t\t!Number.isSafeInteger(marker.ordinal) ||\n\t\t\tNumber(marker.ordinal) < 1\n\t\t) {\n\t\t\tthrow new OrchestrationEventStoreError(\"Invalid orchestration idempotency marker.\");\n\t\t}\n\t\tconst ordinal = Number(marker.ordinal);\n\t\tif (!existsSync(join(this.eventsDir, eventFileName(ordinal)))) {\n\t\t\tconst retained = this.readProjectionSnapshotUnlocked()?.idempotencyEvents.find(\n\t\t\t\t(event) => event.idempotencyKey === key && event.ordinal === ordinal,\n\t\t\t);\n\t\t\tif (retained) return retained;\n\t\t}\n\t\tconst event = this.readEventFileUnlocked(eventFileName(ordinal));\n\t\tif (event.ordinal !== ordinal || event.idempotencyKey !== key) {\n\t\t\tthrow new OrchestrationEventStoreError(\"Orchestration idempotency marker does not match its event.\");\n\t\t}\n\t\treturn event;\n\t}\n\n\t/**\n\t * Reconcile only the crash tail when an event rename committed before its marker/cursor. Normal\n\t * appends read directory metadata plus one marker, never the accumulated event payload prefix.\n\t */\n\tprivate synchronizeIndexesUnlocked(): SynchronizedIndexes {\n\t\tconst names = this.eventFileNamesUnlocked();\n\t\tconst baselineOrdinal = this.readVerifiedSnapshotBaselineUnlocked()?.throughOrdinal ?? 0;\n\t\tthis.assertReadableTailUnlocked(names, baselineOrdinal);\n\t\tconst highestEventOrdinal = names.length > 0 ? Number(EVENT_FILE_PATTERN.exec(names.at(-1)!)?.[1] ?? 0) : 0;\n\t\tconst highest = Math.max(baselineOrdinal, highestEventOrdinal);\n\t\tconst cursor = parseCursor(this.cursorPath);\n\t\tif (\n\t\t\tcursor?.lastOrdinal === highest &&\n\t\t\tcursor.tailBytes !== undefined &&\n\t\t\t(highest > baselineOrdinal || cursor.tailBytes === 0)\n\t\t) {\n\t\t\treturn { lastOrdinal: highest, tailBytes: cursor.tailBytes };\n\t\t}\n\t\tif (cursor && cursor.lastOrdinal > highest) {\n\t\t\tthrow new OrchestrationEventStoreError(\n\t\t\t\t`Orchestration cursor ${cursor.lastOrdinal} is ahead of the last committed event ${highest}.`,\n\t\t\t);\n\t\t}\n\t\tconst rebuildFrom = Math.max(\n\t\t\tbaselineOrdinal + 1,\n\t\t\tcursor && cursor.lastOrdinal >= baselineOrdinal && cursor.lastOrdinal <= highest\n\t\t\t\t? cursor.lastOrdinal + 1\n\t\t\t\t: baselineOrdinal + 1,\n\t\t);\n\t\tfor (const name of names) {\n\t\t\tconst ordinal = Number(EVENT_FILE_PATTERN.exec(name)?.[1] ?? 0);\n\t\t\tif (ordinal < rebuildFrom || ordinal <= baselineOrdinal) continue;\n\t\t\tconst event = this.readEventFileUnlocked(name);\n\t\t\tif (event.ordinal !== ordinal) {\n\t\t\t\tthrow new OrchestrationEventStoreError(`Event ordinal does not match file name: ${name}`);\n\t\t\t}\n\t\t\tif (event.idempotencyKey) {\n\t\t\t\tthis.writeIdempotencyMarkerUnlocked(\n\t\t\t\t\tevent.idempotencyKey,\n\t\t\t\t\tthis.serializeIdempotencyMarker(event.idempotencyKey, ordinal),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tconst tailBytes = names.reduce((total, name) => {\n\t\t\tconst ordinal = Number(EVENT_FILE_PATTERN.exec(name)?.[1] ?? 0);\n\t\t\tif (ordinal <= baselineOrdinal) return total;\n\t\t\ttry {\n\t\t\t\treturn total + statSync(join(this.eventsDir, name)).size;\n\t\t\t} catch {\n\t\t\t\treturn total;\n\t\t\t}\n\t\t}, 0);\n\t\twriteFileAtomicSync(\n\t\t\tthis.cursorPath,\n\t\t\tserializeBounded(\n\t\t\t\t{ version: 1, lastOrdinal: highest, tailBytes } satisfies EventCursor,\n\t\t\t\tMAX_CURSOR_BYTES,\n\t\t\t\t\"Orchestration cursor\",\n\t\t\t),\n\t\t);\n\t\treturn { lastOrdinal: highest, tailBytes };\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"event-store.js","sourceRoot":"","sources":["../../../src/core/orchestration/event-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC1E,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAE/D,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC/E,OAAO,EAAE,6BAA6B,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AACjG,OAAO,EAEN,oBAAoB,EACpB,4BAA4B,GAE5B,MAAM,gBAAgB,CAAC;AAExB,MAAM,kBAAkB,GAAG,kBAAkB,CAAC;AAC9C,MAAM,qBAAqB,GAAG,kBAAkB,CAAC;AACjD,MAAM,uBAAuB,GAAG,GAAG,CAAC;AACpC,MAAM,sBAAsB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;AAC/C,MAAM,8BAA8B,GAAG,GAAG,CAAC;AAC3C,MAAM,0BAA0B,GAAG,KAAK,CAAC;AACzC,MAAM,yBAAyB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AACnD,MAAM,iCAAiC,GAAG,KAAK,CAAC;AAChD,MAAM,2BAA2B,GAAG,KAAK,CAAC;AAC1C,MAAM,iCAAiC,GAAG,KAAK,CAAC;AAChD,MAAM,8BAA8B,GAAG,CAAC,CAAC;AACzC,MAAM,gBAAgB,GAAG,EAAE,GAAG,IAAI,CAAC;AACnC,MAAM,kBAAkB,GAAG,EAAE,GAAG,IAAI,CAA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B,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC;oBAC1D,KAAK,CAAC,cAAe;oBACrB,eAAe,CAAC,KAAK,CAAC;iBACtB,CAAC,CACF;aACD,CAAC;QACJ,MAAM,QAAQ,GAAG,OAAO,CAAC,WAAW,GAAG,CAAC,CAAC;QACzC,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;YAC1B,MAAM,OAAO,GAAG,MAAM,CAAC,kBAAkB,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;YAChE,IAAI,OAAO,GAAG,QAAQ,IAAI,OAAO,IAAI,eAAe;gBAAE,SAAS;YAC/D,MAAM,KAAK,GAAG,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC;YAC/C,IAAI,KAAK,CAAC,OAAO,KAAK,OAAO,EAAE,CAAC;gBAC/B,MAAM,IAAI,4BAA4B,CAAC,2CAA2C,IAAI,EAAE,CAAC,CAAC;YAC3F,CAAC;YACD,IAAI,KAAK,CAAC,cAAc;gBAAE,OAAO,CAAC,iBAAiB,CAAC,GAAG,CAAC,KAAK,CAAC,cAAc,EAAE,KAAK,CAAC,CAAC;YACrF,OAAO,CAAC,SAAS,IAAI,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;YAC/D,OAAO,CAAC,WAAW,GAAG,OAAO,CAAC;QAC/B,CAAC;QACD,OAAO,CAAC,WAAW,GAAG,OAAO,CAAC;QAC9B,IAAI,CAAC,mBAAmB,GAAG,OAAO,CAAC;QACnC,OAAO,OAAO,CAAC;IAChB,CAAC;CACD","sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport { existsSync, statSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { orchestrationEventStoreDir } from \"../agent-paths.ts\";\nimport type { JsonObject } from \"../autonomy/contracts.ts\";\nimport { withFileLockSync, writeFileAtomicSync } from \"../util/atomic-file.ts\";\nimport { readBoundedDirectoryNamesSync, readBoundedTextFileSync } from \"../util/bounded-file.ts\";\nimport {\n\ttype AppendOrchestrationEventInput,\n\tisOrchestrationEvent,\n\tORCHESTRATION_SCHEMA_VERSION,\n\ttype OrchestrationEvent,\n} from \"./contracts.ts\";\n\nconst EVENT_FILE_PATTERN = /^(\\d{16})\\.json$/;\nconst SNAPSHOT_FILE_PATTERN = /^(\\d{16})\\.json$/;\nconst DEFAULT_MAX_TAIL_EVENTS = 256;\nconst DEFAULT_MAX_TAIL_BYTES = 4 * 1024 * 1024;\nconst DEFAULT_MAX_IDEMPOTENCY_EVENTS = 512;\nconst MAX_CONFIGURED_TAIL_EVENTS = 1_024;\nconst MAX_CONFIGURED_TAIL_BYTES = 16 * 1024 * 1024;\nconst MAX_CONFIGURED_IDEMPOTENCY_EVENTS = 1_024;\nconst MAX_EVENT_DIRECTORY_ENTRIES = 2_048;\nconst MAX_IDEMPOTENCY_DIRECTORY_ENTRIES = 2_048;\nconst MAX_SNAPSHOT_DIRECTORY_ENTRIES = 8;\nconst MAX_CURSOR_BYTES = 64 * 1024;\nconst MAX_BASELINE_BYTES = 64 * 1024;\n/** Full current task state plus retained idempotency evidence; intentionally above the 16MiB tail cap. */\nconst MAX_PROJECTION_SNAPSHOT_BYTES = 32 * 1024 * 1024;\n\ninterface EventCursor {\n\tversion: 1;\n\tlastOrdinal: number;\n\ttailBytes?: number;\n}\n\ninterface SynchronizedIndexes {\n\tbaselineOrdinal: number;\n\tbaselineDigest: string | undefined;\n\tlastOrdinal: number;\n\ttailBytes: number;\n\tidempotencyEvents: Map<string, OrchestrationEvent>;\n}\n\ninterface ProjectionSnapshotContent {\n\tversion: 1;\n\tschemaVersion: typeof ORCHESTRATION_SCHEMA_VERSION;\n\tthroughOrdinal: number;\n\tcreatedAt: string;\n\tprojection: JsonObject;\n\tidempotencyEvents: OrchestrationEvent[];\n}\n\ninterface ProjectionSnapshot extends ProjectionSnapshotContent {\n\tdigest: string;\n}\n\ninterface SnapshotBaseline {\n\tversion: 1;\n\tthroughOrdinal: number;\n\tdigest: string;\n\tsnapshotFile: string;\n}\n\ninterface SnapshotFileSignature {\n\tsize: number;\n\tmtimeMs: number;\n\tctimeMs: number;\n}\n\ninterface VerifiedSnapshotBaseline {\n\tbaseline: SnapshotBaseline;\n\tsignature: SnapshotFileSignature;\n\tidempotencyEvents: OrchestrationEvent[];\n}\n\nexport interface OrchestrationEventStoreOptions {\n\tagentDir: string;\n\tsessionId: string;\n\tnow?: () => string;\n\tcreateEventId?: () => string;\n\tmaxTailEvents?: number;\n\tmaxTailBytes?: number;\n\tmaxIdempotencyEvents?: number;\n}\n\nexport class OrchestrationEventStoreError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"OrchestrationEventStoreError\";\n\t}\n}\n\nexport class OrchestrationConcurrencyError extends OrchestrationEventStoreError {\n\tconstructor(expected: number, actual: number) {\n\t\tsuper(`Orchestration event cursor changed: expected ${expected}, actual ${actual}.`);\n\t\tthis.name = \"OrchestrationConcurrencyError\";\n\t}\n}\n\nexport class OrchestrationSnapshotRequiredError extends OrchestrationEventStoreError {\n\treadonly throughOrdinal: number;\n\n\tconstructor(throughOrdinal: number) {\n\t\tsuper(`Orchestration projection snapshot through ordinal ${throughOrdinal} is required.`);\n\t\tthis.name = \"OrchestrationSnapshotRequiredError\";\n\t\tthis.throughOrdinal = throughOrdinal;\n\t}\n}\n\nfunction parseCursor(filePath: string): EventCursor | undefined {\n\tif (!existsSync(filePath)) return undefined;\n\tlet content: string;\n\ttry {\n\t\tcontent = readBoundedTextFileSync(filePath, MAX_CURSOR_BYTES, \"Orchestration cursor\");\n\t} catch (error) {\n\t\tthrow new OrchestrationEventStoreError(\n\t\t\t`Failed to read orchestration cursor: ${error instanceof Error ? error.message : String(error)}`,\n\t\t);\n\t}\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(content);\n\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return undefined;\n\t\tconst record = parsed as Record<string, unknown>;\n\t\tif (record.version !== 1 || !Number.isSafeInteger(record.lastOrdinal) || Number(record.lastOrdinal) < 0) {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (record.tailBytes !== undefined && (!Number.isSafeInteger(record.tailBytes) || Number(record.tailBytes) < 0)) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn {\n\t\t\tversion: 1,\n\t\t\tlastOrdinal: Number(record.lastOrdinal),\n\t\t\t...(record.tailBytes !== undefined ? { tailBytes: Number(record.tailBytes) } : {}),\n\t\t};\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction serialize(value: unknown): string {\n\treturn `${JSON.stringify(value, null, \"\\t\")}\\n`;\n}\n\nfunction serializeBounded(\n\tvalue: unknown,\n\tmaxBytes: number,\n\tlabel: string,\n\toversizedMessage = `${label} exceeds its byte limit.`,\n): string {\n\tconst serialized = serialize(value);\n\tif (Buffer.byteLength(serialized, \"utf-8\") > maxBytes) {\n\t\tthrow new OrchestrationEventStoreError(oversizedMessage);\n\t}\n\treturn serialized;\n}\n\nfunction eventFileName(ordinal: number): string {\n\treturn `${String(ordinal).padStart(16, \"0\")}.json`;\n}\n\nfunction snapshotDigest(content: ProjectionSnapshotContent): string {\n\treturn createHash(\"sha256\").update(JSON.stringify(content)).digest(\"hex\");\n}\n\nfunction positiveSafeInteger(value: number | undefined, fallback: number, maximum: number, label: string): number {\n\tconst resolved = value ?? fallback;\n\tif (!Number.isSafeInteger(resolved) || resolved < 1) {\n\t\tthrow new OrchestrationEventStoreError(`${label} must be a positive safe integer.`);\n\t}\n\tif (resolved > maximum) throw new OrchestrationEventStoreError(`${label} must not exceed ${maximum}.`);\n\treturn resolved;\n}\n\n/**\n * Append-only event tail with a replaceable full-state projection snapshot. Each immutable event is\n * its own commit record: idempotency data is derived directly from the bounded tail, while a small\n * mutable cursor remains only as a corruption high-water mark. Atomic rename prevents torn event\n * records without multiplying one transition into per-key marker files and atomic cursor rewrites.\n * Snapshot publication is two-phase (payload, then small baseline pointer), after which covered event\n * and legacy-index files are pruned. A crash at any point leaves either the old replay prefix or the\n * new verified snapshot authoritative; ordinals never reset.\n */\nexport class OrchestrationEventStore {\n\treadonly rootDir: string;\n\treadonly eventsDir: string;\n\treadonly idempotencyDir: string;\n\treadonly cursorPath: string;\n\treadonly snapshotsDir: string;\n\treadonly baselinePath: string;\n\tprivate readonly now: () => string;\n\tprivate readonly createEventId: () => string;\n\tprivate readonly maxTailEvents: number;\n\tprivate readonly maxTailBytes: number;\n\tprivate readonly maxIdempotencyEvents: number;\n\tprivate readonly listeners = new Set<(event: OrchestrationEvent) => void>();\n\tprivate verifiedSnapshotBaseline: VerifiedSnapshotBaseline | undefined;\n\tprivate synchronizedIndexes: SynchronizedIndexes | undefined;\n\n\tconstructor(options: OrchestrationEventStoreOptions) {\n\t\tthis.rootDir = orchestrationEventStoreDir(options.agentDir, options.sessionId);\n\t\tthis.eventsDir = join(this.rootDir, \"events\");\n\t\tthis.idempotencyDir = join(this.rootDir, \"idempotency\");\n\t\tthis.cursorPath = join(this.rootDir, \"cursor.json\");\n\t\tthis.snapshotsDir = join(this.rootDir, \"snapshots\");\n\t\tthis.baselinePath = join(this.rootDir, \"projection-baseline.json\");\n\t\tthis.now = options.now ?? (() => new Date().toISOString());\n\t\tthis.createEventId = options.createEventId ?? randomUUID;\n\t\tthis.maxTailEvents = positiveSafeInteger(\n\t\t\toptions.maxTailEvents,\n\t\t\tDEFAULT_MAX_TAIL_EVENTS,\n\t\t\tMAX_CONFIGURED_TAIL_EVENTS,\n\t\t\t\"maxTailEvents\",\n\t\t);\n\t\tthis.maxTailBytes = positiveSafeInteger(\n\t\t\toptions.maxTailBytes,\n\t\t\tDEFAULT_MAX_TAIL_BYTES,\n\t\t\tMAX_CONFIGURED_TAIL_BYTES,\n\t\t\t\"maxTailBytes\",\n\t\t);\n\t\tthis.maxIdempotencyEvents = positiveSafeInteger(\n\t\t\toptions.maxIdempotencyEvents,\n\t\t\tDEFAULT_MAX_IDEMPOTENCY_EVENTS,\n\t\t\tMAX_CONFIGURED_IDEMPOTENCY_EVENTS,\n\t\t\t\"maxIdempotencyEvents\",\n\t\t);\n\t}\n\n\tappend(input: AppendOrchestrationEventInput, options: { expectedLastOrdinal?: number } = {}): OrchestrationEvent {\n\t\tconst committed = withFileLockSync(this.cursorPath, (): { event: OrchestrationEvent; appended: boolean } => {\n\t\t\tconst indexes = this.synchronizeIndexesUnlocked();\n\t\t\tconst actual = indexes.lastOrdinal;\n\t\t\tif (input.idempotencyKey) {\n\t\t\t\tconst existing = indexes.idempotencyEvents.get(input.idempotencyKey);\n\t\t\t\tif (existing) return { event: existing, appended: false };\n\t\t\t}\n\t\t\tif (options.expectedLastOrdinal !== undefined) {\n\t\t\t\tif (actual !== options.expectedLastOrdinal) {\n\t\t\t\t\tthrow new OrchestrationConcurrencyError(options.expectedLastOrdinal, actual);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst ordinal = actual + 1;\n\t\t\tconst next: OrchestrationEvent = {\n\t\t\t\tschemaVersion: ORCHESTRATION_SCHEMA_VERSION,\n\t\t\t\tordinal,\n\t\t\t\teventId: this.createEventId(),\n\t\t\t\ttype: input.type,\n\t\t\t\taggregateId: input.aggregateId,\n\t\t\t\tactor: input.actor,\n\t\t\t\toccurredAt: this.now(),\n\t\t\t\t...(input.correlationId ? { correlationId: input.correlationId } : {}),\n\t\t\t\t...(input.causationId ? { causationId: input.causationId } : {}),\n\t\t\t\t...(input.idempotencyKey ? { idempotencyKey: input.idempotencyKey } : {}),\n\t\t\t\tpayload: structuredClone(input.payload),\n\t\t\t};\n\t\t\tconst serializedEvent = serializeBounded(\n\t\t\t\tnext,\n\t\t\t\tthis.maxTailBytes,\n\t\t\t\t\"Orchestration event\",\n\t\t\t\t\"Orchestration event exceeds its configured tail byte limit.\",\n\t\t\t);\n\t\t\tconst nextTailBytes = indexes.tailBytes + Buffer.byteLength(serializedEvent);\n\t\t\tconst serializedCursor = serializeBounded(\n\t\t\t\t{ version: 1, lastOrdinal: ordinal, tailBytes: nextTailBytes } satisfies EventCursor,\n\t\t\t\tMAX_CURSOR_BYTES,\n\t\t\t\t\"Orchestration cursor\",\n\t\t\t);\n\t\t\twriteFileAtomicSync(join(this.eventsDir, eventFileName(ordinal)), serializedEvent);\n\t\t\tindexes.lastOrdinal = ordinal;\n\t\t\tindexes.tailBytes = nextTailBytes;\n\t\t\tif (input.idempotencyKey) indexes.idempotencyEvents.set(input.idempotencyKey, next);\n\t\t\t// The immutable event is authoritative. The cursor is only a corruption high-water mark,\n\t\t\t// so a lock-protected direct overwrite avoids another tmp-file creation and rename on the\n\t\t\t// Windows scanner-sensitive path; a torn cursor is safely rebuilt from the event tail.\n\t\t\twriteFileSync(this.cursorPath, serializedCursor, \"utf-8\");\n\t\t\treturn { event: next, appended: true };\n\t\t});\n\n\t\tif (committed.appended) {\n\t\t\tfor (const listener of this.listeners) listener(structuredClone(committed.event));\n\t\t}\n\t\treturn structuredClone(committed.event);\n\t}\n\n\treadAll(): OrchestrationEvent[] {\n\t\treturn this.readAllUnlocked();\n\t}\n\n\treadAfter(ordinal: number): OrchestrationEvent[] {\n\t\tconst baseline = this.readBaselineUnlocked();\n\t\tif (baseline && ordinal < baseline.throughOrdinal) {\n\t\t\tthrow new OrchestrationSnapshotRequiredError(baseline.throughOrdinal);\n\t\t}\n\t\tconst events: OrchestrationEvent[] = [];\n\t\tconst names = this.eventFileNamesUnlocked();\n\t\tthis.assertReadableTailUnlocked(names, baseline?.throughOrdinal ?? 0);\n\t\tlet previousOrdinal = ordinal;\n\t\tfor (const name of names) {\n\t\t\tconst match = EVENT_FILE_PATTERN.exec(name);\n\t\t\tif (!match) continue;\n\t\t\tconst fileOrdinal = Number(match[1]);\n\t\t\tif (fileOrdinal <= ordinal) continue;\n\t\t\tconst event = this.readEventFileUnlocked(name);\n\t\t\tif (event.ordinal !== fileOrdinal || event.ordinal <= previousOrdinal) {\n\t\t\t\tthrow new OrchestrationEventStoreError(`Non-monotonic orchestration event ordinal in ${name}`);\n\t\t\t}\n\t\t\tpreviousOrdinal = event.ordinal;\n\t\t\tevents.push(structuredClone(event));\n\t\t}\n\t\treturn events;\n\t}\n\n\treadProjectionSnapshot(): { throughOrdinal: number; projection: JsonObject } | undefined {\n\t\tconst snapshot = this.readProjectionSnapshotUnlocked();\n\t\treturn snapshot\n\t\t\t? { throughOrdinal: snapshot.throughOrdinal, projection: structuredClone(snapshot.projection) }\n\t\t\t: undefined;\n\t}\n\n\t/** Replace a large replay prefix with one verified current-state snapshot and a bounded tail. */\n\tcompactIfNeeded(throughOrdinal: number, projection: () => JsonObject): boolean {\n\t\tconst baselineBeforeLock = this.readBaselineUnlocked();\n\t\tconst baselineOrdinalBeforeLock = baselineBeforeLock?.throughOrdinal ?? 0;\n\t\tconst cachedIndexes = this.synchronizedIndexes;\n\t\tif (\n\t\t\tcachedIndexes?.baselineOrdinal === baselineOrdinalBeforeLock &&\n\t\t\tcachedIndexes.baselineDigest === baselineBeforeLock?.digest &&\n\t\t\tcachedIndexes.lastOrdinal === throughOrdinal &&\n\t\t\tthroughOrdinal - baselineOrdinalBeforeLock < this.maxTailEvents &&\n\t\t\tcachedIndexes.tailBytes < this.maxTailBytes\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\tconst cursorBeforeLock = parseCursor(this.cursorPath);\n\t\tif (\n\t\t\t!cachedIndexes &&\n\t\t\tcursorBeforeLock?.lastOrdinal === throughOrdinal &&\n\t\t\tcursorBeforeLock.tailBytes !== undefined &&\n\t\t\tthroughOrdinal - baselineOrdinalBeforeLock < this.maxTailEvents &&\n\t\t\tcursorBeforeLock.tailBytes < this.maxTailBytes\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\treturn withFileLockSync(this.cursorPath, () => {\n\t\t\tconst cursor = this.synchronizeIndexesUnlocked();\n\t\t\tif (cursor.lastOrdinal !== throughOrdinal) return false;\n\t\t\tconst baselineOrdinal = this.readBaselineUnlocked()?.throughOrdinal ?? 0;\n\t\t\tconst tailNames = this.eventFileNamesUnlocked().filter(\n\t\t\t\t(name) => Number(EVENT_FILE_PATTERN.exec(name)?.[1] ?? 0) > baselineOrdinal,\n\t\t\t);\n\t\t\tif (tailNames.length < this.maxTailEvents && cursor.tailBytes < this.maxTailBytes) return false;\n\n\t\t\tconst retainedByKey = new Map<string, OrchestrationEvent>();\n\t\t\tfor (const event of this.readProjectionSnapshotUnlocked()?.idempotencyEvents ?? []) {\n\t\t\t\tif (event.idempotencyKey) retainedByKey.set(event.idempotencyKey, event);\n\t\t\t}\n\t\t\tfor (const name of tailNames) {\n\t\t\t\tconst event = this.readEventFileUnlocked(name);\n\t\t\t\tif (event.ordinal <= throughOrdinal && event.idempotencyKey) {\n\t\t\t\t\tretainedByKey.set(event.idempotencyKey, event);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst idempotencyEvents = [...retainedByKey.values()]\n\t\t\t\t.sort((left, right) => left.ordinal - right.ordinal)\n\t\t\t\t.slice(-this.maxIdempotencyEvents)\n\t\t\t\t.map((event) => structuredClone(event));\n\t\t\tconst content: ProjectionSnapshotContent = {\n\t\t\t\tversion: 1,\n\t\t\t\tschemaVersion: ORCHESTRATION_SCHEMA_VERSION,\n\t\t\t\tthroughOrdinal,\n\t\t\t\tcreatedAt: this.now(),\n\t\t\t\tprojection: structuredClone(projection()),\n\t\t\t\tidempotencyEvents,\n\t\t\t};\n\t\t\tconst digest = snapshotDigest(content);\n\t\t\tconst snapshotFile = eventFileName(throughOrdinal);\n\t\t\tconst serializedSnapshot = serializeBounded(\n\t\t\t\t{ ...content, digest } satisfies ProjectionSnapshot,\n\t\t\t\tMAX_PROJECTION_SNAPSHOT_BYTES,\n\t\t\t\t\"Orchestration projection snapshot\",\n\t\t\t);\n\t\t\tconst serializedBaseline = serializeBounded(\n\t\t\t\t{ version: 1, throughOrdinal, digest, snapshotFile } satisfies SnapshotBaseline,\n\t\t\t\tMAX_BASELINE_BYTES,\n\t\t\t\t\"Orchestration snapshot baseline\",\n\t\t\t);\n\t\t\tconst serializedCursor = serializeBounded(\n\t\t\t\t{ version: 1, lastOrdinal: throughOrdinal, tailBytes: 0 } satisfies EventCursor,\n\t\t\t\tMAX_CURSOR_BYTES,\n\t\t\t\t\"Orchestration cursor\",\n\t\t\t);\n\t\t\twriteFileAtomicSync(join(this.snapshotsDir, snapshotFile), serializedSnapshot);\n\t\t\twriteFileAtomicSync(this.baselinePath, serializedBaseline);\n\n\t\t\tfor (const name of this.idempotencyFileNamesUnlocked()) {\n\t\t\t\tthis.unlinkManagedFile(join(this.idempotencyDir, name));\n\t\t\t}\n\t\t\tfor (const name of this.eventFileNamesUnlocked()) {\n\t\t\t\tconst ordinal = Number(EVENT_FILE_PATTERN.exec(name)?.[1] ?? 0);\n\t\t\t\tif (ordinal <= throughOrdinal) this.unlinkManagedFile(join(this.eventsDir, name));\n\t\t\t}\n\t\t\tfor (const name of this.snapshotFileNamesUnlocked()) {\n\t\t\t\tif (name !== snapshotFile) this.unlinkManagedFile(join(this.snapshotsDir, name));\n\t\t\t}\n\t\t\twriteFileAtomicSync(this.cursorPath, serializedCursor);\n\t\t\tthis.verifiedSnapshotBaseline = undefined;\n\t\t\tthis.synchronizedIndexes = {\n\t\t\t\tbaselineOrdinal: throughOrdinal,\n\t\t\t\tbaselineDigest: digest,\n\t\t\t\tlastOrdinal: throughOrdinal,\n\t\t\t\ttailBytes: 0,\n\t\t\t\tidempotencyEvents: new Map(\n\t\t\t\t\tidempotencyEvents.map((event) => [event.idempotencyKey!, structuredClone(event)]),\n\t\t\t\t),\n\t\t\t};\n\t\t\treturn true;\n\t\t});\n\t}\n\n\tsubscribe(listener: (event: OrchestrationEvent) => void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\tprivate readAllUnlocked(): OrchestrationEvent[] {\n\t\tconst names = this.eventFileNamesUnlocked();\n\t\tconst events: OrchestrationEvent[] = [];\n\t\tconst baselineOrdinal = this.readProjectionSnapshotUnlocked()?.throughOrdinal ?? 0;\n\t\tthis.assertReadableTailUnlocked(names, baselineOrdinal);\n\t\tlet previousOrdinal = baselineOrdinal;\n\t\tfor (const name of names) {\n\t\t\tconst match = EVENT_FILE_PATTERN.exec(name);\n\t\t\tif (!match) continue;\n\t\t\tconst fileOrdinal = Number(match[1]);\n\t\t\tif (fileOrdinal <= baselineOrdinal) continue;\n\t\t\tconst parsed = this.readEventFileUnlocked(name);\n\t\t\tif (parsed.ordinal !== fileOrdinal || parsed.ordinal <= previousOrdinal) {\n\t\t\t\tthrow new OrchestrationEventStoreError(`Non-monotonic orchestration event ordinal in ${name}`);\n\t\t\t}\n\t\t\tpreviousOrdinal = parsed.ordinal;\n\t\t\tevents.push(structuredClone(parsed));\n\t\t}\n\t\treturn events;\n\t}\n\n\tprivate eventFileNamesUnlocked(): string[] {\n\t\ttry {\n\t\t\treturn readBoundedDirectoryNamesSync(\n\t\t\t\tthis.eventsDir,\n\t\t\t\tMAX_EVENT_DIRECTORY_ENTRIES,\n\t\t\t\t\"Orchestration events directory\",\n\t\t\t)\n\t\t\t\t.filter((candidate) => EVENT_FILE_PATTERN.test(candidate))\n\t\t\t\t.sort();\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate idempotencyFileNamesUnlocked(): string[] {\n\t\ttry {\n\t\t\treturn readBoundedDirectoryNamesSync(\n\t\t\t\tthis.idempotencyDir,\n\t\t\t\tMAX_IDEMPOTENCY_DIRECTORY_ENTRIES,\n\t\t\t\t\"Orchestration idempotency directory\",\n\t\t\t).filter((candidate) => candidate.endsWith(\".json\"));\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate snapshotFileNamesUnlocked(): string[] {\n\t\ttry {\n\t\t\treturn readBoundedDirectoryNamesSync(\n\t\t\t\tthis.snapshotsDir,\n\t\t\t\tMAX_SNAPSHOT_DIRECTORY_ENTRIES,\n\t\t\t\t\"Orchestration snapshots directory\",\n\t\t\t)\n\t\t\t\t.filter((candidate) => SNAPSHOT_FILE_PATTERN.test(candidate))\n\t\t\t\t.sort();\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/** Event files are a contiguous append-only tail after the published snapshot. */\n\tprivate assertContiguousTailOrdinalsUnlocked(names: readonly string[], baselineOrdinal: number): void {\n\t\tlet expectedOrdinal = baselineOrdinal + 1;\n\t\tfor (const name of names) {\n\t\t\tconst ordinal = Number(EVENT_FILE_PATTERN.exec(name)?.[1] ?? 0);\n\t\t\t// A crash after publishing the baseline but before pruning is safe: the snapshot covers these files.\n\t\t\tif (ordinal <= baselineOrdinal) continue;\n\t\t\tif (ordinal !== expectedOrdinal) {\n\t\t\t\tthrow new OrchestrationEventStoreError(\n\t\t\t\t\t`Missing orchestration event ordinal ${expectedOrdinal} before ${name}.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\texpectedOrdinal++;\n\t\t}\n\t}\n\n\t/** A valid cursor may lag a newly published snapshot, but it must never lead its committed tail. */\n\tprivate assertReadableTailUnlocked(names: readonly string[], baselineOrdinal: number): void {\n\t\tthis.assertContiguousTailOrdinalsUnlocked(names, baselineOrdinal);\n\t\tconst highestEventOrdinal = names.length > 0 ? Number(EVENT_FILE_PATTERN.exec(names.at(-1)!)?.[1] ?? 0) : 0;\n\t\tconst highestCommittedOrdinal = Math.max(baselineOrdinal, highestEventOrdinal);\n\t\tconst cursor = parseCursor(this.cursorPath);\n\t\tif (cursor && cursor.lastOrdinal > highestCommittedOrdinal) {\n\t\t\tthrow new OrchestrationEventStoreError(\n\t\t\t\t`Orchestration cursor ${cursor.lastOrdinal} is ahead of the last committed event ${highestCommittedOrdinal}.`,\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate readBaselineUnlocked(): SnapshotBaseline | undefined {\n\t\tif (!existsSync(this.baselinePath)) return undefined;\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(\n\t\t\t\treadBoundedTextFileSync(this.baselinePath, MAX_BASELINE_BYTES, \"Orchestration snapshot baseline\"),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow new OrchestrationEventStoreError(\n\t\t\t\t`Failed to parse orchestration snapshot baseline: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n\t\t\tthrow new OrchestrationEventStoreError(\"Invalid orchestration snapshot baseline.\");\n\t\t}\n\t\tconst baseline = parsed as Record<string, unknown>;\n\t\tif (\n\t\t\tbaseline.version !== 1 ||\n\t\t\t!Number.isSafeInteger(baseline.throughOrdinal) ||\n\t\t\tNumber(baseline.throughOrdinal) < 1 ||\n\t\t\ttypeof baseline.digest !== \"string\" ||\n\t\t\tbaseline.digest.length === 0 ||\n\t\t\ttypeof baseline.snapshotFile !== \"string\" ||\n\t\t\t!SNAPSHOT_FILE_PATTERN.test(baseline.snapshotFile) ||\n\t\t\tNumber(SNAPSHOT_FILE_PATTERN.exec(baseline.snapshotFile)?.[1] ?? 0) !== Number(baseline.throughOrdinal)\n\t\t) {\n\t\t\tthrow new OrchestrationEventStoreError(\"Invalid orchestration snapshot baseline.\");\n\t\t}\n\t\treturn {\n\t\t\tversion: 1,\n\t\t\tthroughOrdinal: Number(baseline.throughOrdinal),\n\t\t\tdigest: baseline.digest,\n\t\t\tsnapshotFile: baseline.snapshotFile,\n\t\t};\n\t}\n\n\tprivate readProjectionSnapshotUnlocked(): ProjectionSnapshot | undefined {\n\t\tconst baseline = this.readBaselineUnlocked();\n\t\tif (!baseline) return undefined;\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(\n\t\t\t\treadBoundedTextFileSync(\n\t\t\t\t\tjoin(this.snapshotsDir, baseline.snapshotFile),\n\t\t\t\t\tMAX_PROJECTION_SNAPSHOT_BYTES,\n\t\t\t\t\t\"Orchestration projection snapshot\",\n\t\t\t\t),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow new OrchestrationEventStoreError(\n\t\t\t\t`Failed to parse orchestration projection snapshot: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n\t\t\tthrow new OrchestrationEventStoreError(\"Invalid orchestration projection snapshot.\");\n\t\t}\n\t\tconst snapshot = parsed as Record<string, unknown>;\n\t\tif (\n\t\t\tsnapshot.version !== 1 ||\n\t\t\tsnapshot.schemaVersion !== ORCHESTRATION_SCHEMA_VERSION ||\n\t\t\tsnapshot.throughOrdinal !== baseline.throughOrdinal ||\n\t\t\ttypeof snapshot.createdAt !== \"string\" ||\n\t\t\t!snapshot.projection ||\n\t\t\ttypeof snapshot.projection !== \"object\" ||\n\t\t\tArray.isArray(snapshot.projection) ||\n\t\t\t!Array.isArray(snapshot.idempotencyEvents) ||\n\t\t\tsnapshot.idempotencyEvents.length > this.maxIdempotencyEvents ||\n\t\t\t!snapshot.idempotencyEvents.every(isOrchestrationEvent) ||\n\t\t\t!snapshot.idempotencyEvents.every(\n\t\t\t\t(event) => event.ordinal <= baseline.throughOrdinal && event.idempotencyKey !== undefined,\n\t\t\t) ||\n\t\t\tnew Set(snapshot.idempotencyEvents.map((event) => event.idempotencyKey)).size !==\n\t\t\t\tsnapshot.idempotencyEvents.length ||\n\t\t\ttypeof snapshot.digest !== \"string\" ||\n\t\t\tsnapshot.digest !== baseline.digest\n\t\t) {\n\t\t\tthrow new OrchestrationEventStoreError(\"Invalid orchestration projection snapshot.\");\n\t\t}\n\t\tconst content: ProjectionSnapshotContent = {\n\t\t\tversion: 1,\n\t\t\tschemaVersion: ORCHESTRATION_SCHEMA_VERSION,\n\t\t\tthroughOrdinal: baseline.throughOrdinal,\n\t\t\tcreatedAt: snapshot.createdAt,\n\t\t\tprojection: structuredClone(snapshot.projection) as JsonObject,\n\t\t\tidempotencyEvents: snapshot.idempotencyEvents.map((event) => structuredClone(event)),\n\t\t};\n\t\tif (snapshotDigest(content) !== baseline.digest) {\n\t\t\tthrow new OrchestrationEventStoreError(\"Orchestration projection snapshot digest mismatch.\");\n\t\t}\n\t\treturn { ...content, digest: baseline.digest };\n\t}\n\n\t/**\n\t * Appends need a verified snapshot baseline but must not deserialize its projection on every event.\n\t * The baseline pointer remains small and is reread each time; an immutable snapshot is reparsed only\n\t * when its pointer or filesystem identity changes.\n\t */\n\tprivate readVerifiedSnapshotBaselineUnlocked(): VerifiedSnapshotBaseline | undefined {\n\t\tconst baseline = this.readBaselineUnlocked();\n\t\tif (!baseline) {\n\t\t\tthis.verifiedSnapshotBaseline = undefined;\n\t\t\treturn undefined;\n\t\t}\n\t\tconst signature = this.snapshotFileSignatureUnlocked(baseline);\n\t\tconst cached = this.verifiedSnapshotBaseline;\n\t\tif (\n\t\t\tcached &&\n\t\t\tcached.baseline.throughOrdinal === baseline.throughOrdinal &&\n\t\t\tcached.baseline.digest === baseline.digest &&\n\t\t\tcached.baseline.snapshotFile === baseline.snapshotFile &&\n\t\t\tcached.signature.size === signature.size &&\n\t\t\tcached.signature.mtimeMs === signature.mtimeMs &&\n\t\t\tcached.signature.ctimeMs === signature.ctimeMs\n\t\t) {\n\t\t\treturn cached;\n\t\t}\n\t\tconst snapshot = this.readProjectionSnapshotUnlocked();\n\t\tif (!snapshot) {\n\t\t\tthrow new OrchestrationEventStoreError(\"Orchestration projection snapshot is unavailable.\");\n\t\t}\n\t\tconst verifiedSignature = this.snapshotFileSignatureUnlocked(baseline);\n\t\tif (\n\t\t\tverifiedSignature.size !== signature.size ||\n\t\t\tverifiedSignature.mtimeMs !== signature.mtimeMs ||\n\t\t\tverifiedSignature.ctimeMs !== signature.ctimeMs\n\t\t) {\n\t\t\tthrow new OrchestrationEventStoreError(\"Orchestration projection snapshot changed while being verified.\");\n\t\t}\n\t\tthis.verifiedSnapshotBaseline = {\n\t\t\tbaseline,\n\t\t\tsignature,\n\t\t\tidempotencyEvents: snapshot.idempotencyEvents.map((event) => structuredClone(event)),\n\t\t};\n\t\treturn this.verifiedSnapshotBaseline;\n\t}\n\n\tprivate snapshotFileSignatureUnlocked(baseline: SnapshotBaseline): SnapshotFileSignature {\n\t\ttry {\n\t\t\tconst stats = statSync(join(this.snapshotsDir, baseline.snapshotFile));\n\t\t\tif (!stats.isFile())\n\t\t\t\tthrow new OrchestrationEventStoreError(\"Orchestration projection snapshot is not a file.\");\n\t\t\treturn { size: stats.size, mtimeMs: stats.mtimeMs, ctimeMs: stats.ctimeMs };\n\t\t} catch (error) {\n\t\t\tif (error instanceof OrchestrationEventStoreError) throw error;\n\t\t\tthrow new OrchestrationEventStoreError(\n\t\t\t\t`Failed to parse orchestration projection snapshot: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tprivate unlinkManagedFile(filePath: string): void {\n\t\ttry {\n\t\t\tunlinkSync(filePath);\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n\t\t}\n\t}\n\n\tprivate readEventFileUnlocked(name: string): OrchestrationEvent {\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(\n\t\t\t\treadBoundedTextFileSync(join(this.eventsDir, name), this.maxTailBytes, `Orchestration event ${name}`),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow new OrchestrationEventStoreError(\n\t\t\t\t`Failed to parse orchestration event ${name}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t}\n\t\tif (!isOrchestrationEvent(parsed)) {\n\t\t\tthrow new OrchestrationEventStoreError(`Invalid orchestration event record: ${name}`);\n\t\t}\n\t\treturn parsed;\n\t}\n\n\t/**\n\t * Reconcile the bounded immutable tail into an in-memory index. Independent writers are detected\n\t * from new ordinals while holding the shared lock, so normal same-process appends parse only events\n\t * committed by other writers. A bounded mutable cursor remains derived corruption evidence; legacy\n\t * per-key marker files are no longer needed or rewritten.\n\t */\n\tprivate synchronizeIndexesUnlocked(): SynchronizedIndexes {\n\t\tconst names = this.eventFileNamesUnlocked();\n\t\tconst verifiedBaseline = this.readVerifiedSnapshotBaselineUnlocked();\n\t\tconst baselineOrdinal = verifiedBaseline?.baseline.throughOrdinal ?? 0;\n\t\tconst baselineDigest = verifiedBaseline?.baseline.digest;\n\t\tthis.assertReadableTailUnlocked(names, baselineOrdinal);\n\t\tconst highestEventOrdinal = names.length > 0 ? Number(EVENT_FILE_PATTERN.exec(names.at(-1)!)?.[1] ?? 0) : 0;\n\t\tconst highest = Math.max(baselineOrdinal, highestEventOrdinal);\n\t\tif (\n\t\t\tthis.synchronizedIndexes?.baselineOrdinal === baselineOrdinal &&\n\t\t\tthis.synchronizedIndexes.baselineDigest === baselineDigest &&\n\t\t\tthis.synchronizedIndexes.lastOrdinal > highest\n\t\t) {\n\t\t\tthrow new OrchestrationEventStoreError(\n\t\t\t\t`Orchestration cursor ${this.synchronizedIndexes.lastOrdinal} is ahead of the last committed event ${highest}.`,\n\t\t\t);\n\t\t}\n\t\tconst cached = this.synchronizedIndexes;\n\t\tconst canExtendCached =\n\t\t\tcached?.baselineOrdinal === baselineOrdinal &&\n\t\t\tcached.baselineDigest === baselineDigest &&\n\t\t\tcached.lastOrdinal >= baselineOrdinal &&\n\t\t\tcached.lastOrdinal <= highest;\n\t\tif (canExtendCached && cached.lastOrdinal === highest) return cached;\n\n\t\tconst indexes: SynchronizedIndexes = canExtendCached\n\t\t\t? cached\n\t\t\t: {\n\t\t\t\t\tbaselineOrdinal,\n\t\t\t\t\tbaselineDigest,\n\t\t\t\t\tlastOrdinal: baselineOrdinal,\n\t\t\t\t\ttailBytes: 0,\n\t\t\t\t\tidempotencyEvents: new Map(\n\t\t\t\t\t\t(verifiedBaseline?.idempotencyEvents ?? []).map((event) => [\n\t\t\t\t\t\t\tevent.idempotencyKey!,\n\t\t\t\t\t\t\tstructuredClone(event),\n\t\t\t\t\t\t]),\n\t\t\t\t\t),\n\t\t\t\t};\n\t\tconst scanFrom = indexes.lastOrdinal + 1;\n\t\tfor (const name of names) {\n\t\t\tconst ordinal = Number(EVENT_FILE_PATTERN.exec(name)?.[1] ?? 0);\n\t\t\tif (ordinal < scanFrom || ordinal <= baselineOrdinal) continue;\n\t\t\tconst event = this.readEventFileUnlocked(name);\n\t\t\tif (event.ordinal !== ordinal) {\n\t\t\t\tthrow new OrchestrationEventStoreError(`Event ordinal does not match file name: ${name}`);\n\t\t\t}\n\t\t\tif (event.idempotencyKey) indexes.idempotencyEvents.set(event.idempotencyKey, event);\n\t\t\tindexes.tailBytes += statSync(join(this.eventsDir, name)).size;\n\t\t\tindexes.lastOrdinal = ordinal;\n\t\t}\n\t\tindexes.lastOrdinal = highest;\n\t\tthis.synchronizedIndexes = indexes;\n\t\treturn indexes;\n\t}\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { OrchestrationProfile, ToolCapabilityManifest } from "./contracts.ts";
|
|
2
|
-
export declare const CLASSIFIED_LANE_TOOL_NAMES: readonly ["read", "grep", "find", "ls", "write", "edit", "memory", "run_process"];
|
|
3
|
-
export declare const ORCHESTRATION_PROFILE_TOOL_NAMES: readonly ["read", "grep", "find", "ls", "write", "edit", "memory", "run_process", "delegate", "delegate_status", "profile_writer"];
|
|
2
|
+
export declare const CLASSIFIED_LANE_TOOL_NAMES: readonly ["read", "grep", "find", "ls", "write", "edit", "memory", "run_process", "bash", "powershell"];
|
|
3
|
+
export declare const ORCHESTRATION_PROFILE_TOOL_NAMES: readonly ["read", "grep", "find", "ls", "write", "edit", "memory", "run_process", "bash", "powershell", "delegate", "delegate_status", "profile_writer"];
|
|
4
4
|
/**
|
|
5
5
|
* Manifest-only lane catalogue. It contains no tool factories, so policy compilation can omit
|
|
6
6
|
* denied tools before their executable implementations are constructed.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lane-tool-manifests.d.ts","sourceRoot":"","sources":["../../../src/core/orchestration/lane-tool-manifests.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"lane-tool-manifests.d.ts","sourceRoot":"","sources":["../../../src/core/orchestration/lane-tool-manifests.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AAEnF,eAAO,MAAM,0BAA0B,YACtC,MAAM,EACN,MAAM,EACN,MAAM,EACN,IAAI,EACJ,OAAO,EACP,MAAM,EACN,QAAQ,EACR,aAAa,EACb,MAAM,EACN,YAAY,CACH,CAAC;AACX,eAAO,MAAM,gCAAgC,0JAKnC,CAAC;AAEX;;;GAGG;AACH,wBAAgB,sBAAsB,CACrC,OAAO,EAAE,oBAAoB,EAC7B,gBAAgB,EAAE,SAAS,MAAM,EAAE,GACjC,sBAAsB,EAAE,CAkB1B"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { mapToolNamesForPlatform } from "../default-tool-surface.js";
|
|
1
2
|
import { getToolCapabilityPolicy, resolveProfileToolCapability } from "../tool-capability-policy.js";
|
|
2
3
|
export const CLASSIFIED_LANE_TOOL_NAMES = [
|
|
3
4
|
"read",
|
|
@@ -8,6 +9,8 @@ export const CLASSIFIED_LANE_TOOL_NAMES = [
|
|
|
8
9
|
"edit",
|
|
9
10
|
"memory",
|
|
10
11
|
"run_process",
|
|
12
|
+
"bash",
|
|
13
|
+
"powershell",
|
|
11
14
|
];
|
|
12
15
|
export const ORCHESTRATION_PROFILE_TOOL_NAMES = [
|
|
13
16
|
...CLASSIFIED_LANE_TOOL_NAMES,
|
|
@@ -22,7 +25,7 @@ export const ORCHESTRATION_PROFILE_TOOL_NAMES = [
|
|
|
22
25
|
export function buildLaneToolManifests(profile, enabledToolNames) {
|
|
23
26
|
const enabled = new Set(enabledToolNames);
|
|
24
27
|
const manifests = [];
|
|
25
|
-
for (const toolName of profile.toolNames) {
|
|
28
|
+
for (const toolName of new Set(mapToolNamesForPlatform(profile.toolNames))) {
|
|
26
29
|
if (!enabled.has(toolName))
|
|
27
30
|
continue;
|
|
28
31
|
const policy = getToolCapabilityPolicy(toolName);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lane-tool-manifests.js","sourceRoot":"","sources":["../../../src/core/orchestration/lane-tool-manifests.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,4BAA4B,EAAE,MAAM,8BAA8B,CAAC;AAGrG,MAAM,CAAC,MAAM,0BAA0B,GAAG;IACzC,MAAM;IACN,MAAM;IACN,MAAM;IACN,IAAI;IACJ,OAAO;IACP,MAAM;IACN,QAAQ;IACR,aAAa;
|
|
1
|
+
{"version":3,"file":"lane-tool-manifests.js","sourceRoot":"","sources":["../../../src/core/orchestration/lane-tool-manifests.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,4BAA4B,EAAE,MAAM,8BAA8B,CAAC;AAGrG,MAAM,CAAC,MAAM,0BAA0B,GAAG;IACzC,MAAM;IACN,MAAM;IACN,MAAM;IACN,IAAI;IACJ,OAAO;IACP,MAAM;IACN,QAAQ;IACR,aAAa;IACb,MAAM;IACN,YAAY;CACH,CAAC;AACX,MAAM,CAAC,MAAM,gCAAgC,GAAG;IAC/C,GAAG,0BAA0B;IAC7B,UAAU;IACV,iBAAiB;IACjB,gBAAgB;CACP,CAAC;AAEX;;;GAGG;AACH,MAAM,UAAU,sBAAsB,CACrC,OAA6B,EAC7B,gBAAmC;IAEnC,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,gBAAgB,CAAC,CAAC;IAC1C,MAAM,SAAS,GAA6B,EAAE,CAAC;IAE/C,KAAK,MAAM,QAAQ,IAAI,IAAI,GAAG,CAAC,uBAAuB,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC;QAC5E,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC;YAAE,SAAS;QACrC,MAAM,MAAM,GAAG,uBAAuB,CAAC,QAAQ,CAAC,CAAC;QACjD,MAAM,UAAU,GAAG,4BAA4B,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACnE,IAAI,CAAC,UAAU,IAAI,CAAC,MAAM;YAAE,SAAS;QACrC,SAAS,CAAC,IAAI,CAAC;YACd,QAAQ;YACR,eAAe,EAAE,YAAY,QAAQ,KAAK;YAC1C,YAAY,EAAE,CAAC,UAAU,CAAC;YAC1B,KAAK,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC;YACrB,YAAY,EAAE,CAAC,MAAM,CAAC,WAAW,CAAC;SAClC,CAAC,CAAC;IACJ,CAAC;IACD,OAAO,SAAS,CAAC;AAClB,CAAC","sourcesContent":["import { mapToolNamesForPlatform } from \"../default-tool-surface.ts\";\nimport { getToolCapabilityPolicy, resolveProfileToolCapability } from \"../tool-capability-policy.ts\";\nimport type { OrchestrationProfile, ToolCapabilityManifest } from \"./contracts.ts\";\n\nexport const CLASSIFIED_LANE_TOOL_NAMES = [\n\t\"read\",\n\t\"grep\",\n\t\"find\",\n\t\"ls\",\n\t\"write\",\n\t\"edit\",\n\t\"memory\",\n\t\"run_process\",\n\t\"bash\",\n\t\"powershell\",\n] as const;\nexport const ORCHESTRATION_PROFILE_TOOL_NAMES = [\n\t...CLASSIFIED_LANE_TOOL_NAMES,\n\t\"delegate\",\n\t\"delegate_status\",\n\t\"profile_writer\",\n] as const;\n\n/**\n * Manifest-only lane catalogue. It contains no tool factories, so policy compilation can omit\n * denied tools before their executable implementations are constructed.\n */\nexport function buildLaneToolManifests(\n\tprofile: OrchestrationProfile,\n\tenabledToolNames: readonly string[],\n): ToolCapabilityManifest[] {\n\tconst enabled = new Set(enabledToolNames);\n\tconst manifests: ToolCapabilityManifest[] = [];\n\n\tfor (const toolName of new Set(mapToolNamesForPlatform(profile.toolNames))) {\n\t\tif (!enabled.has(toolName)) continue;\n\t\tconst policy = getToolCapabilityPolicy(toolName);\n\t\tconst capability = resolveProfileToolCapability(profile, toolName);\n\t\tif (!capability || !policy) continue;\n\t\tmanifests.push({\n\t\t\ttoolName,\n\t\t\tmoduleSpecifier: `../tools/${toolName}.ts`,\n\t\t\tcapabilities: [capability],\n\t\t\troles: [profile.role],\n\t\t\tenforcements: [policy.enforcement],\n\t\t});\n\t}\n\treturn manifests;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"policy-compiler.d.ts","sourceRoot":"","sources":["../../../src/core/orchestration/policy-compiler.ts"],"names":[],"mappings":"AACA,OAAO,EACN,KAAK,uBAAuB,EAC5B,KAAK,kBAAkB,EACvB,KAAK,cAAc,
|
|
1
|
+
{"version":3,"file":"policy-compiler.d.ts","sourceRoot":"","sources":["../../../src/core/orchestration/policy-compiler.ts"],"names":[],"mappings":"AACA,OAAO,EACN,KAAK,uBAAuB,EAC5B,KAAK,kBAAkB,EACvB,KAAK,cAAc,EAEnB,KAAK,iBAAiB,EAEtB,KAAK,eAAe,EACpB,KAAK,UAAU,EACf,KAAK,sBAAsB,EAC3B,KAAK,UAAU,EACf,MAAM,gBAAgB,CAAC;AAGxB,eAAO,MAAM,gCAAgC,EAAE,QAAQ,CAAC,MAAM,CAAC,UAAU,EAAE,SAAS,iBAAiB,EAAE,CAAC,CAQvG,CAAC;AAEF,MAAM,WAAW,0BAA0B;IAC1C,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,UAAU,CAAC;IACjB,oBAAoB,EAAE,SAAS,iBAAiB,EAAE,CAAC;IACnD,qBAAqB,CAAC,EAAE,SAAS,iBAAiB,EAAE,CAAC;IAC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