harness-everything 1.3.0 → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/CHANGELOG.md +6 -0
- package/ci/archive/325-prep/README.md +9 -2
- package/ci/archive/325-prep/doc-reconciliation-red.js +34 -8
- package/ci/fixtures/553-t2a/body-edit/base/.agents/harness-everything/project-docs.json +11 -0
- package/ci/fixtures/553-t2a/body-edit/base/docs/a.md +6 -0
- package/ci/fixtures/553-t2a/body-edit/base/docs/b.md +1 -0
- package/ci/fixtures/553-t2a/body-edit/candidate/docs/a.md +6 -0
- package/ci/fixtures/553-t2c/derived-regenerate-must/base/docs/adr/EVID-001-verify-all-evidence.md +11 -0
- package/ci/fixtures/553-t2c/derived-regenerate-must/base/docs/governed-index.md +19 -0
- package/ci/fixtures/553-t2c/derived-regenerate-must/candidate/docs/adr/EVID-001-verify-all-evidence.md +11 -0
- package/ci/fixtures/553-t2c/derived-regenerate-must/candidate/docs/governed-index.md +19 -0
- package/ci/fixtures/553-t2c/derived-regenerate-must/config.json +17 -0
- package/ci/fixtures/doc-obligations/derive/regression-pins.json +153 -0
- package/ci/fixtures/state-persist-post-tool-use/harness.js +206 -0
- package/ci/fixtures/state-persist-post-tool-use/off-handoff-golden.json +16 -0
- package/ci/fixtures/state-persist-post-tool-use/payload-post-tool-use-success.json +13 -0
- package/ci/fixtures/stop/fail-session-writes.js +109 -0
- package/ci/fixtures/workflow-contract/cases.json +3355 -0
- package/ci/fixtures/workflow-contract/wiring-cases.json +560 -0
- package/ci/lib/doc-reconciliation-prep-fixtures.js +4 -9
- package/ci/mechanism-2an-workflow-replay.test.js +324 -0
- package/ci/mechanism-2ax-doc-lifecycle.test.js +132 -0
- package/ci/mechanism-325-3a-doc-evidence.test.js +73 -0
- package/ci/mechanism-325-3a-doc-obligations.test.js +61 -0
- package/ci/mechanism-325-3b-preparation.test.js +208 -49
- package/ci/mechanism-325-3b-s1-review.test.js +20 -828
- package/ci/mechanism-325-3b-s3-providers.test.js +59 -0
- package/ci/mechanism-325-f3-derived-views.test.js +140 -0
- package/ci/mechanism-341-opencode-lane.test.js +164 -284
- package/ci/mechanism-35-verification-contract.test.js +246 -0
- package/ci/mechanism-365-step-edit-accounting.test.js +5 -6
- package/ci/mechanism-383-doc-glob-line-terminators.test.js +0 -30
- package/ci/mechanism-397-opencode-observations.test.js +151 -18
- package/ci/mechanism-553-e1-unhook-credit.test.js +328 -0
- package/ci/mechanism-553-p2a-claude-hooks.test.js +98 -0
- package/ci/mechanism-553-p3-plan-start.test.js +212 -0
- package/ci/mechanism-553-state-persist-post-tool-use.test.js +307 -0
- package/ci/mechanism-553-stop.test.js +427 -0
- package/ci/mechanism-553-t2a-derive.test.js +110 -0
- package/ci/mechanism-553-t2c-derive.test.js +94 -0
- package/ci/mechanism-e1-derived-regenerate.test.js +45 -206
- package/ci/mechanism-outline-sanitizer.test.js +0 -8
- package/ci/mechanism-pr-a-conflict-check.test.js +38 -305
- package/ci/mechanism-prb-outline-review.test.js +101 -3283
- package/docs/adr/DOCS-006-reconciliation-pilot.md +4 -2
- package/docs/adr/DOCS-008-obligation-abstraction-bounded-consumer.md +3 -3
- package/docs/doc-workflow-reconciliation.md +17 -2
- package/docs/document-lifecycle.md +6 -2
- package/docs/platform-capabilities.md +35 -5
- package/hooks/hooks.json +0 -46
- package/hooks/scripts/lib/workflow-obligations.js +0 -55
- package/hooks/scripts/state-persist.js +7 -95
- package/hooks/scripts/workflow-disposition.js +0 -2
- package/hooks/scripts/workflow-stop-gate.js +17 -30
- package/opencode-plugin/index.mjs +6 -70
- package/opencode-plugin/plugin.json +1 -1
- package/package.json +1 -1
- package/plugins/harness-everything/.antigravity-plugin/plugin.json +1 -1
- package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
- package/plugins/harness-everything/hooks/scripts/lib/workflow-obligations.js +0 -55
- package/plugins/harness-everything/hooks/scripts/state-persist.js +7 -95
- package/plugins/harness-everything/hooks/scripts/workflow-disposition.js +0 -2
- package/plugins/harness-everything/hooks/scripts/workflow-stop-gate.js +17 -30
- package/plugins/harness-everything/plugin.json +1 -1
- package/sbom.cdx.json +7 -7
- package/ci/fixtures/doc-obligations/reconciliation-s1/cases.json +0 -6854
- package/ci/fixtures/doc-obligations/reconciliation-s1/fail-session-writes.js +0 -116
- package/ci/fixtures/doc-obligations/reconciliation-s2a/harness.js +0 -507
- package/ci/fixtures/doc-obligations/reconciliation-s2a/run13-workflow-requirements.json +0 -42
- package/ci/fixtures/doc-obligations/reconciliation-s2a/vectors.json +0 -617
- package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/harness.js +0 -415
- package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-post-tool-use-success-minimal.json +0 -9
- package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-subagent-start.json +0 -7
- package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-subagent-stop-freetext-reject.json +0 -11
- package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-subagent-stop-reject.json +0 -11
- package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-subagent-stop.json +0 -11
- package/ci/fixtures/doc-obligations/reconciliation-s2b/capture/payload-task-result.json +0 -19
- package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/off-capture-only.json +0 -99
- package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/off-legacy.json +0 -67
- package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-concurrent-writers.json +0 -62
- package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-lookalikes-runtime-mutations.json +0 -67
- package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-malformed.json +0 -85
- package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-normal-session.json +0 -74
- package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-runtime-drift-later-npm-test.json +0 -58
- package/ci/fixtures/doc-obligations/reconciliation-s2b/corpus/on-valid-direct-quoted-review.json +0 -85
- package/ci/fixtures/doc-obligations/reconciliation-s2b/f4/cases.json +0 -2267
- package/ci/fixtures/doc-obligations/reconciliation-s2b/wiring/cases.json +0 -1110
- package/ci/lib/doc-reconciliation-file-spy.js +0 -23
- package/ci/lib/doc-reconciliation-qualification-preload.js +0 -37
- package/ci/lib/doc-reconciliation-replay.js +0 -104
- package/ci/lib/doc-reconciliation-staged-tree.js +0 -102
- package/ci/mechanism-325-3b-h1-qualification.test.js +0 -206
- package/ci/mechanism-325-3b-s1.test.js +0 -188
- package/ci/mechanism-325-3b-s2a-core.test.js +0 -840
- package/ci/mechanism-325-3b-s2a-producer.test.js +0 -564
- package/ci/mechanism-325-3b-s2b-capture.test.js +0 -566
- package/ci/mechanism-325-3b-s2b-wiring.test.js +0 -679
- package/ci/mechanism-325-f4-invariants.test.js +0 -606
- package/ci/mechanism-325-f4-projections.test.js +0 -392
- package/ci/mechanism-325-f4-qualification.test.js +0 -228
- package/ci/mechanism-325-f4-trust-boundary.test.js +0 -880
- package/ci/mechanism-e1-dependency-artifact-scope.test.js +0 -657
- package/hooks/scripts/lib/doc-reconciliation-capture.sanitized.jsonl +0 -26
- package/hooks/scripts/lib/doc-reconciliation-core.js +0 -336
- package/hooks/scripts/lib/doc-reconciliation-events.js +0 -292
- package/hooks/scripts/lib/doc-reconciliation-outline-capture.sanitized.jsonl +0 -24
- package/hooks/scripts/lib/doc-reconciliation-pilot.js +0 -482
- package/hooks/scripts/lib/doc-reconciliation-producer.js +0 -468
- package/hooks/scripts/lib/doc-reconciliation-provider.js +0 -3304
- package/hooks/scripts/lib/doc-reconciliation-qualification.json +0 -54
- package/hooks/scripts/w6-state-operations.js +0 -239
- package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-capture.sanitized.jsonl +0 -26
- package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-core.js +0 -336
- package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-events.js +0 -292
- package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-outline-capture.sanitized.jsonl +0 -24
- package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-pilot.js +0 -482
- package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-producer.js +0 -468
- package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-provider.js +0 -3304
- package/plugins/harness-everything/hooks/scripts/lib/doc-reconciliation-qualification.json +0 -54
- package/plugins/harness-everything/hooks/scripts/w6-state-operations.js +0 -239
- package/scripts/system-one-eval-laya.js +0 -112
- /package/ci/fixtures/{doc-obligations/reconciliation-s2b/capture → state-persist-post-tool-use}/payload-post-tool-use-failure.json +0 -0
- /package/ci/fixtures/{doc-obligations/reconciliation-s2b/wiring → workflow-contract}/legacy-off-golden.json +0 -0
|
@@ -1,468 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
const fs = require('fs');
|
|
4
|
-
const path = require('path');
|
|
5
|
-
const { execFileSync } = require('child_process');
|
|
6
|
-
const { _internals: U } = require('./doc-reconciliation-core');
|
|
7
|
-
const { convertWorkspaceFiles } = U.runtimeModule('doc-lifecycle.js');
|
|
8
|
-
const { resolveDocsConfigCaptured, validateDocsConfig } = U.runtimeModule('project-docs-resolver.js');
|
|
9
|
-
const { deriveDocFacts, deriveDocObligations } = U.runtimeModule('doc-obligations.js');
|
|
10
|
-
|
|
11
|
-
const MAX_FILES = 10000;
|
|
12
|
-
const MAX_BYTES = 64 * 1024 * 1024;
|
|
13
|
-
const POSIX_MODES = process.platform !== 'win32';
|
|
14
|
-
const PROJECT_CONFIG_PATH = '.agents/harness-everything/project-docs.json';
|
|
15
|
-
const SUPPORTED_ARTIFACT_ROOTS = new Set(['node_modules', '.husky/_']);
|
|
16
|
-
const POLICY_VERSION = 'dependency-artifact-scope/1';
|
|
17
|
-
function fail(code, reasonCode) { throw Object.assign(new Error(code), reasonCode ? { reasonCode } : {}); }
|
|
18
|
-
// The JS realpath keeps Windows 8.3 spellings (RUNNER~1) while Git reports the long name, so
|
|
19
|
-
// directory identity uses native resolution and is case-insensitive on Windows (as workflow-isolation).
|
|
20
|
-
function canonicalPath(value) { return fs.realpathSync.native(path.resolve(value)); }
|
|
21
|
-
function samePath(a, b) {
|
|
22
|
-
const left = canonicalPath(a);
|
|
23
|
-
const right = canonicalPath(b);
|
|
24
|
-
return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right;
|
|
25
|
-
}
|
|
26
|
-
function git(root, args, options = {}) {
|
|
27
|
-
const env = { ...process.env };
|
|
28
|
-
for (const key of Object.keys(env)) if (key.startsWith('GIT_')) delete env[key];
|
|
29
|
-
try {
|
|
30
|
-
return execFileSync('git', ['-C', root, ...args], { env, timeout: 10000, maxBuffer: MAX_BYTES, stdio: ['pipe', 'pipe', 'pipe'], ...options });
|
|
31
|
-
} catch { fail('baseline-unavailable'); }
|
|
32
|
-
}
|
|
33
|
-
function fileRecord(relative, mode, storedBytes, presence = 'present') {
|
|
34
|
-
return { path: relative, presence, type: presence === 'present' ? 'file' : '', mode,
|
|
35
|
-
storedBytes: Buffer.from(storedBytes), digest: U.sha(storedBytes) };
|
|
36
|
-
}
|
|
37
|
-
function validatePaths(records) {
|
|
38
|
-
const names = new Set();
|
|
39
|
-
for (const item of records) {
|
|
40
|
-
const name = item.path;
|
|
41
|
-
if (!name || name.includes('\\') || name.includes('\ufffd') || name.startsWith('/')
|
|
42
|
-
|| name.split('/').some(segment => !segment || segment === '..' || segment === '.')) fail('inventory-unsupported');
|
|
43
|
-
const folded = name.normalize('NFC').toLowerCase();
|
|
44
|
-
if (names.has(folded)) fail('inventory-unsupported');
|
|
45
|
-
names.add(folded);
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
function captureBaseline(root, pin) {
|
|
49
|
-
if (!U.record(pin) || !/^[a-f0-9]{40,64}$/.test(pin.commit || '') || !U.text(pin.root)
|
|
50
|
-
|| !samePath(pin.root, root)) fail('baseline-unavailable');
|
|
51
|
-
const actualRoot = git(root, ['rev-parse', '--show-toplevel']).toString('utf8').trim();
|
|
52
|
-
if (!samePath(actualRoot, root)) fail('baseline-unavailable');
|
|
53
|
-
const commit = git(root, ['rev-parse', '--verify', '--end-of-options', `${pin.commit}^{commit}`]).toString('utf8').trim();
|
|
54
|
-
const treeRef = git(root, ['rev-parse', '--verify', '--end-of-options', `${commit}^{tree}`]).toString('utf8').trim();
|
|
55
|
-
const entries = git(root, ['ls-tree', '-r', '-z', '--full-tree', treeRef]).toString('utf8').split('\0').filter(Boolean);
|
|
56
|
-
if (entries.length > MAX_FILES) fail('inventory-unsupported');
|
|
57
|
-
const records = [];
|
|
58
|
-
let total = 0;
|
|
59
|
-
for (const entry of entries) {
|
|
60
|
-
const match = entry.match(/^(100644|100755) blob ([a-f0-9]{40,64})\t(.+)$/s);
|
|
61
|
-
if (!match) fail('inventory-unsupported');
|
|
62
|
-
const storedBytes = git(root, ['cat-file', 'blob', match[2]]);
|
|
63
|
-
total += storedBytes.length;
|
|
64
|
-
if (total > MAX_BYTES) fail('inventory-unsupported');
|
|
65
|
-
records.push(fileRecord(match[3], match[1], storedBytes));
|
|
66
|
-
}
|
|
67
|
-
validatePaths(records);
|
|
68
|
-
return { commit, treeRef, records };
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
function pathUnderRoot(relative, root) {
|
|
72
|
-
const candidate = String(relative).replace(/\\/g, '/').normalize('NFC').toLowerCase();
|
|
73
|
-
const expected = root.normalize('NFC').toLowerCase();
|
|
74
|
-
return candidate === expected || candidate.startsWith(`${expected}/`);
|
|
75
|
-
}
|
|
76
|
-
function rootMention(value, root) {
|
|
77
|
-
const normalized = String(value).replace(/\\/g, '/').normalize('NFC').toLowerCase();
|
|
78
|
-
const needle = root.normalize('NFC').toLowerCase();
|
|
79
|
-
let offset = 0;
|
|
80
|
-
while ((offset = normalized.indexOf(needle, offset)) >= 0) {
|
|
81
|
-
const before = offset === 0 || !/[a-z0-9_.-]/.test(normalized[offset - 1]);
|
|
82
|
-
const after = offset + needle.length;
|
|
83
|
-
const boundary = after === normalized.length || /[/*?\s"'`:#),;\]]/.test(normalized[after]);
|
|
84
|
-
if (before && boundary) return true;
|
|
85
|
-
offset++;
|
|
86
|
-
}
|
|
87
|
-
return false;
|
|
88
|
-
}
|
|
89
|
-
function globSegmentMatches(rawPattern, rawSegment) {
|
|
90
|
-
// Same NFC + lowercase folding as rootMention()/pathUnderRoot(), so a wildcard spelling cannot dodge it.
|
|
91
|
-
const pattern = rawPattern.normalize('NFC').toLowerCase();
|
|
92
|
-
const segment = rawSegment.normalize('NFC').toLowerCase();
|
|
93
|
-
if (/[\[\]{}]/.test(pattern)) return true;
|
|
94
|
-
const escaped = pattern.split(/([*?])/).map(part => part === '*' ? '[\\s\\S]*' : part === '?' ? '[\\s\\S]'
|
|
95
|
-
: part.replace(/[|\\{}()[\]^$+?.]/g, '\\$&')).join('');
|
|
96
|
-
return new RegExp(`^${escaped}$`).test(segment);
|
|
97
|
-
}
|
|
98
|
-
function relativeSelectorMayIntersectRoot(selector, root) {
|
|
99
|
-
const normalized = selector.replace(/\\/g, '/');
|
|
100
|
-
if (/[\[\]{}]/.test(normalized) || normalized.split('/').includes('..')) return true;
|
|
101
|
-
// `.` and empty segments are redundant anywhere in a workspace-relative selector.
|
|
102
|
-
const pattern = normalized.split('/').filter(segment => segment !== '' && segment !== '.');
|
|
103
|
-
const target = root.split('/');
|
|
104
|
-
let states = new Set([0]);
|
|
105
|
-
const closure = values => {
|
|
106
|
-
const expanded = new Set(values);
|
|
107
|
-
let changed = true;
|
|
108
|
-
while (changed) {
|
|
109
|
-
changed = false;
|
|
110
|
-
for (const index of expanded) {
|
|
111
|
-
if (pattern[index] === '**' && !expanded.has(index + 1)) {
|
|
112
|
-
expanded.add(index + 1);
|
|
113
|
-
changed = true;
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
return expanded;
|
|
118
|
-
};
|
|
119
|
-
states = closure(states);
|
|
120
|
-
for (const segment of target) {
|
|
121
|
-
const next = new Set();
|
|
122
|
-
for (const index of states) {
|
|
123
|
-
if (index >= pattern.length) continue;
|
|
124
|
-
if (pattern[index] === '**') next.add(index);
|
|
125
|
-
else if (globSegmentMatches(pattern[index], segment)) next.add(index + 1);
|
|
126
|
-
}
|
|
127
|
-
states = closure(next);
|
|
128
|
-
if (!states.size) return false;
|
|
129
|
-
}
|
|
130
|
-
return states.size > 0;
|
|
131
|
-
}
|
|
132
|
-
function relativePathWithin(workspace, candidate, pathApi) {
|
|
133
|
-
const relative = pathApi.relative(workspace, candidate);
|
|
134
|
-
if (!relative) return '';
|
|
135
|
-
const normalized = relative.replace(/\\/g, '/');
|
|
136
|
-
// Case and filesystem aliases that cannot be resolved exactly must fail closed.
|
|
137
|
-
const workspaceParts = workspace.replace(/\\/g, '/').split('/').filter(Boolean);
|
|
138
|
-
const candidateParts = candidate.replace(/\\/g, '/').split('/').filter(Boolean);
|
|
139
|
-
const samePrefix = workspaceParts.length <= candidateParts.length
|
|
140
|
-
&& workspaceParts.every((part, index) => part.normalize('NFC').toLowerCase()
|
|
141
|
-
=== candidateParts[index].normalize('NFC').toLowerCase());
|
|
142
|
-
if (samePrefix) return candidateParts.slice(workspaceParts.length).join('/');
|
|
143
|
-
if (pathApi.isAbsolute(relative) || normalized === '..' || normalized.startsWith('../')) return null;
|
|
144
|
-
return normalized;
|
|
145
|
-
}
|
|
146
|
-
function realpathWithMissingSuffix(candidate, pathApi) {
|
|
147
|
-
let current = candidate;
|
|
148
|
-
const suffix = [];
|
|
149
|
-
while (true) {
|
|
150
|
-
try { return pathApi.resolve(fs.realpathSync.native(current), ...suffix); }
|
|
151
|
-
catch (error) {
|
|
152
|
-
if (!['ENOENT', 'ENOTDIR'].includes(error.code)) return null;
|
|
153
|
-
const parent = pathApi.dirname(current);
|
|
154
|
-
if (parent === current) return null;
|
|
155
|
-
suffix.unshift(pathApi.basename(current));
|
|
156
|
-
current = parent;
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
function absoluteSelectorRelatives(selector, workspaceRoot) {
|
|
161
|
-
const windowsDrive = /^[A-Za-z]:/.test(selector);
|
|
162
|
-
if ((windowsDrive || selector.startsWith('\\') || selector.startsWith('//')) && process.platform !== 'win32') return true;
|
|
163
|
-
const pathApi = process.platform === 'win32' ? path.win32 : path;
|
|
164
|
-
if (windowsDrive && !pathApi.isAbsolute(selector)) return true;
|
|
165
|
-
if (!pathApi.isAbsolute(selector)) return null;
|
|
166
|
-
|
|
167
|
-
const workspace = canonicalPath(workspaceRoot);
|
|
168
|
-
const absolute = pathApi.resolve(selector);
|
|
169
|
-
const lexicalRelative = relativePathWithin(workspace, absolute, pathApi);
|
|
170
|
-
const resolved = realpathWithMissingSuffix(absolute, pathApi);
|
|
171
|
-
if (!resolved) return true;
|
|
172
|
-
const realRelative = relativePathWithin(workspace, resolved, pathApi);
|
|
173
|
-
if (lexicalRelative !== null && realRelative !== null) return [lexicalRelative, realRelative];
|
|
174
|
-
if (lexicalRelative !== null || realRelative !== null) return true;
|
|
175
|
-
// A glob outside the workspace can still expand into it (via a parent such as /tmp/*/node_modules/**
|
|
176
|
-
// or a symlinked entry under an unrelated directory); only literal outside paths are provably disjoint.
|
|
177
|
-
if (/[*?\[\]{}]/.test(selector)) return true;
|
|
178
|
-
return false;
|
|
179
|
-
}
|
|
180
|
-
function selectorMayIntersectRoot(selector, root, workspaceRoot) {
|
|
181
|
-
if (typeof selector !== 'string' || !selector.trim()) return true;
|
|
182
|
-
const absolute = absoluteSelectorRelatives(selector, workspaceRoot);
|
|
183
|
-
if (absolute === true) return true;
|
|
184
|
-
if (absolute === false) return false;
|
|
185
|
-
if (absolute !== null) return absolute.some(relative => relativeSelectorMayIntersectRoot(relative || '.', root));
|
|
186
|
-
return relativeSelectorMayIntersectRoot(selector, root);
|
|
187
|
-
}
|
|
188
|
-
function valueMayIntersectRoots(value, roots, workspaceRoot) {
|
|
189
|
-
if (typeof value === 'string') {
|
|
190
|
-
const absolute = absoluteSelectorRelatives(value, workspaceRoot);
|
|
191
|
-
if (absolute === true) return true;
|
|
192
|
-
if (absolute === false) return false;
|
|
193
|
-
if (absolute !== null) return roots.some(root => absolute.some(relative => {
|
|
194
|
-
const selector = relative || '.';
|
|
195
|
-
return rootMention(selector, root)
|
|
196
|
-
|| ((selector.includes('/') || /[*?\[\]{}]/.test(selector)) && selectorMayIntersectRoot(selector, root, workspaceRoot));
|
|
197
|
-
}));
|
|
198
|
-
return roots.some(root => rootMention(value, root)
|
|
199
|
-
|| ((!value.trim() || value.includes('/') || /[*?\[\]{}]/.test(value))
|
|
200
|
-
&& selectorMayIntersectRoot(value, root, workspaceRoot)));
|
|
201
|
-
}
|
|
202
|
-
if (Array.isArray(value)) return value.some(item => valueMayIntersectRoots(item, roots, workspaceRoot));
|
|
203
|
-
if (U.record(value)) return Object.entries(value).some(([key, item]) => valueMayIntersectRoots(key, roots, workspaceRoot)
|
|
204
|
-
|| valueMayIntersectRoots(item, roots, workspaceRoot));
|
|
205
|
-
return false;
|
|
206
|
-
}
|
|
207
|
-
function withoutTaskPinIdentity(value) {
|
|
208
|
-
if (Array.isArray(value)) return value.map(withoutTaskPinIdentity);
|
|
209
|
-
if (!U.record(value)) return value;
|
|
210
|
-
return Object.fromEntries(Object.entries(value)
|
|
211
|
-
.filter(([key]) => !/ids?$/i.test(key))
|
|
212
|
-
.map(([key, item]) => [key, withoutTaskPinIdentity(item)]));
|
|
213
|
-
}
|
|
214
|
-
function projectConfigFromBytes(bytes) {
|
|
215
|
-
try {
|
|
216
|
-
const config = JSON.parse(Buffer.from(bytes).toString('utf8'));
|
|
217
|
-
return { config, valid: validateDocsConfig(config).valid };
|
|
218
|
-
} catch { return { config: null, valid: false }; }
|
|
219
|
-
}
|
|
220
|
-
function baselineProjectConfig(baseline) {
|
|
221
|
-
const source = baseline.records.find(item => item.path === PROJECT_CONFIG_PATH && item.presence === 'present');
|
|
222
|
-
return source ? { source, ...projectConfigFromBytes(source.storedBytes) } : { source: null, config: null, valid: false };
|
|
223
|
-
}
|
|
224
|
-
function capturedProjectConfig(config) {
|
|
225
|
-
const source = config.capture.sources.find(item => item.path === PROJECT_CONFIG_PATH);
|
|
226
|
-
return source && source.presence === 'present'
|
|
227
|
-
? { source, ...projectConfigFromBytes(source.bytes) }
|
|
228
|
-
: { source: source || null, config: null, valid: false };
|
|
229
|
-
}
|
|
230
|
-
function dependencyRoots(config) {
|
|
231
|
-
return U.record(config) && U.record(config.inventory)
|
|
232
|
-
&& Object.prototype.hasOwnProperty.call(config.inventory, 'dependencyArtifactRoots')
|
|
233
|
-
? config.inventory.dependencyArtifactRoots : undefined;
|
|
234
|
-
}
|
|
235
|
-
function sameRootField(left, right) {
|
|
236
|
-
if (left === undefined || right === undefined) return left === right;
|
|
237
|
-
return U.stable([...left].sort()) === U.stable([...right].sort());
|
|
238
|
-
}
|
|
239
|
-
function validateExcludedRoots(workspaceRoot, roots) {
|
|
240
|
-
const workspace = canonicalPath(workspaceRoot);
|
|
241
|
-
const states = [];
|
|
242
|
-
for (const root of roots) {
|
|
243
|
-
let parent = workspace;
|
|
244
|
-
let presence = 'present-directory';
|
|
245
|
-
for (const component of root.split('/')) {
|
|
246
|
-
let entries;
|
|
247
|
-
try { entries = fs.readdirSync(parent, { withFileTypes: true }); }
|
|
248
|
-
catch { fail('inventory-incomplete', 'dependency-root-parent-unreadable'); }
|
|
249
|
-
const aliases = entries.filter(entry => entry.name.normalize('NFC').toLowerCase() === component.normalize('NFC').toLowerCase());
|
|
250
|
-
if (aliases.length > 1 || aliases.some(entry => entry.name !== component)) fail('inventory-unsupported', 'dependency-root-alias');
|
|
251
|
-
const current = path.join(parent, component);
|
|
252
|
-
let stat;
|
|
253
|
-
try { stat = fs.lstatSync(current); }
|
|
254
|
-
catch (error) {
|
|
255
|
-
if (error.code === 'ENOENT') { presence = 'absent'; break; }
|
|
256
|
-
fail('inventory-incomplete', 'dependency-root-unreadable');
|
|
257
|
-
}
|
|
258
|
-
if (stat.isSymbolicLink() || !stat.isDirectory()) fail('inventory-unsupported', 'dependency-root-not-plain-directory');
|
|
259
|
-
let real;
|
|
260
|
-
try { real = fs.realpathSync.native(current); }
|
|
261
|
-
catch { fail('inventory-incomplete', 'dependency-root-unreadable'); }
|
|
262
|
-
const within = process.platform === 'win32'
|
|
263
|
-
? real.toLowerCase().startsWith(`${workspace.toLowerCase()}${path.sep}`)
|
|
264
|
-
: real.startsWith(`${workspace}${path.sep}`);
|
|
265
|
-
if (!within) fail('inventory-unsupported', 'dependency-root-outside-workspace');
|
|
266
|
-
parent = current;
|
|
267
|
-
}
|
|
268
|
-
states.push({ path: root, presence });
|
|
269
|
-
}
|
|
270
|
-
return states;
|
|
271
|
-
}
|
|
272
|
-
function guardedPolicy(root, baseline, capturedConfig, input) {
|
|
273
|
-
const base = baselineProjectConfig(baseline);
|
|
274
|
-
const current = capturedProjectConfig(capturedConfig);
|
|
275
|
-
const baselineRoots = base.valid ? dependencyRoots(base.config) : undefined;
|
|
276
|
-
const candidateRoots = current.valid ? dependencyRoots(current.config) : undefined;
|
|
277
|
-
if (current.valid && candidateRoots !== undefined && (!base.valid || !sameRootField(baselineRoots, candidateRoots))) {
|
|
278
|
-
fail('inventory-unsupported', 'dependency-artifact-policy-changed-or-unpinned');
|
|
279
|
-
}
|
|
280
|
-
if (!base.valid || baselineRoots === undefined || baselineRoots.length === 0) return null;
|
|
281
|
-
if (!current.valid || !sameRootField(baselineRoots, candidateRoots)) fail('inventory-unsupported', 'dependency-artifact-policy-changed-or-unpinned');
|
|
282
|
-
const roots = [...baselineRoots].sort();
|
|
283
|
-
const indexed = git(root, ['ls-files', '-z']).toString('utf8').split('\0').filter(Boolean);
|
|
284
|
-
if (baseline.records.some(item => roots.some(value => pathUnderRoot(item.path, value)))) fail('inventory-unsupported', 'baseline-path-overlap');
|
|
285
|
-
if (indexed.some(item => roots.some(value => pathUnderRoot(item, value)))) fail('inventory-unsupported', 'index-path-overlap');
|
|
286
|
-
if (capturedConfig.capture.sources.some(item => roots.some(value => pathUnderRoot(item.path, value)))) {
|
|
287
|
-
fail('inventory-unsupported', 'config-source-overlap');
|
|
288
|
-
}
|
|
289
|
-
const configs = [base.config, capturedConfig.resolution.config];
|
|
290
|
-
if (configs.some(config => {
|
|
291
|
-
if (!U.record(config)) return false;
|
|
292
|
-
const selectors = Object.fromEntries(Object.entries(config).filter(([key]) => key !== 'inventory'));
|
|
293
|
-
return valueMayIntersectRoots(selectors, roots, root);
|
|
294
|
-
})) fail('inventory-unsupported', 'config-selector-overlap');
|
|
295
|
-
if (valueMayIntersectRoots(withoutTaskPinIdentity(input.task), roots, root) || valueMayIntersectRoots(input.scope, roots, root)) {
|
|
296
|
-
fail('inventory-unsupported', 'task-input-overlap');
|
|
297
|
-
}
|
|
298
|
-
return {
|
|
299
|
-
roots,
|
|
300
|
-
baselineCommit: baseline.commit,
|
|
301
|
-
storedBytesDigest: U.sha(base.source.storedBytes),
|
|
302
|
-
guardOutcomes: [
|
|
303
|
-
{ guard: 'baseline-paths', state: 'clear', reason: 'No baseline path intersects an approved root.' },
|
|
304
|
-
{ guard: 'index-paths', state: 'clear', reason: 'No current index path intersects an approved root.' },
|
|
305
|
-
{ guard: 'config-sources', state: 'clear', reason: 'No baseline or current config source intersects an approved root.' },
|
|
306
|
-
{ guard: 'config-selectors', state: 'clear', reason: 'Baseline and current config declarations are disjoint from approved roots.' },
|
|
307
|
-
{ guard: 'task-inputs', state: 'clear', reason: 'No explicit task or requirement input intersects an approved root.' }
|
|
308
|
-
]
|
|
309
|
-
};
|
|
310
|
-
}
|
|
311
|
-
function captureCandidate(root, baseline, excludedRoots = []) {
|
|
312
|
-
const excludedRootStates = excludedRoots.length ? validateExcludedRoots(root, excludedRoots) : [];
|
|
313
|
-
const raw = [];
|
|
314
|
-
let total = 0;
|
|
315
|
-
let visited = 0;
|
|
316
|
-
function walk(dir, prefix) {
|
|
317
|
-
const entries = fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => U.compare(a.name, b.name));
|
|
318
|
-
for (const entry of entries) {
|
|
319
|
-
if (!prefix && entry.name === '.git') continue;
|
|
320
|
-
const relative = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
321
|
-
if (excludedRoots.includes(relative)) continue;
|
|
322
|
-
if (++visited > MAX_FILES) fail('inventory-unsupported');
|
|
323
|
-
const absolute = path.join(dir, entry.name);
|
|
324
|
-
const stat = fs.lstatSync(absolute);
|
|
325
|
-
if (stat.isDirectory()) {
|
|
326
|
-
// Windows stats carry no POSIX permission bits (directories report 0o666); an unreadable
|
|
327
|
-
// path there makes readdir/readFile throw instead.
|
|
328
|
-
if (POSIX_MODES && (!(stat.mode & 0o444) || !(stat.mode & 0o111))) fail('inventory-incomplete');
|
|
329
|
-
walk(absolute, relative);
|
|
330
|
-
continue;
|
|
331
|
-
}
|
|
332
|
-
if (!stat.isFile()) fail('inventory-unsupported');
|
|
333
|
-
// Unreadable files must remain unavailable even when the process has elevated read access.
|
|
334
|
-
if (POSIX_MODES && !(stat.mode & 0o444)) fail('inventory-incomplete');
|
|
335
|
-
const bytes = fs.readFileSync(absolute);
|
|
336
|
-
total += bytes.length;
|
|
337
|
-
if (raw.length >= MAX_FILES || total > MAX_BYTES) fail('inventory-unsupported');
|
|
338
|
-
raw.push({ path: relative, raw: bytes, mode: stat.mode & 0o111 ? '100755' : '100644' });
|
|
339
|
-
}
|
|
340
|
-
}
|
|
341
|
-
walk(root, '');
|
|
342
|
-
validatePaths(raw);
|
|
343
|
-
// Refuse filters/encodings that the existing stored-byte reader does not model.
|
|
344
|
-
if (raw.length) {
|
|
345
|
-
const attrs = git(root, ['check-attr', '-z', '--stdin', 'filter', 'working-tree-encoding', 'ident'], { input: Buffer.from(raw.map(r => r.path).join('\0') + '\0') }).toString('utf8').split('\0');
|
|
346
|
-
for (let i = 0; i + 2 < attrs.length; i += 3) {
|
|
347
|
-
if (!['unspecified', 'unset'].includes(attrs[i + 2])) fail('inventory-unsupported');
|
|
348
|
-
}
|
|
349
|
-
}
|
|
350
|
-
// Lifecycle owns text/eol/autocrlf conversion. A completeness walk above detects its skipped paths.
|
|
351
|
-
const stored = new Map(convertWorkspaceFiles(root, raw.map(item => ({ path: item.path, bytes: item.raw })))
|
|
352
|
-
.map(item => [item.path, item.bytes]));
|
|
353
|
-
const records = raw.map(item => {
|
|
354
|
-
const converted = stored.get(item.path);
|
|
355
|
-
if (!converted) fail('inventory-unsupported');
|
|
356
|
-
// An unexplained non-CR difference means the two readers observed different bytes.
|
|
357
|
-
if (!item.raw.includes(13) && !item.raw.equals(converted)) fail('snapshot-changed');
|
|
358
|
-
return fileRecord(item.path, item.mode, converted);
|
|
359
|
-
});
|
|
360
|
-
for (const item of baseline.records) if (!stored.has(item.path)) records.push(fileRecord(item.path, '', Buffer.alloc(0), 'deleted'));
|
|
361
|
-
return { records, excludedRootStates };
|
|
362
|
-
}
|
|
363
|
-
const progressKeys = new Set(['status', 'state', 'evidence', 'loaded', 'loadedAt', 'updatedAt', 'createdAt', 'completedAt', 'timestamp', 'report', 'reports']);
|
|
364
|
-
// Progress fields are excluded only at their defined record locations (top-level task/workflow, each
|
|
365
|
-
// requirement, each requirement binding). Nested objects keep every key: a nested `status`/`state` there
|
|
366
|
-
// is semantic and must change taskScopeDigest (PR #353 review P2).
|
|
367
|
-
function withoutProgress(value, keys = progressKeys) {
|
|
368
|
-
if (!U.record(value)) return U.clone(value);
|
|
369
|
-
return Object.fromEntries(Object.keys(value).filter(key => !keys.has(key)).map(key => [key, U.clone(value[key])]));
|
|
370
|
-
}
|
|
371
|
-
// A binding's `report`/`reports` object configures the binding; only its load/status records are progress.
|
|
372
|
-
const bindingProgressKeys = new Set([...progressKeys].filter(key => key !== 'report' && key !== 'reports'));
|
|
373
|
-
function taskSemantics(task) {
|
|
374
|
-
const semantic = withoutProgress(task);
|
|
375
|
-
if (Array.isArray(task?.requirements)) {
|
|
376
|
-
semantic.requirements = task.requirements.map(requirement => {
|
|
377
|
-
const item = withoutProgress(requirement);
|
|
378
|
-
if (U.record(requirement) && Array.isArray(requirement.bindings)) item.bindings = requirement.bindings.map(binding => withoutProgress(binding, bindingProgressKeys));
|
|
379
|
-
return item;
|
|
380
|
-
});
|
|
381
|
-
}
|
|
382
|
-
return semantic;
|
|
383
|
-
}
|
|
384
|
-
function contextFor(input, provider) {
|
|
385
|
-
if (!provider || typeof provider.resolveContext !== 'function') fail('origin-unavailable');
|
|
386
|
-
const response = provider.resolveContext({ workspaceRoot: input.workspaceRoot, workflowId: input.workflow.workflowId, sessionId: input.workflow.sessionId });
|
|
387
|
-
if (response?.status !== 'accepted') fail(response?.status === 'rejected' ? 'origin-untrusted' : 'origin-unavailable');
|
|
388
|
-
const c = response.context;
|
|
389
|
-
if (!U.record(c) || !U.text(response.originRef) || !U.text(c.workspaceId) || !U.text(c.baselineReference)
|
|
390
|
-
|| !U.text(c.principals?.author) || !Array.isArray(c.principals?.executors) || !c.principals.executors.every(U.text)) fail('origin-untrusted');
|
|
391
|
-
for (const key of ['sessionId', 'workflowId', 'workflowRevision']) if (c[key] !== input.workflow[key]) fail('identity-mismatch');
|
|
392
|
-
if (c.taskId !== input.task.taskId || U.stable(c.activeHost) !== U.stable(input.activeHost)) fail('identity-mismatch');
|
|
393
|
-
if (c.workspaceRoot && !samePath(c.workspaceRoot, input.workspaceRoot)) fail('identity-mismatch');
|
|
394
|
-
// The provider must bind the concrete workflow-start pin; a bare reference cannot authorize a
|
|
395
|
-
// re-anchored baseline (PR #353 review P1).
|
|
396
|
-
if (!U.record(c.baseline) || !U.text(c.baseline.commit) || !U.text(c.baseline.root)
|
|
397
|
-
|| !U.record(input.baseline) || c.baseline.commit !== input.baseline.commit || !samePath(c.baseline.root, input.baseline.root)) fail('baseline-unavailable');
|
|
398
|
-
const root = canonicalPath(input.workspaceRoot);
|
|
399
|
-
return U.clone({ ...c, baseline: { ...c.baseline, root }, workspaceRoot: root, originRef: response.originRef });
|
|
400
|
-
}
|
|
401
|
-
function filesOf(records, config) {
|
|
402
|
-
// The inventory is whole-project: binary records keep their stored bytes in the identity framing and are
|
|
403
|
-
// omitted from semantic derivation unless the derive contract can observe them (PR #353 review P2).
|
|
404
|
-
return U.deriveFiles(records, config);
|
|
405
|
-
}
|
|
406
|
-
function produceDocSnapshot(input, dependencies = {}) {
|
|
407
|
-
const originProvider = dependencies?.originProvider;
|
|
408
|
-
try {
|
|
409
|
-
if (!U.record(input) || !U.text(input.workspaceRoot) || !U.record(input.workflow) || !U.record(input.task)
|
|
410
|
-
|| !U.text(input.task.taskId) || !Array.isArray(input.task.requirements) || !U.record(input.scope)
|
|
411
|
-
|| !Number.isInteger(input.workflow.workflowRevision) || input.workflow.workflowRevision < 0) fail('invalid-input');
|
|
412
|
-
if ((input.prdRoot === undefined ? 'docs/prd/' : input.prdRoot) !== 'docs/prd/' || (input.scope.prdRoot && input.scope.prdRoot !== 'docs/prd/')) fail('unsupported-prd-root');
|
|
413
|
-
const root = canonicalPath(input.workspaceRoot);
|
|
414
|
-
const detached = U.clone(input);
|
|
415
|
-
const originContext = contextFor(detached, originProvider);
|
|
416
|
-
const baseline = captureBaseline(root, detached.baseline);
|
|
417
|
-
const config = resolveDocsConfigCaptured(root, { activeHost: detached.activeHost });
|
|
418
|
-
if (!['project', 'host'].includes(config.resolution.status) || config.capture.sources.some(s => s.presence === 'unreadable')) fail('config-unavailable');
|
|
419
|
-
const policy = guardedPolicy(root, baseline, config, detached);
|
|
420
|
-
const firstCapture = captureCandidate(root, baseline, policy?.roots || []);
|
|
421
|
-
const coverage = policy ? {
|
|
422
|
-
kind: 'project-with-dependency-artifact-exclusions',
|
|
423
|
-
policyVersion: POLICY_VERSION,
|
|
424
|
-
policySource: { path: PROJECT_CONFIG_PATH, baselineCommit: policy.baselineCommit, storedBytesDigest: policy.storedBytesDigest },
|
|
425
|
-
dependencyArtifactRoots: policy.roots,
|
|
426
|
-
excluded: ['.git', ...policy.roots],
|
|
427
|
-
excludedRootStates: firstCapture.excludedRootStates,
|
|
428
|
-
guardOutcomes: [...policy.guardOutcomes,
|
|
429
|
-
{ guard: 'excluded-root-types', state: 'clear', reason: 'Each approved root is an in-workspace directory or absent.', roots: firstCapture.excludedRootStates }],
|
|
430
|
-
scope: U.clone(detached.scope)
|
|
431
|
-
} : { kind: 'whole-project', excluded: ['.git'], scope: U.clone(detached.scope) };
|
|
432
|
-
const candidate = { records: firstCapture.records, coverage };
|
|
433
|
-
// Same owned config bytes must be the bytes covered by the working-tree capture.
|
|
434
|
-
for (const source of config.capture.sources) {
|
|
435
|
-
const file = candidate.records.find(r => r.path === source.path && r.presence === 'present');
|
|
436
|
-
if (source.presence === 'present' ? !file || !U.bytes(source.bytes).equals(file.storedBytes) : Boolean(file)) fail('snapshot-changed');
|
|
437
|
-
}
|
|
438
|
-
config.digest = U.configDigest(config);
|
|
439
|
-
baseline.digest = U.snapshotDigest('baseline', baseline, coverage, baseline.records);
|
|
440
|
-
candidate.digest = U.snapshotDigest('candidate', baseline, coverage, candidate.records);
|
|
441
|
-
const planIdentity = { task: taskSemantics(detached.task), scope: U.clone(detached.scope), workflow: withoutProgress(detached.workflow), coverage, configDigest: config.digest, prdRoot: 'docs/prd/' };
|
|
442
|
-
const identity = { workspaceId: originContext.workspaceId, sessionId: originContext.sessionId, workflowId: originContext.workflowId,
|
|
443
|
-
workflowRevision: originContext.workflowRevision, taskId: originContext.taskId, taskScopeDigest: U.structuredDigest('doc-task-scope-v1', planIdentity),
|
|
444
|
-
baselineDigest: baseline.digest, candidateDigest: candidate.digest, configDigest: config.digest, prdRoot: 'docs/prd/' };
|
|
445
|
-
const derived = deriveDocFacts({ base: { files: filesOf(baseline.records, config.resolution.config) },
|
|
446
|
-
candidate: { files: filesOf(candidate.records, config.resolution.config) }, config: config.resolution.config });
|
|
447
|
-
if (!derived.facts?.inputKnown) fail('inventory-incomplete');
|
|
448
|
-
const facts = derived.facts;
|
|
449
|
-
const obligations = deriveDocObligations(facts);
|
|
450
|
-
const derivationReasons = Object.fromEntries(obligations.map(o => [o.id, { applicability: o.applicability, reason: `captured facts derive ${o.capability}: ${o.applicability}`, factRefs: ['facts', ...(o.scope?.paths || []).map(p => `inventory:${p}`)] }]));
|
|
451
|
-
const again = captureCandidate(root, baseline, policy?.roots || []);
|
|
452
|
-
const configAgain = resolveDocsConfigCaptured(root, { activeHost: detached.activeHost });
|
|
453
|
-
const policyAgain = guardedPolicy(root, baseline, configAgain, detached);
|
|
454
|
-
let finalContext;
|
|
455
|
-
try { finalContext = contextFor(detached, originProvider); }
|
|
456
|
-
catch { fail('snapshot-changed'); }
|
|
457
|
-
if (U.snapshotDigest('candidate', baseline, coverage, again.records) !== candidate.digest
|
|
458
|
-
|| U.stable(again.excludedRootStates) !== U.stable(firstCapture.excludedRootStates)
|
|
459
|
-
|| U.stable(policyAgain) !== U.stable(policy) || U.configDigest(configAgain) !== config.digest
|
|
460
|
-
|| U.stable(originContext) !== U.stable(finalContext)) fail('snapshot-changed');
|
|
461
|
-
return { state: 'ready', snapshot: { identity, baseline, candidate, config, originContext, taskSemantics: planIdentity, facts, obligations, derivationReasons }, diagnostics: [] };
|
|
462
|
-
} catch (error) {
|
|
463
|
-
const codes = ['invalid-input', 'baseline-unavailable', 'inventory-incomplete', 'inventory-unsupported', 'snapshot-changed', 'config-unavailable', 'unsupported-prd-root', 'identity-mismatch', 'origin-unavailable', 'origin-untrusted'];
|
|
464
|
-
const code = codes.includes(error.message) ? error.message : 'inventory-unsupported';
|
|
465
|
-
return { state: 'unavailable', snapshot: null, diagnostics: [U.diagnostic(code, error.reasonCode ? { reasonCode: error.reasonCode } : {})] };
|
|
466
|
-
}
|
|
467
|
-
}
|
|
468
|
-
module.exports = { produceDocSnapshot };
|