@bonesofspring/ai-rules 0.2.63 → 0.2.65
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 +96 -1
- package/README.md +11 -4
- package/bin/cli.js +7 -5
- package/bin/lib/ai-local-drift.js +7 -6
- package/bin/lib/engine-scripts.js +17 -4
- package/bin/lib/engine-upgrade.js +10 -2
- package/bin/lib/manifest-schema.js +12 -0
- package/bin/lib/seed-ai-local-team.js +20 -0
- package/bin/mavis-install.js +4 -3
- package/bin/opencode-install.js +22 -6
- package/bin/zcode-install.js +4 -3
- package/docs/MCP-CATALOG.md +1 -1
- package/docs/OPENCODE-COMPATIBILITY.md +3 -2
- package/docs/OPENCODE.md +22 -2
- package/docs/PRESET-CONTRIBUTION.md +43 -2
- package/docs/TEAM-DB.md +213 -5
- package/docs/openapi/team-db.v1.json +5928 -3045
- package/mcp/defectdojo-mcp.mjs +44 -12
- package/mcp/lib/defectdojo.mjs +57 -2
- package/package.json +27 -15
- package/presets/_shared/ai-local/scripts/aggregate-agent-task-metrics.mjs +279 -0
- package/presets/_shared/ai-local/scripts/process-lease.mjs +576 -0
- package/presets/_shared/ai-local/scripts/processes.mjs +1618 -0
- package/presets/_shared/ai-local/scripts/run.mjs +5 -5
- package/presets/_shared/ai-local/scripts/team-db-api.mjs +784 -7
- package/presets/_shared/ai-local/scripts/team-db-dashboard.mjs +235 -10
- package/presets/_shared/ai-local/scripts/team-db-openapi.mjs +813 -7
- package/presets/_shared/ai-local/scripts/team-db-project.mjs +397 -4
- package/presets/_shared/ai-local/scripts/team-db-scheduler.mjs +86 -10
- package/presets/_shared/ai-local/scripts/team-db-schema.mjs +221 -0
- package/presets/_shared/ai-local/scripts/team-db-task-runner.mjs +567 -0
- package/presets/_shared/ai-local/scripts/team-db-tracker.mjs +2069 -0
- package/presets/_shared/ai-local/scripts/team-db-ui.mjs +750 -0
- package/presets/_shared/ai-local/scripts/team-db.mjs +151 -7
- package/presets/_shared/ai-local/scripts/upstream-research.mjs +3 -0
- package/presets/_shared/core/agent-team/agent-task-metrics.md +7 -2
- package/presets/_shared/core/agent-team/agent-team-orchestrator.md +2 -1
- package/presets/_shared/hooks/chain-team-phases.sh.tmpl +314 -1
- package/presets/_shared/hooks/guard-shell-command.mjs.tmpl +40 -2
- package/presets/_shared/hooks/run-hook.mjs +2 -1
- package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +314 -1
- package/presets/claude/android-kotlin/hooks/guard-shell-command.mjs +41 -2
- package/presets/claude/android-kotlin/hooks/run-hook.mjs +2 -1
- package/presets/claude/android-kotlin/rules/tooling-and-review/agent-team-orchestrator.md +2 -1
- package/presets/claude/android-kotlin/settings.json +6 -1
- package/presets/claude/go/hooks/chain-team-phases.sh +314 -1
- package/presets/claude/go/hooks/guard-shell-command.mjs +41 -2
- package/presets/claude/go/hooks/run-hook.mjs +2 -1
- package/presets/claude/go/rules/tooling-and-review/agent-team-orchestrator.md +2 -1
- package/presets/claude/go/settings.json +6 -1
- package/presets/claude/ios-swift/hooks/chain-team-phases.sh +314 -1
- package/presets/claude/ios-swift/hooks/guard-shell-command.mjs +41 -2
- package/presets/claude/ios-swift/hooks/run-hook.mjs +2 -1
- package/presets/claude/ios-swift/rules/tooling-and-review/agent-team-orchestrator.md +2 -1
- package/presets/claude/ios-swift/settings.json +6 -1
- package/presets/claude/java/hooks/chain-team-phases.sh +314 -1
- package/presets/claude/java/hooks/guard-shell-command.mjs +41 -2
- package/presets/claude/java/hooks/run-hook.mjs +2 -1
- package/presets/claude/java/rules/tooling-and-review/agent-team-orchestrator.md +2 -1
- package/presets/claude/java/settings.json +6 -1
- package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +314 -1
- package/presets/claude/mcp-ts/hooks/guard-shell-command.mjs +41 -2
- package/presets/claude/mcp-ts/hooks/run-hook.mjs +2 -1
- package/presets/claude/mcp-ts/rules/tooling-and-review/agent-team-orchestrator.md +2 -1
- package/presets/claude/mcp-ts/settings.json +6 -1
- package/presets/claude/mol/hooks/chain-team-phases.sh +314 -1
- package/presets/claude/mol/hooks/guard-shell-command.mjs +41 -2
- package/presets/claude/mol/hooks/run-hook.mjs +2 -1
- package/presets/claude/mol/rules/tooling-and-review/agent-team-orchestrator.md +2 -1
- package/presets/claude/mol/settings.json +6 -1
- package/presets/claude/next/MCP.md +2 -0
- package/presets/claude/next/REPO_AGENTS.md +2 -0
- package/presets/claude/next/agents/build-verifier.md +1 -1
- package/presets/claude/next/agents/ci-investigator.md +3 -0
- package/presets/claude/next/agents/code-reviewer.md +1 -0
- package/presets/claude/next/agents/debugger.md +3 -0
- package/presets/claude/next/agents/feature-developer.md +3 -0
- package/presets/claude/next/agents/mockup-reviewer.md +4 -1
- package/presets/claude/next/agents/performance-auditor.md +2 -0
- package/presets/claude/next/agents/playwright-test-generator.md +3 -0
- package/presets/claude/next/agents/playwright-test-healer.md +3 -0
- package/presets/claude/next/agents/playwright-test-planner.md +3 -0
- package/presets/claude/next/agents/qa-tester.md +3 -0
- package/presets/claude/next/agents/task-analyst.md +2 -0
- package/presets/claude/next/commands/README.md +6 -0
- package/presets/claude/next/commands/task.md +7 -1
- package/presets/claude/next/commands/technical-retro.md +7 -1
- package/presets/claude/next/commands/ui-start.md +78 -0
- package/presets/claude/next/commands/ui-stop.md +71 -0
- package/presets/claude/next/commands/upstream-research.md +1 -1
- package/presets/claude/next/hooks/chain-team-phases.sh +314 -1
- package/presets/claude/next/hooks/guard-shell-command.mjs +41 -2
- package/presets/claude/next/hooks/run-hook.mjs +2 -1
- package/presets/claude/next/rules/README.md +2 -1
- package/presets/claude/next/rules/stack/next-app-core.md +1 -0
- package/presets/claude/next/rules/tooling-and-review/agent-team-orchestrator.md +2 -1
- package/presets/claude/next/rules/tooling-and-review/dev-process-lifecycle.md +43 -0
- package/presets/claude/next/settings.json +6 -1
- package/presets/claude/next/skills/figma-fidelity/SKILL.md +4 -1
- package/presets/claude/next/skills/mockup-review/SKILL.md +4 -0
- package/presets/claude/next/team/README.md +5 -1
- package/presets/claude/next/team/upstream/jobs.json +34 -0
- package/presets/claude/nuxt/hooks/chain-team-phases.sh +314 -1
- package/presets/claude/nuxt/hooks/guard-shell-command.mjs +41 -2
- package/presets/claude/nuxt/hooks/run-hook.mjs +2 -1
- package/presets/claude/nuxt/rules/tooling-and-review/agent-team-orchestrator.md +2 -1
- package/presets/claude/nuxt/settings.json +6 -1
- package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +314 -1
- package/presets/claude/php-hexagonal/hooks/guard-shell-command.mjs +41 -2
- package/presets/claude/php-hexagonal/hooks/run-hook.mjs +2 -1
- package/presets/claude/php-hexagonal/rules/tooling-and-review/agent-team-orchestrator.md +2 -1
- package/presets/claude/php-hexagonal/settings.json +6 -1
- package/presets/claude/php-laravel/hooks/chain-team-phases.sh +315 -2
- package/presets/claude/php-laravel/hooks/guard-shell-command.mjs +41 -2
- package/presets/claude/php-laravel/hooks/run-hook.mjs +2 -1
- package/presets/claude/php-laravel/rules/tooling-and-review/agent-team-orchestrator.md +2 -1
- package/presets/claude/php-laravel/settings.json +6 -1
- package/presets/claude/svelte/hooks/chain-team-phases.sh +314 -1
- package/presets/claude/svelte/hooks/guard-shell-command.mjs +41 -2
- package/presets/claude/svelte/hooks/run-hook.mjs +2 -1
- package/presets/claude/svelte/rules/tooling-and-review/agent-team-orchestrator.md +2 -1
- package/presets/claude/svelte/settings.json +6 -1
- package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +314 -1
- package/presets/cursor/android-kotlin/hooks/guard-shell-command.mjs +41 -2
- package/presets/cursor/android-kotlin/hooks/run-hook.mjs +2 -1
- package/presets/cursor/go/hooks/chain-team-phases.sh +314 -1
- package/presets/cursor/go/hooks/guard-shell-command.mjs +41 -2
- package/presets/cursor/go/hooks/run-hook.mjs +2 -1
- package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +314 -1
- package/presets/cursor/ios-swift/hooks/guard-shell-command.mjs +41 -2
- package/presets/cursor/ios-swift/hooks/run-hook.mjs +2 -1
- package/presets/cursor/java/hooks/chain-team-phases.sh +314 -1
- package/presets/cursor/java/hooks/guard-shell-command.mjs +41 -2
- package/presets/cursor/java/hooks/run-hook.mjs +2 -1
- package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +314 -1
- package/presets/cursor/mcp-ts/hooks/guard-shell-command.mjs +41 -2
- package/presets/cursor/mcp-ts/hooks/run-hook.mjs +2 -1
- package/presets/cursor/mol/hooks/chain-team-phases.sh +314 -1
- package/presets/cursor/mol/hooks/guard-shell-command.mjs +41 -2
- package/presets/cursor/mol/hooks/run-hook.mjs +2 -1
- package/presets/cursor/next/MCP.md +2 -0
- package/presets/cursor/next/REPO_AGENTS.md +2 -0
- package/presets/cursor/next/agents/build-verifier.md +1 -1
- package/presets/cursor/next/agents/ci-investigator.md +2 -0
- package/presets/cursor/next/agents/code-reviewer.md +1 -0
- package/presets/cursor/next/agents/debugger.md +2 -0
- package/presets/cursor/next/agents/feature-developer.md +2 -0
- package/presets/cursor/next/agents/mockup-reviewer.md +4 -1
- package/presets/cursor/next/agents/performance-auditor.md +2 -0
- package/presets/cursor/next/agents/playwright-test-generator.md +2 -0
- package/presets/cursor/next/agents/playwright-test-healer.md +2 -0
- package/presets/cursor/next/agents/playwright-test-planner.md +2 -0
- package/presets/cursor/next/agents/qa-tester.md +2 -0
- package/presets/cursor/next/agents/task-analyst.md +2 -0
- package/presets/cursor/next/ai-local/rules-library/storybook-dev-compare-figma.md +2 -1
- package/presets/cursor/next/ai-local/rules-library/ui-change-review-gate.md +1 -0
- package/presets/cursor/next/commands/README.md +6 -0
- package/presets/cursor/next/commands/task.md +7 -1
- package/presets/cursor/next/commands/technical-retro.md +7 -1
- package/presets/cursor/next/commands/ui-start.md +78 -0
- package/presets/cursor/next/commands/ui-stop.md +71 -0
- package/presets/cursor/next/commands/upstream-research.md +1 -1
- package/presets/cursor/next/hooks/chain-team-phases.sh +314 -1
- package/presets/cursor/next/hooks/guard-shell-command.mjs +41 -2
- package/presets/cursor/next/hooks/run-hook.mjs +2 -1
- package/presets/cursor/next/rules/README.md +2 -1
- package/presets/cursor/next/rules/dev-process-lifecycle.mdc +43 -0
- package/presets/cursor/next/rules/next-app-core.mdc +1 -0
- package/presets/cursor/next/skills/figma-fidelity/SKILL.md +4 -1
- package/presets/cursor/next/skills/mockup-review/SKILL.md +4 -0
- package/presets/cursor/next/team/README.md +5 -1
- package/presets/cursor/next/team/upstream/jobs.json +34 -0
- package/presets/cursor/nuxt/hooks/chain-team-phases.sh +314 -1
- package/presets/cursor/nuxt/hooks/guard-shell-command.mjs +41 -2
- package/presets/cursor/nuxt/hooks/run-hook.mjs +2 -1
- package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +314 -1
- package/presets/cursor/php-hexagonal/hooks/guard-shell-command.mjs +41 -2
- package/presets/cursor/php-hexagonal/hooks/run-hook.mjs +2 -1
- package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +315 -2
- package/presets/cursor/php-laravel/hooks/guard-shell-command.mjs +41 -2
- package/presets/cursor/php-laravel/hooks/run-hook.mjs +2 -1
- package/presets/cursor/svelte/hooks/chain-team-phases.sh +314 -1
- package/presets/cursor/svelte/hooks/guard-shell-command.mjs +41 -2
- package/presets/cursor/svelte/hooks/run-hook.mjs +2 -1
- package/presets/mavis/android-kotlin/adapter-map.json +1 -1
- package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +314 -1
- package/presets/mavis/android-kotlin/rules/agent-team-orchestrator.md +2 -1
- package/presets/mavis/go/adapter-map.json +1 -1
- package/presets/mavis/go/hooks/chain-team-phases.sh +314 -1
- package/presets/mavis/go/rules/agent-team-orchestrator.md +2 -1
- package/presets/mavis/ios-swift/adapter-map.json +1 -1
- package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +314 -1
- package/presets/mavis/ios-swift/rules/agent-team-orchestrator.md +2 -1
- package/presets/mavis/java/adapter-map.json +1 -1
- package/presets/mavis/java/hooks/chain-team-phases.sh +314 -1
- package/presets/mavis/java/rules/agent-team-orchestrator.md +2 -1
- package/presets/mavis/mcp-ts/adapter-map.json +1 -1
- package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +314 -1
- package/presets/mavis/mcp-ts/rules/agent-team-orchestrator.md +2 -1
- package/presets/mavis/mol/adapter-map.json +1 -1
- package/presets/mavis/mol/hooks/chain-team-phases.sh +314 -1
- package/presets/mavis/mol/rules/agent-team-orchestrator.md +2 -1
- package/presets/mavis/next/MCP.md +2 -0
- package/presets/mavis/next/REPO_AGENTS.md +2 -0
- package/presets/mavis/next/adapter-map.json +33 -1
- package/presets/mavis/next/agents/build-verifier.md +1 -1
- package/presets/mavis/next/agents/ci-investigator.md +3 -0
- package/presets/mavis/next/agents/code-reviewer.md +1 -0
- package/presets/mavis/next/agents/debugger.md +3 -0
- package/presets/mavis/next/agents/feature-developer.md +3 -0
- package/presets/mavis/next/agents/mockup-reviewer.md +4 -1
- package/presets/mavis/next/agents/performance-auditor.md +2 -0
- package/presets/mavis/next/agents/playwright-test-generator.md +3 -0
- package/presets/mavis/next/agents/playwright-test-healer.md +3 -0
- package/presets/mavis/next/agents/playwright-test-planner.md +3 -0
- package/presets/mavis/next/agents/qa-tester.md +3 -0
- package/presets/mavis/next/agents/task-analyst.md +2 -0
- package/presets/mavis/next/ai-local/rules-library/storybook-dev-compare-figma.md +2 -1
- package/presets/mavis/next/ai-local/rules-library/ui-change-review-gate.md +1 -0
- package/presets/mavis/next/commands/README.md +6 -0
- package/presets/mavis/next/commands/task.md +7 -1
- package/presets/mavis/next/commands/technical-retro.md +7 -1
- package/presets/mavis/next/commands/ui-start.md +73 -0
- package/presets/mavis/next/commands/ui-stop.md +66 -0
- package/presets/mavis/next/commands/upstream-research.md +1 -1
- package/presets/mavis/next/hooks/chain-team-phases.sh +314 -1
- package/presets/mavis/next/rules/agent-team-orchestrator.md +2 -1
- package/presets/mavis/next/rules/dev-process-lifecycle.md +38 -0
- package/presets/mavis/next/rules/next-app-core.md +1 -0
- package/presets/mavis/next/skills/figma-fidelity/SKILL.md +4 -1
- package/presets/mavis/next/skills/mockup-review/SKILL.md +4 -0
- package/presets/mavis/next/team/README.md +5 -1
- package/presets/mavis/next/team/upstream/jobs.json +34 -0
- package/presets/mavis/nuxt/adapter-map.json +1 -1
- package/presets/mavis/nuxt/hooks/chain-team-phases.sh +314 -1
- package/presets/mavis/nuxt/rules/agent-team-orchestrator.md +2 -1
- package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
- package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +314 -1
- package/presets/mavis/php-hexagonal/rules/agent-team-orchestrator.md +2 -1
- package/presets/mavis/php-laravel/adapter-map.json +1 -1
- package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +315 -2
- package/presets/mavis/php-laravel/rules/agent-team-orchestrator.md +2 -1
- package/presets/mavis/svelte/adapter-map.json +1 -1
- package/presets/mavis/svelte/hooks/chain-team-phases.sh +314 -1
- package/presets/mavis/svelte/rules/agent-team-orchestrator.md +2 -1
- package/presets/opencode/android-kotlin/OPENCODE.md +4 -1
- package/presets/opencode/android-kotlin/README.md +1 -0
- package/presets/opencode/android-kotlin/adapter-map.json +1 -1
- package/presets/opencode/android-kotlin/hooks/README.md +4 -2
- package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +314 -1
- package/presets/opencode/android-kotlin/opencode.json +5 -1
- package/presets/opencode/android-kotlin/rules/agent-team-orchestrator.md +2 -1
- package/presets/opencode/go/OPENCODE.md +4 -1
- package/presets/opencode/go/README.md +1 -0
- package/presets/opencode/go/adapter-map.json +1 -1
- package/presets/opencode/go/hooks/README.md +4 -2
- package/presets/opencode/go/hooks/chain-team-phases.sh +314 -1
- package/presets/opencode/go/opencode.json +5 -1
- package/presets/opencode/go/rules/agent-team-orchestrator.md +2 -1
- package/presets/opencode/ios-swift/OPENCODE.md +4 -1
- package/presets/opencode/ios-swift/README.md +1 -0
- package/presets/opencode/ios-swift/adapter-map.json +1 -1
- package/presets/opencode/ios-swift/hooks/README.md +4 -2
- package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +314 -1
- package/presets/opencode/ios-swift/opencode.json +5 -1
- package/presets/opencode/ios-swift/rules/agent-team-orchestrator.md +2 -1
- package/presets/opencode/java/OPENCODE.md +4 -1
- package/presets/opencode/java/README.md +1 -0
- package/presets/opencode/java/adapter-map.json +1 -1
- package/presets/opencode/java/hooks/README.md +4 -2
- package/presets/opencode/java/hooks/chain-team-phases.sh +314 -1
- package/presets/opencode/java/opencode.json +5 -1
- package/presets/opencode/java/rules/agent-team-orchestrator.md +2 -1
- package/presets/opencode/mcp-ts/OPENCODE.md +4 -1
- package/presets/opencode/mcp-ts/README.md +1 -0
- package/presets/opencode/mcp-ts/adapter-map.json +1 -1
- package/presets/opencode/mcp-ts/hooks/README.md +4 -2
- package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +314 -1
- package/presets/opencode/mcp-ts/opencode.json +5 -1
- package/presets/opencode/mcp-ts/rules/agent-team-orchestrator.md +2 -1
- package/presets/opencode/mol/OPENCODE.md +4 -1
- package/presets/opencode/mol/README.md +1 -0
- package/presets/opencode/mol/adapter-map.json +1 -1
- package/presets/opencode/mol/hooks/README.md +4 -2
- package/presets/opencode/mol/hooks/chain-team-phases.sh +314 -1
- package/presets/opencode/mol/opencode.json +4 -0
- package/presets/opencode/mol/rules/agent-team-orchestrator.md +2 -1
- package/presets/opencode/next/MCP.md +2 -0
- package/presets/opencode/next/OPENCODE.md +4 -1
- package/presets/opencode/next/README.md +1 -0
- package/presets/opencode/next/REPO_AGENTS.md +2 -0
- package/presets/opencode/next/adapter-map.json +33 -1
- package/presets/opencode/next/agents/build-verifier.md +1 -1
- package/presets/opencode/next/agents/ci-investigator.md +3 -0
- package/presets/opencode/next/agents/code-reviewer.md +1 -0
- package/presets/opencode/next/agents/debugger.md +3 -0
- package/presets/opencode/next/agents/feature-developer.md +3 -0
- package/presets/opencode/next/agents/mockup-reviewer.md +4 -1
- package/presets/opencode/next/agents/performance-auditor.md +2 -0
- package/presets/opencode/next/agents/playwright-test-generator.md +3 -0
- package/presets/opencode/next/agents/playwright-test-healer.md +3 -0
- package/presets/opencode/next/agents/playwright-test-planner.md +3 -0
- package/presets/opencode/next/agents/qa-tester.md +3 -0
- package/presets/opencode/next/agents/task-analyst.md +2 -0
- package/presets/opencode/next/ai-local/rules-library/storybook-dev-compare-figma.md +2 -1
- package/presets/opencode/next/ai-local/rules-library/ui-change-review-gate.md +1 -0
- package/presets/opencode/next/commands/README.md +6 -0
- package/presets/opencode/next/commands/task.md +7 -1
- package/presets/opencode/next/commands/technical-retro.md +7 -1
- package/presets/opencode/next/commands/ui-start.md +81 -0
- package/presets/opencode/next/commands/ui-stop.md +74 -0
- package/presets/opencode/next/commands/upstream-research.md +1 -1
- package/presets/opencode/next/hooks/README.md +4 -2
- package/presets/opencode/next/hooks/chain-team-phases.sh +314 -1
- package/presets/opencode/next/opencode.json +4 -0
- package/presets/opencode/next/rules/agent-team-orchestrator.md +2 -1
- package/presets/opencode/next/rules/dev-process-lifecycle.md +38 -0
- package/presets/opencode/next/rules/next-app-core.md +1 -0
- package/presets/opencode/next/skills/figma-fidelity/SKILL.md +4 -1
- package/presets/opencode/next/skills/mockup-review/SKILL.md +4 -0
- package/presets/opencode/next/team/README.md +5 -1
- package/presets/opencode/next/team/upstream/jobs.json +34 -0
- package/presets/opencode/nuxt/OPENCODE.md +4 -1
- package/presets/opencode/nuxt/README.md +1 -0
- package/presets/opencode/nuxt/adapter-map.json +1 -1
- package/presets/opencode/nuxt/hooks/README.md +4 -2
- package/presets/opencode/nuxt/hooks/chain-team-phases.sh +314 -1
- package/presets/opencode/nuxt/opencode.json +4 -0
- package/presets/opencode/nuxt/rules/agent-team-orchestrator.md +2 -1
- package/presets/opencode/php-hexagonal/OPENCODE.md +4 -1
- package/presets/opencode/php-hexagonal/README.md +1 -0
- package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
- package/presets/opencode/php-hexagonal/hooks/README.md +4 -2
- package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +314 -1
- package/presets/opencode/php-hexagonal/opencode.json +5 -1
- package/presets/opencode/php-hexagonal/rules/agent-team-orchestrator.md +2 -1
- package/presets/opencode/php-laravel/OPENCODE.md +4 -1
- package/presets/opencode/php-laravel/README.md +1 -0
- package/presets/opencode/php-laravel/adapter-map.json +1 -1
- package/presets/opencode/php-laravel/hooks/README.md +4 -2
- package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +315 -2
- package/presets/opencode/php-laravel/opencode.json +5 -1
- package/presets/opencode/php-laravel/rules/agent-team-orchestrator.md +2 -1
- package/presets/opencode/platform-contract.json +6 -0
- package/presets/opencode/plugins/task-status/README.md +92 -0
- package/presets/opencode/plugins/task-status/details-data.ts +130 -0
- package/presets/opencode/plugins/task-status/details.tsx +84 -0
- package/presets/opencode/plugins/task-status/eta.ts +230 -0
- package/presets/opencode/plugins/task-status/index.ts +6 -0
- package/presets/opencode/plugins/task-status/package.json +10 -0
- package/presets/opencode/plugins/task-status/task-view.ts +606 -0
- package/presets/opencode/plugins/task-status/tui.tsx +139 -0
- package/presets/opencode/svelte/OPENCODE.md +4 -1
- package/presets/opencode/svelte/README.md +1 -0
- package/presets/opencode/svelte/adapter-map.json +1 -1
- package/presets/opencode/svelte/hooks/README.md +4 -2
- package/presets/opencode/svelte/hooks/chain-team-phases.sh +314 -1
- package/presets/opencode/svelte/opencode.json +4 -0
- package/presets/opencode/svelte/rules/agent-team-orchestrator.md +2 -1
- package/presets/zcode/android-kotlin/adapter-map.json +1 -1
- package/presets/zcode/android-kotlin/hooks/chain-team-phases.sh +314 -1
- package/presets/zcode/android-kotlin/rules/agent-team-orchestrator.md +2 -1
- package/presets/zcode/go/adapter-map.json +1 -1
- package/presets/zcode/go/hooks/chain-team-phases.sh +314 -1
- package/presets/zcode/go/rules/agent-team-orchestrator.md +2 -1
- package/presets/zcode/ios-swift/adapter-map.json +1 -1
- package/presets/zcode/ios-swift/hooks/chain-team-phases.sh +314 -1
- package/presets/zcode/ios-swift/rules/agent-team-orchestrator.md +2 -1
- package/presets/zcode/java/adapter-map.json +1 -1
- package/presets/zcode/java/hooks/chain-team-phases.sh +314 -1
- package/presets/zcode/java/rules/agent-team-orchestrator.md +2 -1
- package/presets/zcode/mcp-ts/adapter-map.json +1 -1
- package/presets/zcode/mcp-ts/hooks/chain-team-phases.sh +314 -1
- package/presets/zcode/mcp-ts/rules/agent-team-orchestrator.md +2 -1
- package/presets/zcode/mol/adapter-map.json +1 -1
- package/presets/zcode/mol/hooks/chain-team-phases.sh +314 -1
- package/presets/zcode/mol/rules/agent-team-orchestrator.md +2 -1
- package/presets/zcode/next/MCP.md +2 -0
- package/presets/zcode/next/REPO_AGENTS.md +2 -0
- package/presets/zcode/next/adapter-map.json +33 -1
- package/presets/zcode/next/agents/build-verifier.md +1 -1
- package/presets/zcode/next/agents/ci-investigator.md +3 -0
- package/presets/zcode/next/agents/code-reviewer.md +1 -0
- package/presets/zcode/next/agents/debugger.md +3 -0
- package/presets/zcode/next/agents/feature-developer.md +3 -0
- package/presets/zcode/next/agents/mockup-reviewer.md +4 -1
- package/presets/zcode/next/agents/performance-auditor.md +2 -0
- package/presets/zcode/next/agents/playwright-test-generator.md +3 -0
- package/presets/zcode/next/agents/playwright-test-healer.md +3 -0
- package/presets/zcode/next/agents/playwright-test-planner.md +3 -0
- package/presets/zcode/next/agents/qa-tester.md +3 -0
- package/presets/zcode/next/agents/task-analyst.md +2 -0
- package/presets/zcode/next/ai-local/rules-library/storybook-dev-compare-figma.md +2 -1
- package/presets/zcode/next/ai-local/rules-library/ui-change-review-gate.md +1 -0
- package/presets/zcode/next/commands/README.md +6 -0
- package/presets/zcode/next/commands/task.md +7 -1
- package/presets/zcode/next/commands/technical-retro.md +7 -1
- package/presets/zcode/next/commands/ui-start.md +81 -0
- package/presets/zcode/next/commands/ui-stop.md +74 -0
- package/presets/zcode/next/commands/upstream-research.md +1 -1
- package/presets/zcode/next/hooks/chain-team-phases.sh +314 -1
- package/presets/zcode/next/rules/agent-team-orchestrator.md +2 -1
- package/presets/zcode/next/rules/dev-process-lifecycle.md +38 -0
- package/presets/zcode/next/rules/next-app-core.md +1 -0
- package/presets/zcode/next/skills/figma-fidelity/SKILL.md +4 -1
- package/presets/zcode/next/skills/mockup-review/SKILL.md +4 -0
- package/presets/zcode/next/team/README.md +5 -1
- package/presets/zcode/next/team/upstream/jobs.json +34 -0
- package/presets/zcode/nuxt/adapter-map.json +1 -1
- package/presets/zcode/nuxt/hooks/chain-team-phases.sh +314 -1
- package/presets/zcode/nuxt/rules/agent-team-orchestrator.md +2 -1
- package/presets/zcode/php-hexagonal/adapter-map.json +1 -1
- package/presets/zcode/php-hexagonal/hooks/chain-team-phases.sh +314 -1
- package/presets/zcode/php-hexagonal/rules/agent-team-orchestrator.md +2 -1
- package/presets/zcode/php-laravel/adapter-map.json +1 -1
- package/presets/zcode/php-laravel/hooks/chain-team-phases.sh +315 -2
- package/presets/zcode/php-laravel/rules/agent-team-orchestrator.md +2 -1
- package/presets/zcode/svelte/adapter-map.json +1 -1
- package/presets/zcode/svelte/hooks/chain-team-phases.sh +314 -1
- package/presets/zcode/svelte/rules/agent-team-orchestrator.md +2 -1
- package/scripts/aggregate-agent-task-metrics.mjs +48 -4
|
@@ -0,0 +1,2069 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The file-authoritative tracker store for `.ai.local/team/tracker/**`:
|
|
3
|
+
* items, links, the launch queue, the deterministic eligibility order and the
|
|
4
|
+
* import envelope.
|
|
5
|
+
*
|
|
6
|
+
* Files are authoritative and this module is the only writer of
|
|
7
|
+
* `tracker/items/*.json`, `tracker/links/*.json` and `tracker/queue/*.json`
|
|
8
|
+
* (I-1, I-2). The store is
|
|
9
|
+
* file-only by design: no verb here opens a database, so the kill switch
|
|
10
|
+
* (`AI_RULES_TEAM_DB_DISABLE=1`) never disables a tracker write — it stops the
|
|
11
|
+
* projection only (R3-7). The `team-db.mjs` wrapper projects the tracker store after a write so the
|
|
12
|
+
* read-only API sees fresh rows; a projection failure never fails the write.
|
|
13
|
+
*
|
|
14
|
+
* The stored status lattice
|
|
15
|
+
* (`backlog|planned|completed|cancelled|superseded`) is the only decision
|
|
16
|
+
* recorded; every operational status (`effectiveStatus`) is derived from the
|
|
17
|
+
* item, the links, the queue entries and the hook-owned task state, and is
|
|
18
|
+
* never written to a file (I-3). `rank(item) = priority ASC → createdAt ASC
|
|
19
|
+
* → id ASC` is a total order and the only order (I-4, D-4). This module never
|
|
20
|
+
* writes a lifecycle, gate or metric file and never starts an agent run: the
|
|
21
|
+
* hook stop seam consumes `drain --claim` and owns the launch (I-5, D-5).
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import crypto from 'node:crypto';
|
|
25
|
+
import fs from 'node:fs';
|
|
26
|
+
import path from 'node:path';
|
|
27
|
+
|
|
28
|
+
import { DEFAULT_TEAM_ROOT, TeamDbError, teamDbFail } from './team-db-schema.mjs';
|
|
29
|
+
import { acquireLock, releaseLock } from './lock.mjs';
|
|
30
|
+
|
|
31
|
+
export const TRACKER_DIR = 'tracker';
|
|
32
|
+
/** The shipped store directory this one replaced; read once by `migrate-ids`. */
|
|
33
|
+
const LEGACY_TRACKER_DIR = 'backlog';
|
|
34
|
+
export const ITEMS_DIR = 'items';
|
|
35
|
+
export const QUEUE_DIR = 'queue';
|
|
36
|
+
export const LINKS_DIR = 'links';
|
|
37
|
+
export const CONFIG_FILE = 'config.json';
|
|
38
|
+
|
|
39
|
+
export const ITEM_SCHEMA_VERSION = 1;
|
|
40
|
+
export const ENTRY_SCHEMA_VERSION = 1;
|
|
41
|
+
export const LINK_SCHEMA_VERSION = 1;
|
|
42
|
+
export const CONFIG_SCHEMA_VERSION = 1;
|
|
43
|
+
|
|
44
|
+
/** Tracker item ids are positive integers assigned by the store. */
|
|
45
|
+
export const ITEM_ID_RE = /^[1-9][0-9]*$/;
|
|
46
|
+
/** The team-task slug grammar; the link carries a slug that may differ from the item id. */
|
|
47
|
+
export const TASK_SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
48
|
+
/** The scheduler's `RUN_ID_RE` shape, so one id grammar reads across the tree. */
|
|
49
|
+
export const ENTRY_ID_RE = /^[0-9]{8}T[0-9]{6}Z-[0-9a-f]{8}$/;
|
|
50
|
+
|
|
51
|
+
/** Parse a persisted or path item id into the one numeric representation. */
|
|
52
|
+
export const parseItemId = (value, label = 'item id') => {
|
|
53
|
+
const id = typeof value === 'number' ? value : /^[0-9]+$/.test(String(value)) ? Number(value) : NaN;
|
|
54
|
+
if (!Number.isInteger(id) || id < 1) reject('E_SCHEMA', `${label} must be a positive integer`);
|
|
55
|
+
return id;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
export const LINK_DECISIONS = ['requested', 'stopped', 'unlinked'];
|
|
59
|
+
export const LINK_ROLES = ['primary', 'follow-up'];
|
|
60
|
+
|
|
61
|
+
export const ITEM_STATUSES = ['backlog', 'planned', 'completed', 'cancelled', 'superseded'];
|
|
62
|
+
export const ITEM_TYPES = ['feature', 'bugfix', 'spike', 'chore', 'docs', 'refactor'];
|
|
63
|
+
export const ENTRY_STATUSES = ['queued', 'claimed', 'cancelled', 'expired'];
|
|
64
|
+
|
|
65
|
+
export const ITEM_HISTORY_TYPES = new Set([
|
|
66
|
+
'created',
|
|
67
|
+
'updated',
|
|
68
|
+
'status-changed',
|
|
69
|
+
'priority-changed',
|
|
70
|
+
'deps-changed',
|
|
71
|
+
'imported',
|
|
72
|
+
'cancelled',
|
|
73
|
+
'completed',
|
|
74
|
+
'reopened',
|
|
75
|
+
'superseded',
|
|
76
|
+
]);
|
|
77
|
+
export const ENTRY_HISTORY_TYPES = new Set(['enqueued', 'claimed', 'released', 'cancelled', 'expired', 'recovered']);
|
|
78
|
+
|
|
79
|
+
export const EFFECTIVE_ITEM_STATUSES = ['backlog', 'planned', 'queued', 'launched', 'completed', 'cancelled', 'superseded'];
|
|
80
|
+
export const EFFECTIVE_ENTRY_STATUSES = ['queued', 'claimed', 'active', 'done', 'cancelled', 'expired'];
|
|
81
|
+
|
|
82
|
+
/** The derived state of a link, never stored (the stored field is `decision`). */
|
|
83
|
+
export const EFFECTIVE_LINK_STATES = [
|
|
84
|
+
'requested',
|
|
85
|
+
'claimed',
|
|
86
|
+
'active',
|
|
87
|
+
'paused',
|
|
88
|
+
'stopped',
|
|
89
|
+
'completed',
|
|
90
|
+
'failed',
|
|
91
|
+
'unlinked',
|
|
92
|
+
];
|
|
93
|
+
|
|
94
|
+
/** WIP states that hold a launch slot; everything else is passive (R3-2). */
|
|
95
|
+
export const HOLDING_TASK_STATES = new Set(['in_progress', 'awaiting_artifact_receipt', 'blocked']);
|
|
96
|
+
|
|
97
|
+
/** A claim older than this with no task row is released on the next drain (the scheduler's lease). */
|
|
98
|
+
export const CLAIM_STALE_MS = 90 * 1000;
|
|
99
|
+
/** `createdAt` further in the future than this skew is `E_SCHEMA` (F-8). */
|
|
100
|
+
export const FUTURE_CREATED_AT_SKEW_MS = 5 * 60 * 1000;
|
|
101
|
+
|
|
102
|
+
export const MAX_TITLE_CHARS = 120;
|
|
103
|
+
export const MAX_TASK_SLUG_CHARS = 48;
|
|
104
|
+
export const MAX_PROMPT_BYTES = 64 * 1024;
|
|
105
|
+
export const MAX_LINK_HISTORY = 64;
|
|
106
|
+
export const MAX_DESCRIPTION_CHARS = 2000;
|
|
107
|
+
export const MAX_LABELS = 8;
|
|
108
|
+
export const MAX_LABEL_CHARS = 32;
|
|
109
|
+
export const MAX_ITEM_HISTORY = 64;
|
|
110
|
+
export const MAX_ENTRY_HISTORY = 32;
|
|
111
|
+
export const MAX_DEPENDENCIES = 32;
|
|
112
|
+
export const MAX_SOURCE_REFS = 16;
|
|
113
|
+
export const MAX_SOURCE_REF_CHARS = 40;
|
|
114
|
+
export const MAX_CANCEL_REASON_CHARS = 200;
|
|
115
|
+
export const MAX_REASON_CHARS = 200;
|
|
116
|
+
export const MAX_REQUESTED_BY_CHARS = 120;
|
|
117
|
+
export const MAX_COMMAND_CHARS = 200;
|
|
118
|
+
export const MAX_ACTIVE_MIN = 1;
|
|
119
|
+
export const MAX_ACTIVE_MAX = 8;
|
|
120
|
+
export const DEFAULT_MAX_ACTIVE = 1;
|
|
121
|
+
export const DEFAULT_PRUNE_DAYS = 90;
|
|
122
|
+
|
|
123
|
+
const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
124
|
+
|
|
125
|
+
const isTruthy = (value) => {
|
|
126
|
+
if (typeof value !== 'string') return false;
|
|
127
|
+
const normalized = value.trim().toLowerCase();
|
|
128
|
+
return normalized === '1' || normalized === 'true' || normalized === 'yes';
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
const nowIso = () => new Date().toISOString();
|
|
132
|
+
|
|
133
|
+
/** RFC 3339 with an explicit `Z`; anything else is a schema failure. */
|
|
134
|
+
const isIsoZ = (value) => typeof value === 'string' && /Z$/.test(value) && !Number.isNaN(Date.parse(value));
|
|
135
|
+
|
|
136
|
+
const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');
|
|
137
|
+
|
|
138
|
+
/** Canonical JSON with sorted keys, so content-hash equality is byte-stable. */
|
|
139
|
+
const canonicalJson = (value) => {
|
|
140
|
+
const walk = (node) => {
|
|
141
|
+
if (node === null || typeof node !== 'object') return node;
|
|
142
|
+
if (Array.isArray(node)) return node.map(walk);
|
|
143
|
+
const sorted = {};
|
|
144
|
+
for (const key of Object.keys(node).sort()) sorted[key] = walk(node[key]);
|
|
145
|
+
return sorted;
|
|
146
|
+
};
|
|
147
|
+
return JSON.stringify(walk(value));
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
const reject = (code, message) => teamDbFail(code, message, 1);
|
|
151
|
+
|
|
152
|
+
const capHistory = (history, max) => history.slice(Math.max(0, history.length - max));
|
|
153
|
+
|
|
154
|
+
/* --------------------------------- paths ---------------------------------- */
|
|
155
|
+
|
|
156
|
+
export const trackerPaths = (teamRoot) => {
|
|
157
|
+
const root = path.join(teamRoot, TRACKER_DIR);
|
|
158
|
+
return {
|
|
159
|
+
root,
|
|
160
|
+
items: path.join(root, ITEMS_DIR),
|
|
161
|
+
queue: path.join(root, QUEUE_DIR),
|
|
162
|
+
links: path.join(root, LINKS_DIR),
|
|
163
|
+
config: path.join(root, CONFIG_FILE),
|
|
164
|
+
lock: path.join(root, '.lock'),
|
|
165
|
+
};
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
export const itemFilePath = (teamRoot, id) => path.join(trackerPaths(teamRoot).items, `${id}.json`);
|
|
169
|
+
export const entryFilePath = (teamRoot, entryId) => path.join(trackerPaths(teamRoot).queue, `${entryId}.json`);
|
|
170
|
+
export const linkFilePath = (teamRoot, linkId) => path.join(trackerPaths(teamRoot).links, `${linkId}.json`);
|
|
171
|
+
export const linkPromptPath = (teamRoot, linkId) => path.join(trackerPaths(teamRoot).links, `${linkId}.md`);
|
|
172
|
+
export const linkIdOf = (itemId, taskSlug) => `${itemId}--${taskSlug}`;
|
|
173
|
+
export const sequenceFilePath = (teamRoot) => path.join(trackerPaths(teamRoot).root, 'sequence.json');
|
|
174
|
+
const idMigrationFilePath = (teamRoot) => path.join(trackerPaths(teamRoot).root, 'id-migration.json');
|
|
175
|
+
|
|
176
|
+
/** The monotonic item-id sequence; max(existing) covers a lost sequence file. */
|
|
177
|
+
const nextItemId = (teamRoot) => {
|
|
178
|
+
const current = listItemIds(teamRoot).reduce((max, id) => Math.max(max, id), 0);
|
|
179
|
+
let reserved = 0;
|
|
180
|
+
try {
|
|
181
|
+
const parsed = JSON.parse(fs.readFileSync(sequenceFilePath(teamRoot), 'utf8'));
|
|
182
|
+
if (Number.isInteger(parsed?.nextId) && parsed.nextId > 0) reserved = parsed.nextId;
|
|
183
|
+
} catch {
|
|
184
|
+
/* a missing or unreadable sequence falls back to the file maximum */
|
|
185
|
+
}
|
|
186
|
+
const nextId = Math.max(current + 1, reserved, 1);
|
|
187
|
+
writeAtomic(sequenceFilePath(teamRoot), `${JSON.stringify({ schemaVersion: 1, nextId: nextId + 1 }, null, 2)}\n`);
|
|
188
|
+
return nextId;
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
/** Both directories are created on first write (`mkdir -p` inside the CLI). */
|
|
192
|
+
const ensureTrackerDirs = (teamRoot) => {
|
|
193
|
+
fs.mkdirSync(trackerPaths(teamRoot).items, { recursive: true });
|
|
194
|
+
fs.mkdirSync(trackerPaths(teamRoot).queue, { recursive: true });
|
|
195
|
+
fs.mkdirSync(trackerPaths(teamRoot).links, { recursive: true });
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
const withTrackerLock = (teamRoot, run) => {
|
|
199
|
+
fs.mkdirSync(trackerPaths(teamRoot).root, { recursive: true });
|
|
200
|
+
const lockPath = trackerPaths(teamRoot).lock;
|
|
201
|
+
let token = null;
|
|
202
|
+
try {
|
|
203
|
+
token = acquireLock(lockPath, { timeoutMs: 5000 });
|
|
204
|
+
} catch (error) {
|
|
205
|
+
teamDbFail('E_TRACKER_BUSY', `could not take the tracker lock at ${lockPath}: ${error.message}`, 4);
|
|
206
|
+
}
|
|
207
|
+
try {
|
|
208
|
+
return run();
|
|
209
|
+
} finally {
|
|
210
|
+
releaseLock(lockPath, token);
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
/* --------------------------------- reading -------------------------------- */
|
|
215
|
+
|
|
216
|
+
export const listItemIds = (teamRoot) => {
|
|
217
|
+
const dir = trackerPaths(teamRoot).items;
|
|
218
|
+
if (!fs.existsSync(dir)) return [];
|
|
219
|
+
return fs
|
|
220
|
+
.readdirSync(dir)
|
|
221
|
+
.filter((name) => name.endsWith('.json') && ITEM_ID_RE.test(name.slice(0, -'.json'.length)))
|
|
222
|
+
.map((name) => Number(name.slice(0, -'.json'.length)))
|
|
223
|
+
.sort((left, right) => left - right);
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
export const listEntryIds = (teamRoot) => {
|
|
227
|
+
const dir = trackerPaths(teamRoot).queue;
|
|
228
|
+
if (!fs.existsSync(dir)) return [];
|
|
229
|
+
return fs
|
|
230
|
+
.readdirSync(dir)
|
|
231
|
+
.filter((name) => name.endsWith('.json'))
|
|
232
|
+
.map((name) => name.slice(0, -'.json'.length))
|
|
233
|
+
.sort();
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
export const listLinkIds = (teamRoot) => {
|
|
237
|
+
const dir = trackerPaths(teamRoot).links;
|
|
238
|
+
if (!fs.existsSync(dir)) return [];
|
|
239
|
+
return fs
|
|
240
|
+
.readdirSync(dir)
|
|
241
|
+
.filter((name) => name.endsWith('.json'))
|
|
242
|
+
.map((name) => name.slice(0, -'.json'.length))
|
|
243
|
+
.sort();
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
export const readLinkFile = (teamRoot, linkId) => {
|
|
247
|
+
try {
|
|
248
|
+
return JSON.parse(fs.readFileSync(linkFilePath(teamRoot, linkId), 'utf8'));
|
|
249
|
+
} catch (error) {
|
|
250
|
+
if (error.code === 'ENOENT') return null;
|
|
251
|
+
teamDbFail('E_SCHEMA', `tracker link ${linkId} is unreadable: ${error.message}`, 1);
|
|
252
|
+
}
|
|
253
|
+
return null;
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
export const readLinkPrompt = (teamRoot, linkId) => {
|
|
257
|
+
try {
|
|
258
|
+
return fs.readFileSync(linkPromptPath(teamRoot, linkId), 'utf8');
|
|
259
|
+
} catch (error) {
|
|
260
|
+
if (error.code === 'ENOENT') return null;
|
|
261
|
+
teamDbFail('E_SCHEMA', `tracker link prompt ${linkId} is unreadable: ${error.message}`, 1);
|
|
262
|
+
}
|
|
263
|
+
return null;
|
|
264
|
+
};
|
|
265
|
+
|
|
266
|
+
export const readItemFile = (teamRoot, id) => {
|
|
267
|
+
try {
|
|
268
|
+
return JSON.parse(fs.readFileSync(itemFilePath(teamRoot, id), 'utf8'));
|
|
269
|
+
} catch (error) {
|
|
270
|
+
if (error.code === 'ENOENT') return null;
|
|
271
|
+
teamDbFail('E_SCHEMA', `tracker item ${id} is unreadable: ${error.message}`, 1);
|
|
272
|
+
}
|
|
273
|
+
return null;
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
const readEntryFile = (teamRoot, entryId) => {
|
|
277
|
+
try {
|
|
278
|
+
return JSON.parse(fs.readFileSync(entryFilePath(teamRoot, entryId), 'utf8'));
|
|
279
|
+
} catch (error) {
|
|
280
|
+
if (error.code === 'ENOENT') return null;
|
|
281
|
+
teamDbFail('E_SCHEMA', `queue entry ${entryId} is unreadable: ${error.message}`, 1);
|
|
282
|
+
}
|
|
283
|
+
return null;
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
const listAllItemStems = (teamRoot) => {
|
|
287
|
+
const dir = trackerPaths(teamRoot).items;
|
|
288
|
+
if (!fs.existsSync(dir)) return [];
|
|
289
|
+
return fs
|
|
290
|
+
.readdirSync(dir)
|
|
291
|
+
.filter((name) => name.endsWith('.json'))
|
|
292
|
+
.map((name) => name.slice(0, -'.json'.length))
|
|
293
|
+
.sort();
|
|
294
|
+
};
|
|
295
|
+
|
|
296
|
+
const readAllItems = (teamRoot) => {
|
|
297
|
+
const items = new Map();
|
|
298
|
+
for (const id of listItemIds(teamRoot)) {
|
|
299
|
+
const item = readItemFile(teamRoot, id);
|
|
300
|
+
if (item) items.set(id, item);
|
|
301
|
+
}
|
|
302
|
+
return items;
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
const readAllItemsIncludingLegacy = (teamRoot) => {
|
|
306
|
+
const items = new Map();
|
|
307
|
+
for (const stem of listAllItemStems(teamRoot)) {
|
|
308
|
+
const item = readItemFile(teamRoot, stem);
|
|
309
|
+
if (item) items.set(item.id ?? stem, item);
|
|
310
|
+
}
|
|
311
|
+
return items;
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
const readAllEntries = (teamRoot) => {
|
|
315
|
+
const entries = new Map();
|
|
316
|
+
for (const entryId of listEntryIds(teamRoot)) {
|
|
317
|
+
const entry = readEntryFile(teamRoot, entryId);
|
|
318
|
+
if (entry) entries.set(entryId, entry);
|
|
319
|
+
}
|
|
320
|
+
return entries;
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
const readAllLinks = (teamRoot) => {
|
|
324
|
+
const links = new Map();
|
|
325
|
+
for (const linkId of listLinkIds(teamRoot)) {
|
|
326
|
+
const link = readLinkFile(teamRoot, linkId);
|
|
327
|
+
if (link) links.set(linkId, link);
|
|
328
|
+
}
|
|
329
|
+
return links;
|
|
330
|
+
};
|
|
331
|
+
|
|
332
|
+
/** The hook-owned `state` of every `tasks/<slug>/status.json`, read once. */
|
|
333
|
+
export const readTaskStates = (teamRoot) => {
|
|
334
|
+
const states = new Map();
|
|
335
|
+
const tasksDir = path.join(teamRoot, 'tasks');
|
|
336
|
+
if (!fs.existsSync(tasksDir)) return states;
|
|
337
|
+
for (const entry of fs.readdirSync(tasksDir, { withFileTypes: true })) {
|
|
338
|
+
if (!entry.isDirectory() || !TASK_SLUG_RE.test(entry.name)) continue;
|
|
339
|
+
try {
|
|
340
|
+
const status = JSON.parse(fs.readFileSync(path.join(tasksDir, entry.name, 'status.json'), 'utf8'));
|
|
341
|
+
if (isRecord(status) && typeof status.state === 'string') states.set(entry.name, status.state);
|
|
342
|
+
} catch {
|
|
343
|
+
/* no status.json or unreadable — no task state, no launch evidence */
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
return states;
|
|
347
|
+
};
|
|
348
|
+
|
|
349
|
+
/* ------------------------------- configuration ---------------------------- */
|
|
350
|
+
|
|
351
|
+
export function validateTrackerConfig(config) {
|
|
352
|
+
if (!isRecord(config) || config.schemaVersion !== CONFIG_SCHEMA_VERSION) {
|
|
353
|
+
reject('E_SCHEMA', `tracker config.json: schemaVersion must be ${CONFIG_SCHEMA_VERSION}`, 1);
|
|
354
|
+
}
|
|
355
|
+
if (!Number.isInteger(config.maxActive) || config.maxActive < MAX_ACTIVE_MIN || config.maxActive > MAX_ACTIVE_MAX) {
|
|
356
|
+
reject('E_SCHEMA', `tracker config.json: maxActive must be an integer between ${MAX_ACTIVE_MIN} and ${MAX_ACTIVE_MAX}`, 1);
|
|
357
|
+
}
|
|
358
|
+
return config;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** Operator-edited like `scheduler/jobs.json`; absent means the default. */
|
|
362
|
+
export const readTrackerConfig = (teamRoot) => {
|
|
363
|
+
const file = trackerPaths(teamRoot).config;
|
|
364
|
+
if (!fs.existsSync(file)) return { schemaVersion: CONFIG_SCHEMA_VERSION, maxActive: DEFAULT_MAX_ACTIVE };
|
|
365
|
+
let config;
|
|
366
|
+
try {
|
|
367
|
+
config = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
368
|
+
} catch (error) {
|
|
369
|
+
teamDbFail('E_SCHEMA', `tracker config.json is not valid JSON: ${error.message}`, 1);
|
|
370
|
+
}
|
|
371
|
+
return validateTrackerConfig(config);
|
|
372
|
+
};
|
|
373
|
+
|
|
374
|
+
/* -------------------------------- validation ------------------------------ */
|
|
375
|
+
|
|
376
|
+
const validateNullableTimestamp = (item, field, value) => {
|
|
377
|
+
if (value === null) return null;
|
|
378
|
+
if (!isIsoZ(value)) reject('E_SCHEMA', `item ${item.id}: ${field} must be an RFC 3339 timestamp ending in Z`);
|
|
379
|
+
return value;
|
|
380
|
+
};
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* Schema phase: field shapes and bounds only. Validation order is schema →
|
|
384
|
+
* identity → graph; the first failure wins (the frozen outcome table).
|
|
385
|
+
*/
|
|
386
|
+
export function validateItemSchema(item) {
|
|
387
|
+
if (!isRecord(item)) reject('E_SCHEMA', 'tracker item must be an object');
|
|
388
|
+
if (item.schemaVersion !== ITEM_SCHEMA_VERSION) {
|
|
389
|
+
reject('E_SCHEMA', `item ${item.id ?? '?'}: schemaVersion must be ${ITEM_SCHEMA_VERSION}`);
|
|
390
|
+
}
|
|
391
|
+
const id = item.id;
|
|
392
|
+
if (!Number.isInteger(id) || id < 1) {
|
|
393
|
+
reject('E_SCHEMA', 'item id must be a positive integer');
|
|
394
|
+
}
|
|
395
|
+
if (!Number.isInteger(item.revision) || item.revision < 1) {
|
|
396
|
+
reject('E_SCHEMA', `item ${id}: revision must be an integer >= 1`);
|
|
397
|
+
}
|
|
398
|
+
if (
|
|
399
|
+
typeof item.title !== 'string' ||
|
|
400
|
+
item.title !== item.title.trim() ||
|
|
401
|
+
item.title.length < 1 ||
|
|
402
|
+
item.title.length > MAX_TITLE_CHARS ||
|
|
403
|
+
item.title.includes('\n')
|
|
404
|
+
) {
|
|
405
|
+
reject('E_SCHEMA', `item ${id}: title must be trimmed, one line, 1-${MAX_TITLE_CHARS} characters`);
|
|
406
|
+
}
|
|
407
|
+
if (!ITEM_STATUSES.includes(item.status)) {
|
|
408
|
+
reject('E_SCHEMA', `item ${id}: status must be one of ${ITEM_STATUSES.join('|')}`);
|
|
409
|
+
}
|
|
410
|
+
if (!isIsoZ(item.createdAt)) reject('E_SCHEMA', `item ${id}: createdAt must be an RFC 3339 timestamp ending in Z`);
|
|
411
|
+
if (Date.parse(item.createdAt) > Date.now() + FUTURE_CREATED_AT_SKEW_MS) {
|
|
412
|
+
reject('E_SCHEMA', `item ${id}: createdAt is in the future`);
|
|
413
|
+
}
|
|
414
|
+
if (!isIsoZ(item.updatedAt)) reject('E_SCHEMA', `item ${id}: updatedAt must be an RFC 3339 timestamp ending in Z`);
|
|
415
|
+
if (Date.parse(item.updatedAt) < Date.parse(item.createdAt)) {
|
|
416
|
+
reject('E_SCHEMA', `item ${id}: updatedAt must be >= createdAt`);
|
|
417
|
+
}
|
|
418
|
+
item.completedAt = validateNullableTimestamp(item, 'completedAt', item.completedAt);
|
|
419
|
+
item.cancelledAt = validateNullableTimestamp(item, 'cancelledAt', item.cancelledAt);
|
|
420
|
+
if (item.status === 'completed' && item.completedAt === null) {
|
|
421
|
+
reject('E_SCHEMA', `item ${id}: completedAt is required when status is completed`);
|
|
422
|
+
}
|
|
423
|
+
if (item.status === 'cancelled' && item.cancelledAt === null) {
|
|
424
|
+
reject('E_SCHEMA', `item ${id}: cancelledAt is required when status is cancelled`);
|
|
425
|
+
}
|
|
426
|
+
if (item.cancelReason !== null && !(typeof item.cancelReason === 'string' && item.cancelReason.length >= 1 && item.cancelReason.length <= MAX_CANCEL_REASON_CHARS)) {
|
|
427
|
+
reject('E_SCHEMA', `item ${id}: cancelReason must be 1-${MAX_CANCEL_REASON_CHARS} characters`);
|
|
428
|
+
}
|
|
429
|
+
if (item.supersededBy !== null && (!Number.isInteger(item.supersededBy) || item.supersededBy < 1)) {
|
|
430
|
+
reject('E_SCHEMA', `item ${id}: supersededBy must be a positive integer`);
|
|
431
|
+
}
|
|
432
|
+
if (item.status === 'superseded' && item.supersededBy === null) {
|
|
433
|
+
reject('E_SCHEMA', `item ${id}: supersededBy is required when status is superseded`);
|
|
434
|
+
}
|
|
435
|
+
if (!Array.isArray(item.dependsOn) || item.dependsOn.length > MAX_DEPENDENCIES) {
|
|
436
|
+
reject('E_SCHEMA', `item ${id}: dependsOn must be an array of at most ${MAX_DEPENDENCIES} ids`);
|
|
437
|
+
}
|
|
438
|
+
if (new Set(item.dependsOn).size !== item.dependsOn.length) {
|
|
439
|
+
reject('E_SCHEMA', `item ${id}: dependsOn must not contain duplicates`);
|
|
440
|
+
}
|
|
441
|
+
for (const dep of item.dependsOn) {
|
|
442
|
+
if (!Number.isInteger(dep) || dep < 1) {
|
|
443
|
+
reject('E_SCHEMA', `item ${id}: dependency "${String(dep)}" must be a positive integer`);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
if (!Number.isInteger(item.priority) || item.priority < 0 || item.priority > 9) {
|
|
447
|
+
reject('E_SCHEMA', `item ${id}: priority must be an integer between 0 and 9`);
|
|
448
|
+
}
|
|
449
|
+
if (item.sourceTask !== null && !(typeof item.sourceTask === 'string' && TASK_SLUG_RE.test(item.sourceTask))) {
|
|
450
|
+
reject('E_SCHEMA', `item ${id}: sourceTask must match ${TASK_SLUG_RE.source}`);
|
|
451
|
+
}
|
|
452
|
+
if (!Array.isArray(item.sourceRefs) || item.sourceRefs.length > MAX_SOURCE_REFS) {
|
|
453
|
+
reject('E_SCHEMA', `item ${id}: sourceRefs must be an array of at most ${MAX_SOURCE_REFS} refs`);
|
|
454
|
+
}
|
|
455
|
+
for (const ref of item.sourceRefs) {
|
|
456
|
+
if (!(typeof ref === 'string' && ref.length >= 1 && ref.length <= MAX_SOURCE_REF_CHARS)) {
|
|
457
|
+
reject('E_SCHEMA', `item ${id}: every sourceRef must be 1-${MAX_SOURCE_REF_CHARS} characters`);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
if (!ITEM_TYPES.includes(item.type)) {
|
|
461
|
+
reject('E_SCHEMA', `item ${id}: type must be one of ${ITEM_TYPES.join('|')}`);
|
|
462
|
+
}
|
|
463
|
+
if (item.description !== null && !(typeof item.description === 'string' && item.description.length <= MAX_DESCRIPTION_CHARS)) {
|
|
464
|
+
reject('E_SCHEMA', `item ${id}: description must be at most ${MAX_DESCRIPTION_CHARS} characters`);
|
|
465
|
+
}
|
|
466
|
+
if (!Array.isArray(item.labels) || item.labels.length > MAX_LABELS) {
|
|
467
|
+
reject('E_SCHEMA', `item ${id}: labels must be an array of at most ${MAX_LABELS} labels`);
|
|
468
|
+
}
|
|
469
|
+
for (const label of item.labels) {
|
|
470
|
+
if (!(typeof label === 'string' && label.length >= 1 && label.length <= MAX_LABEL_CHARS)) {
|
|
471
|
+
reject('E_SCHEMA', `item ${id}: every label must be 1-${MAX_LABEL_CHARS} characters`);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
if (!Array.isArray(item.history) || item.history.length > MAX_ITEM_HISTORY) {
|
|
475
|
+
reject('E_SCHEMA', `item ${id}: history must be an array capped at ${MAX_ITEM_HISTORY}`);
|
|
476
|
+
}
|
|
477
|
+
for (const event of item.history) {
|
|
478
|
+
validateHistoryEvent(`item ${id}`, event, ITEM_HISTORY_TYPES);
|
|
479
|
+
}
|
|
480
|
+
return item;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
const validateHistoryEvent = (where, event, types) => {
|
|
484
|
+
if (!isRecord(event) || !isIsoZ(event.at)) reject('E_SCHEMA', `${where}: every history event needs an RFC 3339 "at"`);
|
|
485
|
+
if (!types.has(event.type)) reject('E_SCHEMA', `${where}: history event type "${String(event.type)}" is unknown`);
|
|
486
|
+
if (typeof event.actor !== 'string') reject('E_SCHEMA', `${where}: every history event needs an "actor"`);
|
|
487
|
+
if (event.detail !== null && typeof event.detail !== 'string') {
|
|
488
|
+
reject('E_SCHEMA', `${where}: history "detail" must be a string or null`);
|
|
489
|
+
}
|
|
490
|
+
};
|
|
491
|
+
|
|
492
|
+
/** Identity phase: the file stem is the id (one file per id, D-2). */
|
|
493
|
+
export function validateItemIdentity(item, fileStem) {
|
|
494
|
+
if (!ITEM_ID_RE.test(String(fileStem)) || Number(fileStem) !== item.id) {
|
|
495
|
+
reject('E_TRACKER_DUPLICATE_ID', `item file "${fileStem}.json" holds id "${item.id}"`);
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
const detectsCycleThrough = (startId, itemsById) => {
|
|
500
|
+
const seen = new Set();
|
|
501
|
+
const stack = [startId];
|
|
502
|
+
while (stack.length > 0) {
|
|
503
|
+
const current = stack.pop();
|
|
504
|
+
if (seen.has(current)) continue;
|
|
505
|
+
seen.add(current);
|
|
506
|
+
for (const dep of itemsById.get(current)?.dependsOn ?? []) {
|
|
507
|
+
if (dep === startId) return true;
|
|
508
|
+
if (!seen.has(dep)) stack.push(dep);
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
return false;
|
|
512
|
+
};
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* Graph phase: dependencies must exist, must not name the item itself, and the
|
|
516
|
+
* graph must stay acyclic (including 2-cycles). `supersededBy` must name an
|
|
517
|
+
* existing item. Broken files are a recorded error, never a cascade (D-3).
|
|
518
|
+
*/
|
|
519
|
+
export function validateItemGraph(item, itemsById) {
|
|
520
|
+
// The prospective record's own edges are part of the graph under test.
|
|
521
|
+
const merged = new Map(itemsById);
|
|
522
|
+
merged.set(item.id, item);
|
|
523
|
+
for (const dep of item.dependsOn ?? []) {
|
|
524
|
+
if (dep === item.id) reject('E_TRACKER_SELF_DEP', `item ${item.id}: dependsOn contains itself`);
|
|
525
|
+
if (!merged.has(dep)) reject('E_TRACKER_UNKNOWN_DEP', `item ${item.id}: dependency "${dep}" has no item file`);
|
|
526
|
+
}
|
|
527
|
+
if (item.supersededBy !== null && !merged.has(item.supersededBy)) {
|
|
528
|
+
reject('E_TRACKER_UNKNOWN_DEP', `item ${item.id}: supersededBy "${item.supersededBy}" has no item file`);
|
|
529
|
+
}
|
|
530
|
+
if (detectsCycleThrough(item.id, merged)) {
|
|
531
|
+
reject('E_TRACKER_CYCLE', `item ${item.id}: dependsOn contains a cycle`);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* The stored lattice: planned → completed (reopen back to planned), planned →
|
|
537
|
+
* cancelled, planned → superseded. Terminal statuses never leave. A cancelled
|
|
538
|
+
* item needs its `cancelReason` (the frozen outcome table folds this into
|
|
539
|
+
* `E_TRACKER_TRANSITION`).
|
|
540
|
+
*/
|
|
541
|
+
export function validateTransition(existing, next) {
|
|
542
|
+
const from = existing?.status ?? null;
|
|
543
|
+
const to = next.status;
|
|
544
|
+
const needsReason = () => {
|
|
545
|
+
if (to === 'cancelled' && !(typeof next.cancelReason === 'string' && next.cancelReason.length >= 1)) {
|
|
546
|
+
reject('E_TRACKER_TRANSITION', `item ${next.id}: a cancelled item needs cancelReason`);
|
|
547
|
+
}
|
|
548
|
+
};
|
|
549
|
+
if (from === null) {
|
|
550
|
+
needsReason();
|
|
551
|
+
return;
|
|
552
|
+
}
|
|
553
|
+
if (to === from) {
|
|
554
|
+
needsReason();
|
|
555
|
+
return;
|
|
556
|
+
}
|
|
557
|
+
const legal = {
|
|
558
|
+
backlog: new Set(['backlog', 'planned', 'completed', 'cancelled', 'superseded']),
|
|
559
|
+
planned: new Set(['backlog', 'planned', 'completed', 'cancelled', 'superseded']),
|
|
560
|
+
completed: new Set(['backlog', 'planned']),
|
|
561
|
+
cancelled: new Set(),
|
|
562
|
+
superseded: new Set(),
|
|
563
|
+
};
|
|
564
|
+
if (!legal[from]?.has(to)) {
|
|
565
|
+
reject('E_TRACKER_TRANSITION', `item ${next.id}: transition ${from} -> ${to} is outside the stored lattice`);
|
|
566
|
+
}
|
|
567
|
+
needsReason();
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/* ------------------------------- queue schema ----------------------------- */
|
|
571
|
+
|
|
572
|
+
export function validateEntrySchema(entry) {
|
|
573
|
+
if (!isRecord(entry)) reject('E_SCHEMA', 'queue entry must be an object');
|
|
574
|
+
if (entry.schemaVersion !== ENTRY_SCHEMA_VERSION) {
|
|
575
|
+
reject('E_SCHEMA', `entry ${entry.entryId ?? '?'}: schemaVersion must be ${ENTRY_SCHEMA_VERSION}`);
|
|
576
|
+
}
|
|
577
|
+
if (typeof entry.entryId !== 'string' || !ENTRY_ID_RE.test(entry.entryId)) {
|
|
578
|
+
reject('E_SCHEMA', `entry id must match ${ENTRY_ID_RE.source}`);
|
|
579
|
+
}
|
|
580
|
+
if (!Number.isInteger(entry.itemId) || entry.itemId < 1) {
|
|
581
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: itemId must be a positive integer`);
|
|
582
|
+
}
|
|
583
|
+
if (entry.taskSlug !== undefined && entry.taskSlug !== null) {
|
|
584
|
+
if (typeof entry.taskSlug !== 'string' || !TASK_SLUG_RE.test(entry.taskSlug) || entry.taskSlug.length > MAX_TASK_SLUG_CHARS) {
|
|
585
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: taskSlug must match ${TASK_SLUG_RE.source} with 3-${MAX_TASK_SLUG_CHARS} characters`);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
if (entry.linkId !== undefined && entry.linkId !== null) {
|
|
589
|
+
if (typeof entry.linkId !== 'string' || entry.linkId.length > 160) {
|
|
590
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: linkId must be null or <itemId>--<taskSlug>`);
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
if (!ENTRY_STATUSES.includes(entry.status)) {
|
|
594
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: status must be one of ${ENTRY_STATUSES.join('|')}`);
|
|
595
|
+
}
|
|
596
|
+
if (!(typeof entry.reason === 'string' && entry.reason.length >= 1 && entry.reason.length <= MAX_REASON_CHARS)) {
|
|
597
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: reason must be 1-${MAX_REASON_CHARS} characters`);
|
|
598
|
+
}
|
|
599
|
+
if (!(typeof entry.requestedBy === 'string' && entry.requestedBy.length >= 1 && entry.requestedBy.length <= MAX_REQUESTED_BY_CHARS)) {
|
|
600
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: requestedBy must be 1-${MAX_REQUESTED_BY_CHARS} characters`);
|
|
601
|
+
}
|
|
602
|
+
if (entry.command !== null && !(typeof entry.command === 'string' && entry.command.length >= 1 && entry.command.length <= MAX_COMMAND_CHARS)) {
|
|
603
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: command must be null or 1-${MAX_COMMAND_CHARS} characters`);
|
|
604
|
+
}
|
|
605
|
+
if (!Number.isInteger(entry.revision) || entry.revision < 1) {
|
|
606
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: revision must be an integer >= 1`);
|
|
607
|
+
}
|
|
608
|
+
if (!isIsoZ(entry.requestedAt)) reject('E_SCHEMA', `entry ${entry.entryId}: requestedAt must be an RFC 3339 timestamp ending in Z`);
|
|
609
|
+
if (entry.claimedAt !== null && !isIsoZ(entry.claimedAt)) {
|
|
610
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: claimedAt must be null or an RFC 3339 timestamp`);
|
|
611
|
+
}
|
|
612
|
+
if (entry.status === 'claimed' && entry.claimedAt === null) {
|
|
613
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: claimedAt is required when status is claimed`);
|
|
614
|
+
}
|
|
615
|
+
if (entry.finishedAt !== null && !isIsoZ(entry.finishedAt)) {
|
|
616
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: finishedAt must be null or an RFC 3339 timestamp`);
|
|
617
|
+
}
|
|
618
|
+
if ((entry.status === 'cancelled' || entry.status === 'expired') && entry.finishedAt === null) {
|
|
619
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: finishedAt is required when status is ${entry.status}`);
|
|
620
|
+
}
|
|
621
|
+
if (!Array.isArray(entry.history) || entry.history.length > MAX_ENTRY_HISTORY) {
|
|
622
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: history must be an array capped at ${MAX_ENTRY_HISTORY}`);
|
|
623
|
+
}
|
|
624
|
+
for (const event of entry.history) {
|
|
625
|
+
validateHistoryEvent(`entry ${entry.entryId}`, event, ENTRY_HISTORY_TYPES);
|
|
626
|
+
}
|
|
627
|
+
return entry;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/* ------------------------------- link schema ------------------------------ */
|
|
631
|
+
|
|
632
|
+
const LINK_ID_RE = /^[1-9][0-9]*--[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
633
|
+
|
|
634
|
+
export function validateLinkSchema(link) {
|
|
635
|
+
if (!isRecord(link)) reject('E_SCHEMA', 'tracker link must be an object');
|
|
636
|
+
if (link.schemaVersion !== LINK_SCHEMA_VERSION) {
|
|
637
|
+
reject('E_SCHEMA', `link ${link.linkId ?? '?'}: schemaVersion must be ${LINK_SCHEMA_VERSION}`);
|
|
638
|
+
}
|
|
639
|
+
if (typeof link.linkId !== 'string' || !LINK_ID_RE.test(link.linkId) || link.linkId.length > 160) {
|
|
640
|
+
reject('E_SCHEMA', `link ${link.linkId ?? '?'}: linkId must be <itemId>--<taskSlug>`);
|
|
641
|
+
}
|
|
642
|
+
if (!Number.isInteger(link.itemId) || link.itemId < 1) {
|
|
643
|
+
reject('E_SCHEMA', `link ${link.linkId}: itemId must be a positive integer`);
|
|
644
|
+
}
|
|
645
|
+
if (typeof link.taskSlug !== 'string' || !TASK_SLUG_RE.test(link.taskSlug) || link.taskSlug.length > MAX_TASK_SLUG_CHARS) {
|
|
646
|
+
reject('E_SCHEMA', `link ${link.linkId}: taskSlug must match ${TASK_SLUG_RE.source} with 3-${MAX_TASK_SLUG_CHARS} characters`);
|
|
647
|
+
}
|
|
648
|
+
if (link.linkId !== linkIdOf(link.itemId, link.taskSlug)) {
|
|
649
|
+
reject('E_SCHEMA', `link ${link.linkId}: linkId must be "${linkIdOf(link.itemId, link.taskSlug)}"`);
|
|
650
|
+
}
|
|
651
|
+
if (link.entryId !== null && (typeof link.entryId !== 'string' || !ENTRY_ID_RE.test(link.entryId))) {
|
|
652
|
+
reject('E_SCHEMA', `link ${link.linkId}: entryId must be null or a queue entry id`);
|
|
653
|
+
}
|
|
654
|
+
if (!LINK_ROLES.includes(link.role)) {
|
|
655
|
+
reject('E_SCHEMA', `link ${link.linkId}: role must be one of ${LINK_ROLES.join('|')}`);
|
|
656
|
+
}
|
|
657
|
+
if (!LINK_DECISIONS.includes(link.decision)) {
|
|
658
|
+
reject('E_SCHEMA', `link ${link.linkId}: decision must be one of ${LINK_DECISIONS.join('|')}`);
|
|
659
|
+
}
|
|
660
|
+
if (
|
|
661
|
+
link.promptPath !== null &&
|
|
662
|
+
!(typeof link.promptPath === 'string' && link.promptPath.startsWith(`${TRACKER_DIR}/${LINKS_DIR}/`) && !link.promptPath.includes('..'))
|
|
663
|
+
) {
|
|
664
|
+
reject('E_SCHEMA', `link ${link.linkId}: promptPath must stay under ${TRACKER_DIR}/${LINKS_DIR}/`);
|
|
665
|
+
}
|
|
666
|
+
if (link.language !== null && !(typeof link.language === 'string' && link.language.length >= 2 && link.language.length <= 16)) {
|
|
667
|
+
reject('E_SCHEMA', `link ${link.linkId}: language must be null or a 2-16 character tag`);
|
|
668
|
+
}
|
|
669
|
+
if (!Number.isInteger(link.revision) || link.revision < 1) {
|
|
670
|
+
reject('E_SCHEMA', `link ${link.linkId}: revision must be an integer >= 1`);
|
|
671
|
+
}
|
|
672
|
+
if (!isIsoZ(link.createdAt)) reject('E_SCHEMA', `link ${link.linkId}: createdAt must be an RFC 3339 timestamp ending in Z`);
|
|
673
|
+
if (!isIsoZ(link.updatedAt)) reject('E_SCHEMA', `link ${link.linkId}: updatedAt must be an RFC 3339 timestamp ending in Z`);
|
|
674
|
+
if (Date.parse(link.updatedAt) < Date.parse(link.createdAt)) {
|
|
675
|
+
reject('E_SCHEMA', `link ${link.linkId}: updatedAt must be >= createdAt`);
|
|
676
|
+
}
|
|
677
|
+
if (!Array.isArray(link.history) || link.history.length > MAX_LINK_HISTORY) {
|
|
678
|
+
reject('E_SCHEMA', `link ${link.linkId}: history must be an array capped at ${MAX_LINK_HISTORY}`);
|
|
679
|
+
}
|
|
680
|
+
for (const event of link.history) {
|
|
681
|
+
if (!isRecord(event) || !isIsoZ(event.at) || typeof event.type !== 'string' || typeof event.actor !== 'string') {
|
|
682
|
+
reject('E_SCHEMA', `link ${link.linkId}: every history event needs at, type and actor`);
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
return link;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
export function validateLinkIdentity(link, fileStem) {
|
|
689
|
+
if (link.linkId !== fileStem) {
|
|
690
|
+
reject('E_TRACKER_LINK_ID', `link file "${fileStem}.json" holds linkId "${link.linkId}"`);
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
/* ------------------------------ file writes ------------------------------- */
|
|
695
|
+
|
|
696
|
+
const writeAtomic = (file, content) => {
|
|
697
|
+
const tmp = `${file}.tmp`;
|
|
698
|
+
fs.writeFileSync(tmp, content, { encoding: 'utf8', mode: 0o600 });
|
|
699
|
+
fs.renameSync(tmp, file);
|
|
700
|
+
};
|
|
701
|
+
|
|
702
|
+
const writeItemFile = (teamRoot, item) => {
|
|
703
|
+
ensureTrackerDirs(teamRoot);
|
|
704
|
+
writeAtomic(itemFilePath(teamRoot, item.id), `${JSON.stringify(item, null, 2)}\n`);
|
|
705
|
+
};
|
|
706
|
+
|
|
707
|
+
const writeEntryFile = (teamRoot, entry) => {
|
|
708
|
+
ensureTrackerDirs(teamRoot);
|
|
709
|
+
writeAtomic(entryFilePath(teamRoot, entry.entryId), `${JSON.stringify(entry, null, 2)}\n`);
|
|
710
|
+
};
|
|
711
|
+
|
|
712
|
+
const writeLinkFile = (teamRoot, link) => {
|
|
713
|
+
ensureTrackerDirs(teamRoot);
|
|
714
|
+
writeAtomic(linkFilePath(teamRoot, link.linkId), `${JSON.stringify(link, null, 2)}\n`);
|
|
715
|
+
};
|
|
716
|
+
|
|
717
|
+
const writeLinkPrompt = (teamRoot, linkId, prompt) => {
|
|
718
|
+
ensureTrackerDirs(teamRoot);
|
|
719
|
+
writeAtomic(linkPromptPath(teamRoot, linkId), prompt);
|
|
720
|
+
};
|
|
721
|
+
|
|
722
|
+
/** The scheduler's `newRunId` shape — duplicated so the queue stays file-only. */
|
|
723
|
+
export const newEntryId = () => {
|
|
724
|
+
const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}Z$/, 'Z');
|
|
725
|
+
return `${stamp}-${crypto.randomBytes(4).toString('hex')}`;
|
|
726
|
+
};
|
|
727
|
+
|
|
728
|
+
/* ---------------------------- derived statuses ---------------------------- */
|
|
729
|
+
|
|
730
|
+
/** The stored decision lattice plus the derived operational status (I-3). */
|
|
731
|
+
export const effectiveItemStatus = (item, taskState, nonTerminalEntryExists, links = [], taskStates = new Map()) => {
|
|
732
|
+
if (item.status === 'cancelled') return 'cancelled';
|
|
733
|
+
if (item.status === 'superseded') return 'superseded';
|
|
734
|
+
if (item.status === 'completed') return 'completed';
|
|
735
|
+
if (links.length > 0) {
|
|
736
|
+
const states = links.map((link) => effectiveLinkState(link, null, taskStates.get(link.taskSlug) ?? null));
|
|
737
|
+
if (states.every((state) => state === 'completed')) return 'completed';
|
|
738
|
+
if (states.some((state) => ['active', 'paused', 'claimed'].includes(state))) return 'launched';
|
|
739
|
+
if (states.some((state) => state === 'requested')) return 'queued';
|
|
740
|
+
if (states.every((state) => ['stopped', 'unlinked'].includes(state))) {
|
|
741
|
+
if (nonTerminalEntryExists) return 'queued';
|
|
742
|
+
return item.status === 'backlog' ? 'backlog' : 'planned';
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
if (taskState === 'completed') return 'completed';
|
|
746
|
+
if (item.status === 'backlog') return 'backlog';
|
|
747
|
+
if (taskState !== null) return 'launched';
|
|
748
|
+
if (nonTerminalEntryExists) return 'queued';
|
|
749
|
+
return 'planned';
|
|
750
|
+
};
|
|
751
|
+
|
|
752
|
+
export const effectiveEntryStatus = (entry, taskState) => {
|
|
753
|
+
if (entry.status === 'cancelled') return 'cancelled';
|
|
754
|
+
if (entry.status === 'expired') return 'expired';
|
|
755
|
+
if (taskState === 'completed') return 'done';
|
|
756
|
+
if (taskState !== null) return 'active';
|
|
757
|
+
if (entry.status === 'claimed') return 'claimed';
|
|
758
|
+
return 'queued';
|
|
759
|
+
};
|
|
760
|
+
|
|
761
|
+
/**
|
|
762
|
+
* The derived state of one link.
|
|
763
|
+
*
|
|
764
|
+
* The stored decision wins only for a stop/unlink the operator made. A task
|
|
765
|
+
* row, when present, is the stronger signal: completed/active/paused. An open
|
|
766
|
+
* queue entry means the request is still waiting for the hook.
|
|
767
|
+
*/
|
|
768
|
+
export const effectiveLinkState = (link, entry, taskState) => {
|
|
769
|
+
if (link.decision === 'unlinked') return 'unlinked';
|
|
770
|
+
if (link.decision === 'stopped') return 'stopped';
|
|
771
|
+
if (taskState === 'completed') return 'completed';
|
|
772
|
+
if (taskState === 'paused') return 'paused';
|
|
773
|
+
if (taskState !== null) return 'active';
|
|
774
|
+
if (entry !== null && entry !== undefined) {
|
|
775
|
+
if (entry.status === 'claimed') return 'claimed';
|
|
776
|
+
if (entry.status === 'queued') return 'requested';
|
|
777
|
+
}
|
|
778
|
+
return 'requested';
|
|
779
|
+
};
|
|
780
|
+
|
|
781
|
+
const isNonTerminalEntryStatus = (status) => !['cancelled', 'expired', 'done'].includes(status);
|
|
782
|
+
|
|
783
|
+
/** Collapse the linked task states into the item's display state. */
|
|
784
|
+
const aggregateTaskState = (states, linkCount, legacyState) => {
|
|
785
|
+
if (legacyState !== null) return legacyState;
|
|
786
|
+
if (linkCount === 0 || states.length === 0) return null;
|
|
787
|
+
if (states.every((state) => state === 'completed')) return 'completed';
|
|
788
|
+
const holding = states.find((state) => HOLDING_TASK_STATES.has(state));
|
|
789
|
+
if (holding !== undefined) return holding;
|
|
790
|
+
if (states.includes('paused')) return 'paused';
|
|
791
|
+
return states[0];
|
|
792
|
+
};
|
|
793
|
+
|
|
794
|
+
/* ------------------------------- ordering --------------------------------- */
|
|
795
|
+
|
|
796
|
+
/** The total order comparator: `priority ASC → createdAt ASC → id ASC` (R-3). */
|
|
797
|
+
export const rankCompare = (left, right) =>
|
|
798
|
+
left.priority - right.priority ||
|
|
799
|
+
(left.createdAt < right.createdAt ? -1 : left.createdAt > right.createdAt ? 1 : 0) ||
|
|
800
|
+
(left.id < right.id ? -1 : left.id > right.id ? 1 : 0);
|
|
801
|
+
|
|
802
|
+
/**
|
|
803
|
+
* One snapshot, one pass (D-4, R-1…R-6). Feed this the item, queue, link and
|
|
804
|
+
* task records the caller read once — files on the CLI path, projected rows on
|
|
805
|
+
* the API path — so the CLI and the SQL read plane can never disagree. No wall
|
|
806
|
+
* clock, readdir order or database row order may influence the output.
|
|
807
|
+
*/
|
|
808
|
+
export function deriveTrackerOrdering({ items, entries, links = new Map(), taskStates, asOf }) {
|
|
809
|
+
const byId = new Map();
|
|
810
|
+
const linksByItem = new Map();
|
|
811
|
+
for (const link of links.values()) {
|
|
812
|
+
const list = linksByItem.get(link.itemId) ?? [];
|
|
813
|
+
list.push(link);
|
|
814
|
+
linksByItem.set(link.itemId, list);
|
|
815
|
+
}
|
|
816
|
+
const entryTaskSlug = (entry) => entry.taskSlug ?? `tracker-${entry.itemId}`;
|
|
817
|
+
const entryStatuses = new Map();
|
|
818
|
+
for (const [entryId, entry] of entries) {
|
|
819
|
+
entryStatuses.set(entryId, effectiveEntryStatus(entry, taskStates.get(entryTaskSlug(entry)) ?? null));
|
|
820
|
+
}
|
|
821
|
+
const openEntriesByItem = new Map();
|
|
822
|
+
for (const [entryId, entry] of entries) {
|
|
823
|
+
const status = entryStatuses.get(entryId);
|
|
824
|
+
if (!isNonTerminalEntryStatus(status)) continue;
|
|
825
|
+
const list = openEntriesByItem.get(entry.itemId) ?? [];
|
|
826
|
+
list.push(entryId);
|
|
827
|
+
openEntriesByItem.set(entry.itemId, list);
|
|
828
|
+
}
|
|
829
|
+
for (const [id, item] of items) {
|
|
830
|
+
const itemLinks = linksByItem.get(id) ?? [];
|
|
831
|
+
const statusLinks = itemLinks.filter((link) => link.decision !== 'unlinked');
|
|
832
|
+
const linkedStates = statusLinks
|
|
833
|
+
.map((link) => taskStates.get(link.taskSlug) ?? null)
|
|
834
|
+
.filter((state) => state !== null);
|
|
835
|
+
const legacyState = statusLinks.length === 0 ? (taskStates.get(String(id)) ?? null) : null;
|
|
836
|
+
const taskState = aggregateTaskState(linkedStates, statusLinks.length, legacyState);
|
|
837
|
+
const openEntries = openEntriesByItem.get(id) ?? [];
|
|
838
|
+
const openEntryId = openEntries.length > 0 ? openEntries.sort()[0] : null;
|
|
839
|
+
const openEntry = openEntryId !== null ? entries.get(openEntryId) : null;
|
|
840
|
+
const effectiveStatus = effectiveItemStatus(item, taskState, openEntryId !== null, statusLinks, taskStates);
|
|
841
|
+
byId.set(id, {
|
|
842
|
+
item,
|
|
843
|
+
effectiveStatus,
|
|
844
|
+
taskState,
|
|
845
|
+
openEntry,
|
|
846
|
+
queueEntryId: openEntryId,
|
|
847
|
+
queuedAt: openEntry?.requestedAt ?? null,
|
|
848
|
+
links: itemLinks,
|
|
849
|
+
ready: false,
|
|
850
|
+
blocked: false,
|
|
851
|
+
waitingOn: [],
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
for (const [id, annotated] of byId) {
|
|
855
|
+
const unsatisfied = (annotated.item.dependsOn ?? []).filter((dep) => {
|
|
856
|
+
const depAnnotated = byId.get(dep);
|
|
857
|
+
return !depAnnotated || depAnnotated.effectiveStatus !== 'completed';
|
|
858
|
+
});
|
|
859
|
+
unsatisfied.sort((a, b) => rankCompare(byId.get(a).item, byId.get(b).item));
|
|
860
|
+
annotated.waitingOn = unsatisfied;
|
|
861
|
+
annotated.blocked = unsatisfied.length > 0;
|
|
862
|
+
// An enqueued item keeps its operational launchability: effective status
|
|
863
|
+
// `queued` is the planned state plus a recorded request, and reading it as
|
|
864
|
+
// "not ready" would empty the drain order for every input (D-5 requires
|
|
865
|
+
// the entry to "become claimable when the graph allows it").
|
|
866
|
+
annotated.ready = ['planned', 'queued'].includes(annotated.effectiveStatus) && !annotated.blocked;
|
|
867
|
+
}
|
|
868
|
+
const rankedItems = [...byId.values()].sort((a, b) => rankCompare(a.item, b.item));
|
|
869
|
+
const readyIds = rankedItems.filter((annotated) => annotated.ready).map((annotated) => annotated.item.id);
|
|
870
|
+
const drainOrderEntryIds = [...entries.values()]
|
|
871
|
+
.filter((entry) => {
|
|
872
|
+
if (entryStatuses.get(entry.entryId) !== 'queued') return false;
|
|
873
|
+
const annotated = byId.get(entry.itemId);
|
|
874
|
+
return annotated !== undefined && annotated.ready;
|
|
875
|
+
})
|
|
876
|
+
.sort((a, b) => rankCompare(byId.get(a.itemId).item, byId.get(b.itemId).item))
|
|
877
|
+
.map((entry) => entry.entryId);
|
|
878
|
+
return {
|
|
879
|
+
asOf,
|
|
880
|
+
byId,
|
|
881
|
+
readyIds,
|
|
882
|
+
drainOrderEntryIds,
|
|
883
|
+
criticalPathIds: computeCriticalPathIds(items, byId),
|
|
884
|
+
};
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
/** Longest chain of open items in item count; ties by the rank of the chain's first item. */
|
|
888
|
+
const computeCriticalPathIds = (items, byId) => {
|
|
889
|
+
const openIds = new Set(
|
|
890
|
+
[...byId.values()]
|
|
891
|
+
.filter((annotated) => ['backlog', 'planned', 'queued', 'launched'].includes(annotated.effectiveStatus))
|
|
892
|
+
.map((annotated) => annotated.item.id),
|
|
893
|
+
);
|
|
894
|
+
const memo = new Map();
|
|
895
|
+
const chainBetter = (a, b) => {
|
|
896
|
+
if (b.length === 0) return true;
|
|
897
|
+
if (a.length !== b.length) return a.length > b.length;
|
|
898
|
+
return rankCompare(items.get(a[0]), items.get(b[0])) < 0;
|
|
899
|
+
};
|
|
900
|
+
const longest = (id) => {
|
|
901
|
+
if (memo.has(id)) return memo.get(id);
|
|
902
|
+
const deps = (items.get(id)?.dependsOn ?? []).filter((dep) => openIds.has(dep));
|
|
903
|
+
let best = [id];
|
|
904
|
+
for (const dep of deps) {
|
|
905
|
+
const candidate = [id, ...longest(dep)];
|
|
906
|
+
if (chainBetter(candidate, best)) best = candidate;
|
|
907
|
+
}
|
|
908
|
+
memo.set(id, best);
|
|
909
|
+
return best;
|
|
910
|
+
};
|
|
911
|
+
let best = [];
|
|
912
|
+
for (const id of openIds) {
|
|
913
|
+
const candidate = longest(id);
|
|
914
|
+
if (chainBetter(candidate, best)) best = candidate;
|
|
915
|
+
}
|
|
916
|
+
return best;
|
|
917
|
+
};
|
|
918
|
+
|
|
919
|
+
/** Read the whole tracker tree once, under the tree lock (R-4). */
|
|
920
|
+
export function readTrackerSnapshot(teamRoot) {
|
|
921
|
+
return withTrackerLock(teamRoot, () => {
|
|
922
|
+
const asOf = nowIso();
|
|
923
|
+
const items = new Map();
|
|
924
|
+
const entries = new Map();
|
|
925
|
+
const errors = [];
|
|
926
|
+
for (const id of listItemIds(teamRoot)) {
|
|
927
|
+
try {
|
|
928
|
+
items.set(id, JSON.parse(fs.readFileSync(itemFilePath(teamRoot, id), 'utf8')));
|
|
929
|
+
} catch (error) {
|
|
930
|
+
errors.push({ path: `tracker/items/${id}.json`, reason: error.message });
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
for (const entryId of listEntryIds(teamRoot)) {
|
|
934
|
+
try {
|
|
935
|
+
entries.set(entryId, JSON.parse(fs.readFileSync(entryFilePath(teamRoot, entryId), 'utf8')));
|
|
936
|
+
} catch (error) {
|
|
937
|
+
errors.push({ path: `tracker/queue/${entryId}.json`, reason: error.message });
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
const links = new Map();
|
|
941
|
+
for (const linkId of listLinkIds(teamRoot)) {
|
|
942
|
+
try {
|
|
943
|
+
links.set(linkId, JSON.parse(fs.readFileSync(linkFilePath(teamRoot, linkId), 'utf8')));
|
|
944
|
+
} catch (error) {
|
|
945
|
+
errors.push({ path: `tracker/links/${linkId}.json`, reason: error.message });
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
return { asOf, items, entries, links, taskStates: readTaskStates(teamRoot), errors };
|
|
949
|
+
});
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
export const countActiveTasks = (taskStates) => {
|
|
953
|
+
let count = 0;
|
|
954
|
+
for (const state of taskStates.values()) {
|
|
955
|
+
if (HOLDING_TASK_STATES.has(state)) count += 1;
|
|
956
|
+
}
|
|
957
|
+
return count;
|
|
958
|
+
};
|
|
959
|
+
|
|
960
|
+
/* ------------------------------- item writes ------------------------------ */
|
|
961
|
+
|
|
962
|
+
export function addTrackerItem(teamRoot, payload, options = {}) {
|
|
963
|
+
if (!isRecord(payload)) reject('E_SCHEMA', 'tracker add payload must be an object');
|
|
964
|
+
return withTrackerLock(teamRoot, () => {
|
|
965
|
+
const items = readAllItems(teamRoot);
|
|
966
|
+
const id = nextItemId(teamRoot);
|
|
967
|
+
const now = nowIso();
|
|
968
|
+
const createdAt = payload.createdAt ?? now;
|
|
969
|
+
const item = {
|
|
970
|
+
schemaVersion: ITEM_SCHEMA_VERSION,
|
|
971
|
+
id,
|
|
972
|
+
revision: 1,
|
|
973
|
+
title: typeof payload.title === 'string' ? payload.title.trim() : payload.title,
|
|
974
|
+
status: payload.status ?? 'planned',
|
|
975
|
+
priority: payload.priority ?? 5,
|
|
976
|
+
sourceTask: payload.sourceTask ?? null,
|
|
977
|
+
sourceRefs: payload.sourceRefs ?? [],
|
|
978
|
+
createdAt,
|
|
979
|
+
updatedAt: now,
|
|
980
|
+
completedAt: payload.completedAt ?? null,
|
|
981
|
+
cancelledAt: payload.cancelledAt ?? null,
|
|
982
|
+
cancelReason: payload.cancelReason ?? null,
|
|
983
|
+
supersededBy: payload.supersededBy ?? null,
|
|
984
|
+
type: payload.type ?? 'feature',
|
|
985
|
+
description: payload.description ?? null,
|
|
986
|
+
labels: payload.labels ?? [],
|
|
987
|
+
dependsOn: payload.dependsOn ?? [],
|
|
988
|
+
history: [{ at: now, type: 'created', actor: options.actor ?? 'operator', detail: null }],
|
|
989
|
+
};
|
|
990
|
+
validateItemSchema(item);
|
|
991
|
+
validateItemIdentity(item, id);
|
|
992
|
+
validateItemGraph(item, items);
|
|
993
|
+
validateTransition(null, item);
|
|
994
|
+
writeItemFile(teamRoot, item);
|
|
995
|
+
return item;
|
|
996
|
+
});
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
export function setTrackerItem(teamRoot, id, payload, options = {}) {
|
|
1000
|
+
if (!isRecord(payload)) reject('E_SCHEMA', 'tracker set payload must be an object');
|
|
1001
|
+
id = parseItemId(id, 'item id');
|
|
1002
|
+
return withTrackerLock(teamRoot, () => {
|
|
1003
|
+
const existing = readItemFile(teamRoot, id);
|
|
1004
|
+
if (!existing) reject('E_TRACKER_UNKNOWN_DEP', `no tracker item "${id}"`);
|
|
1005
|
+
if (!Number.isInteger(payload.revision) || payload.revision !== existing.revision) {
|
|
1006
|
+
reject('E_TRACKER_REVISION', `item ${id}: revision ${payload.revision ?? 'missing'} does not match the stored ${existing.revision}`);
|
|
1007
|
+
}
|
|
1008
|
+
const next = { ...existing };
|
|
1009
|
+
for (const key of ['title', 'status', 'priority', 'dependsOn', 'type', 'description', 'labels', 'completedAt', 'cancelledAt', 'cancelReason', 'supersededBy']) {
|
|
1010
|
+
if (payload[key] !== undefined) next[key] = payload[key];
|
|
1011
|
+
}
|
|
1012
|
+
if (payload.title !== undefined) next.title = typeof next.title === 'string' ? next.title.trim() : next.title;
|
|
1013
|
+
const now = nowIso();
|
|
1014
|
+
next.revision = existing.revision + 1;
|
|
1015
|
+
next.updatedAt = now;
|
|
1016
|
+
validateItemSchema(next);
|
|
1017
|
+
validateItemIdentity(next, id);
|
|
1018
|
+
validateItemGraph(next, readAllItems(teamRoot));
|
|
1019
|
+
validateTransition(existing, next);
|
|
1020
|
+
const actor = options.actor ?? 'operator';
|
|
1021
|
+
let type = 'updated';
|
|
1022
|
+
if (next.status !== existing.status) {
|
|
1023
|
+
if (next.status === 'completed') type = 'completed';
|
|
1024
|
+
else if (next.status === 'cancelled') type = 'cancelled';
|
|
1025
|
+
else if (next.status === 'superseded') type = 'superseded';
|
|
1026
|
+
else if (next.status === 'planned' && existing.status === 'completed') type = 'reopened';
|
|
1027
|
+
else type = 'status-changed';
|
|
1028
|
+
} else if (next.priority !== existing.priority) {
|
|
1029
|
+
type = 'priority-changed';
|
|
1030
|
+
} else if (canonicalJson(next.dependsOn) !== canonicalJson(existing.dependsOn)) {
|
|
1031
|
+
type = 'deps-changed';
|
|
1032
|
+
}
|
|
1033
|
+
next.history = capHistory([...(existing.history ?? []), { at: now, type, actor, detail: null }], MAX_ITEM_HISTORY);
|
|
1034
|
+
if (next.status === 'cancelled' || next.status === 'superseded') {
|
|
1035
|
+
expireEntriesForItem(teamRoot, id, next.status === 'cancelled' ? 'item-cancelled' : 'item-superseded', actor);
|
|
1036
|
+
}
|
|
1037
|
+
writeItemFile(teamRoot, next);
|
|
1038
|
+
return next;
|
|
1039
|
+
});
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
/* ------------------------------- link writes ------------------------------ */
|
|
1043
|
+
|
|
1044
|
+
export function listLinksForItem(teamRoot, itemId) {
|
|
1045
|
+
itemId = parseItemId(itemId, 'itemId');
|
|
1046
|
+
return [...readAllLinks(teamRoot).values()]
|
|
1047
|
+
.filter((link) => link.itemId === itemId)
|
|
1048
|
+
.sort((left, right) => left.createdAt.localeCompare(right.createdAt) || left.linkId.localeCompare(right.linkId));
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
export function addTrackerLink(teamRoot, payload, options = {}) {
|
|
1052
|
+
if (!isRecord(payload)) reject('E_SCHEMA', 'tracker link payload must be an object');
|
|
1053
|
+
return withTrackerLock(teamRoot, () => {
|
|
1054
|
+
const itemId = parseItemId(payload.itemId, 'itemId');
|
|
1055
|
+
const item = readItemFile(teamRoot, itemId);
|
|
1056
|
+
if (!item) reject('E_TRACKER_UNKNOWN_DEP', `no tracker item "${itemId}"`);
|
|
1057
|
+
if (item.status === 'cancelled' || item.status === 'superseded') {
|
|
1058
|
+
reject('E_TRACKER_TRANSITION', `item ${itemId} is ${item.status}; a task cannot be linked`);
|
|
1059
|
+
}
|
|
1060
|
+
const taskSlug = payload.taskSlug;
|
|
1061
|
+
if (typeof taskSlug !== 'string' || !TASK_SLUG_RE.test(taskSlug) || taskSlug.length < 3 || taskSlug.length > MAX_TASK_SLUG_CHARS) {
|
|
1062
|
+
reject('E_SCHEMA', `taskSlug must match ${TASK_SLUG_RE.source} with 3-${MAX_TASK_SLUG_CHARS} characters`);
|
|
1063
|
+
}
|
|
1064
|
+
const linkId = linkIdOf(itemId, taskSlug);
|
|
1065
|
+
if (readLinkFile(teamRoot, linkId)) {
|
|
1066
|
+
reject('E_TRACKER_LINK_EXISTS', `link ${linkId} already exists`);
|
|
1067
|
+
}
|
|
1068
|
+
const prompt = typeof payload.prompt === 'string' && payload.prompt.trim() !== ''
|
|
1069
|
+
? payload.prompt
|
|
1070
|
+
: (item.description ?? item.title);
|
|
1071
|
+
if (Buffer.byteLength(prompt, 'utf8') > MAX_PROMPT_BYTES) {
|
|
1072
|
+
reject('E_SCHEMA', `link prompt must be at most ${MAX_PROMPT_BYTES} bytes`);
|
|
1073
|
+
}
|
|
1074
|
+
const language = payload.language ?? null;
|
|
1075
|
+
if (language !== null && !(typeof language === 'string' && language.length >= 2 && language.length <= 16)) {
|
|
1076
|
+
reject('E_SCHEMA', 'language must be null or a 2-16 character tag');
|
|
1077
|
+
}
|
|
1078
|
+
const now = nowIso();
|
|
1079
|
+
const link = {
|
|
1080
|
+
schemaVersion: LINK_SCHEMA_VERSION,
|
|
1081
|
+
linkId,
|
|
1082
|
+
itemId,
|
|
1083
|
+
taskSlug,
|
|
1084
|
+
entryId: payload.entryId ?? null,
|
|
1085
|
+
role: payload.role ?? 'primary',
|
|
1086
|
+
decision: 'requested',
|
|
1087
|
+
promptPath: `${TRACKER_DIR}/${LINKS_DIR}/${linkId}.md`,
|
|
1088
|
+
language,
|
|
1089
|
+
revision: 1,
|
|
1090
|
+
createdAt: now,
|
|
1091
|
+
updatedAt: now,
|
|
1092
|
+
history: [{ at: now, type: 'created', actor: options.actor ?? 'operator', detail: null }],
|
|
1093
|
+
};
|
|
1094
|
+
validateLinkSchema(link);
|
|
1095
|
+
validateLinkIdentity(link, linkId);
|
|
1096
|
+
writeLinkPrompt(teamRoot, linkId, prompt);
|
|
1097
|
+
writeLinkFile(teamRoot, link);
|
|
1098
|
+
return link;
|
|
1099
|
+
});
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
export function setTrackerLink(teamRoot, linkId, payload, options = {}) {
|
|
1103
|
+
if (!isRecord(payload)) reject('E_SCHEMA', 'tracker link set payload must be an object');
|
|
1104
|
+
return withTrackerLock(teamRoot, () => {
|
|
1105
|
+
const existing = readLinkFile(teamRoot, linkId);
|
|
1106
|
+
if (!existing) reject('E_TRACKER_LINK_UNKNOWN', `no tracker link "${linkId}"`);
|
|
1107
|
+
if (payload.revision !== undefined && (!Number.isInteger(payload.revision) || payload.revision !== existing.revision)) {
|
|
1108
|
+
reject('E_TRACKER_REVISION', `link ${linkId}: revision ${payload.revision ?? 'missing'} does not match the stored ${existing.revision}`);
|
|
1109
|
+
}
|
|
1110
|
+
const next = { ...existing };
|
|
1111
|
+
for (const key of ['decision', 'entryId', 'role', 'language']) {
|
|
1112
|
+
if (payload[key] !== undefined) next[key] = payload[key];
|
|
1113
|
+
}
|
|
1114
|
+
if (payload.prompt !== undefined) {
|
|
1115
|
+
if (typeof payload.prompt !== 'string' || Buffer.byteLength(payload.prompt, 'utf8') > MAX_PROMPT_BYTES) {
|
|
1116
|
+
reject('E_SCHEMA', `link prompt must be a string of at most ${MAX_PROMPT_BYTES} bytes`);
|
|
1117
|
+
}
|
|
1118
|
+
writeLinkPrompt(teamRoot, linkId, payload.prompt);
|
|
1119
|
+
}
|
|
1120
|
+
const now = nowIso();
|
|
1121
|
+
next.revision = existing.revision + 1;
|
|
1122
|
+
next.updatedAt = now;
|
|
1123
|
+
const actor = options.actor ?? 'operator';
|
|
1124
|
+
const type = next.decision !== existing.decision
|
|
1125
|
+
? (next.decision === 'stopped' ? 'stopped' : next.decision === 'unlinked' ? 'unlinked' : 'resumed')
|
|
1126
|
+
: 'updated';
|
|
1127
|
+
next.history = capHistory([...(existing.history ?? []), { at: now, type, actor, detail: null }], MAX_LINK_HISTORY);
|
|
1128
|
+
validateLinkSchema(next);
|
|
1129
|
+
validateLinkIdentity(next, linkId);
|
|
1130
|
+
writeLinkFile(teamRoot, next);
|
|
1131
|
+
return next;
|
|
1132
|
+
});
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
export function removeTrackerLink(teamRoot, linkId, options = {}) {
|
|
1136
|
+
return withTrackerLock(teamRoot, () => {
|
|
1137
|
+
const existing = readLinkFile(teamRoot, linkId);
|
|
1138
|
+
if (!existing) reject('E_TRACKER_LINK_UNKNOWN', `no tracker link "${linkId}"`);
|
|
1139
|
+
fs.rmSync(linkFilePath(teamRoot, linkId), { force: true });
|
|
1140
|
+
fs.rmSync(linkPromptPath(teamRoot, linkId), { force: true });
|
|
1141
|
+
return { linkId, itemId: existing.itemId, taskSlug: existing.taskSlug };
|
|
1142
|
+
});
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
/**
|
|
1146
|
+
* Hard delete one tracker item with its links and prompts. Team tasks are
|
|
1147
|
+
* never removed: an active link or a live queue entry refuses the delete.
|
|
1148
|
+
*/
|
|
1149
|
+
export function deleteTrackerItem(teamRoot, id, options = {}) {
|
|
1150
|
+
id = parseItemId(id, 'item id');
|
|
1151
|
+
return withTrackerLock(teamRoot, () => {
|
|
1152
|
+
const existing = readItemFile(teamRoot, id);
|
|
1153
|
+
if (!existing) reject('E_TRACKER_UNKNOWN_DEP', `no tracker item "${id}"`);
|
|
1154
|
+
const itemLinks = listLinksForItem(teamRoot, id);
|
|
1155
|
+
const taskStates = readTaskStates(teamRoot);
|
|
1156
|
+
if (itemLinks.length === 0) {
|
|
1157
|
+
const legacyState = taskStates.get(String(id)) ?? null;
|
|
1158
|
+
if (legacyState !== null && !['completed', 'cancelled', 'superseded'].includes(legacyState)) {
|
|
1159
|
+
reject('E_TRACKER_LINK_ACTIVE', `item ${id} has an active legacy task ${id}`);
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
for (const link of itemLinks) {
|
|
1163
|
+
const state = taskStates.get(link.taskSlug) ?? null;
|
|
1164
|
+
if (state !== null && !['completed', 'cancelled', 'superseded'].includes(state)) {
|
|
1165
|
+
reject('E_TRACKER_LINK_ACTIVE', `item ${id} has an active linked task ${link.taskSlug}`);
|
|
1166
|
+
}
|
|
1167
|
+
if (link.decision === 'requested' && link.entryId !== null) {
|
|
1168
|
+
const entry = readEntryFile(teamRoot, link.entryId);
|
|
1169
|
+
if (entry && ['queued', 'claimed'].includes(entry.status)) {
|
|
1170
|
+
reject('E_TRACKER_QUEUE_ACTIVE', `item ${id} has a live queue entry ${link.entryId}`);
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
for (const entry of readAllEntries(teamRoot).values()) {
|
|
1175
|
+
if (entry.itemId === id && ['queued', 'claimed'].includes(entry.status)) {
|
|
1176
|
+
reject('E_TRACKER_QUEUE_ACTIVE', `item ${id} has a live queue entry ${entry.entryId}`);
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
for (const link of itemLinks) {
|
|
1180
|
+
fs.rmSync(linkFilePath(teamRoot, link.linkId), { force: true });
|
|
1181
|
+
fs.rmSync(linkPromptPath(teamRoot, link.linkId), { force: true });
|
|
1182
|
+
}
|
|
1183
|
+
fs.rmSync(itemFilePath(teamRoot, id), { force: true });
|
|
1184
|
+
for (const entry of readAllEntries(teamRoot).values()) {
|
|
1185
|
+
if (entry.itemId === id) fs.rmSync(entryFilePath(teamRoot, entry.entryId), { force: true });
|
|
1186
|
+
}
|
|
1187
|
+
return { id, removedLinks: itemLinks.length };
|
|
1188
|
+
});
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
/**
|
|
1192
|
+
* One-time file migration from the shipped slug ids to the integer sequence.
|
|
1193
|
+
* The item files, links, queue entries and the monotonic sequence move as one
|
|
1194
|
+
* lock-held transaction; a mixed tree is left readable by mapping slugs after
|
|
1195
|
+
* the existing numeric ids.
|
|
1196
|
+
*/
|
|
1197
|
+
export function migrateTrackerIds(teamRoot) {
|
|
1198
|
+
return withTrackerLock(teamRoot, () => {
|
|
1199
|
+
const trackerRoot = trackerPaths(teamRoot).root;
|
|
1200
|
+
const legacyRoot = path.join(teamRoot, LEGACY_TRACKER_DIR);
|
|
1201
|
+
if (fs.existsSync(legacyRoot)) {
|
|
1202
|
+
for (const name of [ITEMS_DIR, QUEUE_DIR]) {
|
|
1203
|
+
const from = path.join(legacyRoot, name);
|
|
1204
|
+
const to = path.join(trackerRoot, name);
|
|
1205
|
+
if (!fs.existsSync(from)) continue;
|
|
1206
|
+
if (!fs.existsSync(to)) {
|
|
1207
|
+
fs.renameSync(from, to);
|
|
1208
|
+
continue;
|
|
1209
|
+
}
|
|
1210
|
+
// A tree already touched by an earlier sync may carry an empty target
|
|
1211
|
+
// directory: merge file by file instead of abandoning the legacy store.
|
|
1212
|
+
for (const entry of fs.readdirSync(from)) {
|
|
1213
|
+
const target = path.join(to, entry);
|
|
1214
|
+
if (!fs.existsSync(target)) fs.renameSync(path.join(from, entry), target);
|
|
1215
|
+
}
|
|
1216
|
+
try {
|
|
1217
|
+
fs.rmdirSync(from);
|
|
1218
|
+
} catch {
|
|
1219
|
+
/* a name collision keeps the source file for the operator */
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
try {
|
|
1223
|
+
fs.rmdirSync(legacyRoot);
|
|
1224
|
+
} catch {
|
|
1225
|
+
/* an unexpected extra file keeps the legacy directory in place */
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
const items = readAllItemsIncludingLegacy(teamRoot);
|
|
1229
|
+
const slugItems = [...items.values()].filter((item) => !Number.isInteger(item.id));
|
|
1230
|
+
if (slugItems.length === 0) {
|
|
1231
|
+
const max = listItemIds(teamRoot).reduce((value, id) => Math.max(value, id), 0);
|
|
1232
|
+
if (max > 0) {
|
|
1233
|
+
writeAtomic(sequenceFilePath(teamRoot), `${JSON.stringify({ schemaVersion: 1, nextId: max + 1 }, null, 2)}\n`);
|
|
1234
|
+
}
|
|
1235
|
+
fs.rmSync(idMigrationFilePath(teamRoot), { force: true });
|
|
1236
|
+
return { migrated: 0, mapping: {} };
|
|
1237
|
+
}
|
|
1238
|
+
const numericMax = [...items.values()]
|
|
1239
|
+
.filter((item) => Number.isInteger(item.id))
|
|
1240
|
+
.reduce((value, item) => Math.max(value, item.id), 0);
|
|
1241
|
+
// A crash midway through the rename must not shift the mapping on resume:
|
|
1242
|
+
// the manifest is written before the first file and removed only at the end.
|
|
1243
|
+
let resumed = {};
|
|
1244
|
+
try {
|
|
1245
|
+
const parsed = JSON.parse(fs.readFileSync(idMigrationFilePath(teamRoot), 'utf8'));
|
|
1246
|
+
if (isRecord(parsed?.mapping)) resumed = parsed.mapping;
|
|
1247
|
+
} catch {
|
|
1248
|
+
/* the first run has no manifest */
|
|
1249
|
+
}
|
|
1250
|
+
const reserved = Object.values(resumed).filter((value) => Number.isInteger(value) && value > 0);
|
|
1251
|
+
const ordered = [...slugItems].sort(
|
|
1252
|
+
(left, right) =>
|
|
1253
|
+
String(left.createdAt).localeCompare(String(right.createdAt)) ||
|
|
1254
|
+
String(left.id).localeCompare(String(right.id)),
|
|
1255
|
+
);
|
|
1256
|
+
const mapping = new Map();
|
|
1257
|
+
let next = Math.max(numericMax, ...reserved, 0) + 1;
|
|
1258
|
+
for (const item of ordered) {
|
|
1259
|
+
const id = Number.isInteger(resumed[item.id]) ? resumed[item.id] : next;
|
|
1260
|
+
mapping.set(item.id, id);
|
|
1261
|
+
if (id >= next) next = id + 1;
|
|
1262
|
+
}
|
|
1263
|
+
writeAtomic(
|
|
1264
|
+
idMigrationFilePath(teamRoot),
|
|
1265
|
+
`${JSON.stringify({ schemaVersion: 1, mapping: Object.fromEntries(mapping), nextId: next }, null, 2)}\n`,
|
|
1266
|
+
);
|
|
1267
|
+
const allLinks = readAllLinks(teamRoot);
|
|
1268
|
+
const oldLinkToNew = new Map();
|
|
1269
|
+
for (const item of ordered) {
|
|
1270
|
+
const newId = mapping.get(item.id);
|
|
1271
|
+
const nextItem = {
|
|
1272
|
+
...item,
|
|
1273
|
+
id: newId,
|
|
1274
|
+
dependsOn: (item.dependsOn ?? []).map((dep) => mapping.get(dep) ?? dep),
|
|
1275
|
+
supersededBy: item.supersededBy === null ? null : (mapping.get(item.supersededBy) ?? item.supersededBy),
|
|
1276
|
+
};
|
|
1277
|
+
validateItemSchema(nextItem);
|
|
1278
|
+
writeAtomic(itemFilePath(teamRoot, newId), `${JSON.stringify(nextItem, null, 2)}\n`);
|
|
1279
|
+
const legacyTaskSlug = String(item.id);
|
|
1280
|
+
if (fs.existsSync(path.join(teamRoot, 'tasks', legacyTaskSlug))) {
|
|
1281
|
+
const legacyLinkId = linkIdOf(newId, legacyTaskSlug);
|
|
1282
|
+
if (!readLinkFile(teamRoot, legacyLinkId)) {
|
|
1283
|
+
const now = nowIso();
|
|
1284
|
+
const legacyLink = {
|
|
1285
|
+
schemaVersion: LINK_SCHEMA_VERSION,
|
|
1286
|
+
linkId: legacyLinkId,
|
|
1287
|
+
itemId: newId,
|
|
1288
|
+
taskSlug: legacyTaskSlug,
|
|
1289
|
+
entryId: null,
|
|
1290
|
+
role: 'primary',
|
|
1291
|
+
decision: 'requested',
|
|
1292
|
+
promptPath: `${TRACKER_DIR}/${LINKS_DIR}/${legacyLinkId}.md`,
|
|
1293
|
+
language: null,
|
|
1294
|
+
revision: 1,
|
|
1295
|
+
createdAt: now,
|
|
1296
|
+
updatedAt: now,
|
|
1297
|
+
history: [{ at: now, type: 'adopted', actor: 'migration', detail: 'legacy tasks/<itemId>/ relation' }],
|
|
1298
|
+
};
|
|
1299
|
+
validateLinkSchema(legacyLink);
|
|
1300
|
+
writeLinkPrompt(teamRoot, legacyLinkId, item.description ?? item.title);
|
|
1301
|
+
writeLinkFile(teamRoot, legacyLink);
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
for (const link of allLinks.values()) {
|
|
1305
|
+
if (link.itemId !== item.id) continue;
|
|
1306
|
+
const nextLinkId = linkIdOf(newId, link.taskSlug);
|
|
1307
|
+
const oldPrompt = linkPromptPath(teamRoot, link.linkId);
|
|
1308
|
+
const nextLink = {
|
|
1309
|
+
...link,
|
|
1310
|
+
linkId: nextLinkId,
|
|
1311
|
+
itemId: newId,
|
|
1312
|
+
promptPath: `${TRACKER_DIR}/${LINKS_DIR}/${nextLinkId}.md`,
|
|
1313
|
+
};
|
|
1314
|
+
validateLinkSchema(nextLink);
|
|
1315
|
+
if (fs.existsSync(oldPrompt)) {
|
|
1316
|
+
fs.renameSync(oldPrompt, linkPromptPath(teamRoot, nextLinkId));
|
|
1317
|
+
}
|
|
1318
|
+
writeLinkFile(teamRoot, nextLink);
|
|
1319
|
+
fs.rmSync(linkFilePath(teamRoot, link.linkId), { force: true });
|
|
1320
|
+
oldLinkToNew.set(link.linkId, nextLinkId);
|
|
1321
|
+
}
|
|
1322
|
+
fs.rmSync(itemFilePath(teamRoot, item.id), { force: true });
|
|
1323
|
+
}
|
|
1324
|
+
for (const [entryId, entry] of readAllEntries(teamRoot)) {
|
|
1325
|
+
const mappedItem = mapping.get(entry.itemId);
|
|
1326
|
+
if (mappedItem === undefined) continue;
|
|
1327
|
+
const nextEntry = {
|
|
1328
|
+
...entry,
|
|
1329
|
+
itemId: mappedItem,
|
|
1330
|
+
taskSlug: entry.taskSlug ?? String(entry.itemId),
|
|
1331
|
+
linkId: entry.linkId === null || entry.linkId === undefined
|
|
1332
|
+
? null
|
|
1333
|
+
: (oldLinkToNew.get(entry.linkId) ?? entry.linkId),
|
|
1334
|
+
};
|
|
1335
|
+
validateEntrySchema(nextEntry);
|
|
1336
|
+
writeEntryFile(teamRoot, nextEntry);
|
|
1337
|
+
}
|
|
1338
|
+
writeAtomic(sequenceFilePath(teamRoot), `${JSON.stringify({ schemaVersion: 1, nextId: next }, null, 2)}\n`);
|
|
1339
|
+
fs.rmSync(idMigrationFilePath(teamRoot), { force: true });
|
|
1340
|
+
return { migrated: ordered.length, mapping: Object.fromEntries(mapping) };
|
|
1341
|
+
});
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
/**
|
|
1345
|
+
* Materialize the legacy 1:1 relation (`tasks/<itemId>/`) as an explicit link
|
|
1346
|
+
* for one item or for every item that has no links. Reads stay honest without
|
|
1347
|
+
* this command; it exists so an operator can adopt the old shape deliberately.
|
|
1348
|
+
*/
|
|
1349
|
+
export function adoptLegacyLinks(teamRoot, itemId = null, options = {}) {
|
|
1350
|
+
itemId = itemId === null ? null : parseItemId(itemId, 'itemId');
|
|
1351
|
+
return withTrackerLock(teamRoot, () => {
|
|
1352
|
+
const ids = itemId === null ? listItemIds(teamRoot) : [itemId];
|
|
1353
|
+
const adopted = [];
|
|
1354
|
+
for (const id of ids) {
|
|
1355
|
+
const item = readItemFile(teamRoot, id);
|
|
1356
|
+
if (!item) {
|
|
1357
|
+
if (itemId !== null) reject('E_TRACKER_UNKNOWN_DEP', `no tracker item "${id}"`);
|
|
1358
|
+
continue;
|
|
1359
|
+
}
|
|
1360
|
+
if (listLinksForItem(teamRoot, id).length > 0) continue;
|
|
1361
|
+
if (!fs.existsSync(path.join(teamRoot, 'tasks', String(id)))) continue;
|
|
1362
|
+
const linkId = linkIdOf(id, String(id));
|
|
1363
|
+
if (readLinkFile(teamRoot, linkId)) continue;
|
|
1364
|
+
const prompt = item.description ?? item.title;
|
|
1365
|
+
const now = nowIso();
|
|
1366
|
+
const link = {
|
|
1367
|
+
schemaVersion: LINK_SCHEMA_VERSION,
|
|
1368
|
+
linkId,
|
|
1369
|
+
itemId: id,
|
|
1370
|
+
taskSlug: String(id),
|
|
1371
|
+
entryId: null,
|
|
1372
|
+
role: 'primary',
|
|
1373
|
+
decision: 'requested',
|
|
1374
|
+
promptPath: `${TRACKER_DIR}/${LINKS_DIR}/${linkId}.md`,
|
|
1375
|
+
language: null,
|
|
1376
|
+
revision: 1,
|
|
1377
|
+
createdAt: now,
|
|
1378
|
+
updatedAt: now,
|
|
1379
|
+
history: [{ at: now, type: 'adopted', actor: options.actor ?? 'operator', detail: 'legacy tasks/<itemId>/ relation' }],
|
|
1380
|
+
};
|
|
1381
|
+
validateLinkSchema(link);
|
|
1382
|
+
validateLinkIdentity(link, linkId);
|
|
1383
|
+
writeLinkPrompt(teamRoot, linkId, prompt);
|
|
1384
|
+
writeLinkFile(teamRoot, link);
|
|
1385
|
+
adopted.push(linkId);
|
|
1386
|
+
}
|
|
1387
|
+
return { adopted };
|
|
1388
|
+
});
|
|
1389
|
+
}
|
|
1390
|
+
|
|
1391
|
+
/* ------------------------------ launch queue ------------------------------ */
|
|
1392
|
+
|
|
1393
|
+
const expireEntriesForItem = (teamRoot, itemId, detail, actor) => {
|
|
1394
|
+
const at = nowIso();
|
|
1395
|
+
for (const [entryId, entry] of readAllEntries(teamRoot)) {
|
|
1396
|
+
if (entry.itemId !== itemId) continue;
|
|
1397
|
+
if (entry.status === 'cancelled' || entry.status === 'expired') continue;
|
|
1398
|
+
const next = {
|
|
1399
|
+
...entry,
|
|
1400
|
+
status: 'expired',
|
|
1401
|
+
claimedAt: entry.status === 'claimed' ? entry.claimedAt : null,
|
|
1402
|
+
finishedAt: at,
|
|
1403
|
+
revision: entry.revision + 1,
|
|
1404
|
+
history: capHistory([...(entry.history ?? []), { at, type: 'expired', actor, detail }], MAX_ENTRY_HISTORY),
|
|
1405
|
+
};
|
|
1406
|
+
validateEntrySchema(next);
|
|
1407
|
+
writeEntryFile(teamRoot, next);
|
|
1408
|
+
}
|
|
1409
|
+
};
|
|
1410
|
+
|
|
1411
|
+
export function enqueueTrackerItem(teamRoot, payload, options = {}) {
|
|
1412
|
+
if (!isRecord(payload)) reject('E_SCHEMA', 'tracker enqueue payload must be an object');
|
|
1413
|
+
return withTrackerLock(teamRoot, () => {
|
|
1414
|
+
const itemId = parseItemId(payload.itemId, 'itemId');
|
|
1415
|
+
const item = readItemFile(teamRoot, itemId);
|
|
1416
|
+
if (!item) reject('E_TRACKER_UNKNOWN_DEP', `no tracker item "${itemId}"`);
|
|
1417
|
+
const taskSlug = payload.taskSlug ?? `tracker-${itemId}`;
|
|
1418
|
+
if (typeof taskSlug !== 'string' || !TASK_SLUG_RE.test(taskSlug) || taskSlug.length < 3 || taskSlug.length > MAX_TASK_SLUG_CHARS) {
|
|
1419
|
+
reject('E_SCHEMA', `taskSlug must match ${TASK_SLUG_RE.source} with 3-${MAX_TASK_SLUG_CHARS} characters`);
|
|
1420
|
+
}
|
|
1421
|
+
const linkId = payload.linkId ?? linkIdOf(itemId, taskSlug);
|
|
1422
|
+
if (typeof linkId !== 'string' || linkId.length > 160) {
|
|
1423
|
+
reject('E_SCHEMA', 'linkId must be <itemId>--<taskSlug>');
|
|
1424
|
+
}
|
|
1425
|
+
const link = readLinkFile(teamRoot, linkId);
|
|
1426
|
+
if (link !== null && (link.itemId !== itemId || link.taskSlug !== taskSlug)) {
|
|
1427
|
+
reject('E_SCHEMA', `link ${linkId} does not belong to ${itemId} / ${taskSlug}`);
|
|
1428
|
+
}
|
|
1429
|
+
if (link !== null && link.decision === 'unlinked') {
|
|
1430
|
+
reject('E_TRACKER_TRANSITION', `link ${linkId} is unlinked`);
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
// A backlog item is captured, not rejectable: starting work promotes it to
|
|
1434
|
+
// planned so the existing ready/drain rules apply without a second action.
|
|
1435
|
+
let currentItem = item;
|
|
1436
|
+
if (item.status === 'backlog') {
|
|
1437
|
+
const at = nowIso();
|
|
1438
|
+
currentItem = {
|
|
1439
|
+
...item,
|
|
1440
|
+
status: 'planned',
|
|
1441
|
+
revision: item.revision + 1,
|
|
1442
|
+
updatedAt: at,
|
|
1443
|
+
history: capHistory(
|
|
1444
|
+
[...(item.history ?? []), { at, type: 'status-changed', actor: options.actor ?? 'operator', detail: 'backlog -> planned (launch)' }],
|
|
1445
|
+
MAX_ITEM_HISTORY,
|
|
1446
|
+
),
|
|
1447
|
+
};
|
|
1448
|
+
validateItemSchema(currentItem);
|
|
1449
|
+
writeItemFile(teamRoot, currentItem);
|
|
1450
|
+
}
|
|
1451
|
+
const taskStates = readTaskStates(teamRoot);
|
|
1452
|
+
const entries = readAllEntries(teamRoot);
|
|
1453
|
+
const itemLinks = listLinksForItem(teamRoot, itemId).filter((candidate) => candidate.decision !== 'unlinked');
|
|
1454
|
+
const openEntry = [...entries.values()].find((entry) => {
|
|
1455
|
+
if (entry.itemId !== itemId) return false;
|
|
1456
|
+
if ((entry.taskSlug ?? `tracker-${entry.itemId}`) !== taskSlug) return false;
|
|
1457
|
+
return isNonTerminalEntryStatus(effectiveEntryStatus(entry, taskStates.get(entry.taskSlug ?? `tracker-${entry.itemId}`) ?? null));
|
|
1458
|
+
});
|
|
1459
|
+
const effective = effectiveItemStatus(currentItem, taskStates.get(taskSlug) ?? null, openEntry !== undefined, itemLinks, taskStates);
|
|
1460
|
+
if (['completed', 'cancelled', 'superseded'].includes(effective)) {
|
|
1461
|
+
reject('E_TRACKER_TRANSITION', `item ${itemId} is ${effective}; enqueue is refused`);
|
|
1462
|
+
}
|
|
1463
|
+
const actor = options.actor ?? 'operator';
|
|
1464
|
+
if (openEntry) {
|
|
1465
|
+
// R3-5: a duplicate enqueue appends the new reason to the history
|
|
1466
|
+
// instead of dropping it; enqueue stays idempotent per task link.
|
|
1467
|
+
const reason = typeof payload.reason === 'string' && payload.reason.length >= 1 ? payload.reason : openEntry.reason;
|
|
1468
|
+
const next = {
|
|
1469
|
+
...openEntry,
|
|
1470
|
+
revision: openEntry.revision + 1,
|
|
1471
|
+
history: capHistory(
|
|
1472
|
+
[...(openEntry.history ?? []), { at: nowIso(), type: 'enqueued', actor, detail: reason }],
|
|
1473
|
+
MAX_ENTRY_HISTORY,
|
|
1474
|
+
),
|
|
1475
|
+
};
|
|
1476
|
+
validateEntrySchema(next);
|
|
1477
|
+
writeEntryFile(teamRoot, next);
|
|
1478
|
+
return { entry: next, existing: true };
|
|
1479
|
+
}
|
|
1480
|
+
const now = nowIso();
|
|
1481
|
+
const entry = {
|
|
1482
|
+
schemaVersion: ENTRY_SCHEMA_VERSION,
|
|
1483
|
+
entryId: newEntryId(),
|
|
1484
|
+
itemId,
|
|
1485
|
+
taskSlug,
|
|
1486
|
+
linkId,
|
|
1487
|
+
status: 'queued',
|
|
1488
|
+
reason: payload.reason,
|
|
1489
|
+
requestedBy: payload.requestedBy,
|
|
1490
|
+
command: payload.command ?? null,
|
|
1491
|
+
revision: 1,
|
|
1492
|
+
requestedAt: now,
|
|
1493
|
+
claimedAt: null,
|
|
1494
|
+
finishedAt: null,
|
|
1495
|
+
history: [{ at: now, type: 'enqueued', actor, detail: null }],
|
|
1496
|
+
};
|
|
1497
|
+
validateEntrySchema(entry);
|
|
1498
|
+
writeEntryFile(teamRoot, entry);
|
|
1499
|
+
if (link !== null && link.entryId !== entry.entryId) {
|
|
1500
|
+
const linked = {
|
|
1501
|
+
...link,
|
|
1502
|
+
entryId: entry.entryId,
|
|
1503
|
+
revision: link.revision + 1,
|
|
1504
|
+
updatedAt: now,
|
|
1505
|
+
history: capHistory(
|
|
1506
|
+
[...(link.history ?? []), { at: now, type: 'linked', actor, detail: null }],
|
|
1507
|
+
MAX_LINK_HISTORY,
|
|
1508
|
+
),
|
|
1509
|
+
};
|
|
1510
|
+
validateLinkSchema(linked);
|
|
1511
|
+
writeLinkFile(teamRoot, linked);
|
|
1512
|
+
}
|
|
1513
|
+
return { entry, existing: false };
|
|
1514
|
+
});
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
export function cancelTrackerEntry(teamRoot, entryId, options = {}) {
|
|
1518
|
+
return withTrackerLock(teamRoot, () => {
|
|
1519
|
+
const entry = readEntryFile(teamRoot, entryId);
|
|
1520
|
+
if (!entry) reject('E_TRACKER_UNKNOWN_DEP', `no queue entry "${entryId}"`);
|
|
1521
|
+
const taskState = readTaskStates(teamRoot).get(entry.taskSlug ?? `tracker-${entry.itemId}`) ?? null;
|
|
1522
|
+
const effective = effectiveEntryStatus(entry, taskState);
|
|
1523
|
+
if (effective === 'active') {
|
|
1524
|
+
reject('E_TRACKER_TRANSITION', `entry ${entryId} is active; an active run belongs to the hook`);
|
|
1525
|
+
}
|
|
1526
|
+
if (['cancelled', 'expired', 'done'].includes(effective)) return { entry, unchanged: true };
|
|
1527
|
+
const at = nowIso();
|
|
1528
|
+
const next = {
|
|
1529
|
+
...entry,
|
|
1530
|
+
status: 'cancelled',
|
|
1531
|
+
claimedAt: entry.status === 'claimed' ? entry.claimedAt : null,
|
|
1532
|
+
finishedAt: at,
|
|
1533
|
+
revision: entry.revision + 1,
|
|
1534
|
+
history: capHistory(
|
|
1535
|
+
[...(entry.history ?? []), { at, type: 'cancelled', actor: options.actor ?? 'operator', detail: null }],
|
|
1536
|
+
MAX_ENTRY_HISTORY,
|
|
1537
|
+
),
|
|
1538
|
+
};
|
|
1539
|
+
validateEntrySchema(next);
|
|
1540
|
+
writeEntryFile(teamRoot, next);
|
|
1541
|
+
return { entry: next, unchanged: false };
|
|
1542
|
+
});
|
|
1543
|
+
}
|
|
1544
|
+
|
|
1545
|
+
/**
|
|
1546
|
+
* A claim older than the stale window with no task row is never treated as
|
|
1547
|
+
* evidence of a launch — the task row is the only such evidence (D-5). The
|
|
1548
|
+
* next drain or an explicit recover writes it back to `queued`.
|
|
1549
|
+
*/
|
|
1550
|
+
const releaseStaleClaims = (teamRoot, actor) => {
|
|
1551
|
+
let recovered = 0;
|
|
1552
|
+
const taskStates = readTaskStates(teamRoot);
|
|
1553
|
+
for (const [entryId, entry] of readAllEntries(teamRoot)) {
|
|
1554
|
+
if (entry.status !== 'claimed' || entry.claimedAt === null) continue;
|
|
1555
|
+
if (taskStates.has(entry.taskSlug ?? `tracker-${entry.itemId}`)) continue;
|
|
1556
|
+
if (Date.now() - Date.parse(entry.claimedAt) < CLAIM_STALE_MS) continue;
|
|
1557
|
+
const at = nowIso();
|
|
1558
|
+
const next = {
|
|
1559
|
+
...entry,
|
|
1560
|
+
status: 'queued',
|
|
1561
|
+
claimedAt: null,
|
|
1562
|
+
revision: entry.revision + 1,
|
|
1563
|
+
history: capHistory(
|
|
1564
|
+
[...(entry.history ?? []), { at, type: 'recovered', actor, detail: 'stale claim' }],
|
|
1565
|
+
MAX_ENTRY_HISTORY,
|
|
1566
|
+
),
|
|
1567
|
+
};
|
|
1568
|
+
validateEntrySchema(next);
|
|
1569
|
+
writeEntryFile(teamRoot, next);
|
|
1570
|
+
recovered += 1;
|
|
1571
|
+
}
|
|
1572
|
+
return recovered;
|
|
1573
|
+
};
|
|
1574
|
+
|
|
1575
|
+
export function recoverTrackerEntries(teamRoot, options = {}) {
|
|
1576
|
+
return withTrackerLock(teamRoot, () => ({ recovered: releaseStaleClaims(teamRoot, options.actor ?? 'operator') }));
|
|
1577
|
+
}
|
|
1578
|
+
|
|
1579
|
+
export function drainTracker(teamRoot, { claim = false, actor = 'operator' } = {}) {
|
|
1580
|
+
return withTrackerLock(teamRoot, () => {
|
|
1581
|
+
releaseStaleClaims(teamRoot, actor);
|
|
1582
|
+
const snapshot = {
|
|
1583
|
+
asOf: nowIso(),
|
|
1584
|
+
items: readAllItems(teamRoot),
|
|
1585
|
+
entries: readAllEntries(teamRoot),
|
|
1586
|
+
links: readAllLinks(teamRoot),
|
|
1587
|
+
taskStates: readTaskStates(teamRoot),
|
|
1588
|
+
};
|
|
1589
|
+
const ordering = deriveTrackerOrdering(snapshot);
|
|
1590
|
+
const config = readTrackerConfig(teamRoot);
|
|
1591
|
+
const activeCount = countActiveTasks(snapshot.taskStates);
|
|
1592
|
+
const claimedOrActiveCount = [...snapshot.entries.values()].filter((entry) =>
|
|
1593
|
+
['claimed', 'active'].includes(effectiveEntryStatus(entry, snapshot.taskStates.get(entry.taskSlug ?? `tracker-${entry.itemId}`) ?? null)),
|
|
1594
|
+
).length;
|
|
1595
|
+
const claimable = activeCount < config.maxActive && claimedOrActiveCount < config.maxActive;
|
|
1596
|
+
const base = {
|
|
1597
|
+
asOf: snapshot.asOf,
|
|
1598
|
+
ready: ordering.readyIds,
|
|
1599
|
+
drainOrder: ordering.drainOrderEntryIds,
|
|
1600
|
+
claimable,
|
|
1601
|
+
maxActive: config.maxActive,
|
|
1602
|
+
activeCount,
|
|
1603
|
+
};
|
|
1604
|
+
if (!claim) return base;
|
|
1605
|
+
if (!claimable) {
|
|
1606
|
+
const reason = activeCount >= config.maxActive ? 'capacity: active tasks' : 'capacity: claimed or active entries';
|
|
1607
|
+
return { ok: true, claim: null, reason, ...base };
|
|
1608
|
+
}
|
|
1609
|
+
const headEntryId = ordering.drainOrderEntryIds[0];
|
|
1610
|
+
if (!headEntryId) return { ok: true, claim: null, reason: 'empty drain order', ...base };
|
|
1611
|
+
const entry = snapshot.entries.get(headEntryId);
|
|
1612
|
+
const at = nowIso();
|
|
1613
|
+
const next = {
|
|
1614
|
+
...entry,
|
|
1615
|
+
status: 'claimed',
|
|
1616
|
+
claimedAt: at,
|
|
1617
|
+
revision: entry.revision + 1,
|
|
1618
|
+
history: capHistory([...(entry.history ?? []), { at, type: 'claimed', actor, detail: null }], MAX_ENTRY_HISTORY),
|
|
1619
|
+
};
|
|
1620
|
+
validateEntrySchema(next);
|
|
1621
|
+
writeEntryFile(teamRoot, next);
|
|
1622
|
+
return { ok: true, claim: { entryId: next.entryId, itemId: next.itemId, taskSlug: next.taskSlug ?? `tracker-${next.itemId}`, linkId: next.linkId ?? null, slug: next.taskSlug ?? `tracker-${next.itemId}` }, reason: null, ...base };
|
|
1623
|
+
});
|
|
1624
|
+
}
|
|
1625
|
+
|
|
1626
|
+
export function pruneTrackerEntries(teamRoot, { olderThanDays = DEFAULT_PRUNE_DAYS } = {}) {
|
|
1627
|
+
return withTrackerLock(teamRoot, () => {
|
|
1628
|
+
const cutoff = Date.now() - olderThanDays * 24 * 60 * 60 * 1000;
|
|
1629
|
+
let pruned = 0;
|
|
1630
|
+
for (const [entryId, entry] of readAllEntries(teamRoot)) {
|
|
1631
|
+
if (entry.status !== 'cancelled' && entry.status !== 'expired') continue;
|
|
1632
|
+
if (!entry.finishedAt || Date.parse(entry.finishedAt) >= cutoff) continue;
|
|
1633
|
+
fs.rmSync(entryFilePath(teamRoot, entryId), { force: true });
|
|
1634
|
+
pruned += 1;
|
|
1635
|
+
}
|
|
1636
|
+
return { pruned };
|
|
1637
|
+
});
|
|
1638
|
+
}
|
|
1639
|
+
|
|
1640
|
+
/* --------------------------------- import --------------------------------- */
|
|
1641
|
+
|
|
1642
|
+
const normalizeImportItem = (raw) => ({
|
|
1643
|
+
schemaVersion: ITEM_SCHEMA_VERSION,
|
|
1644
|
+
id: raw.id,
|
|
1645
|
+
revision: raw.revision ?? 1,
|
|
1646
|
+
title: typeof raw.title === 'string' ? raw.title.trim() : raw.title,
|
|
1647
|
+
status: raw.status ?? 'planned',
|
|
1648
|
+
priority: raw.priority ?? 5,
|
|
1649
|
+
sourceTask: raw.sourceTask ?? null,
|
|
1650
|
+
sourceRefs: raw.sourceRefs ?? [],
|
|
1651
|
+
createdAt: raw.createdAt,
|
|
1652
|
+
updatedAt: raw.updatedAt,
|
|
1653
|
+
completedAt: raw.completedAt ?? null,
|
|
1654
|
+
cancelledAt: raw.cancelledAt ?? null,
|
|
1655
|
+
cancelReason: raw.cancelReason ?? null,
|
|
1656
|
+
supersededBy: raw.supersededBy ?? null,
|
|
1657
|
+
type: raw.type ?? 'feature',
|
|
1658
|
+
description: raw.description ?? null,
|
|
1659
|
+
labels: raw.labels ?? [],
|
|
1660
|
+
dependsOn: raw.dependsOn ?? [],
|
|
1661
|
+
history: Array.isArray(raw.history) ? raw.history : [],
|
|
1662
|
+
});
|
|
1663
|
+
|
|
1664
|
+
/**
|
|
1665
|
+
* The envelope-driven fields — the content whose equality makes a re-import
|
|
1666
|
+
* idle. `revision` and `history` are store-owned bookkeeping, never part of
|
|
1667
|
+
* the comparison (D-8: content-hash equality, the projector's idiom).
|
|
1668
|
+
*/
|
|
1669
|
+
const envelopeFields = (item) => {
|
|
1670
|
+
const { revision, history, ...fields } = item;
|
|
1671
|
+
void revision;
|
|
1672
|
+
void history;
|
|
1673
|
+
return fields;
|
|
1674
|
+
};
|
|
1675
|
+
|
|
1676
|
+
/**
|
|
1677
|
+
* D-8: a versioned envelope `{schemaVersion, source: {task, generatedAt},
|
|
1678
|
+
* items[]}`, validated as one transaction — nothing is written unless every
|
|
1679
|
+
* item passes — upserted by id, `--dry-run` writes nothing, and an idle
|
|
1680
|
+
* re-import (content-hash equality) writes nothing.
|
|
1681
|
+
*/
|
|
1682
|
+
export function importTrackerItems(teamRoot, envelope, options = {}) {
|
|
1683
|
+
if (!isRecord(envelope)) reject('E_SCHEMA', 'import envelope must be an object');
|
|
1684
|
+
if (envelope.schemaVersion !== ITEM_SCHEMA_VERSION) {
|
|
1685
|
+
reject('E_SCHEMA', `import envelope schemaVersion must be ${ITEM_SCHEMA_VERSION}`);
|
|
1686
|
+
}
|
|
1687
|
+
const source = envelope.source;
|
|
1688
|
+
if (!isRecord(source) || typeof source.task !== 'string' || source.task.length < 1) {
|
|
1689
|
+
reject('E_SCHEMA', 'import envelope source.task is required');
|
|
1690
|
+
}
|
|
1691
|
+
if (!isIsoZ(source.generatedAt)) {
|
|
1692
|
+
reject('E_SCHEMA', 'import envelope source.generatedAt must be an RFC 3339 timestamp ending in Z');
|
|
1693
|
+
}
|
|
1694
|
+
if (!Array.isArray(envelope.items)) reject('E_SCHEMA', 'import envelope items must be an array');
|
|
1695
|
+
const dryRun = Boolean(options.dryRun);
|
|
1696
|
+
return withTrackerLock(teamRoot, () => {
|
|
1697
|
+
const existing = readAllItems(teamRoot);
|
|
1698
|
+
const byId = new Map(existing);
|
|
1699
|
+
const plan = [];
|
|
1700
|
+
// Validate the whole envelope before the first write: one transaction.
|
|
1701
|
+
for (const [index, raw] of envelope.items.entries()) {
|
|
1702
|
+
if (!isRecord(raw)) reject('E_SCHEMA', `import items[${index}] must be an object`);
|
|
1703
|
+
const item = normalizeImportItem(raw);
|
|
1704
|
+
if (item.id === undefined || item.id === null) {
|
|
1705
|
+
reject('E_SCHEMA', `import items[${index}]: id is required`);
|
|
1706
|
+
}
|
|
1707
|
+
if (plan.some((entry) => entry.item.id === item.id)) {
|
|
1708
|
+
reject('E_TRACKER_DUPLICATE_ID', `import envelope: items[${index}] duplicates id "${item.id}"`);
|
|
1709
|
+
}
|
|
1710
|
+
validateItemSchema(item);
|
|
1711
|
+
const previous = byId.get(item.id) ?? null;
|
|
1712
|
+
if (!previous) {
|
|
1713
|
+
// D-2 collision guard applies to new ids, exactly as on `add`.
|
|
1714
|
+
if (fs.existsSync(path.join(teamRoot, 'tasks', String(item.id)))) {
|
|
1715
|
+
reject('E_ID_COLLISION', `id "${item.id}" already names a tasks/${item.id}/ directory`);
|
|
1716
|
+
}
|
|
1717
|
+
} else {
|
|
1718
|
+
validateTransition(previous, item);
|
|
1719
|
+
}
|
|
1720
|
+
validateItemGraph(item, byId);
|
|
1721
|
+
const at = nowIso();
|
|
1722
|
+
const unchanged =
|
|
1723
|
+
previous !== null && canonicalJson(envelopeFields(item)) === canonicalJson(envelopeFields(previous));
|
|
1724
|
+
let target = null;
|
|
1725
|
+
if (unchanged) {
|
|
1726
|
+
target = previous;
|
|
1727
|
+
} else if (previous === null) {
|
|
1728
|
+
target = {
|
|
1729
|
+
...item,
|
|
1730
|
+
revision: 1,
|
|
1731
|
+
history: capHistory([...(item.history ?? []), { at, type: 'created', actor: source.task, detail: null }], MAX_ITEM_HISTORY),
|
|
1732
|
+
};
|
|
1733
|
+
} else {
|
|
1734
|
+
target = {
|
|
1735
|
+
...item,
|
|
1736
|
+
revision: previous.revision + 1,
|
|
1737
|
+
history: capHistory(
|
|
1738
|
+
[...(previous.history ?? []), { at, type: 'imported', actor: source.task, detail: null }],
|
|
1739
|
+
MAX_ITEM_HISTORY,
|
|
1740
|
+
),
|
|
1741
|
+
};
|
|
1742
|
+
}
|
|
1743
|
+
plan.push({ item: target, previous, unchanged });
|
|
1744
|
+
byId.set(item.id, { ...byId.get(item.id), ...target });
|
|
1745
|
+
}
|
|
1746
|
+
const result = { inserted: 0, updated: 0, unchanged: 0, dryRun };
|
|
1747
|
+
for (const step of plan) {
|
|
1748
|
+
if (step.unchanged) {
|
|
1749
|
+
result.unchanged += 1;
|
|
1750
|
+
continue;
|
|
1751
|
+
}
|
|
1752
|
+
if (step.previous === null) result.inserted += 1;
|
|
1753
|
+
else result.updated += 1;
|
|
1754
|
+
if (!dryRun) writeItemFile(teamRoot, step.item);
|
|
1755
|
+
}
|
|
1756
|
+
if (!dryRun) {
|
|
1757
|
+
const maxImported = plan.reduce((max, step) => Math.max(max, step.item.id), 0);
|
|
1758
|
+
let reserved = 0;
|
|
1759
|
+
try {
|
|
1760
|
+
const parsed = JSON.parse(fs.readFileSync(sequenceFilePath(teamRoot), 'utf8'));
|
|
1761
|
+
if (Number.isInteger(parsed?.nextId) && parsed.nextId > 0) reserved = parsed.nextId;
|
|
1762
|
+
} catch {
|
|
1763
|
+
/* the first import creates the sequence */
|
|
1764
|
+
}
|
|
1765
|
+
const nextId = Math.max(maxImported + 1, reserved, 1);
|
|
1766
|
+
writeAtomic(sequenceFilePath(teamRoot), `${JSON.stringify({ schemaVersion: 1, nextId }, null, 2)}\\n`);
|
|
1767
|
+
}
|
|
1768
|
+
return result;
|
|
1769
|
+
});
|
|
1770
|
+
}
|
|
1771
|
+
|
|
1772
|
+
/* ------------------------ whole-tree validation --------------------------- */
|
|
1773
|
+
|
|
1774
|
+
export function validateTrackerTree(teamRoot) {
|
|
1775
|
+
return withTrackerLock(teamRoot, () => {
|
|
1776
|
+
const errors = [];
|
|
1777
|
+
const items = readAllItems(teamRoot);
|
|
1778
|
+
readTrackerConfig(teamRoot);
|
|
1779
|
+
for (const stem of listAllItemStems(teamRoot)) {
|
|
1780
|
+
if (!ITEM_ID_RE.test(stem)) {
|
|
1781
|
+
errors.push({
|
|
1782
|
+
path: `tracker/items/${stem}.json`,
|
|
1783
|
+
code: 'E_SCHEMA',
|
|
1784
|
+
message: 'item file name must be a positive integer id; run `tracker migrate-ids` for a legacy store',
|
|
1785
|
+
});
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
for (const id of listItemIds(teamRoot)) {
|
|
1789
|
+
const record = items.get(id);
|
|
1790
|
+
const collect = (code, message) => errors.push({ path: `tracker/items/${id}.json`, code, message });
|
|
1791
|
+
if (!record) {
|
|
1792
|
+
collect('E_SCHEMA', 'item file is not readable');
|
|
1793
|
+
continue;
|
|
1794
|
+
}
|
|
1795
|
+
try {
|
|
1796
|
+
validateItemSchema(record);
|
|
1797
|
+
} catch (error) {
|
|
1798
|
+
collect(error instanceof TeamDbError ? error.code : 'E_SCHEMA', error.message);
|
|
1799
|
+
continue;
|
|
1800
|
+
}
|
|
1801
|
+
try {
|
|
1802
|
+
validateItemIdentity(record, id);
|
|
1803
|
+
} catch (error) {
|
|
1804
|
+
collect(error instanceof TeamDbError ? error.code : 'E_SCHEMA', error.message);
|
|
1805
|
+
continue;
|
|
1806
|
+
}
|
|
1807
|
+
try {
|
|
1808
|
+
validateItemGraph(record, items);
|
|
1809
|
+
} catch (error) {
|
|
1810
|
+
collect(error instanceof TeamDbError ? error.code : 'E_SCHEMA', error.message);
|
|
1811
|
+
continue;
|
|
1812
|
+
}
|
|
1813
|
+
try {
|
|
1814
|
+
validateTransition(null, record);
|
|
1815
|
+
} catch (error) {
|
|
1816
|
+
collect(error instanceof TeamDbError ? error.code : 'E_SCHEMA', error.message);
|
|
1817
|
+
}
|
|
1818
|
+
}
|
|
1819
|
+
for (const entryId of listEntryIds(teamRoot)) {
|
|
1820
|
+
try {
|
|
1821
|
+
validateEntrySchema(readEntryFile(teamRoot, entryId));
|
|
1822
|
+
} catch (error) {
|
|
1823
|
+
errors.push({
|
|
1824
|
+
path: `tracker/queue/${entryId}.json`,
|
|
1825
|
+
code: error instanceof TeamDbError ? error.code : 'E_SCHEMA',
|
|
1826
|
+
message: error.message,
|
|
1827
|
+
});
|
|
1828
|
+
}
|
|
1829
|
+
}
|
|
1830
|
+
return { ok: errors.length === 0, items: items.size, errors };
|
|
1831
|
+
});
|
|
1832
|
+
}
|
|
1833
|
+
|
|
1834
|
+
/* --------------------------- projection seam ------------------------------ */
|
|
1835
|
+
|
|
1836
|
+
/* ------------------------------ CLI surface ------------------------------- */
|
|
1837
|
+
|
|
1838
|
+
export const TRACKER_SUBCOMMANDS = new Set([
|
|
1839
|
+
'add',
|
|
1840
|
+
'set',
|
|
1841
|
+
'show',
|
|
1842
|
+
'list',
|
|
1843
|
+
'ready',
|
|
1844
|
+
'validate',
|
|
1845
|
+
'import',
|
|
1846
|
+
'enqueue',
|
|
1847
|
+
'cancel',
|
|
1848
|
+
'drain',
|
|
1849
|
+
'recover',
|
|
1850
|
+
'prune',
|
|
1851
|
+
'link',
|
|
1852
|
+
'delete',
|
|
1853
|
+
'adopt',
|
|
1854
|
+
'migrate-ids',
|
|
1855
|
+
]);
|
|
1856
|
+
|
|
1857
|
+
const SUBCOMMAND_FLAGS = {
|
|
1858
|
+
add: new Set(['file']),
|
|
1859
|
+
set: new Set(['file']),
|
|
1860
|
+
show: new Set(),
|
|
1861
|
+
list: new Set(['status', 'ready']),
|
|
1862
|
+
ready: new Set(),
|
|
1863
|
+
validate: new Set(),
|
|
1864
|
+
import: new Set(['file', 'dry-run']),
|
|
1865
|
+
enqueue: new Set(['file']),
|
|
1866
|
+
cancel: new Set(),
|
|
1867
|
+
drain: new Set(['claim']),
|
|
1868
|
+
recover: new Set(),
|
|
1869
|
+
prune: new Set(['older-than']),
|
|
1870
|
+
link: new Set(['file']),
|
|
1871
|
+
delete: new Set(),
|
|
1872
|
+
adopt: new Set(['file']),
|
|
1873
|
+
'migrate-ids': new Set(),
|
|
1874
|
+
};
|
|
1875
|
+
|
|
1876
|
+
const WITH_ID = new Set(['set', 'show', 'cancel', 'delete']);
|
|
1877
|
+
const WITH_FILE = new Set(['add', 'set', 'import', 'enqueue', 'link', 'adopt']);
|
|
1878
|
+
|
|
1879
|
+
export function runTrackerCommand(subcommand, positionalId, options = {}) {
|
|
1880
|
+
const teamRoot = path.resolve(options.root || DEFAULT_TEAM_ROOT);
|
|
1881
|
+
const json = Boolean(options.json);
|
|
1882
|
+
const quiet = Boolean(options.quiet);
|
|
1883
|
+
if (!TRACKER_SUBCOMMANDS.has(subcommand)) teamDbFail('E_USAGE', `unknown tracker subcommand "${subcommand}"`, 3);
|
|
1884
|
+
const allowed = SUBCOMMAND_FLAGS[subcommand];
|
|
1885
|
+
const present = [];
|
|
1886
|
+
if (options.file !== undefined) present.push('file');
|
|
1887
|
+
if (options.dryRun) present.push('dry-run');
|
|
1888
|
+
if (options.olderThanDays !== undefined) present.push('older-than');
|
|
1889
|
+
if (options.claim) present.push('claim');
|
|
1890
|
+
if (options.status !== undefined) present.push('status');
|
|
1891
|
+
if (options.ready) present.push('ready');
|
|
1892
|
+
for (const flag of present) {
|
|
1893
|
+
if (!allowed.has(flag)) teamDbFail('E_USAGE', `flag --${flag} does not apply to tracker ${subcommand}`, 3);
|
|
1894
|
+
}
|
|
1895
|
+
if (WITH_ID.has(subcommand) && (typeof positionalId !== 'string' || positionalId === '')) {
|
|
1896
|
+
teamDbFail('E_USAGE', `tracker ${subcommand} needs an id`, 3);
|
|
1897
|
+
}
|
|
1898
|
+
if (!WITH_ID.has(subcommand) && positionalId !== null && positionalId !== undefined) {
|
|
1899
|
+
teamDbFail('E_USAGE', `tracker ${subcommand} takes no id argument`, 3);
|
|
1900
|
+
}
|
|
1901
|
+
const readPayload = () => {
|
|
1902
|
+
if (options.file === undefined) teamDbFail('E_USAGE', `tracker ${subcommand} needs --file <path|->`, 3);
|
|
1903
|
+
const text = options.file === '-' ? fs.readFileSync(0, 'utf8') : fs.readFileSync(path.resolve(options.file), 'utf8');
|
|
1904
|
+
try {
|
|
1905
|
+
return JSON.parse(text);
|
|
1906
|
+
} catch (error) {
|
|
1907
|
+
teamDbFail('E_SCHEMA', `--file payload is not valid JSON: ${error.message}`, 1);
|
|
1908
|
+
}
|
|
1909
|
+
return null;
|
|
1910
|
+
};
|
|
1911
|
+
const out = (text) => {
|
|
1912
|
+
if (json) return `${text}\n`;
|
|
1913
|
+
if (!quiet) return `${text}\n`;
|
|
1914
|
+
return '';
|
|
1915
|
+
};
|
|
1916
|
+
const itemLine = (item) => `tracker: id=${item.id} status=${item.status} revision=${item.revision}`;
|
|
1917
|
+
const entryLine = (entry) => `tracker: entry=${entry.entryId} item=${entry.itemId} status=${entry.status}`;
|
|
1918
|
+
const rankedItems = (ordering) =>
|
|
1919
|
+
[...ordering.byId.values()].sort((a, b) => rankCompare(a.item, b.item));
|
|
1920
|
+
|
|
1921
|
+
let output = '';
|
|
1922
|
+
let wrote = false;
|
|
1923
|
+
|
|
1924
|
+
if (subcommand === 'add') {
|
|
1925
|
+
const item = addTrackerItem(teamRoot, readPayload());
|
|
1926
|
+
wrote = true;
|
|
1927
|
+
output += out(json ? JSON.stringify({ ok: true, item }) : itemLine(item));
|
|
1928
|
+
} else if (subcommand === 'set') {
|
|
1929
|
+
const item = setTrackerItem(teamRoot, positionalId, readPayload());
|
|
1930
|
+
wrote = true;
|
|
1931
|
+
output += out(json ? JSON.stringify({ ok: true, item }) : itemLine(item));
|
|
1932
|
+
} else if (subcommand === 'show') {
|
|
1933
|
+
const snapshot = readTrackerSnapshot(teamRoot);
|
|
1934
|
+
const annotated = deriveTrackerOrdering(snapshot).byId.get(parseItemId(positionalId, 'item id'));
|
|
1935
|
+
if (!annotated) reject('E_TRACKER_UNKNOWN_DEP', `no tracker item "${positionalId}"`);
|
|
1936
|
+
if (json) annotated.links = listLinksForItem(teamRoot, positionalId);
|
|
1937
|
+
output += out(JSON.stringify(annotated, null, json ? 0 : 2));
|
|
1938
|
+
} else if (subcommand === 'list') {
|
|
1939
|
+
const snapshot = readTrackerSnapshot(teamRoot);
|
|
1940
|
+
const ordering = deriveTrackerOrdering(snapshot);
|
|
1941
|
+
const statuses = options.status !== undefined ? options.status.split(',').map((value) => value.trim()) : null;
|
|
1942
|
+
if (statuses) {
|
|
1943
|
+
for (const status of statuses) {
|
|
1944
|
+
if (!EFFECTIVE_ITEM_STATUSES.includes(status)) teamDbFail('E_USAGE', `--status "${status}" is not one of ${EFFECTIVE_ITEM_STATUSES.join(',')}`, 3);
|
|
1945
|
+
}
|
|
1946
|
+
}
|
|
1947
|
+
const items = rankedItems(ordering)
|
|
1948
|
+
.filter((annotated) => (statuses ? statuses.includes(annotated.effectiveStatus) : true))
|
|
1949
|
+
.filter((annotated) => (options.ready ? annotated.ready : true))
|
|
1950
|
+
.map((annotated) => ({
|
|
1951
|
+
id: annotated.item.id,
|
|
1952
|
+
title: annotated.item.title,
|
|
1953
|
+
status: annotated.item.status,
|
|
1954
|
+
effectiveStatus: annotated.effectiveStatus,
|
|
1955
|
+
priority: annotated.item.priority,
|
|
1956
|
+
ready: annotated.ready,
|
|
1957
|
+
waitingOn: annotated.waitingOn,
|
|
1958
|
+
createdAt: annotated.item.createdAt,
|
|
1959
|
+
updatedAt: annotated.item.updatedAt,
|
|
1960
|
+
queueEntryId: annotated.queueEntryId,
|
|
1961
|
+
}));
|
|
1962
|
+
if (json) {
|
|
1963
|
+
output += out(JSON.stringify({ asOf: snapshot.asOf, items, total: items.length, readyCount: ordering.readyIds.length }));
|
|
1964
|
+
} else {
|
|
1965
|
+
for (const item of items) {
|
|
1966
|
+
output += `${item.id} ${item.effectiveStatus} p${item.priority}${item.ready ? ' ready' : item.waitingOn.length > 0 ? ` waiting_on ${item.waitingOn.join(',')}` : ''} ${item.title}\n`;
|
|
1967
|
+
}
|
|
1968
|
+
if (quiet) output = '';
|
|
1969
|
+
}
|
|
1970
|
+
} else if (subcommand === 'ready') {
|
|
1971
|
+
const snapshot = readTrackerSnapshot(teamRoot);
|
|
1972
|
+
const ordering = deriveTrackerOrdering(snapshot);
|
|
1973
|
+
output += json
|
|
1974
|
+
? out(JSON.stringify({ asOf: snapshot.asOf, ready: ordering.readyIds }))
|
|
1975
|
+
: out(ordering.readyIds.join('\n') || '(no ready items)');
|
|
1976
|
+
} else if (subcommand === 'validate') {
|
|
1977
|
+
const report = validateTrackerTree(teamRoot);
|
|
1978
|
+
if (!report.ok) {
|
|
1979
|
+
for (const error of report.errors) process.stderr.write(`${error.path}: ${error.code}: ${error.message}\n`);
|
|
1980
|
+
if (json) output += `${JSON.stringify({ ok: false, items: report.items, errors: report.errors })}\n`;
|
|
1981
|
+
return { output, exitCode: 1 };
|
|
1982
|
+
}
|
|
1983
|
+
output += out(json ? JSON.stringify({ ok: true, items: report.items, errors: [] }) : `tracker validate: ${report.items} items, all valid`);
|
|
1984
|
+
} else if (subcommand === 'import') {
|
|
1985
|
+
const result = importTrackerItems(teamRoot, readPayload(), { dryRun: options.dryRun });
|
|
1986
|
+
if (!options.dryRun) wrote = true;
|
|
1987
|
+
output += json
|
|
1988
|
+
? out(JSON.stringify({ ok: true, ...result }))
|
|
1989
|
+
: out(`tracker import: inserted=${result.inserted} updated=${result.updated} unchanged=${result.unchanged}${result.dryRun ? ' (dry run)' : ''}`);
|
|
1990
|
+
} else if (subcommand === 'enqueue') {
|
|
1991
|
+
const { entry, existing } = enqueueTrackerItem(teamRoot, readPayload());
|
|
1992
|
+
wrote = true;
|
|
1993
|
+
output += out(json ? JSON.stringify({ ok: true, entry, existing }) : `${entryLine(entry)}${existing ? ' (existing)' : ''}`);
|
|
1994
|
+
} else if (subcommand === 'cancel') {
|
|
1995
|
+
const { entry, unchanged } = cancelTrackerEntry(teamRoot, positionalId);
|
|
1996
|
+
wrote = true;
|
|
1997
|
+
output += out(json ? JSON.stringify({ ok: true, entry, unchanged }) : `${entryLine(entry)}${unchanged ? ' (unchanged)' : ''}`);
|
|
1998
|
+
} else if (subcommand === 'drain') {
|
|
1999
|
+
const result = drainTracker(teamRoot, { claim: options.claim });
|
|
2000
|
+
if (json) {
|
|
2001
|
+
output += out(JSON.stringify(result));
|
|
2002
|
+
} else if (result.claim !== undefined) {
|
|
2003
|
+
output += out(
|
|
2004
|
+
result.claim
|
|
2005
|
+
? `tracker drain: claimed ${result.claim.entryId} for ${result.claim.slug}`
|
|
2006
|
+
: `tracker drain: no claim (${result.reason ?? 'nothing ready'})`,
|
|
2007
|
+
);
|
|
2008
|
+
} else {
|
|
2009
|
+
output += out(`tracker drain: ready=${result.ready.length} drainOrder=${result.drainOrder.length} claimable=${result.claimable}`);
|
|
2010
|
+
}
|
|
2011
|
+
} else if (subcommand === 'recover') {
|
|
2012
|
+
const { recovered } = recoverTrackerEntries(teamRoot);
|
|
2013
|
+
if (recovered > 0) wrote = true;
|
|
2014
|
+
output += out(json ? JSON.stringify({ ok: true, recovered }) : `tracker recover: ${recovered} stale claim(s) released`);
|
|
2015
|
+
} else if (subcommand === 'prune') {
|
|
2016
|
+
const days = options.olderThanDays === undefined ? DEFAULT_PRUNE_DAYS : Number(options.olderThanDays);
|
|
2017
|
+
if (!Number.isInteger(days) || days < 1) teamDbFail('E_USAGE', '--older-than must be a positive integer number of days', 3);
|
|
2018
|
+
const { pruned } = pruneTrackerEntries(teamRoot, { olderThanDays: days });
|
|
2019
|
+
if (pruned > 0) wrote = true;
|
|
2020
|
+
output += out(json ? JSON.stringify({ ok: true, pruned }) : `tracker prune: ${pruned} terminal entr${pruned === 1 ? 'y' : 'ies'} deleted`);
|
|
2021
|
+
} else if (subcommand === 'link') {
|
|
2022
|
+
const payload = readPayload();
|
|
2023
|
+
const action = payload.action ?? 'list';
|
|
2024
|
+
if (action === 'add') {
|
|
2025
|
+
const link = addTrackerLink(teamRoot, payload);
|
|
2026
|
+
wrote = true;
|
|
2027
|
+
output += out(json ? JSON.stringify({ ok: true, link }) : `tracker link: ${link.linkId} -> ${link.taskSlug}`);
|
|
2028
|
+
} else if (action === 'set') {
|
|
2029
|
+
const link = setTrackerLink(teamRoot, payload.linkId, payload);
|
|
2030
|
+
wrote = true;
|
|
2031
|
+
output += out(json ? JSON.stringify({ ok: true, link }) : `tracker link: ${link.linkId} ${link.decision} r${link.revision}`);
|
|
2032
|
+
} else if (action === 'remove') {
|
|
2033
|
+
const removed = removeTrackerLink(teamRoot, payload.linkId);
|
|
2034
|
+
wrote = true;
|
|
2035
|
+
output += out(json ? JSON.stringify({ ok: true, ...removed }) : `tracker link: removed ${removed.linkId}`);
|
|
2036
|
+
} else if (action === 'adopt') {
|
|
2037
|
+
const result = adoptLegacyLinks(teamRoot, payload.itemId ?? null);
|
|
2038
|
+
if (result.adopted.length > 0) wrote = true;
|
|
2039
|
+
output += out(json ? JSON.stringify({ ok: true, ...result }) : `tracker link: adopted ${result.adopted.length} legacy relation(s)`);
|
|
2040
|
+
} else if (action === 'list') {
|
|
2041
|
+
const links = payload.itemId ? listLinksForItem(teamRoot, payload.itemId) : [...readAllLinks(teamRoot).values()];
|
|
2042
|
+
output += out(json ? JSON.stringify({ ok: true, links }) : links.map((link) => `${link.linkId} ${link.decision}`).join('\n'));
|
|
2043
|
+
} else {
|
|
2044
|
+
teamDbFail('E_USAGE', `unknown tracker link action "${action}"`, 3);
|
|
2045
|
+
}
|
|
2046
|
+
} else if (subcommand === 'delete') {
|
|
2047
|
+
const result = deleteTrackerItem(teamRoot, parseItemId(positionalId, 'item id'));
|
|
2048
|
+
wrote = true;
|
|
2049
|
+
output += out(json ? JSON.stringify({ ok: true, ...result }) : `tracker delete: ${result.id} (${result.removedLinks} link(s))`);
|
|
2050
|
+
} else if (subcommand === 'adopt') {
|
|
2051
|
+
const result = adoptLegacyLinks(teamRoot, null);
|
|
2052
|
+
if (result.adopted.length > 0) wrote = true;
|
|
2053
|
+
output += out(json ? JSON.stringify({ ok: true, ...result }) : `tracker adopt: ${result.adopted.length} legacy relation(s)`);
|
|
2054
|
+
} else if (subcommand === 'migrate-ids') {
|
|
2055
|
+
const result = migrateTrackerIds(teamRoot);
|
|
2056
|
+
if (result.migrated > 0) wrote = true;
|
|
2057
|
+
output += out(
|
|
2058
|
+
json
|
|
2059
|
+
? JSON.stringify({ ok: true, ...result })
|
|
2060
|
+
: result.migrated === 0
|
|
2061
|
+
? 'tracker migrate-ids: already numeric'
|
|
2062
|
+
: `tracker migrate-ids: migrated ${result.migrated} item(s)`,
|
|
2063
|
+
);
|
|
2064
|
+
}
|
|
2065
|
+
|
|
2066
|
+
// The API's bounded child writes the file, then projects; `runTracker` in
|
|
2067
|
+
// `team-db.mjs` owns the scoped projection so this module stays file-only.
|
|
2068
|
+
return { output, exitCode: 0, wrote };
|
|
2069
|
+
}
|