opencode-work-context 0.10.1 → 0.10.3
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 +70 -0
- package/commands/wc.md +8 -0
- package/package.json +1 -1
- package/plugin/stages-tui.js +22 -19
- package/plugin/work-context.js +4 -4
- package/src/core.js +14 -1
- package/src/delivery-contracts.js +108 -0
- package/src/delivery-doctor.js +304 -0
- package/src/delivery-git.js +159 -0
- package/src/delivery-redaction.js +68 -0
- package/src/delivery-slices.js +125 -0
- package/src/delivery.js +126 -0
- package/src/errors.js +2 -0
- package/src/index.js +5 -0
- package/src/opencode-adapter.js +25 -0
- package/src/protocol.js +47 -0
- package/src/storage.js +18 -5
- package/src/tool-definitions.js +42 -2
- package/tools/work_context_doctor_delivery.js +3 -0
- package/tools/work_context_explain_delivery.js +3 -0
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { Buffer } from "node:buffer";
|
|
4
|
+
import { ERROR_CODES, fail } from "./errors.js";
|
|
5
|
+
import {
|
|
6
|
+
WORK_CONTEXT_PROTOCOL,
|
|
7
|
+
WORK_CONTEXT_PROTOCOL_DESCRIPTOR_HASH,
|
|
8
|
+
parseWorkContextProtocolMarker,
|
|
9
|
+
} from "./protocol.js";
|
|
10
|
+
|
|
11
|
+
export const DELIVERY_DOCTOR_CONTRACT_VERSION = "1.0";
|
|
12
|
+
export const DELIVERY_DOCTOR_OPERATION = "delivery.doctor";
|
|
13
|
+
export const DELIVERY_DOCTOR_EVIDENCE_KINDS = Object.freeze(["self_reported", "host_attested", "unavailable"]);
|
|
14
|
+
|
|
15
|
+
const PACKAGE_NAME = "opencode-work-context";
|
|
16
|
+
const MAX_FILE_BYTES = 1024 * 1024;
|
|
17
|
+
const MAX_VALUE_CHARACTERS = 256;
|
|
18
|
+
const SAFE_VERSION_PATTERN = /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
|
|
19
|
+
const relativeFiles = Object.freeze({
|
|
20
|
+
command: ".opencode/commands/wc.md",
|
|
21
|
+
opencode: ".opencode/opencode.json",
|
|
22
|
+
tui: ".opencode/tui.json",
|
|
23
|
+
rootManifest: "package.json",
|
|
24
|
+
opencodeManifest: ".opencode/package.json",
|
|
25
|
+
rootInstalled: `node_modules/${PACKAGE_NAME}/package.json`,
|
|
26
|
+
opencodeInstalled: `.opencode/node_modules/${PACKAGE_NAME}/package.json`,
|
|
27
|
+
localLoader: ".opencode/plugins/work-context.js",
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
const cleanValue = (value) => typeof value === "string"
|
|
31
|
+
&& value.length > 0
|
|
32
|
+
&& value.length <= MAX_VALUE_CHARACTERS
|
|
33
|
+
&& /^[A-Za-z0-9._+-]+$/.test(value)
|
|
34
|
+
? value
|
|
35
|
+
: null;
|
|
36
|
+
const cleanVersion = (value) => typeof value === "string" && value.length <= 128 && SAFE_VERSION_PATTERN.test(value) ? value : null;
|
|
37
|
+
|
|
38
|
+
const safeFile = (projectRoot, relative, parseJson = false) => {
|
|
39
|
+
const file = path.join(projectRoot, ...relative.split("/"));
|
|
40
|
+
let current = projectRoot;
|
|
41
|
+
try {
|
|
42
|
+
for (const part of relative.split("/")) {
|
|
43
|
+
current = path.join(current, part);
|
|
44
|
+
const stat = fs.lstatSync(current);
|
|
45
|
+
if (stat.isSymbolicLink()) return { status: "unsafe", path: relative };
|
|
46
|
+
if (current !== file && !stat.isDirectory()) return { status: "unsafe", path: relative };
|
|
47
|
+
if (current === file && !stat.isFile()) return { status: "unsafe", path: relative };
|
|
48
|
+
}
|
|
49
|
+
const descriptor = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
|
|
50
|
+
let content;
|
|
51
|
+
try {
|
|
52
|
+
const opened = fs.fstatSync(descriptor);
|
|
53
|
+
if (!opened.isFile()) return { status: "unsafe", path: relative };
|
|
54
|
+
if (opened.size > MAX_FILE_BYTES) return { status: "oversized", path: relative };
|
|
55
|
+
content = fs.readFileSync(descriptor, "utf8");
|
|
56
|
+
const after = fs.lstatSync(file);
|
|
57
|
+
if (after.isSymbolicLink() || !after.isFile() || after.dev !== opened.dev || after.ino !== opened.ino) return { status: "unsafe", path: relative };
|
|
58
|
+
} finally {
|
|
59
|
+
fs.closeSync(descriptor);
|
|
60
|
+
}
|
|
61
|
+
if (!parseJson) return { status: "available", path: relative, content };
|
|
62
|
+
try {
|
|
63
|
+
const value = JSON.parse(content);
|
|
64
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return { status: "malformed", path: relative };
|
|
65
|
+
return { status: "available", path: relative, value };
|
|
66
|
+
} catch {
|
|
67
|
+
return { status: "malformed", path: relative };
|
|
68
|
+
}
|
|
69
|
+
} catch (error) {
|
|
70
|
+
if (error.code === "ENOENT") return { status: "missing", path: relative };
|
|
71
|
+
return { status: "unavailable", path: relative };
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const packageSpec = (value) => {
|
|
76
|
+
if (typeof value !== "string") return null;
|
|
77
|
+
if (value === PACKAGE_NAME) return { package: PACKAGE_NAME, version: null };
|
|
78
|
+
if (!value.startsWith(`${PACKAGE_NAME}@`)) return null;
|
|
79
|
+
const version = cleanVersion(value.slice(PACKAGE_NAME.length + 1));
|
|
80
|
+
return version ? { package: PACKAGE_NAME, version } : null;
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
const dependencySpec = (value) => {
|
|
84
|
+
if (typeof value !== "string") return null;
|
|
85
|
+
const version = value.startsWith("=") ? value.slice(1) : value;
|
|
86
|
+
const normalized = cleanVersion(version);
|
|
87
|
+
return normalized ? { package: PACKAGE_NAME, version: normalized } : null;
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const collectDeclarations = (projectRoot) => {
|
|
91
|
+
const observations = [];
|
|
92
|
+
for (const [source, relative] of [["opencode", relativeFiles.opencode], ["tui", relativeFiles.tui]]) {
|
|
93
|
+
const file = safeFile(projectRoot, relative, true);
|
|
94
|
+
if (file.status !== "available") {
|
|
95
|
+
observations.push({ source, path: relative, status: file.status });
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
const fields = source === "opencode" ? ["plugin", "plugins"] : ["plugin"];
|
|
99
|
+
let supported = true;
|
|
100
|
+
for (const field of fields) {
|
|
101
|
+
if (file.value[field] !== undefined && !Array.isArray(file.value[field])) supported = false;
|
|
102
|
+
for (const value of Array.isArray(file.value[field]) ? file.value[field] : []) {
|
|
103
|
+
const parsed = packageSpec(value);
|
|
104
|
+
if (parsed) observations.push({ source, path: relative, field, status: "declared", ...parsed, model: "managed" });
|
|
105
|
+
else if (typeof value === "string" && value.startsWith(PACKAGE_NAME)) observations.push({ source, path: relative, field, status: "malformed" });
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (!supported) observations.push({ source, path: relative, status: "unsupported" });
|
|
109
|
+
}
|
|
110
|
+
for (const [source, relative] of [["root_manifest", relativeFiles.rootManifest], ["opencode_manifest", relativeFiles.opencodeManifest]]) {
|
|
111
|
+
const file = safeFile(projectRoot, relative, true);
|
|
112
|
+
if (file.status !== "available") {
|
|
113
|
+
observations.push({ source, path: relative, status: file.status });
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
for (const field of ["dependencies", "devDependencies"]) {
|
|
117
|
+
const container = file.value[field];
|
|
118
|
+
if (container !== undefined && (!container || typeof container !== "object" || Array.isArray(container))) {
|
|
119
|
+
observations.push({ source, path: relative, status: "unsupported" });
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
if (!Object.hasOwn(container || {}, PACKAGE_NAME)) continue;
|
|
123
|
+
const parsed = dependencySpec(container[PACKAGE_NAME]);
|
|
124
|
+
observations.push(parsed
|
|
125
|
+
? { source, path: relative, field, status: "declared", ...parsed, model: "pinned_local" }
|
|
126
|
+
: { source, path: relative, field, status: "malformed" });
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return observations;
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
const collectInstallations = (projectRoot) => [["root", relativeFiles.rootInstalled], ["opencode", relativeFiles.opencodeInstalled]].map(([source, relative]) => {
|
|
133
|
+
const file = safeFile(projectRoot, relative, true);
|
|
134
|
+
if (file.status !== "available") return { source, path: relative, status: file.status };
|
|
135
|
+
const name = file.value.name === PACKAGE_NAME ? PACKAGE_NAME : null;
|
|
136
|
+
const version = cleanVersion(file.value.version);
|
|
137
|
+
if (name !== PACKAGE_NAME || !version) return { source, path: relative, status: "malformed" };
|
|
138
|
+
return { source, path: relative, status: "installed", package: name, version };
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
const normalizeRuntimeEvidence = (evidence, kind) => {
|
|
142
|
+
if (!evidence || evidence.evidence_kind === "unavailable") return {
|
|
143
|
+
evidence_kind: "unavailable",
|
|
144
|
+
reason: kind === "host_attested" ? "authoritative runtime evidence is not provided by the host" : "loaded-plugin self-report is unavailable",
|
|
145
|
+
};
|
|
146
|
+
const packageName = evidence.package_name === PACKAGE_NAME ? PACKAGE_NAME : null;
|
|
147
|
+
const packageVersion = cleanVersion(evidence.package_version);
|
|
148
|
+
const origin = ["project_local", "managed_cache", "package_source", "unknown"].includes(evidence.module_origin) ? evidence.module_origin : "unknown";
|
|
149
|
+
const protocol = evidence.protocol;
|
|
150
|
+
if (packageName !== PACKAGE_NAME || !packageVersion || !protocol
|
|
151
|
+
|| !Number.isInteger(protocol.schema) || !Number.isInteger(protocol.major) || !Number.isInteger(protocol.minor)
|
|
152
|
+
|| typeof protocol.descriptor_hash !== "string" || !/^[a-f0-9]{64}$/.test(protocol.descriptor_hash)) {
|
|
153
|
+
return { evidence_kind: "unavailable", reason: `${kind} runtime evidence is malformed` };
|
|
154
|
+
}
|
|
155
|
+
return {
|
|
156
|
+
evidence_kind: kind,
|
|
157
|
+
package_name: packageName,
|
|
158
|
+
package_version: packageVersion,
|
|
159
|
+
module_origin: origin,
|
|
160
|
+
protocol: {
|
|
161
|
+
schema: protocol.schema,
|
|
162
|
+
major: protocol.major,
|
|
163
|
+
minor: protocol.minor,
|
|
164
|
+
descriptor_hash: protocol.descriptor_hash,
|
|
165
|
+
},
|
|
166
|
+
};
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
const repairFor = (model, version, commandChanged) => {
|
|
170
|
+
const target = cleanVersion(version);
|
|
171
|
+
if (!target || !["managed", "pinned_local"].includes(model)) return {
|
|
172
|
+
model: "unknown",
|
|
173
|
+
steps: ["Resolve the installation model and exact loaded package version, then rerun delivery doctor."],
|
|
174
|
+
restart_required: false,
|
|
175
|
+
};
|
|
176
|
+
if (model === "managed") return {
|
|
177
|
+
model: "managed",
|
|
178
|
+
steps: [
|
|
179
|
+
`opencode plugin ${PACKAGE_NAME}@${target} --force`,
|
|
180
|
+
...(commandChanged ? [`npx --yes ${PACKAGE_NAME}@${target} activate --force`] : []),
|
|
181
|
+
"Restart OpenCode.",
|
|
182
|
+
],
|
|
183
|
+
restart_required: true,
|
|
184
|
+
};
|
|
185
|
+
return {
|
|
186
|
+
model: "pinned_local",
|
|
187
|
+
steps: [`npx --yes ${PACKAGE_NAME}@${target} init --force`, "Restart OpenCode."],
|
|
188
|
+
restart_required: true,
|
|
189
|
+
};
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
const addFinding = (findings, id, severity, summary, repair) => {
|
|
193
|
+
if (!findings.some((finding) => finding.id === id)) findings.push({ id, severity, summary, ...(repair ? { repair } : {}) });
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
export function validateDeliveryDoctorEnvelope(envelope) {
|
|
197
|
+
if (!envelope || typeof envelope !== "object" || Array.isArray(envelope)
|
|
198
|
+
|| envelope.contract_version !== DELIVERY_DOCTOR_CONTRACT_VERSION
|
|
199
|
+
|| envelope.operation !== DELIVERY_DOCTOR_OPERATION
|
|
200
|
+
|| !envelope.protocol || typeof envelope.protocol !== "object" || Array.isArray(envelope.protocol)
|
|
201
|
+
|| !envelope.evidence || typeof envelope.evidence !== "object" || Array.isArray(envelope.evidence)
|
|
202
|
+
|| !DELIVERY_DOCTOR_EVIDENCE_KINDS.includes(envelope.evidence.loaded_plugin?.evidence_kind)
|
|
203
|
+
|| !DELIVERY_DOCTOR_EVIDENCE_KINDS.includes(envelope.evidence.host_attestation?.evidence_kind)
|
|
204
|
+
|| !Array.isArray(envelope.evidence.declarations) || !Array.isArray(envelope.evidence.installations)
|
|
205
|
+
|| !Array.isArray(envelope.findings)
|
|
206
|
+
|| envelope.findings.length > 100) fail(ERROR_CODES.INVALID_ARGUMENT, "Invalid delivery doctor output envelope");
|
|
207
|
+
for (const finding of envelope.findings) {
|
|
208
|
+
if (!finding || typeof finding !== "object" || Array.isArray(finding)
|
|
209
|
+
|| typeof finding.id !== "string" || !/^[a-z][a-z0-9_.-]*$/.test(finding.id)
|
|
210
|
+
|| !["info", "warning", "error"].includes(finding.severity)
|
|
211
|
+
|| typeof finding.summary !== "string" || !finding.summary) fail(ERROR_CODES.INVALID_ARGUMENT, "Invalid delivery doctor finding");
|
|
212
|
+
}
|
|
213
|
+
const serialized = JSON.stringify(envelope);
|
|
214
|
+
if (Buffer.byteLength(serialized, "utf8") > MAX_FILE_BYTES) fail(ERROR_CODES.DELIVERY_DIAGNOSTIC_TOO_LARGE, "Delivery doctor output exceeds the supported 1 MiB limit");
|
|
215
|
+
return envelope;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export function doctorDelivery(projectRoot, options = {}) {
|
|
219
|
+
projectRoot = fs.realpathSync(path.resolve(projectRoot));
|
|
220
|
+
const loaded = normalizeRuntimeEvidence(options.loadedPlugin, "self_reported");
|
|
221
|
+
const host = normalizeRuntimeEvidence(options.hostAttestation, "host_attested");
|
|
222
|
+
const commandFile = safeFile(projectRoot, relativeFiles.command);
|
|
223
|
+
const marker = commandFile.status === "available" ? parseWorkContextProtocolMarker(commandFile.content) : null;
|
|
224
|
+
const command = {
|
|
225
|
+
path: relativeFiles.command,
|
|
226
|
+
status: commandFile.status === "available" ? (marker ? "available" : "malformed") : commandFile.status,
|
|
227
|
+
...(marker ? { marker } : {}),
|
|
228
|
+
};
|
|
229
|
+
const declarations = collectDeclarations(projectRoot);
|
|
230
|
+
const installations = collectInstallations(projectRoot);
|
|
231
|
+
const declared = declarations.filter((item) => item.status === "declared");
|
|
232
|
+
const installed = installations.filter((item) => item.status === "installed");
|
|
233
|
+
const models = [...new Set(declared.map((item) => item.model))];
|
|
234
|
+
const model = models.length > 1 ? "conflict" : models[0] || (loaded.module_origin === "managed_cache" ? "managed" : "pinned_local");
|
|
235
|
+
const version = loaded.package_version;
|
|
236
|
+
const findings = [];
|
|
237
|
+
|
|
238
|
+
if (marker && loaded.evidence_kind === "self_reported" && marker.major !== loaded.protocol.major) {
|
|
239
|
+
fail(ERROR_CODES.DELIVERY_COMMAND_PROTOCOL_MISMATCH, "Generated command and loaded plugin use incompatible protocol majors", {
|
|
240
|
+
command_major: marker.major,
|
|
241
|
+
loaded_major: loaded.protocol.major,
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
if (command.status !== "available") addFinding(findings, `command.${command.status}`, "error", `Generated command protocol marker is ${command.status}.`, repairFor(model, version, true));
|
|
245
|
+
if (marker && loaded.evidence_kind === "self_reported") {
|
|
246
|
+
if (marker.minor !== loaded.protocol.minor) {
|
|
247
|
+
const direction = marker.minor < loaded.protocol.minor ? "generated command is older" : "loaded plugin is older";
|
|
248
|
+
addFinding(findings, "command.protocol_minor_drift", "warning", `Protocol minors differ: ${direction}.`, repairFor(model, version, true));
|
|
249
|
+
}
|
|
250
|
+
if (marker.schema !== loaded.protocol.schema) addFinding(findings, "command.schema_mismatch", "warning", "Generated command protocol schema differs from the loaded plugin.", repairFor(model, version, true));
|
|
251
|
+
if (marker.descriptor_hash !== `sha256:${loaded.protocol.descriptor_hash}`) addFinding(findings, "command.descriptor_hash_mismatch", "warning", "Generated command descriptor hash differs from the loaded plugin.", repairFor(model, version, true));
|
|
252
|
+
}
|
|
253
|
+
if (loaded.evidence_kind === "unavailable") {
|
|
254
|
+
addFinding(findings, "runtime.protocol_major_unknown", "error", "Loaded-plugin protocol major is unknown, so compatibility cannot be established.", repairFor(model, version, false));
|
|
255
|
+
addFinding(findings, "runtime.self_report_unavailable", "warning", "Loaded-plugin self-report is unavailable.", repairFor(model, version, false));
|
|
256
|
+
} else {
|
|
257
|
+
if (loaded.protocol.schema !== WORK_CONTEXT_PROTOCOL.schema) addFinding(findings, "runtime.self_report_schema_mismatch", "warning", "Loaded-plugin self-reported protocol schema differs from this package contract.", repairFor(model, version, false));
|
|
258
|
+
if (loaded.protocol.descriptor_hash !== WORK_CONTEXT_PROTOCOL_DESCRIPTOR_HASH) addFinding(findings, "runtime.self_report_hash_mismatch", "warning", "Loaded-plugin self-reported descriptor hash differs from this package contract.", repairFor(model, version, false));
|
|
259
|
+
}
|
|
260
|
+
if (host.evidence_kind === "unavailable") addFinding(findings, "runtime.host_attestation_unavailable", "info", "The host does not provide authoritative loaded-plugin attestation.");
|
|
261
|
+
if (host.evidence_kind === "host_attested" && loaded.evidence_kind === "self_reported") {
|
|
262
|
+
if (host.protocol.major !== loaded.protocol.major) addFinding(findings, "runtime.host_protocol_mismatch", "error", "Host-attested and self-reported protocol majors differ.", repairFor(model, version, false));
|
|
263
|
+
if (host.protocol.minor !== loaded.protocol.minor) addFinding(findings, "runtime.host_protocol_minor_mismatch", "warning", "Host-attested and self-reported protocol minors differ.", repairFor(model, version, false));
|
|
264
|
+
if (host.protocol.schema !== loaded.protocol.schema) addFinding(findings, "runtime.host_schema_mismatch", "warning", "Host-attested and self-reported protocol schemas differ.", repairFor(model, version, false));
|
|
265
|
+
if (host.protocol.descriptor_hash !== loaded.protocol.descriptor_hash) addFinding(findings, "runtime.host_hash_mismatch", "warning", "Host-attested and self-reported descriptor hashes differ.", repairFor(model, version, false));
|
|
266
|
+
if (host.package_version !== loaded.package_version) addFinding(findings, "runtime.host_version_mismatch", "warning", "Host-attested and self-reported package versions differ.", repairFor(model, version, false));
|
|
267
|
+
if (host.module_origin !== "unknown" && host.module_origin !== loaded.module_origin) addFinding(findings, "runtime.host_origin_mismatch", "warning", "Host-attested and self-reported module origins differ.", repairFor(model, version, false));
|
|
268
|
+
}
|
|
269
|
+
for (const observation of declarations) {
|
|
270
|
+
if (!["missing", "available", "declared"].includes(observation.status)) addFinding(findings, `declaration.${observation.source}.${observation.status}`, "warning", `${observation.path} declaration evidence is ${observation.status}.`, repairFor(model, version, false));
|
|
271
|
+
}
|
|
272
|
+
for (const observation of installations) {
|
|
273
|
+
if (!["missing", "installed"].includes(observation.status)) addFinding(findings, `installation.${observation.source}.${observation.status}`, "warning", `${observation.path} installation evidence is ${observation.status}.`, repairFor(model, version, false));
|
|
274
|
+
}
|
|
275
|
+
if (!declared.length) addFinding(findings, "declaration.missing", "warning", "No supported project declaration for opencode-work-context was found.", repairFor(model, version, false));
|
|
276
|
+
if (declared.some((item) => item.version === null)) addFinding(findings, "declaration.version_unpinned", "warning", "A managed package declaration does not identify an exact version.", repairFor(model, version, false));
|
|
277
|
+
const declarationKeys = declared.map((item) => `${item.path}:${item.field}:${item.version || "unversioned"}`);
|
|
278
|
+
if (new Set(declarationKeys).size !== declarationKeys.length) addFinding(findings, "declaration.duplicate", "warning", "A project configuration contains duplicate opencode-work-context declarations.", repairFor(model, version, false));
|
|
279
|
+
if (models.length > 1) addFinding(findings, "declaration.installation_model_conflict", "error", "Managed and pinned-local declarations are both present.", repairFor(model, version, false));
|
|
280
|
+
if (version && declared.some((item) => item.version && item.version !== version)) addFinding(findings, "declaration.version_mismatch", "warning", "A declared package version differs from the loaded package version.", repairFor(model, version, false));
|
|
281
|
+
if (model === "pinned_local" && !installed.length) addFinding(findings, "installation.missing", "warning", "No safely discoverable pinned-local package manifest was found.", repairFor(model, version, false));
|
|
282
|
+
if (version && installed.some((item) => item.version !== version)) addFinding(findings, "installation.version_mismatch", "warning", "An installed package version differs from the loaded package version.", repairFor(model, version, false));
|
|
283
|
+
const localLoader = safeFile(projectRoot, relativeFiles.localLoader);
|
|
284
|
+
if (model === "pinned_local" && localLoader.status !== "available") addFinding(findings, "origin.local_loader_missing", "warning", "Pinned-local declaration exists without a regular package-managed loader.", repairFor(model, version, false));
|
|
285
|
+
if (loaded.evidence_kind === "self_reported"
|
|
286
|
+
&& ((model === "managed" && loaded.module_origin === "project_local") || (model === "pinned_local" && loaded.module_origin === "managed_cache"))) {
|
|
287
|
+
addFinding(findings, "origin.installation_model_mismatch", "warning", "Loaded-plugin origin differs from the declared installation model.", repairFor(model, version, false));
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
findings.sort((left, right) => left.id < right.id ? -1 : left.id > right.id ? 1 : 0);
|
|
291
|
+
return validateDeliveryDoctorEnvelope({
|
|
292
|
+
contract_version: DELIVERY_DOCTOR_CONTRACT_VERSION,
|
|
293
|
+
operation: DELIVERY_DOCTOR_OPERATION,
|
|
294
|
+
protocol: {
|
|
295
|
+
schema: WORK_CONTEXT_PROTOCOL.schema,
|
|
296
|
+
major: WORK_CONTEXT_PROTOCOL.major,
|
|
297
|
+
minor: WORK_CONTEXT_PROTOCOL.minor,
|
|
298
|
+
descriptor_hash: WORK_CONTEXT_PROTOCOL_DESCRIPTOR_HASH,
|
|
299
|
+
},
|
|
300
|
+
evidence: { command, declarations, installations, loaded_plugin: loaded, host_attestation: host },
|
|
301
|
+
findings,
|
|
302
|
+
complete: true,
|
|
303
|
+
});
|
|
304
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { Buffer } from "node:buffer";
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
3
|
+
import { ERROR_CODES, fail } from "./errors.js";
|
|
4
|
+
import { DELIVERY_DIAGNOSTIC_LIMITS } from "./delivery-contracts.js";
|
|
5
|
+
import { repositoryState } from "./git-candidates.js";
|
|
6
|
+
|
|
7
|
+
const hashPattern = /^[0-9a-f]{40,64}$/;
|
|
8
|
+
const gitFlags = ["--no-ext-diff", "--no-textconv", "--no-color"];
|
|
9
|
+
const compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
|
|
10
|
+
|
|
11
|
+
const assertHash = (value, label) => {
|
|
12
|
+
if (typeof value !== "string" || !hashPattern.test(value)) fail(ERROR_CODES.INVALID_ARGUMENT, `${label} must be a full lowercase commit hash`);
|
|
13
|
+
return value;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const runGit = (root, args, budget, options = {}) => {
|
|
17
|
+
const remaining = DELIVERY_DIAGNOSTIC_LIMITS.git_output_bytes - budget.bytes;
|
|
18
|
+
if (remaining <= 0) fail(ERROR_CODES.DELIVERY_RANGE_TOO_LARGE, "Delivery Git evidence exceeds the supported 4 MiB limit");
|
|
19
|
+
const result = spawnSync("git", args, {
|
|
20
|
+
cwd: root,
|
|
21
|
+
encoding: null,
|
|
22
|
+
env: { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_LITERAL_PATHSPECS: "1" },
|
|
23
|
+
maxBuffer: remaining,
|
|
24
|
+
});
|
|
25
|
+
if (result.error?.code === "ENOENT") fail(ERROR_CODES.GIT_UNAVAILABLE, "Git executable is unavailable");
|
|
26
|
+
if (result.error?.code === "ENOBUFS") fail(ERROR_CODES.DELIVERY_RANGE_TOO_LARGE, "Delivery Git evidence exceeds the supported 4 MiB limit");
|
|
27
|
+
if (result.error) fail(ERROR_CODES.GIT_UNAVAILABLE, "Cannot execute Git");
|
|
28
|
+
budget.bytes += (result.stdout?.length || 0) + (result.stderr?.length || 0);
|
|
29
|
+
if (budget.bytes > DELIVERY_DIAGNOSTIC_LIMITS.git_output_bytes) fail(ERROR_CODES.DELIVERY_RANGE_TOO_LARGE, "Delivery Git evidence exceeds the supported 4 MiB limit");
|
|
30
|
+
if (result.status !== 0 && !options.allowFailure) fail(options.code || ERROR_CODES.DELIVERY_INVALID_RANGE, options.message || "Cannot inspect delivery range");
|
|
31
|
+
return result;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const sanitizeSubject = (value) => {
|
|
35
|
+
const normalized = value.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/gu, " ").replace(/\s+/gu, " ").trim();
|
|
36
|
+
const bytes = Buffer.from(normalized, "utf8");
|
|
37
|
+
if (bytes.length <= DELIVERY_DIAGNOSTIC_LIMITS.commit_subject_bytes) return normalized;
|
|
38
|
+
let end = DELIVERY_DIAGNOSTIC_LIMITS.commit_subject_bytes;
|
|
39
|
+
while (end > 0 && (bytes[end] & 0xc0) === 0x80) end -= 1;
|
|
40
|
+
return bytes.subarray(0, end).toString("utf8").trimEnd();
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const normalizePath = (value) => value.replace(/^\.\//u, "");
|
|
44
|
+
|
|
45
|
+
const parseNameStatus = (buffer) => {
|
|
46
|
+
const tokens = buffer.toString("utf8").split("\0");
|
|
47
|
+
const changes = [];
|
|
48
|
+
for (let index = 0; index < tokens.length - 1;) {
|
|
49
|
+
const code = tokens[index++];
|
|
50
|
+
if (!code) continue;
|
|
51
|
+
const kind = code[0];
|
|
52
|
+
const source = normalizePath(tokens[index++]);
|
|
53
|
+
if (kind === "R" || kind === "C") {
|
|
54
|
+
const destination = normalizePath(tokens[index++]);
|
|
55
|
+
changes.push({ code: kind, similarity: Number(code.slice(1)), source, path: destination });
|
|
56
|
+
} else {
|
|
57
|
+
changes.push({ code: kind, path: source });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return changes;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const parseNumstat = (buffer) => {
|
|
64
|
+
const tokens = buffer.toString("utf8").split("\0");
|
|
65
|
+
const stats = new Map();
|
|
66
|
+
for (let index = 0; index < tokens.length - 1;) {
|
|
67
|
+
const token = tokens[index++];
|
|
68
|
+
if (!token) continue;
|
|
69
|
+
const firstTab = token.indexOf("\t");
|
|
70
|
+
const secondTab = token.indexOf("\t", firstTab + 1);
|
|
71
|
+
if (firstTab < 0 || secondTab < 0) continue;
|
|
72
|
+
const added = token.slice(0, firstTab);
|
|
73
|
+
const deleted = token.slice(firstTab + 1, secondTab);
|
|
74
|
+
let file = token.slice(secondTab + 1);
|
|
75
|
+
if (!file) {
|
|
76
|
+
index += 1;
|
|
77
|
+
file = tokens[index++] || "";
|
|
78
|
+
}
|
|
79
|
+
stats.set(normalizePath(file), {
|
|
80
|
+
additions: added === "-" ? null : Number(added),
|
|
81
|
+
deletions: deleted === "-" ? null : Number(deleted),
|
|
82
|
+
binary: added === "-" || deleted === "-",
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
return stats;
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const statusName = (code) => ({ A: "added", D: "deleted", R: "renamed", C: "copied" }[code] || "modified");
|
|
89
|
+
|
|
90
|
+
export function inspectDetailedCommitRange(projectRoot, from, to) {
|
|
91
|
+
const repository = repositoryState(projectRoot);
|
|
92
|
+
from = assertHash(from, "Range start");
|
|
93
|
+
to = assertHash(to, "Range end");
|
|
94
|
+
const budget = { bytes: 0 };
|
|
95
|
+
const available = (commit) => runGit(repository.root, ["cat-file", "-e", `${commit}^{commit}`], budget, { allowFailure: true }).status === 0;
|
|
96
|
+
if (!available(from) || !available(to)
|
|
97
|
+
|| runGit(repository.root, ["merge-base", "--is-ancestor", from, to], budget, { allowFailure: true }).status !== 0) {
|
|
98
|
+
fail(ERROR_CODES.DELIVERY_INVALID_RANGE, "Delivery range must contain available commits in ancestor order", { from, to });
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const count = Number(runGit(repository.root, ["rev-list", "--first-parent", "--count", `${from}..${to}`], budget).stdout.toString("utf8").trim());
|
|
102
|
+
const hashes = runGit(repository.root, ["rev-list", "--first-parent", "--reverse", `--max-count=${DELIVERY_DIAGNOSTIC_LIMITS.commits}`, `${from}..${to}`], budget)
|
|
103
|
+
.stdout.toString("utf8").trim().split("\n").filter(Boolean);
|
|
104
|
+
const commits = [];
|
|
105
|
+
const provenance = new Map();
|
|
106
|
+
const lineage = [];
|
|
107
|
+
|
|
108
|
+
for (const hash of hashes) {
|
|
109
|
+
const subject = runGit(repository.root, ["show", "-s", "--format=%s", hash], budget).stdout.toString("utf8").replace(/\n$/u, "");
|
|
110
|
+
commits.push({ commit: hash, subject: sanitizeSubject(subject) });
|
|
111
|
+
const baseArgs = ["diff-tree", "-r", "-z", ...gitFlags, "--find-renames=50%", "--find-copies=50%", `${hash}^1`, hash, "--"];
|
|
112
|
+
const changes = parseNameStatus(runGit(repository.root, [...baseArgs.slice(0, 3), "--name-status", ...baseArgs.slice(3)], budget).stdout);
|
|
113
|
+
for (const change of changes) {
|
|
114
|
+
let pathProvenance = provenance.get(change.path);
|
|
115
|
+
if (!pathProvenance) {
|
|
116
|
+
pathProvenance = { commits: [], truncated: false };
|
|
117
|
+
provenance.set(change.path, pathProvenance);
|
|
118
|
+
}
|
|
119
|
+
if (pathProvenance.commits.length < DELIVERY_DIAGNOSTIC_LIMITS.provenance_commits_per_path) pathProvenance.commits.push(hash);
|
|
120
|
+
else pathProvenance.truncated = true;
|
|
121
|
+
if (change.code === "R" || change.code === "C") {
|
|
122
|
+
lineage.push({ commit: hash, status: statusName(change.code), similarity: change.similarity, from_path: change.source, to_path: change.path });
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const endpointArgs = ["diff", "-z", ...gitFlags, "--find-renames=50%", "--find-copies=50%", from, to, "--"];
|
|
128
|
+
const finalChanges = parseNameStatus(runGit(repository.root, [...endpointArgs.slice(0, 2), "--name-status", ...endpointArgs.slice(2)], budget).stdout);
|
|
129
|
+
const finalStats = parseNumstat(runGit(repository.root, [...endpointArgs.slice(0, 2), "--numstat", ...endpointArgs.slice(2)], budget).stdout);
|
|
130
|
+
const allPaths = finalChanges.map((change) => {
|
|
131
|
+
const stat = finalStats.get(change.path) || { additions: 0, deletions: 0, binary: false };
|
|
132
|
+
const pathProvenance = provenance.get(change.path) || { commits: [], truncated: false };
|
|
133
|
+
return {
|
|
134
|
+
path: change.path,
|
|
135
|
+
status: statusName(change.code),
|
|
136
|
+
additions: stat.additions,
|
|
137
|
+
deletions: stat.deletions,
|
|
138
|
+
binary: stat.binary,
|
|
139
|
+
provenance: pathProvenance.commits,
|
|
140
|
+
provenance_truncated: pathProvenance.truncated,
|
|
141
|
+
};
|
|
142
|
+
}).sort((left, right) => compareText(left.path, right.path));
|
|
143
|
+
const commitOrder = new Map(hashes.map((hash, index) => [hash, index]));
|
|
144
|
+
lineage.sort((left, right) => (commitOrder.get(left.commit) - commitOrder.get(right.commit))
|
|
145
|
+
|| compareText(left.to_path, right.to_path) || compareText(left.from_path, right.from_path));
|
|
146
|
+
return {
|
|
147
|
+
immutable_range: { from, to },
|
|
148
|
+
commit_count: count,
|
|
149
|
+
commits,
|
|
150
|
+
commits_truncated: count > commits.length,
|
|
151
|
+
path_count: allPaths.length,
|
|
152
|
+
paths: allPaths.slice(0, DELIVERY_DIAGNOSTIC_LIMITS.paths),
|
|
153
|
+
paths_truncated: allPaths.length > DELIVERY_DIAGNOSTIC_LIMITS.paths,
|
|
154
|
+
lineage,
|
|
155
|
+
git_output_bytes: budget.bytes,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export { sanitizeSubject as sanitizeDeliveryCommitSubject };
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { DELIVERY_DIAGNOSTIC_LIMITS } from "./delivery-contracts.js";
|
|
3
|
+
import { ERROR_CODES, fail } from "./errors.js";
|
|
4
|
+
|
|
5
|
+
const compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
|
|
6
|
+
const invalidGlobCharacters = /[\u0000-\u001f\u007f\\\[\]{}?!]/u;
|
|
7
|
+
|
|
8
|
+
export function validateSecretPathPatterns(value = []) {
|
|
9
|
+
if (!Array.isArray(value) || value.length > DELIVERY_DIAGNOSTIC_LIMITS.secret_path_patterns) {
|
|
10
|
+
fail(ERROR_CODES.STORAGE_ERROR, "Invalid work-context config");
|
|
11
|
+
}
|
|
12
|
+
const patterns = value.map((pattern) => {
|
|
13
|
+
if (typeof pattern !== "string" || !pattern || pattern.length > DELIVERY_DIAGNOSTIC_LIMITS.secret_path_pattern_characters
|
|
14
|
+
|| path.posix.isAbsolute(pattern) || invalidGlobCharacters.test(pattern)) {
|
|
15
|
+
fail(ERROR_CODES.STORAGE_ERROR, "Invalid work-context config");
|
|
16
|
+
}
|
|
17
|
+
const segments = pattern.split("/");
|
|
18
|
+
if (segments.some((segment) => !segment || segment === "." || segment === ".." || (segment.includes("**") && segment !== "**"))) {
|
|
19
|
+
fail(ERROR_CODES.STORAGE_ERROR, "Invalid work-context config");
|
|
20
|
+
}
|
|
21
|
+
return pattern;
|
|
22
|
+
});
|
|
23
|
+
if (new Set(patterns).size !== patterns.length) fail(ERROR_CODES.STORAGE_ERROR, "Invalid work-context config");
|
|
24
|
+
return patterns;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const segmentMatches = (pattern, value) => {
|
|
28
|
+
const source = pattern.split("*").map((part) => part.replace(/[.+^$()|]/gu, "\\$&")).join(".*");
|
|
29
|
+
return new RegExp(`^${source}$`, "u").test(value);
|
|
30
|
+
};
|
|
31
|
+
const pathMatches = (pattern, value) => {
|
|
32
|
+
const patterns = pattern.split("/");
|
|
33
|
+
const segments = value.split("/");
|
|
34
|
+
const memo = new Map();
|
|
35
|
+
const visit = (patternIndex, segmentIndex) => {
|
|
36
|
+
const key = `${patternIndex}:${segmentIndex}`;
|
|
37
|
+
if (memo.has(key)) return memo.get(key);
|
|
38
|
+
let result;
|
|
39
|
+
if (patternIndex === patterns.length) return segmentIndex === segments.length;
|
|
40
|
+
if (patterns[patternIndex] === "**") {
|
|
41
|
+
result = visit(patternIndex + 1, segmentIndex) || (segmentIndex < segments.length && visit(patternIndex, segmentIndex + 1));
|
|
42
|
+
} else {
|
|
43
|
+
result = segmentIndex < segments.length && segmentMatches(patterns[patternIndex], segments[segmentIndex]) && visit(patternIndex + 1, segmentIndex + 1);
|
|
44
|
+
}
|
|
45
|
+
memo.set(key, result);
|
|
46
|
+
return result;
|
|
47
|
+
};
|
|
48
|
+
return visit(0, 0);
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export function createDeliveryPathRedactor(patterns, paths) {
|
|
52
|
+
const validatedPatterns = validateSecretPathPatterns(patterns);
|
|
53
|
+
const redactedPaths = [...new Set(paths.filter((value) => typeof value === "string" && validatedPatterns.some((pattern) => pathMatches(pattern, value))))].sort(compareText);
|
|
54
|
+
const tokens = new Map(redactedPaths.map((value, index) => [value, `<redacted:path-${String(index + 1).padStart(4, "0")}>`]));
|
|
55
|
+
const textPaths = [...redactedPaths].sort((left, right) => right.length - left.length || compareText(left, right));
|
|
56
|
+
return {
|
|
57
|
+
path(value) { return tokens.get(value) || value; },
|
|
58
|
+
text(value) {
|
|
59
|
+
if (typeof value !== "string") return value;
|
|
60
|
+
return textPaths.reduce((text, secretPath) => text.split(secretPath).join(tokens.get(secretPath)), value);
|
|
61
|
+
},
|
|
62
|
+
summary: {
|
|
63
|
+
applied: tokens.size > 0,
|
|
64
|
+
path_count: tokens.size,
|
|
65
|
+
tokens: [...tokens.values()],
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { ERROR_CODES, fail } from "./errors.js";
|
|
2
|
+
|
|
3
|
+
const strategies = new Set(["exact", "shared_foundation", "integration"]);
|
|
4
|
+
const confidenceByStrategy = Object.freeze({ exact: 1, shared_foundation: 0.8, integration: 0.6 });
|
|
5
|
+
const strategyOrder = Object.freeze({ exact: 0, shared_foundation: 1, integration: 2 });
|
|
6
|
+
const stableIdPattern = /^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/;
|
|
7
|
+
const candidatePattern = /^CC-\d{6}$/;
|
|
8
|
+
const commitPattern = /^[0-9a-f]{40,64}$/;
|
|
9
|
+
const referenceLimits = Object.freeze({ paths: 500, findings: 200, rationale: 4, candidates: 500, commits: 500, slices: 200 });
|
|
10
|
+
const compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
|
|
11
|
+
const sortedUnique = (values) => [...new Set(values)].sort(compareText);
|
|
12
|
+
const intersects = (left, right) => left.some((value) => right.has(value));
|
|
13
|
+
|
|
14
|
+
function components(items, connected) {
|
|
15
|
+
const parents = items.map((_, index) => index);
|
|
16
|
+
const root = (index) => {
|
|
17
|
+
while (parents[index] !== index) {
|
|
18
|
+
parents[index] = parents[parents[index]];
|
|
19
|
+
index = parents[index];
|
|
20
|
+
}
|
|
21
|
+
return index;
|
|
22
|
+
};
|
|
23
|
+
const union = (left, right) => {
|
|
24
|
+
left = root(left);
|
|
25
|
+
right = root(right);
|
|
26
|
+
if (left !== right) parents[right] = left;
|
|
27
|
+
};
|
|
28
|
+
for (let left = 0; left < items.length; left += 1) {
|
|
29
|
+
for (let right = left + 1; right < items.length; right += 1) {
|
|
30
|
+
if (connected(items[left], items[right])) union(left, right);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
const groups = new Map();
|
|
34
|
+
for (let index = 0; index < items.length; index += 1) {
|
|
35
|
+
const key = root(index);
|
|
36
|
+
if (!groups.has(key)) groups.set(key, []);
|
|
37
|
+
groups.get(key).push(items[index]);
|
|
38
|
+
}
|
|
39
|
+
return [...groups.values()];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function candidateReferences(paths, commits, traceability) {
|
|
43
|
+
const pathSet = new Set(paths);
|
|
44
|
+
const commitSet = new Set(commits);
|
|
45
|
+
return sortedUnique((traceability?.candidates || [])
|
|
46
|
+
.filter((candidate) => intersects(candidate.paths || [], pathSet) || intersects(candidate.commits || [], commitSet))
|
|
47
|
+
.map((candidate) => candidate.candidate));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function recommendation(strategy, findings, pathEvidence, traceability, sharedCommits = []) {
|
|
51
|
+
const pathReferences = sortedUnique(findings.flatMap((finding) => finding.matched_paths));
|
|
52
|
+
const allCommits = sortedUnique(pathReferences.flatMap((path) => pathEvidence.get(path)?.provenance || []));
|
|
53
|
+
const candidateRefs = candidateReferences(pathReferences, allCommits, traceability);
|
|
54
|
+
const rationale = {
|
|
55
|
+
exact: "delivery.slice.exact_path_match",
|
|
56
|
+
shared_foundation: "delivery.slice.shared_commit_provenance",
|
|
57
|
+
integration: "delivery.slice.overlapping_finding_paths",
|
|
58
|
+
}[strategy];
|
|
59
|
+
return {
|
|
60
|
+
strategy,
|
|
61
|
+
confidence: confidenceByStrategy[strategy],
|
|
62
|
+
path_references: pathReferences,
|
|
63
|
+
finding_references: findings.map((finding) => finding.id).sort(compareText),
|
|
64
|
+
rationale_ids: [rationale, ...(candidateRefs.length ? ["delivery.slice.candidate_traceability"] : [])].sort(compareText),
|
|
65
|
+
candidate_references: candidateRefs,
|
|
66
|
+
commit_references: sortedUnique(sharedCommits),
|
|
67
|
+
requires_user_decision: true,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function recommendDeliverySlices({ findings = [], paths = [], candidate_traceability: traceability = {} } = {}) {
|
|
72
|
+
const pathEvidence = new Map(paths.map((item) => [item.path, item]));
|
|
73
|
+
const ambiguousPaths = new Set(findings
|
|
74
|
+
.filter((finding) => !Array.isArray(finding.matched_paths) || !Array.isArray(finding.unmatched_paths)
|
|
75
|
+
|| finding.unmatched_paths.length > 0 || finding.matched_paths.length !== finding.affected_paths?.length)
|
|
76
|
+
.flatMap((finding) => finding.matched_paths || []));
|
|
77
|
+
const eligible = findings.filter((finding) => Array.isArray(finding.matched_paths) && finding.matched_paths.length > 0
|
|
78
|
+
&& Array.isArray(finding.unmatched_paths) && finding.unmatched_paths.length === 0
|
|
79
|
+
&& finding.matched_paths.length === finding.affected_paths?.length
|
|
80
|
+
&& finding.matched_paths.every((item) => pathEvidence.has(item) && !ambiguousPaths.has(item)));
|
|
81
|
+
|
|
82
|
+
const pathGroups = components(eligible, (left, right) => intersects(left.matched_paths, new Set(right.matched_paths)));
|
|
83
|
+
const recommendations = pathGroups.filter((group) => group.length > 1)
|
|
84
|
+
.map((group) => recommendation("integration", group, pathEvidence, traceability));
|
|
85
|
+
const separable = pathGroups.filter((group) => group.length === 1).map(([finding]) => ({
|
|
86
|
+
finding,
|
|
87
|
+
commits: new Set(finding.matched_paths.flatMap((item) => pathEvidence.get(item).provenance || [])),
|
|
88
|
+
}));
|
|
89
|
+
const provenanceGroups = components(separable, (left, right) => intersects([...left.commits], right.commits));
|
|
90
|
+
for (const group of provenanceGroups) {
|
|
91
|
+
if (group.length === 1) {
|
|
92
|
+
recommendations.push(recommendation("exact", [group[0].finding], pathEvidence, traceability));
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
const commitCounts = new Map();
|
|
96
|
+
for (const item of group) for (const commit of item.commits) commitCounts.set(commit, (commitCounts.get(commit) || 0) + 1);
|
|
97
|
+
const sharedCommits = [...commitCounts].filter(([, count]) => count > 1).map(([commit]) => commit);
|
|
98
|
+
recommendations.push(recommendation("shared_foundation", group.map((item) => item.finding), pathEvidence, traceability, sharedCommits));
|
|
99
|
+
}
|
|
100
|
+
return recommendations.sort((left, right) => strategyOrder[left.strategy] - strategyOrder[right.strategy]
|
|
101
|
+
|| compareText(left.finding_references[0], right.finding_references[0])
|
|
102
|
+
|| compareText(left.path_references[0], right.path_references[0]));
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const validSortedUnique = (values, limit, validator) => Array.isArray(values) && values.length <= limit
|
|
106
|
+
&& values.every(validator) && new Set(values).size === values.length
|
|
107
|
+
&& values.every((value, index) => index === 0 || compareText(values[index - 1], value) < 0);
|
|
108
|
+
|
|
109
|
+
export function validateDeliverySlices(slices) {
|
|
110
|
+
const keys = ["strategy", "confidence", "path_references", "finding_references", "rationale_ids", "candidate_references", "commit_references", "requires_user_decision"];
|
|
111
|
+
const valid = Array.isArray(slices) && slices.length <= referenceLimits.slices && slices.every((slice) => slice && typeof slice === "object" && !Array.isArray(slice)
|
|
112
|
+
&& Object.keys(slice).length === keys.length && keys.every((key) => Object.hasOwn(slice, key))
|
|
113
|
+
&& strategies.has(slice.strategy) && slice.confidence === confidenceByStrategy[slice.strategy]
|
|
114
|
+
&& slice.requires_user_decision === true
|
|
115
|
+
&& validSortedUnique(slice.path_references, referenceLimits.paths, (value) => typeof value === "string" && value.length > 0)
|
|
116
|
+
&& slice.path_references.length > 0
|
|
117
|
+
&& validSortedUnique(slice.finding_references, referenceLimits.findings, (value) => typeof value === "string" && stableIdPattern.test(value))
|
|
118
|
+
&& slice.finding_references.length > 0
|
|
119
|
+
&& validSortedUnique(slice.rationale_ids, referenceLimits.rationale, (value) => typeof value === "string" && stableIdPattern.test(value))
|
|
120
|
+
&& slice.rationale_ids.length > 0
|
|
121
|
+
&& validSortedUnique(slice.candidate_references, referenceLimits.candidates, (value) => typeof value === "string" && candidatePattern.test(value))
|
|
122
|
+
&& validSortedUnique(slice.commit_references, referenceLimits.commits, (value) => typeof value === "string" && commitPattern.test(value)));
|
|
123
|
+
if (!valid) fail(ERROR_CODES.INVALID_ARGUMENT, "Invalid delivery candidate-slice recommendations");
|
|
124
|
+
return slices;
|
|
125
|
+
}
|