digdig 0.0.1 → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +439 -2
- package/digdig.config.example.json +14 -0
- package/dist/claims/deterministic-checks.d.ts +48 -0
- package/dist/claims/deterministic-checks.d.ts.map +1 -0
- package/dist/claims/deterministic-checks.js +162 -0
- package/dist/claims/deterministic-checks.js.map +1 -0
- package/dist/claims/policy.d.ts +25 -0
- package/dist/claims/policy.d.ts.map +1 -0
- package/dist/claims/policy.js +168 -0
- package/dist/claims/policy.js.map +1 -0
- package/dist/claims/store.d.ts +37 -0
- package/dist/claims/store.d.ts.map +1 -0
- package/dist/claims/store.js +152 -0
- package/dist/claims/store.js.map +1 -0
- package/dist/claims/types.d.ts +98 -0
- package/dist/claims/types.d.ts.map +1 -0
- package/dist/claims/types.js +9 -0
- package/dist/claims/types.js.map +1 -0
- package/dist/commands/build-graph.d.ts +8 -0
- package/dist/commands/build-graph.d.ts.map +1 -0
- package/dist/commands/build-graph.js +70 -0
- package/dist/commands/build-graph.js.map +1 -0
- package/dist/commands/claim.d.ts +13 -0
- package/dist/commands/claim.d.ts.map +1 -0
- package/dist/commands/claim.js +131 -0
- package/dist/commands/claim.js.map +1 -0
- package/dist/commands/doc-index.d.ts +12 -0
- package/dist/commands/doc-index.d.ts.map +1 -0
- package/dist/commands/doc-index.js +49 -0
- package/dist/commands/doc-index.js.map +1 -0
- package/dist/commands/doc-search.d.ts +16 -0
- package/dist/commands/doc-search.d.ts.map +1 -0
- package/dist/commands/doc-search.js +41 -0
- package/dist/commands/doc-search.js.map +1 -0
- package/dist/commands/evidence.d.ts +20 -0
- package/dist/commands/evidence.d.ts.map +1 -0
- package/dist/commands/evidence.js +215 -0
- package/dist/commands/evidence.js.map +1 -0
- package/dist/commands/extract.d.ts +10 -0
- package/dist/commands/extract.d.ts.map +1 -0
- package/dist/commands/extract.js +77 -0
- package/dist/commands/extract.js.map +1 -0
- package/dist/commands/graph-add.d.ts +7 -0
- package/dist/commands/graph-add.d.ts.map +1 -0
- package/dist/commands/graph-add.d.ts.sync-conflict-20260629-232900-2SGIW5T.map +1 -0
- package/dist/commands/graph-add.js +93 -0
- package/dist/commands/graph-add.js.map +1 -0
- package/dist/commands/graph-add.js.sync-conflict-20260629-232916-2SGIW5T.map +1 -0
- package/dist/commands/graph-add.sync-conflict-20260629-232853-2SGIW5T.js +163 -0
- package/dist/commands/graph-drill.d.ts +11 -0
- package/dist/commands/graph-drill.d.ts.map +1 -0
- package/dist/commands/graph-drill.js +26 -0
- package/dist/commands/graph-drill.js.map +1 -0
- package/dist/commands/graph-explore.d.ts +10 -0
- package/dist/commands/graph-explore.d.ts.map +1 -0
- package/dist/commands/graph-explore.js +32 -0
- package/dist/commands/graph-explore.js.map +1 -0
- package/dist/commands/graph-obfuscate.d.ts +17 -0
- package/dist/commands/graph-obfuscate.d.ts.map +1 -0
- package/dist/commands/graph-obfuscate.js +110 -0
- package/dist/commands/graph-obfuscate.js.map +1 -0
- package/dist/commands/graph-search.d.ts +11 -0
- package/dist/commands/graph-search.d.ts.map +1 -0
- package/dist/commands/graph-search.js +19 -0
- package/dist/commands/graph-search.js.map +1 -0
- package/dist/commands/graph-traverse.d.ts +10 -0
- package/dist/commands/graph-traverse.d.ts.map +1 -0
- package/dist/commands/graph-traverse.js +39 -0
- package/dist/commands/graph-traverse.js.map +1 -0
- package/dist/commands/json-input.d.ts +18 -0
- package/dist/commands/json-input.d.ts.map +1 -0
- package/dist/commands/json-input.js +50 -0
- package/dist/commands/json-input.js.map +1 -0
- package/dist/commands/query-graph.d.ts +13 -0
- package/dist/commands/query-graph.d.ts.map +1 -0
- package/dist/commands/query-graph.js +219 -0
- package/dist/commands/query-graph.js.map +1 -0
- package/dist/commands/raw.d.ts +14 -0
- package/dist/commands/raw.d.ts.map +1 -0
- package/dist/commands/raw.js +125 -0
- package/dist/commands/raw.js.map +1 -0
- package/dist/commands/results-add.d.ts +10 -0
- package/dist/commands/results-add.d.ts.map +1 -0
- package/dist/commands/results-add.js +80 -0
- package/dist/commands/results-add.js.map +1 -0
- package/dist/commands/review.d.ts +12 -0
- package/dist/commands/review.d.ts.map +1 -0
- package/dist/commands/review.js +119 -0
- package/dist/commands/review.js.map +1 -0
- package/dist/commands/session.d.ts +28 -0
- package/dist/commands/session.d.ts.map +1 -0
- package/dist/commands/session.js +149 -0
- package/dist/commands/session.js.map +1 -0
- package/dist/commands/verdict.d.ts +9 -0
- package/dist/commands/verdict.d.ts.map +1 -0
- package/dist/commands/verdict.js +40 -0
- package/dist/commands/verdict.js.map +1 -0
- package/dist/config.d.ts +28 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +148 -0
- package/dist/config.js.map +1 -0
- package/dist/deep/co-occurrence.d.ts +50 -0
- package/dist/deep/co-occurrence.d.ts.map +1 -0
- package/dist/deep/co-occurrence.js +95 -0
- package/dist/deep/co-occurrence.js.map +1 -0
- package/dist/deep/dedupe.d.ts +19 -0
- package/dist/deep/dedupe.d.ts.map +1 -0
- package/dist/deep/dedupe.js +96 -0
- package/dist/deep/dedupe.js.map +1 -0
- package/dist/deep/degree-utils.d.ts +39 -0
- package/dist/deep/degree-utils.d.ts.map +1 -0
- package/dist/deep/degree-utils.js +42 -0
- package/dist/deep/degree-utils.js.map +1 -0
- package/dist/deep/extractor.d.sync-conflict-20260629-232902-2SGIW5T.ts +37 -0
- package/dist/deep/extractor.d.ts +42 -0
- package/dist/deep/extractor.d.ts.map +1 -0
- package/dist/deep/extractor.d.ts.sync-conflict-20260629-232921-2SGIW5T.map +1 -0
- package/dist/deep/extractor.js +392 -0
- package/dist/deep/extractor.js.map +1 -0
- package/dist/deep/extractor.js.sync-conflict-20260629-232921-2SGIW5T.map +1 -0
- package/dist/deep/extractor.sync-conflict-20260629-232903-2SGIW5T.js +203 -0
- package/dist/deep/graph-explore.d.ts +115 -0
- package/dist/deep/graph-explore.d.ts.map +1 -0
- package/dist/deep/graph-explore.js +588 -0
- package/dist/deep/graph-explore.js.map +1 -0
- package/dist/deep/graph-obfuscate.d.ts +51 -0
- package/dist/deep/graph-obfuscate.d.ts.map +1 -0
- package/dist/deep/graph-obfuscate.js +226 -0
- package/dist/deep/graph-obfuscate.js.map +1 -0
- package/dist/deep/graph-preprocess.d.ts +48 -0
- package/dist/deep/graph-preprocess.d.ts.map +1 -0
- package/dist/deep/graph-preprocess.js +40 -0
- package/dist/deep/graph-preprocess.js.map +1 -0
- package/dist/deep/graph-sampling.d.ts +51 -0
- package/dist/deep/graph-sampling.d.ts.map +1 -0
- package/dist/deep/graph-sampling.js +410 -0
- package/dist/deep/graph-sampling.js.map +1 -0
- package/dist/deep/graph.d.sync-conflict-20260629-232917-2SGIW5T.ts +78 -0
- package/dist/deep/graph.d.ts +87 -0
- package/dist/deep/graph.d.ts.map +1 -0
- package/dist/deep/graph.d.ts.sync-conflict-20260629-232911-2SGIW5T.map +1 -0
- package/dist/deep/graph.js +200 -0
- package/dist/deep/graph.js.map +1 -0
- package/dist/deep/graph.js.sync-conflict-20260629-232855-2SGIW5T.map +1 -0
- package/dist/deep/graph.sync-conflict-20260629-232907-2SGIW5T.js +194 -0
- package/dist/deep/index.d.ts +10 -0
- package/dist/deep/index.d.ts.map +1 -0
- package/dist/deep/index.js +10 -0
- package/dist/deep/index.js.map +1 -0
- package/dist/deep/iteration-data.d.ts +38 -0
- package/dist/deep/iteration-data.d.ts.map +1 -0
- package/dist/deep/iteration-data.js +49 -0
- package/dist/deep/iteration-data.js.map +1 -0
- package/dist/deep/keywords.d.ts +27 -0
- package/dist/deep/keywords.d.ts.map +1 -0
- package/dist/deep/keywords.js +293 -0
- package/dist/deep/keywords.js.map +1 -0
- package/dist/deep/local-doc/indexer.d.ts +30 -0
- package/dist/deep/local-doc/indexer.d.ts.map +1 -0
- package/dist/deep/local-doc/indexer.js +402 -0
- package/dist/deep/local-doc/indexer.js.map +1 -0
- package/dist/deep/local-doc/scanner.d.ts +10 -0
- package/dist/deep/local-doc/scanner.d.ts.map +1 -0
- package/dist/deep/local-doc/scanner.js +165 -0
- package/dist/deep/local-doc/scanner.js.map +1 -0
- package/dist/deep/local-doc/searcher.d.ts +38 -0
- package/dist/deep/local-doc/searcher.d.ts.map +1 -0
- package/dist/deep/local-doc/searcher.js +212 -0
- package/dist/deep/local-doc/searcher.js.map +1 -0
- package/dist/deep/local-doc/searcher.sync-conflict-20260805-191858-2SGIW5T.d.ts +38 -0
- package/dist/deep/local-doc/searcher.sync-conflict-20260805-191858-2SGIW5T.d.ts.map +1 -0
- package/dist/deep/local-doc/searcher.sync-conflict-20260805-191858-2SGIW5T.js +212 -0
- package/dist/deep/local-doc/searcher.sync-conflict-20260805-191858-2SGIW5T.js.map +1 -0
- package/dist/deep/local-doc/types.d.ts +61 -0
- package/dist/deep/local-doc/types.d.ts.map +1 -0
- package/dist/deep/local-doc/types.js +18 -0
- package/dist/deep/local-doc/types.js.map +1 -0
- package/dist/deep/path-extraction.d.ts +53 -0
- package/dist/deep/path-extraction.d.ts.map +1 -0
- package/dist/deep/path-extraction.js +229 -0
- package/dist/deep/path-extraction.js.map +1 -0
- package/dist/deep/quality-assess.d.ts +46 -0
- package/dist/deep/quality-assess.d.ts.map +1 -0
- package/dist/deep/quality-assess.js +122 -0
- package/dist/deep/quality-assess.js.map +1 -0
- package/dist/deep/quality-assess.sync-conflict-20260728-195206-JAULAPO.d.ts +46 -0
- package/dist/deep/quality-assess.sync-conflict-20260728-195206-JAULAPO.d.ts.map +1 -0
- package/dist/deep/quality-assess.sync-conflict-20260728-195206-JAULAPO.js +122 -0
- package/dist/deep/quality-assess.sync-conflict-20260728-195206-JAULAPO.js.map +1 -0
- package/dist/deep/query-redundancy.d.ts +52 -0
- package/dist/deep/query-redundancy.d.ts.map +1 -0
- package/dist/deep/query-redundancy.js +122 -0
- package/dist/deep/query-redundancy.js.map +1 -0
- package/dist/deep/query-suggest.d.ts +35 -0
- package/dist/deep/query-suggest.d.ts.map +1 -0
- package/dist/deep/query-suggest.js +98 -0
- package/dist/deep/query-suggest.js.map +1 -0
- package/dist/deep/recovery-analysis.d.ts +60 -0
- package/dist/deep/recovery-analysis.d.ts.map +1 -0
- package/dist/deep/recovery-analysis.js +185 -0
- package/dist/deep/recovery-analysis.js.map +1 -0
- package/dist/deep/rrf.d.ts +13 -0
- package/dist/deep/rrf.d.ts.map +1 -0
- package/dist/deep/rrf.js +23 -0
- package/dist/deep/rrf.js.map +1 -0
- package/dist/deep/search-strategy.d.ts +37 -0
- package/dist/deep/search-strategy.d.ts.map +1 -0
- package/dist/deep/search-strategy.js +106 -0
- package/dist/deep/search-strategy.js.map +1 -0
- package/dist/deep/session.d.sync-conflict-20260629-232917-2SGIW5T.ts +71 -0
- package/dist/deep/session.d.ts +180 -0
- package/dist/deep/session.d.ts.map +1 -0
- package/dist/deep/session.d.ts.sync-conflict-20260629-232921-2SGIW5T.map +1 -0
- package/dist/deep/session.js +643 -0
- package/dist/deep/session.js.map +1 -0
- package/dist/deep/session.js.sync-conflict-20260629-232854-2SGIW5T.map +1 -0
- package/dist/deep/simhash.d.ts +17 -0
- package/dist/deep/simhash.d.ts.map +1 -0
- package/dist/deep/simhash.js +72 -0
- package/dist/deep/simhash.js.map +1 -0
- package/dist/deep/tfidf.d.ts +38 -0
- package/dist/deep/tfidf.d.ts.map +1 -0
- package/dist/deep/tfidf.js +103 -0
- package/dist/deep/tfidf.js.map +1 -0
- package/dist/deepseek-service.d.ts +22 -0
- package/dist/deepseek-service.d.ts.map +1 -0
- package/dist/deepseek-service.js +80 -0
- package/dist/deepseek-service.js.map +1 -0
- package/dist/entry.d.ts +9 -0
- package/dist/entry.d.ts.map +1 -0
- package/dist/entry.js +24 -0
- package/dist/entry.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -0
- package/dist/init.d.ts +16 -0
- package/dist/init.d.ts.map +1 -0
- package/dist/init.js +143 -0
- package/dist/init.js.map +1 -0
- package/dist/legacy.d.ts +60 -0
- package/dist/legacy.d.ts.map +1 -0
- package/dist/legacy.js +119 -0
- package/dist/legacy.js.map +1 -0
- package/dist/ollama-service.d.ts +22 -0
- package/dist/ollama-service.d.ts.map +1 -0
- package/dist/ollama-service.js +50 -0
- package/dist/ollama-service.js.map +1 -0
- package/dist/protocol.d.ts +23 -0
- package/dist/protocol.d.ts.map +1 -0
- package/dist/protocol.js +26 -0
- package/dist/protocol.js.map +1 -0
- package/dist/runCli.d.ts +8 -0
- package/dist/runCli.d.ts.map +1 -0
- package/dist/runCli.d.ts.sync-conflict-20260629-232854-2SGIW5T.map +1 -0
- package/dist/runCli.js +1564 -0
- package/dist/runCli.js.map +1 -0
- package/dist/runCli.js.sync-conflict-20260629-232857-2SGIW5T.map +1 -0
- package/dist/runCli.sync-conflict-20260629-232915-2SGIW5T.js +1109 -0
- package/dist/runCli.sync-conflict-20260629-233530-JAULAPO.d.ts +8 -0
- package/dist/runCli.sync-conflict-20260629-233530-JAULAPO.d.ts.map +1 -0
- package/dist/runCli.sync-conflict-20260629-233530-JAULAPO.js +1111 -0
- package/dist/runCli.sync-conflict-20260629-233530-JAULAPO.js.map +1 -0
- package/dist/service.d.ts +63 -0
- package/dist/service.d.ts.map +1 -0
- package/dist/service.js +139 -0
- package/dist/service.js.map +1 -0
- package/dist/sxng.d.ts +11 -0
- package/dist/sxng.d.ts.map +1 -0
- package/dist/sxng.js +14 -0
- package/dist/sxng.js.map +1 -0
- package/package.json +56 -12
|
@@ -0,0 +1,643 @@
|
|
|
1
|
+
/**
|
|
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.
|
|
5
|
+
*/
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'fs';
|
|
7
|
+
import { dirname, join, relative, resolve } from 'path';
|
|
8
|
+
import { MultiDirectedGraph } from 'graphology';
|
|
9
|
+
import { buildStructuralEdges, deserializeGraph, graphStats, resultId, serializeGraph } from './graph.js';
|
|
10
|
+
import { resultUrlKey } from './dedupe.js';
|
|
11
|
+
import { getDefaultSessionRoot, loadSessionMeta } from '../commands/session.js';
|
|
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
|
+
}
|
|
35
|
+
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
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/** Keep related session artifacts consistent while one command updates them. */
|
|
70
|
+
export function mutateSessionState(sessionDir, action) {
|
|
71
|
+
return withSessionLock(sessionDir, () => {
|
|
72
|
+
repairInvalidDependents(sessionDir, loadSessionResults(sessionDir));
|
|
73
|
+
return action();
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
function originKey(origin) {
|
|
77
|
+
return `${origin.tool}\0${origin.engine ?? ''}\0${origin.query}\0${origin.round ?? ''}`;
|
|
78
|
+
}
|
|
79
|
+
function mergeOrigins(target, additions, round) {
|
|
80
|
+
const normalized = additions.map(origin => ({
|
|
81
|
+
...origin,
|
|
82
|
+
...(round !== undefined && origin.round === undefined ? { round } : {}),
|
|
83
|
+
}));
|
|
84
|
+
const merged = new Map(target.origins.map(origin => [originKey(origin), origin]));
|
|
85
|
+
for (const origin of normalized)
|
|
86
|
+
merged.set(originKey(origin), origin);
|
|
87
|
+
const next = [...merged.values()];
|
|
88
|
+
const changed = JSON.stringify(next) !== JSON.stringify(target.origins);
|
|
89
|
+
target.origins = next;
|
|
90
|
+
return changed;
|
|
91
|
+
}
|
|
92
|
+
function isDirectOrigin(origin) {
|
|
93
|
+
return origin.tool === 'user' || origin.tool === 'agent';
|
|
94
|
+
}
|
|
95
|
+
function needsRound(result) {
|
|
96
|
+
return (result.origins ?? []).some(origin => !isDirectOrigin(origin) && origin.round === undefined);
|
|
97
|
+
}
|
|
98
|
+
function inferredContentType(result) {
|
|
99
|
+
if (result.contentType)
|
|
100
|
+
return result.contentType;
|
|
101
|
+
return typeof result.content === 'string' && typeof result.extractedAt === 'number' ? 'extracted' : 'search';
|
|
102
|
+
}
|
|
103
|
+
function makeResult(input, round) {
|
|
104
|
+
const contentType = inferredContentType(input);
|
|
105
|
+
const now = Date.now();
|
|
106
|
+
const result = {
|
|
107
|
+
...input,
|
|
108
|
+
id: resultId(input.url),
|
|
109
|
+
revision: 1,
|
|
110
|
+
url: input.url,
|
|
111
|
+
title: input.title,
|
|
112
|
+
contentType,
|
|
113
|
+
origins: [],
|
|
114
|
+
status: 'pending',
|
|
115
|
+
};
|
|
116
|
+
if (contentType === 'search') {
|
|
117
|
+
delete result.content;
|
|
118
|
+
delete result.extractor;
|
|
119
|
+
delete result.extractedAt;
|
|
120
|
+
// The body is not deleted with them: it moves to `excerpt`, which is this
|
|
121
|
+
// layer's name for it and what the display layer reads back. `content` is
|
|
122
|
+
// reserved for a verified extraction, so a provider body cannot stay
|
|
123
|
+
// there without claiming an extractor that does not exist.
|
|
124
|
+
if (result.excerpt === undefined) {
|
|
125
|
+
const body = input.content || input.snippet;
|
|
126
|
+
// Assigned only when non-empty: `x = undefined` would still create the
|
|
127
|
+
// key, and the point is that a bodyless result carries no excerpt at all.
|
|
128
|
+
if (body)
|
|
129
|
+
result.excerpt = body;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
else {
|
|
133
|
+
result.content = input.content ?? '';
|
|
134
|
+
result.extractor = input.extractor || 'default';
|
|
135
|
+
result.extractedAt = input.extractedAt ?? now;
|
|
136
|
+
}
|
|
137
|
+
// `snippet` is the search layer's name for the display slot; at this layer it
|
|
138
|
+
// is `excerpt`, and carrying both would be one thing with two names.
|
|
139
|
+
delete result.snippet;
|
|
140
|
+
mergeOrigins(result, input.origins ?? [], round);
|
|
141
|
+
return result;
|
|
142
|
+
}
|
|
143
|
+
function touch(result) {
|
|
144
|
+
result.revision += 1;
|
|
145
|
+
}
|
|
146
|
+
function pruneGraphProvenance(graph, resultIdValue) {
|
|
147
|
+
let changed = false;
|
|
148
|
+
const nodesToDrop = [];
|
|
149
|
+
graph.forEachNode((node, attrs) => {
|
|
150
|
+
if (!attrs.sourceResultIds?.includes(resultIdValue))
|
|
151
|
+
return;
|
|
152
|
+
const sourceResultIds = attrs.sourceResultIds.filter(id => id !== resultIdValue);
|
|
153
|
+
if (sourceResultIds.length) {
|
|
154
|
+
graph.mergeNodeAttributes(node, { sourceResultIds });
|
|
155
|
+
changed = true;
|
|
156
|
+
}
|
|
157
|
+
else
|
|
158
|
+
nodesToDrop.push(node);
|
|
159
|
+
});
|
|
160
|
+
for (const node of nodesToDrop) {
|
|
161
|
+
graph.dropNode(node);
|
|
162
|
+
changed = true;
|
|
163
|
+
}
|
|
164
|
+
const edgesToDrop = [];
|
|
165
|
+
graph.forEachEdge((edge, attrs) => {
|
|
166
|
+
if (!attrs.sourceResultIds?.includes(resultIdValue))
|
|
167
|
+
return;
|
|
168
|
+
const sourceResultIds = attrs.sourceResultIds.filter(id => id !== resultIdValue);
|
|
169
|
+
if (sourceResultIds.length) {
|
|
170
|
+
graph.replaceEdgeAttributes(edge, { ...attrs, sourceResultIds });
|
|
171
|
+
changed = true;
|
|
172
|
+
}
|
|
173
|
+
else
|
|
174
|
+
edgesToDrop.push(edge);
|
|
175
|
+
});
|
|
176
|
+
for (const edge of edgesToDrop) {
|
|
177
|
+
graph.dropEdge(edge);
|
|
178
|
+
changed = true;
|
|
179
|
+
}
|
|
180
|
+
if (graph.hasNode(resultIdValue)) {
|
|
181
|
+
graph.dropNode(resultIdValue);
|
|
182
|
+
changed = true;
|
|
183
|
+
}
|
|
184
|
+
// Path nodes derive from semantic entities and are invalid once an input entity disappears.
|
|
185
|
+
const pathsToDrop = [];
|
|
186
|
+
graph.forEachNode((node, attrs) => {
|
|
187
|
+
if (attrs.type === 'path' && attrs.entities?.some(entity => !graph.hasNode(entity)))
|
|
188
|
+
pathsToDrop.push(node);
|
|
189
|
+
});
|
|
190
|
+
for (const node of pathsToDrop) {
|
|
191
|
+
graph.dropNode(node);
|
|
192
|
+
changed = true;
|
|
193
|
+
}
|
|
194
|
+
const structuralNodesToDrop = [];
|
|
195
|
+
graph.forEachNode((node, attrs) => {
|
|
196
|
+
if ((attrs.type === 'query' || attrs.type === 'domain') && graph.degree(node) === 0)
|
|
197
|
+
structuralNodesToDrop.push(node);
|
|
198
|
+
});
|
|
199
|
+
for (const node of structuralNodesToDrop) {
|
|
200
|
+
graph.dropNode(node);
|
|
201
|
+
changed = true;
|
|
202
|
+
}
|
|
203
|
+
return changed;
|
|
204
|
+
}
|
|
205
|
+
function writeResults(sessionDir, results, rounds) {
|
|
206
|
+
atomicWriteJson(join(sessionDir, 'results.json'), { status: 'ok', data: { results, rounds } });
|
|
207
|
+
}
|
|
208
|
+
function readResultsFile(sessionDir) {
|
|
209
|
+
const file = join(sessionDir, 'results.json');
|
|
210
|
+
if (!existsSync(file))
|
|
211
|
+
return undefined;
|
|
212
|
+
try {
|
|
213
|
+
const parsed = JSON.parse(readFileSync(file, 'utf-8'));
|
|
214
|
+
if (parsed.status !== 'ok' || !Array.isArray(parsed.data?.results) || !Number.isSafeInteger(parsed.data.rounds)) {
|
|
215
|
+
throw new Error('invalid results envelope');
|
|
216
|
+
}
|
|
217
|
+
return parsed;
|
|
218
|
+
}
|
|
219
|
+
catch (error) {
|
|
220
|
+
throw new SessionStateError('SESSION_CORRUPTED', `Cannot read session results: ${file}`);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
function touchMeta(sessionDir) {
|
|
224
|
+
const existing = loadSessionMeta(sessionDir);
|
|
225
|
+
if (!existing)
|
|
226
|
+
return;
|
|
227
|
+
atomicWriteJson(join(sessionDir, 'meta.json'), { ...existing, updatedAt: Date.now() });
|
|
228
|
+
}
|
|
229
|
+
/** A result may enter evidence and semantic workflows only with a captured body. */
|
|
230
|
+
export function hasVerifiedContent(result) {
|
|
231
|
+
return result.contentType === 'extracted'
|
|
232
|
+
&& typeof result.content === 'string'
|
|
233
|
+
&& result.content.trim().length > 0
|
|
234
|
+
&& typeof result.extractedAt === 'number'
|
|
235
|
+
&& Number.isFinite(result.extractedAt)
|
|
236
|
+
&& result.extractedAt > 0
|
|
237
|
+
&& typeof result.extractor === 'string'
|
|
238
|
+
&& result.extractor.length > 0;
|
|
239
|
+
}
|
|
240
|
+
export function resolveSessionPath(sessionValue) {
|
|
241
|
+
if (sessionValue === 'new') {
|
|
242
|
+
const root = getDefaultSessionRoot();
|
|
243
|
+
mkdirSync(root, { recursive: true });
|
|
244
|
+
return join(root, `ds_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`);
|
|
245
|
+
}
|
|
246
|
+
return !sessionValue.includes('/') && !sessionValue.includes('\\')
|
|
247
|
+
? join(getDefaultSessionRoot(), sessionValue)
|
|
248
|
+
: sessionValue;
|
|
249
|
+
}
|
|
250
|
+
export function initSessionDir(sessionDir, owner, description, query) {
|
|
251
|
+
mkdirSync(sessionDir, { recursive: true });
|
|
252
|
+
mkdirSync(join(sessionDir, 'agent-inputs'), { recursive: true });
|
|
253
|
+
const existing = loadSessionMeta(sessionDir);
|
|
254
|
+
const now = Date.now();
|
|
255
|
+
const meta = {
|
|
256
|
+
owner: owner || existing?.owner || '',
|
|
257
|
+
description: description || existing?.description || '',
|
|
258
|
+
createdAt: existing?.createdAt || now,
|
|
259
|
+
updatedAt: now,
|
|
260
|
+
query: query || existing?.query || '',
|
|
261
|
+
};
|
|
262
|
+
atomicWriteJson(join(sessionDir, 'meta.json'), meta);
|
|
263
|
+
}
|
|
264
|
+
/** Agent write inputs must belong to exactly the session being mutated. */
|
|
265
|
+
export function validateSessionInputFile(sessionDir, inputFile) {
|
|
266
|
+
const inputsDir = resolve(sessionDir, 'agent-inputs');
|
|
267
|
+
const candidate = resolve(inputFile);
|
|
268
|
+
const rel = relative(inputsDir, candidate);
|
|
269
|
+
if (rel === '' || rel.startsWith('..') || rel.includes(':') || !existsSync(candidate))
|
|
270
|
+
return undefined;
|
|
271
|
+
return candidate;
|
|
272
|
+
}
|
|
273
|
+
export function loadSessionResults(sessionDir) {
|
|
274
|
+
const data = readResultsFile(sessionDir);
|
|
275
|
+
return data?.data.results ?? [];
|
|
276
|
+
}
|
|
277
|
+
export function loadSessionRounds(sessionDir) {
|
|
278
|
+
return readResultsFile(sessionDir)?.data.rounds ?? 0;
|
|
279
|
+
}
|
|
280
|
+
export function appendSessionResults(sessionDir, newResults, options) {
|
|
281
|
+
return withSessionLock(sessionDir, () => {
|
|
282
|
+
const state = readResultsFile(sessionDir);
|
|
283
|
+
const results = state?.data.results ?? [];
|
|
284
|
+
const currentRounds = state?.data.rounds ?? 0;
|
|
285
|
+
const incrementRound = !options?.skipRoundIncrement && newResults.some(needsRound);
|
|
286
|
+
const round = incrementRound ? currentRounds + 1 : currentRounds;
|
|
287
|
+
const byKey = new Map(results.map(result => [resultUrlKey(result), result]));
|
|
288
|
+
let added = 0;
|
|
289
|
+
let updated = 0;
|
|
290
|
+
const approvedResults = [];
|
|
291
|
+
for (const input of newResults) {
|
|
292
|
+
const key = resultUrlKey(input);
|
|
293
|
+
const existing = byKey.get(key);
|
|
294
|
+
const importRound = needsRound(input) ? Math.max(1, round) : undefined;
|
|
295
|
+
if (!existing) {
|
|
296
|
+
const created = makeResult(input, importRound);
|
|
297
|
+
byKey.set(key, created);
|
|
298
|
+
added++;
|
|
299
|
+
continue;
|
|
300
|
+
}
|
|
301
|
+
let changed = mergeOrigins(existing, input.origins ?? [], importRound);
|
|
302
|
+
if (inferredContentType(input) === 'extracted') {
|
|
303
|
+
const nextContent = input.content ?? '';
|
|
304
|
+
const bodyChanged = existing.contentType !== 'extracted' || existing.content !== nextContent;
|
|
305
|
+
const nextExtractedAt = input.extractedAt ?? Date.now();
|
|
306
|
+
if (bodyChanged) {
|
|
307
|
+
existing.contentType = 'extracted';
|
|
308
|
+
existing.content = nextContent;
|
|
309
|
+
changed = true;
|
|
310
|
+
}
|
|
311
|
+
if (existing.extractor !== (input.extractor || 'default')) {
|
|
312
|
+
existing.extractor = input.extractor || 'default';
|
|
313
|
+
changed = true;
|
|
314
|
+
}
|
|
315
|
+
if (existing.extractedAt !== nextExtractedAt) {
|
|
316
|
+
existing.extractedAt = nextExtractedAt;
|
|
317
|
+
changed = true;
|
|
318
|
+
}
|
|
319
|
+
// An imported body is a fresh Agent input, even when its text is unchanged.
|
|
320
|
+
if (existing.skippedAt !== undefined) {
|
|
321
|
+
existing.skippedAt = undefined;
|
|
322
|
+
changed = true;
|
|
323
|
+
}
|
|
324
|
+
if (existing.failureCount !== undefined || existing.lastFailedAt !== undefined || existing.lastFailure !== undefined) {
|
|
325
|
+
existing.failureCount = undefined;
|
|
326
|
+
existing.lastFailedAt = undefined;
|
|
327
|
+
existing.lastFailure = undefined;
|
|
328
|
+
changed = true;
|
|
329
|
+
}
|
|
330
|
+
if (existing.status !== 'pending') {
|
|
331
|
+
existing.status = 'pending';
|
|
332
|
+
changed = true;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
if (input.title && input.title !== existing.title) {
|
|
336
|
+
existing.title = input.title;
|
|
337
|
+
changed = true;
|
|
338
|
+
}
|
|
339
|
+
if (input.excerpt !== undefined && input.excerpt !== existing.excerpt) {
|
|
340
|
+
existing.excerpt = input.excerpt;
|
|
341
|
+
changed = true;
|
|
342
|
+
}
|
|
343
|
+
else if (input.excerpt === undefined
|
|
344
|
+
&& inferredContentType(input) === 'search'
|
|
345
|
+
&& existing.contentType === 'search') {
|
|
346
|
+
// A search result carries its body in `content` and its short blurb
|
|
347
|
+
// in `snippet`; both are `excerpt` at this layer. Only for a
|
|
348
|
+
// search result: an extracted entry's excerpt is the page
|
|
349
|
+
// description a provider body has no business replacing.
|
|
350
|
+
const body = input.content || input.snippet;
|
|
351
|
+
if (body && body !== existing.excerpt) {
|
|
352
|
+
existing.excerpt = body;
|
|
353
|
+
changed = true;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
for (const field of ['score', 'fusionScore', 'retrievedAt', 'rank', 'publishedDate']) {
|
|
357
|
+
if (input[field] !== undefined && input[field] !== existing[field]) {
|
|
358
|
+
existing[field] = input[field];
|
|
359
|
+
changed = true;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
if (changed) {
|
|
363
|
+
touch(existing);
|
|
364
|
+
updated++;
|
|
365
|
+
if (existing.status === 'approved')
|
|
366
|
+
approvedResults.push(existing);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
const all = [...byKey.values()];
|
|
370
|
+
writeResults(sessionDir, all, round);
|
|
371
|
+
repairInvalidDependents(sessionDir, all);
|
|
372
|
+
touchMeta(sessionDir);
|
|
373
|
+
return { added, updated, total: all.length, round, approvedResults };
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
export function getPendingExtractionResults(sessionDir) {
|
|
377
|
+
return loadSessionResults(sessionDir).filter(result => result.contentType === 'search'
|
|
378
|
+
&& !result.skippedAt
|
|
379
|
+
&& (result.failureCount ?? 0) < 2);
|
|
380
|
+
}
|
|
381
|
+
/** Extracted records awaiting an approval decision. */
|
|
382
|
+
export function getPendingResults(sessionDir) {
|
|
383
|
+
return loadSessionResults(sessionDir).filter(result => result.status === 'pending'
|
|
384
|
+
&& !result.skippedAt
|
|
385
|
+
&& hasVerifiedContent(result));
|
|
386
|
+
}
|
|
387
|
+
export function getApprovedResults(sessionDir) {
|
|
388
|
+
return loadSessionResults(sessionDir).filter(result => result.status === 'approved' && !result.skippedAt && hasVerifiedContent(result));
|
|
389
|
+
}
|
|
390
|
+
function repairInvalidDependents(sessionDir, results) {
|
|
391
|
+
const invalidReasons = new Map(results
|
|
392
|
+
.filter(result => result.skippedAt || result.status !== 'approved' || !hasVerifiedContent(result))
|
|
393
|
+
.map(result => [result.id, result.skippedAt ? 'sourceSkipped' : 'contentChanged']));
|
|
394
|
+
if (!invalidReasons.size)
|
|
395
|
+
return;
|
|
396
|
+
try {
|
|
397
|
+
assertClaimsStoreReadable(sessionDir);
|
|
398
|
+
const evidences = loadEvidences(sessionDir);
|
|
399
|
+
const affectedClaims = new Set();
|
|
400
|
+
const now = Date.now();
|
|
401
|
+
let evidenceChanged = false;
|
|
402
|
+
for (const evidence of evidences) {
|
|
403
|
+
const reason = invalidReasons.get(evidence.resultId);
|
|
404
|
+
if (reason) {
|
|
405
|
+
affectedClaims.add(evidence.claimId);
|
|
406
|
+
}
|
|
407
|
+
if (reason && !evidence.invalid) {
|
|
408
|
+
evidence.invalid = true;
|
|
409
|
+
evidence.invalidatedAt = now;
|
|
410
|
+
evidence.invalidationReason = reason;
|
|
411
|
+
evidenceChanged = true;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
if (affectedClaims.size) {
|
|
415
|
+
if (evidenceChanged)
|
|
416
|
+
saveEvidences(sessionDir, evidences);
|
|
417
|
+
const claims = loadClaims(sessionDir);
|
|
418
|
+
for (const claim of claims)
|
|
419
|
+
if (affectedClaims.has(claim.id))
|
|
420
|
+
claim.status = 'verifying';
|
|
421
|
+
saveClaims(sessionDir, claims);
|
|
422
|
+
saveReviews(sessionDir, loadReviews(sessionDir).filter(review => !affectedClaims.has(review.claimId)));
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
catch { /* Preserve corrupt claim artifacts for their dedicated repair commands. */ }
|
|
426
|
+
try {
|
|
427
|
+
const { graph, missing } = readSessionGraph(sessionDir);
|
|
428
|
+
if (!missing) {
|
|
429
|
+
let graphChanged = false;
|
|
430
|
+
for (const resultIdValue of invalidReasons.keys())
|
|
431
|
+
graphChanged = pruneGraphProvenance(graph, resultIdValue) || graphChanged;
|
|
432
|
+
if (graphChanged)
|
|
433
|
+
writeSessionGraph(sessionDir, graph);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
catch (error) {
|
|
437
|
+
if (!(error instanceof SessionStateError))
|
|
438
|
+
throw error;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
export function approveResults(sessionDir, selections) {
|
|
442
|
+
return withSessionLock(sessionDir, () => {
|
|
443
|
+
const state = readResultsFile(sessionDir);
|
|
444
|
+
const results = state?.data.results ?? [];
|
|
445
|
+
repairInvalidDependents(sessionDir, results);
|
|
446
|
+
const selected = new Set();
|
|
447
|
+
for (const selection of selections) {
|
|
448
|
+
const result = results.find(item => item.id === selection.id);
|
|
449
|
+
if (!result)
|
|
450
|
+
return { approved: 0, total: results.length, approvedResults: [], error: { code: 'RESULT_NOT_FOUND', message: `Result not found: ${selection.id}`, id: selection.id } };
|
|
451
|
+
if (result.revision !== selection.revision)
|
|
452
|
+
return { approved: 0, total: results.length, approvedResults: [], error: { code: 'RESULT_REVISION_CONFLICT', message: `Result revision changed: ${selection.id}`, id: selection.id, revision: result.revision } };
|
|
453
|
+
if (result.skippedAt)
|
|
454
|
+
return { approved: 0, total: results.length, approvedResults: [], error: { code: 'RESULT_SKIPPED', message: `Result is skipped: ${selection.id}`, id: selection.id } };
|
|
455
|
+
if (!hasVerifiedContent(result))
|
|
456
|
+
return { approved: 0, total: results.length, approvedResults: [], error: { code: 'RESULT_NOT_VERIFIED', message: `Result has no extracted body: ${selection.id}`, id: selection.id } };
|
|
457
|
+
selected.add(result.id);
|
|
458
|
+
}
|
|
459
|
+
const approvedResults = [];
|
|
460
|
+
for (const result of results) {
|
|
461
|
+
if (selected.has(result.id) && result.status !== 'approved') {
|
|
462
|
+
result.status = 'approved';
|
|
463
|
+
touch(result);
|
|
464
|
+
approvedResults.push(result);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
writeResults(sessionDir, results, state?.data.rounds ?? 0);
|
|
468
|
+
touchMeta(sessionDir);
|
|
469
|
+
return { approved: approvedResults.length, total: results.length, approvedResults };
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
export function setSkipped(sessionDir, selections, skipped) {
|
|
473
|
+
return withSessionLock(sessionDir, () => {
|
|
474
|
+
const state = readResultsFile(sessionDir);
|
|
475
|
+
const results = state?.data.results ?? [];
|
|
476
|
+
const selected = [];
|
|
477
|
+
const selectedIds = new Set();
|
|
478
|
+
for (const selection of selections) {
|
|
479
|
+
const result = results.find(item => item.id === selection.id);
|
|
480
|
+
if (!result)
|
|
481
|
+
return { changed: 0, results: [], error: { code: 'RESULT_NOT_FOUND', message: `Result not found: ${selection.id}`, id: selection.id } };
|
|
482
|
+
if (result.revision !== selection.revision)
|
|
483
|
+
return { changed: 0, results: [], error: { code: 'RESULT_REVISION_CONFLICT', message: `Result revision changed: ${selection.id}`, id: selection.id, revision: result.revision } };
|
|
484
|
+
if (!selectedIds.has(result.id)) {
|
|
485
|
+
selectedIds.add(result.id);
|
|
486
|
+
selected.push(result);
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
let changed = 0;
|
|
490
|
+
for (const result of selected) {
|
|
491
|
+
const shouldChange = skipped ? result.skippedAt === undefined : result.skippedAt !== undefined;
|
|
492
|
+
if (shouldChange) {
|
|
493
|
+
const wasSkipped = result.skippedAt !== undefined;
|
|
494
|
+
result.skippedAt = skipped ? Date.now() : undefined;
|
|
495
|
+
if (wasSkipped && !skipped && result.status === 'approved')
|
|
496
|
+
result.status = 'pending';
|
|
497
|
+
touch(result);
|
|
498
|
+
changed++;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
writeResults(sessionDir, results, state?.data.rounds ?? 0);
|
|
502
|
+
repairInvalidDependents(sessionDir, results);
|
|
503
|
+
touchMeta(sessionDir);
|
|
504
|
+
return { changed, results: selected };
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
export function recordExtractionOutcome(sessionDir, outcomes) {
|
|
508
|
+
return withSessionLock(sessionDir, () => {
|
|
509
|
+
const state = readResultsFile(sessionDir);
|
|
510
|
+
const results = state?.data.results ?? [];
|
|
511
|
+
const byKey = new Map(results.map(result => [resultUrlKey(result), result]));
|
|
512
|
+
let updated = 0;
|
|
513
|
+
let failed = 0;
|
|
514
|
+
for (const outcome of outcomes) {
|
|
515
|
+
const result = byKey.get(resultUrlKey({ url: outcome.url }));
|
|
516
|
+
if (!result)
|
|
517
|
+
continue;
|
|
518
|
+
if (outcome.failure) {
|
|
519
|
+
result.failureCount = (result.failureCount ?? 0) + 1;
|
|
520
|
+
result.lastFailedAt = Date.now();
|
|
521
|
+
result.lastFailure = outcome.failure;
|
|
522
|
+
touch(result);
|
|
523
|
+
failed++;
|
|
524
|
+
continue;
|
|
525
|
+
}
|
|
526
|
+
if (typeof outcome.content !== 'string' || !outcome.content.trim())
|
|
527
|
+
continue;
|
|
528
|
+
const wasSkipped = result.skippedAt !== undefined;
|
|
529
|
+
const changedBody = result.contentType !== 'extracted' || result.content !== outcome.content;
|
|
530
|
+
result.contentType = 'extracted';
|
|
531
|
+
result.content = outcome.content;
|
|
532
|
+
result.extractor = outcome.extractor || 'default';
|
|
533
|
+
result.extractedAt = outcome.extractedAt ?? Date.now();
|
|
534
|
+
result.title = outcome.title || result.title;
|
|
535
|
+
if (outcome.excerpt !== undefined)
|
|
536
|
+
result.excerpt = outcome.excerpt;
|
|
537
|
+
if (outcome.byline !== undefined)
|
|
538
|
+
result.byline = outcome.byline;
|
|
539
|
+
if (outcome.siteName !== undefined)
|
|
540
|
+
result.siteName = outcome.siteName;
|
|
541
|
+
if (outcome.length !== undefined)
|
|
542
|
+
result.contentLength = outcome.length;
|
|
543
|
+
result.skippedAt = undefined;
|
|
544
|
+
result.failureCount = undefined;
|
|
545
|
+
result.lastFailedAt = undefined;
|
|
546
|
+
result.lastFailure = undefined;
|
|
547
|
+
if ((changedBody || wasSkipped) && result.status === 'approved')
|
|
548
|
+
result.status = 'pending';
|
|
549
|
+
touch(result);
|
|
550
|
+
updated++;
|
|
551
|
+
}
|
|
552
|
+
writeResults(sessionDir, results, state?.data.rounds ?? 0);
|
|
553
|
+
repairInvalidDependents(sessionDir, results);
|
|
554
|
+
touchMeta(sessionDir);
|
|
555
|
+
return { updated, failed, total: results.length };
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
/** Compatibility name for callers that already provide extraction output. */
|
|
559
|
+
export function mergeExtractedContent(sessionDir, extracted) {
|
|
560
|
+
const result = recordExtractionOutcome(sessionDir, extracted.map(item => item.error
|
|
561
|
+
? { url: item.url, failure: { code: 'tool', message: item.error } }
|
|
562
|
+
: item));
|
|
563
|
+
return { updated: result.updated, total: result.total };
|
|
564
|
+
}
|
|
565
|
+
function readSessionGraph(sessionDir) {
|
|
566
|
+
const file = join(sessionDir, 'graph.json');
|
|
567
|
+
if (!existsSync(file))
|
|
568
|
+
return { graph: new MultiDirectedGraph(), missing: true };
|
|
569
|
+
try {
|
|
570
|
+
const parsed = JSON.parse(readFileSync(file, 'utf-8'));
|
|
571
|
+
const graphData = parsed.status === 'ok' && parsed.data?.graph ? parsed.data.graph : null;
|
|
572
|
+
if (!graphData)
|
|
573
|
+
throw new Error('invalid graph envelope');
|
|
574
|
+
return { graph: deserializeGraph(graphData), missing: false };
|
|
575
|
+
}
|
|
576
|
+
catch {
|
|
577
|
+
throw new SessionStateError('SESSION_CORRUPTED', `Cannot read session graph: ${file}`);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
export function loadSessionGraph(sessionDir) {
|
|
581
|
+
return withSessionLock(sessionDir, () => {
|
|
582
|
+
repairInvalidDependents(sessionDir, loadSessionResults(sessionDir));
|
|
583
|
+
return readSessionGraph(sessionDir).graph;
|
|
584
|
+
});
|
|
585
|
+
}
|
|
586
|
+
function writeSessionGraph(sessionDir, graph) {
|
|
587
|
+
atomicWriteJson(join(sessionDir, 'graph.json'), { status: 'ok', data: { graph: serializeGraph(graph), stats: graphStats(graph) } });
|
|
588
|
+
touchMeta(sessionDir);
|
|
589
|
+
}
|
|
590
|
+
function buildApprovedStructuralEdges(graph, approved) {
|
|
591
|
+
const groups = new Map();
|
|
592
|
+
for (const result of approved) {
|
|
593
|
+
for (const origin of result.origins) {
|
|
594
|
+
const key = `${origin.round ?? ''}\0${origin.query}`;
|
|
595
|
+
const group = groups.get(key) ?? { query: origin.query, round: origin.round, results: [] };
|
|
596
|
+
group.results.push({ url: result.url, title: result.title, origins: result.origins });
|
|
597
|
+
groups.set(key, group);
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
for (const group of groups.values())
|
|
601
|
+
buildStructuralEdges(graph, group.query, group.results, group.round);
|
|
602
|
+
}
|
|
603
|
+
/** Serialize graph read-modify-write operations under one session lock. */
|
|
604
|
+
export function mutateSessionGraph(sessionDir, action, options) {
|
|
605
|
+
return withSessionLock(sessionDir, () => {
|
|
606
|
+
repairInvalidDependents(sessionDir, loadSessionResults(sessionDir));
|
|
607
|
+
const { graph, missing } = readSessionGraph(sessionDir);
|
|
608
|
+
// Results are authoritative; a missing derived graph can safely regain its structural layer.
|
|
609
|
+
const approved = getApprovedResults(sessionDir);
|
|
610
|
+
if (missing && options?.reconcileStructural)
|
|
611
|
+
buildApprovedStructuralEdges(graph, approved);
|
|
612
|
+
const value = action(graph, approved);
|
|
613
|
+
writeSessionGraph(sessionDir, graph);
|
|
614
|
+
return value;
|
|
615
|
+
});
|
|
616
|
+
}
|
|
617
|
+
export function injectApprovedResults(sessionDir, approved) {
|
|
618
|
+
const verified = approved.filter(hasVerifiedContent);
|
|
619
|
+
if (!verified.length)
|
|
620
|
+
return { nodesAdded: 0, edgesAdded: 0 };
|
|
621
|
+
return mutateSessionGraph(sessionDir, graph => {
|
|
622
|
+
const beforeNodes = graph.order;
|
|
623
|
+
const beforeEdges = graph.size;
|
|
624
|
+
// Rebuild all approved structure when graph.json is absent, then add this approval.
|
|
625
|
+
buildApprovedStructuralEdges(graph, getApprovedResults(sessionDir));
|
|
626
|
+
return { nodesAdded: graph.order - beforeNodes, edgesAdded: graph.size - beforeEdges };
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
export function countPendingResults(sessionDir) {
|
|
630
|
+
return getPendingResults(sessionDir).length;
|
|
631
|
+
}
|
|
632
|
+
export function updateSessionGraph(sessionDir, query, results, round) {
|
|
633
|
+
const verified = results.filter(hasVerifiedContent);
|
|
634
|
+
if (!verified.length)
|
|
635
|
+
return { nodesAdded: 0, edgesAdded: 0 };
|
|
636
|
+
return mutateSessionGraph(sessionDir, graph => {
|
|
637
|
+
const beforeNodes = graph.order;
|
|
638
|
+
const beforeEdges = graph.size;
|
|
639
|
+
buildStructuralEdges(graph, query, verified.map(result => ({ url: result.url, title: result.title, origins: result.origins })), round);
|
|
640
|
+
return { nodesAdded: graph.order - beforeNodes, edgesAdded: graph.size - beforeEdges };
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
//# sourceMappingURL=session.js.map
|