geloforge 0.0.0-stage → 0.6.0
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/LICENSE +21 -0
- package/README.md +140 -2
- package/THIRD_PARTY_NOTICES.md +33 -0
- package/VERSION +1 -0
- package/core/adopt-project.mjs +458 -0
- package/core/checkpoint.mjs +438 -0
- package/core/codebase-map.mjs +886 -0
- package/core/compatibility.json +16 -0
- package/core/compatibility.mjs +123 -0
- package/core/context-compiler.mjs +1315 -0
- package/core/evidence-capture.mjs +326 -0
- package/core/git-utils.mjs +167 -0
- package/core/handoff.mjs +815 -0
- package/core/json-schema-lite.mjs +119 -0
- package/core/mcp-init.mjs +248 -0
- package/core/mcp-server.mjs +915 -0
- package/core/path-safety.mjs +508 -0
- package/core/project-locator.mjs +231 -0
- package/core/project-lock.mjs +438 -0
- package/core/project-status.mjs +609 -0
- package/core/project-validator.mjs +544 -0
- package/core/skills-history.mjs +572 -0
- package/core/skills-lifecycle.mjs +2225 -0
- package/core/skills-lint.mjs +365 -0
- package/core/skills.mjs +1449 -0
- package/core/task-manager.mjs +1042 -0
- package/core/template-utils.mjs +190 -0
- package/core/text-utils.mjs +48 -0
- package/core/verify-task.mjs +48 -0
- package/core/yaml-subset.mjs +572 -0
- package/package.json +47 -4
- package/policies/approval-boundaries.md +42 -0
- package/policies/memory-policy.md +53 -0
- package/policies/token-efficiency.md +30 -0
- package/schemas/README.md +43 -0
- package/schemas/adr.schema.json +64 -0
- package/schemas/agent-handoff.schema.json +139 -0
- package/schemas/approval-record.schema.json +101 -0
- package/schemas/conflict-record.schema.json +60 -0
- package/schemas/context-pack-manifest.schema.json +194 -0
- package/schemas/evidence-manifest.schema.json +83 -0
- package/schemas/incident-record.schema.json +53 -0
- package/schemas/project-manifest.schema.json +90 -0
- package/schemas/project-state.schema.json +64 -0
- package/schemas/recovery-checkpoint.schema.json +49 -0
- package/schemas/research-record.schema.json +76 -0
- package/schemas/task-contract.schema.json +95 -0
- package/scripts/bootstrap-project.mjs +357 -0
- package/scripts/geloforge.mjs +2291 -0
- package/templates/profiles/README.md +19 -0
- package/templates/profiles/ai-system/brain/profile.md +21 -0
- package/templates/profiles/ai-system/gitignore.append +5 -0
- package/templates/profiles/ai-system/profile.json +6 -0
- package/templates/profiles/automation/brain/profile.md +19 -0
- package/templates/profiles/automation/gitignore.append +5 -0
- package/templates/profiles/automation/profile.json +6 -0
- package/templates/profiles/desktop/brain/profile.md +21 -0
- package/templates/profiles/desktop/gitignore.append +7 -0
- package/templates/profiles/desktop/profile.json +6 -0
- package/templates/profiles/mobile/brain/profile.md +20 -0
- package/templates/profiles/mobile/gitignore.append +8 -0
- package/templates/profiles/mobile/profile.json +6 -0
- package/templates/profiles/web/brain/profile.md +21 -0
- package/templates/profiles/web/gitignore.append +6 -0
- package/templates/profiles/web/profile.json +6 -0
- package/templates/project-starter/AGENTS.md +26 -0
- package/templates/project-starter/GEMINI.md +16 -0
- package/templates/project-starter/README.md +26 -0
- package/templates/project-starter/brain/INDEX.md +40 -0
- package/templates/project-starter/brain/architecture/overview.md +30 -0
- package/templates/project-starter/brain/decisions/.gitkeep +0 -0
- package/templates/project-starter/brain/manifest.yaml +36 -0
- package/templates/project-starter/brain/requirements/constraints.md +29 -0
- package/templates/project-starter/brain/requirements/prd.md +37 -0
- package/templates/project-starter/brain/state/current.yaml +19 -0
- package/templates/project-starter/gitignore.template +25 -0
- package/templates/project-starter/src/.gitkeep +0 -0
- package/templates/project-starter/tasks/.gitkeep +0 -0
- package/templates/project-starter/tests/.gitkeep +0 -0
package/core/handoff.mjs
ADDED
|
@@ -0,0 +1,815 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cross-Agent File-Based Handoff Engine for GeloForge (v0.3 Stage 3).
|
|
3
|
+
* Creates and inspects schema-valid HANDOFF-NNNN YAML + Markdown summaries across AI tools
|
|
4
|
+
* and agent roles while reading Second Brain contracts read-only, strictly separating
|
|
5
|
+
* verified EVID-* test evidence from unverified agent claims, and refusing secret leaks.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import fs from "node:fs";
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
import { parseYaml, extractFrontmatter, serializeYaml } from "./yaml-subset.mjs";
|
|
12
|
+
import { validateAgainstSchema } from "./json-schema-lite.mjs";
|
|
13
|
+
import {
|
|
14
|
+
assertSafeWithinRoot,
|
|
15
|
+
atomicWriteFile,
|
|
16
|
+
deriveSlug,
|
|
17
|
+
hasSecretContent,
|
|
18
|
+
isForbiddenSecretPath,
|
|
19
|
+
validateOutputFilePath,
|
|
20
|
+
walkNonSymlinkFiles,
|
|
21
|
+
} from "./path-safety.mjs";
|
|
22
|
+
import { getGitRepoInfo, getGitStatusScoped } from "./git-utils.mjs";
|
|
23
|
+
import { checkRecordSchemaVersion, loadCompatibilityConfig } from "./compatibility.mjs";
|
|
24
|
+
import { resolveProjectPaths } from "./project-locator.mjs";
|
|
25
|
+
|
|
26
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
27
|
+
const __dirname = path.dirname(__filename);
|
|
28
|
+
const DEFAULT_HARNESS_DIR = path.resolve(__dirname, "..");
|
|
29
|
+
|
|
30
|
+
const ALLOWED_ROLES = new Set([
|
|
31
|
+
"orchestrator",
|
|
32
|
+
"researcher",
|
|
33
|
+
"software-architect",
|
|
34
|
+
"developer",
|
|
35
|
+
"qa-security-reviewer",
|
|
36
|
+
]);
|
|
37
|
+
|
|
38
|
+
const ALLOWED_HANDOFF_STATUSES = new Set(["draft", "submitted", "acknowledged", "rejected", "superseded"]);
|
|
39
|
+
const MAX_RECORD_BYTES = 512 * 1024;
|
|
40
|
+
const VERIFICATION_CLAIM_REGEX =
|
|
41
|
+
/\b(?:tests?\s+(?:are\s+)?pass(?:ed|ing)?|all\s+checks?\s+(?:are\s+)?pass(?:ed|ing)?|checks?\s+pass(?:ed|ing)?|build\s+(?:passed|succeeded|green)|(?:0|zero)\s+(?:test\s+)?failures?|verified\s+pass(?:ing)?|suite\s+pass(?:ed|ing)?|ci\s+(?:green|pass(?:ed|ing)?)|coverage\s+\d+%)\b/i;
|
|
42
|
+
|
|
43
|
+
function loadSchema(harnessDir, name) {
|
|
44
|
+
return JSON.parse(fs.readFileSync(path.join(harnessDir, "schemas", name), "utf8"));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function readSafeProjectText(projectDir, relPath, warnings) {
|
|
48
|
+
const norm = relPath.replace(/\\/g, "/");
|
|
49
|
+
if (isForbiddenSecretPath(norm)) {
|
|
50
|
+
warnings.push(`Blocked forbidden secret path: ${norm}`);
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
let resolved;
|
|
54
|
+
try {
|
|
55
|
+
resolved = assertSafeWithinRoot(projectDir, norm);
|
|
56
|
+
} catch (err) {
|
|
57
|
+
warnings.push(`Blocked unsafe path "${norm}": ${err.message}`);
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
if (!fs.existsSync(resolved)) {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
const stat = fs.lstatSync(resolved);
|
|
64
|
+
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
65
|
+
warnings.push(`Skipped non-regular or symlink file: ${norm}`);
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
if (stat.size > MAX_RECORD_BYTES) {
|
|
69
|
+
warnings.push(`Skipped oversized file (> ${MAX_RECORD_BYTES} bytes): ${norm}`);
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
const text = fs.readFileSync(resolved, "utf8");
|
|
73
|
+
if (hasSecretContent(text)) {
|
|
74
|
+
warnings.push(`Blocked file with credential-like content: ${norm}`);
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
return { resolved, text };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function collectGitState(projectDir, warnings) {
|
|
81
|
+
const gs = getGitStatusScoped(projectDir, warnings);
|
|
82
|
+
if (!gs.available) {
|
|
83
|
+
return { available: false, branch: null, head: null, dirty: false, changed_files: [] };
|
|
84
|
+
}
|
|
85
|
+
if (gs.changedFiles.length > 100) {
|
|
86
|
+
warnings.push(`Truncated git_state.changed_files from ${gs.changedFiles.length} to 100 entries.`);
|
|
87
|
+
}
|
|
88
|
+
return {
|
|
89
|
+
available: true,
|
|
90
|
+
branch: gs.branch,
|
|
91
|
+
head: gs.unborn ? "unborn-head" : gs.head,
|
|
92
|
+
dirty: gs.dirty,
|
|
93
|
+
changed_files: gs.changedFiles.slice(0, 100),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function serializeHandoffYaml(record) {
|
|
98
|
+
return serializeYaml(record);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function renderHandoffMarkdown(record, inspectMeta = null) {
|
|
102
|
+
const lines = [
|
|
103
|
+
`# Agent Handoff: ${record.id}`,
|
|
104
|
+
"",
|
|
105
|
+
`- **Schema Version:** \`${record.schema_version}\``,
|
|
106
|
+
`- **Task:** ${record.task_id ? `\`${record.task_id}\`` : "None (project-level handoff)"}`,
|
|
107
|
+
`- **Transfer:** \`${record.from_role}\`${record.from_tool ? ` (${record.from_tool})` : ""} -> \`${record.to_role}\`${record.to_tool ? ` (${record.to_tool})` : ""}`,
|
|
108
|
+
`- **Status / Authority:** \`${record.status}\` / \`${record.authority_level}\` (${record.memory_layer})`,
|
|
109
|
+
`- **Created At:** \`${record.created_at}\``,
|
|
110
|
+
`- **Summary:** ${record.summary}`,
|
|
111
|
+
];
|
|
112
|
+
|
|
113
|
+
if (record.git_state) {
|
|
114
|
+
const g = record.git_state;
|
|
115
|
+
lines.push(
|
|
116
|
+
"",
|
|
117
|
+
"## Git State",
|
|
118
|
+
`- **Git Available:** ${g.available ? "Yes" : "No"}`,
|
|
119
|
+
...(g.available
|
|
120
|
+
? [
|
|
121
|
+
`- **Branch:** \`${g.branch || "detached"}\` | **HEAD:** \`${g.head || "unknown"}\` | **Dirty:** ${g.dirty ? "Yes" : "No"}`,
|
|
122
|
+
...(g.changed_files.length > 0
|
|
123
|
+
? g.changed_files.map((f) => ` - \`${f}\``)
|
|
124
|
+
: [" - *(no changed files)*"]),
|
|
125
|
+
]
|
|
126
|
+
: [])
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (inspectMeta && inspectMeta.gitDrift && inspectMeta.gitDrift.changed) {
|
|
131
|
+
lines.push(
|
|
132
|
+
"",
|
|
133
|
+
`> **Git Revision Drift:** Current repository HEAD is \`${inspectMeta.gitDrift.currentHead}\`, while handoff recorded \`${inspectMeta.gitDrift.recordedHead}\`.`
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
lines.push("", "## Requirements & Approved Decisions (Authoritative References)");
|
|
138
|
+
const reqs = record.relevant_requirements || [];
|
|
139
|
+
const decs = record.relevant_decisions || [];
|
|
140
|
+
if (reqs.length === 0 && decs.length === 0) {
|
|
141
|
+
lines.push("- (none linked)");
|
|
142
|
+
} else {
|
|
143
|
+
for (const r of reqs) lines.push(`- Requirement: \`${r}\``);
|
|
144
|
+
for (const d of decs) lines.push(`- Decision: \`${d}\``);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
lines.push("", "## Completed Work");
|
|
148
|
+
if (record.completed_items.length === 0) lines.push("- (none)");
|
|
149
|
+
else for (const item of record.completed_items) lines.push(`- ${item}`);
|
|
150
|
+
|
|
151
|
+
lines.push("", "## Verified Evidence (Backed by Audited EVID-* Records)");
|
|
152
|
+
const verifiedEv = record.verified_evidence || [];
|
|
153
|
+
if (verifiedEv.length === 0) {
|
|
154
|
+
lines.push("- *(None verified — do not assume tests/checks passed without inspecting or running them.)*");
|
|
155
|
+
} else {
|
|
156
|
+
for (const ev of verifiedEv) {
|
|
157
|
+
lines.push(
|
|
158
|
+
`- **\`${ev.id}\`** (\`${ev.path}\`, verified_by=\`${ev.verified_by || "unassigned"}\`) — ${ev.checks_summary}`
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
lines.push("", "## Unverified Agent Claims (Non-Authoritative — Must Be Verified)");
|
|
164
|
+
const claims = record.unverified_claims || [];
|
|
165
|
+
if (claims.length === 0) lines.push("- (none)");
|
|
166
|
+
else for (const c of claims) lines.push(`- [UNVERIFIED] ${c}`);
|
|
167
|
+
|
|
168
|
+
lines.push("", "## Remaining Work & Blockers");
|
|
169
|
+
lines.push("### Open Items");
|
|
170
|
+
if (record.open_items.length === 0) lines.push("- (none)");
|
|
171
|
+
else for (const item of record.open_items) lines.push(`- ${item}`);
|
|
172
|
+
|
|
173
|
+
if ((record.blockers || []).length > 0) {
|
|
174
|
+
lines.push("", "### Blockers");
|
|
175
|
+
for (const b of record.blockers) lines.push(`- ${b}`);
|
|
176
|
+
}
|
|
177
|
+
if ((record.open_questions || []).length > 0) {
|
|
178
|
+
lines.push("", "### Open Questions");
|
|
179
|
+
for (const q of record.open_questions) lines.push(`- ${q}`);
|
|
180
|
+
}
|
|
181
|
+
if (record.unresolved_risks.length > 0) {
|
|
182
|
+
lines.push("", "### Unresolved Risks");
|
|
183
|
+
for (const r of record.unresolved_risks) lines.push(`- ${r}`);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
lines.push("", "## Conflicts & Contradiction Warnings");
|
|
187
|
+
const hasConf = record.conflicts_detected.length > 0 || (record.contradiction_warnings || []).length > 0;
|
|
188
|
+
if (!hasConf) {
|
|
189
|
+
lines.push("- (none)");
|
|
190
|
+
} else {
|
|
191
|
+
for (const cid of record.conflicts_detected) lines.push(`- Open Conflict: \`${cid}\``);
|
|
192
|
+
for (const cw of record.contradiction_warnings || []) lines.push(`- [WARNING] ${cw}`);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
lines.push("", "## Recommended Next Action", `- ${record.recommended_next_action}`);
|
|
196
|
+
return `${lines.join("\n")}\n`;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function normalizeStringList(raw, fieldName) {
|
|
200
|
+
if (raw === undefined || raw === null) return [];
|
|
201
|
+
const arr = Array.isArray(raw) ? raw : [raw];
|
|
202
|
+
const out = [];
|
|
203
|
+
for (const item of arr) {
|
|
204
|
+
if (typeof item !== "string" || item.trim().length === 0) {
|
|
205
|
+
throw new Error(`Invalid empty entry in ${fieldName}.`);
|
|
206
|
+
}
|
|
207
|
+
const trimmed = item.trim();
|
|
208
|
+
if (hasSecretContent(trimmed)) {
|
|
209
|
+
throw new Error(`Refusing to write handoff containing credential-like content in ${fieldName}.`);
|
|
210
|
+
}
|
|
211
|
+
out.push(trimmed);
|
|
212
|
+
}
|
|
213
|
+
return out;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function loadProjectSnapshot(projectDir, harnessDir, warnings) {
|
|
217
|
+
const manifestRead = readSafeProjectText(projectDir, "brain/manifest.yaml", warnings);
|
|
218
|
+
if (!manifestRead) {
|
|
219
|
+
throw new Error(`Missing or unreadable brain/manifest.yaml in ${projectDir}`);
|
|
220
|
+
}
|
|
221
|
+
const manifest = parseYaml(manifestRead.text, "brain/manifest.yaml");
|
|
222
|
+
const manifestRes = validateAgainstSchema(manifest, loadSchema(harnessDir, "project-manifest.schema.json"));
|
|
223
|
+
if (!manifestRes.valid) {
|
|
224
|
+
throw new Error(`Invalid brain/manifest.yaml: ${manifestRes.errors.join("; ")}`);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const projectPaths = resolveProjectPaths(manifest);
|
|
228
|
+
|
|
229
|
+
const stateRead = readSafeProjectText(projectDir, projectPaths.state, warnings);
|
|
230
|
+
if (!stateRead) {
|
|
231
|
+
throw new Error(`Missing or unreadable ${projectPaths.state} in ${projectDir}`);
|
|
232
|
+
}
|
|
233
|
+
const state = parseYaml(stateRead.text, projectPaths.state);
|
|
234
|
+
const stateRes = validateAgainstSchema(state, loadSchema(harnessDir, "project-state.schema.json"));
|
|
235
|
+
if (!stateRes.valid) {
|
|
236
|
+
throw new Error(`Invalid ${projectPaths.state}: ${stateRes.errors.join("; ")}`);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const requirements = [];
|
|
240
|
+
for (const reqFile of walkNonSymlinkFiles(projectDir, path.join(projectDir, "brain", "requirements"), (p) => p.endsWith(".md"), warnings)) {
|
|
241
|
+
requirements.push(path.relative(projectDir, reqFile).replace(/\\/g, "/"));
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const scanTypedRecords = ({ relDir, filenameRegex, parser, schemaName, label }) => {
|
|
245
|
+
const out = [];
|
|
246
|
+
const schema = loadSchema(harnessDir, schemaName);
|
|
247
|
+
const files = walkNonSymlinkFiles(
|
|
248
|
+
projectDir,
|
|
249
|
+
path.join(projectDir, relDir),
|
|
250
|
+
(p) => filenameRegex.test(path.basename(p)),
|
|
251
|
+
warnings
|
|
252
|
+
);
|
|
253
|
+
for (const file of files) {
|
|
254
|
+
const rel = path.relative(projectDir, file).replace(/\\/g, "/");
|
|
255
|
+
const r = readSafeProjectText(projectDir, rel, warnings);
|
|
256
|
+
if (!r) continue;
|
|
257
|
+
try {
|
|
258
|
+
const data = parser(r.text, rel);
|
|
259
|
+
const v = validateAgainstSchema(data, schema);
|
|
260
|
+
if (v.valid) {
|
|
261
|
+
out.push({ rel, data });
|
|
262
|
+
} else {
|
|
263
|
+
warnings.push(`Skipped invalid ${label} ${rel}: ${v.errors.join("; ")}`);
|
|
264
|
+
}
|
|
265
|
+
} catch (err) {
|
|
266
|
+
warnings.push(`Skipped malformed ${label} ${rel}: ${err.message}`);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return out;
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
const decisions = scanTypedRecords({
|
|
273
|
+
relDir: projectPaths.decisions_dir,
|
|
274
|
+
filenameRegex: /^ADR-\d{4}.*\.md$/i,
|
|
275
|
+
parser: extractFrontmatter,
|
|
276
|
+
schemaName: "adr.schema.json",
|
|
277
|
+
label: "ADR",
|
|
278
|
+
});
|
|
279
|
+
const tasks = scanTypedRecords({
|
|
280
|
+
relDir: projectPaths.tasks_dir,
|
|
281
|
+
filenameRegex: /^TASK-\d{4}.*\.ya?ml$/i,
|
|
282
|
+
parser: parseYaml,
|
|
283
|
+
schemaName: "task-contract.schema.json",
|
|
284
|
+
label: "TASK",
|
|
285
|
+
});
|
|
286
|
+
const evidences = scanTypedRecords({
|
|
287
|
+
relDir: projectPaths.evidence_dir,
|
|
288
|
+
filenameRegex: /^EVID-\d{4}.*\.ya?ml$/i,
|
|
289
|
+
parser: parseYaml,
|
|
290
|
+
schemaName: "evidence-manifest.schema.json",
|
|
291
|
+
label: "EVID",
|
|
292
|
+
});
|
|
293
|
+
const conflicts = scanTypedRecords({
|
|
294
|
+
relDir: projectPaths.conflicts_dir,
|
|
295
|
+
filenameRegex: /^CONF-\d{4}.*\.ya?ml$/i,
|
|
296
|
+
parser: parseYaml,
|
|
297
|
+
schemaName: "conflict-record.schema.json",
|
|
298
|
+
label: "CONF",
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
const existingHandoffs = [];
|
|
302
|
+
for (const dirName of Array.from(new Set([projectPaths.handoffs_dir, projectPaths.tasks_dir]))) {
|
|
303
|
+
for (const hf of walkNonSymlinkFiles(projectDir, path.join(projectDir, dirName), (p) => /^HANDOFF-\d{4}.*\.ya?ml$/i.test(path.basename(p)), warnings)) {
|
|
304
|
+
const rel = path.relative(projectDir, hf).replace(/\\/g, "/");
|
|
305
|
+
const r = readSafeProjectText(projectDir, rel, warnings);
|
|
306
|
+
if (!r) continue;
|
|
307
|
+
try {
|
|
308
|
+
const data = parseYaml(r.text, rel);
|
|
309
|
+
if (data && typeof data.id === "string") {
|
|
310
|
+
existingHandoffs.push({ rel, id: data.id, data });
|
|
311
|
+
}
|
|
312
|
+
} catch {
|
|
313
|
+
const idMatch = path.basename(rel).match(/^(HANDOFF-\d{4})/i);
|
|
314
|
+
if (idMatch) existingHandoffs.push({ rel, id: idMatch[1].toUpperCase(), data: null });
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
return { manifest, state, projectPaths, requirements, decisions, tasks, evidences, conflicts, existingHandoffs };
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function summarizeEvidence(ev) {
|
|
323
|
+
const checks = Array.isArray(ev.data.checks) ? ev.data.checks : [];
|
|
324
|
+
const passed = checks.filter((c) => c.result === "passed").length;
|
|
325
|
+
const failed = checks.filter((c) => c.result === "failed").length;
|
|
326
|
+
const blocked = checks.filter((c) => c.result === "blocked").length;
|
|
327
|
+
const other = checks.length - passed - failed - blocked;
|
|
328
|
+
const verifiedStatus =
|
|
329
|
+
ev.data.status === "verified" && passed > 0 && failed === 0 && blocked === 0 && !ev.data.is_example;
|
|
330
|
+
return {
|
|
331
|
+
verified: verifiedStatus,
|
|
332
|
+
failedCount: failed,
|
|
333
|
+
blockedCount: blocked,
|
|
334
|
+
passedCount: passed,
|
|
335
|
+
summary: `${passed} passed, ${failed} failed, ${blocked} blocked, ${other} other (status=${ev.data.status})`,
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
export function createHandoff(options = {}) {
|
|
340
|
+
const harnessDir = path.resolve(options.harnessDir || DEFAULT_HARNESS_DIR);
|
|
341
|
+
const workspaceRoot = path.resolve(options.workspaceRoot || path.resolve(harnessDir, ".."));
|
|
342
|
+
|
|
343
|
+
if (typeof options.projectDir !== "string" || options.projectDir.trim().length === 0) {
|
|
344
|
+
throw new Error("Missing required project directory (--project <dir>).");
|
|
345
|
+
}
|
|
346
|
+
const projectDir = path.resolve(options.projectDir);
|
|
347
|
+
if (!fs.existsSync(projectDir)) {
|
|
348
|
+
throw new Error(`Project directory does not exist: ${projectDir}`);
|
|
349
|
+
}
|
|
350
|
+
const rootStat = fs.lstatSync(projectDir);
|
|
351
|
+
if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {
|
|
352
|
+
throw new Error(`Project root must be a real non-symlink directory: ${projectDir}`);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const fromRole = options.fromRole || "developer";
|
|
356
|
+
const toRole = options.toRole || "qa-security-reviewer";
|
|
357
|
+
if (!ALLOWED_ROLES.has(fromRole)) {
|
|
358
|
+
throw new Error(`Invalid --from-role "${fromRole}". Allowed: ${Array.from(ALLOWED_ROLES).join(", ")}`);
|
|
359
|
+
}
|
|
360
|
+
if (!ALLOWED_ROLES.has(toRole)) {
|
|
361
|
+
throw new Error(`Invalid --to-role "${toRole}". Allowed: ${Array.from(ALLOWED_ROLES).join(", ")}`);
|
|
362
|
+
}
|
|
363
|
+
const status = options.status || "submitted";
|
|
364
|
+
if (!ALLOWED_HANDOFF_STATUSES.has(status)) {
|
|
365
|
+
throw new Error(`Invalid handoff status "${status}".`);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
const fromTool = options.fromTool ? String(options.fromTool).trim() : null;
|
|
369
|
+
const toTool = options.toTool ? String(options.toTool).trim() : null;
|
|
370
|
+
if ((fromTool && hasSecretContent(fromTool)) || (toTool && hasSecretContent(toTool))) {
|
|
371
|
+
throw new Error("Refusing to write handoff containing credential-like content in tool metadata.");
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const warnings = [];
|
|
375
|
+
const contradictionWarnings = [];
|
|
376
|
+
const snap = loadProjectSnapshot(projectDir, harnessDir, warnings);
|
|
377
|
+
|
|
378
|
+
// Determine task linkage
|
|
379
|
+
const taskId = options.taskId ? options.taskId.trim() : snap.state.active_tasks?.[0] || null;
|
|
380
|
+
if (taskId !== null && !/^TASK-\d{4}$/.test(taskId)) {
|
|
381
|
+
throw new Error(`Invalid task ID "${taskId}". Expected TASK-NNNN.`);
|
|
382
|
+
}
|
|
383
|
+
let targetTask = null;
|
|
384
|
+
if (taskId) {
|
|
385
|
+
targetTask = snap.tasks.find((t) => t.data.id === taskId) || null;
|
|
386
|
+
if (!targetTask) {
|
|
387
|
+
throw new Error(`Task "${taskId}" was not found or failed validation in ${projectDir}.`);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// Assign deterministic non-colliding ID
|
|
392
|
+
const usedIds = new Set(snap.existingHandoffs.map((h) => h.id));
|
|
393
|
+
let handoffId = options.id ? options.id.trim().toUpperCase() : null;
|
|
394
|
+
if (handoffId) {
|
|
395
|
+
if (!/^HANDOFF-\d{4}$/.test(handoffId)) {
|
|
396
|
+
throw new Error(`Invalid handoff ID "${handoffId}". Expected format HANDOFF-NNNN.`);
|
|
397
|
+
}
|
|
398
|
+
if (usedIds.has(handoffId)) {
|
|
399
|
+
throw new Error(`Duplicate handoff ID "${handoffId}" already exists in project.`);
|
|
400
|
+
}
|
|
401
|
+
} else {
|
|
402
|
+
let maxNum = 0;
|
|
403
|
+
for (const existing of usedIds) {
|
|
404
|
+
const m = existing.match(/^HANDOFF-(\d{4})$/);
|
|
405
|
+
if (m) maxNum = Math.max(maxNum, Number.parseInt(m[1], 10));
|
|
406
|
+
}
|
|
407
|
+
handoffId = `HANDOFF-${String(maxNum + 1).padStart(4, "0")}`;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// Validate caller-supplied lists (never allow secret leaks)
|
|
411
|
+
const completedItems = normalizeStringList(options.completedItems, "completed_items");
|
|
412
|
+
const openItems = normalizeStringList(options.openItems, "open_items");
|
|
413
|
+
const unverifiedClaims = normalizeStringList(options.unverifiedClaims, "unverified_claims");
|
|
414
|
+
const blockers = normalizeStringList(options.blockers, "blockers");
|
|
415
|
+
const openQuestions = normalizeStringList(options.openQuestions, "open_questions");
|
|
416
|
+
const unresolvedRisks = normalizeStringList(options.unresolvedRisks, "unresolved_risks");
|
|
417
|
+
|
|
418
|
+
const summaryRaw =
|
|
419
|
+
typeof options.summary === "string" && options.summary.trim().length > 0
|
|
420
|
+
? options.summary.trim()
|
|
421
|
+
: targetTask
|
|
422
|
+
? `Cross-agent handoff for ${taskId} (${targetTask.data.title}) from ${fromRole} to ${toRole}.`
|
|
423
|
+
: `Project handoff for ${snap.manifest.name} from ${fromRole} to ${toRole}.`;
|
|
424
|
+
if (hasSecretContent(summaryRaw)) {
|
|
425
|
+
throw new Error("Refusing to write handoff containing credential-like content in summary.");
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
const nextActionRaw =
|
|
429
|
+
typeof options.nextAction === "string" && options.nextAction.trim().length > 0
|
|
430
|
+
? options.nextAction.trim()
|
|
431
|
+
: targetTask
|
|
432
|
+
? `Review ${taskId} acceptance criteria, verified evidence, and open items before continuing.`
|
|
433
|
+
: `Review current operational state and prioritize remaining tasks.`;
|
|
434
|
+
if (hasSecretContent(nextActionRaw)) {
|
|
435
|
+
throw new Error("Refusing to write handoff containing credential-like content in recommended_next_action.");
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
const contextPackRef = options.contextPackRef ? options.contextPackRef.trim() : null;
|
|
439
|
+
if (contextPackRef !== null && !/^CPACK-\d{4}$/.test(contextPackRef)) {
|
|
440
|
+
throw new Error(`Invalid --context-pack-ref "${contextPackRef}". Expected CPACK-NNNN.`);
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// Artifacts (if explicitly provided; never fabricate)
|
|
444
|
+
const artifactsProduced = [];
|
|
445
|
+
for (const art of options.artifactsProduced || []) {
|
|
446
|
+
if (!art || typeof art.path !== "string") continue;
|
|
447
|
+
if (isForbiddenSecretPath(art.path)) {
|
|
448
|
+
throw new Error(`Refusing secret artifact path in handoff: ${art.path}`);
|
|
449
|
+
}
|
|
450
|
+
assertSafeWithinRoot(projectDir, art.path);
|
|
451
|
+
const purpose = String(art.purpose || "Artifact produced during task execution").trim();
|
|
452
|
+
if (hasSecretContent(purpose)) {
|
|
453
|
+
throw new Error(`Refusing credential-like content in artifact purpose for ${art.path}`);
|
|
454
|
+
}
|
|
455
|
+
artifactsProduced.push({
|
|
456
|
+
path: art.path.replace(/\\/g, "/"),
|
|
457
|
+
purpose,
|
|
458
|
+
status: ["draft", "proposed", "verified", "rejected"].includes(art.status) ? art.status : "draft",
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
// Read-only approved decisions & unapproved ADR alerts
|
|
463
|
+
const relevantDecisions = [];
|
|
464
|
+
for (const adr of snap.decisions) {
|
|
465
|
+
if (adr.data.is_example) continue;
|
|
466
|
+
if (adr.data.status === "accepted" && (!adr.data.approved_by || !adr.data.decided_at)) {
|
|
467
|
+
contradictionWarnings.push(
|
|
468
|
+
`Untrusted ADR ${adr.data.id} (${adr.rel}) has status "accepted" without approved_by/decided_at; excluded from relevant_decisions.`
|
|
469
|
+
);
|
|
470
|
+
continue;
|
|
471
|
+
}
|
|
472
|
+
if (adr.data.status === "accepted") {
|
|
473
|
+
relevantDecisions.push(adr.data.id);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
relevantDecisions.sort();
|
|
477
|
+
|
|
478
|
+
// Open conflicts
|
|
479
|
+
const openConflicts = snap.conflicts
|
|
480
|
+
.filter((c) => !c.data.is_example && (c.data.status === "open" || c.data.status === "under_review"))
|
|
481
|
+
.map((c) => c.data.id)
|
|
482
|
+
.sort();
|
|
483
|
+
if (openConflicts.length > 0) {
|
|
484
|
+
contradictionWarnings.push(
|
|
485
|
+
`Project has ${openConflicts.length} unresolved conflict(s): ${openConflicts.join(", ")}.`
|
|
486
|
+
);
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// Gather & strictly verify evidence vs. unverified claims
|
|
490
|
+
const requestedEvidenceIds = normalizeStringList(options.evidenceRefs, "evidence_refs");
|
|
491
|
+
const candidateEvidenceIds = new Set(requestedEvidenceIds);
|
|
492
|
+
if (targetTask) {
|
|
493
|
+
for (const evId of targetTask.data.evidence_refs || []) candidateEvidenceIds.add(evId);
|
|
494
|
+
}
|
|
495
|
+
for (const ev of snap.evidences) {
|
|
496
|
+
if (!ev.data.is_example && taskId && ev.data.task_id === taskId) {
|
|
497
|
+
candidateEvidenceIds.add(ev.data.id);
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
const evidenceById = new Map(snap.evidences.map((e) => [e.data.id, e]));
|
|
502
|
+
const evidenceRefs = [];
|
|
503
|
+
const verifiedEvidence = [];
|
|
504
|
+
let failedEvidenceDetected = false;
|
|
505
|
+
|
|
506
|
+
for (const evId of Array.from(candidateEvidenceIds).sort()) {
|
|
507
|
+
const ev = evidenceById.get(evId);
|
|
508
|
+
if (!ev) {
|
|
509
|
+
contradictionWarnings.push(
|
|
510
|
+
`Referenced evidence ${evId} does not exist or failed schema validation; excluded from evidence_refs and verified_evidence.`
|
|
511
|
+
);
|
|
512
|
+
unverifiedClaims.push(`Claimed evidence ${evId} not found in audited evidence/*.yaml`);
|
|
513
|
+
continue;
|
|
514
|
+
}
|
|
515
|
+
if (ev.data.is_example) {
|
|
516
|
+
contradictionWarnings.push(`Canonical example fixture ${evId} cannot be used as real task evidence.`);
|
|
517
|
+
continue;
|
|
518
|
+
}
|
|
519
|
+
evidenceRefs.push(ev.data.id);
|
|
520
|
+
const summaryInfo = summarizeEvidence(ev);
|
|
521
|
+
if (summaryInfo.failedCount > 0) {
|
|
522
|
+
failedEvidenceDetected = true;
|
|
523
|
+
}
|
|
524
|
+
if (summaryInfo.verified) {
|
|
525
|
+
verifiedEvidence.push({
|
|
526
|
+
id: ev.data.id,
|
|
527
|
+
path: ev.rel,
|
|
528
|
+
status: "verified",
|
|
529
|
+
verified_by: ev.data.verified_by ?? null,
|
|
530
|
+
checks_summary: summaryInfo.summary,
|
|
531
|
+
});
|
|
532
|
+
} else {
|
|
533
|
+
contradictionWarnings.push(
|
|
534
|
+
`Evidence ${ev.data.id} (${ev.rel}) is not verified (${summaryInfo.summary}); excluded from verified_evidence.`
|
|
535
|
+
);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// Check for agent verification claims lacking backing verified evidence or contradicting failed checks
|
|
540
|
+
const promotedCompletedWarnings = [];
|
|
541
|
+
for (const item of completedItems) {
|
|
542
|
+
if (VERIFICATION_CLAIM_REGEX.test(item)) {
|
|
543
|
+
if (verifiedEvidence.length === 0 || failedEvidenceDetected) {
|
|
544
|
+
const msg = `Completed item makes test/verification assertion ("${item}") without uncontradicted verified EVID-* record.`;
|
|
545
|
+
contradictionWarnings.push(msg);
|
|
546
|
+
promotedCompletedWarnings.push(`Verification assertion from completed_items (unverified): ${item}`);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
for (const claim of unverifiedClaims) {
|
|
551
|
+
if (VERIFICATION_CLAIM_REGEX.test(claim)) {
|
|
552
|
+
if (verifiedEvidence.length === 0) {
|
|
553
|
+
contradictionWarnings.push(
|
|
554
|
+
`Agent claim asserts verification ("${claim}") with zero verified EVID-* records in evidence/.`
|
|
555
|
+
);
|
|
556
|
+
}
|
|
557
|
+
if (failedEvidenceDetected) {
|
|
558
|
+
contradictionWarnings.push(
|
|
559
|
+
`Contradiction: agent claim asserts verification ("${claim}") while evidence contains failed check(s).`
|
|
560
|
+
);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
const finalUnverifiedClaims = Array.from(new Set([...unverifiedClaims, ...promotedCompletedWarnings]));
|
|
565
|
+
|
|
566
|
+
// Derive remaining items from target task acceptance criteria if none provided
|
|
567
|
+
const finalOpenItems =
|
|
568
|
+
openItems.length > 0
|
|
569
|
+
? openItems
|
|
570
|
+
: targetTask && verifiedEvidence.length === 0
|
|
571
|
+
? [`Verify task acceptance criteria for ${taskId} before marking complete.`]
|
|
572
|
+
: [];
|
|
573
|
+
|
|
574
|
+
const gitState = collectGitState(projectDir, warnings);
|
|
575
|
+
const createdAt = options.createdAt || new Date().toISOString();
|
|
576
|
+
|
|
577
|
+
const record = {
|
|
578
|
+
schema_version: "1.1",
|
|
579
|
+
id: handoffId,
|
|
580
|
+
task_id: taskId,
|
|
581
|
+
from_role: fromRole,
|
|
582
|
+
to_role: toRole,
|
|
583
|
+
from_tool: fromTool,
|
|
584
|
+
to_tool: toTool,
|
|
585
|
+
status,
|
|
586
|
+
memory_layer: "L2_OPERATIONAL",
|
|
587
|
+
authority_level: "A4",
|
|
588
|
+
created_at: createdAt,
|
|
589
|
+
summary: summaryRaw,
|
|
590
|
+
completed_items: completedItems,
|
|
591
|
+
open_items: finalOpenItems,
|
|
592
|
+
artifacts_produced: artifactsProduced,
|
|
593
|
+
evidence_refs: evidenceRefs,
|
|
594
|
+
unresolved_risks: unresolvedRisks,
|
|
595
|
+
conflicts_detected: openConflicts,
|
|
596
|
+
recommended_next_action: nextActionRaw,
|
|
597
|
+
context_pack_ref: contextPackRef,
|
|
598
|
+
git_state: gitState,
|
|
599
|
+
relevant_requirements: snap.requirements.sort(),
|
|
600
|
+
relevant_decisions: relevantDecisions,
|
|
601
|
+
verified_evidence: verifiedEvidence,
|
|
602
|
+
unverified_claims: finalUnverifiedClaims,
|
|
603
|
+
blockers,
|
|
604
|
+
open_questions: openQuestions,
|
|
605
|
+
contradiction_warnings: contradictionWarnings,
|
|
606
|
+
};
|
|
607
|
+
|
|
608
|
+
const yamlText = serializeHandoffYaml(record);
|
|
609
|
+
const schema = loadSchema(harnessDir, "agent-handoff.schema.json");
|
|
610
|
+
const roundTripParsed = parseYaml(yamlText, `${handoffId}.yaml`);
|
|
611
|
+
const schemaCheck = validateAgainstSchema(roundTripParsed, schema);
|
|
612
|
+
if (!schemaCheck.valid) {
|
|
613
|
+
throw new Error(`Internal handoff failed schema validation: ${schemaCheck.errors.join("; ")}`);
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
// Determine destination path safely (refuse symlinks, traversal, or overwrites)
|
|
617
|
+
const slugPart = taskId ? taskId.toLowerCase() : deriveSlug(snap.manifest.name);
|
|
618
|
+
const handoffsRelDir = snap.projectPaths.handoffs_dir;
|
|
619
|
+
const defaultRel = `${handoffsRelDir}/${handoffId}-${slugPart}.yaml`;
|
|
620
|
+
let targetAbs;
|
|
621
|
+
let targetRel;
|
|
622
|
+
if (options.out) {
|
|
623
|
+
targetAbs = validateOutputFilePath(options.out, { harnessDir, workspaceRoot });
|
|
624
|
+
targetRel = path.relative(projectDir, targetAbs).replace(/\\/g, "/");
|
|
625
|
+
} else {
|
|
626
|
+
const handoffsDir = path.join(projectDir, handoffsRelDir);
|
|
627
|
+
if (fs.existsSync(handoffsDir) && fs.lstatSync(handoffsDir).isSymbolicLink()) {
|
|
628
|
+
throw new Error(`Refusing symbolic link directory: ${handoffsDir}`);
|
|
629
|
+
}
|
|
630
|
+
targetAbs = assertSafeWithinRoot(projectDir, defaultRel);
|
|
631
|
+
targetRel = defaultRel;
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
if (fs.existsSync(targetAbs)) {
|
|
635
|
+
throw new Error(`Refusing to overwrite existing handoff file: ${targetAbs}`);
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
const dryRun = Boolean(options.dryRun);
|
|
639
|
+
if (!dryRun) {
|
|
640
|
+
atomicWriteFile(targetAbs, yamlText, {
|
|
641
|
+
allowOverwrite: false,
|
|
642
|
+
onBeforeCommit: options.onBeforeCommit || null,
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
return {
|
|
647
|
+
id: handoffId,
|
|
648
|
+
taskId,
|
|
649
|
+
filePath: targetAbs,
|
|
650
|
+
relPath: targetRel,
|
|
651
|
+
dryRun,
|
|
652
|
+
record,
|
|
653
|
+
yaml: yamlText,
|
|
654
|
+
markdown: renderHandoffMarkdown(record),
|
|
655
|
+
warnings: [...warnings, ...contradictionWarnings],
|
|
656
|
+
};
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
export function inspectHandoff(options = {}) {
|
|
660
|
+
const harnessDir = path.resolve(options.harnessDir || DEFAULT_HARNESS_DIR);
|
|
661
|
+
const compatConfig = options.compatibilityConfig || loadCompatibilityConfig();
|
|
662
|
+
|
|
663
|
+
if (typeof options.projectDir !== "string" || options.projectDir.trim().length === 0) {
|
|
664
|
+
throw new Error("Missing required project directory (--project <dir>).");
|
|
665
|
+
}
|
|
666
|
+
const projectDir = path.resolve(options.projectDir);
|
|
667
|
+
if (!fs.existsSync(projectDir)) {
|
|
668
|
+
throw new Error(`Project directory does not exist: ${projectDir}`);
|
|
669
|
+
}
|
|
670
|
+
const rootStat = fs.lstatSync(projectDir);
|
|
671
|
+
if (rootStat.isSymbolicLink() || !rootStat.isDirectory()) {
|
|
672
|
+
throw new Error(`Project root must be a real non-symlink directory: ${projectDir}`);
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
if (typeof options.handoffPath !== "string" || options.handoffPath.trim().length === 0) {
|
|
676
|
+
throw new Error("Missing handoff file path (--inspect <file>).");
|
|
677
|
+
}
|
|
678
|
+
const relOrRaw = options.handoffPath.trim();
|
|
679
|
+
let resolvedHandoff;
|
|
680
|
+
if (path.isAbsolute(relOrRaw)) {
|
|
681
|
+
// Allow explicit absolute file path inside projectDir (still checking no symlinks/traversal via relative conversion)
|
|
682
|
+
const rel = path.relative(projectDir, path.resolve(relOrRaw));
|
|
683
|
+
if (rel.startsWith("..") || path.isAbsolute(rel)) {
|
|
684
|
+
throw new Error(`Handoff file path must reside within project root: ${relOrRaw}`);
|
|
685
|
+
}
|
|
686
|
+
resolvedHandoff = assertSafeWithinRoot(projectDir, rel);
|
|
687
|
+
} else {
|
|
688
|
+
resolvedHandoff = assertSafeWithinRoot(projectDir, relOrRaw);
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
if (isForbiddenSecretPath(path.relative(projectDir, resolvedHandoff))) {
|
|
692
|
+
throw new Error(`Refusing secret path as handoff file: ${relOrRaw}`);
|
|
693
|
+
}
|
|
694
|
+
if (!fs.existsSync(resolvedHandoff)) {
|
|
695
|
+
throw new Error(`Handoff file not found: ${resolvedHandoff}`);
|
|
696
|
+
}
|
|
697
|
+
const stat = fs.lstatSync(resolvedHandoff);
|
|
698
|
+
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
699
|
+
throw new Error(`Handoff path must be a regular non-symlink file: ${relOrRaw}`);
|
|
700
|
+
}
|
|
701
|
+
if (stat.size > MAX_RECORD_BYTES) {
|
|
702
|
+
throw new Error(`Handoff file exceeds ${MAX_RECORD_BYTES} byte limit: ${relOrRaw}`);
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
const rawText = fs.readFileSync(resolvedHandoff, "utf8");
|
|
706
|
+
if (hasSecretContent(rawText)) {
|
|
707
|
+
throw new Error(`Refusing handoff file containing credential-like content: ${relOrRaw}`);
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
const relLabel = path.relative(projectDir, resolvedHandoff).replace(/\\/g, "/");
|
|
711
|
+
const record = parseYaml(rawText, relLabel);
|
|
712
|
+
if (!record || typeof record !== "object" || Array.isArray(record)) {
|
|
713
|
+
throw new Error(`Malformed handoff YAML in ${relLabel}: expected mapping object.`);
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
const errors = [];
|
|
717
|
+
const warnings = [];
|
|
718
|
+
const verCheck = checkRecordSchemaVersion(record, compatConfig);
|
|
719
|
+
if (!verCheck.compatible) {
|
|
720
|
+
errors.push(verCheck.error);
|
|
721
|
+
}
|
|
722
|
+
const schemaCheck = validateAgainstSchema(record, loadSchema(harnessDir, "agent-handoff.schema.json"));
|
|
723
|
+
if (!schemaCheck.valid) {
|
|
724
|
+
errors.push(...schemaCheck.errors);
|
|
725
|
+
}
|
|
726
|
+
const snap = loadProjectSnapshot(projectDir, harnessDir, warnings);
|
|
727
|
+
const canonicalHandoffPrefixes = [snap.projectPaths.handoffs_dir, snap.projectPaths.tasks_dir];
|
|
728
|
+
const inCanonicalDir = canonicalHandoffPrefixes.some((p) => relLabel === p || relLabel.startsWith(`${p}/`));
|
|
729
|
+
if (inCanonicalDir && record.is_example === true) {
|
|
730
|
+
errors.push(`Example fixture (is_example: true) is forbidden in canonical handoff path ${relLabel}.`);
|
|
731
|
+
}
|
|
732
|
+
if (record.task_id && !snap.tasks.some((t) => t.data.id === record.task_id)) {
|
|
733
|
+
errors.push(`Broken reference task_id="${record.task_id}" not found in project tasks/.`);
|
|
734
|
+
}
|
|
735
|
+
const evMap = new Map(snap.evidences.map((e) => [e.data.id, e]));
|
|
736
|
+
for (const evId of record.evidence_refs || []) {
|
|
737
|
+
const ev = evMap.get(evId);
|
|
738
|
+
if (!ev) {
|
|
739
|
+
errors.push(`Broken reference evidence_refs entry "${evId}" not found in evidence/.`);
|
|
740
|
+
} else if (!summarizeEvidence(ev).verified) {
|
|
741
|
+
warnings.push(`Referenced evidence "${evId}" is not currently verified (${summarizeEvidence(ev).summary}).`);
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
for (const ve of record.verified_evidence || []) {
|
|
745
|
+
const ev = evMap.get(ve.id);
|
|
746
|
+
if (!ev) {
|
|
747
|
+
errors.push(`Forged/missing verified_evidence entry "${ve.id}" not found in evidence/.`);
|
|
748
|
+
continue;
|
|
749
|
+
}
|
|
750
|
+
if (ev.data.is_example) {
|
|
751
|
+
errors.push(`Example evidence fixture "${ve.id}" cannot appear in verified_evidence.`);
|
|
752
|
+
continue;
|
|
753
|
+
}
|
|
754
|
+
const evSummary = summarizeEvidence(ev);
|
|
755
|
+
if (!evSummary.verified) {
|
|
756
|
+
errors.push(`Evidence "${ve.id}" in verified_evidence failed authenticity check (${evSummary.summary}).`);
|
|
757
|
+
}
|
|
758
|
+
if (ve.path && ve.path !== ev.rel) {
|
|
759
|
+
errors.push(`Evidence "${ve.id}" path mismatch in verified_evidence ("${ve.path}" vs "${ev.rel}").`);
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
for (const art of record.artifacts_produced || []) {
|
|
763
|
+
if (art && typeof art.path === "string") {
|
|
764
|
+
if (isForbiddenSecretPath(art.path)) {
|
|
765
|
+
errors.push(`Forbidden secret path in artifacts_produced: "${art.path}".`);
|
|
766
|
+
continue;
|
|
767
|
+
}
|
|
768
|
+
try {
|
|
769
|
+
assertSafeWithinRoot(projectDir, art.path);
|
|
770
|
+
} catch (err) {
|
|
771
|
+
errors.push(`Unsafe path in artifacts_produced "${art.path}": ${err.message}`);
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
const confMap = new Map(snap.conflicts.map((c) => [c.data.id, c]));
|
|
776
|
+
for (const confId of record.conflicts_detected || []) {
|
|
777
|
+
if (!confMap.has(confId)) {
|
|
778
|
+
errors.push(`Broken reference conflicts_detected entry "${confId}" not found in brain/conflicts/.`);
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
const adrIds = new Set(snap.decisions.map((d) => d.data.id));
|
|
782
|
+
for (const adrId of record.relevant_decisions || []) {
|
|
783
|
+
if (!adrIds.has(adrId)) {
|
|
784
|
+
errors.push(`Broken reference relevant_decisions entry "${adrId}" not found in brain/decisions/.`);
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
const currentGit = getGitRepoInfo(projectDir);
|
|
789
|
+
const currentHead = currentGit.available ? (currentGit.unborn ? "unborn-head" : currentGit.head) : null;
|
|
790
|
+
const recordedHead = record.git_state?.head || null;
|
|
791
|
+
const gitDrift = {
|
|
792
|
+
available: currentGit.available,
|
|
793
|
+
recordedHead,
|
|
794
|
+
currentHead,
|
|
795
|
+
changed: Boolean(currentGit.available && recordedHead && currentHead && recordedHead !== currentHead),
|
|
796
|
+
};
|
|
797
|
+
if (gitDrift.changed) {
|
|
798
|
+
warnings.push(`Git HEAD moved since handoff (${recordedHead} -> ${currentHead}).`);
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
return {
|
|
802
|
+
valid: errors.length === 0,
|
|
803
|
+
compatible: verCheck.compatible,
|
|
804
|
+
compatibilityStatus: verCheck.compatible ? "compatible" : "incompatible",
|
|
805
|
+
id: record.id || null,
|
|
806
|
+
schemaVersion: record.schema_version || null,
|
|
807
|
+
filePath: resolvedHandoff,
|
|
808
|
+
relPath: relLabel,
|
|
809
|
+
record,
|
|
810
|
+
errors,
|
|
811
|
+
warnings,
|
|
812
|
+
gitDrift,
|
|
813
|
+
markdown: errors.length === 0 ? renderHandoffMarkdown(record, { gitDrift }) : null,
|
|
814
|
+
};
|
|
815
|
+
}
|