@osovv/vv-opencode 2.3.3 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +18 -13
  3. package/dist/cli.js +5 -3
  4. package/dist/cli.js.map +1 -1
  5. package/dist/commands/doctor.d.ts +4 -0
  6. package/dist/commands/doctor.js +60 -51
  7. package/dist/commands/doctor.js.map +1 -1
  8. package/dist/commands/plugin-toggle.d.ts +0 -16
  9. package/dist/commands/plugin-toggle.js +2 -34
  10. package/dist/commands/plugin-toggle.js.map +1 -1
  11. package/dist/commands/preset.d.ts +0 -8
  12. package/dist/commands/preset.js +3 -24
  13. package/dist/commands/preset.js.map +1 -1
  14. package/dist/commands/role.js +2 -30
  15. package/dist/commands/role.js.map +1 -1
  16. package/dist/commands/session.d.ts +50 -0
  17. package/dist/commands/session.js +354 -0
  18. package/dist/commands/session.js.map +1 -0
  19. package/dist/lib/managed-agents.js +2 -2
  20. package/dist/lib/managed-agents.js.map +1 -1
  21. package/dist/lib/managed-skills.js +3 -3
  22. package/dist/lib/managed-skills.js.map +1 -1
  23. package/dist/lib/opencode/agent-registrations.js +103 -13
  24. package/dist/lib/opencode/agent-registrations.js.map +1 -1
  25. package/dist/lib/opencode/inspection.js +131 -5
  26. package/dist/lib/opencode/inspection.js.map +1 -1
  27. package/dist/plugins/analytics/index.js +8 -19
  28. package/dist/plugins/analytics/index.js.map +1 -1
  29. package/dist/plugins/guardian/index.js +7 -21
  30. package/dist/plugins/guardian/index.js.map +1 -1
  31. package/dist/plugins/hashline-edit/index.js +6 -20
  32. package/dist/plugins/hashline-edit/index.js.map +1 -1
  33. package/dist/plugins/model-roles/index.d.ts +3 -3
  34. package/dist/plugins/model-roles/index.js +8 -8
  35. package/dist/plugins/model-roles/index.js.map +1 -1
  36. package/dist/plugins/peak-hours/index.js +9 -20
  37. package/dist/plugins/peak-hours/index.js.map +1 -1
  38. package/dist/plugins/secrets-redaction/index.js +11 -24
  39. package/dist/plugins/secrets-redaction/index.js.map +1 -1
  40. package/dist/plugins/spec-guard/index.js +10 -22
  41. package/dist/plugins/spec-guard/index.js.map +1 -1
  42. package/dist/plugins/system-context-injection/guidance.d.ts +6 -0
  43. package/dist/plugins/system-context-injection/guidance.js +79 -0
  44. package/dist/plugins/system-context-injection/guidance.js.map +1 -0
  45. package/dist/plugins/system-context-injection/index.js +20 -121
  46. package/dist/plugins/system-context-injection/index.js.map +1 -1
  47. package/dist/plugins/tool-history-compaction/index.js +14 -25
  48. package/dist/plugins/tool-history-compaction/index.js.map +1 -1
  49. package/dist/plugins/web-tools/index.js +14 -25
  50. package/dist/plugins/web-tools/index.js.map +1 -1
  51. package/dist/plugins/workflow/index.d.ts +3 -2
  52. package/dist/plugins/workflow/index.js +6 -22
  53. package/dist/plugins/workflow/index.js.map +1 -1
  54. package/dist/plugins/workflow/input-validation.d.ts +1 -1
  55. package/dist/plugins/workflow/input-validation.js +2 -2
  56. package/dist/plugins/workflow/input-validation.js.map +1 -1
  57. package/dist/plugins/workflow/results.d.ts +40 -40
  58. package/dist/plugins/workflow/system-instruction.md +20 -0
  59. package/dist/runtime/auxiliary.d.ts +11 -6
  60. package/dist/runtime/auxiliary.js +43 -35
  61. package/dist/runtime/auxiliary.js.map +1 -1
  62. package/dist/runtime/context-inspection.d.ts +7 -6
  63. package/dist/runtime/context-inspection.js +37 -43
  64. package/dist/runtime/context-inspection.js.map +1 -1
  65. package/dist/runtime/context.d.ts +22 -45
  66. package/dist/runtime/context.js +348 -634
  67. package/dist/runtime/context.js.map +1 -1
  68. package/dist/runtime/model-registry.d.ts +3 -34
  69. package/dist/runtime/model-registry.js +10 -190
  70. package/dist/runtime/model-registry.js.map +1 -1
  71. package/dist/runtime/session-settings.d.ts +204 -0
  72. package/dist/runtime/session-settings.js +445 -0
  73. package/dist/runtime/session-settings.js.map +1 -0
  74. package/dist/runtime/snapshot-config.d.ts +7 -70
  75. package/dist/runtime/snapshot-config.js +16 -198
  76. package/dist/runtime/snapshot-config.js.map +1 -1
  77. package/dist/runtime/types.d.ts +15 -256
  78. package/dist/runtime/types.js +9 -63
  79. package/dist/runtime/types.js.map +1 -1
  80. package/dist/tui/settings/plugin.d.ts +29 -0
  81. package/dist/tui/settings/plugin.js +134 -0
  82. package/dist/tui/settings/plugin.js.map +1 -0
  83. package/dist/tui.js +12 -12
  84. package/dist/tui.js.map +1 -1
  85. package/package.json +1 -1
  86. package/schemas/vvoc/v3.json +1 -1
  87. package/templates/agents/vv-code-reviewer.md +2 -2
  88. package/templates/agents/vv-controller.md +176 -151
  89. package/templates/agents/vv-implementer.md +2 -2
  90. package/templates/agents/vv-reflector.md +7 -0
  91. package/templates/agents/vv-spec-reviewer.md +2 -2
  92. package/templates/skills/vv-execute/SKILL.md +25 -4
  93. package/templates/skills/vv-execute/references/tool-contracts.md +3 -3
  94. package/templates/skills/vv-reflect/SKILL.md +1 -0
  95. package/templates/skills/vv-reflect/references/session-graph.py +581 -7
  96. package/templates/skills/vv-review/SKILL.md +2 -2
  97. package/dist/lib/rebind-request.d.ts +0 -41
  98. package/dist/lib/rebind-request.js +0 -134
  99. package/dist/lib/rebind-request.js.map +0 -1
  100. package/dist/runtime/snapshot-store.d.ts +0 -63
  101. package/dist/runtime/snapshot-store.js +0 -668
  102. package/dist/runtime/snapshot-store.js.map +0 -1
  103. package/dist/runtime/snapshots.d.ts +0 -36
  104. package/dist/runtime/snapshots.js +0 -508
  105. package/dist/runtime/snapshots.js.map +0 -1
  106. package/dist/tui/rebind/plugin.d.ts +0 -22
  107. package/dist/tui/rebind/plugin.js +0 -101
  108. package/dist/tui/rebind/plugin.js.map +0 -1
@@ -1,668 +0,0 @@
1
- // FILE: src/runtime/snapshot-store.ts
2
- // VERSION: 2.0.0
3
- // START_MODULE_CONTRACT
4
- // PURPOSE: Persist durable per-family policy captures and staged admission candidates under the vvoc data directory with atomic writes, project-scoped isolation, integrity verification, and fail-closed reads.
5
- // SCOPE: File-backed SnapshotStore implementation, project-scoped snapshot root resolution, atomic write/rename, candidate staging files, family listing, content-integrity recomputation, deep-frozen immutable reads, and strict shape validation that rejects corrupt or foreign state. No admission logic, no native client, no host mutation.
6
- // DEPENDS: [node:crypto, node:fs/promises, node:path, src/runtime/types.ts, src/lib/vvoc-paths.ts]
7
- // LINKS: [M-NATIVE-RUNTIME, V-M-NATIVE-RUNTIME]
8
- // ROLE: RUNTIME
9
- // MAP_MODE: EXPORTS
10
- // END_MODULE_CONTRACT
11
- //
12
- // START_MODULE_MAP
13
- // SNAPSHOT_STORE_DIR_NAME - Directory name holding vvoc family snapshots inside the vvoc data dir.
14
- // FileSnapshotStoreOptions - Project scope and optional data-dir override for the file store.
15
- // createFileSnapshotStore - Build a durable file-backed SnapshotStore for one project scope.
16
- // snapshotScopeDirName - Stable, collision-free directory name for one project scope.
17
- // familyCaptureIntegrity - Recompute the behavior-relevant content digest of a capture.
18
- // decodeFamilyCapture - Strictly validate and integrity-check a persisted family capture.
19
- // decodeStagedCandidate - Strictly validate a persisted staged candidate.
20
- // decodeStagedCandidates - Strictly validate a persisted staged-candidate array.
21
- // BINDING_STORE_DIR_NAME - Directory name holding content-addressed policy snapshots and family pointers.
22
- // FileBindingStoreOptions - Project scope and optional data-dir override for the binding store.
23
- // FamilyBindingRecord - Durable pointer from a family to its content-addressed policy snapshot.
24
- // FileBindingStore - Content-addressed snapshot and per-family pointer store with fail-soft reads.
25
- // END_MODULE_MAP
26
- //
27
- // START_CHANGE_SUMMARY
28
- // LAST_CHANGE: [C-SNAPSHOT-ANCHORING-REDESIGN T-003 - Added the content-addressed FileBindingStore with fail-soft reads and reference-counted GC primitives alongside the legacy capture store.]
29
- // END_CHANGE_SUMMARY
30
- import { createHash, randomBytes } from "node:crypto";
31
- import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
32
- import { dirname, join } from "node:path";
33
- import { parseVvocConfigText } from "../lib/vvoc-config.js";
34
- import { getGlobalVvocDataDir } from "../lib/vvoc-paths.js";
35
- import { behaviourContentHash } from "./snapshot-config.js";
36
- import { SnapshotStoreError, stagedCandidateKey, } from "./types.js";
37
- /** Directory name holding vvoc family snapshots inside the vvoc data dir. */
38
- export const SNAPSHOT_STORE_DIR_NAME = "snapshots";
39
- /** Stable, collision-free directory name for one project scope. */
40
- export function snapshotScopeDirName(scopeKey) {
41
- return createHash("sha256").update(scopeKey).digest("hex").slice(0, 32);
42
- }
43
- function isRecord(value) {
44
- return typeof value === "object" && value !== null;
45
- }
46
- /**
47
- * Behavior-relevant projection used for integrity. Generated variant ids and the
48
- * snapshot id are excluded so the digest is stable and recomputable while still
49
- * covering every policy, native overlay, and source variant that changes payload.
50
- */
51
- function integrityProjection(capture) {
52
- return JSON.stringify({
53
- familyId: capture.familyId,
54
- // `capturedAt` is an observation timestamp, never behavior: excluding it keeps
55
- // the digest (and snapshot id) stable across unchanged restaging so a repeat
56
- // admission is idempotent instead of creating a new revision.
57
- location: capture.location,
58
- roles: capture.roles,
59
- roleModels: capture.roleModels,
60
- agents: capture.agents,
61
- variants: [...capture.variants]
62
- .map((variant) => ({
63
- providerID: variant.providerID,
64
- modelID: variant.modelID,
65
- sourceVariant: variant.sourceVariant ?? null,
66
- settings: variant.settings ?? null,
67
- body: variant.body ?? null,
68
- headers: variant.headers ?? null,
69
- }))
70
- .sort((left, right) => `${left.providerID}/${left.modelID}/${left.sourceVariant}`.localeCompare(`${right.providerID}/${right.modelID}/${right.sourceVariant}`)),
71
- modelSettings: capture.modelSettings,
72
- vvoc: capture.vvoc,
73
- rawIntent: capture.rawIntent ?? null,
74
- rootSelection: capture.rootSelection ?? null,
75
- modelOverride: capture.modelOverride ?? null,
76
- intent: capture.intent,
77
- });
78
- }
79
- /** Recompute the behavior-relevant content digest of a capture. */
80
- export function familyCaptureIntegrity(capture) {
81
- return createHash("sha256").update(integrityProjection(capture)).digest("hex");
82
- }
83
- function deepFreeze(value) {
84
- if (value === null || typeof value !== "object")
85
- return value;
86
- if (Object.isFrozen(value))
87
- return value;
88
- for (const entry of Object.values(value))
89
- deepFreeze(entry);
90
- return Object.freeze(value);
91
- }
92
- function decodeSelection(value) {
93
- if (!isRecord(value))
94
- return undefined;
95
- const { providerID, modelID, variant } = value;
96
- if (typeof providerID !== "string" || typeof modelID !== "string")
97
- return undefined;
98
- if (variant !== undefined && typeof variant !== "string")
99
- return undefined;
100
- return { providerID, modelID, ...(variant === undefined ? {} : { variant }) };
101
- }
102
- function decodeSelections(value) {
103
- if (!isRecord(value))
104
- return undefined;
105
- const decoded = {};
106
- for (const [key, entry] of Object.entries(value)) {
107
- const selection = decodeSelection(entry);
108
- if (selection === undefined)
109
- return undefined;
110
- decoded[key] = selection;
111
- }
112
- return decoded;
113
- }
114
- function decodeStringRecord(value) {
115
- if (!isRecord(value))
116
- return undefined;
117
- const decoded = {};
118
- for (const [key, entry] of Object.entries(value)) {
119
- if (typeof entry !== "string")
120
- return undefined;
121
- decoded[key] = entry;
122
- }
123
- return decoded;
124
- }
125
- function decodeVariants(value) {
126
- if (!Array.isArray(value))
127
- return undefined;
128
- const decoded = [];
129
- for (const entry of value) {
130
- if (!isRecord(entry) || typeof entry.id !== "string")
131
- return undefined;
132
- if (typeof entry.providerID !== "string" || typeof entry.modelID !== "string")
133
- return undefined;
134
- if (entry.sourceVariant !== undefined && typeof entry.sourceVariant !== "string") {
135
- return undefined;
136
- }
137
- const recorded = { id: entry.id, providerID: entry.providerID, modelID: entry.modelID };
138
- if (entry.sourceVariant !== undefined)
139
- recorded.sourceVariant = entry.sourceVariant;
140
- if (entry.settings !== undefined) {
141
- if (!isRecord(entry.settings))
142
- return undefined;
143
- recorded.settings = entry.settings;
144
- }
145
- if (entry.body !== undefined) {
146
- if (!isRecord(entry.body))
147
- return undefined;
148
- recorded.body = entry.body;
149
- }
150
- if (entry.headers !== undefined) {
151
- const headers = decodeStringRecord(entry.headers);
152
- if (headers === undefined)
153
- return undefined;
154
- recorded.headers = headers;
155
- }
156
- decoded.push(recorded);
157
- }
158
- return decoded;
159
- }
160
- function decodeModelSettings(value) {
161
- if (!Array.isArray(value))
162
- return undefined;
163
- const decoded = [];
164
- for (const entry of value) {
165
- if (!isRecord(entry))
166
- return undefined;
167
- const selection = decodeSelection(entry);
168
- if (selection === undefined)
169
- return undefined;
170
- const recorded = selection;
171
- if (entry.settings !== undefined) {
172
- if (!isRecord(entry.settings))
173
- return undefined;
174
- recorded.settings = entry.settings;
175
- }
176
- if (entry.body !== undefined) {
177
- if (!isRecord(entry.body))
178
- return undefined;
179
- recorded.body = entry.body;
180
- }
181
- if (entry.headers !== undefined) {
182
- const headers = decodeStringRecord(entry.headers);
183
- if (headers === undefined)
184
- return undefined;
185
- recorded.headers = headers;
186
- }
187
- decoded.push(recorded);
188
- }
189
- return decoded;
190
- }
191
- function decodeRawIntent(value) {
192
- if (value === undefined)
193
- return undefined;
194
- if (!isRecord(value))
195
- return undefined;
196
- if (value.model !== undefined && typeof value.model !== "string")
197
- return undefined;
198
- if (value.smallModel !== undefined && typeof value.smallModel !== "string")
199
- return undefined;
200
- if (value.sourcePath !== undefined && typeof value.sourcePath !== "string")
201
- return undefined;
202
- const agents = decodeStringRecord(value.agents);
203
- const commands = decodeStringRecord(value.commands);
204
- if (agents === undefined || commands === undefined)
205
- return undefined;
206
- return {
207
- ...(value.model === undefined ? {} : { model: value.model }),
208
- ...(value.smallModel === undefined ? {} : { smallModel: value.smallModel }),
209
- agents,
210
- commands,
211
- ...(value.sourcePath === undefined ? {} : { sourcePath: value.sourcePath }),
212
- };
213
- }
214
- function decodeAgents(value) {
215
- if (!Array.isArray(value))
216
- return undefined;
217
- const decoded = [];
218
- for (const entry of value) {
219
- if (!isRecord(entry) || typeof entry.agentID !== "string")
220
- return undefined;
221
- if (entry.role !== undefined && typeof entry.role !== "string")
222
- return undefined;
223
- const selection = entry.selection === undefined ? undefined : decodeSelection(entry.selection);
224
- if (entry.selection !== undefined && selection === undefined)
225
- return undefined;
226
- decoded.push({
227
- agentID: entry.agentID,
228
- ...(entry.role === undefined ? {} : { role: entry.role }),
229
- ...(selection === undefined ? {} : { selection }),
230
- });
231
- }
232
- return decoded;
233
- }
234
- function decodeIntent(value) {
235
- if (!isRecord(value))
236
- return undefined;
237
- const { mode, source, roleRef, literal } = value;
238
- if (mode !== "explicit" && mode !== "implicit" && mode !== "staged")
239
- return undefined;
240
- if (source !== "config" && source !== "switch" && source !== "watcher" && source !== "preset") {
241
- return undefined;
242
- }
243
- if (roleRef !== undefined && typeof roleRef !== "string")
244
- return undefined;
245
- const decodedLiteral = literal === undefined ? undefined : decodeSelection(literal);
246
- if (literal !== undefined && decodedLiteral === undefined)
247
- return undefined;
248
- return {
249
- mode,
250
- source,
251
- ...(roleRef === undefined ? {} : { roleRef }),
252
- ...(decodedLiteral === undefined ? {} : { literal: decodedLiteral }),
253
- };
254
- }
255
- function decodeIdentity(value) {
256
- if (!isRecord(value))
257
- return undefined;
258
- const { directory, workspaceID, projectID, canonical } = value;
259
- if (typeof directory !== "string" ||
260
- typeof projectID !== "string" ||
261
- typeof canonical !== "string" ||
262
- (workspaceID !== undefined && typeof workspaceID !== "string")) {
263
- return undefined;
264
- }
265
- return { directory, ...(workspaceID === undefined ? {} : { workspaceID }), projectID, canonical };
266
- }
267
- /** Strictly validate and integrity-check a persisted family capture. */
268
- export function decodeFamilyCapture(value) {
269
- if (!isRecord(value))
270
- return undefined;
271
- if (value.schemaVersion !== 1)
272
- return undefined;
273
- if (typeof value.snapshotId !== "string" || typeof value.integrity !== "string")
274
- return undefined;
275
- if (typeof value.familyId !== "string")
276
- return undefined;
277
- if (typeof value.capturedAt !== "number" || !Number.isFinite(value.capturedAt))
278
- return undefined;
279
- const location = decodeIdentity(value.location);
280
- if (location === undefined)
281
- return undefined;
282
- const roles = decodeStringRecord(value.roles);
283
- if (roles === undefined)
284
- return undefined;
285
- const roleModels = decodeSelections(value.roleModels);
286
- if (roleModels === undefined)
287
- return undefined;
288
- const agents = decodeAgents(value.agents);
289
- if (agents === undefined)
290
- return undefined;
291
- const variants = decodeVariants(value.variants);
292
- if (variants === undefined)
293
- return undefined;
294
- const modelSettings = decodeModelSettings(value.modelSettings);
295
- if (modelSettings === undefined)
296
- return undefined;
297
- if (!isRecord(value.vvoc))
298
- return undefined;
299
- let vvoc;
300
- try {
301
- // Re-validate the captured document with the canonical strict parser; never trust raw bytes.
302
- vvoc = parseVvocConfigText(JSON.stringify(value.vvoc), `snapshot:${value.familyId}`);
303
- }
304
- catch {
305
- return undefined;
306
- }
307
- const rawIntent = decodeRawIntent(value.rawIntent);
308
- if (value.rawIntent !== undefined && rawIntent === undefined)
309
- return undefined;
310
- const intent = decodeIntent(value.intent);
311
- if (intent === undefined)
312
- return undefined;
313
- const modelOverride = value.modelOverride === undefined ? undefined : decodeSelection(value.modelOverride);
314
- if (value.modelOverride !== undefined && modelOverride === undefined)
315
- return undefined;
316
- const rootSelection = value.rootSelection === undefined ? undefined : decodeSelection(value.rootSelection);
317
- if (value.rootSelection !== undefined && rootSelection === undefined)
318
- return undefined;
319
- const decoded = deepFreeze({
320
- schemaVersion: 1,
321
- snapshotId: value.snapshotId,
322
- integrity: value.integrity,
323
- familyId: value.familyId,
324
- capturedAt: value.capturedAt,
325
- location,
326
- roles,
327
- roleModels,
328
- agents,
329
- variants,
330
- modelSettings,
331
- vvoc,
332
- ...(rawIntent === undefined ? {} : { rawIntent }),
333
- ...(rootSelection === undefined ? {} : { rootSelection }),
334
- ...(modelOverride === undefined ? {} : { modelOverride }),
335
- intent,
336
- });
337
- // A mismatch means the persisted state is stale, tampered, or from an incompatible version.
338
- if (familyCaptureIntegrity(decoded) !== decoded.integrity)
339
- return undefined;
340
- return decoded;
341
- }
342
- /** Strictly validate a persisted staged candidate. */
343
- export function decodeStagedCandidate(value) {
344
- if (!isRecord(value))
345
- return undefined;
346
- if (typeof value.familyId !== "string" || typeof value.sessionID !== "string")
347
- return undefined;
348
- if (typeof value.stagedAt !== "number" || !Number.isFinite(value.stagedAt))
349
- return undefined;
350
- if (typeof value.revision !== "string")
351
- return undefined;
352
- if (value.inboxID !== undefined && typeof value.inboxID !== "string")
353
- return undefined;
354
- if (value.operationID !== undefined && typeof value.operationID !== "string")
355
- return undefined;
356
- if (value.workload !== undefined && typeof value.workload !== "string")
357
- return undefined;
358
- const selection = decodeSelection(value.selection);
359
- if (selection === undefined)
360
- return undefined;
361
- const before = value.before === undefined ? undefined : decodeSelection(value.before);
362
- if (value.before !== undefined && before === undefined)
363
- return undefined;
364
- const capture = decodeFamilyCapture(value.capture);
365
- if (capture === undefined)
366
- return undefined;
367
- return deepFreeze({
368
- familyId: value.familyId,
369
- sessionID: value.sessionID,
370
- ...(value.inboxID === undefined ? {} : { inboxID: value.inboxID }),
371
- ...(value.operationID === undefined ? {} : { operationID: value.operationID }),
372
- ...(value.workload === undefined ? {} : { workload: value.workload }),
373
- stagedAt: value.stagedAt,
374
- revision: value.revision,
375
- selection,
376
- ...(before === undefined ? {} : { before }),
377
- capture,
378
- });
379
- }
380
- /** Strictly validate a persisted staged-candidate array; any invalid entry fails the whole read. */
381
- export function decodeStagedCandidates(value) {
382
- if (!Array.isArray(value))
383
- return undefined;
384
- const decoded = [];
385
- const seen = new Set();
386
- for (const entry of value) {
387
- const candidate = decodeStagedCandidate(entry);
388
- if (candidate === undefined)
389
- return undefined;
390
- const key = stagedCandidateKey(candidate);
391
- if (seen.has(key))
392
- return undefined;
393
- seen.add(key);
394
- decoded.push(candidate);
395
- }
396
- return decoded;
397
- }
398
- // START_BLOCK_FILE_STORE
399
- /** Build a durable file-backed SnapshotStore for one project scope. */
400
- export function createFileSnapshotStore(options) {
401
- const baseDir = join(options.dataDir ?? getGlobalVvocDataDir(), SNAPSHOT_STORE_DIR_NAME, snapshotScopeDirName(options.scopeKey));
402
- const capturePath = (familyId) => join(baseDir, `${encodeURIComponent(familyId)}.json`);
403
- const candidatesPath = (familyId) => join(baseDir, `${encodeURIComponent(familyId)}.candidates.json`);
404
- const markerPath = (familyId) => join(baseDir, `${encodeURIComponent(familyId)}.bound.json`);
405
- async function readJson(path) {
406
- let text;
407
- try {
408
- text = await readFile(path, "utf8");
409
- }
410
- catch (error) {
411
- if (error.code === "ENOENT")
412
- return undefined;
413
- throw new SnapshotStoreError(`Snapshot state could not be read at ${path}.`, {
414
- cause: error,
415
- });
416
- }
417
- try {
418
- return JSON.parse(text);
419
- }
420
- catch (error) {
421
- throw new SnapshotStoreError(`Snapshot state at ${path} is not valid JSON.`, {
422
- cause: error,
423
- });
424
- }
425
- }
426
- async function writeAtomic(path, value) {
427
- await mkdir(dirname(path), { recursive: true, mode: 0o700 });
428
- const temp = `${path}.tmp-${process.pid}-${randomBytes(6).toString("hex")}`;
429
- try {
430
- await writeFile(temp, `${JSON.stringify(value)}\n`, { encoding: "utf8", mode: 0o600 });
431
- await rename(temp, path);
432
- }
433
- catch (error) {
434
- await rm(temp, { force: true });
435
- throw new SnapshotStoreError(`Snapshot state could not be written at ${path}.`, {
436
- cause: error,
437
- });
438
- }
439
- }
440
- async function readCandidatesFor(familyId) {
441
- const raw = await readJson(candidatesPath(familyId));
442
- if (raw === undefined)
443
- return [];
444
- const candidates = decodeStagedCandidates(raw);
445
- if (candidates === undefined) {
446
- throw new SnapshotStoreError(`Staged admission candidates for family ${familyId} are invalid.`);
447
- }
448
- return candidates;
449
- }
450
- return {
451
- async read(familyId) {
452
- const raw = await readJson(capturePath(familyId));
453
- if (raw === undefined)
454
- return undefined;
455
- const capture = decodeFamilyCapture(raw);
456
- if (capture === undefined) {
457
- throw new SnapshotStoreError(`Snapshot state for family ${familyId} is invalid; refusing to adopt current configuration.`);
458
- }
459
- return capture;
460
- },
461
- async write(familyId, capture) {
462
- await writeAtomic(capturePath(familyId), capture);
463
- },
464
- async remove(familyId) {
465
- await rm(capturePath(familyId), { force: true });
466
- },
467
- readCandidates: readCandidatesFor,
468
- async writeCandidate(candidate) {
469
- const existing = await readCandidatesFor(candidate.familyId);
470
- const key = stagedCandidateKey(candidate);
471
- const merged = existing.filter((entry) => stagedCandidateKey(entry) !== key);
472
- merged.push(candidate);
473
- await writeAtomic(candidatesPath(candidate.familyId), merged);
474
- },
475
- async removeCandidate(familyId, candidateKey) {
476
- const existing = await readCandidatesFor(familyId);
477
- const remaining = existing.filter((entry) => stagedCandidateKey(entry) !== candidateKey);
478
- if (remaining.length === existing.length)
479
- return;
480
- if (remaining.length === 0) {
481
- await rm(candidatesPath(familyId), { force: true });
482
- return;
483
- }
484
- await writeAtomic(candidatesPath(familyId), remaining);
485
- },
486
- async removeCandidates(familyId) {
487
- await rm(candidatesPath(familyId), { force: true });
488
- },
489
- async readMarker(familyId) {
490
- const raw = await readJson(markerPath(familyId));
491
- return raw !== undefined;
492
- },
493
- async writeMarker(familyId) {
494
- await writeAtomic(markerPath(familyId), { bound: true });
495
- },
496
- async removeMarker(familyId) {
497
- await rm(markerPath(familyId), { force: true });
498
- },
499
- async list() {
500
- let entries;
501
- try {
502
- entries = await readdir(baseDir);
503
- }
504
- catch (error) {
505
- if (error.code === "ENOENT")
506
- return [];
507
- throw new SnapshotStoreError(`Snapshot directory could not be listed at ${baseDir}.`, {
508
- cause: error,
509
- });
510
- }
511
- const familyIds = [];
512
- for (const entry of entries) {
513
- if (!entry.endsWith(".json") ||
514
- entry.endsWith(".candidates.json") ||
515
- entry.endsWith(".bound.json"))
516
- continue;
517
- familyIds.push(decodeURIComponent(entry.slice(0, -".json".length)));
518
- }
519
- return familyIds;
520
- },
521
- };
522
- }
523
- // END_BLOCK_FILE_STORE
524
- // START_BLOCK_BINDING_STORE
525
- /** Directory name holding content-addressed policy snapshots and family pointers. */
526
- export const BINDING_STORE_DIR_NAME = "bindings";
527
- function decodeFamilyBinding(text) {
528
- try {
529
- const value = JSON.parse(text);
530
- if (!isRecord(value))
531
- return undefined;
532
- if (typeof value.familyId !== "string" ||
533
- typeof value.snapshotHash !== "string" ||
534
- typeof value.boundAt !== "string") {
535
- return undefined;
536
- }
537
- return { familyId: value.familyId, snapshotHash: value.snapshotHash, boundAt: value.boundAt };
538
- }
539
- catch {
540
- return undefined;
541
- }
542
- }
543
- function decodeBehaviourProjection(text) {
544
- try {
545
- const value = JSON.parse(text);
546
- if (!isRecord(value))
547
- return undefined;
548
- if (!isRecord(value.roleModels) ||
549
- !Array.isArray(value.agentBindings) ||
550
- !isRecord(value.policy)) {
551
- return undefined;
552
- }
553
- return value;
554
- }
555
- catch {
556
- return undefined;
557
- }
558
- }
559
- async function writeJsonAtomic(path, value) {
560
- await mkdir(dirname(path), { recursive: true });
561
- const temporary = `${path}.${randomBytes(6).toString("hex")}.tmp`;
562
- await writeFile(temporary, JSON.stringify(value), { mode: 0o600 });
563
- await rename(temporary, path);
564
- }
565
- async function readTextSafe(path) {
566
- try {
567
- return await readFile(path, "utf8");
568
- }
569
- catch {
570
- return undefined;
571
- }
572
- }
573
- async function readNamesSafe(path) {
574
- try {
575
- return await readdir(path);
576
- }
577
- catch {
578
- return [];
579
- }
580
- }
581
- /**
582
- * Content-addressed store for credential-free behaviour-policy snapshots plus a
583
- * tiny per-family pointer. Reads never throw: a missing, unparseable, or
584
- * hash-mismatched artifact returns undefined so callers can fail soft per family.
585
- */
586
- export class FileBindingStore {
587
- #root;
588
- constructor(options) {
589
- const dataDir = options.dataDir ?? getGlobalVvocDataDir();
590
- this.#root = join(dataDir, BINDING_STORE_DIR_NAME, snapshotScopeDirName(options.scopeKey));
591
- }
592
- #policiesDir() {
593
- return join(this.#root, "policies");
594
- }
595
- #familiesDir() {
596
- return join(this.#root, "families");
597
- }
598
- #policyPath(hash) {
599
- return join(this.#policiesDir(), `${hash}.json`);
600
- }
601
- #familyPath(familyId) {
602
- return join(this.#familiesDir(), `${encodeURIComponent(familyId)}.json`);
603
- }
604
- /** Persist a projection under its content hash and return that hash; identical content reuses the file. */
605
- async writeSnapshot(projection) {
606
- const contentHash = behaviourContentHash(projection);
607
- await writeJsonAtomic(this.#policyPath(contentHash), projection);
608
- return contentHash;
609
- }
610
- /** Load a projection by hash; undefined when missing, corrupt, or hash-mismatched. */
611
- async readSnapshot(hash) {
612
- const text = await readTextSafe(this.#policyPath(hash));
613
- if (text === undefined)
614
- return undefined;
615
- const decoded = decodeBehaviourProjection(text);
616
- if (decoded === undefined)
617
- return undefined;
618
- if (behaviourContentHash(decoded) !== hash)
619
- return undefined;
620
- return decoded;
621
- }
622
- async writeBinding(record) {
623
- await writeJsonAtomic(this.#familyPath(record.familyId), record);
624
- }
625
- /** Load a family pointer; undefined when missing or corrupt. */
626
- async readBinding(familyId) {
627
- const text = await readTextSafe(this.#familyPath(familyId));
628
- if (text === undefined)
629
- return undefined;
630
- return decodeFamilyBinding(text);
631
- }
632
- async removeBinding(familyId) {
633
- await rm(this.#familyPath(familyId), { force: true });
634
- }
635
- async listBindings() {
636
- const records = [];
637
- for (const name of await readNamesSafe(this.#familiesDir())) {
638
- if (!name.endsWith(".json"))
639
- continue;
640
- const text = await readTextSafe(join(this.#familiesDir(), name));
641
- if (text === undefined)
642
- continue;
643
- const record = decodeFamilyBinding(text);
644
- if (record !== undefined)
645
- records.push(record);
646
- }
647
- return records;
648
- }
649
- async listSnapshots() {
650
- const names = await readNamesSafe(this.#policiesDir());
651
- return names
652
- .filter((name) => name.endsWith(".json"))
653
- .map((name) => name.slice(0, -".json".length));
654
- }
655
- async removeSnapshot(hash) {
656
- await rm(this.#policyPath(hash), { force: true });
657
- }
658
- /** Count how many live families reference each snapshot hash, for reference-counted garbage collection. */
659
- async countBindings() {
660
- const counts = new Map();
661
- for (const record of await this.listBindings()) {
662
- counts.set(record.snapshotHash, (counts.get(record.snapshotHash) ?? 0) + 1);
663
- }
664
- return counts;
665
- }
666
- }
667
- // END_BLOCK_BINDING_STORE
668
- //# sourceMappingURL=snapshot-store.js.map