@saturn-universe/runtime-host 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/LICENSE +661 -0
  2. package/dist/builtin-plugins/saturn-plugin-ctf/README.md +13 -0
  3. package/dist/builtin-plugins/saturn-plugin-ctf/index.mjs +1473 -0
  4. package/dist/builtin-plugins/saturn-plugin-ctf/package.json +10 -0
  5. package/dist/builtin-plugins/saturn-plugin-ctf/src/board.mjs +321 -0
  6. package/dist/builtin-plugins/saturn-plugin-ctf/src/ledger.mjs +1143 -0
  7. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/ctfd.mjs +154 -0
  8. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/ctfplus.mjs +769 -0
  9. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/gzctf.mjs +130 -0
  10. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/http.mjs +336 -0
  11. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/index.mjs +133 -0
  12. package/dist/builtin-plugins/saturn-plugin-ctf/src/platform/lease.mjs +153 -0
  13. package/dist/builtin-plugins/saturn-plugin-ctf/src/server.mjs +336 -0
  14. package/dist/builtin-plugins/saturn-plugin-ctf/src/view.mjs +714 -0
  15. package/dist/command-dispatch.d.ts +10 -0
  16. package/dist/command-dispatch.js +65 -0
  17. package/dist/completion-judge.d.ts +10 -0
  18. package/dist/completion-judge.js +156 -0
  19. package/dist/composition.d.ts +108 -0
  20. package/dist/composition.js +1180 -0
  21. package/dist/configuration.d.ts +49 -0
  22. package/dist/configuration.js +51 -0
  23. package/dist/context-extensions.d.ts +681 -0
  24. package/dist/context-extensions.js +289 -0
  25. package/dist/cordis/context-core-plugin.d.ts +35 -0
  26. package/dist/cordis/context-core-plugin.js +296 -0
  27. package/dist/cordis/env-probe-plugin.d.ts +27 -0
  28. package/dist/cordis/env-probe-plugin.js +114 -0
  29. package/dist/cordis/host-context.d.ts +65 -0
  30. package/dist/cordis/host-context.js +199 -0
  31. package/dist/cordis/model-responses-plugin.d.ts +81 -0
  32. package/dist/cordis/model-responses-plugin.js +209 -0
  33. package/dist/cordis/plugin-contributions.d.ts +47 -0
  34. package/dist/cordis/plugin-contributions.js +119 -0
  35. package/dist/cordis/plugin-lifecycle.d.ts +57 -0
  36. package/dist/cordis/plugin-lifecycle.js +222 -0
  37. package/dist/cordis/plugin-loader.d.ts +18 -0
  38. package/dist/cordis/plugin-loader.js +310 -0
  39. package/dist/cordis/plugin-sdk-adapter.d.ts +17 -0
  40. package/dist/cordis/plugin-sdk-adapter.js +283 -0
  41. package/dist/cordis/required-host-plugin.d.ts +6 -0
  42. package/dist/cordis/required-host-plugin.js +1 -0
  43. package/dist/cordis/runtime-hooks-plugin.d.ts +23 -0
  44. package/dist/cordis/runtime-hooks-plugin.js +103 -0
  45. package/dist/cordis/sandbox-plugin.d.ts +18 -0
  46. package/dist/cordis/sandbox-plugin.js +21 -0
  47. package/dist/cordis/scoped-layers.d.ts +63 -0
  48. package/dist/cordis/scoped-layers.js +170 -0
  49. package/dist/cordis/tools/builtin-agent-tools-plugin.d.ts +11 -0
  50. package/dist/cordis/tools/builtin-agent-tools-plugin.js +171 -0
  51. package/dist/cordis/tools/index.d.ts +17 -0
  52. package/dist/cordis/tools/index.js +40 -0
  53. package/dist/cordis/tools/mcp-tools-plugin.d.ts +7 -0
  54. package/dist/cordis/tools/mcp-tools-plugin.js +116 -0
  55. package/dist/cordis/tools/process-manager-plugin.d.ts +11 -0
  56. package/dist/cordis/tools/process-manager-plugin.js +39 -0
  57. package/dist/cordis/tools/sandbox-target-tools-plugin.d.ts +13 -0
  58. package/dist/cordis/tools/sandbox-target-tools-plugin.js +255 -0
  59. package/dist/cordis/tools/tool-guidance.d.ts +4 -0
  60. package/dist/cordis/tools/tool-guidance.js +30 -0
  61. package/dist/cordis/tools/tools-core-plugin.d.ts +128 -0
  62. package/dist/cordis/tools/tools-core-plugin.js +486 -0
  63. package/dist/cordis/tools/web-fetch.d.ts +17 -0
  64. package/dist/cordis/tools/web-fetch.js +529 -0
  65. package/dist/cordis/tools/web-search-tools-plugin.d.ts +10 -0
  66. package/dist/cordis/tools/web-search-tools-plugin.js +191 -0
  67. package/dist/cordis/tools/workspace-tools-plugin.d.ts +8 -0
  68. package/dist/cordis/tools/workspace-tools-plugin.js +145 -0
  69. package/dist/env-probe.d.ts +8 -0
  70. package/dist/env-probe.js +172 -0
  71. package/dist/host-configuration.d.ts +27 -0
  72. package/dist/host-configuration.js +185 -0
  73. package/dist/host-tools.d.ts +19 -0
  74. package/dist/host-tools.js +30 -0
  75. package/dist/index.d.ts +2 -0
  76. package/dist/index.js +140 -0
  77. package/dist/ipc.d.ts +24 -0
  78. package/dist/ipc.js +162 -0
  79. package/dist/logger.d.ts +11 -0
  80. package/dist/logger.js +84 -0
  81. package/dist/mcp-configuration.d.ts +17 -0
  82. package/dist/mcp-configuration.js +50 -0
  83. package/dist/modes.d.ts +27 -0
  84. package/dist/modes.js +478 -0
  85. package/dist/ownership.d.ts +7 -0
  86. package/dist/ownership.js +100 -0
  87. package/dist/plugin-configuration.d.ts +9 -0
  88. package/dist/plugin-configuration.js +21 -0
  89. package/dist/plugin-tool-grants.d.ts +18 -0
  90. package/dist/plugin-tool-grants.js +21 -0
  91. package/dist/process-workspaces.d.ts +4 -0
  92. package/dist/process-workspaces.js +28 -0
  93. package/dist/progress.d.ts +30 -0
  94. package/dist/progress.js +699 -0
  95. package/dist/provider-catalog.d.ts +754 -0
  96. package/dist/provider-catalog.js +472 -0
  97. package/dist/run-budget.d.ts +24 -0
  98. package/dist/run-budget.js +47 -0
  99. package/dist/run-checkpoint.d.ts +2 -0
  100. package/dist/run-checkpoint.js +52 -0
  101. package/dist/sandbox-manager.d.ts +111 -0
  102. package/dist/sandbox-manager.js +1519 -0
  103. package/dist/session-paths.d.ts +15 -0
  104. package/dist/session-paths.js +40 -0
  105. package/dist/side-question.d.ts +14 -0
  106. package/dist/side-question.js +89 -0
  107. package/dist/skills-runtime.d.ts +13 -0
  108. package/dist/skills-runtime.js +243 -0
  109. package/dist/token-estimator.d.ts +3 -0
  110. package/dist/token-estimator.js +73 -0
  111. package/dist/tool-result.d.ts +2 -0
  112. package/dist/tool-result.js +91 -0
  113. package/dist/user-config.d.ts +23 -0
  114. package/dist/user-config.js +36 -0
  115. package/package.json +28 -3
  116. package/README.md +0 -3
@@ -0,0 +1,1143 @@
1
+ import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+
4
+ export const DEFAULT_LEDGER_MAX_BYTES = 6144;
5
+
6
+ const FACT_CATEGORIES = new Set(['target', 'mitigation', 'primitive', 'offset', 'asset', 'endpoint']);
7
+ const FACT_CONFIDENCES = new Set(['verified', 'inferred']);
8
+ const HYPOTHESIS_STATUSES = new Set(['open', 'testing', 'verified', 'falsified']);
9
+ const PLUGIN_SOURCE = { kind: 'plugin', sourceId: 'security' };
10
+ const MAX_CACHED_TURN_SNAPSHOTS = 256;
11
+ const TRUNCATION_NOTE =
12
+ 'Note: Older or lower-priority entries were truncated to fit ledger_max_bytes. Call security_query_ledger for the complete ledger.';
13
+
14
+ export function sanitizeRunId(runId) {
15
+ const raw = typeof runId === 'string' ? runId.trim() : '';
16
+ if (!raw) return 'unknown';
17
+ const cleaned = raw.replace(/[^a-zA-Z0-9._-]/g, '_').replace(/\.\.+/g, '_');
18
+ if (!cleaned || cleaned === '.' || cleaned === '..') return 'unknown';
19
+ return cleaned;
20
+ }
21
+
22
+ function isPlainObject(value) {
23
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
24
+ }
25
+
26
+ function nonEmptyTrimmed(value) {
27
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
28
+ }
29
+
30
+ function resolveAuthorRole(input, context) {
31
+ const explicit = nonEmptyTrimmed(input?.author_role);
32
+ if (explicit) return explicit;
33
+ const agentId = nonEmptyTrimmed(context?.agentId);
34
+ return agentId ?? 'unknown';
35
+ }
36
+
37
+ function escapeField(value) {
38
+ return String(value ?? '')
39
+ .replaceAll('&', '&')
40
+ .replaceAll('<', '&lt;')
41
+ .replaceAll('>', '&gt;')
42
+ .replace(/[\r\n]+/g, ' ')
43
+ .trim();
44
+ }
45
+
46
+ function utf8Bytes(text) {
47
+ return Buffer.byteLength(text, 'utf8');
48
+ }
49
+
50
+ function sliceUtf8Bytes(text, maxBytes) {
51
+ if (maxBytes <= 0) return '';
52
+ if (utf8Bytes(text) <= maxBytes) return text;
53
+ let end = Math.min(text.length, maxBytes);
54
+ while (end > 0 && utf8Bytes(text.slice(0, end)) > maxBytes) {
55
+ end -= 1;
56
+ }
57
+ return text.slice(0, end);
58
+ }
59
+
60
+ function clipLineToBytes(line, maxBytes) {
61
+ if (utf8Bytes(line) <= maxBytes) return line;
62
+ if (maxBytes <= 3) return sliceUtf8Bytes(line, maxBytes);
63
+ return `${sliceUtf8Bytes(line, maxBytes - 3)}...`;
64
+ }
65
+
66
+ function isValidRecord(record) {
67
+ if (!isPlainObject(record) || typeof record.type !== 'string') return false;
68
+ if (record.type === 'fact') {
69
+ return (
70
+ typeof record.id === 'string' &&
71
+ FACT_CATEGORIES.has(record.category) &&
72
+ typeof record.summary === 'string' &&
73
+ typeof record.evidence === 'string' &&
74
+ FACT_CONFIDENCES.has(record.confidence) &&
75
+ typeof record.authorRole === 'string' &&
76
+ typeof record.recordedAt === 'string'
77
+ );
78
+ }
79
+ if (record.type === 'hypothesis') {
80
+ return (
81
+ typeof record.id === 'string' &&
82
+ typeof record.title === 'string' &&
83
+ typeof record.transition === 'string' &&
84
+ HYPOTHESIS_STATUSES.has(record.status) &&
85
+ (record.outcome === undefined || typeof record.outcome === 'string') &&
86
+ (record.evidence === undefined || typeof record.evidence === 'string') &&
87
+ typeof record.authorRole === 'string' &&
88
+ typeof record.recordedAt === 'string'
89
+ );
90
+ }
91
+ if (record.type === 'skill_unlocked') {
92
+ return (
93
+ typeof record.skill === 'string' &&
94
+ typeof record.authorRole === 'string' &&
95
+ typeof record.recordedAt === 'string'
96
+ );
97
+ }
98
+ if (record.type === 'inherited_from') {
99
+ return typeof record.sourceRunId === 'string' && typeof record.recordedAt === 'string';
100
+ }
101
+ return false;
102
+ }
103
+
104
+ function createEmptyState() {
105
+ return {
106
+ facts: new Map(),
107
+ hypotheses: new Map(),
108
+ unlockedSkills: new Map(),
109
+ nextFactSeq: 1,
110
+ nextHypothesisSeq: 1,
111
+ needsLeadingNewline: false,
112
+ inheritanceChecked: false,
113
+ };
114
+ }
115
+
116
+ function allocateNextFactId(state) {
117
+ while (state.facts.has(`F${state.nextFactSeq}`)) {
118
+ state.nextFactSeq += 1;
119
+ }
120
+ return `F${state.nextFactSeq}`;
121
+ }
122
+
123
+ function allocateNextHypothesisId(state) {
124
+ while (state.hypotheses.has(`H${state.nextHypothesisSeq}`)) {
125
+ state.nextHypothesisSeq += 1;
126
+ }
127
+ return `H${state.nextHypothesisSeq}`;
128
+ }
129
+
130
+ function applyRecord(state, record) {
131
+ if (record.type === 'fact') {
132
+ state.facts.delete(record.id);
133
+ state.facts.set(record.id, record);
134
+ const match = /^F(\d+)$/.exec(record.id);
135
+ if (match) {
136
+ const seq = Number(match[1]) + 1;
137
+ if (seq > state.nextFactSeq) state.nextFactSeq = seq;
138
+ }
139
+ return;
140
+ }
141
+ if (record.type === 'hypothesis') {
142
+ state.hypotheses.delete(record.id);
143
+ state.hypotheses.set(record.id, record);
144
+ const match = /^H(\d+)$/.exec(record.id);
145
+ if (match) {
146
+ const seq = Number(match[1]) + 1;
147
+ if (seq > state.nextHypothesisSeq) state.nextHypothesisSeq = seq;
148
+ }
149
+ return;
150
+ }
151
+ if (record.type === 'skill_unlocked') {
152
+ if (!state.unlockedSkills.has(record.skill)) {
153
+ state.unlockedSkills.set(record.skill, record);
154
+ }
155
+ }
156
+ }
157
+
158
+ function formatFactLine(fact) {
159
+ const parts = [`- [${escapeField(fact.id)}] (${escapeField(fact.category)}) ${escapeField(fact.summary)}`];
160
+ if (fact.evidence) parts.push(`evidence: ${escapeField(fact.evidence)}`);
161
+ return parts.join(' | ');
162
+ }
163
+
164
+ function formatHypothesisLine(hypothesis) {
165
+ const parts = [
166
+ `- [${escapeField(hypothesis.id)}] (${escapeField(hypothesis.status)}) ${escapeField(hypothesis.title)}`,
167
+ `transition: ${escapeField(hypothesis.transition)}`,
168
+ ];
169
+ if (hypothesis.outcome) parts.push(`outcome: ${escapeField(hypothesis.outcome)}`);
170
+ if (hypothesis.evidence) parts.push(`evidence: ${escapeField(hypothesis.evidence)}`);
171
+ return parts.join(' | ');
172
+ }
173
+
174
+ function formatSkillLine(record) {
175
+ return `- ${escapeField(record.skill)} (unlocked by ${escapeField(record.authorRole)})`;
176
+ }
177
+
178
+ function composeLedgerXml(sections, truncated) {
179
+ const lines = ['<security_fact_ledger>'];
180
+ for (const section of sections) {
181
+ if (!section.items.length) continue;
182
+ lines.push(section.header);
183
+ for (const item of section.items) lines.push(item);
184
+ }
185
+ if (truncated) lines.push(TRUNCATION_NOTE);
186
+ lines.push('</security_fact_ledger>');
187
+ return lines.join('\n');
188
+ }
189
+
190
+ export function renderLedgerXml(state, maxBytes = DEFAULT_LEDGER_MAX_BYTES) {
191
+ const facts = [...state.facts.values()];
192
+ const hypotheses = [...state.hypotheses.values()];
193
+ const unlockedSkills = [...state.unlockedSkills.values()];
194
+
195
+ if (facts.length === 0 && hypotheses.length === 0 && unlockedSkills.length === 0) {
196
+ return '';
197
+ }
198
+
199
+ const verifiedFacts = facts.filter((f) => f.confidence === 'verified').map(formatFactLine);
200
+ const inferredFacts = facts.filter((f) => f.confidence === 'inferred').map(formatFactLine);
201
+ const falsifiedHypotheses = hypotheses.filter((h) => h.status === 'falsified').map(formatHypothesisLine);
202
+ const otherHypotheses = hypotheses.filter((h) => h.status !== 'falsified').map(formatHypothesisLine);
203
+ const skillLines = unlockedSkills.map(formatSkillLine);
204
+
205
+ const fullSections = [
206
+ { header: 'Verified Facts:', items: verifiedFacts },
207
+ { header: 'Falsified Hypotheses (do not repeat):', items: falsifiedHypotheses },
208
+ { header: 'Unlocked Skills:', items: skillLines },
209
+ { header: 'Other Hypotheses:', items: otherHypotheses },
210
+ { header: 'Inferred Facts:', items: inferredFacts },
211
+ ];
212
+
213
+ const fullRendered = composeLedgerXml(fullSections, false);
214
+ if (utf8Bytes(fullRendered) <= maxBytes) {
215
+ return fullRendered;
216
+ }
217
+
218
+ // Budget exceeded: prioritize Verified Facts and Falsified Hypotheses (newest kept first),
219
+ // then remaining sections if room permits, always strictly <= maxBytes.
220
+ const openTag = '<security_fact_ledger>';
221
+ const closeTag = '</security_fact_ledger>';
222
+ const minEnvelope = `${openTag}\n${TRUNCATION_NOTE}\n${closeTag}`;
223
+ if (utf8Bytes(minEnvelope) >= maxBytes) {
224
+ const bare = `${openTag}\n${closeTag}`;
225
+ if (utf8Bytes(bare) >= maxBytes) {
226
+ return sliceUtf8Bytes(bare, maxBytes);
227
+ }
228
+ const innerBudget = maxBytes - utf8Bytes(bare) - 1;
229
+ const clippedNote = clipLineToBytes(TRUNCATION_NOTE, Math.max(0, innerBudget));
230
+ return clippedNote ? `${openTag}\n${clippedNote}\n${closeTag}` : bare;
231
+ }
232
+
233
+ const kept = {
234
+ verifiedFacts: [],
235
+ falsifiedHypotheses: [],
236
+ skillLines: [],
237
+ otherHypotheses: [],
238
+ inferredFacts: [],
239
+ };
240
+
241
+ const buildCurrent = () =>
242
+ composeLedgerXml(
243
+ [
244
+ { header: 'Verified Facts:', items: [...kept.verifiedFacts].reverse() },
245
+ { header: 'Falsified Hypotheses (do not repeat):', items: [...kept.falsifiedHypotheses].reverse() },
246
+ { header: 'Unlocked Skills:', items: [...kept.skillLines].reverse() },
247
+ { header: 'Other Hypotheses:', items: [...kept.otherHypotheses].reverse() },
248
+ { header: 'Inferred Facts:', items: [...kept.inferredFacts].reverse() },
249
+ ],
250
+ true,
251
+ );
252
+
253
+ const tryAdd = (bucketKey, line, allowClip) => {
254
+ const bucket = kept[bucketKey];
255
+ bucket.push(line);
256
+ if (utf8Bytes(buildCurrent()) <= maxBytes) return true;
257
+ bucket.pop();
258
+ if (!allowClip) return false;
259
+
260
+ const baselineBytes = utf8Bytes(buildCurrent());
261
+ // Account for header line if this is the first item in the bucket plus newline(s).
262
+ bucket.push('');
263
+ const emptyLineOverhead = utf8Bytes(buildCurrent()) - baselineBytes;
264
+ bucket.pop();
265
+ const availableForLine = maxBytes - baselineBytes - emptyLineOverhead;
266
+ if (availableForLine < 16) return false;
267
+
268
+ const clipped = clipLineToBytes(line, availableForLine);
269
+ if (!clipped) return false;
270
+ bucket.push(clipped);
271
+ if (utf8Bytes(buildCurrent()) <= maxBytes) return true;
272
+ bucket.pop();
273
+ return false;
274
+ };
275
+
276
+ // Tier 1: interleave newest Verified Facts and newest Falsified Hypotheses so neither starves the other.
277
+ const vfNewest = [...verifiedFacts].reverse();
278
+ const fhNewest = [...falsifiedHypotheses].reverse();
279
+ const tier1Max = Math.max(vfNewest.length, fhNewest.length);
280
+ let tier1Dropped = false;
281
+ for (let i = 0; i < tier1Max; i += 1) {
282
+ if (i < vfNewest.length) {
283
+ if (!tryAdd('verifiedFacts', vfNewest[i], kept.verifiedFacts.length === 0)) {
284
+ tier1Dropped = true;
285
+ }
286
+ }
287
+ if (i < fhNewest.length) {
288
+ if (!tryAdd('falsifiedHypotheses', fhNewest[i], kept.falsifiedHypotheses.length === 0)) {
289
+ tier1Dropped = true;
290
+ }
291
+ }
292
+ }
293
+
294
+ // Tier 2: only add lower-priority sections if Tier 1 fit completely or space remains.
295
+ if (!tier1Dropped) {
296
+ for (const [key, source] of [
297
+ ['skillLines', [...skillLines].reverse()],
298
+ ['otherHypotheses', [...otherHypotheses].reverse()],
299
+ ['inferredFacts', [...inferredFacts].reverse()],
300
+ ]) {
301
+ for (const line of source) {
302
+ if (!tryAdd(key, line, kept[key].length === 0)) break;
303
+ }
304
+ }
305
+ }
306
+
307
+ const finalOutput = buildCurrent();
308
+ return utf8Bytes(finalOutput) <= maxBytes ? finalOutput : sliceUtf8Bytes(finalOutput, maxBytes);
309
+ }
310
+
311
+ function findActiveTurnBlock(input) {
312
+ const surface = input?.state?.surface;
313
+ if (!surface || !Array.isArray(surface.continuations) || !Array.isArray(surface.items)) return undefined;
314
+ const activeMessages = new Map();
315
+ for (const item of surface.items) {
316
+ if (item?.active && item.message?.id) {
317
+ activeMessages.set(item.message.id, item.message);
318
+ }
319
+ }
320
+ let latest;
321
+ for (const block of surface.continuations) {
322
+ if (!block?.active) continue;
323
+ const message = activeMessages.get(block.assistantMessageId);
324
+ if (message && message.turnId === input.turnId) {
325
+ latest = block;
326
+ }
327
+ }
328
+ return latest;
329
+ }
330
+
331
+ function extractLedgerFromContinuationBlock(block, surface) {
332
+ const candidates = [
333
+ block,
334
+ ...(Array.isArray(surface?.continuations) && block?.state?.epochId
335
+ ? surface.continuations.filter(
336
+ (candidate) =>
337
+ candidate !== block && candidate?.active && candidate?.state?.epochId === block.state.epochId,
338
+ )
339
+ : []),
340
+ ];
341
+ for (const candidate of candidates) {
342
+ const fullInput = candidate?.requestPlan?.fullInput;
343
+ if (Array.isArray(fullInput)) {
344
+ for (const item of fullInput) {
345
+ if (item?.type !== 'message' || item.role !== 'user' || !Array.isArray(item.content)) continue;
346
+ for (const part of item.content) {
347
+ const text = typeof part?.text === 'string' ? part.text : '';
348
+ const match = /<security_fact_ledger>[\s\S]*?<\/security_fact_ledger>/.exec(text);
349
+ if (match) return match[0];
350
+ }
351
+ }
352
+ }
353
+ const initialBackground = candidate?.requestPlan?.initialBackground;
354
+ if (Array.isArray(initialBackground)) {
355
+ for (const msg of initialBackground) {
356
+ if (msg?.role !== 'user' || !Array.isArray(msg.content)) continue;
357
+ for (const part of msg.content) {
358
+ const text = typeof part?.text === 'string' ? part.text : '';
359
+ const match = /<security_fact_ledger>[\s\S]*?<\/security_fact_ledger>/.exec(text);
360
+ if (match) return match[0];
361
+ }
362
+ }
363
+ }
364
+ }
365
+ return '';
366
+ }
367
+
368
+ function errorObservation(code, message) {
369
+ return {
370
+ effect: 'none',
371
+ outcome: {
372
+ status: 'error',
373
+ error: { code, message, retryable: false },
374
+ },
375
+ };
376
+ }
377
+
378
+ export function createLedgerController({
379
+ workspaceRoot,
380
+ logger,
381
+ maxBytes = DEFAULT_LEDGER_MAX_BYTES,
382
+ ledgerDir = path.join(workspaceRoot, '.saturn', 'plugins', 'security'),
383
+ resolveLedgerDir,
384
+ filenameFor = (id) => `ledger-${id}.jsonl`,
385
+ keyFor = sanitizeRunId,
386
+ sanitizeRecord = (record) => record,
387
+ }) {
388
+ const states = new Map();
389
+ const pendingLoads = new Map();
390
+ const writeChains = new Map();
391
+ const turnSnapshots = new Map();
392
+ const runLedgerDirs = new Map();
393
+ let disposed = false;
394
+
395
+ function effectiveLedgerDir(runId, context) {
396
+ if (context && resolveLedgerDir) {
397
+ const resolved = resolveLedgerDir(context);
398
+ if (resolved) {
399
+ runLedgerDirs.set(runId, resolved);
400
+ return resolved;
401
+ }
402
+ }
403
+ return runLedgerDirs.get(runId) ?? ledgerDir;
404
+ }
405
+
406
+ function ledgerPathFor(runId, context) {
407
+ return path.join(effectiveLedgerDir(runId, context), filenameFor(keyFor(runId)));
408
+ }
409
+
410
+ function legacyLedgerPathFor(runId) {
411
+ return path.join(ledgerDir, filenameFor(keyFor(runId)));
412
+ }
413
+
414
+ function parseRawIntoState(raw, runId, state) {
415
+ if (raw.length > 0 && !raw.endsWith('\n')) {
416
+ state.needsLeadingNewline = true;
417
+ }
418
+
419
+ const lines = raw.split(/\r?\n/);
420
+ let validCount = 0;
421
+ for (let index = 0; index < lines.length; index += 1) {
422
+ const line = lines[index].trim();
423
+ if (!line) continue;
424
+ let parsed;
425
+ try {
426
+ parsed = JSON.parse(line);
427
+ } catch {
428
+ logger.error(
429
+ { code: 'SECURITY_LEDGER_CORRUPT_LINE', runId, lineNumber: index + 1 },
430
+ 'Skipped corrupted JSONL line in security ledger',
431
+ );
432
+ continue;
433
+ }
434
+ if (!isValidRecord(parsed)) {
435
+ logger.error(
436
+ { code: 'SECURITY_LEDGER_CORRUPT_LINE', runId, lineNumber: index + 1 },
437
+ 'Skipped malformed record in security ledger',
438
+ );
439
+ continue;
440
+ }
441
+ applyRecord(state, parsed);
442
+ if (parsed.type !== 'inherited_from') validCount += 1;
443
+ }
444
+ return validCount;
445
+ }
446
+
447
+ async function tryInheritFromSource(runId, sourceRunId, state) {
448
+ const sourcePath = ledgerPathFor(sourceRunId);
449
+ let sourceRaw;
450
+ try {
451
+ sourceRaw = await readFile(sourcePath, 'utf8');
452
+ } catch (error) {
453
+ if (error?.code === 'ENOENT') {
454
+ logger.info(
455
+ { code: 'SECURITY_LEDGER_INHERIT_SOURCE_MISSING', runId, sourceRunId },
456
+ 'Checkpoint source security ledger does not exist; starting with empty ledger',
457
+ );
458
+ } else {
459
+ logger.error(
460
+ {
461
+ code: 'SECURITY_LEDGER_INHERIT_FAILED',
462
+ runId,
463
+ sourceRunId,
464
+ reason: String(error?.message ?? error),
465
+ },
466
+ 'Failed to read checkpoint source security ledger; degrading to empty ledger',
467
+ );
468
+ }
469
+ return;
470
+ }
471
+
472
+ const sourceState = createEmptyState();
473
+ parseRawIntoState(sourceRaw, sourceRunId, sourceState);
474
+ const inheritedEntries = [
475
+ ...sourceState.facts.values(),
476
+ ...sourceState.hypotheses.values(),
477
+ ...sourceState.unlockedSkills.values(),
478
+ ];
479
+ if (inheritedEntries.length === 0) {
480
+ logger.info(
481
+ { code: 'SECURITY_LEDGER_INHERIT_SOURCE_EMPTY', runId, sourceRunId },
482
+ 'Checkpoint source security ledger contained no valid entries; starting with empty ledger',
483
+ );
484
+ return;
485
+ }
486
+
487
+ const auditRecord = {
488
+ type: 'inherited_from',
489
+ sourceRunId,
490
+ recordedAt: new Date().toISOString(),
491
+ };
492
+ const serialized =
493
+ [auditRecord, ...inheritedEntries].map((item) => JSON.stringify(item)).join('\n') + '\n';
494
+ const targetPath = ledgerPathFor(runId);
495
+
496
+ try {
497
+ await mkdir(ledgerDir, { recursive: true });
498
+ await writeFile(targetPath, serialized, { encoding: 'utf8', flag: 'wx' });
499
+ } catch (error) {
500
+ if (error?.code === 'EEXIST') {
501
+ try {
502
+ const existingRaw = await readFile(targetPath, 'utf8');
503
+ parseRawIntoState(existingRaw, runId, state);
504
+ return;
505
+ } catch (readError) {
506
+ logger.error(
507
+ {
508
+ code: 'SECURITY_LEDGER_READ_FAILED',
509
+ runId,
510
+ reason: String(readError?.message ?? readError),
511
+ },
512
+ 'Failed to read existing security ledger file after concurrent inheritance',
513
+ );
514
+ return;
515
+ }
516
+ }
517
+ logger.error(
518
+ {
519
+ code: 'SECURITY_LEDGER_INHERIT_WRITE_FAILED',
520
+ runId,
521
+ sourceRunId,
522
+ reason: String(error?.message ?? error),
523
+ },
524
+ 'Failed to persist inherited security ledger; degrading to empty ledger',
525
+ );
526
+ return;
527
+ }
528
+
529
+ for (const record of inheritedEntries) {
530
+ applyRecord(state, record);
531
+ }
532
+ }
533
+
534
+ async function loadState(runId, options = {}) {
535
+ const context = options?.context;
536
+ const sourceRunId = nonEmptyTrimmed(options?.checkpointSourceRunId);
537
+ const canInherit = Boolean(sourceRunId && sanitizeRunId(sourceRunId) !== sanitizeRunId(runId));
538
+ const cached = states.get(runId);
539
+ if (cached && (!canInherit || cached.inheritanceChecked)) {
540
+ return cached;
541
+ }
542
+
543
+ const pending = pendingLoads.get(runId);
544
+ if (pending) {
545
+ const loaded = await pending;
546
+ if (!canInherit || loaded.inheritanceChecked) return loaded;
547
+ }
548
+
549
+ const task = (async () => {
550
+ const state = cached ?? createEmptyState();
551
+ const filePath = ledgerPathFor(runId, context);
552
+ const legacyPath = legacyLedgerPathFor(runId);
553
+ let raw;
554
+ try {
555
+ raw = await readFile(filePath, 'utf8');
556
+ } catch (error) {
557
+ if (error?.code === 'ENOENT' && filePath !== legacyPath) {
558
+ try {
559
+ raw = await readFile(legacyPath, 'utf8');
560
+ } catch (legacyError) {
561
+ error = legacyError;
562
+ }
563
+ }
564
+ if (raw === undefined) {
565
+ if (error?.code !== 'ENOENT') {
566
+ logger.error(
567
+ { code: 'SECURITY_LEDGER_READ_FAILED', runId, reason: String(error?.message ?? error) },
568
+ 'Failed to read security ledger file',
569
+ );
570
+ state.inheritanceChecked = true;
571
+ states.set(runId, state);
572
+ return state;
573
+ }
574
+ if (canInherit) {
575
+ await tryInheritFromSource(runId, sourceRunId, state);
576
+ state.inheritanceChecked = true;
577
+ }
578
+ states.set(runId, state);
579
+ return state;
580
+ }
581
+ }
582
+
583
+ if (!cached) {
584
+ parseRawIntoState(raw, runId, state);
585
+ }
586
+ state.inheritanceChecked = true;
587
+ states.set(runId, state);
588
+ return state;
589
+ })();
590
+
591
+ pendingLoads.set(runId, task);
592
+ try {
593
+ return await task;
594
+ } finally {
595
+ if (pendingLoads.get(runId) === task) pendingLoads.delete(runId);
596
+ }
597
+ }
598
+
599
+ function enqueueWrite(runId, work) {
600
+ const key = keyFor(runId);
601
+ const previous = writeChains.get(key) ?? Promise.resolve();
602
+ const next = previous.then(work);
603
+ const tail = next.then(
604
+ () => undefined,
605
+ () => undefined,
606
+ );
607
+ writeChains.set(key, tail);
608
+ tail.finally(() => {
609
+ if (writeChains.get(key) === tail) writeChains.delete(key);
610
+ });
611
+ return next;
612
+ }
613
+
614
+ async function appendRecord(runId, buildRecord, options = {}) {
615
+ return enqueueWrite(runId, async () => {
616
+ const targetDir = effectiveLedgerDir(runId, options?.context);
617
+ const targetFile = ledgerPathFor(runId, options?.context);
618
+ const state = await loadState(runId, options);
619
+ const record = sanitizeRecord(buildRecord(state));
620
+ await mkdir(targetDir, { recursive: true });
621
+ const prefix = state.needsLeadingNewline ? '\n' : '';
622
+ await appendFile(targetFile, `${prefix}${JSON.stringify(record)}\n`, 'utf8');
623
+ state.needsLeadingNewline = false;
624
+ state.inheritanceChecked = true;
625
+ applyRecord(state, record);
626
+ return record;
627
+ });
628
+ }
629
+
630
+ async function recordSkillUnlocked({ runId, checkpointSourceRunId, skill, authorRole }) {
631
+ return appendRecord(
632
+ runId,
633
+ () => ({
634
+ type: 'skill_unlocked',
635
+ skill,
636
+ authorRole,
637
+ recordedAt: new Date().toISOString(),
638
+ }),
639
+ { checkpointSourceRunId },
640
+ );
641
+ }
642
+
643
+ function rememberTurnSnapshot(turnKey, text) {
644
+ if (turnSnapshots.size >= MAX_CACHED_TURN_SNAPSHOTS && !turnSnapshots.has(turnKey)) {
645
+ const oldest = turnSnapshots.keys().next().value;
646
+ if (oldest !== undefined) turnSnapshots.delete(oldest);
647
+ }
648
+ turnSnapshots.set(turnKey, text);
649
+ }
650
+
651
+ function register(api) {
652
+ api.registerTool(
653
+ {
654
+ name: 'security_record_fact',
655
+ version: '1',
656
+ description:
657
+ 'Record a verified or inferred security fact in the current Run fact ledger. Omit id when creating a new record so the system auto-assigns a unique ID; only pass id with update=true when intentionally updating an existing record. Verified facts require non-empty empirical evidence.',
658
+ inputSchema: {
659
+ type: 'object',
660
+ properties: {
661
+ id: {
662
+ type: 'string',
663
+ description:
664
+ 'Optional fact ID. Omit when creating a new record (auto-assigned). Pass an existing ID with update=true only when explicitly updating that record.',
665
+ },
666
+ update: {
667
+ type: 'boolean',
668
+ description:
669
+ 'Set to true only when intentionally updating an existing fact with the given id (default false).',
670
+ },
671
+ category: {
672
+ type: 'string',
673
+ enum: ['target', 'mitigation', 'primitive', 'offset', 'asset', 'endpoint'],
674
+ description: 'Fact category.',
675
+ },
676
+ summary: {
677
+ type: 'string',
678
+ description: 'Concise factual summary.',
679
+ },
680
+ evidence: {
681
+ type: 'string',
682
+ description:
683
+ 'Empirical evidence backing the fact. Must be a non-empty string when confidence is "verified".',
684
+ },
685
+ confidence: {
686
+ type: 'string',
687
+ enum: ['verified', 'inferred'],
688
+ description: 'Whether this fact is empirically verified or inferred.',
689
+ },
690
+ author_role: {
691
+ type: 'string',
692
+ description: 'Optional author role label.',
693
+ },
694
+ },
695
+ required: ['category', 'summary', 'confidence'],
696
+ additionalProperties: false,
697
+ },
698
+ source: PLUGIN_SOURCE,
699
+ effects: 'idempotent_write',
700
+ supportsIdempotencyKey: true,
701
+ supportsReconcile: false,
702
+ concurrency: 'serial_per_run',
703
+ timeoutMs: 5000,
704
+ },
705
+ {
706
+ async invoke(input, context) {
707
+ if (!isPlainObject(input)) {
708
+ return errorObservation('INVALID_INPUT', 'Expected an object payload for security_record_fact.');
709
+ }
710
+ const category = input.category;
711
+ if (!FACT_CATEGORIES.has(category)) {
712
+ return errorObservation(
713
+ 'INVALID_INPUT',
714
+ 'category must be one of target, mitigation, primitive, offset, asset, endpoint.',
715
+ );
716
+ }
717
+ const summary = nonEmptyTrimmed(input.summary);
718
+ if (!summary) {
719
+ return errorObservation('INVALID_INPUT', 'summary must be a non-empty string.');
720
+ }
721
+ const confidence = input.confidence;
722
+ if (!FACT_CONFIDENCES.has(confidence)) {
723
+ return errorObservation('INVALID_INPUT', 'confidence must be "verified" or "inferred".');
724
+ }
725
+ if (input.id !== undefined && !nonEmptyTrimmed(input.id)) {
726
+ return errorObservation('INVALID_INPUT', 'id must be a non-empty string when provided.');
727
+ }
728
+ if (input.update !== undefined && typeof input.update !== 'boolean') {
729
+ return errorObservation('INVALID_INPUT', 'update must be a boolean when provided.');
730
+ }
731
+ if (input.evidence !== undefined && typeof input.evidence !== 'string') {
732
+ return errorObservation('INVALID_INPUT', 'evidence must be a string when provided.');
733
+ }
734
+ const evidence = typeof input.evidence === 'string' ? input.evidence.trim() : '';
735
+ if (confidence === 'verified' && evidence.length === 0) {
736
+ return errorObservation(
737
+ 'EVIDENCE_REQUIRED',
738
+ 'Verified facts require a non-empty evidence string.',
739
+ );
740
+ }
741
+
742
+ const explicitId = nonEmptyTrimmed(input.id);
743
+ const allowUpdate = input.update === true;
744
+ const authorRole = resolveAuthorRole(input, context);
745
+ let reassignedFrom;
746
+ const record = await appendRecord(
747
+ context.runId,
748
+ (state) => {
749
+ reassignedFrom = undefined;
750
+ let id;
751
+ if (!explicitId) {
752
+ id = allocateNextFactId(state);
753
+ } else if (state.facts.has(explicitId) && !allowUpdate) {
754
+ id = allocateNextFactId(state);
755
+ reassignedFrom = explicitId;
756
+ } else {
757
+ id = explicitId;
758
+ }
759
+ return {
760
+ type: 'fact',
761
+ id,
762
+ category,
763
+ summary,
764
+ evidence,
765
+ confidence,
766
+ authorRole,
767
+ recordedAt: new Date().toISOString(),
768
+ };
769
+ },
770
+ { checkpointSourceRunId: context?.checkpointSourceRunId, context },
771
+ );
772
+
773
+ const responseData = reassignedFrom ? { ...record, reassignedFrom } : record;
774
+ return {
775
+ effect: 'applied',
776
+ outcome: {
777
+ status: 'success',
778
+ content: [{ type: 'text', text: JSON.stringify(responseData) }],
779
+ data: responseData,
780
+ },
781
+ };
782
+ },
783
+ },
784
+ );
785
+
786
+ api.registerTool(
787
+ {
788
+ name: 'security_record_hypothesis',
789
+ version: '1',
790
+ description:
791
+ 'Record or update a security hypothesis in the current Run ledger. Omit id when creating a new record so the system auto-assigns a unique ID; only pass id with update=true when intentionally updating an existing record. Status "verified" or "falsified" requires non-empty outcome and evidence.',
792
+ inputSchema: {
793
+ type: 'object',
794
+ properties: {
795
+ id: {
796
+ type: 'string',
797
+ description:
798
+ 'Optional hypothesis ID. Omit when creating a new record (auto-assigned). Pass an existing ID with update=true only when explicitly updating that record.',
799
+ },
800
+ update: {
801
+ type: 'boolean',
802
+ description:
803
+ 'Set to true only when intentionally updating an existing hypothesis with the given id (default false).',
804
+ },
805
+ title: {
806
+ type: 'string',
807
+ description: 'Short hypothesis title.',
808
+ },
809
+ transition: {
810
+ type: 'string',
811
+ description: 'State transition or attack step being tested.',
812
+ },
813
+ status: {
814
+ type: 'string',
815
+ enum: ['open', 'testing', 'verified', 'falsified'],
816
+ description: 'Lifecycle status of the hypothesis.',
817
+ },
818
+ outcome: {
819
+ type: 'string',
820
+ description: 'Observed outcome. Required when status is "verified" or "falsified".',
821
+ },
822
+ evidence: {
823
+ type: 'string',
824
+ description: 'Empirical evidence. Required when status is "verified" or "falsified".',
825
+ },
826
+ author_role: {
827
+ type: 'string',
828
+ description: 'Optional author role label.',
829
+ },
830
+ },
831
+ required: ['title', 'transition', 'status'],
832
+ additionalProperties: false,
833
+ },
834
+ source: PLUGIN_SOURCE,
835
+ effects: 'idempotent_write',
836
+ supportsIdempotencyKey: true,
837
+ supportsReconcile: false,
838
+ concurrency: 'serial_per_run',
839
+ timeoutMs: 5000,
840
+ },
841
+ {
842
+ async invoke(input, context) {
843
+ if (!isPlainObject(input)) {
844
+ return errorObservation(
845
+ 'INVALID_INPUT',
846
+ 'Expected an object payload for security_record_hypothesis.',
847
+ );
848
+ }
849
+ const title = nonEmptyTrimmed(input.title);
850
+ if (!title) {
851
+ return errorObservation('INVALID_INPUT', 'title must be a non-empty string.');
852
+ }
853
+ const transition = nonEmptyTrimmed(input.transition);
854
+ if (!transition) {
855
+ return errorObservation('INVALID_INPUT', 'transition must be a non-empty string.');
856
+ }
857
+ const status = input.status;
858
+ if (!HYPOTHESIS_STATUSES.has(status)) {
859
+ return errorObservation(
860
+ 'INVALID_INPUT',
861
+ 'status must be one of open, testing, verified, falsified.',
862
+ );
863
+ }
864
+ if (input.id !== undefined && !nonEmptyTrimmed(input.id)) {
865
+ return errorObservation('INVALID_INPUT', 'id must be a non-empty string when provided.');
866
+ }
867
+ if (input.update !== undefined && typeof input.update !== 'boolean') {
868
+ return errorObservation('INVALID_INPUT', 'update must be a boolean when provided.');
869
+ }
870
+ if (input.outcome !== undefined && typeof input.outcome !== 'string') {
871
+ return errorObservation('INVALID_INPUT', 'outcome must be a string when provided.');
872
+ }
873
+ if (input.evidence !== undefined && typeof input.evidence !== 'string') {
874
+ return errorObservation('INVALID_INPUT', 'evidence must be a string when provided.');
875
+ }
876
+
877
+ const outcome = nonEmptyTrimmed(input.outcome);
878
+ const evidence = nonEmptyTrimmed(input.evidence);
879
+ if ((status === 'verified' || status === 'falsified') && (!outcome || !evidence)) {
880
+ return errorObservation(
881
+ 'EVIDENCE_REQUIRED',
882
+ `Hypotheses with status "${status}" require both non-empty outcome and non-empty evidence.`,
883
+ );
884
+ }
885
+
886
+ const explicitId = nonEmptyTrimmed(input.id);
887
+ const allowUpdate = input.update === true;
888
+ const authorRole = resolveAuthorRole(input, context);
889
+ let reassignedFrom;
890
+ const record = await appendRecord(
891
+ context.runId,
892
+ (state) => {
893
+ reassignedFrom = undefined;
894
+ let id;
895
+ if (!explicitId) {
896
+ id = allocateNextHypothesisId(state);
897
+ } else if (state.hypotheses.has(explicitId) && !allowUpdate) {
898
+ id = allocateNextHypothesisId(state);
899
+ reassignedFrom = explicitId;
900
+ } else {
901
+ id = explicitId;
902
+ }
903
+ return {
904
+ type: 'hypothesis',
905
+ id,
906
+ title,
907
+ transition,
908
+ status,
909
+ ...(outcome ? { outcome } : {}),
910
+ ...(evidence ? { evidence } : {}),
911
+ authorRole,
912
+ recordedAt: new Date().toISOString(),
913
+ };
914
+ },
915
+ { checkpointSourceRunId: context?.checkpointSourceRunId, context },
916
+ );
917
+
918
+ const responseData = reassignedFrom ? { ...record, reassignedFrom } : record;
919
+ return {
920
+ effect: 'applied',
921
+ outcome: {
922
+ status: 'success',
923
+ content: [{ type: 'text', text: JSON.stringify(responseData) }],
924
+ data: responseData,
925
+ },
926
+ };
927
+ },
928
+ },
929
+ );
930
+
931
+ api.registerTool(
932
+ {
933
+ name: 'security_query_ledger',
934
+ version: '1',
935
+ description:
936
+ 'Query the current Run security fact ledger, optionally filtering by category, hypothesis status, or keyword.',
937
+ inputSchema: {
938
+ type: 'object',
939
+ properties: {
940
+ category: {
941
+ type: 'string',
942
+ enum: ['target', 'mitigation', 'primitive', 'offset', 'asset', 'endpoint'],
943
+ description: 'Optional fact category filter.',
944
+ },
945
+ status: {
946
+ type: 'string',
947
+ enum: ['open', 'testing', 'verified', 'falsified'],
948
+ description: 'Optional hypothesis status filter.',
949
+ },
950
+ keyword: {
951
+ type: 'string',
952
+ description: 'Optional case-insensitive substring filter.',
953
+ },
954
+ },
955
+ additionalProperties: false,
956
+ },
957
+ source: PLUGIN_SOURCE,
958
+ effects: 'read',
959
+ supportsIdempotencyKey: true,
960
+ supportsReconcile: false,
961
+ concurrency: 'parallel',
962
+ timeoutMs: 5000,
963
+ },
964
+ {
965
+ async invoke(input, context) {
966
+ const payload = input === undefined || input === null ? {} : input;
967
+ if (!isPlainObject(payload)) {
968
+ return errorObservation('INVALID_INPUT', 'Expected an object payload for security_query_ledger.');
969
+ }
970
+ if (payload.category !== undefined && !FACT_CATEGORIES.has(payload.category)) {
971
+ return errorObservation(
972
+ 'INVALID_INPUT',
973
+ 'category must be one of target, mitigation, primitive, offset, asset, endpoint.',
974
+ );
975
+ }
976
+ if (payload.status !== undefined && !HYPOTHESIS_STATUSES.has(payload.status)) {
977
+ return errorObservation(
978
+ 'INVALID_INPUT',
979
+ 'status must be one of open, testing, verified, falsified.',
980
+ );
981
+ }
982
+ if (payload.keyword !== undefined && typeof payload.keyword !== 'string') {
983
+ return errorObservation('INVALID_INPUT', 'keyword must be a string when provided.');
984
+ }
985
+
986
+ const state = await loadState(context.runId, {
987
+ checkpointSourceRunId: context?.checkpointSourceRunId,
988
+ context,
989
+ });
990
+ const category = payload.category;
991
+ const status = payload.status;
992
+ const keyword = payload.keyword ? payload.keyword.trim().toLowerCase() : '';
993
+
994
+ const matchesKeyword = (fields) =>
995
+ !keyword ||
996
+ fields.some((field) =>
997
+ String(field ?? '')
998
+ .toLowerCase()
999
+ .includes(keyword),
1000
+ );
1001
+
1002
+ const includeFacts = category !== undefined || status === undefined;
1003
+ const includeHypotheses = status !== undefined || category === undefined;
1004
+ const includeSkills = category === undefined && status === undefined;
1005
+
1006
+ const facts = includeFacts
1007
+ ? [...state.facts.values()].filter(
1008
+ (fact) =>
1009
+ (category === undefined || fact.category === category) &&
1010
+ matchesKeyword([
1011
+ fact.id,
1012
+ fact.category,
1013
+ fact.summary,
1014
+ fact.evidence,
1015
+ fact.confidence,
1016
+ fact.authorRole,
1017
+ ]),
1018
+ )
1019
+ : [];
1020
+
1021
+ const hypotheses = includeHypotheses
1022
+ ? [...state.hypotheses.values()].filter(
1023
+ (hyp) =>
1024
+ (status === undefined || hyp.status === status) &&
1025
+ matchesKeyword([
1026
+ hyp.id,
1027
+ hyp.title,
1028
+ hyp.transition,
1029
+ hyp.status,
1030
+ hyp.outcome,
1031
+ hyp.evidence,
1032
+ hyp.authorRole,
1033
+ ]),
1034
+ )
1035
+ : [];
1036
+
1037
+ const unlockedSkills = includeSkills
1038
+ ? [...state.unlockedSkills.values()].filter((item) =>
1039
+ matchesKeyword([item.skill, item.authorRole]),
1040
+ )
1041
+ : [];
1042
+
1043
+ const result = {
1044
+ runId: context.runId,
1045
+ facts,
1046
+ hypotheses,
1047
+ unlockedSkills,
1048
+ counts: {
1049
+ facts: facts.length,
1050
+ hypotheses: hypotheses.length,
1051
+ unlockedSkills: unlockedSkills.length,
1052
+ },
1053
+ };
1054
+
1055
+ return {
1056
+ effect: 'none',
1057
+ outcome: {
1058
+ status: 'success',
1059
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
1060
+ data: result,
1061
+ },
1062
+ };
1063
+ },
1064
+ },
1065
+ );
1066
+
1067
+ api.registerContextProvider(
1068
+ {
1069
+ id: 'security:fact-ledger',
1070
+ version: '1',
1071
+ phase: 'extensions',
1072
+ priority: 20,
1073
+ required: false,
1074
+ timeoutMs: 2000,
1075
+ async collect(input) {
1076
+ const empty = {
1077
+ providerId: 'security:fact-ledger',
1078
+ version: '1',
1079
+ prompt: [],
1080
+ background: [],
1081
+ tools: [],
1082
+ relevantTurnIds: [],
1083
+ };
1084
+ if (disposed) return empty;
1085
+
1086
+ const turnKey = `${input.runId}:${input.agentSessionId}:${input.turnId}`;
1087
+ const activeBlock = findActiveTurnBlock(input);
1088
+ let rendered;
1089
+
1090
+ if (activeBlock) {
1091
+ if (turnSnapshots.has(turnKey)) {
1092
+ rendered = turnSnapshots.get(turnKey);
1093
+ } else {
1094
+ // Preserve the active turn's continuation prefix after a mid-turn Host restart.
1095
+ rendered = extractLedgerFromContinuationBlock(activeBlock, input?.state?.surface);
1096
+ rememberTurnSnapshot(turnKey, rendered);
1097
+ }
1098
+ } else {
1099
+ const state = await loadState(input.runId, {
1100
+ checkpointSourceRunId: input?.checkpointSourceRunId ?? input?.config?.checkpoint?.sourceRunId,
1101
+ context: input,
1102
+ });
1103
+ rendered = renderLedgerXml(state, maxBytes);
1104
+ rememberTurnSnapshot(turnKey, rendered);
1105
+ }
1106
+
1107
+ if (!rendered) return empty;
1108
+
1109
+ return {
1110
+ ...empty,
1111
+ background: [
1112
+ {
1113
+ id: 'security:fact-ledger',
1114
+ source: 'security:fact-ledger',
1115
+ priority: 20,
1116
+ required: false,
1117
+ text: rendered,
1118
+ },
1119
+ ],
1120
+ };
1121
+ },
1122
+ },
1123
+ { scope: { kind: 'global' } },
1124
+ );
1125
+ }
1126
+
1127
+ async function dispose() {
1128
+ disposed = true;
1129
+ await Promise.allSettled([...writeChains.values(), ...pendingLoads.values()]);
1130
+ writeChains.clear();
1131
+ pendingLoads.clear();
1132
+ states.clear();
1133
+ turnSnapshots.clear();
1134
+ }
1135
+
1136
+ return {
1137
+ register,
1138
+ loadState,
1139
+ recordSkillUnlocked,
1140
+ ledgerPathFor,
1141
+ dispose,
1142
+ };
1143
+ }