@bonesofspring/ai-rules 0.2.42 → 0.2.43
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/CHANGELOG.md +44 -0
- package/bin/lib/seed-ai-local-team.js +41 -4
- package/docs/LOCAL-OVERLAY.md +3 -1
- package/docs/specs/INDEX.md +3 -1
- package/docs/specs/_templates/feature.md +6 -0
- package/package.json +1 -1
- package/presets/_shared/assets/docs-specs/_templates/feature.md +6 -0
- package/presets/_shared/core/agent-team/agent-team-orchestrator.md +21 -5
- package/presets/_shared/core/agent-team/plan-graph.md +9 -1
- package/presets/_shared/core/quality/anti-hallucination-contract.md +2 -0
- package/presets/_shared/core/quality/context-and-iteration.md +2 -1
- package/presets/_shared/hooks/chain-team-phases.sh.tmpl +1080 -4
- package/presets/claude/android-kotlin/commands/task-continue.md +1 -1
- package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +1080 -4
- package/presets/claude/android-kotlin/rules/tooling-and-review/agent-team-orchestrator.md +21 -5
- package/presets/claude/android-kotlin/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
- package/presets/claude/go/commands/task-continue.md +1 -1
- package/presets/claude/go/hooks/chain-team-phases.sh +1080 -4
- package/presets/claude/go/rules/tooling-and-review/agent-team-orchestrator.md +21 -5
- package/presets/claude/go/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
- package/presets/claude/ios-swift/commands/task-continue.md +1 -1
- package/presets/claude/ios-swift/hooks/chain-team-phases.sh +1080 -4
- package/presets/claude/ios-swift/rules/tooling-and-review/agent-team-orchestrator.md +21 -5
- package/presets/claude/ios-swift/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
- package/presets/claude/java/commands/task-continue.md +1 -1
- package/presets/claude/java/hooks/chain-team-phases.sh +1080 -4
- package/presets/claude/java/rules/tooling-and-review/agent-team-orchestrator.md +21 -5
- package/presets/claude/java/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
- package/presets/claude/mcp-ts/commands/task-continue.md +1 -1
- package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +1080 -4
- package/presets/claude/mcp-ts/rules/tooling-and-review/agent-team-orchestrator.md +21 -5
- package/presets/claude/mcp-ts/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
- package/presets/claude/next/REPO_AGENTS.md +1 -1
- package/presets/claude/next/agents/openspec-author.md +26 -2
- package/presets/claude/next/agents/task-analyst.md +15 -6
- package/presets/claude/next/agents/task-router.md +20 -2
- package/presets/{cursor/next/ai-local/rules-library → claude/next/ai-local/rules}/task-levels.md +2 -0
- package/presets/claude/next/commands/task-continue.md +1 -1
- package/presets/claude/next/hooks/chain-team-phases.sh +1080 -4
- package/presets/claude/next/rules/tooling-and-review/agent-team-orchestrator.md +21 -5
- package/presets/claude/next/rules/tooling-and-review/ai-local-overlay.md +1 -1
- package/presets/claude/next/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
- package/presets/claude/nuxt/agents/README.md +1 -1
- package/presets/claude/nuxt/commands/task-continue.md +1 -1
- package/presets/claude/nuxt/hooks/chain-team-phases.sh +1080 -4
- package/presets/claude/nuxt/rules/tooling-and-review/agent-team-orchestrator.md +21 -5
- package/presets/claude/nuxt/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
- package/presets/claude/php-hexagonal/commands/task-continue.md +1 -1
- package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +1080 -4
- package/presets/claude/php-hexagonal/rules/tooling-and-review/agent-team-orchestrator.md +21 -5
- package/presets/claude/php-hexagonal/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
- package/presets/claude/php-laravel/commands/task-continue.md +1 -1
- package/presets/claude/php-laravel/hooks/chain-team-phases.sh +1080 -4
- package/presets/claude/php-laravel/rules/tooling-and-review/agent-team-orchestrator.md +21 -5
- package/presets/claude/php-laravel/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
- package/presets/claude/svelte/agents/README.md +1 -1
- package/presets/claude/svelte/commands/task-continue.md +1 -1
- package/presets/claude/svelte/hooks/chain-team-phases.sh +1080 -4
- package/presets/claude/svelte/rules/tooling-and-review/agent-team-orchestrator.md +21 -5
- package/presets/claude/svelte/rules/tooling-and-review/anti-hallucination-contract.md +2 -0
- package/presets/cursor/android-kotlin/commands/task-continue.md +1 -1
- package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +1080 -4
- package/presets/cursor/android-kotlin/rules/anti-hallucination-contract.mdc +2 -0
- package/presets/cursor/go/commands/task-continue.md +1 -1
- package/presets/cursor/go/hooks/chain-team-phases.sh +1080 -4
- package/presets/cursor/go/rules/anti-hallucination-contract.mdc +2 -0
- package/presets/cursor/ios-swift/commands/task-continue.md +1 -1
- package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +1080 -4
- package/presets/cursor/ios-swift/rules/anti-hallucination-contract.mdc +2 -0
- package/presets/cursor/java/commands/task-continue.md +1 -1
- package/presets/cursor/java/hooks/chain-team-phases.sh +1080 -4
- package/presets/cursor/java/rules/anti-hallucination-contract.mdc +2 -0
- package/presets/cursor/mcp-ts/commands/task-continue.md +1 -1
- package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +1080 -4
- package/presets/cursor/mcp-ts/rules/anti-hallucination-contract.mdc +2 -0
- package/presets/cursor/next/REPO_AGENTS.md +1 -1
- package/presets/cursor/next/agents/README.md +1 -1
- package/presets/cursor/next/agents/build-verifier.md +2 -0
- package/presets/cursor/next/agents/feature-developer.md +9 -0
- package/presets/cursor/next/agents/openspec-author.md +26 -2
- package/presets/cursor/next/agents/task-analyst.md +20 -6
- package/presets/cursor/next/agents/task-router.md +31 -2
- package/presets/cursor/next/ai-local/conventions.md +20 -0
- package/presets/{mavis/next/ai-local/rules-library → cursor/next/ai-local/rules}/task-levels.md +12 -0
- package/presets/cursor/next/commands/task-continue.md +1 -1
- package/presets/cursor/next/hooks/chain-team-phases.sh +1080 -4
- package/presets/cursor/next/rules/agent-team-orchestrator.mdc +18 -2
- package/presets/cursor/next/rules/ai-local-overlay.mdc +1 -1
- package/presets/cursor/next/rules/anti-hallucination-contract.mdc +2 -0
- package/presets/cursor/nuxt/agents/README.md +1 -1
- package/presets/cursor/nuxt/commands/task-continue.md +1 -1
- package/presets/cursor/nuxt/hooks/chain-team-phases.sh +1080 -4
- package/presets/cursor/nuxt/rules/anti-hallucination-contract.mdc +2 -0
- package/presets/cursor/php-hexagonal/commands/task-continue.md +1 -1
- package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +1080 -4
- package/presets/cursor/php-hexagonal/rules/anti-hallucination-contract.mdc +2 -0
- package/presets/cursor/php-laravel/commands/task-continue.md +1 -1
- package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +1080 -4
- package/presets/cursor/php-laravel/rules/anti-hallucination-contract.mdc +2 -0
- package/presets/cursor/svelte/agents/README.md +1 -1
- package/presets/cursor/svelte/commands/task-continue.md +1 -1
- package/presets/cursor/svelte/hooks/chain-team-phases.sh +1080 -4
- package/presets/cursor/svelte/rules/anti-hallucination-contract.mdc +2 -0
- package/presets/mavis/android-kotlin/adapter-map.json +1 -1
- package/presets/mavis/android-kotlin/commands/task-continue.md +1 -1
- package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +1080 -4
- package/presets/mavis/android-kotlin/rules/agent-team-orchestrator.md +21 -5
- package/presets/mavis/android-kotlin/rules/anti-hallucination-contract.md +2 -0
- package/presets/mavis/go/adapter-map.json +1 -1
- package/presets/mavis/go/commands/task-continue.md +1 -1
- package/presets/mavis/go/hooks/chain-team-phases.sh +1080 -4
- package/presets/mavis/go/rules/agent-team-orchestrator.md +21 -5
- package/presets/mavis/go/rules/anti-hallucination-contract.md +2 -0
- package/presets/mavis/ios-swift/adapter-map.json +1 -1
- package/presets/mavis/ios-swift/commands/task-continue.md +1 -1
- package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +1080 -4
- package/presets/mavis/ios-swift/rules/agent-team-orchestrator.md +21 -5
- package/presets/mavis/ios-swift/rules/anti-hallucination-contract.md +2 -0
- package/presets/mavis/java/adapter-map.json +1 -1
- package/presets/mavis/java/commands/task-continue.md +1 -1
- package/presets/mavis/java/hooks/chain-team-phases.sh +1080 -4
- package/presets/mavis/java/rules/agent-team-orchestrator.md +21 -5
- package/presets/mavis/java/rules/anti-hallucination-contract.md +2 -0
- package/presets/mavis/mcp-ts/adapter-map.json +1 -1
- package/presets/mavis/mcp-ts/commands/task-continue.md +1 -1
- package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +1080 -4
- package/presets/mavis/mcp-ts/rules/agent-team-orchestrator.md +21 -5
- package/presets/mavis/mcp-ts/rules/anti-hallucination-contract.md +2 -0
- package/presets/mavis/next/REPO_AGENTS.md +1 -1
- package/presets/mavis/next/adapter-map.json +5 -5
- package/presets/mavis/next/agents/build-verifier.md +2 -0
- package/presets/mavis/next/agents/feature-developer.md +9 -0
- package/presets/mavis/next/agents/openspec-author.md +26 -2
- package/presets/mavis/next/agents/task-analyst.md +20 -6
- package/presets/mavis/next/agents/task-router.md +31 -2
- package/presets/mavis/next/ai-local/conventions.md +20 -0
- package/presets/{opencode/next/ai-local/rules-library → mavis/next/ai-local/rules}/task-levels.md +12 -0
- package/presets/mavis/next/commands/task-continue.md +1 -1
- package/presets/mavis/next/hooks/chain-team-phases.sh +1080 -4
- package/presets/mavis/next/rules/agent-team-orchestrator.md +21 -5
- package/presets/mavis/next/rules/ai-local-overlay.md +1 -1
- package/presets/mavis/next/rules/anti-hallucination-contract.md +2 -0
- package/presets/mavis/nuxt/adapter-map.json +1 -1
- package/presets/mavis/nuxt/commands/task-continue.md +1 -1
- package/presets/mavis/nuxt/hooks/chain-team-phases.sh +1080 -4
- package/presets/mavis/nuxt/rules/agent-team-orchestrator.md +21 -5
- package/presets/mavis/nuxt/rules/anti-hallucination-contract.md +2 -0
- package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
- package/presets/mavis/php-hexagonal/commands/task-continue.md +1 -1
- package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +1080 -4
- package/presets/mavis/php-hexagonal/rules/agent-team-orchestrator.md +21 -5
- package/presets/mavis/php-hexagonal/rules/anti-hallucination-contract.md +2 -0
- package/presets/mavis/php-laravel/adapter-map.json +1 -1
- package/presets/mavis/php-laravel/commands/task-continue.md +1 -1
- package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +1080 -4
- package/presets/mavis/php-laravel/rules/agent-team-orchestrator.md +21 -5
- package/presets/mavis/php-laravel/rules/anti-hallucination-contract.md +2 -0
- package/presets/mavis/svelte/adapter-map.json +1 -1
- package/presets/mavis/svelte/commands/task-continue.md +1 -1
- package/presets/mavis/svelte/hooks/chain-team-phases.sh +1080 -4
- package/presets/mavis/svelte/rules/agent-team-orchestrator.md +21 -5
- package/presets/mavis/svelte/rules/anti-hallucination-contract.md +2 -0
- package/presets/opencode/android-kotlin/adapter-map.json +1 -1
- package/presets/opencode/android-kotlin/commands/task-continue.md +1 -1
- package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +1080 -4
- package/presets/opencode/android-kotlin/rules/agent-team-orchestrator.md +21 -5
- package/presets/opencode/android-kotlin/rules/anti-hallucination-contract.md +2 -0
- package/presets/opencode/go/adapter-map.json +1 -1
- package/presets/opencode/go/commands/task-continue.md +1 -1
- package/presets/opencode/go/hooks/chain-team-phases.sh +1080 -4
- package/presets/opencode/go/rules/agent-team-orchestrator.md +21 -5
- package/presets/opencode/go/rules/anti-hallucination-contract.md +2 -0
- package/presets/opencode/ios-swift/adapter-map.json +1 -1
- package/presets/opencode/ios-swift/commands/task-continue.md +1 -1
- package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +1080 -4
- package/presets/opencode/ios-swift/rules/agent-team-orchestrator.md +21 -5
- package/presets/opencode/ios-swift/rules/anti-hallucination-contract.md +2 -0
- package/presets/opencode/java/adapter-map.json +1 -1
- package/presets/opencode/java/commands/task-continue.md +1 -1
- package/presets/opencode/java/hooks/chain-team-phases.sh +1080 -4
- package/presets/opencode/java/rules/agent-team-orchestrator.md +21 -5
- package/presets/opencode/java/rules/anti-hallucination-contract.md +2 -0
- package/presets/opencode/mcp-ts/adapter-map.json +1 -1
- package/presets/opencode/mcp-ts/commands/task-continue.md +1 -1
- package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +1080 -4
- package/presets/opencode/mcp-ts/rules/agent-team-orchestrator.md +21 -5
- package/presets/opencode/mcp-ts/rules/anti-hallucination-contract.md +2 -0
- package/presets/opencode/next/REPO_AGENTS.md +1 -1
- package/presets/opencode/next/adapter-map.json +5 -5
- package/presets/opencode/next/agents/build-verifier.md +2 -0
- package/presets/opencode/next/agents/feature-developer.md +9 -0
- package/presets/opencode/next/agents/openspec-author.md +26 -2
- package/presets/opencode/next/agents/task-analyst.md +20 -6
- package/presets/opencode/next/agents/task-router.md +31 -2
- package/presets/opencode/next/ai-local/conventions.md +20 -0
- package/presets/opencode/next/ai-local/rules/task-levels.md +40 -0
- package/presets/opencode/next/commands/task-continue.md +1 -1
- package/presets/opencode/next/hooks/chain-team-phases.sh +1080 -4
- package/presets/opencode/next/rules/agent-team-orchestrator.md +21 -5
- package/presets/opencode/next/rules/ai-local-overlay.md +1 -1
- package/presets/opencode/next/rules/anti-hallucination-contract.md +2 -0
- package/presets/opencode/nuxt/adapter-map.json +1 -1
- package/presets/opencode/nuxt/commands/task-continue.md +1 -1
- package/presets/opencode/nuxt/hooks/chain-team-phases.sh +1080 -4
- package/presets/opencode/nuxt/rules/agent-team-orchestrator.md +21 -5
- package/presets/opencode/nuxt/rules/anti-hallucination-contract.md +2 -0
- package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
- package/presets/opencode/php-hexagonal/commands/task-continue.md +1 -1
- package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +1080 -4
- package/presets/opencode/php-hexagonal/rules/agent-team-orchestrator.md +21 -5
- package/presets/opencode/php-hexagonal/rules/anti-hallucination-contract.md +2 -0
- package/presets/opencode/php-laravel/adapter-map.json +1 -1
- package/presets/opencode/php-laravel/commands/task-continue.md +1 -1
- package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +1080 -4
- package/presets/opencode/php-laravel/rules/agent-team-orchestrator.md +21 -5
- package/presets/opencode/php-laravel/rules/anti-hallucination-contract.md +2 -0
- package/presets/opencode/svelte/adapter-map.json +1 -1
- package/presets/opencode/svelte/commands/task-continue.md +1 -1
- package/presets/opencode/svelte/hooks/chain-team-phases.sh +1080 -4
- package/presets/opencode/svelte/rules/agent-team-orchestrator.md +21 -5
- package/presets/opencode/svelte/rules/anti-hallucination-contract.md +2 -0
|
@@ -290,10 +290,429 @@ function writeSkeletonManifest(manifestPath) {
|
|
|
290
290
|
}
|
|
291
291
|
}
|
|
292
292
|
|
|
293
|
+
function normalizeRepoPath(value) {
|
|
294
|
+
let text = typeof value === 'string' ? value.trim() : '';
|
|
295
|
+
text = text.replace(/\\/g, '/');
|
|
296
|
+
while (text.startsWith('./')) text = text.slice(2);
|
|
297
|
+
if (!text || text === '—' || text === '-' || text === '–') return '';
|
|
298
|
+
if (/[\s()]/.test(text)) return '';
|
|
299
|
+
return text;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function isAppPath(file) {
|
|
303
|
+
const normalized = normalizeRepoPath(file);
|
|
304
|
+
return normalized === 'app' || normalized.startsWith('app/') || normalized.startsWith('app/**') || normalized.startsWith('app/*');
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
function isSpecFolderPath(file) {
|
|
308
|
+
const normalized = normalizeRepoPath(file);
|
|
309
|
+
return normalized.startsWith('docs/specs/') || normalized.startsWith('docs/specs/**') || normalized.startsWith('openspec/') || normalized.startsWith('openspec/**');
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
function listsBothSpecAndApp(files) {
|
|
313
|
+
let app = false;
|
|
314
|
+
let spec = false;
|
|
315
|
+
for (const file of files || []) {
|
|
316
|
+
if (isAppPath(file)) app = true;
|
|
317
|
+
if (isSpecFolderPath(file)) spec = true;
|
|
318
|
+
}
|
|
319
|
+
return app && spec;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function pathInWriteScopes(file, writeScopes) {
|
|
323
|
+
const target = normalizeRepoPath(file);
|
|
324
|
+
if (!target) return false;
|
|
325
|
+
const scopes = Array.isArray(writeScopes) ? writeScopes : [];
|
|
326
|
+
for (const scope of scopes) {
|
|
327
|
+
const normalized = normalizeRepoPath(scope);
|
|
328
|
+
if (!normalized) continue;
|
|
329
|
+
if (normalized === target) return true;
|
|
330
|
+
if (normalized.endsWith('/**')) {
|
|
331
|
+
const prefix = normalized.slice(0, -3);
|
|
332
|
+
if (target === prefix || target.startsWith(prefix + '/')) return true;
|
|
333
|
+
} else if (normalized.endsWith('/*')) {
|
|
334
|
+
const prefix = normalized.slice(0, -2);
|
|
335
|
+
const rest = target.startsWith(prefix + '/') ? target.slice(prefix.length + 1) : '';
|
|
336
|
+
if (rest && !rest.includes('/')) return true;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
return false;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function taskFileSet(task) {
|
|
343
|
+
const all = []
|
|
344
|
+
.concat((task && task.files) || [], (task && task.specFiles) || [], (task && task.appFiles) || [])
|
|
345
|
+
.map((file) => normalizeRepoPath(file))
|
|
346
|
+
.filter(Boolean);
|
|
347
|
+
return new Set(all);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function taskReaches(tasks, startId, targetId) {
|
|
351
|
+
const byId = new Map(tasks.map((task) => [String(task.id), task]));
|
|
352
|
+
const seen = new Set();
|
|
353
|
+
const stack = [String(startId)];
|
|
354
|
+
while (stack.length > 0) {
|
|
355
|
+
const id = stack.pop();
|
|
356
|
+
if (seen.has(id)) continue;
|
|
357
|
+
seen.add(id);
|
|
358
|
+
const task = byId.get(id);
|
|
359
|
+
const deps = task && Array.isArray(task.dependsOn) ? task.dependsOn : [];
|
|
360
|
+
for (const dep of deps) {
|
|
361
|
+
if (String(dep) === String(targetId)) return true;
|
|
362
|
+
stack.push(String(dep));
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
return false;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function tasksAreOrdered(tasks, left, right) {
|
|
369
|
+
return taskReaches(tasks, left.id, right.id) || taskReaches(tasks, right.id, left.id);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function validateTaskFileLists(tasks, writeScopes) {
|
|
373
|
+
const list = Array.isArray(tasks) ? tasks : [];
|
|
374
|
+
const scopes = Array.isArray(writeScopes) ? writeScopes : [];
|
|
375
|
+
for (const task of list) {
|
|
376
|
+
const id = task && task.id ? task.id : '(unnamed)';
|
|
377
|
+
const files = (task && task.files) || [];
|
|
378
|
+
if (listsBothSpecAndApp(files)) {
|
|
379
|
+
return 'task "' + id + '" lists spec-folder paths and app/** paths in one file list; they are different lists';
|
|
380
|
+
}
|
|
381
|
+
if (scopes.length === 0) continue;
|
|
382
|
+
const combined = files.concat((task && task.specFiles) || [], (task && task.appFiles) || []);
|
|
383
|
+
for (const file of combined) {
|
|
384
|
+
if (!pathInWriteScopes(file, scopes)) {
|
|
385
|
+
const label = normalizeRepoPath(file) || file;
|
|
386
|
+
return 'task "' + id + '" file "' + label + '" is outside the implementing step writeScopes';
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
for (let i = 0; i < list.length; i += 1) {
|
|
391
|
+
for (let j = i + 1; j < list.length; j += 1) {
|
|
392
|
+
if (tasksAreOrdered(list, list[i], list[j])) continue;
|
|
393
|
+
const left = taskFileSet(list[i]);
|
|
394
|
+
let shared = '';
|
|
395
|
+
for (const file of taskFileSet(list[j])) {
|
|
396
|
+
if (left.has(file)) {
|
|
397
|
+
shared = file;
|
|
398
|
+
break;
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
if (shared) return 'parallel tasks "' + list[i].id + '" and "' + list[j].id + '" share "' + shared + '"';
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
return null;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
function productionPathsOutsideTaskList(paths, tasks) {
|
|
408
|
+
const allowed = new Set();
|
|
409
|
+
for (const task of tasks || []) {
|
|
410
|
+
for (const file of taskFileSet(task)) allowed.add(file);
|
|
411
|
+
}
|
|
412
|
+
const outside = [];
|
|
413
|
+
for (const cited of paths || []) {
|
|
414
|
+
const normalized = normalizeRepoPath(cited);
|
|
415
|
+
if (normalized && !allowed.has(normalized)) outside.push(normalized);
|
|
416
|
+
}
|
|
417
|
+
return outside;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function splitMarkdownCells(line) {
|
|
421
|
+
const trimmed = String(line || '').trim();
|
|
422
|
+
if (!trimmed.startsWith('|')) return [];
|
|
423
|
+
const cells = trimmed.split('|').map((cell) => cell.trim());
|
|
424
|
+
if (cells.length && cells[0] === '') cells.shift();
|
|
425
|
+
if (cells.length && cells[cells.length - 1] === '') cells.pop();
|
|
426
|
+
return cells;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function isSeparatorRow(cells) {
|
|
430
|
+
return cells.length > 0 && cells.every((cell) => /^:?-{3,}:?$/.test(cell));
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
function pathsFromCell(cell) {
|
|
434
|
+
const text = String(cell || '');
|
|
435
|
+
const found = [];
|
|
436
|
+
const pattern = /`([^`]+)`/g;
|
|
437
|
+
let match = pattern.exec(text);
|
|
438
|
+
while (match) {
|
|
439
|
+
const normalized = normalizeRepoPath(match[1]);
|
|
440
|
+
if (normalized && normalized.includes('/')) found.push(normalized);
|
|
441
|
+
match = pattern.exec(text);
|
|
442
|
+
}
|
|
443
|
+
if (found.length > 0) return found;
|
|
444
|
+
return text.split(',').map((part) => normalizeRepoPath(part)).filter((part) => part.includes('/'));
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function dependsFromCell(cell) {
|
|
448
|
+
const cleaned = String(cell || '').replace(/[`*]/g, '').trim();
|
|
449
|
+
if (!cleaned || cleaned === '—' || cleaned === '-' || cleaned === '–') return [];
|
|
450
|
+
return cleaned.split(/[,|/]/).map((part) => part.trim()).filter((part) => /^[A-Za-z][A-Za-z0-9._-]*$/.test(part));
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
function cellIsComplete(cell) {
|
|
454
|
+
const cleaned = String(cell || '').replace(/[`*[\]]/g, '').trim().toLowerCase();
|
|
455
|
+
return cleaned === 'complete' || cleaned === 'completed' || cleaned === 'done' || cleaned === 'x';
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function absorbMarkdownTable(block, byId) {
|
|
459
|
+
const rows = [];
|
|
460
|
+
for (const line of block) {
|
|
461
|
+
const cells = splitMarkdownCells(line);
|
|
462
|
+
if (cells.length === 0 || isSeparatorRow(cells)) continue;
|
|
463
|
+
rows.push(cells);
|
|
464
|
+
}
|
|
465
|
+
if (rows.length < 2) return false;
|
|
466
|
+
const headers = rows[0].map((cell) => cell.replace(/[`*]/g, '').trim());
|
|
467
|
+
const idIndex = headers.findIndex((header) => /^id$/i.test(header));
|
|
468
|
+
if (idIndex < 0) return false;
|
|
469
|
+
const dependsIndex = headers.findIndex((header) => /dependson/i.test(header));
|
|
470
|
+
const specIndex = headers.findIndex((header) => /spec files/i.test(header));
|
|
471
|
+
const appIndex = headers.findIndex((header) => /^app files$/i.test(header));
|
|
472
|
+
const filesIndex = headers.findIndex((header, index) => index !== specIndex && index !== appIndex && /files|paths/i.test(header));
|
|
473
|
+
const statusIndex = headers.findIndex((header) => /^(status|done|state)$/i.test(header));
|
|
474
|
+
const sawFiles = specIndex >= 0 || appIndex >= 0 || filesIndex >= 0;
|
|
475
|
+
for (const cells of rows.slice(1)) {
|
|
476
|
+
const id = String(cells[idIndex] || '').replace(/[`*]/g, '').trim();
|
|
477
|
+
if (!id || /^id$/i.test(id)) continue;
|
|
478
|
+
const task = byId.get(id) || { id, dependsOn: [], files: [], specFiles: [], appFiles: [], tracked: false, rowComplete: false };
|
|
479
|
+
if (dependsIndex >= 0) {
|
|
480
|
+
task.dependsOn = dependsFromCell(cells[dependsIndex] || '');
|
|
481
|
+
task.tracked = true;
|
|
482
|
+
}
|
|
483
|
+
if (statusIndex >= 0) task.rowComplete = cellIsComplete(cells[statusIndex] || '');
|
|
484
|
+
if (filesIndex >= 0) {
|
|
485
|
+
const parsed = pathsFromCell(cells[filesIndex] || '');
|
|
486
|
+
if (parsed.length > 0) task.files = parsed;
|
|
487
|
+
}
|
|
488
|
+
if (specIndex >= 0) {
|
|
489
|
+
const parsed = pathsFromCell(cells[specIndex] || '');
|
|
490
|
+
if (parsed.length > 0) task.specFiles = parsed;
|
|
491
|
+
}
|
|
492
|
+
if (appIndex >= 0) {
|
|
493
|
+
const parsed = pathsFromCell(cells[appIndex] || '');
|
|
494
|
+
if (parsed.length > 0) task.appFiles = parsed;
|
|
495
|
+
}
|
|
496
|
+
byId.set(id, task);
|
|
497
|
+
}
|
|
498
|
+
return sawFiles;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
function parseDecompositionTaskFileLists(markdown) {
|
|
502
|
+
const lines = String(markdown || '').split(/\r?\n/);
|
|
503
|
+
const byId = new Map();
|
|
504
|
+
let hasFileColumn = false;
|
|
505
|
+
let index = 0;
|
|
506
|
+
while (index < lines.length) {
|
|
507
|
+
if (!String(lines[index] || '').trim().startsWith('|')) {
|
|
508
|
+
index += 1;
|
|
509
|
+
continue;
|
|
510
|
+
}
|
|
511
|
+
const block = [];
|
|
512
|
+
while (index < lines.length && String(lines[index] || '').trim().startsWith('|')) {
|
|
513
|
+
block.push(lines[index]);
|
|
514
|
+
index += 1;
|
|
515
|
+
}
|
|
516
|
+
if (absorbMarkdownTable(block, byId)) hasFileColumn = true;
|
|
517
|
+
}
|
|
518
|
+
return { tasks: [...byId.values()], hasFileColumn };
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function parseDecompositionTasks(markdown) {
|
|
522
|
+
const lines = String(markdown || '').split(/\r?\n/);
|
|
523
|
+
const byId = new Map();
|
|
524
|
+
let index = 0;
|
|
525
|
+
while (index < lines.length) {
|
|
526
|
+
if (!String(lines[index] || '').trim().startsWith('|')) {
|
|
527
|
+
index += 1;
|
|
528
|
+
continue;
|
|
529
|
+
}
|
|
530
|
+
const block = [];
|
|
531
|
+
while (index < lines.length && String(lines[index] || '').trim().startsWith('|')) {
|
|
532
|
+
block.push(lines[index]);
|
|
533
|
+
index += 1;
|
|
534
|
+
}
|
|
535
|
+
absorbMarkdownTable(block, byId);
|
|
536
|
+
}
|
|
537
|
+
return [...byId.values()].filter((task) => task.tracked === true);
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
function taskCoveredByCompletedArtifact(taskId, artifacts) {
|
|
541
|
+
const id = String(taskId);
|
|
542
|
+
const list = Array.isArray(artifacts) ? artifacts : [];
|
|
543
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
544
|
+
const artifact = list[index];
|
|
545
|
+
if (!artifact || artifact.status !== 'completed') continue;
|
|
546
|
+
if (String(artifact.id) === id) return true;
|
|
547
|
+
const taskIds = Array.isArray(artifact.taskIds) ? artifact.taskIds : [];
|
|
548
|
+
for (let taskIndex = 0; taskIndex < taskIds.length; taskIndex += 1) {
|
|
549
|
+
if (String(taskIds[taskIndex]) === id) return true;
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
return false;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
function computeDecompositionReadySet(tasks, artifacts) {
|
|
556
|
+
const list = (Array.isArray(tasks) ? tasks : []).filter((task) => task && task.id && task.tracked !== false);
|
|
557
|
+
const complete = new Set();
|
|
558
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
559
|
+
const task = list[index];
|
|
560
|
+
if (task.rowComplete === true || taskCoveredByCompletedArtifact(task.id, artifacts)) complete.add(String(task.id));
|
|
561
|
+
}
|
|
562
|
+
const ready = [];
|
|
563
|
+
const blocked = [];
|
|
564
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
565
|
+
const task = list[index];
|
|
566
|
+
const id = String(task.id);
|
|
567
|
+
if (complete.has(id)) continue;
|
|
568
|
+
const deps = Array.isArray(task.dependsOn) ? task.dependsOn.map((dep) => String(dep)) : [];
|
|
569
|
+
const waiting = [];
|
|
570
|
+
const seen = new Set();
|
|
571
|
+
for (let depIndex = 0; depIndex < deps.length; depIndex += 1) {
|
|
572
|
+
const dep = deps[depIndex];
|
|
573
|
+
if (!dep || seen.has(dep) || complete.has(dep)) continue;
|
|
574
|
+
seen.add(dep);
|
|
575
|
+
waiting.push(dep);
|
|
576
|
+
}
|
|
577
|
+
if (waiting.length === 0) ready.push(id);
|
|
578
|
+
else blocked.push({ id, waiting_on: waiting });
|
|
579
|
+
}
|
|
580
|
+
return { ready, blocked };
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
function readManifestArtifacts(dir) {
|
|
584
|
+
try {
|
|
585
|
+
const manifest = JSON.parse(fs.readFileSync(path.join(dir, 'artifact-manifest.json'), 'utf8'));
|
|
586
|
+
return Array.isArray(manifest.artifacts) ? manifest.artifacts : [];
|
|
587
|
+
} catch {
|
|
588
|
+
return [];
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
function readDecompositionReadySet(dir) {
|
|
593
|
+
let markdown = '';
|
|
594
|
+
try {
|
|
595
|
+
markdown = fs.readFileSync(path.join(dir, 'decomposition.md'), 'utf8');
|
|
596
|
+
} catch {
|
|
597
|
+
markdown = '';
|
|
598
|
+
}
|
|
599
|
+
return computeDecompositionReadySet(parseDecompositionTasks(markdown), readManifestArtifacts(dir));
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
function formatDecompositionReadyClause(report, stepsForRows) {
|
|
603
|
+
const source = report && typeof report === 'object' ? report : { ready: [], blocked: [] };
|
|
604
|
+
const stepList = Array.isArray(stepsForRows) ? stepsForRows : [];
|
|
605
|
+
const allow = [];
|
|
606
|
+
for (let index = 0; index < stepList.length; index += 1) {
|
|
607
|
+
const taskIds = stepList[index] && stepList[index].taskIds;
|
|
608
|
+
if (!Array.isArray(taskIds)) continue;
|
|
609
|
+
for (let idIndex = 0; idIndex < taskIds.length; idIndex += 1) {
|
|
610
|
+
if (taskIds[idIndex] != null && String(taskIds[idIndex])) allow.push(String(taskIds[idIndex]));
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
const gate = allow.length > 0 ? new Set(allow) : null;
|
|
614
|
+
const ready = (Array.isArray(source.ready) ? source.ready : []).filter((id) => !gate || gate.has(String(id)));
|
|
615
|
+
const blocked = (Array.isArray(source.blocked) ? source.blocked : []).filter((row) => row && (!gate || gate.has(String(row.id))));
|
|
616
|
+
const readyText = ready.length > 0 ? ready.join(', ') : '(none)';
|
|
617
|
+
let text = ' Decomposition ready set: ' + readyText + '.';
|
|
618
|
+
if (blocked.length > 0) {
|
|
619
|
+
const parts = [];
|
|
620
|
+
for (let index = 0; index < blocked.length; index += 1) {
|
|
621
|
+
const row = blocked[index];
|
|
622
|
+
const waiting = Array.isArray(row.waiting_on) ? row.waiting_on.join(', ') : '';
|
|
623
|
+
parts.push(String(row.id) + ' waiting_on ' + waiting);
|
|
624
|
+
}
|
|
625
|
+
text += ' Blocked: ' + parts.join('; ') + '.';
|
|
626
|
+
}
|
|
627
|
+
return text;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
function decompositionReadyClause(stepsForRows) {
|
|
631
|
+
try {
|
|
632
|
+
return formatDecompositionReadyClause(readDecompositionReadySet(taskDir), stepsForRows);
|
|
633
|
+
} catch {
|
|
634
|
+
return ' Decomposition ready set: (none).';
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
function productionCitationRepoPath(cited) {
|
|
639
|
+
const value = typeof cited === 'string' ? cited.trim() : '';
|
|
640
|
+
if (!value) return null;
|
|
641
|
+
const normalized = value.replace(/\\/g, '/');
|
|
642
|
+
if (path.isAbsolute(normalized)) {
|
|
643
|
+
const fromCwd = path.relative(process.cwd(), normalized);
|
|
644
|
+
if (fromCwd && !fromCwd.startsWith('..') && !path.isAbsolute(fromCwd)) return normalizeRepoPath(fromCwd);
|
|
645
|
+
return normalizeRepoPath(normalized) || normalized;
|
|
646
|
+
}
|
|
647
|
+
const taskResolved = path.resolve(taskDir, normalized);
|
|
648
|
+
const taskRelative = path.relative(taskDir, taskResolved);
|
|
649
|
+
const insideTask = taskRelative !== '' && taskRelative !== '..' && !taskRelative.startsWith('..' + path.sep) && !path.isAbsolute(taskRelative);
|
|
650
|
+
if (insideTask) {
|
|
651
|
+
try {
|
|
652
|
+
if (fs.statSync(taskResolved).isFile()) return null;
|
|
653
|
+
} catch {}
|
|
654
|
+
}
|
|
655
|
+
return normalizeRepoPath(normalized);
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
function implementingStepForTaskIds(taskIds) {
|
|
659
|
+
if (!Array.isArray(steps) || taskIds.length === 0) return null;
|
|
660
|
+
return steps.find((step) => Array.isArray(step && step.taskIds) && taskIds.some((id) => step.taskIds.map((item) => String(item)).includes(String(id)))) || null;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
function productionWriteListError(entry) {
|
|
664
|
+
const artifactId = entry && entry.id ? entry.id : '(unnamed)';
|
|
665
|
+
const resume = 'Then resume with: /task-continue ' + slug;
|
|
666
|
+
const fail = (detail) => '[chain-team-phases] ' + slug + ': receipt "' + artifactId + '" ' + detail + ' ' + resume;
|
|
667
|
+
try {
|
|
668
|
+
const evidence = entry && Array.isArray(entry.evidencePaths) ? entry.evidencePaths : [];
|
|
669
|
+
const production = [];
|
|
670
|
+
for (const cited of evidence) {
|
|
671
|
+
const repoPath = productionCitationRepoPath(cited);
|
|
672
|
+
if (repoPath) production.push(repoPath);
|
|
673
|
+
}
|
|
674
|
+
if (production.length === 0) return null;
|
|
675
|
+
let markdown = '';
|
|
676
|
+
try {
|
|
677
|
+
markdown = fs.readFileSync(path.join(taskDir, 'decomposition.md'), 'utf8');
|
|
678
|
+
} catch {
|
|
679
|
+
markdown = '';
|
|
680
|
+
}
|
|
681
|
+
const parsed = parseDecompositionTaskFileLists(markdown);
|
|
682
|
+
if (!parsed.hasFileColumn) return null;
|
|
683
|
+
const tasks = parsed.tasks;
|
|
684
|
+
const taskIds = Array.isArray(entry && entry.taskIds) ? entry.taskIds.map((id) => String(id)) : [];
|
|
685
|
+
const step = implementingStepForTaskIds(taskIds);
|
|
686
|
+
const selectedIds = new Set(taskIds);
|
|
687
|
+
if (step && Array.isArray(step.taskIds)) {
|
|
688
|
+
for (const id of step.taskIds) selectedIds.add(String(id));
|
|
689
|
+
}
|
|
690
|
+
const selected = tasks.filter((task) => selectedIds.has(String(task.id)));
|
|
691
|
+
if (selected.length === 0) {
|
|
692
|
+
return fail('cites production paths but decomposition.md has no file list for ' + (taskIds.join(', ') || '(none)') + '. Record the task file list.');
|
|
693
|
+
}
|
|
694
|
+
const writeScopes = step && Array.isArray(step.writeScopes) ? step.writeScopes : [];
|
|
695
|
+
const listError = validateTaskFileLists(selected, writeScopes);
|
|
696
|
+
if (listError) return fail(listError + '.');
|
|
697
|
+
const owned = selected.filter((task) => taskIds.includes(String(task.id)));
|
|
698
|
+
const citedAgainst = owned.length > 0 ? owned : selected;
|
|
699
|
+
const outside = productionPathsOutsideTaskList(production, citedAgainst);
|
|
700
|
+
if (outside.length > 0) {
|
|
701
|
+
const ids = taskIds.length > 0 ? taskIds.join(', ') : citedAgainst.map((task) => task.id).join(', ');
|
|
702
|
+
return fail('cites production path "' + outside[0] + '", which is not on the decomposition file list for ' + ids + '.');
|
|
703
|
+
}
|
|
704
|
+
return null;
|
|
705
|
+
} catch (error) {
|
|
706
|
+
return fail('production file-list check failed (' + (error && error.message ? error.message : error) + ').');
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
|
|
293
710
|
// A2: a `completed` receipt must cite evidence the harness can inspect. Order is
|
|
294
711
|
// the message order — the first failing predicate wins, so the operator sees one
|
|
295
712
|
// actionable line. `authoritativePaths[]` stays task-dir-relative; external
|
|
296
|
-
// references belong in `evidencePaths[]`.
|
|
713
|
+
// references belong in `evidencePaths[]`. The task-folder checks below stay in
|
|
714
|
+
// place. A later production evidencePaths check uses the decomposition file list
|
|
715
|
+
// only when that list column exists.
|
|
297
716
|
function validateCompletedArtifact(entry) {
|
|
298
717
|
const artifactId = entry && entry.id ? entry.id : '(unnamed)';
|
|
299
718
|
const entryStatus = entry && entry.status;
|
|
@@ -325,6 +744,8 @@ function validateCompletedArtifact(entry) {
|
|
|
325
744
|
}
|
|
326
745
|
}
|
|
327
746
|
}
|
|
747
|
+
const productionListError = productionWriteListError(entry);
|
|
748
|
+
if (productionListError) return productionListError;
|
|
328
749
|
return null;
|
|
329
750
|
}
|
|
330
751
|
|
|
@@ -494,6 +915,309 @@ function recordSkippedStep(step, stepIndex) {
|
|
|
494
915
|
}
|
|
495
916
|
}
|
|
496
917
|
|
|
918
|
+
// Living task files and the hook ledger stay put. A completed entry's other markdown is the body that leaves the default read.
|
|
919
|
+
const CLOSED_BODY_KEEP = new Set([
|
|
920
|
+
'brief.md',
|
|
921
|
+
'decomposition.md',
|
|
922
|
+
'goal.md',
|
|
923
|
+
'prompt.md',
|
|
924
|
+
'prompt-log.md',
|
|
925
|
+
'pipeline.json',
|
|
926
|
+
'implementation.md',
|
|
927
|
+
'.memlog.md',
|
|
928
|
+
'focus.md',
|
|
929
|
+
'status.json',
|
|
930
|
+
'metrics.json',
|
|
931
|
+
'artifact-manifest.json',
|
|
932
|
+
'overlay-scope.json',
|
|
933
|
+
]);
|
|
934
|
+
|
|
935
|
+
function closedMarkdownBody(dir, cited) {
|
|
936
|
+
if (typeof cited !== 'string') return null;
|
|
937
|
+
const value = cited.trim();
|
|
938
|
+
if (!value || path.isAbsolute(value)) return null;
|
|
939
|
+
const resolved = path.resolve(dir, value);
|
|
940
|
+
const relative = path.relative(dir, resolved);
|
|
941
|
+
if (!relative || relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)) return null;
|
|
942
|
+
const normalized = relative.split(path.sep).join('/');
|
|
943
|
+
if (!/\.md$/i.test(normalized) || normalized.startsWith('archive/')) return null;
|
|
944
|
+
const base = normalized.slice(normalized.lastIndexOf('/') + 1);
|
|
945
|
+
if (CLOSED_BODY_KEEP.has(base) || CLOSED_BODY_KEEP.has(normalized)) return null;
|
|
946
|
+
return { resolved, base };
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
function archiveClosedBody(dir, date, id, body) {
|
|
950
|
+
const archiveDir = path.join(dir, 'archive', date);
|
|
951
|
+
fs.mkdirSync(archiveDir, { recursive: true });
|
|
952
|
+
let name = body.base;
|
|
953
|
+
let destination = path.join(archiveDir, name);
|
|
954
|
+
if (fs.existsSync(destination)) {
|
|
955
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(id)) return null;
|
|
956
|
+
name = id + '--' + body.base;
|
|
957
|
+
destination = path.join(archiveDir, name);
|
|
958
|
+
}
|
|
959
|
+
if (fs.existsSync(destination)) return null;
|
|
960
|
+
fs.renameSync(body.resolved, destination);
|
|
961
|
+
return 'archive/' + date + '/' + name;
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
function appendMemlogEvent(dir, text) {
|
|
965
|
+
const memlogPath = path.join(dir, '.memlog.md');
|
|
966
|
+
const line = '- `event`: ' + text + '\n';
|
|
967
|
+
let existing = '';
|
|
968
|
+
try { existing = fs.readFileSync(memlogPath, 'utf8'); } catch { existing = ''; }
|
|
969
|
+
if (existing.includes(text)) return existing;
|
|
970
|
+
const prefix = existing.length > 0 && !existing.endsWith('\n') ? '\n' : '';
|
|
971
|
+
fs.appendFileSync(memlogPath, prefix + line);
|
|
972
|
+
return existing + prefix + line;
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
function writeJsonFile(filePath, value) {
|
|
976
|
+
const temporary = filePath + '.' + String(process.pid) + '.tmp';
|
|
977
|
+
const fd = fs.openSync(temporary, 'w');
|
|
978
|
+
try {
|
|
979
|
+
fs.writeSync(fd, JSON.stringify(value, null, 2) + '\n');
|
|
980
|
+
} finally {
|
|
981
|
+
fs.closeSync(fd);
|
|
982
|
+
}
|
|
983
|
+
fs.renameSync(temporary, filePath);
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
function compactClosedManifestBodies(dir, closedOn) {
|
|
987
|
+
const date = typeof closedOn === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(closedOn)
|
|
988
|
+
? closedOn
|
|
989
|
+
: new Date().toISOString().slice(0, 10);
|
|
990
|
+
const manifestPath = path.join(dir, 'artifact-manifest.json');
|
|
991
|
+
let manifest;
|
|
992
|
+
try {
|
|
993
|
+
manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
|
|
994
|
+
} catch {
|
|
995
|
+
return { moved: [] };
|
|
996
|
+
}
|
|
997
|
+
const slugBefore = manifest.slug;
|
|
998
|
+
const artifacts = Array.isArray(manifest.artifacts) ? manifest.artifacts : [];
|
|
999
|
+
let memlog = '';
|
|
1000
|
+
try { memlog = fs.readFileSync(path.join(dir, '.memlog.md'), 'utf8'); } catch { memlog = ''; }
|
|
1001
|
+
let manifestChanged = false;
|
|
1002
|
+
const moved = [];
|
|
1003
|
+
for (let index = 0; index < artifacts.length; index += 1) {
|
|
1004
|
+
const entry = artifacts[index];
|
|
1005
|
+
if (!entry || entry.status !== 'completed' || typeof entry.id !== 'string' || !entry.id) continue;
|
|
1006
|
+
const marker = 'closed manifest artifact ' + entry.id + ';';
|
|
1007
|
+
if (memlog.includes(marker)) continue;
|
|
1008
|
+
const cited = Array.isArray(entry.authoritativePaths) ? entry.authoritativePaths.slice() : [];
|
|
1009
|
+
const relocated = [];
|
|
1010
|
+
for (let pathIndex = 0; pathIndex < cited.length; pathIndex += 1) {
|
|
1011
|
+
const body = closedMarkdownBody(dir, cited[pathIndex]);
|
|
1012
|
+
if (!body) continue;
|
|
1013
|
+
let stat = null;
|
|
1014
|
+
try { stat = fs.statSync(body.resolved); } catch { stat = null; }
|
|
1015
|
+
if (!stat || !stat.isFile()) continue;
|
|
1016
|
+
let content = '';
|
|
1017
|
+
try { content = fs.readFileSync(body.resolved, 'utf8'); } catch { content = ''; }
|
|
1018
|
+
if (!/\S/.test(content)) continue;
|
|
1019
|
+
const archived = archiveClosedBody(dir, date, entry.id, body);
|
|
1020
|
+
if (!archived) continue;
|
|
1021
|
+
cited[pathIndex] = archived;
|
|
1022
|
+
relocated.push(archived);
|
|
1023
|
+
moved.push(archived);
|
|
1024
|
+
manifestChanged = true;
|
|
1025
|
+
}
|
|
1026
|
+
if (relocated.length > 0) entry.authoritativePaths = cited;
|
|
1027
|
+
let archiveHint = relocated.length > 0 ? 'archive/' + date + '/' : '';
|
|
1028
|
+
if (!archiveHint) {
|
|
1029
|
+
for (let pathIndex = 0; pathIndex < cited.length; pathIndex += 1) {
|
|
1030
|
+
const value = typeof cited[pathIndex] === 'string' ? cited[pathIndex].trim() : '';
|
|
1031
|
+
const match = /^archive\/\d{4}-\d{2}-\d{2}\//.exec(value);
|
|
1032
|
+
if (match) {
|
|
1033
|
+
archiveHint = match[0];
|
|
1034
|
+
break;
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
const text = archiveHint
|
|
1039
|
+
? 'closed manifest artifact ' + entry.id + '; body archived under ' + archiveHint
|
|
1040
|
+
: 'closed manifest artifact ' + entry.id + '; no bulky markdown body moved';
|
|
1041
|
+
memlog = appendMemlogEvent(dir, text);
|
|
1042
|
+
}
|
|
1043
|
+
if (manifest.slug !== slugBefore) manifest.slug = slugBefore;
|
|
1044
|
+
if (manifestChanged) writeJsonFile(manifestPath, manifest);
|
|
1045
|
+
return { moved };
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
function projectResumeArtifact(entry) {
|
|
1049
|
+
if (!entry || typeof entry !== 'object') return entry;
|
|
1050
|
+
if (entry.status !== 'completed') return entry;
|
|
1051
|
+
return {
|
|
1052
|
+
id: entry.id,
|
|
1053
|
+
status: entry.status,
|
|
1054
|
+
authoritativePaths: Array.isArray(entry.authoritativePaths) ? entry.authoritativePaths : [],
|
|
1055
|
+
};
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
function defaultResumeRead(dir) {
|
|
1059
|
+
const chunks = [];
|
|
1060
|
+
try { chunks.push(fs.readFileSync(path.join(dir, 'focus.md'), 'utf8')); } catch {}
|
|
1061
|
+
try {
|
|
1062
|
+
const manifest = JSON.parse(fs.readFileSync(path.join(dir, 'artifact-manifest.json'), 'utf8'));
|
|
1063
|
+
const artifacts = Array.isArray(manifest.artifacts) ? manifest.artifacts : [];
|
|
1064
|
+
const projected = [];
|
|
1065
|
+
for (let index = 0; index < artifacts.length; index += 1) {
|
|
1066
|
+
projected.push(projectResumeArtifact(artifacts[index]));
|
|
1067
|
+
}
|
|
1068
|
+
chunks.push(JSON.stringify({ slug: manifest.slug, artifacts: projected }));
|
|
1069
|
+
} catch {}
|
|
1070
|
+
try { chunks.push(fs.readFileSync(path.join(dir, '.memlog.md'), 'utf8')); } catch {}
|
|
1071
|
+
return chunks.join('\n');
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
function archiveIndexLine(dir) {
|
|
1075
|
+
const root = path.join(dir, 'archive');
|
|
1076
|
+
let names = [];
|
|
1077
|
+
try { names = fs.readdirSync(root); } catch { names = []; }
|
|
1078
|
+
const dates = [];
|
|
1079
|
+
for (let index = 0; index < names.length; index += 1) {
|
|
1080
|
+
const name = names[index];
|
|
1081
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(name)) continue;
|
|
1082
|
+
let stat = null;
|
|
1083
|
+
try { stat = fs.statSync(path.join(root, name)); } catch { stat = null; }
|
|
1084
|
+
if (stat && stat.isDirectory()) dates.push(name);
|
|
1085
|
+
}
|
|
1086
|
+
dates.sort();
|
|
1087
|
+
if (dates.length === 0) return '- archive index: (none)';
|
|
1088
|
+
const parts = [];
|
|
1089
|
+
for (let index = 0; index < dates.length; index += 1) parts.push('archive/' + dates[index] + '/');
|
|
1090
|
+
return '- archive index: ' + parts.join(', ');
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
function focusDigestMarkdown(dir, statusSnapshot) {
|
|
1094
|
+
const snapshot = statusSnapshot && typeof statusSnapshot === 'object' ? statusSnapshot : {};
|
|
1095
|
+
const slugValue = typeof snapshot.slug === 'string' ? snapshot.slug : '';
|
|
1096
|
+
const stepIndex = Number.isInteger(snapshot.pipelineIndex) ? snapshot.pipelineIndex : 0;
|
|
1097
|
+
const incomplete = [];
|
|
1098
|
+
try {
|
|
1099
|
+
const manifest = JSON.parse(fs.readFileSync(path.join(dir, 'artifact-manifest.json'), 'utf8'));
|
|
1100
|
+
const artifacts = Array.isArray(manifest.artifacts) ? manifest.artifacts : [];
|
|
1101
|
+
for (let index = 0; index < artifacts.length; index += 1) {
|
|
1102
|
+
const artifact = artifacts[index];
|
|
1103
|
+
if (!artifact || artifact.status === 'completed') continue;
|
|
1104
|
+
const id = typeof artifact.id === 'string' ? artifact.id : '(no id)';
|
|
1105
|
+
const cited = Array.isArray(artifact.authoritativePaths) ? artifact.authoritativePaths : [];
|
|
1106
|
+
const paths = [];
|
|
1107
|
+
for (let pathIndex = 0; pathIndex < cited.length; pathIndex += 1) {
|
|
1108
|
+
if (typeof cited[pathIndex] === 'string') paths.push(cited[pathIndex]);
|
|
1109
|
+
}
|
|
1110
|
+
incomplete.push({ id, paths });
|
|
1111
|
+
}
|
|
1112
|
+
} catch {}
|
|
1113
|
+
let lastEvent = '(none)';
|
|
1114
|
+
try {
|
|
1115
|
+
const raw = fs.readFileSync(path.join(dir, '.memlog.md'), 'utf8');
|
|
1116
|
+
const lines = raw.split(/\r?\n/);
|
|
1117
|
+
const tickEvent = /`event`:\s*(.*)$/;
|
|
1118
|
+
const bareEvent = /(?:^|\s)event:\s*(.*)$/;
|
|
1119
|
+
for (let index = lines.length - 1; index >= 0; index -= 1) {
|
|
1120
|
+
const line = lines[index];
|
|
1121
|
+
let matched = tickEvent.exec(line);
|
|
1122
|
+
if (!matched) matched = bareEvent.exec(line);
|
|
1123
|
+
if (matched && matched[1].trim()) {
|
|
1124
|
+
lastEvent = matched[1].trim();
|
|
1125
|
+
break;
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
} catch {}
|
|
1129
|
+
let nextGate = 'none';
|
|
1130
|
+
if (snapshot.awaitingHumanGate === true || snapshot.state === 'awaiting_approval') {
|
|
1131
|
+
nextGate = 'human gate — /task-continue ' + slugValue;
|
|
1132
|
+
} else {
|
|
1133
|
+
try {
|
|
1134
|
+
const pipeline = JSON.parse(fs.readFileSync(path.join(dir, 'pipeline.json'), 'utf8'));
|
|
1135
|
+
const steps = Array.isArray(pipeline.steps) ? pipeline.steps : [];
|
|
1136
|
+
const gates = Array.isArray(pipeline.humanGates) ? pipeline.humanGates : [];
|
|
1137
|
+
for (let index = stepIndex; index < steps.length; index += 1) {
|
|
1138
|
+
const step = steps[index];
|
|
1139
|
+
const agents = !step ? [] : (Array.isArray(step.agent) ? step.agent : [step.agent]);
|
|
1140
|
+
let hit = '';
|
|
1141
|
+
for (let agentIndex = 0; agentIndex < agents.length; agentIndex += 1) {
|
|
1142
|
+
const agent = agents[agentIndex];
|
|
1143
|
+
if (typeof agent === 'string' && gates.indexOf('after:' + agent) !== -1) {
|
|
1144
|
+
hit = agent;
|
|
1145
|
+
break;
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
if (hit) {
|
|
1149
|
+
const stepId = step && typeof step.id === 'string' ? step.id : 'step-' + String(index);
|
|
1150
|
+
nextGate = 'after:' + hit + ' (step ' + stepId + ', index ' + String(index) + ')';
|
|
1151
|
+
break;
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
} catch {}
|
|
1155
|
+
}
|
|
1156
|
+
const pathLines = [];
|
|
1157
|
+
if (incomplete.length === 0) pathLines.push(' - (none)');
|
|
1158
|
+
else {
|
|
1159
|
+
for (let index = 0; index < incomplete.length; index += 1) {
|
|
1160
|
+
const item = incomplete[index];
|
|
1161
|
+
if (item.paths.length === 0) pathLines.push(' - ' + item.id + ': (none)');
|
|
1162
|
+
else {
|
|
1163
|
+
for (let pathIndex = 0; pathIndex < item.paths.length; pathIndex += 1) {
|
|
1164
|
+
pathLines.push(' - ' + item.id + ': ' + item.paths[pathIndex]);
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
let readyLine = '- decomposition ready set: (none)';
|
|
1170
|
+
try {
|
|
1171
|
+
const report = readDecompositionReadySet(dir);
|
|
1172
|
+
const ids = Array.isArray(report.ready) ? report.ready : [];
|
|
1173
|
+
readyLine = '- decomposition ready set: ' + (ids.length > 0 ? ids.join(', ') : '(none)');
|
|
1174
|
+
} catch {
|
|
1175
|
+
readyLine = '- decomposition ready set: (none)';
|
|
1176
|
+
}
|
|
1177
|
+
const head = [
|
|
1178
|
+
'# focus.md',
|
|
1179
|
+
'',
|
|
1180
|
+
'View only. `status.json`, `metrics.json`, `artifact-manifest.json`, and `.memlog.md` stay the system of record.',
|
|
1181
|
+
'',
|
|
1182
|
+
'- slug: ' + slugValue,
|
|
1183
|
+
'- pipeline step index: ' + String(stepIndex),
|
|
1184
|
+
readyLine,
|
|
1185
|
+
archiveIndexLine(dir),
|
|
1186
|
+
'- incomplete authoritative paths:',
|
|
1187
|
+
];
|
|
1188
|
+
const tail = [
|
|
1189
|
+
'- last memlog event: ' + lastEvent,
|
|
1190
|
+
'- next gate: ' + nextGate,
|
|
1191
|
+
];
|
|
1192
|
+
let pathBudget = 99 - head.length - tail.length;
|
|
1193
|
+
if (pathBudget < 1) pathBudget = 1;
|
|
1194
|
+
let kept = pathLines;
|
|
1195
|
+
if (pathLines.length > pathBudget) {
|
|
1196
|
+
const room = pathBudget - 1;
|
|
1197
|
+
kept = pathLines.slice(0, room);
|
|
1198
|
+
const omitted = pathLines.length - kept.length;
|
|
1199
|
+
kept.push(' - (' + String(omitted) + ' lines omitted to stay under 100)');
|
|
1200
|
+
}
|
|
1201
|
+
return head.concat(kept, tail).join('\n') + '\n';
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
function writeFocusDigest() {
|
|
1205
|
+
const focusPath = path.join(taskDir, 'focus.md');
|
|
1206
|
+
const temporary = focusPath + '.' + String(process.pid) + '.' + String(Date.now()) + '.tmp';
|
|
1207
|
+
try {
|
|
1208
|
+
const markdown = focusDigestMarkdown(taskDir, status);
|
|
1209
|
+
const fd = fs.openSync(temporary, 'w');
|
|
1210
|
+
try {
|
|
1211
|
+
fs.writeSync(fd, markdown);
|
|
1212
|
+
try { fs.fsyncSync(fd); } catch {}
|
|
1213
|
+
} finally {
|
|
1214
|
+
fs.closeSync(fd);
|
|
1215
|
+
}
|
|
1216
|
+
fs.renameSync(temporary, focusPath);
|
|
1217
|
+
} catch {
|
|
1218
|
+
try { fs.unlinkSync(temporary); } catch {}
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
497
1221
|
|
|
498
1222
|
function writeStatus(next) {
|
|
499
1223
|
status = { ...status, ...next, slug, updatedAt: now };
|
|
@@ -510,6 +1234,11 @@ function writeStatus(next) {
|
|
|
510
1234
|
fs.closeSync(fd);
|
|
511
1235
|
}
|
|
512
1236
|
fs.renameSync(temporary, statusPath);
|
|
1237
|
+
// Closed bodies move after the checkpoint lands. A compaction miss must not roll status.json back.
|
|
1238
|
+
try { compactClosedManifestBodies(taskDir, now.slice(0, 10)); } catch {}
|
|
1239
|
+
// focus.md is a view of this checkpoint. It is written after status.json
|
|
1240
|
+
// lands so a digest failure cannot roll the checkpoint back.
|
|
1241
|
+
writeFocusDigest();
|
|
513
1242
|
}
|
|
514
1243
|
|
|
515
1244
|
function out(message) {
|
|
@@ -672,7 +1401,8 @@ function handoffForWave(units, waveId) {
|
|
|
672
1401
|
`Invoke IN PARALLEL (one message, multiple Task calls): ${labels.join(' AND ')} for slug "${slug}"${waveId ? ` (waveId=${waveId})` : ''}. ` +
|
|
673
1402
|
`Each agent writes its artifact and owned receipt; the hook records slot joins from stops. Do not mutate status.json lifecycle fields. ` +
|
|
674
1403
|
`Artifact inputs: ${inputIds.length > 0 ? inputIds.join(', ') : 'manifest defaults'}; owned output IDs: ${outputIds.join('; ')}. ` +
|
|
675
|
-
`Metrics attemptIds: ${attemptIds.join('; ')}. If the hook cannot identify a parallel stop, append a minimal { attemptId, outcome } receipt to .metrics-receipts.json; do not calculate duration. ${receiptPathClause()}`
|
|
1404
|
+
`Metrics attemptIds: ${attemptIds.join('; ')}. If the hook cannot identify a parallel stop, append a minimal { attemptId, outcome } receipt to .metrics-receipts.json; do not calculate duration. ${receiptPathClause()}` +
|
|
1405
|
+
decompositionReadyClause(units.map((unit) => steps[unit.stepIndex]))
|
|
676
1406
|
);
|
|
677
1407
|
}
|
|
678
1408
|
function blockedNotice(blockedIndex, agent) {
|
|
@@ -708,6 +1438,9 @@ function dispatchReadyWave(prefixMessage) {
|
|
|
708
1438
|
// Slot-filtered dispatch: only unsatisfied (stepIndex, agent) slots are invoked.
|
|
709
1439
|
const units = wave.flatMap((stepIndex) => unsatisfiedAgents(stepIndex).map((agent) => ({ stepIndex, agent })));
|
|
710
1440
|
if (units.length === 0) return false;
|
|
1441
|
+
const unitAgents = units.map((unit) => unit.agent);
|
|
1442
|
+
refuseImplementationStart(unitAgents, (agent) => implementationDebugRetry(agent));
|
|
1443
|
+
recordAllowedDebugRetries(unitAgents);
|
|
711
1444
|
const first = units[0].stepIndex;
|
|
712
1445
|
const waveId = `${status.metricsRunId || slug}:wave-${first}`;
|
|
713
1446
|
for (const unit of units) activateAttempts(steps[unit.stepIndex], unit.stepIndex, units.length > 1 ? waveId : null, [unit.agent]);
|
|
@@ -855,10 +1588,165 @@ function artifactHandoff(step, agent) {
|
|
|
855
1588
|
return ` Artifact inputs: ${inputIds}; owned output ID: ${artifactOutputIdFor(step, agent)}. Bind the terminal receipt to the supplied attemptId. ${receiptPathClause()}`;
|
|
856
1589
|
}
|
|
857
1590
|
|
|
1591
|
+
// <<<implementation-rail>>>
|
|
1592
|
+
// Opt-in. Omitted, "off", and non-production intents stay off. Only "on" applies.
|
|
1593
|
+
function testBeforeHandoffRule() {
|
|
1594
|
+
return 'Include unit tests for mappers/logic before handoff.';
|
|
1595
|
+
}
|
|
1596
|
+
function railOnHandoffClause() {
|
|
1597
|
+
return ' Strict implementation rail: write a failing test before production edits; use a branch or worktree before the first implementation task; run code-reviewer between decomposition tasks; debug retries for this handoff are capped at two.';
|
|
1598
|
+
}
|
|
1599
|
+
function implementationRailApplies(pipeline) {
|
|
1600
|
+
if (!pipeline || typeof pipeline !== 'object') return false;
|
|
1601
|
+
const intent = typeof pipeline.intent === 'string' ? pipeline.intent : '';
|
|
1602
|
+
const level = pipeline.taskLevel;
|
|
1603
|
+
if (level === 'L0' || level === 0 || level === '0') return false;
|
|
1604
|
+
if (intent === 'docs-only' || intent === 'research' || intent === 'preset-only' || intent === 'spike') return false;
|
|
1605
|
+
if (pipeline.presetOnly === true) return false;
|
|
1606
|
+
return pipeline.implementationRail === 'on';
|
|
1607
|
+
}
|
|
1608
|
+
function briefHasOpenClarificationMarker(text) {
|
|
1609
|
+
if (typeof text !== 'string' || text.length === 0) return false;
|
|
1610
|
+
const lines = text.split(/\r?\n/);
|
|
1611
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
1612
|
+
let body = lines[index].trim().replace(/^(?:>\s*)+/, '');
|
|
1613
|
+
body = body.replace(/^(?:[-*+]|\d+[.)])\s+/, '');
|
|
1614
|
+
if (body.startsWith('[NEEDS CLARIFICATION]')) return true;
|
|
1615
|
+
}
|
|
1616
|
+
return false;
|
|
1617
|
+
}
|
|
1618
|
+
function implementationHandoffDecision(input) {
|
|
1619
|
+
const agent = input && input.agent;
|
|
1620
|
+
const applies = agent === 'feature-developer' && implementationRailApplies(input && input.pipeline);
|
|
1621
|
+
if (!applies) {
|
|
1622
|
+
return {
|
|
1623
|
+
start: true,
|
|
1624
|
+
rail: 'off',
|
|
1625
|
+
handoffRule: agent === 'feature-developer' ? testBeforeHandoffRule() : null,
|
|
1626
|
+
constraints: [],
|
|
1627
|
+
};
|
|
1628
|
+
}
|
|
1629
|
+
if (briefHasOpenClarificationMarker(input && input.briefText)) {
|
|
1630
|
+
return { start: false, rail: 'on', reason: 'open-marker', handoffRule: testBeforeHandoffRule(), constraints: [] };
|
|
1631
|
+
}
|
|
1632
|
+
const debugRetries = Number(input && input.debugRetryCount) || 0;
|
|
1633
|
+
if (input && input.debugRetry === true && debugRetries >= 2) {
|
|
1634
|
+
return { start: false, rail: 'on', reason: 'debug-retry-cap', handoffRule: testBeforeHandoffRule(), constraints: [] };
|
|
1635
|
+
}
|
|
1636
|
+
return {
|
|
1637
|
+
start: true,
|
|
1638
|
+
rail: 'on',
|
|
1639
|
+
handoffRule: testBeforeHandoffRule(),
|
|
1640
|
+
constraints: [
|
|
1641
|
+
'failing test before production edits',
|
|
1642
|
+
'branch or worktree before the first implementation task',
|
|
1643
|
+
'code-reviewer between decomposition tasks',
|
|
1644
|
+
'debug retries capped at two',
|
|
1645
|
+
],
|
|
1646
|
+
};
|
|
1647
|
+
}
|
|
1648
|
+
// <<<implementation-rail-end>>>
|
|
1649
|
+
|
|
1650
|
+
function readPipelineRecord() {
|
|
1651
|
+
try {
|
|
1652
|
+
return JSON.parse(fs.readFileSync(pipelinePath, 'utf8'));
|
|
1653
|
+
} catch {
|
|
1654
|
+
return null;
|
|
1655
|
+
}
|
|
1656
|
+
}
|
|
1657
|
+
function readBriefText() {
|
|
1658
|
+
try {
|
|
1659
|
+
return fs.readFileSync(path.join(taskDir, 'brief.md'), 'utf8');
|
|
1660
|
+
} catch {
|
|
1661
|
+
return '';
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
function countDebugImplementationRetries() {
|
|
1665
|
+
try {
|
|
1666
|
+
const metrics = JSON.parse(fs.readFileSync(METRICS_PATH, 'utf8'));
|
|
1667
|
+
const events = Array.isArray(metrics.events) ? metrics.events : [];
|
|
1668
|
+
return events.filter((event) => event && event.type === 'retry_scheduled' && event.nextAgent === 'feature-developer' && event.retryAfterFix === 'debugger').length;
|
|
1669
|
+
} catch {
|
|
1670
|
+
return 0;
|
|
1671
|
+
}
|
|
1672
|
+
}
|
|
1673
|
+
function featureDeveloperAlreadyStarted() {
|
|
1674
|
+
try {
|
|
1675
|
+
const metrics = JSON.parse(fs.readFileSync(METRICS_PATH, 'utf8'));
|
|
1676
|
+
const events = Array.isArray(metrics.events) ? metrics.events : [];
|
|
1677
|
+
return events.some((event) => event && event.type === 'attempt_started' && event.agent === 'feature-developer');
|
|
1678
|
+
} catch {
|
|
1679
|
+
return false;
|
|
1680
|
+
}
|
|
1681
|
+
}
|
|
1682
|
+
function implementationDebugRetry(agent) {
|
|
1683
|
+
return agent === 'feature-developer' && status.currentAgent === 'debugger' && featureDeveloperAlreadyStarted();
|
|
1684
|
+
}
|
|
1685
|
+
function blockImplementationStart(agent, debugRetry) {
|
|
1686
|
+
const decision = implementationHandoffDecision({
|
|
1687
|
+
agent,
|
|
1688
|
+
pipeline: readPipelineRecord(),
|
|
1689
|
+
briefText: readBriefText(),
|
|
1690
|
+
debugRetry: Boolean(debugRetry),
|
|
1691
|
+
debugRetryCount: countDebugImplementationRetries(),
|
|
1692
|
+
});
|
|
1693
|
+
if (decision.start) return null;
|
|
1694
|
+
if (decision.reason === 'debug-retry-cap') {
|
|
1695
|
+
return `Strict implementation rail is on for slug "${slug}". Debug retries for the implementation handoff are capped at two. Do not start implementation.`;
|
|
1696
|
+
}
|
|
1697
|
+
return `Strict implementation rail is on for slug "${slug}" and a [NEEDS CLARIFICATION] marker is open. Do not start implementation.`;
|
|
1698
|
+
}
|
|
1699
|
+
function refuseImplementationStart(agents, debugRetryFor) {
|
|
1700
|
+
const list = Array.isArray(agents) ? agents : [agents];
|
|
1701
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
1702
|
+
const block = blockImplementationStart(list[index], debugRetryFor(list[index]));
|
|
1703
|
+
if (!block) continue;
|
|
1704
|
+
beginHumanGate();
|
|
1705
|
+
writeStatus({
|
|
1706
|
+
state: 'awaiting_approval',
|
|
1707
|
+
phase: 'human_gate',
|
|
1708
|
+
awaitingHumanGate: true,
|
|
1709
|
+
waveSteps: [],
|
|
1710
|
+
waveId: null,
|
|
1711
|
+
retryAfterFix: null,
|
|
1712
|
+
retryAfterFixStepIndex: null,
|
|
1713
|
+
});
|
|
1714
|
+
out(block);
|
|
1715
|
+
process.exit(0);
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
function recordAllowedDebugRetries(agents) {
|
|
1719
|
+
if (!implementationRailApplies(readPipelineRecord())) return;
|
|
1720
|
+
const list = Array.isArray(agents) ? agents : [agents];
|
|
1721
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
1722
|
+
if (!implementationDebugRetry(list[index])) continue;
|
|
1723
|
+
appendMetric({
|
|
1724
|
+
type: 'retry_scheduled',
|
|
1725
|
+
at: now,
|
|
1726
|
+
attemptId: null,
|
|
1727
|
+
nextAgent: 'feature-developer',
|
|
1728
|
+
retryAfterFix: 'debugger',
|
|
1729
|
+
source: 'hook',
|
|
1730
|
+
attributionConfidence: 'high',
|
|
1731
|
+
});
|
|
1732
|
+
}
|
|
1733
|
+
}
|
|
1734
|
+
function railInstructionClause(agent) {
|
|
1735
|
+
const decision = implementationHandoffDecision({
|
|
1736
|
+
agent,
|
|
1737
|
+
pipeline: readPipelineRecord(),
|
|
1738
|
+
briefText: readBriefText(),
|
|
1739
|
+
debugRetry: false,
|
|
1740
|
+
debugRetryCount: 0,
|
|
1741
|
+
});
|
|
1742
|
+
if (decision.rail !== 'on' || !decision.start) return '';
|
|
1743
|
+
return railOnHandoffClause();
|
|
1744
|
+
}
|
|
1745
|
+
|
|
858
1746
|
function handoffForAgent(agent, scope, step = null) {
|
|
859
1747
|
const fn = AGENT_HANDOFF[agent];
|
|
860
1748
|
const handoff = fn ? fn(slug, scope) : `Invoke ${agent} subagent for slug "${slug}". Upsert the owned terminal receipt in artifact-manifest.json; do not mutate status.json lifecycle fields.`;
|
|
861
|
-
return handoff + artifactHandoff(step, agent) + metricsHandoff(agent);
|
|
1749
|
+
return handoff + railInstructionClause(agent) + artifactHandoff(step, agent) + metricsHandoff(agent) + decompositionReadyClause(step ? [step] : []);
|
|
862
1750
|
}
|
|
863
1751
|
|
|
864
1752
|
function handoffForParallelStep(step) {
|
|
@@ -870,7 +1758,8 @@ function handoffForParallelStep(step) {
|
|
|
870
1758
|
`Invoke IN PARALLEL (one message, multiple Task calls): ${agents.join(' AND ')} for slug "${slug}". ` +
|
|
871
1759
|
`Each agent writes its artifact and owned receipt; the hook records parallelCompleted from stops. Do not mutate status.json lifecycle fields. ` +
|
|
872
1760
|
`Artifact inputs: ${Array.isArray(step.artifactInputIds) ? step.artifactInputIds.join(', ') : 'manifest defaults'}; owned output IDs: ${agents.map((agent) => `${agent}=${artifactOutputIdFor(step, agent)}`).join('; ')}. ` +
|
|
873
|
-
`Metrics attemptIds: ${attemptIds.join('; ')}. If the hook cannot identify a parallel stop, append a minimal { attemptId, outcome } receipt to .metrics-receipts.json; do not calculate duration. ${receiptPathClause()}`
|
|
1761
|
+
`Metrics attemptIds: ${attemptIds.join('; ')}. If the hook cannot identify a parallel stop, append a minimal { attemptId, outcome } receipt to .metrics-receipts.json; do not calculate duration. ${receiptPathClause()}` +
|
|
1762
|
+
decompositionReadyClause([step])
|
|
874
1763
|
);
|
|
875
1764
|
}
|
|
876
1765
|
|
|
@@ -1033,6 +1922,8 @@ if (hookInput.action === 'end_human_gate') {
|
|
|
1033
1922
|
const resumeNext = findNextExecutableStep(resumeSteps, resumeStart, taskDir);
|
|
1034
1923
|
if (resumeNext) {
|
|
1035
1924
|
const resumeAgents = getStepAgents(resumeNext.step);
|
|
1925
|
+
refuseImplementationStart(resumeAgents, (agent) => implementationDebugRetry(agent));
|
|
1926
|
+
recordAllowedDebugRetries(resumeAgents);
|
|
1036
1927
|
activateAttempts(resumeNext.step, resumeNext.index);
|
|
1037
1928
|
writeStatus({
|
|
1038
1929
|
pipelineIndex: resumeNext.index,
|
|
@@ -1189,6 +2080,9 @@ function nearestPrecedingStepIndex(agent, fromIndex, fallback) {
|
|
|
1189
2080
|
return match >= 0 ? match : fallback;
|
|
1190
2081
|
}
|
|
1191
2082
|
function scheduleRetry(agent, retryAfterFix, predecessor, explicitStepIndex = null) {
|
|
2083
|
+
if (agent === 'feature-developer') {
|
|
2084
|
+
refuseImplementationStart([agent], () => retryAfterFix === 'debugger');
|
|
2085
|
+
}
|
|
1192
2086
|
const currentIndex = typeof status.pipelineIndex === 'number' ? status.pipelineIndex : 0;
|
|
1193
2087
|
const explicitOk = Number.isInteger(explicitStepIndex) && getStepAgents(steps[explicitStepIndex]).includes(agent);
|
|
1194
2088
|
const stepIndex = explicitOk ? explicitStepIndex : nearestPrecedingStepIndex(agent, currentIndex, -1);
|
|
@@ -1496,6 +2390,8 @@ if (!next) {
|
|
|
1496
2390
|
const { step: nextStep, index: nextIdx } = next;
|
|
1497
2391
|
const nextAgents = getStepAgents(nextStep);
|
|
1498
2392
|
|
|
2393
|
+
refuseImplementationStart(nextAgents, (agent) => implementationDebugRetry(agent));
|
|
2394
|
+
recordAllowedDebugRetries(nextAgents);
|
|
1499
2395
|
activateAttempts(nextStep, nextIdx);
|
|
1500
2396
|
writeStatus({
|
|
1501
2397
|
pipelineIndex: nextIdx,
|
|
@@ -1524,6 +2420,180 @@ const fs = require('fs');
|
|
|
1524
2420
|
const path = require('path');
|
|
1525
2421
|
const { spawnSync } = require('child_process');
|
|
1526
2422
|
|
|
2423
|
+
// <<<standards-draft>>>
|
|
2424
|
+
// Explicit payload only. This postflight never walks the repo and never
|
|
2425
|
+
// creates `.ai.local/rules/`. The same provenance tag does not rewrite an
|
|
2426
|
+
// accepted Gotchas, Patterns, or Decisions line.
|
|
2427
|
+
function standardsDraftTag(provenance) {
|
|
2428
|
+
return '(`' + provenance + '`)';
|
|
2429
|
+
}
|
|
2430
|
+
|
|
2431
|
+
function standardsDraftLineIndex(content, header) {
|
|
2432
|
+
if (content.startsWith(header) && (content.length === header.length || content.charAt(header.length) === '\n')) return 0;
|
|
2433
|
+
const at = content.indexOf('\n' + header + '\n');
|
|
2434
|
+
if (at !== -1) return at + 1;
|
|
2435
|
+
if (content.endsWith('\n' + header)) return content.length - header.length;
|
|
2436
|
+
return -1;
|
|
2437
|
+
}
|
|
2438
|
+
|
|
2439
|
+
function standardsDraftSection(content, name) {
|
|
2440
|
+
const header = '## ' + name;
|
|
2441
|
+
const start = standardsDraftLineIndex(content, header);
|
|
2442
|
+
if (start === -1) return null;
|
|
2443
|
+
const from = start + header.length;
|
|
2444
|
+
const next = content.indexOf('\n## ', from);
|
|
2445
|
+
const end = next === -1 ? content.length : next;
|
|
2446
|
+
return content.slice(start, end);
|
|
2447
|
+
}
|
|
2448
|
+
|
|
2449
|
+
function standardsDraftProtected(content) {
|
|
2450
|
+
const names = ['Language', 'Gotchas', 'Patterns', 'Decisions', 'Advisory index'];
|
|
2451
|
+
let snapshot = '';
|
|
2452
|
+
for (let index = 0; index < names.length; index += 1) {
|
|
2453
|
+
const body = standardsDraftSection(content, names[index]);
|
|
2454
|
+
snapshot += names[index] + '\n' + (body === null ? '' : body) + '\n';
|
|
2455
|
+
}
|
|
2456
|
+
return snapshot;
|
|
2457
|
+
}
|
|
2458
|
+
|
|
2459
|
+
function standardsDraftNormalize(line) {
|
|
2460
|
+
return line.trim().replace(/\s+/g, ' ').replace(/^-\s+/, '').replace(/\s+\(`[^`]*`\)$/, '').toLowerCase();
|
|
2461
|
+
}
|
|
2462
|
+
|
|
2463
|
+
function standardsDraftAccepted(content, text) {
|
|
2464
|
+
const pending = standardsDraftSection(content, 'Pending');
|
|
2465
|
+
let rest = content;
|
|
2466
|
+
if (pending !== null) {
|
|
2467
|
+
const start = content.indexOf(pending);
|
|
2468
|
+
rest = content.slice(0, start) + content.slice(start + pending.length);
|
|
2469
|
+
}
|
|
2470
|
+
const needle = standardsDraftNormalize(text);
|
|
2471
|
+
if (!needle) return false;
|
|
2472
|
+
const lines = rest.split('\n');
|
|
2473
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
2474
|
+
const line = lines[index];
|
|
2475
|
+
if (!/^-\s+\S/.test(line)) continue;
|
|
2476
|
+
if (standardsDraftNormalize(line) === needle) return true;
|
|
2477
|
+
}
|
|
2478
|
+
return false;
|
|
2479
|
+
}
|
|
2480
|
+
|
|
2481
|
+
function standardsDraftAppendPending(content, line) {
|
|
2482
|
+
const header = '## Pending';
|
|
2483
|
+
const start = standardsDraftLineIndex(content, header);
|
|
2484
|
+
if (start === -1) {
|
|
2485
|
+
const sep = content.endsWith('\n') ? '\n' : '\n\n';
|
|
2486
|
+
return content + sep + header + '\n\n' + line + '\n';
|
|
2487
|
+
}
|
|
2488
|
+
const from = start + header.length;
|
|
2489
|
+
const next = content.indexOf('\n## ', from);
|
|
2490
|
+
const end = next === -1 ? content.length : next;
|
|
2491
|
+
let body = content.slice(from, end);
|
|
2492
|
+
const hasBullet = /(^|\n)-\s+\S/.test(body);
|
|
2493
|
+
if (!hasBullet && /(^|\n)-[ \t]*(?=\n|$)/.test(body)) {
|
|
2494
|
+
body = body.replace(/(^|\n)-[ \t]*(?=\n|$)/, '$1' + line);
|
|
2495
|
+
} else if (body.endsWith('\n\n')) {
|
|
2496
|
+
body = body.slice(0, -1) + line + '\n\n';
|
|
2497
|
+
} else if (body.endsWith('\n')) {
|
|
2498
|
+
body = body + line + '\n';
|
|
2499
|
+
} else {
|
|
2500
|
+
body = body + '\n' + line + '\n';
|
|
2501
|
+
}
|
|
2502
|
+
return content.slice(0, from) + body + content.slice(end);
|
|
2503
|
+
}
|
|
2504
|
+
|
|
2505
|
+
function standardsDraftProvenance(draft) {
|
|
2506
|
+
if (!draft || typeof draft.provenance !== 'string') return '';
|
|
2507
|
+
const provenance = draft.provenance.trim();
|
|
2508
|
+
if (/^incident: [A-Za-z0-9][A-Za-z0-9._:-]{0,80}$/.test(provenance)) return provenance;
|
|
2509
|
+
const read = /^read: ([A-Za-z0-9][A-Za-z0-9._/-]{0,160})$/.exec(provenance);
|
|
2510
|
+
if (!read) return '';
|
|
2511
|
+
const parts = read[1].split('/');
|
|
2512
|
+
if (parts.indexOf('..') !== -1 || parts.indexOf('.') !== -1) return '';
|
|
2513
|
+
if (read[1] === '.ai.local/rules' || read[1].indexOf('.ai.local/rules/') === 0) return '';
|
|
2514
|
+
return provenance;
|
|
2515
|
+
}
|
|
2516
|
+
|
|
2517
|
+
function standardsDraftWrite(target, content) {
|
|
2518
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
2519
|
+
const temporary = target + '.' + String(process.pid) + '.tmp';
|
|
2520
|
+
fs.writeFileSync(temporary, content);
|
|
2521
|
+
fs.renameSync(temporary, target);
|
|
2522
|
+
}
|
|
2523
|
+
|
|
2524
|
+
function appendOptionalStandardsDraft(root, draft) {
|
|
2525
|
+
const provenance = standardsDraftProvenance(draft);
|
|
2526
|
+
if (!provenance) return { wrote: false, reason: 'provenance' };
|
|
2527
|
+
const text = draft && typeof draft.text === 'string' ? draft.text.trim() : '';
|
|
2528
|
+
if (!text || text.length > 400 || text.indexOf('\n') !== -1 || text.indexOf('\r') !== -1 || text.indexOf('## ') !== -1) {
|
|
2529
|
+
return { wrote: false, reason: 'text' };
|
|
2530
|
+
}
|
|
2531
|
+
let destination = 'conventions';
|
|
2532
|
+
if (draft.destination != null) {
|
|
2533
|
+
if (draft.destination === 'conventions' || draft.destination === 'rules-library') destination = draft.destination;
|
|
2534
|
+
else return { wrote: false, reason: 'destination' };
|
|
2535
|
+
}
|
|
2536
|
+
const line = '- ' + text + ' ' + standardsDraftTag(provenance);
|
|
2537
|
+
const overlay = path.join(root, '.ai.local');
|
|
2538
|
+
const rulesDir = path.join(overlay, 'rules');
|
|
2539
|
+
const rulesPrefix = rulesDir + path.sep;
|
|
2540
|
+
|
|
2541
|
+
if (destination === 'rules-library') {
|
|
2542
|
+
const stem = draft && typeof draft.stem === 'string' ? draft.stem : '';
|
|
2543
|
+
if (!/^[a-z0-9]+(?:-[a-z0-9]+){0,8}$/.test(stem) || stem.length > 48) {
|
|
2544
|
+
return { wrote: false, reason: 'stem' };
|
|
2545
|
+
}
|
|
2546
|
+
const libraryDir = path.join(overlay, 'rules-library');
|
|
2547
|
+
const target = path.join(libraryDir, stem + '.md');
|
|
2548
|
+
const libraryPrefix = libraryDir + path.sep;
|
|
2549
|
+
if (!target.startsWith(libraryPrefix)) return { wrote: false, reason: 'path' };
|
|
2550
|
+
if (target === rulesDir || target.startsWith(rulesPrefix)) return { wrote: false, reason: 'rules' };
|
|
2551
|
+
let existing = null;
|
|
2552
|
+
try {
|
|
2553
|
+
existing = fs.readFileSync(target, 'utf8');
|
|
2554
|
+
} catch (error) {
|
|
2555
|
+
if (!error || error.code !== 'ENOENT') throw error;
|
|
2556
|
+
}
|
|
2557
|
+
if (existing !== null) {
|
|
2558
|
+
if (existing.indexOf(standardsDraftTag(provenance)) !== -1) {
|
|
2559
|
+
return { wrote: false, reason: 'same-provenance', target: target };
|
|
2560
|
+
}
|
|
2561
|
+
const prefix = existing.endsWith('\n') ? '' : '\n';
|
|
2562
|
+
fs.appendFileSync(target, prefix + line + '\n');
|
|
2563
|
+
return { wrote: true, target: target, mode: 'append-provenance' };
|
|
2564
|
+
}
|
|
2565
|
+
standardsDraftWrite(target, '# ' + stem + '\n\nPending draft. Inactive until a human moves this file into `.ai.local/rules/`.\n\n' + line + '\n');
|
|
2566
|
+
return { wrote: true, target: target, mode: 'create' };
|
|
2567
|
+
}
|
|
2568
|
+
|
|
2569
|
+
const conventionsPath = path.join(overlay, 'conventions.md');
|
|
2570
|
+
if (conventionsPath === rulesDir || conventionsPath.startsWith(rulesPrefix)) {
|
|
2571
|
+
return { wrote: false, reason: 'rules' };
|
|
2572
|
+
}
|
|
2573
|
+
let content = null;
|
|
2574
|
+
try {
|
|
2575
|
+
content = fs.readFileSync(conventionsPath, 'utf8');
|
|
2576
|
+
} catch (error) {
|
|
2577
|
+
if (!error || error.code !== 'ENOENT') throw error;
|
|
2578
|
+
}
|
|
2579
|
+
if (content === null) content = '# Living conventions\n';
|
|
2580
|
+
if (content.indexOf(standardsDraftTag(provenance)) !== -1) {
|
|
2581
|
+
return { wrote: false, reason: 'same-provenance', target: conventionsPath };
|
|
2582
|
+
}
|
|
2583
|
+
const before = standardsDraftProtected(content);
|
|
2584
|
+
const next = standardsDraftAppendPending(content, line);
|
|
2585
|
+
if (standardsDraftProtected(next) !== before) {
|
|
2586
|
+
return { wrote: false, reason: 'protected', target: conventionsPath };
|
|
2587
|
+
}
|
|
2588
|
+
standardsDraftWrite(conventionsPath, next);
|
|
2589
|
+
return {
|
|
2590
|
+
wrote: true,
|
|
2591
|
+
target: conventionsPath,
|
|
2592
|
+
mode: standardsDraftAccepted(content, text) ? 'provenance-only' : 'pending',
|
|
2593
|
+
};
|
|
2594
|
+
}
|
|
2595
|
+
// <<<standards-draft-end>>>
|
|
2596
|
+
|
|
1527
2597
|
let input;
|
|
1528
2598
|
try {
|
|
1529
2599
|
input = JSON.parse(process.env.INPUT || '');
|
|
@@ -1556,6 +2626,12 @@ if (pipeline && (pipeline.profile === 'light' || pipeline.intent === 'spike')) {
|
|
|
1556
2626
|
process.exit(0);
|
|
1557
2627
|
}
|
|
1558
2628
|
|
|
2629
|
+
try {
|
|
2630
|
+
appendOptionalStandardsDraft(process.cwd(), input.standardsDraft);
|
|
2631
|
+
} catch {
|
|
2632
|
+
// A draft failure must not fail the stop, and must not add a WARNING.
|
|
2633
|
+
}
|
|
2634
|
+
|
|
1559
2635
|
if (!fs.existsSync(path.join(process.cwd(), '.ai.local', 'scripts', 'run.mjs'))) {
|
|
1560
2636
|
process.stderr.write(
|
|
1561
2637
|
'WARNING: self-learning loop skipped: .ai.local/scripts/run.mjs is missing (install it with `npx @bonesofspring/ai-rules init <tool> --preset <stack>`)\n',
|