digdig 0.0.8 → 0.0.10

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 (112) hide show
  1. package/README.md +13 -5
  2. package/dist/claims/deterministic-checks.d.ts +2 -0
  3. package/dist/claims/deterministic-checks.d.ts.map +1 -1
  4. package/dist/claims/deterministic-checks.js +2 -2
  5. package/dist/claims/deterministic-checks.js.map +1 -1
  6. package/dist/claims/policy-input.d.ts +4 -0
  7. package/dist/claims/policy-input.d.ts.map +1 -0
  8. package/dist/claims/policy-input.js +19 -0
  9. package/dist/claims/policy-input.js.map +1 -0
  10. package/dist/claims/policy.d.ts +2 -1
  11. package/dist/claims/policy.d.ts.map +1 -1
  12. package/dist/claims/policy.js +24 -20
  13. package/dist/claims/policy.js.map +1 -1
  14. package/dist/claims/source-assessment.d.ts +10 -0
  15. package/dist/claims/source-assessment.d.ts.map +1 -0
  16. package/dist/claims/source-assessment.js +49 -0
  17. package/dist/claims/source-assessment.js.map +1 -0
  18. package/dist/claims/source-relations.d.ts +4 -0
  19. package/dist/claims/source-relations.d.ts.map +1 -0
  20. package/dist/claims/source-relations.js +26 -0
  21. package/dist/claims/source-relations.js.map +1 -0
  22. package/dist/claims/store.d.ts +5 -5
  23. package/dist/claims/store.d.ts.map +1 -1
  24. package/dist/claims/store.js +17 -42
  25. package/dist/claims/store.js.map +1 -1
  26. package/dist/claims/types.d.ts +26 -0
  27. package/dist/claims/types.d.ts.map +1 -1
  28. package/dist/commands/evidence.d.ts.map +1 -1
  29. package/dist/commands/evidence.js +12 -9
  30. package/dist/commands/evidence.js.map +1 -1
  31. package/dist/commands/extract.d.ts.map +1 -1
  32. package/dist/commands/extract.js +6 -1
  33. package/dist/commands/extract.js.map +1 -1
  34. package/dist/commands/graph-add.d.ts.map +1 -1
  35. package/dist/commands/graph-add.js +9 -2
  36. package/dist/commands/graph-add.js.map +1 -1
  37. package/dist/commands/graph-input.d.ts +5 -0
  38. package/dist/commands/graph-input.d.ts.map +1 -0
  39. package/dist/commands/graph-input.js +17 -0
  40. package/dist/commands/graph-input.js.map +1 -0
  41. package/dist/commands/graph-obfuscate.d.ts.map +1 -1
  42. package/dist/commands/graph-obfuscate.js +42 -23
  43. package/dist/commands/graph-obfuscate.js.map +1 -1
  44. package/dist/commands/query-graph.d.ts.map +1 -1
  45. package/dist/commands/query-graph.js +13 -24
  46. package/dist/commands/query-graph.js.map +1 -1
  47. package/dist/commands/review.d.ts.map +1 -1
  48. package/dist/commands/review.js +23 -17
  49. package/dist/commands/review.js.map +1 -1
  50. package/dist/commands/session.d.ts +1 -1
  51. package/dist/commands/session.d.ts.map +1 -1
  52. package/dist/commands/session.js +27 -33
  53. package/dist/commands/session.js.map +1 -1
  54. package/dist/commands/source-relations.d.ts +5 -0
  55. package/dist/commands/source-relations.d.ts.map +1 -0
  56. package/dist/commands/source-relations.js +113 -0
  57. package/dist/commands/source-relations.js.map +1 -0
  58. package/dist/deep/extractor.d.ts.map +1 -1
  59. package/dist/deep/extractor.js +1 -4
  60. package/dist/deep/extractor.js.map +1 -1
  61. package/dist/deep/graph-explore.d.ts.map +1 -1
  62. package/dist/deep/graph-explore.js +1 -3
  63. package/dist/deep/graph-explore.js.map +1 -1
  64. package/dist/deep/graph.d.ts +6 -0
  65. package/dist/deep/graph.d.ts.map +1 -1
  66. package/dist/deep/graph.js.map +1 -1
  67. package/dist/deep/iteration-data.d.ts +1 -0
  68. package/dist/deep/iteration-data.d.ts.map +1 -1
  69. package/dist/deep/iteration-data.js +1 -1
  70. package/dist/deep/iteration-data.js.map +1 -1
  71. package/dist/deep/local-doc/searcher.d.ts.map +1 -1
  72. package/dist/deep/local-doc/searcher.js +3 -4
  73. package/dist/deep/local-doc/searcher.js.map +1 -1
  74. package/dist/deep/search-strategy.d.ts +3 -3
  75. package/dist/deep/search-strategy.d.ts.map +1 -1
  76. package/dist/deep/search-strategy.js +16 -21
  77. package/dist/deep/search-strategy.js.map +1 -1
  78. package/dist/deep/session-db.d.ts +14 -0
  79. package/dist/deep/session-db.d.ts.map +1 -0
  80. package/dist/deep/session-db.js +251 -0
  81. package/dist/deep/session-db.js.map +1 -0
  82. package/dist/deep/session-lock.d.ts +7 -0
  83. package/dist/deep/session-lock.d.ts.map +1 -0
  84. package/dist/deep/session-lock.js +51 -0
  85. package/dist/deep/session-lock.js.map +1 -0
  86. package/dist/deep/session-migrate.d.ts +9 -0
  87. package/dist/deep/session-migrate.d.ts.map +1 -0
  88. package/dist/deep/session-migrate.js +174 -0
  89. package/dist/deep/session-migrate.js.map +1 -0
  90. package/dist/deep/session-store-claims.d.ts +5 -0
  91. package/dist/deep/session-store-claims.d.ts.map +1 -0
  92. package/dist/deep/session-store-claims.js +58 -0
  93. package/dist/deep/session-store-claims.js.map +1 -0
  94. package/dist/deep/session-store-results.d.ts +5 -0
  95. package/dist/deep/session-store-results.d.ts.map +1 -0
  96. package/dist/deep/session-store-results.js +59 -0
  97. package/dist/deep/session-store-results.js.map +1 -0
  98. package/dist/deep/session-store.d.ts +6 -0
  99. package/dist/deep/session-store.d.ts.map +1 -0
  100. package/dist/deep/session-store.js +64 -0
  101. package/dist/deep/session-store.js.map +1 -0
  102. package/dist/deep/session.d.ts +21 -7
  103. package/dist/deep/session.d.ts.map +1 -1
  104. package/dist/deep/session.js +242 -101
  105. package/dist/deep/session.js.map +1 -1
  106. package/dist/entry.d.ts.map +1 -1
  107. package/dist/entry.js +8 -1
  108. package/dist/entry.js.map +1 -1
  109. package/dist/runCli.d.ts.map +1 -1
  110. package/dist/runCli.js +62 -33
  111. package/dist/runCli.js.map +1 -1
  112. package/package.json +3 -3
@@ -1,70 +1,22 @@
1
1
  /**
2
2
  * Session state is the authority for discovery, extracted bodies, and approval.
3
- * Every mutation uses an atomic same-directory write so an interrupted command
4
- * cannot turn a valid session into an empty one.
3
+ * Session mutations share a SQLite transaction to preserve related state.
5
4
  */
6
- import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'fs';
7
- import { dirname, isAbsolute, join, relative, resolve } from 'path';
5
+ import { existsSync, mkdirSync } from 'fs';
6
+ import { createHash } from 'crypto';
7
+ import { isAbsolute, join, relative, resolve } from 'path';
8
8
  import { MultiDirectedGraph } from 'graphology';
9
9
  import { buildStructuralEdges, deserializeGraph, graphStats, resultId, serializeGraph } from './graph.js';
10
10
  import { resultUrlKey } from './dedupe.js';
11
11
  import { getDefaultSessionRoot, loadSessionMeta } from '../commands/session.js';
12
12
  import { assertClaimsStoreReadable, loadClaims, loadEvidences, loadReviews, saveClaims, saveEvidences, saveReviews } from '../claims/store.js';
13
- export class SessionStateError extends Error {
14
- code;
15
- constructor(code, message) {
16
- super(message);
17
- this.code = code;
18
- }
19
- }
20
- const SESSION_LOCK_STALE_MS = 30_000;
21
- function atomicWriteJson(file, value) {
22
- const temp = join(dirname(file), `.${file.split(/[\\/]/).pop()}.${process.pid}.${Date.now()}.tmp`);
23
- writeFileSync(temp, JSON.stringify(value, null, 2), 'utf-8');
24
- try {
25
- renameSync(temp, file);
26
- }
27
- catch (error) {
28
- try {
29
- rmSync(temp, { force: true });
30
- }
31
- catch { /* preserve the original write error */ }
32
- throw error;
33
- }
34
- }
13
+ import { SessionStateError } from './session-lock.js';
14
+ import { withSessionRead, withSessionWrite } from './session-store.js';
15
+ import { bodyVersionId, ensureBodyVersion } from './session-db.js';
16
+ import { readResults as readStoredResults, writeResults as writeStoredResults } from './session-store-results.js';
17
+ export { SessionStateError } from './session-lock.js';
35
18
  function withSessionLock(sessionDir, action) {
36
- mkdirSync(sessionDir, { recursive: true });
37
- const lockDir = join(sessionDir, '.lock');
38
- let acquired = false;
39
- try {
40
- try {
41
- mkdirSync(lockDir);
42
- acquired = true;
43
- }
44
- catch (error) {
45
- try {
46
- const age = Date.now() - statSync(lockDir).mtimeMs;
47
- if (age > SESSION_LOCK_STALE_MS)
48
- rmSync(lockDir, { recursive: true, force: true });
49
- else
50
- throw error;
51
- mkdirSync(lockDir);
52
- acquired = true;
53
- }
54
- catch {
55
- throw new SessionStateError('SESSION_BUSY', `Session is busy: ${sessionDir}`);
56
- }
57
- }
58
- return action();
59
- }
60
- finally {
61
- if (acquired) {
62
- try {
63
- rmSync(lockDir, { recursive: true, force: true });
64
- }
65
- catch { /* lock cleanup is best effort */ }
66
- }
67
- }
19
+ return withSessionWrite(sessionDir, action);
68
20
  }
69
21
  /** Keep related session artifacts consistent while one command updates them. */
70
22
  export function mutateSessionState(sessionDir, action) {
@@ -140,6 +92,7 @@ function makeResult(input, round) {
140
92
  }
141
93
  else {
142
94
  result.content = input.content ?? '';
95
+ result.contentLength = result.content.length;
143
96
  result.extractor = input.extractor || 'default';
144
97
  result.extractedAt = input.extractedAt ?? now;
145
98
  }
@@ -211,29 +164,85 @@ function pruneGraphProvenance(graph, resultIdValue) {
211
164
  }
212
165
  return changed;
213
166
  }
167
+ function markGraphProvenancePending(graph, resultIdValue) {
168
+ let changed = false;
169
+ graph.forEachNode((node, attrs) => {
170
+ if (attrs.sourceResultIds?.includes(resultIdValue) && !attrs.pendingSourceResultIds?.includes(resultIdValue)) {
171
+ graph.mergeNodeAttributes(node, { pendingSourceResultIds: [...(attrs.pendingSourceResultIds ?? []), resultIdValue] });
172
+ changed = true;
173
+ }
174
+ });
175
+ graph.forEachEdge((edge, attrs) => {
176
+ if (attrs.sourceResultIds?.includes(resultIdValue) && !attrs.pendingSourceResultIds?.includes(resultIdValue)) {
177
+ graph.mergeEdgeAttributes(edge, { pendingSourceResultIds: [...(attrs.pendingSourceResultIds ?? []), resultIdValue] });
178
+ changed = true;
179
+ }
180
+ });
181
+ return changed;
182
+ }
183
+ export function visibleSessionGraph(graph, results) {
184
+ const visible = graph.copy();
185
+ const pendingResults = new Set(results.filter(result => result.status !== 'approved' || result.skippedAt).map(result => result.id));
186
+ const dropNodes = [];
187
+ visible.forEachNode((node, attrs) => {
188
+ if (attrs.type === 'result' && pendingResults.has(node)) {
189
+ dropNodes.push(node);
190
+ return;
191
+ }
192
+ if (!attrs.pendingSourceResultIds?.length || !attrs.sourceResultIds?.length)
193
+ return;
194
+ const active = attrs.sourceResultIds.filter(id => !attrs.pendingSourceResultIds.includes(id));
195
+ if (!active.length)
196
+ dropNodes.push(node);
197
+ else
198
+ visible.mergeNodeAttributes(node, { sourceResultIds: active });
199
+ });
200
+ for (const node of dropNodes)
201
+ visible.dropNode(node);
202
+ const dropEdges = [];
203
+ const affectedPathEdges = [];
204
+ visible.forEachEdge((edge, attrs, source, target) => {
205
+ if (!attrs.pendingSourceResultIds?.length || !attrs.sourceResultIds?.length)
206
+ return;
207
+ const active = attrs.sourceResultIds.filter(id => !attrs.pendingSourceResultIds.includes(id));
208
+ if (!active.length) {
209
+ dropEdges.push(edge);
210
+ affectedPathEdges.push([source, target]);
211
+ }
212
+ else
213
+ visible.mergeEdgeAttributes(edge, { sourceResultIds: active });
214
+ });
215
+ for (const edge of dropEdges)
216
+ visible.dropEdge(edge);
217
+ const dropPaths = [];
218
+ visible.forEachNode((node, attrs) => {
219
+ if (attrs.type === 'path' && attrs.entities && (attrs.entities.some(entity => graph.hasNode(entity) && !visible.hasNode(entity))
220
+ || affectedPathEdges.some(([source, target]) => attrs.entities.includes(source) && attrs.entities.includes(target))))
221
+ dropPaths.push(node);
222
+ });
223
+ for (const node of dropPaths)
224
+ visible.dropNode(node);
225
+ return visible;
226
+ }
214
227
  function writeResults(sessionDir, results, rounds) {
215
- atomicWriteJson(join(sessionDir, 'results.json'), { status: 'ok', data: { results, rounds } });
228
+ withSessionWrite(sessionDir, db => writeStoredResults(db, results, rounds));
216
229
  }
217
230
  function readResultsFile(sessionDir) {
218
- const file = join(sessionDir, 'results.json');
219
- if (!existsSync(file))
220
- return undefined;
221
231
  try {
222
- const parsed = JSON.parse(readFileSync(file, 'utf-8'));
223
- if (parsed.status !== 'ok' || !Array.isArray(parsed.data?.results) || !Number.isSafeInteger(parsed.data.rounds)) {
224
- throw new Error('invalid results envelope');
225
- }
226
- return parsed;
232
+ return withSessionRead(sessionDir, readStoredResults);
227
233
  }
228
234
  catch (error) {
229
- throw new SessionStateError('SESSION_CORRUPTED', `Cannot read session results: ${file}`);
235
+ if (error instanceof SessionStateError)
236
+ throw error;
237
+ throw new SessionStateError('SESSION_CORRUPTED', `Cannot read session results: ${sessionDir}`);
230
238
  }
231
239
  }
232
240
  function touchMeta(sessionDir) {
233
241
  const existing = loadSessionMeta(sessionDir);
234
242
  if (!existing)
235
243
  return;
236
- atomicWriteJson(join(sessionDir, 'meta.json'), { ...existing, updatedAt: Date.now() });
244
+ withSessionWrite(sessionDir, db => db.prepare("INSERT INTO session_meta (key, data) VALUES ('meta', ?) ON CONFLICT(key) DO UPDATE SET data=excluded.data")
245
+ .run(JSON.stringify({ ...existing, updatedAt: Date.now() })));
237
246
  }
238
247
  /** A result may enter evidence and semantic workflows only with a captured body. */
239
248
  export function hasVerifiedContent(result) {
@@ -268,7 +277,7 @@ export function initSessionDir(sessionDir, owner, description, query) {
268
277
  updatedAt: now,
269
278
  query: query || existing?.query || '',
270
279
  };
271
- atomicWriteJson(join(sessionDir, 'meta.json'), meta);
280
+ withSessionWrite(sessionDir, db => db.prepare("INSERT INTO session_meta (key, data) VALUES ('meta', ?) ON CONFLICT(key) DO UPDATE SET data=excluded.data").run(JSON.stringify(meta)));
272
281
  }
273
282
  /** Agent write inputs must belong to exactly the session being mutated. */
274
283
  export function validateSessionInputFile(sessionDir, inputFile) {
@@ -286,12 +295,33 @@ export function loadSessionResults(sessionDir) {
286
295
  export function loadSessionRounds(sessionDir) {
287
296
  return readResultsFile(sessionDir)?.data.rounds ?? 0;
288
297
  }
289
- export function appendSessionResults(sessionDir, newResults) {
298
+ /** Record each successful query immediately; the first success allocates a batch round. */
299
+ export function recordSuccessfulQuery(sessionDir, query, allocatedRound) {
300
+ return withSessionWrite(sessionDir, db => {
301
+ const row = db.prepare("SELECT data FROM session_meta WHERE key = 'rounds'").get();
302
+ const current = row ? JSON.parse(String(row.data)) : 0;
303
+ if (!Number.isSafeInteger(current) || current < 0)
304
+ throw new SessionStateError('SESSION_CORRUPTED', 'Invalid stored round count');
305
+ const round = allocatedRound ?? current + 1;
306
+ db.prepare('INSERT INTO search_queries (round, query, executed_at) VALUES (?, ?, ?)').run(round, query, Date.now());
307
+ if (round > current)
308
+ db.prepare("INSERT INTO session_meta (key, data) VALUES ('rounds', ?) ON CONFLICT(key) DO UPDATE SET data=excluded.data").run(JSON.stringify(round));
309
+ return round;
310
+ });
311
+ }
312
+ export function loadSessionQueryHistory(sessionDir) {
313
+ return withSessionRead(sessionDir, db => {
314
+ const recorded = db.prepare('SELECT query FROM search_queries ORDER BY id').all().map(row => String(row.query));
315
+ const legacy = db.prepare('SELECT data FROM origins ORDER BY result_id, ordinal').all().map(row => JSON.parse(String(row.data)).query);
316
+ return [...new Set([...recorded, ...legacy].filter(query => typeof query === 'string' && query.trim()))];
317
+ }) ?? [];
318
+ }
319
+ export function appendSessionResults(sessionDir, newResults, allocatedRound) {
290
320
  return withSessionLock(sessionDir, () => {
291
321
  const state = readResultsFile(sessionDir);
292
322
  const results = state?.data.results ?? [];
293
323
  const currentRounds = state?.data.rounds ?? 0;
294
- const incrementRound = newResults.some(needsRound);
324
+ const incrementRound = allocatedRound === undefined && newResults.some(needsRound);
295
325
  const round = incrementRound ? currentRounds + 1 : currentRounds;
296
326
  const byKey = new Map(results.map(result => [resultUrlKey(result), result]));
297
327
  let added = 0;
@@ -303,7 +333,10 @@ export function appendSessionResults(sessionDir, newResults) {
303
333
  // Every origin records a round, so no reader has to guess what an
304
334
  // absent one means. A discovery carries the round it opened; an
305
335
  // extracted body carries the round that discovered it.
306
- const importRound = Math.max(1, round);
336
+ const previousRounds = existing?.origins?.map(origin => origin.round).filter((value) => Number.isSafeInteger(value) && value > 0) ?? [];
337
+ const importRound = existing && inferredContentType(input) === 'extracted' && previousRounds.length
338
+ ? Math.min(...previousRounds)
339
+ : Math.max(1, allocatedRound ?? round);
307
340
  if (!existing) {
308
341
  const created = makeResult(input, importRound);
309
342
  byKey.set(key, created);
@@ -313,11 +346,17 @@ export function appendSessionResults(sessionDir, newResults) {
313
346
  let changed = mergeOrigins(existing, input.origins ?? [], importRound);
314
347
  if (inferredContentType(input) === 'extracted') {
315
348
  const nextContent = input.content ?? '';
349
+ if (existing.contentLength !== nextContent.length) {
350
+ existing.contentLength = nextContent.length;
351
+ changed = true;
352
+ }
316
353
  const bodyChanged = existing.contentType !== 'extracted' || existing.content !== nextContent;
317
354
  const nextExtractedAt = input.extractedAt ?? Date.now();
318
355
  if (bodyChanged) {
319
356
  existing.contentType = 'extracted';
320
357
  existing.content = nextContent;
358
+ if (existing.approvedSnapshotId)
359
+ existing.contentNeedsApproval = true;
321
360
  changed = true;
322
361
  }
323
362
  if (existing.extractor !== (input.extractor || 'default')) {
@@ -354,7 +393,7 @@ export function appendSessionResults(sessionDir, newResults) {
354
393
  existing.title = input.title;
355
394
  changed = true;
356
395
  }
357
- if (input.excerpt !== undefined && input.excerpt !== existing.excerpt) {
396
+ if (input.excerpt !== undefined && (inferredContentType(input) !== 'extracted' || input.excerpt.trim()) && input.excerpt !== existing.excerpt) {
358
397
  existing.excerpt = input.excerpt;
359
398
  changed = true;
360
399
  }
@@ -391,6 +430,13 @@ export function appendSessionResults(sessionDir, newResults) {
391
430
  return { added, updated, total: all.length, round, approvedResults };
392
431
  });
393
432
  }
433
+ export function appendAndInjectSessionResults(sessionDir, newResults, allocatedRound) {
434
+ return withSessionWrite(sessionDir, () => {
435
+ const result = appendSessionResults(sessionDir, newResults, allocatedRound);
436
+ injectApprovedResults(sessionDir, result.approvedResults);
437
+ return result;
438
+ });
439
+ }
394
440
  /** A search result still waiting for a body, and not yet given up on. */
395
441
  export function isPendingExtraction(result) {
396
442
  return result.contentType === 'search'
@@ -414,16 +460,30 @@ export function getApprovedResults(sessionDir) {
414
460
  return loadSessionResults(sessionDir).filter(result => result.status === 'approved' && !result.skippedAt && hasVerifiedContent(result));
415
461
  }
416
462
  function repairInvalidDependents(sessionDir, results) {
463
+ const changedRelations = withSessionWrite(sessionDir, db => {
464
+ const rows = db.prepare('SELECT * FROM source_relations WHERE invalidated_at IS NULL').all();
465
+ const changed = new Set();
466
+ for (const row of rows) {
467
+ const stale = [['left_result_id', 'left_snapshot_id'], ['right_result_id', 'right_snapshot_id']].some(([resultKey, snapshotKey]) => {
468
+ const result = results.find(item => item.id === row[resultKey]);
469
+ return !result || typeof result.content !== 'string' || bodyVersionId(result.id, result.content) !== row[snapshotKey];
470
+ });
471
+ if (stale) {
472
+ db.prepare("UPDATE source_relations SET invalidated_at = ?, invalidation_reason = 'snapshot_changed' WHERE id = ?").run(Date.now(), String(row.id));
473
+ changed.add(String(row.claim_id));
474
+ }
475
+ }
476
+ return changed;
477
+ });
417
478
  const invalidReasons = new Map(results
418
- .filter(result => result.skippedAt || result.status !== 'approved' || !hasVerifiedContent(result))
479
+ .filter(result => result.skippedAt || result.contentNeedsApproval || (result.approvedSnapshotId !== undefined
480
+ && (typeof result.content !== 'string' || result.approvedSnapshotId !== bodyVersionId(result.id, result.content))))
419
481
  .map(result => [result.id, result.skippedAt ? 'sourceSkipped' : 'contentChanged']));
420
- if (!invalidReasons.size)
421
- return;
422
- try {
482
+ {
423
483
  assertClaimsStoreReadable(sessionDir);
424
484
  const evidences = loadEvidences(sessionDir);
425
- const affectedClaims = new Set();
426
- const newlyInvalidClaims = new Set();
485
+ const affectedClaims = new Set(changedRelations);
486
+ const newlyInvalidClaims = new Set(changedRelations);
427
487
  const now = Date.now();
428
488
  let evidenceChanged = false;
429
489
  for (const evidence of evidences) {
@@ -431,7 +491,33 @@ function repairInvalidDependents(sessionDir, results) {
431
491
  if (reason) {
432
492
  affectedClaims.add(evidence.claimId);
433
493
  }
434
- if (reason && !evidence.invalid) {
494
+ if (evidence.invalid && evidence.invalidatedAt !== undefined)
495
+ affectedClaims.add(evidence.claimId);
496
+ const result = results.find(item => item.id === evidence.resultId);
497
+ const changedAgain = reason === 'contentChanged' && evidence.invalid && evidence.relocationStatus === 'matched'
498
+ && typeof result?.content === 'string' && evidence.snapshotId !== bodyVersionId(result.id, result.content);
499
+ if (reason && (!evidence.invalid || changedAgain)) {
500
+ if (reason === 'contentChanged' && evidence.snapshotId && result?.content) {
501
+ const oldSnapshot = withSessionRead(sessionDir, db => db.prepare('SELECT content FROM body_versions WHERE id = ? AND result_id = ?').get(evidence.snapshotId, evidence.resultId));
502
+ const oldContent = typeof oldSnapshot?.content === 'string' ? oldSnapshot.content : '';
503
+ const oldQuote = oldContent.slice(evidence.charStart, evidence.charEnd);
504
+ const oldValid = evidence.charStart >= 0 && evidence.charEnd > evidence.charStart && evidence.charEnd <= oldContent.length
505
+ && oldQuote === evidence.quote && createHash('sha256').update(oldQuote).digest('hex') === evidence.contentHash;
506
+ const first = result.content.indexOf(evidence.quote);
507
+ const unique = oldValid && evidence.quote.length > 0 && first >= 0 && result.content.indexOf(evidence.quote, first + 1) < 0;
508
+ if (unique) {
509
+ evidence.anchorHistory = [...(evidence.anchorHistory ?? []), { snapshotId: evidence.snapshotId, charStart: evidence.charStart, charEnd: evidence.charEnd, extractedAt: evidence.extractedAt, snapshotBinding: evidence.snapshotBinding }];
510
+ evidence.snapshotId = withSessionWrite(sessionDir, db => ensureBodyVersion(db, result.id, result.content));
511
+ evidence.snapshotBinding = 'anchored';
512
+ evidence.charStart = first;
513
+ evidence.charEnd = first + evidence.quote.length;
514
+ if (result.extractedAt !== undefined)
515
+ evidence.extractedAt = result.extractedAt;
516
+ evidence.relocationStatus = 'matched';
517
+ }
518
+ else
519
+ evidence.relocationStatus = 'needs_check';
520
+ }
435
521
  evidence.invalid = true;
436
522
  evidence.invalidatedAt = now;
437
523
  evidence.invalidationReason = reason;
@@ -462,21 +548,17 @@ function repairInvalidDependents(sessionDir, results) {
462
548
  saveEvidences(sessionDir, evidences);
463
549
  }
464
550
  }
465
- catch { /* Preserve corrupt claim artifacts for their dedicated repair commands. */ }
466
- try {
551
+ {
467
552
  const { graph, missing } = readSessionGraph(sessionDir);
468
553
  if (!missing) {
469
554
  let graphChanged = false;
470
- for (const resultIdValue of invalidReasons.keys())
471
- graphChanged = pruneGraphProvenance(graph, resultIdValue) || graphChanged;
555
+ for (const [resultIdValue, reason] of invalidReasons) {
556
+ graphChanged = (reason === 'sourceSkipped' ? pruneGraphProvenance(graph, resultIdValue) : markGraphProvenancePending(graph, resultIdValue)) || graphChanged;
557
+ }
472
558
  if (graphChanged)
473
559
  writeSessionGraph(sessionDir, graph);
474
560
  }
475
561
  }
476
- catch (error) {
477
- if (!(error instanceof SessionStateError))
478
- throw error;
479
- }
480
562
  }
481
563
  export function approveResults(sessionDir, selections) {
482
564
  return withSessionLock(sessionDir, () => {
@@ -500,15 +582,48 @@ export function approveResults(sessionDir, selections) {
500
582
  for (const result of results) {
501
583
  if (selected.has(result.id) && result.status !== 'approved') {
502
584
  result.status = 'approved';
585
+ result.approvedSnapshotId = bodyVersionId(result.id, result.content);
586
+ result.contentNeedsApproval = false;
503
587
  touch(result);
504
588
  approvedResults.push(result);
505
589
  }
506
590
  }
591
+ if (approvedResults.length) {
592
+ const evidence = loadEvidences(sessionDir);
593
+ const claims = loadClaims(sessionDir);
594
+ const changedClaims = new Set();
595
+ for (const item of evidence) {
596
+ const result = approvedResults.find(candidate => candidate.id === item.resultId);
597
+ if (!result?.content || !item.invalid || item.invalidationReason !== 'contentChanged' || item.relocationStatus !== 'matched')
598
+ continue;
599
+ const currentId = withSessionWrite(sessionDir, db => ensureBodyVersion(db, result.id, result.content));
600
+ if (item.snapshotId !== currentId || result.content.slice(item.charStart, item.charEnd) !== item.quote)
601
+ continue;
602
+ item.invalid = false;
603
+ delete item.invalidatedAt;
604
+ delete item.invalidationReason;
605
+ changedClaims.add(item.claimId);
606
+ }
607
+ if (changedClaims.size) {
608
+ for (const claim of claims)
609
+ if (changedClaims.has(claim.id))
610
+ claim.status = 'verifying';
611
+ saveEvidences(sessionDir, evidence);
612
+ saveClaims(sessionDir, claims);
613
+ }
614
+ }
507
615
  writeResults(sessionDir, results, state?.data.rounds ?? 0);
508
616
  touchMeta(sessionDir);
509
617
  return { approved: approvedResults.length, total: results.length, approvedResults };
510
618
  });
511
619
  }
620
+ export function approveAndInjectResults(sessionDir, selections) {
621
+ return withSessionWrite(sessionDir, () => {
622
+ const approval = approveResults(sessionDir, selections);
623
+ const injectInfo = approval.error ? { nodesAdded: 0, edgesAdded: 0 } : injectApprovedResults(sessionDir, approval.approvedResults);
624
+ return { approval, injectInfo };
625
+ });
626
+ }
512
627
  export function setSkipped(sessionDir, selections, skipped) {
513
628
  return withSessionLock(sessionDir, () => {
514
629
  const state = readResultsFile(sessionDir);
@@ -568,19 +683,20 @@ export function recordExtractionOutcome(sessionDir, outcomes) {
568
683
  continue;
569
684
  const wasSkipped = result.skippedAt !== undefined;
570
685
  const changedBody = result.contentType !== 'extracted' || result.content !== outcome.content;
686
+ if (changedBody && result.approvedSnapshotId)
687
+ result.contentNeedsApproval = true;
571
688
  result.contentType = 'extracted';
572
689
  result.content = outcome.content;
573
690
  result.extractor = outcome.extractor || 'default';
574
691
  result.extractedAt = outcome.extractedAt ?? Date.now();
575
692
  result.title = outcome.title || result.title;
576
- if (outcome.excerpt !== undefined)
693
+ if (outcome.excerpt?.trim())
577
694
  result.excerpt = outcome.excerpt;
578
695
  if (outcome.byline !== undefined)
579
696
  result.byline = outcome.byline;
580
697
  if (outcome.siteName !== undefined)
581
698
  result.siteName = outcome.siteName;
582
- if (outcome.length !== undefined)
583
- result.contentLength = outcome.length;
699
+ result.contentLength = outcome.content.length;
584
700
  result.skippedAt = undefined;
585
701
  result.failureCount = undefined;
586
702
  result.lastFailedAt = undefined;
@@ -604,28 +720,53 @@ export function mergeExtractedContent(sessionDir, extracted) {
604
720
  return { updated: result.updated, total: result.total };
605
721
  }
606
722
  function readSessionGraph(sessionDir) {
607
- const file = join(sessionDir, 'graph.json');
608
- if (!existsSync(file))
609
- return { graph: new MultiDirectedGraph(), missing: true };
610
723
  try {
611
- const parsed = JSON.parse(readFileSync(file, 'utf-8'));
724
+ const row = withSessionRead(sessionDir, db => db.prepare('SELECT data FROM graph_snapshot WHERE id = 1').get());
725
+ if (!row)
726
+ return { graph: new MultiDirectedGraph(), missing: true };
727
+ const parsed = JSON.parse(String(row.data));
612
728
  const graphData = parsed.status === 'ok' && parsed.data?.graph ? parsed.data.graph : null;
613
729
  if (!graphData)
614
730
  throw new Error('invalid graph envelope');
615
731
  return { graph: deserializeGraph(graphData), missing: false };
616
732
  }
617
- catch {
618
- throw new SessionStateError('SESSION_CORRUPTED', `Cannot read session graph: ${file}`);
733
+ catch (error) {
734
+ if (error instanceof SessionStateError)
735
+ throw error;
736
+ throw new SessionStateError('SESSION_CORRUPTED', `Cannot read session graph: ${sessionDir}`);
619
737
  }
620
738
  }
621
739
  export function loadSessionGraph(sessionDir) {
740
+ if (!['session.sqlite', 'meta.json', 'results.json', 'graph.json', 'claims'].some(name => existsSync(join(sessionDir, name)))) {
741
+ return new MultiDirectedGraph();
742
+ }
743
+ return withSessionLock(sessionDir, () => {
744
+ repairInvalidDependents(sessionDir, loadSessionResults(sessionDir));
745
+ return visibleSessionGraph(readSessionGraph(sessionDir).graph, loadSessionResults(sessionDir));
746
+ });
747
+ }
748
+ export function listPendingGraph(sessionDir) {
749
+ if (!['session.sqlite', 'meta.json', 'results.json', 'graph.json', 'claims'].some(name => existsSync(join(sessionDir, name))))
750
+ return { nodes: [], edges: [] };
622
751
  return withSessionLock(sessionDir, () => {
623
752
  repairInvalidDependents(sessionDir, loadSessionResults(sessionDir));
624
- return readSessionGraph(sessionDir).graph;
753
+ const graph = readSessionGraph(sessionDir).graph;
754
+ const nodes = [];
755
+ const edges = [];
756
+ graph.forEachNode((id, attrs) => {
757
+ if (attrs.pendingSourceResultIds?.length)
758
+ nodes.push({ id, ...attrs });
759
+ });
760
+ graph.forEachEdge((id, attrs, source, target) => {
761
+ if (attrs.pendingSourceResultIds?.length)
762
+ edges.push({ id, source, target, ...attrs });
763
+ });
764
+ return { nodes, edges };
625
765
  });
626
766
  }
627
767
  function writeSessionGraph(sessionDir, graph) {
628
- atomicWriteJson(join(sessionDir, 'graph.json'), { status: 'ok', data: { graph: serializeGraph(graph), stats: graphStats(graph) } });
768
+ const value = { status: 'ok', data: { graph: serializeGraph(graph), stats: graphStats(graph) } };
769
+ withSessionWrite(sessionDir, db => db.prepare('INSERT INTO graph_snapshot (id, data) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET data=excluded.data').run(JSON.stringify(value)));
629
770
  touchMeta(sessionDir);
630
771
  }
631
772
  function buildApprovedStructuralEdges(graph, approved) {
@@ -662,7 +803,7 @@ export function injectApprovedResults(sessionDir, approved) {
662
803
  return mutateSessionGraph(sessionDir, graph => {
663
804
  const beforeNodes = graph.order;
664
805
  const beforeEdges = graph.size;
665
- // Rebuild all approved structure when graph.json is absent, then add this approval.
806
+ // Rebuild all approved structure when the graph is absent, then add this approval.
666
807
  buildApprovedStructuralEdges(graph, getApprovedResults(sessionDir));
667
808
  return { nodesAdded: graph.order - beforeNodes, edgesAdded: graph.size - beforeEdges };
668
809
  });