geloforge 0.6.0 → 0.9.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.
@@ -0,0 +1,500 @@
1
+ /**
2
+ * Bounded implement -> verify -> review -> fix coding loop orchestrator.
3
+ * Deterministic verification (captureEvidence) gates completion and cannot be overridden by LLM review.
4
+ */
5
+ import path from "node:path";
6
+ import { execFileSync } from "node:child_process";
7
+ import { resolveAuditProvider, runProviderProcess, startAuditProvider } from "./audit-provider.mjs";
8
+ import { createCheckpoint } from "./checkpoint.mjs";
9
+ import { compileContext } from "./context-compiler.mjs";
10
+ import { captureEvidence } from "./evidence-capture.mjs";
11
+ import { getGitRepoInfo } from "./git-utils.mjs";
12
+ import { hasSecretContent, isForbiddenSecretPath, redactSecretContent } from "./path-safety.mjs";
13
+ import { loadProjectManifestAndState } from "./project-locator.mjs";
14
+ import { withProjectLock } from "./project-lock.mjs";
15
+ import { readRuntimeJson, writeRuntimeJson } from "./runtime-files.mjs";
16
+ import { completeTask, getTask, updateTask } from "./task-manager.mjs";
17
+
18
+ export const CODING_LOOP_VERSION = 1;
19
+ const CLOSED_TASK_STATUSES = new Set(["completed", "cancelled", "superseded"]);
20
+ const MAX_DIFF_CHARS = 32 * 1024;
21
+ const MAX_FEEDBACK_CHARS = 4096;
22
+
23
+ export function codingLoopProgressPath(taskId) {
24
+ return `local-runtime/checkpoints/${taskId}-coding-loop.json`;
25
+ }
26
+
27
+ function boundedInteger(name, value, min, max) {
28
+ if (!Number.isInteger(value) || value < min || value > max) {
29
+ throw new Error(`${name} must be an integer between ${min} and ${max}.`);
30
+ }
31
+ return value;
32
+ }
33
+
34
+ function readLoopConfig(projectDir, relativePath) {
35
+ if (
36
+ typeof relativePath !== "string" ||
37
+ !relativePath.endsWith(".json") ||
38
+ path.win32.isAbsolute(relativePath) ||
39
+ path.posix.isAbsolute(relativePath) ||
40
+ isForbiddenSecretPath(relativePath) ||
41
+ hasSecretContent(relativePath)
42
+ ) {
43
+ throw new Error("Supply a project-relative JSON config path with --config.");
44
+ }
45
+ const raw = readRuntimeJson(projectDir, relativePath);
46
+ if (!raw || raw.version !== CODING_LOOP_VERSION) {
47
+ throw new Error("Coding loop config requires version: 1.");
48
+ }
49
+ if (
50
+ !Array.isArray(raw.verifyCommand) ||
51
+ raw.verifyCommand.length === 0 ||
52
+ raw.verifyCommand.some((part) => typeof part !== "string" || !part.trim() || hasSecretContent(part))
53
+ ) {
54
+ throw new Error("Coding loop config requires a non-empty verifyCommand array of safe command strings.");
55
+ }
56
+ const implementer = resolveAuditProvider(raw.implementer, projectDir);
57
+ const reviewer = raw.reviewer != null ? resolveAuditProvider(raw.reviewer, projectDir) : null;
58
+ return {
59
+ version: CODING_LOOP_VERSION,
60
+ maxFixRounds: boundedInteger("maxFixRounds", raw.maxFixRounds ?? 2, 0, 5),
61
+ timeoutMs: boundedInteger("timeoutMs", raw.timeoutMs ?? 60_000, 100, 300_000),
62
+ verifyCommand: [...raw.verifyCommand],
63
+ implementer,
64
+ reviewer,
65
+ };
66
+ }
67
+
68
+ function resolveOpenTask(projectDir, harnessDir, explicitTaskId) {
69
+ let taskId = explicitTaskId;
70
+ if (!taskId) {
71
+ const { state } = loadProjectManifestAndState(projectDir, harnessDir);
72
+ const active = state.active_tasks ?? [];
73
+ if (active.length !== 1) {
74
+ throw new Error("Pass --task TASK-NNNN when there is no single active task.");
75
+ }
76
+ [taskId] = active;
77
+ }
78
+ const task = getTask({ projectDir, harnessDir, taskId });
79
+ if (CLOSED_TASK_STATUSES.has(task.record.status)) {
80
+ throw new Error(`${task.id} is ${task.record.status}. Reopen or create a new task before running the loop.`);
81
+ }
82
+ return task;
83
+ }
84
+
85
+ function collectBoundedDiff(projectDir) {
86
+ const info = getGitRepoInfo(projectDir);
87
+ if (!info.available) return "";
88
+ let raw = "";
89
+ try {
90
+ const args = info.unborn ? ["diff", "--", "."] : ["diff", "HEAD", "--", "."];
91
+ raw = execFileSync("git", ["-C", projectDir, ...args], {
92
+ encoding: "utf8",
93
+ windowsHide: true,
94
+ maxBuffer: 2 * 1024 * 1024,
95
+ stdio: ["ignore", "pipe", "pipe"],
96
+ });
97
+ } catch {
98
+ return "";
99
+ }
100
+ if (!raw) return "";
101
+
102
+ const kept = [];
103
+ let allowSection = true;
104
+ for (const line of raw.split(/\r?\n/)) {
105
+ const match = /^diff --git a\/(.+?) b\/(.+?)$/.exec(line);
106
+ if (match) {
107
+ allowSection = !isForbiddenSecretPath(match[1]) && !isForbiddenSecretPath(match[2]);
108
+ }
109
+ if (allowSection) kept.push(line);
110
+ }
111
+ const safe = redactSecretContent(kept.join("\n").trim());
112
+ return safe.length > MAX_DIFF_CHARS ? `${safe.slice(0, MAX_DIFF_CHARS)}\n... [diff truncated]` : safe;
113
+ }
114
+
115
+ function buildImplementPrompt({ stage, round, task, contextMarkdown, feedback }) {
116
+ const sections = [
117
+ `Stage: ${stage} (round ${round})`,
118
+ `Task ${task.id}: ${task.record.title}`,
119
+ `Objective: ${task.record.objective}`,
120
+ `Acceptance criteria:\n${(task.record.acceptance_criteria ?? []).map((item) => `- ${item}`).join("\n")}`,
121
+ `Respond with concise JSON if convenient: { "summary": "...", "notes": [] }`,
122
+ ];
123
+ if (feedback) {
124
+ sections.push(`Prior failure/review feedback to resolve:\n${redactSecretContent(feedback).slice(0, MAX_FEEDBACK_CHARS)}`);
125
+ }
126
+ sections.push(`Project context:\n${redactSecretContent(contextMarkdown).slice(0, 48 * 1024)}`);
127
+ return sections.join("\n\n");
128
+ }
129
+
130
+ function buildReviewPrompt({ round, task, evidence, diffText }) {
131
+ const checkSummary = evidence.record?.checks?.[0]?.summary ?? "";
132
+ return [
133
+ "Perform an independent read-only code review against the task contract, scope boundaries, and acceptance criteria.",
134
+ "Verify scope_out, secret/PII safety, and acceptance criteria in policy_checks before setting verdict to approve.",
135
+ "Do not modify files, run external network calls, or override deterministic test results.",
136
+ "Return ONLY valid JSON with format:",
137
+ '{ "verdict": "approve" | "request_changes", "summary": "...", "policy_checks": [{ "rule": "...", "passed": true | false }], "findings": [{ "severity": "blocking" | "minor", "file": "...", "message": "..." }] }',
138
+ JSON.stringify({
139
+ taskId: task.id,
140
+ round,
141
+ title: task.record.title,
142
+ objective: task.record.objective,
143
+ scopeIn: task.record.scope_in ?? [],
144
+ scopeOut: task.record.scope_out ?? [],
145
+ acceptanceCriteria: task.record.acceptance_criteria ?? [],
146
+ verifiedEvidence: {
147
+ id: evidence.id,
148
+ exitCode: evidence.exitCode,
149
+ summary: redactSecretContent(checkSummary).slice(0, 600),
150
+ },
151
+ }),
152
+ `Working tree diff:\n${diffText || "(no git diff available)"}`,
153
+ ].join("\n\n");
154
+ }
155
+
156
+ function validateReviewResponse(output) {
157
+ if (!output || typeof output !== "object" || Array.isArray(output)) {
158
+ throw new Error("Reviewer output must be a JSON object.");
159
+ }
160
+ if (!["approve", "request_changes"].includes(output.verdict)) {
161
+ throw new Error('Reviewer verdict must be "approve" or "request_changes".');
162
+ }
163
+ if (typeof output.summary !== "string" || !output.summary.trim()) {
164
+ throw new Error("Reviewer response requires a non-empty summary.");
165
+ }
166
+ let policyChecks = [];
167
+ if (output.policy_checks !== undefined) {
168
+ if (!Array.isArray(output.policy_checks) || output.policy_checks.length > 20) {
169
+ throw new Error("Reviewer policy_checks must be an array of at most 20 entries.");
170
+ }
171
+ policyChecks = output.policy_checks.map((item) => {
172
+ if (!item || typeof item !== "object" || typeof item.rule !== "string" || !item.rule.trim() ||
173
+ typeof item.passed !== "boolean") {
174
+ throw new Error("Each reviewer policy check requires non-empty rule and boolean passed.");
175
+ }
176
+ return {
177
+ rule: redactSecretContent(item.rule.trim()).slice(0, 300),
178
+ passed: item.passed,
179
+ };
180
+ });
181
+ }
182
+ if (output.verdict === "approve" && policyChecks.some((item) => !item.passed)) {
183
+ throw new Error('Reviewer cannot return verdict "approve" with a failed policy check.');
184
+ }
185
+ if (!Array.isArray(output.findings) || output.findings.length > 50) {
186
+ throw new Error("Reviewer findings must be an array of at most 50 entries.");
187
+ }
188
+ const findings = output.findings.map((item) => {
189
+ if (!item || typeof item !== "object" || !["blocking", "minor"].includes(item.severity) ||
190
+ typeof item.message !== "string" || !item.message.trim()) {
191
+ throw new Error("Each reviewer finding requires severity (blocking|minor) and non-empty message.");
192
+ }
193
+ return {
194
+ severity: item.severity,
195
+ ...(typeof item.file === "string" && item.file.trim() ? { file: redactSecretContent(item.file.trim()).slice(0, 200) } : {}),
196
+ message: redactSecretContent(item.message.trim()).slice(0, 500),
197
+ };
198
+ });
199
+ if (output.verdict === "approve" && findings.some((item) => item.severity === "blocking")) {
200
+ throw new Error('Reviewer cannot return verdict "approve" with blocking findings.');
201
+ }
202
+ return {
203
+ verdict: output.verdict,
204
+ summary: redactSecretContent(output.summary.trim()).slice(0, 600),
205
+ policy_checks: policyChecks,
206
+ findings,
207
+ };
208
+ }
209
+
210
+ async function runWorkspaceProvider(resolvedProvider, projectDir, prompt, timeoutMs) {
211
+ const request = "Complete the task described in the prompt provided on stdin (also saved in loop-input.txt outside the project) and return a concise JSON summary {\"summary\": \"...\", \"notes\": []}.";
212
+ const result = await runProviderProcess({
213
+ ...resolvedProvider,
214
+ prompt,
215
+ cwd: projectDir,
216
+ inputFile: "loop-input.txt",
217
+ timeoutMs,
218
+ requireJson: false,
219
+ buildArgs: ({ finalPath, provider }) => ({
220
+ codex: ["--ask-for-approval", "never", "exec", "--sandbox", "workspace-write", "--skip-git-repo-check",
221
+ "--ephemeral", "--ignore-user-config", "--output-last-message", finalPath, request],
222
+ gemini: ["--approval-mode=auto_edit", "--output-format=json", "--prompt", request],
223
+ antigravity: ["--mode=agent", "--output-format=json", "--print", request],
224
+ }[provider]),
225
+ }).promise;
226
+
227
+ if (result.parsed && typeof result.parsed.summary === "string") {
228
+ return {
229
+ summary: redactSecretContent(result.parsed.summary.trim()).slice(0, 600),
230
+ notes: Array.isArray(result.parsed.notes) ? result.parsed.notes.slice(0, 10).map((n) => redactSecretContent(String(n))) : [],
231
+ };
232
+ }
233
+ return {
234
+ summary: redactSecretContent(String(result.rawText ?? "").trim() || "Implementation turn finished.").slice(0, 600),
235
+ notes: [],
236
+ };
237
+ }
238
+
239
+ /**
240
+ * Executes a bounded implement -> verify -> review -> fix loop for one open task.
241
+ */
242
+ export async function runCodingLoop({
243
+ projectDir,
244
+ harnessDir,
245
+ configFile,
246
+ taskId = null,
247
+ tool = null,
248
+ sessionId = null,
249
+ dryRun = false,
250
+ } = {}) {
251
+ const loaded = loadProjectManifestAndState(projectDir, harnessDir);
252
+ const absProject = loaded.projectDir;
253
+ const config = readLoopConfig(absProject, configFile);
254
+ const initialTask = resolveOpenTask(absProject, harnessDir, taskId);
255
+ const progressPath = codingLoopProgressPath(initialTask.id);
256
+
257
+ compileContext({
258
+ projectDir: absProject,
259
+ harnessDir,
260
+ taskId: initialTask.id,
261
+ profile: "working",
262
+ includeMap: true,
263
+ includeSkills: true,
264
+ globalSkillsDir: null,
265
+ });
266
+
267
+ if (dryRun) {
268
+ return {
269
+ status: "dry_run",
270
+ projectDir: absProject,
271
+ taskId: initialTask.id,
272
+ maxFixRounds: config.maxFixRounds,
273
+ verifyCommand: config.verifyCommand,
274
+ implementer: config.implementer.runner,
275
+ reviewer: config.reviewer?.runner ?? null,
276
+ progressPath,
277
+ };
278
+ }
279
+
280
+ let task = initialTask;
281
+ if (task.record.status !== "active") {
282
+ updateTask({ projectDir: absProject, harnessDir, taskId: task.id, status: "active", activate: true, tool, sessionId });
283
+ task = getTask({ projectDir: absProject, harnessDir, taskId: task.id });
284
+ }
285
+
286
+ const progress = {
287
+ version: CODING_LOOP_VERSION,
288
+ taskId: task.id,
289
+ status: "running",
290
+ maxFixRounds: config.maxFixRounds,
291
+ verifyCommand: config.verifyCommand,
292
+ roundsUsed: 0,
293
+ implementAttempts: 0,
294
+ startedAt: new Date().toISOString(),
295
+ updatedAt: new Date().toISOString(),
296
+ evidenceId: null,
297
+ checkpointId: null,
298
+ reason: null,
299
+ review: null,
300
+ history: [],
301
+ };
302
+ const persist = () => {
303
+ progress.updatedAt = new Date().toISOString();
304
+ writeRuntimeJson(absProject, progressPath, progress);
305
+ };
306
+ persist();
307
+
308
+ const stopBlocked = (reason, summary, { evidenceId = null, verifiedEvidence = false, review = null } = {}) => {
309
+ let checkpoint;
310
+ withProjectLock(absProject, () => {
311
+ updateTask({ projectDir: absProject, harnessDir, taskId: task.id, status: "blocked", tool, sessionId });
312
+ checkpoint = createCheckpoint({
313
+ projectDir: absProject,
314
+ harnessDir,
315
+ ...(verifiedEvidence && evidenceId ? { evidenceRef: evidenceId } : {}),
316
+ summary,
317
+ });
318
+ });
319
+ progress.status = "blocked";
320
+ progress.reason = reason;
321
+ progress.evidenceId = evidenceId;
322
+ progress.checkpointId = checkpoint.checkpointId;
323
+ progress.review = review;
324
+ persist();
325
+ return {
326
+ status: "blocked",
327
+ reason,
328
+ projectDir: absProject,
329
+ taskId: task.id,
330
+ roundsUsed: progress.roundsUsed,
331
+ implementAttempts: progress.implementAttempts,
332
+ evidenceId,
333
+ checkpointId: checkpoint.checkpointId,
334
+ review,
335
+ progressPath,
336
+ };
337
+ };
338
+
339
+ const runImplementStage = async (stage, round, feedback = null) => {
340
+ progress.implementAttempts += 1;
341
+ const context = compileContext({
342
+ projectDir: absProject,
343
+ harnessDir,
344
+ taskId: task.id,
345
+ profile: "working",
346
+ includeMap: true,
347
+ fromDiff: stage === "fix",
348
+ includeSkills: true,
349
+ globalSkillsDir: null,
350
+ });
351
+ const prompt = buildImplementPrompt({ stage, round, task, contextMarkdown: context.markdown, feedback });
352
+ try {
353
+ const reply = await runWorkspaceProvider(config.implementer, absProject, prompt, config.timeoutMs);
354
+ progress.history.push({ stage, round, ok: true, summary: reply.summary });
355
+ persist();
356
+ return { ok: true, error: null };
357
+ } catch (err) {
358
+ const msg = redactSecretContent(err.message);
359
+ progress.history.push({ stage, round, ok: false, error: msg });
360
+ persist();
361
+ return { ok: false, error: msg };
362
+ }
363
+ };
364
+
365
+ await runImplementStage("implement", 0, null);
366
+
367
+ let lastReview = null;
368
+ for (let round = 0; round <= config.maxFixRounds; round += 1) {
369
+ progress.roundsUsed = round;
370
+ const evidence = captureEvidence({
371
+ projectDir: absProject,
372
+ harnessDir,
373
+ taskId: task.id,
374
+ commandArgv: config.verifyCommand,
375
+ name: "Coding loop verification gate",
376
+ timeoutMs: config.timeoutMs,
377
+ linkVerifiedOnly: true,
378
+ });
379
+ const checkSummary = redactSecretContent(evidence.record?.checks?.[0]?.summary ?? "");
380
+ progress.history.push({
381
+ stage: "verify",
382
+ round,
383
+ evidenceId: evidence.id,
384
+ verified: evidence.verified,
385
+ exitCode: evidence.exitCode,
386
+ summary: checkSummary.slice(0, 600),
387
+ });
388
+ persist();
389
+
390
+ if (!evidence.verified) {
391
+ if (round < config.maxFixRounds) {
392
+ const feedback = `${checkSummary}\n${evidence.outputExcerpt ?? ""}`.trim();
393
+ await runImplementStage("fix", round + 1, feedback);
394
+ continue;
395
+ }
396
+ return stopBlocked(
397
+ "verify_failed_max_rounds",
398
+ `Coding loop blocked after ${config.maxFixRounds} fix round(s); verification failed (${evidence.id}).`,
399
+ { evidenceId: evidence.id, verifiedEvidence: false }
400
+ );
401
+ }
402
+
403
+ if (config.reviewer) {
404
+ const diffText = collectBoundedDiff(absProject);
405
+ const reviewPrompt = buildReviewPrompt({ round, task, evidence, diffText });
406
+ let review;
407
+ try {
408
+ const rawReview = await startAuditProvider(config.reviewer, reviewPrompt, { timeoutMs: config.timeoutMs }).promise;
409
+ review = validateReviewResponse(rawReview);
410
+ } catch (err) {
411
+ const msg = redactSecretContent(err.message);
412
+ review = {
413
+ verdict: "request_changes",
414
+ summary: msg,
415
+ findings: [{ severity: "blocking", message: msg }],
416
+ invalid: true,
417
+ };
418
+ }
419
+ lastReview = review;
420
+ progress.history.push({ stage: "review", round, ...review });
421
+ persist();
422
+
423
+ if (review.verdict !== "approve") {
424
+ if (round < config.maxFixRounds) {
425
+ const feedback = JSON.stringify(review);
426
+ await runImplementStage("fix", round + 1, feedback);
427
+ continue;
428
+ }
429
+ return stopBlocked(
430
+ "review_changes_requested_max_rounds",
431
+ `Coding loop blocked after ${config.maxFixRounds} fix round(s); reviewer requested changes (${evidence.id}).`,
432
+ { evidenceId: evidence.id, verifiedEvidence: true, review }
433
+ );
434
+ }
435
+ }
436
+
437
+ let checkpoint;
438
+ withProjectLock(absProject, () => {
439
+ checkpoint = createCheckpoint({
440
+ projectDir: absProject,
441
+ harnessDir,
442
+ evidenceRef: evidence.id,
443
+ summary: `Coding loop verified and completed ${task.id} (${evidence.id}).`,
444
+ });
445
+ completeTask({
446
+ projectDir: absProject,
447
+ harnessDir,
448
+ taskId: task.id,
449
+ requireEvidence: true,
450
+ evidenceRefs: [evidence.id],
451
+ tool,
452
+ sessionId,
453
+ });
454
+ });
455
+ progress.status = "completed";
456
+ progress.evidenceId = evidence.id;
457
+ progress.checkpointId = checkpoint.checkpointId;
458
+ progress.review = lastReview;
459
+ persist();
460
+ return {
461
+ status: "completed",
462
+ projectDir: absProject,
463
+ taskId: task.id,
464
+ roundsUsed: round,
465
+ implementAttempts: progress.implementAttempts,
466
+ evidenceId: evidence.id,
467
+ checkpointId: checkpoint.checkpointId,
468
+ review: lastReview,
469
+ progressPath,
470
+ };
471
+ }
472
+
473
+ throw new Error("Coding loop exited unexpectedly without resolution.");
474
+ }
475
+
476
+ /**
477
+ * Loads the persisted coding-loop status and stage history for a task.
478
+ */
479
+ export function getCodingLoopStatus({ projectDir, harnessDir, taskId = null } = {}) {
480
+ const loaded = loadProjectManifestAndState(projectDir, harnessDir);
481
+ let targetId = taskId;
482
+ if (!targetId) {
483
+ const active = loaded.state.active_tasks ?? [];
484
+ if (active.length !== 1) {
485
+ throw new Error("Pass --task TASK-NNNN when there is no single active task.");
486
+ }
487
+ [targetId] = active;
488
+ }
489
+ const task = getTask({ projectDir: loaded.projectDir, harnessDir, taskId: targetId });
490
+ const progressPath = codingLoopProgressPath(task.id);
491
+ const progress = readRuntimeJson(loaded.projectDir, progressPath);
492
+ if (!progress) {
493
+ throw new Error(`No coding loop progress found for ${task.id}.`);
494
+ }
495
+ return {
496
+ projectDir: loaded.projectDir,
497
+ progressPath,
498
+ ...progress,
499
+ };
500
+ }
@@ -1,5 +1,5 @@
1
1
  {
2
- "harness_version": "0.6.0",
2
+ "harness_version": "0.9.0",
3
3
  "template_version": "1.0.0",
4
4
  "default_schema_version": "1.1",
5
5
  "supported_schema_versions": ["1.0", "1.1"],
@@ -0,0 +1,114 @@
1
+ /** Opt-in disk cache for query packets. Unsafe or dynamic inputs use the normal compiler. */
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import { createHash } from "node:crypto";
5
+ import { fileURLToPath } from "node:url";
6
+ import { compileContext } from "./context-compiler.mjs";
7
+ import { getGitRepoInfo } from "./git-utils.mjs";
8
+ import { assertSafeWithinRoot, hasSecretContent, isForbiddenSecretPath, walkNonSymlinkFiles } from "./path-safety.mjs";
9
+ import { parseYaml } from "./yaml-subset.mjs";
10
+ import { listTaskLeases, TASK_LEASES_PATH } from "./task-manager.mjs";
11
+ import { resolveProjectPaths } from "./project-locator.mjs";
12
+ import { readRegularFile, readRuntimeJson, sha256, writeRuntimeJson } from "./runtime-files.mjs";
13
+
14
+ const CACHE = "local-runtime/context-cache/packet.json";
15
+ const MAX_BYTES = 512 * 1024;
16
+ const DEFAULT_HARNESS_DIR = fileURLToPath(new URL("../", import.meta.url));
17
+ const BUILD_DIGESTS = new Map();
18
+
19
+ function buildDigest(harnessDir) {
20
+ if (!BUILD_DIGESTS.has(harnessDir)) {
21
+ const hash = createHash("sha256");
22
+ const core = path.join(harnessDir, "core");
23
+ for (const name of fs.readdirSync(core).filter((name) => /\.(mjs|json)$/.test(name)).sort()) {
24
+ hash.update(name).update(sha256(fs.readFileSync(path.join(core, name))));
25
+ }
26
+ BUILD_DIGESTS.set(harnessDir, hash.digest("hex"));
27
+ }
28
+ return BUILD_DIGESTS.get(harnessDir);
29
+ }
30
+
31
+ function fingerprint(options) {
32
+ const root = path.resolve(options.projectDir);
33
+ const harnessDir = path.resolve(options.harnessDir ?? DEFAULT_HARNESS_DIR);
34
+ const manifestFile = assertSafeWithinRoot(root, "brain/manifest.yaml");
35
+ const rawManifest = readRegularFile(manifestFile);
36
+ if (!rawManifest || fs.lstatSync(root).isSymbolicLink()) return null;
37
+ if (fs.existsSync(assertSafeWithinRoot(root, TASK_LEASES_PATH)) &&
38
+ listTaskLeases({ projectDir: root, harnessDir }).activeLeases.length > 0) return null;
39
+ const manifest = parseYaml(rawManifest.toString("utf8"), "brain/manifest.yaml");
40
+ const projectPaths = resolveProjectPaths(manifest);
41
+ const git = getGitRepoInfo(root);
42
+ const hash = createHash("sha256").update(JSON.stringify([
43
+ "context-cache-v1", buildDigest(harnessDir), root, harnessDir, git.available, git.head, git.unborn,
44
+ options.query, options.profile, options.budget, options.excludeUnverified, options.includeCompleted, options.referenceDate,
45
+ ]));
46
+ let total = 0;
47
+ let count = 0;
48
+ const hashFile = (base, relativePath) => {
49
+ if (isForbiddenSecretPath(relativePath)) return;
50
+ const bytes = readRegularFile(assertSafeWithinRoot(base, relativePath), MAX_BYTES);
51
+ total += bytes?.length ?? 0;
52
+ count += 1;
53
+ if (total > 16 * 1024 * 1024 || count > 1000) throw new Error("Context cache limits exceeded.");
54
+ hash.update(JSON.stringify([base, relativePath, bytes ? sha256(bytes) : null]));
55
+ };
56
+ const hashTree = (base, dir) => {
57
+ const absolute = assertSafeWithinRoot(base, dir);
58
+ const files = walkNonSymlinkFiles(base, absolute, (file) => /\.(md|ya?ml|json)$/i.test(file), null, {
59
+ onSymlink: () => { throw new Error("Context cache excludes symlinked inputs."); },
60
+ ignoreDirs: new Set([".git", "node_modules", "secrets"]),
61
+ });
62
+ for (const file of files) hashFile(base, path.relative(base, file));
63
+ };
64
+ hashTree(harnessDir, "policies");
65
+ hashTree(harnessDir, "schemas");
66
+ hashFile(root, "brain/manifest.yaml");
67
+ hashFile(root, "brain/profile.md");
68
+ hashTree(root, "brain/lessons");
69
+ for (const [key, file] of Object.entries(projectPaths)) {
70
+ if (key.endsWith("_dir")) hashTree(root, file);
71
+ else hashFile(root, file);
72
+ }
73
+ return hash.digest("hex");
74
+ }
75
+
76
+ export function compileCachedContext(options) {
77
+ const compile = () => ({ ...compileContext(options), diskCache: "bypassed" });
78
+ if (!options.query || options.taskId || options.includeMap || options.fromDiff || options.includeSkills ||
79
+ options.pinnedSkills?.length || options.compiledAt || options.compatibilityConfig ||
80
+ options.mapBudget !== undefined || options.skillsBudget !== undefined) return compile();
81
+
82
+ const prepared = { ...options, referenceDate: options.referenceDate ?? new Date().toISOString().slice(0, 10) };
83
+ let key;
84
+ try {
85
+ key = fingerprint(prepared);
86
+ } catch {
87
+ return compile();
88
+ }
89
+ if (!key) return compile();
90
+ const { projectDir } = options;
91
+ try {
92
+ const entry = readRuntimeJson(projectDir, CACHE, { maxBytes: MAX_BYTES });
93
+ if (entry?.key === key && entry.packet?.manifest?.status === "compiled" && typeof entry.packet.markdown === "string") {
94
+ const saved = JSON.stringify(entry.packet);
95
+ if (sha256(saved) === entry.digest && !hasSecretContent(saved)) {
96
+ return { ...entry.packet, diskCache: "hit" };
97
+ }
98
+ }
99
+ } catch {
100
+ // The compiler still works when a local cache file is unreadable or corrupt.
101
+ }
102
+
103
+ const packet = compileContext(prepared);
104
+ const packetJson = JSON.stringify(packet);
105
+ try {
106
+ if (!hasSecretContent(packetJson) && fingerprint(prepared) === key) {
107
+ const entry = { key, digest: sha256(packetJson), packet };
108
+ if (Buffer.byteLength(JSON.stringify(entry, null, 2), "utf8") < MAX_BYTES) writeRuntimeJson(projectDir, CACHE, entry);
109
+ }
110
+ } catch {
111
+ // Unstable sources and cache-write failures do not change the compiled packet.
112
+ }
113
+ return { ...packet, diskCache: "miss" };
114
+ }