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