opencode-work-context 0.10.1 → 0.10.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.
@@ -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
+ }
package/src/delivery.js CHANGED
@@ -5,6 +5,10 @@ import { atomicWrite } from "./storage.js";
5
5
  import { ERROR_CODES, fail } from "./errors.js";
6
6
  import { normalizeWorkspaceId } from "./identifiers.js";
7
7
  import { inspectCommitRange, isCommitAncestor, repositoryState } from "./git-candidates.js";
8
+ import { inspectDetailedCommitRange } from "./delivery-git.js";
9
+ import { DELIVERY_DIAGNOSTIC_LIMITS, DELIVERY_EXPLAIN_CONTRACT_VERSION, DELIVERY_EXPLAIN_OPERATION, deliveryDiagnosticComplete, validateDeliveryExplainEnvelope, validateDeliveryFindings } from "./delivery-contracts.js";
10
+ import { createDeliveryPathRedactor } from "./delivery-redaction.js";
11
+ import { recommendDeliverySlices } from "./delivery-slices.js";
8
12
 
9
13
  const environmentPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
10
14
  const hashPattern = /^[0-9a-f]{40,64}$/;
@@ -12,6 +16,9 @@ const candidatePattern = /^CC-\d{6}$/;
12
16
  const timestamp = (value) => typeof value === "string" && !Number.isNaN(Date.parse(value)) && new Date(value).toISOString() === value;
13
17
  const maxEnvironments = 20;
14
18
  const maxCandidates = 10000;
19
+ const diagnosticCandidateLimit = DELIVERY_DIAGNOSTIC_LIMITS.commits;
20
+ const diagnosticCandidatePathLimit = DELIVERY_DIAGNOSTIC_LIMITS.paths;
21
+ const compareText = (left, right) => left < right ? -1 : left > right ? 1 : 0;
15
22
  const checkpointIntegrity = (checkpoint) => createHash("sha256").update(JSON.stringify({
16
23
  deployed_head: checkpoint.deployed_head,
17
24
  deployed_at: checkpoint.deployed_at,
@@ -111,6 +118,125 @@ export class DeliveryStore {
111
118
  return { workspace, environment, checkpoint, ...projection, ...(range ? { range } : {}) };
112
119
  }
113
120
 
121
+ explain(workspace, options = {}) {
122
+ workspace = this.assertWorkspace(workspace);
123
+ const findings = validateDeliveryFindings(options.findings).map((finding) => {
124
+ const affectedPaths = finding.affected_paths.map((item) => {
125
+ const normalized = item.replace(/^(?:\.\/)+/u, "");
126
+ if (path.posix.isAbsolute(normalized) || normalized.includes("\\") || normalized.split("/").some((segment) => !segment || segment === "." || segment === "..")) {
127
+ fail(ERROR_CODES.DELIVERY_INVALID_FINDINGS, "Affected paths must be repository-relative normalized paths", { id: finding.id });
128
+ }
129
+ return normalized;
130
+ });
131
+ if (new Set(affectedPaths).size !== affectedPaths.length) fail(ERROR_CODES.DELIVERY_INVALID_FINDINGS, "Affected paths must remain unique after normalization", { id: finding.id });
132
+ return { ...finding, affected_paths: affectedPaths.sort(compareText) };
133
+ });
134
+ const evidence = inspectDetailedCommitRange(this.context.storage.projectRoot, options.from, options.to);
135
+ const workspaceMode = this.context.storage.readWorkspace(workspace).data.mode || "standard";
136
+ const commitSet = new Set(evidence.commits.map(({ commit }) => commit));
137
+ const finalPathSet = new Set(evidence.paths.map(({ path: file }) => file));
138
+ const traceability = workspaceMode === "startup"
139
+ ? this.candidateTraceability(workspace, commitSet)
140
+ : { capability: "unavailable", candidates: [], direct_commits: [] };
141
+ const allPaths = [
142
+ ...evidence.paths.map(({ path: file }) => file),
143
+ ...evidence.lineage.flatMap(({ from_path: fromPath, to_path: toPath }) => [fromPath, toPath]),
144
+ ...findings.flatMap((finding) => finding.affected_paths),
145
+ ...traceability.candidates.flatMap((candidate) => candidate.paths),
146
+ ];
147
+ const redactor = createDeliveryPathRedactor(this.context.storage.config.delivery.secret_path_patterns, allPaths);
148
+ const limits = {
149
+ commits: { count: evidence.commit_count, limit: DELIVERY_DIAGNOSTIC_LIMITS.commits, truncated: evidence.commits_truncated },
150
+ paths: { count: evidence.path_count, limit: DELIVERY_DIAGNOSTIC_LIMITS.paths, truncated: evidence.paths_truncated },
151
+ provenance: { limit_per_path: DELIVERY_DIAGNOSTIC_LIMITS.provenance_commits_per_path, truncated: evidence.paths.some((item) => item.provenance_truncated) },
152
+ candidate_traceability: {
153
+ candidates_limit: diagnosticCandidateLimit,
154
+ paths_limit: diagnosticCandidatePathLimit,
155
+ candidates_truncated: traceability.candidates_truncated || evidence.commits_truncated || false,
156
+ paths_truncated: traceability.paths_truncated || false,
157
+ },
158
+ git_output: { bytes: evidence.git_output_bytes, limit: DELIVERY_DIAGNOSTIC_LIMITS.git_output_bytes, truncated: false },
159
+ };
160
+ const complete = deliveryDiagnosticComplete(limits);
161
+ const normalizedFindings = findings.map((finding) => {
162
+ const matchedPaths = finding.affected_paths.filter((file) => finalPathSet.has(file));
163
+ const unmatchedPaths = finding.affected_paths.filter((file) => !finalPathSet.has(file));
164
+ const normalized = {
165
+ ...finding,
166
+ summary: redactor.text(finding.summary),
167
+ affected_paths: finding.affected_paths.map(redactor.path),
168
+ ...(evidence.paths_truncated ? {} : {
169
+ matched_paths: matchedPaths.map(redactor.path),
170
+ unmatched_paths: unmatchedPaths.map(redactor.path),
171
+ }),
172
+ ...(finding.recommendation === undefined || !complete ? {} : { recommendation: redactor.text(finding.recommendation) }),
173
+ };
174
+ if (!complete) delete normalized.recommendation;
175
+ return normalized;
176
+ });
177
+ const candidates = traceability.candidates.map((candidate) => ({ ...candidate, paths: candidate.paths.map(redactor.path) }));
178
+ const redactedPaths = evidence.paths.map((item) => ({ ...item, path: redactor.path(item.path) }));
179
+ const candidateTraceability = { ...traceability, candidates };
180
+ const candidateSlice = complete ? recommendDeliverySlices({
181
+ findings: normalizedFindings,
182
+ paths: redactedPaths,
183
+ candidate_traceability: candidateTraceability,
184
+ }) : [];
185
+ const severity = { info: 0, warning: 0, error: 0 };
186
+ for (const finding of normalizedFindings) severity[finding.severity] += 1;
187
+ return validateDeliveryExplainEnvelope({
188
+ contract_version: DELIVERY_EXPLAIN_CONTRACT_VERSION,
189
+ operation: DELIVERY_EXPLAIN_OPERATION,
190
+ immutable_range: evidence.immutable_range,
191
+ limits,
192
+ summary: {
193
+ commits: evidence.commit_count,
194
+ paths: evidence.path_count,
195
+ findings: normalizedFindings.length,
196
+ severity,
197
+ candidate_attributed_commits: traceability.capability === "available" ? new Set(candidates.flatMap((candidate) => candidate.commits)).size : null,
198
+ direct_commits: traceability.capability === "available" ? traceability.direct_commits.length : null,
199
+ },
200
+ paths: redactedPaths,
201
+ lineage: evidence.lineage.map((item) => ({ ...item, from_path: redactor.path(item.from_path), to_path: redactor.path(item.to_path) })),
202
+ findings: normalizedFindings,
203
+ candidate_traceability: candidateTraceability,
204
+ candidate_slice: candidateSlice,
205
+ redactions: redactor.summary,
206
+ complete,
207
+ });
208
+ }
209
+
210
+ candidateTraceability(workspace, commitSet) {
211
+ const records = this.context.candidates().projectionRecords(workspace)
212
+ .filter((candidate) => candidate.status === "committed" && commitSet.has(candidate.commit_hash))
213
+ .sort((left, right) => left.candidate.localeCompare(right.candidate));
214
+ const included = records.slice(0, diagnosticCandidateLimit);
215
+ let remainingPaths = diagnosticCandidatePathLimit;
216
+ let pathsTruncated = false;
217
+ const candidates = included.map((candidate) => {
218
+ const selectedPaths = [...candidate.selected_paths].sort(compareText);
219
+ const paths = selectedPaths.slice(0, remainingPaths);
220
+ remainingPaths -= paths.length;
221
+ if (paths.length < selectedPaths.length) pathsTruncated = true;
222
+ return {
223
+ candidate: candidate.candidate,
224
+ strategy: candidate.strategy || "exact",
225
+ related_stages: candidate.related_stages || [],
226
+ commits: [candidate.commit_hash],
227
+ paths,
228
+ };
229
+ });
230
+ const attributed = new Set(records.map((candidate) => candidate.commit_hash));
231
+ return {
232
+ capability: "available",
233
+ candidates,
234
+ direct_commits: [...commitSet].filter((commit) => !attributed.has(commit)),
235
+ candidates_truncated: records.length > included.length,
236
+ paths_truncated: pathsTruncated,
237
+ };
238
+ }
239
+
114
240
  mark(workspace, environment, commit, confirmation) {
115
241
  workspace = this.assertWorkspace(workspace);
116
242
  environment = normalizeEnvironment(environment);
package/src/errors.js CHANGED
@@ -11,6 +11,8 @@ export const ERROR_CODES = Object.freeze({
11
11
  CANDIDATE_REF_RACE: "CANDIDATE_REF_RACE", CANDIDATE_COMMIT_FAILED: "CANDIDATE_COMMIT_FAILED",
12
12
  EXECUTION_REVISION_CONFLICT: "EXECUTION_REVISION_CONFLICT", EXECUTION_LIMIT_EXCEEDED: "EXECUTION_LIMIT_EXCEEDED",
13
13
  DELIVERY_INVALID_RANGE: "DELIVERY_INVALID_RANGE", DELIVERY_RANGE_TOO_LARGE: "DELIVERY_RANGE_TOO_LARGE",
14
+ DELIVERY_INVALID_FINDINGS: "DELIVERY_INVALID_FINDINGS", DELIVERY_DIAGNOSTIC_TOO_LARGE: "DELIVERY_DIAGNOSTIC_TOO_LARGE",
15
+ DELIVERY_COMMAND_PROTOCOL_MISMATCH: "DELIVERY_COMMAND_PROTOCOL_MISMATCH",
14
16
  });
15
17
 
16
18
  export class WorkContextError extends Error {
package/src/index.js CHANGED
@@ -14,4 +14,9 @@ export * from "./work-context-snapshot.js";
14
14
  export * from "./git-candidates.js";
15
15
  export * from "./candidates.js";
16
16
  export * from "./delivery.js";
17
+ export * from "./delivery-contracts.js";
18
+ export * from "./delivery-git.js";
19
+ export * from "./delivery-redaction.js";
20
+ export * from "./delivery-doctor.js";
21
+ export * from "./protocol.js";
17
22
  export * from "./capability-profiles.js";
@@ -1,6 +1,8 @@
1
+ import fs from "node:fs";
1
2
  import path from "node:path";
2
3
  import { fileURLToPath } from "node:url";
3
4
  import { WorkContext } from "./core.js";
5
+ import { WORK_CONTEXT_PROTOCOL, WORK_CONTEXT_PROTOCOL_DESCRIPTOR_HASH } from "./protocol.js";
4
6
  import { renderTitle } from "./title.js";
5
7
  export { readStagesSnapshot } from "./stages-snapshot.js";
6
8
 
@@ -20,3 +22,26 @@ export function titleFor(context, workspace, stage, sessionId, knownSession = nu
20
22
  return renderTitle({ workspace, stageTitle: stageMeta.title, stage, ordinal: current.ordinal, state: current.state, trackerLinks: primaryTrackerLinks, stageTrackerLinks, issuePrefix: context.storage.config.title?.issue_prefix || "short" });
21
23
  }
22
24
  export const packageRoot = () => path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
25
+
26
+ export function runtimeSelfReport(projectRoot) {
27
+ const root = packageRoot();
28
+ let manifest = {};
29
+ try { manifest = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")); } catch {}
30
+ const project = path.resolve(projectRoot);
31
+ const localRoots = [path.join(project, "node_modules"), path.join(project, ".opencode", "node_modules")];
32
+ const moduleOrigin = localRoots.some((candidate) => root === candidate || root.startsWith(`${candidate}${path.sep}`))
33
+ ? "project_local"
34
+ : root.endsWith(`${path.sep}opencode-work-context`) && root.includes(`${path.sep}.cache${path.sep}`)
35
+ ? "managed_cache"
36
+ : "package_source";
37
+ return {
38
+ evidence_kind: "self_reported",
39
+ package_name: manifest.name,
40
+ package_version: manifest.version,
41
+ module_origin: moduleOrigin,
42
+ protocol: {
43
+ ...WORK_CONTEXT_PROTOCOL,
44
+ descriptor_hash: WORK_CONTEXT_PROTOCOL_DESCRIPTOR_HASH,
45
+ },
46
+ };
47
+ }
@@ -0,0 +1,47 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ export const WORK_CONTEXT_PROTOCOL = Object.freeze({
4
+ schema: 1,
5
+ major: 1,
6
+ minor: 0,
7
+ });
8
+
9
+ export const WORK_CONTEXT_PROTOCOL_DESCRIPTOR = Object.freeze({
10
+ schema: WORK_CONTEXT_PROTOCOL.schema,
11
+ name: "opencode-work-context/wc",
12
+ protocol: Object.freeze({
13
+ major: WORK_CONTEXT_PROTOCOL.major,
14
+ minor: WORK_CONTEXT_PROTOCOL.minor,
15
+ }),
16
+ operations: Object.freeze(["delivery.doctor"]),
17
+ });
18
+
19
+ export const WORK_CONTEXT_PROTOCOL_DESCRIPTOR_BYTES = JSON.stringify(WORK_CONTEXT_PROTOCOL_DESCRIPTOR);
20
+ export const WORK_CONTEXT_PROTOCOL_DESCRIPTOR_HASH = createHash("sha256")
21
+ .update(WORK_CONTEXT_PROTOCOL_DESCRIPTOR_BYTES)
22
+ .digest("hex");
23
+
24
+ export const WORK_CONTEXT_PROTOCOL_MARKER = `<!-- opencode-work-context-protocol: ${JSON.stringify({
25
+ schema: WORK_CONTEXT_PROTOCOL.schema,
26
+ major: WORK_CONTEXT_PROTOCOL.major,
27
+ minor: WORK_CONTEXT_PROTOCOL.minor,
28
+ descriptor_hash: `sha256:${WORK_CONTEXT_PROTOCOL_DESCRIPTOR_HASH}`,
29
+ })} -->`;
30
+
31
+ export function parseWorkContextProtocolMarker(content) {
32
+ if (typeof content !== "string") return null;
33
+ const matches = [...content.matchAll(/<!-- opencode-work-context-protocol: (\{[^\r\n]*\}) -->/g)];
34
+ if (matches.length !== 1) return null;
35
+ try {
36
+ const marker = JSON.parse(matches[0][1]);
37
+ if (!marker || typeof marker !== "object" || Array.isArray(marker)
38
+ || !Number.isInteger(marker.schema) || marker.schema < 1
39
+ || !Number.isInteger(marker.major) || marker.major < 0
40
+ || !Number.isInteger(marker.minor) || marker.minor < 0
41
+ || typeof marker.descriptor_hash !== "string"
42
+ || !/^sha256:[a-f0-9]{64}$/.test(marker.descriptor_hash)) return null;
43
+ return marker;
44
+ } catch {
45
+ return null;
46
+ }
47
+ }