@bonesofspring/ai-rules 0.2.61 → 0.2.64
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 +85 -0
- package/README.md +13 -6
- package/bin/cli.js +7 -5
- package/bin/lib/ai-local-drift.js +7 -6
- package/bin/lib/engine-scripts.js +4 -0
- package/bin/lib/engine-upgrade.js +10 -2
- package/bin/lib/manifest-schema.js +12 -0
- package/bin/lib/seed-ai-local-team.js +16 -0
- package/bin/mavis-install.js +4 -1
- package/bin/opencode-install.js +22 -4
- package/bin/zcode-install.js +4 -1
- package/docs/MAVIS.md +5 -2
- package/docs/MCP-CATALOG.md +1 -1
- package/docs/OPENCODE-COMPATIBILITY.md +3 -2
- package/docs/OPENCODE.md +27 -4
- package/docs/PLATFORMS.md +1 -1
- package/docs/PRESET-CONTRIBUTION.md +20 -17
- package/docs/TEAM-DB.md +78 -5
- package/docs/openapi/team-db.v1.json +4817 -2795
- package/mcp/defectdojo-mcp.mjs +41 -11
- package/mcp/lib/defectdojo.mjs +45 -2
- package/package.json +10 -4
- package/presets/_shared/ai-local/scripts/aggregate-agent-task-metrics.mjs +279 -0
- package/presets/_shared/ai-local/scripts/check-write-scope.mjs +176 -28
- package/presets/_shared/ai-local/scripts/lock.mjs +60 -121
- package/presets/_shared/ai-local/scripts/team-db-api.mjs +471 -7
- package/presets/_shared/ai-local/scripts/team-db-backlog.mjs +1366 -0
- package/presets/_shared/ai-local/scripts/team-db-openapi.mjs +573 -7
- package/presets/_shared/ai-local/scripts/team-db-project.mjs +288 -4
- package/presets/_shared/ai-local/scripts/team-db-scheduler.mjs +82 -10
- package/presets/_shared/ai-local/scripts/team-db-schema.mjs +83 -0
- package/presets/_shared/ai-local/scripts/team-db.mjs +69 -6
- package/presets/_shared/ai-local/scripts/upstream-research.mjs +3 -0
- package/presets/_shared/core/agent-team/agent-artifact-contracts.md +4 -0
- package/presets/_shared/core/agent-team/agent-task-metrics.md +7 -2
- package/presets/_shared/core/agent-team/agent-team-intake.md +1 -0
- package/presets/_shared/core/agent-team/agent-team-orchestrator.md +6 -2
- package/presets/_shared/core/meta/preset-pr-checklist.md +4 -4
- package/presets/_shared/core/meta/preset-twin-sync.md +1 -1
- package/presets/_shared/hooks/chain-team-phases.sh.tmpl +225 -0
- package/presets/_shared/hooks/check-preset-update.mjs +4 -3
- package/presets/_shared/hooks/run-hook.mjs +2 -1
- package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +225 -0
- package/presets/claude/android-kotlin/hooks/check-preset-update.mjs +4 -3
- package/presets/claude/android-kotlin/hooks/run-hook.mjs +2 -1
- package/presets/claude/android-kotlin/rules/tooling-and-review/agent-team-intake.md +1 -0
- package/presets/claude/android-kotlin/rules/tooling-and-review/agent-team-orchestrator.md +6 -2
- package/presets/claude/android-kotlin/rules/tooling-and-review/preset-pr-checklist.md +4 -4
- package/presets/claude/android-kotlin/rules/tooling-and-review/preset-twin-sync.md +1 -1
- package/presets/claude/go/hooks/chain-team-phases.sh +225 -0
- package/presets/claude/go/hooks/check-preset-update.mjs +4 -3
- package/presets/claude/go/hooks/run-hook.mjs +2 -1
- package/presets/claude/go/rules/tooling-and-review/agent-team-intake.md +1 -0
- package/presets/claude/go/rules/tooling-and-review/agent-team-orchestrator.md +6 -2
- package/presets/claude/go/rules/tooling-and-review/preset-pr-checklist.md +4 -4
- package/presets/claude/go/rules/tooling-and-review/preset-twin-sync.md +1 -1
- package/presets/claude/ios-swift/hooks/chain-team-phases.sh +225 -0
- package/presets/claude/ios-swift/hooks/check-preset-update.mjs +4 -3
- package/presets/claude/ios-swift/hooks/run-hook.mjs +2 -1
- package/presets/claude/ios-swift/rules/tooling-and-review/agent-team-intake.md +1 -0
- package/presets/claude/ios-swift/rules/tooling-and-review/agent-team-orchestrator.md +6 -2
- package/presets/claude/ios-swift/rules/tooling-and-review/preset-pr-checklist.md +4 -4
- package/presets/claude/ios-swift/rules/tooling-and-review/preset-twin-sync.md +1 -1
- package/presets/claude/java/hooks/chain-team-phases.sh +225 -0
- package/presets/claude/java/hooks/check-preset-update.mjs +4 -3
- package/presets/claude/java/hooks/run-hook.mjs +2 -1
- package/presets/claude/java/rules/tooling-and-review/agent-team-intake.md +1 -0
- package/presets/claude/java/rules/tooling-and-review/agent-team-orchestrator.md +6 -2
- package/presets/claude/java/rules/tooling-and-review/preset-pr-checklist.md +4 -4
- package/presets/claude/java/rules/tooling-and-review/preset-twin-sync.md +1 -1
- package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +225 -0
- package/presets/claude/mcp-ts/hooks/check-preset-update.mjs +4 -3
- package/presets/claude/mcp-ts/hooks/run-hook.mjs +2 -1
- package/presets/claude/mcp-ts/rules/tooling-and-review/agent-team-intake.md +1 -0
- package/presets/claude/mcp-ts/rules/tooling-and-review/agent-team-orchestrator.md +6 -2
- package/presets/claude/mcp-ts/rules/tooling-and-review/preset-pr-checklist.md +4 -4
- package/presets/claude/mcp-ts/rules/tooling-and-review/preset-twin-sync.md +1 -1
- package/presets/claude/mol/hooks/chain-team-phases.sh +225 -0
- package/presets/claude/mol/hooks/check-preset-update.mjs +4 -3
- package/presets/claude/mol/hooks/run-hook.mjs +2 -1
- package/presets/claude/mol/rules/tooling-and-review/agent-team-intake.md +1 -0
- package/presets/claude/mol/rules/tooling-and-review/agent-team-orchestrator.md +6 -2
- package/presets/claude/mol/rules/tooling-and-review/preset-pr-checklist.md +4 -4
- package/presets/claude/mol/rules/tooling-and-review/preset-twin-sync.md +1 -1
- package/presets/claude/next/agents/build-verifier.md +16 -3
- package/presets/claude/next/agents/code-reviewer.md +1 -0
- package/presets/claude/next/agents/feature-developer.md +2 -1
- package/presets/claude/next/agents/mockup-reviewer.md +2 -1
- package/presets/claude/next/agents/task-analyst.md +4 -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/upstream-research.md +1 -1
- package/presets/claude/next/hooks/chain-team-phases.sh +225 -0
- package/presets/claude/next/hooks/check-preset-update.mjs +4 -3
- package/presets/claude/next/hooks/run-hook.mjs +2 -1
- package/presets/claude/next/rules/tooling-and-review/agent-team-intake.md +1 -0
- package/presets/claude/next/rules/tooling-and-review/agent-team-orchestrator.md +6 -2
- package/presets/claude/next/rules/tooling-and-review/preset-pr-checklist.md +4 -4
- package/presets/claude/next/rules/tooling-and-review/preset-twin-sync.md +1 -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 +225 -0
- package/presets/claude/nuxt/hooks/check-preset-update.mjs +4 -3
- package/presets/claude/nuxt/hooks/run-hook.mjs +2 -1
- package/presets/claude/nuxt/rules/tooling-and-review/agent-team-intake.md +1 -0
- package/presets/claude/nuxt/rules/tooling-and-review/agent-team-orchestrator.md +6 -2
- package/presets/claude/nuxt/rules/tooling-and-review/preset-pr-checklist.md +4 -4
- package/presets/claude/nuxt/rules/tooling-and-review/preset-twin-sync.md +1 -1
- package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +225 -0
- package/presets/claude/php-hexagonal/hooks/check-preset-update.mjs +4 -3
- package/presets/claude/php-hexagonal/hooks/run-hook.mjs +2 -1
- package/presets/claude/php-hexagonal/rules/tooling-and-review/agent-team-intake.md +1 -0
- package/presets/claude/php-hexagonal/rules/tooling-and-review/agent-team-orchestrator.md +6 -2
- package/presets/claude/php-hexagonal/rules/tooling-and-review/preset-pr-checklist.md +4 -4
- package/presets/claude/php-hexagonal/rules/tooling-and-review/preset-twin-sync.md +1 -1
- package/presets/claude/php-laravel/hooks/chain-team-phases.sh +225 -0
- package/presets/claude/php-laravel/hooks/check-preset-update.mjs +4 -3
- package/presets/claude/php-laravel/hooks/run-hook.mjs +2 -1
- package/presets/claude/php-laravel/rules/tooling-and-review/agent-team-intake.md +1 -0
- package/presets/claude/php-laravel/rules/tooling-and-review/agent-team-orchestrator.md +6 -2
- package/presets/claude/php-laravel/rules/tooling-and-review/preset-pr-checklist.md +4 -4
- package/presets/claude/php-laravel/rules/tooling-and-review/preset-twin-sync.md +1 -1
- package/presets/claude/svelte/hooks/chain-team-phases.sh +225 -0
- package/presets/claude/svelte/hooks/check-preset-update.mjs +4 -3
- package/presets/claude/svelte/hooks/run-hook.mjs +2 -1
- package/presets/claude/svelte/rules/tooling-and-review/agent-team-intake.md +1 -0
- package/presets/claude/svelte/rules/tooling-and-review/agent-team-orchestrator.md +6 -2
- package/presets/claude/svelte/rules/tooling-and-review/preset-pr-checklist.md +4 -4
- package/presets/claude/svelte/rules/tooling-and-review/preset-twin-sync.md +1 -1
- package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +225 -0
- package/presets/cursor/android-kotlin/hooks/check-preset-update.mjs +4 -3
- package/presets/cursor/android-kotlin/hooks/run-hook.mjs +2 -1
- package/presets/cursor/android-kotlin/rules/agent-team-intake.mdc +1 -0
- package/presets/cursor/android-kotlin/rules/agent-team-orchestrator.mdc +2 -1
- package/presets/cursor/android-kotlin/rules/preset-pr-checklist.mdc +4 -4
- package/presets/cursor/android-kotlin/rules/preset-twin-sync.mdc +1 -1
- package/presets/cursor/go/hooks/chain-team-phases.sh +225 -0
- package/presets/cursor/go/hooks/check-preset-update.mjs +4 -3
- package/presets/cursor/go/hooks/run-hook.mjs +2 -1
- package/presets/cursor/go/rules/agent-team-intake.mdc +1 -0
- package/presets/cursor/go/rules/agent-team-orchestrator.mdc +2 -1
- package/presets/cursor/go/rules/preset-pr-checklist.mdc +4 -4
- package/presets/cursor/go/rules/preset-twin-sync.mdc +1 -1
- package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +225 -0
- package/presets/cursor/ios-swift/hooks/check-preset-update.mjs +4 -3
- package/presets/cursor/ios-swift/hooks/run-hook.mjs +2 -1
- package/presets/cursor/ios-swift/rules/agent-team-intake.mdc +1 -0
- package/presets/cursor/ios-swift/rules/agent-team-orchestrator.mdc +2 -1
- package/presets/cursor/ios-swift/rules/preset-pr-checklist.mdc +4 -4
- package/presets/cursor/ios-swift/rules/preset-twin-sync.mdc +1 -1
- package/presets/cursor/java/hooks/chain-team-phases.sh +225 -0
- package/presets/cursor/java/hooks/check-preset-update.mjs +4 -3
- package/presets/cursor/java/hooks/run-hook.mjs +2 -1
- package/presets/cursor/java/rules/agent-team-intake.mdc +1 -0
- package/presets/cursor/java/rules/agent-team-orchestrator.mdc +2 -1
- package/presets/cursor/java/rules/preset-pr-checklist.mdc +4 -4
- package/presets/cursor/java/rules/preset-twin-sync.mdc +1 -1
- package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +225 -0
- package/presets/cursor/mcp-ts/hooks/check-preset-update.mjs +4 -3
- package/presets/cursor/mcp-ts/hooks/run-hook.mjs +2 -1
- package/presets/cursor/mcp-ts/rules/agent-team-intake.mdc +1 -0
- package/presets/cursor/mcp-ts/rules/agent-team-orchestrator.mdc +2 -1
- package/presets/cursor/mcp-ts/rules/preset-pr-checklist.mdc +4 -4
- package/presets/cursor/mcp-ts/rules/preset-twin-sync.mdc +1 -1
- package/presets/cursor/mol/hooks/chain-team-phases.sh +225 -0
- package/presets/cursor/mol/hooks/check-preset-update.mjs +4 -3
- package/presets/cursor/mol/hooks/run-hook.mjs +2 -1
- package/presets/cursor/mol/rules/agent-team-intake.mdc +1 -0
- package/presets/cursor/mol/rules/agent-team-orchestrator.mdc +2 -1
- package/presets/cursor/mol/rules/preset-pr-checklist.mdc +4 -4
- package/presets/cursor/mol/rules/preset-twin-sync.mdc +1 -1
- package/presets/cursor/next/agents/build-verifier.md +16 -3
- package/presets/cursor/next/agents/code-reviewer.md +1 -0
- package/presets/cursor/next/agents/feature-developer.md +2 -1
- package/presets/cursor/next/agents/mockup-reviewer.md +2 -1
- package/presets/cursor/next/agents/task-analyst.md +4 -0
- package/presets/cursor/next/ai-local/rules-library/storybook-dev-compare-figma.md +1 -0
- package/presets/cursor/next/ai-local/rules-library/ui-change-review-gate.md +1 -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/upstream-research.md +1 -1
- package/presets/cursor/next/hooks/chain-team-phases.sh +225 -0
- package/presets/cursor/next/hooks/check-preset-update.mjs +4 -3
- package/presets/cursor/next/hooks/run-hook.mjs +2 -1
- package/presets/cursor/next/rules/agent-team-intake.mdc +1 -0
- package/presets/cursor/next/rules/agent-team-orchestrator.mdc +2 -1
- package/presets/cursor/next/rules/preset-pr-checklist.mdc +4 -4
- package/presets/cursor/next/rules/preset-twin-sync.mdc +1 -1
- 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 +225 -0
- package/presets/cursor/nuxt/hooks/check-preset-update.mjs +4 -3
- package/presets/cursor/nuxt/hooks/run-hook.mjs +2 -1
- package/presets/cursor/nuxt/rules/agent-team-intake.mdc +1 -0
- package/presets/cursor/nuxt/rules/agent-team-orchestrator.mdc +2 -1
- package/presets/cursor/nuxt/rules/preset-pr-checklist.mdc +4 -4
- package/presets/cursor/nuxt/rules/preset-twin-sync.mdc +1 -1
- package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +225 -0
- package/presets/cursor/php-hexagonal/hooks/check-preset-update.mjs +4 -3
- package/presets/cursor/php-hexagonal/hooks/run-hook.mjs +2 -1
- package/presets/cursor/php-hexagonal/rules/agent-team-intake.mdc +1 -0
- package/presets/cursor/php-hexagonal/rules/agent-team-orchestrator.mdc +2 -1
- package/presets/cursor/php-hexagonal/rules/preset-pr-checklist.mdc +4 -4
- package/presets/cursor/php-hexagonal/rules/preset-twin-sync.mdc +1 -1
- package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +225 -0
- package/presets/cursor/php-laravel/hooks/check-preset-update.mjs +4 -3
- package/presets/cursor/php-laravel/hooks/run-hook.mjs +2 -1
- package/presets/cursor/php-laravel/rules/agent-team-intake.mdc +1 -0
- package/presets/cursor/php-laravel/rules/agent-team-orchestrator.mdc +2 -1
- package/presets/cursor/php-laravel/rules/preset-pr-checklist.mdc +4 -4
- package/presets/cursor/php-laravel/rules/preset-twin-sync.mdc +1 -1
- package/presets/cursor/svelte/hooks/chain-team-phases.sh +225 -0
- package/presets/cursor/svelte/hooks/check-preset-update.mjs +4 -3
- package/presets/cursor/svelte/hooks/run-hook.mjs +2 -1
- package/presets/cursor/svelte/rules/agent-team-intake.mdc +1 -0
- package/presets/cursor/svelte/rules/agent-team-orchestrator.mdc +2 -1
- package/presets/cursor/svelte/rules/preset-pr-checklist.mdc +4 -4
- package/presets/cursor/svelte/rules/preset-twin-sync.mdc +1 -1
- package/presets/mavis/android-kotlin/adapter-map.json +1 -1
- package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +225 -0
- package/presets/mavis/android-kotlin/hooks/check-preset-update.mjs +4 -3
- package/presets/mavis/android-kotlin/rules/agent-team-intake.md +1 -0
- package/presets/mavis/android-kotlin/rules/agent-team-orchestrator.md +6 -2
- package/presets/mavis/android-kotlin/rules/preset-pr-checklist.md +4 -4
- package/presets/mavis/android-kotlin/rules/preset-twin-sync.md +1 -1
- package/presets/mavis/go/adapter-map.json +1 -1
- package/presets/mavis/go/hooks/chain-team-phases.sh +225 -0
- package/presets/mavis/go/hooks/check-preset-update.mjs +4 -3
- package/presets/mavis/go/rules/agent-team-intake.md +1 -0
- package/presets/mavis/go/rules/agent-team-orchestrator.md +6 -2
- package/presets/mavis/go/rules/preset-pr-checklist.md +4 -4
- package/presets/mavis/go/rules/preset-twin-sync.md +1 -1
- package/presets/mavis/ios-swift/adapter-map.json +1 -1
- package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +225 -0
- package/presets/mavis/ios-swift/hooks/check-preset-update.mjs +4 -3
- package/presets/mavis/ios-swift/rules/agent-team-intake.md +1 -0
- package/presets/mavis/ios-swift/rules/agent-team-orchestrator.md +6 -2
- package/presets/mavis/ios-swift/rules/preset-pr-checklist.md +4 -4
- package/presets/mavis/ios-swift/rules/preset-twin-sync.md +1 -1
- package/presets/mavis/java/adapter-map.json +1 -1
- package/presets/mavis/java/hooks/chain-team-phases.sh +225 -0
- package/presets/mavis/java/hooks/check-preset-update.mjs +4 -3
- package/presets/mavis/java/rules/agent-team-intake.md +1 -0
- package/presets/mavis/java/rules/agent-team-orchestrator.md +6 -2
- package/presets/mavis/java/rules/preset-pr-checklist.md +4 -4
- package/presets/mavis/java/rules/preset-twin-sync.md +1 -1
- package/presets/mavis/mcp-ts/adapter-map.json +1 -1
- package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +225 -0
- package/presets/mavis/mcp-ts/hooks/check-preset-update.mjs +4 -3
- package/presets/mavis/mcp-ts/rules/agent-team-intake.md +1 -0
- package/presets/mavis/mcp-ts/rules/agent-team-orchestrator.md +6 -2
- package/presets/mavis/mcp-ts/rules/preset-pr-checklist.md +4 -4
- package/presets/mavis/mcp-ts/rules/preset-twin-sync.md +1 -1
- package/presets/mavis/mol/adapter-map.json +1 -1
- package/presets/mavis/mol/hooks/chain-team-phases.sh +225 -0
- package/presets/mavis/mol/hooks/check-preset-update.mjs +4 -3
- package/presets/mavis/mol/rules/agent-team-intake.md +1 -0
- package/presets/mavis/mol/rules/agent-team-orchestrator.md +6 -2
- package/presets/mavis/mol/rules/preset-pr-checklist.md +4 -4
- package/presets/mavis/mol/rules/preset-twin-sync.md +1 -1
- package/presets/mavis/next/adapter-map.json +9 -1
- package/presets/mavis/next/agents/build-verifier.md +16 -3
- package/presets/mavis/next/agents/code-reviewer.md +1 -0
- package/presets/mavis/next/agents/feature-developer.md +2 -1
- package/presets/mavis/next/agents/mockup-reviewer.md +2 -1
- package/presets/mavis/next/agents/task-analyst.md +4 -0
- package/presets/mavis/next/ai-local/rules-library/storybook-dev-compare-figma.md +1 -0
- package/presets/mavis/next/ai-local/rules-library/ui-change-review-gate.md +1 -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/upstream-research.md +1 -1
- package/presets/mavis/next/hooks/chain-team-phases.sh +225 -0
- package/presets/mavis/next/hooks/check-preset-update.mjs +4 -3
- package/presets/mavis/next/rules/agent-team-intake.md +1 -0
- package/presets/mavis/next/rules/agent-team-orchestrator.md +6 -2
- package/presets/mavis/next/rules/preset-pr-checklist.md +4 -4
- package/presets/mavis/next/rules/preset-twin-sync.md +1 -1
- 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 +225 -0
- package/presets/mavis/nuxt/hooks/check-preset-update.mjs +4 -3
- package/presets/mavis/nuxt/rules/agent-team-intake.md +1 -0
- package/presets/mavis/nuxt/rules/agent-team-orchestrator.md +6 -2
- package/presets/mavis/nuxt/rules/preset-pr-checklist.md +4 -4
- package/presets/mavis/nuxt/rules/preset-twin-sync.md +1 -1
- package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
- package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +225 -0
- package/presets/mavis/php-hexagonal/hooks/check-preset-update.mjs +4 -3
- package/presets/mavis/php-hexagonal/rules/agent-team-intake.md +1 -0
- package/presets/mavis/php-hexagonal/rules/agent-team-orchestrator.md +6 -2
- package/presets/mavis/php-hexagonal/rules/preset-pr-checklist.md +4 -4
- package/presets/mavis/php-hexagonal/rules/preset-twin-sync.md +1 -1
- package/presets/mavis/php-laravel/adapter-map.json +1 -1
- package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +225 -0
- package/presets/mavis/php-laravel/hooks/check-preset-update.mjs +4 -3
- package/presets/mavis/php-laravel/rules/agent-team-intake.md +1 -0
- package/presets/mavis/php-laravel/rules/agent-team-orchestrator.md +6 -2
- package/presets/mavis/php-laravel/rules/preset-pr-checklist.md +4 -4
- package/presets/mavis/php-laravel/rules/preset-twin-sync.md +1 -1
- package/presets/mavis/svelte/adapter-map.json +1 -1
- package/presets/mavis/svelte/hooks/chain-team-phases.sh +225 -0
- package/presets/mavis/svelte/hooks/check-preset-update.mjs +4 -3
- package/presets/mavis/svelte/rules/agent-team-intake.md +1 -0
- package/presets/mavis/svelte/rules/agent-team-orchestrator.md +6 -2
- package/presets/mavis/svelte/rules/preset-pr-checklist.md +4 -4
- package/presets/mavis/svelte/rules/preset-twin-sync.md +1 -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 +225 -0
- package/presets/opencode/android-kotlin/hooks/check-preset-update.mjs +4 -3
- package/presets/opencode/android-kotlin/rules/agent-team-intake.md +1 -0
- package/presets/opencode/android-kotlin/rules/agent-team-orchestrator.md +6 -2
- package/presets/opencode/android-kotlin/rules/preset-pr-checklist.md +4 -4
- package/presets/opencode/android-kotlin/rules/preset-twin-sync.md +1 -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 +225 -0
- package/presets/opencode/go/hooks/check-preset-update.mjs +4 -3
- package/presets/opencode/go/rules/agent-team-intake.md +1 -0
- package/presets/opencode/go/rules/agent-team-orchestrator.md +6 -2
- package/presets/opencode/go/rules/preset-pr-checklist.md +4 -4
- package/presets/opencode/go/rules/preset-twin-sync.md +1 -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 +225 -0
- package/presets/opencode/ios-swift/hooks/check-preset-update.mjs +4 -3
- package/presets/opencode/ios-swift/rules/agent-team-intake.md +1 -0
- package/presets/opencode/ios-swift/rules/agent-team-orchestrator.md +6 -2
- package/presets/opencode/ios-swift/rules/preset-pr-checklist.md +4 -4
- package/presets/opencode/ios-swift/rules/preset-twin-sync.md +1 -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 +225 -0
- package/presets/opencode/java/hooks/check-preset-update.mjs +4 -3
- package/presets/opencode/java/rules/agent-team-intake.md +1 -0
- package/presets/opencode/java/rules/agent-team-orchestrator.md +6 -2
- package/presets/opencode/java/rules/preset-pr-checklist.md +4 -4
- package/presets/opencode/java/rules/preset-twin-sync.md +1 -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 +225 -0
- package/presets/opencode/mcp-ts/hooks/check-preset-update.mjs +4 -3
- package/presets/opencode/mcp-ts/rules/agent-team-intake.md +1 -0
- package/presets/opencode/mcp-ts/rules/agent-team-orchestrator.md +6 -2
- package/presets/opencode/mcp-ts/rules/preset-pr-checklist.md +4 -4
- package/presets/opencode/mcp-ts/rules/preset-twin-sync.md +1 -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 +225 -0
- package/presets/opencode/mol/hooks/check-preset-update.mjs +4 -3
- package/presets/opencode/mol/rules/agent-team-intake.md +1 -0
- package/presets/opencode/mol/rules/agent-team-orchestrator.md +6 -2
- package/presets/opencode/mol/rules/preset-pr-checklist.md +4 -4
- package/presets/opencode/mol/rules/preset-twin-sync.md +1 -1
- package/presets/opencode/next/OPENCODE.md +4 -1
- package/presets/opencode/next/README.md +1 -0
- package/presets/opencode/next/adapter-map.json +9 -1
- package/presets/opencode/next/agents/build-verifier.md +16 -3
- package/presets/opencode/next/agents/code-reviewer.md +1 -0
- package/presets/opencode/next/agents/feature-developer.md +2 -1
- package/presets/opencode/next/agents/mockup-reviewer.md +2 -1
- package/presets/opencode/next/agents/task-analyst.md +4 -0
- package/presets/opencode/next/ai-local/rules-library/storybook-dev-compare-figma.md +1 -0
- package/presets/opencode/next/ai-local/rules-library/ui-change-review-gate.md +1 -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/upstream-research.md +1 -1
- package/presets/opencode/next/hooks/README.md +4 -2
- package/presets/opencode/next/hooks/chain-team-phases.sh +225 -0
- package/presets/opencode/next/hooks/check-preset-update.mjs +4 -3
- package/presets/opencode/next/rules/agent-team-intake.md +1 -0
- package/presets/opencode/next/rules/agent-team-orchestrator.md +6 -2
- package/presets/opencode/next/rules/preset-pr-checklist.md +4 -4
- package/presets/opencode/next/rules/preset-twin-sync.md +1 -1
- 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 +225 -0
- package/presets/opencode/nuxt/hooks/check-preset-update.mjs +4 -3
- package/presets/opencode/nuxt/rules/agent-team-intake.md +1 -0
- package/presets/opencode/nuxt/rules/agent-team-orchestrator.md +6 -2
- package/presets/opencode/nuxt/rules/preset-pr-checklist.md +4 -4
- package/presets/opencode/nuxt/rules/preset-twin-sync.md +1 -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 +225 -0
- package/presets/opencode/php-hexagonal/hooks/check-preset-update.mjs +4 -3
- package/presets/opencode/php-hexagonal/rules/agent-team-intake.md +1 -0
- package/presets/opencode/php-hexagonal/rules/agent-team-orchestrator.md +6 -2
- package/presets/opencode/php-hexagonal/rules/preset-pr-checklist.md +4 -4
- package/presets/opencode/php-hexagonal/rules/preset-twin-sync.md +1 -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 +225 -0
- package/presets/opencode/php-laravel/hooks/check-preset-update.mjs +4 -3
- package/presets/opencode/php-laravel/rules/agent-team-intake.md +1 -0
- package/presets/opencode/php-laravel/rules/agent-team-orchestrator.md +6 -2
- package/presets/opencode/php-laravel/rules/preset-pr-checklist.md +4 -4
- package/presets/opencode/php-laravel/rules/preset-twin-sync.md +1 -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 +225 -0
- package/presets/opencode/svelte/hooks/check-preset-update.mjs +4 -3
- package/presets/opencode/svelte/rules/agent-team-intake.md +1 -0
- package/presets/opencode/svelte/rules/agent-team-orchestrator.md +6 -2
- package/presets/opencode/svelte/rules/preset-pr-checklist.md +4 -4
- package/presets/opencode/svelte/rules/preset-twin-sync.md +1 -1
- package/presets/zcode/android-kotlin/adapter-map.json +1 -1
- package/presets/zcode/android-kotlin/hooks/chain-team-phases.sh +225 -0
- package/presets/zcode/android-kotlin/hooks/check-preset-update.mjs +4 -3
- package/presets/zcode/android-kotlin/rules/agent-team-intake.md +1 -0
- package/presets/zcode/android-kotlin/rules/agent-team-orchestrator.md +6 -2
- package/presets/zcode/android-kotlin/rules/preset-pr-checklist.md +4 -4
- package/presets/zcode/android-kotlin/rules/preset-twin-sync.md +1 -1
- package/presets/zcode/go/adapter-map.json +1 -1
- package/presets/zcode/go/hooks/chain-team-phases.sh +225 -0
- package/presets/zcode/go/hooks/check-preset-update.mjs +4 -3
- package/presets/zcode/go/rules/agent-team-intake.md +1 -0
- package/presets/zcode/go/rules/agent-team-orchestrator.md +6 -2
- package/presets/zcode/go/rules/preset-pr-checklist.md +4 -4
- package/presets/zcode/go/rules/preset-twin-sync.md +1 -1
- package/presets/zcode/ios-swift/adapter-map.json +1 -1
- package/presets/zcode/ios-swift/hooks/chain-team-phases.sh +225 -0
- package/presets/zcode/ios-swift/hooks/check-preset-update.mjs +4 -3
- package/presets/zcode/ios-swift/rules/agent-team-intake.md +1 -0
- package/presets/zcode/ios-swift/rules/agent-team-orchestrator.md +6 -2
- package/presets/zcode/ios-swift/rules/preset-pr-checklist.md +4 -4
- package/presets/zcode/ios-swift/rules/preset-twin-sync.md +1 -1
- package/presets/zcode/java/adapter-map.json +1 -1
- package/presets/zcode/java/hooks/chain-team-phases.sh +225 -0
- package/presets/zcode/java/hooks/check-preset-update.mjs +4 -3
- package/presets/zcode/java/rules/agent-team-intake.md +1 -0
- package/presets/zcode/java/rules/agent-team-orchestrator.md +6 -2
- package/presets/zcode/java/rules/preset-pr-checklist.md +4 -4
- package/presets/zcode/java/rules/preset-twin-sync.md +1 -1
- package/presets/zcode/mcp-ts/adapter-map.json +1 -1
- package/presets/zcode/mcp-ts/hooks/chain-team-phases.sh +225 -0
- package/presets/zcode/mcp-ts/hooks/check-preset-update.mjs +4 -3
- package/presets/zcode/mcp-ts/rules/agent-team-intake.md +1 -0
- package/presets/zcode/mcp-ts/rules/agent-team-orchestrator.md +6 -2
- package/presets/zcode/mcp-ts/rules/preset-pr-checklist.md +4 -4
- package/presets/zcode/mcp-ts/rules/preset-twin-sync.md +1 -1
- package/presets/zcode/mol/adapter-map.json +1 -1
- package/presets/zcode/mol/hooks/chain-team-phases.sh +225 -0
- package/presets/zcode/mol/hooks/check-preset-update.mjs +4 -3
- package/presets/zcode/mol/rules/agent-team-intake.md +1 -0
- package/presets/zcode/mol/rules/agent-team-orchestrator.md +6 -2
- package/presets/zcode/mol/rules/preset-pr-checklist.md +4 -4
- package/presets/zcode/mol/rules/preset-twin-sync.md +1 -1
- package/presets/zcode/next/adapter-map.json +9 -1
- package/presets/zcode/next/agents/build-verifier.md +16 -3
- package/presets/zcode/next/agents/code-reviewer.md +1 -0
- package/presets/zcode/next/agents/feature-developer.md +2 -1
- package/presets/zcode/next/agents/mockup-reviewer.md +2 -1
- package/presets/zcode/next/agents/task-analyst.md +4 -0
- package/presets/zcode/next/ai-local/rules-library/storybook-dev-compare-figma.md +1 -0
- package/presets/zcode/next/ai-local/rules-library/ui-change-review-gate.md +1 -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/upstream-research.md +1 -1
- package/presets/zcode/next/hooks/chain-team-phases.sh +225 -0
- package/presets/zcode/next/hooks/check-preset-update.mjs +4 -3
- package/presets/zcode/next/rules/agent-team-intake.md +1 -0
- package/presets/zcode/next/rules/agent-team-orchestrator.md +6 -2
- package/presets/zcode/next/rules/preset-pr-checklist.md +4 -4
- package/presets/zcode/next/rules/preset-twin-sync.md +1 -1
- 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 +225 -0
- package/presets/zcode/nuxt/hooks/check-preset-update.mjs +4 -3
- package/presets/zcode/nuxt/rules/agent-team-intake.md +1 -0
- package/presets/zcode/nuxt/rules/agent-team-orchestrator.md +6 -2
- package/presets/zcode/nuxt/rules/preset-pr-checklist.md +4 -4
- package/presets/zcode/nuxt/rules/preset-twin-sync.md +1 -1
- package/presets/zcode/php-hexagonal/adapter-map.json +1 -1
- package/presets/zcode/php-hexagonal/hooks/chain-team-phases.sh +225 -0
- package/presets/zcode/php-hexagonal/hooks/check-preset-update.mjs +4 -3
- package/presets/zcode/php-hexagonal/rules/agent-team-intake.md +1 -0
- package/presets/zcode/php-hexagonal/rules/agent-team-orchestrator.md +6 -2
- package/presets/zcode/php-hexagonal/rules/preset-pr-checklist.md +4 -4
- package/presets/zcode/php-hexagonal/rules/preset-twin-sync.md +1 -1
- package/presets/zcode/php-laravel/adapter-map.json +1 -1
- package/presets/zcode/php-laravel/hooks/chain-team-phases.sh +225 -0
- package/presets/zcode/php-laravel/hooks/check-preset-update.mjs +4 -3
- package/presets/zcode/php-laravel/rules/agent-team-intake.md +1 -0
- package/presets/zcode/php-laravel/rules/agent-team-orchestrator.md +6 -2
- package/presets/zcode/php-laravel/rules/preset-pr-checklist.md +4 -4
- package/presets/zcode/php-laravel/rules/preset-twin-sync.md +1 -1
- package/presets/zcode/svelte/adapter-map.json +1 -1
- package/presets/zcode/svelte/hooks/chain-team-phases.sh +225 -0
- package/presets/zcode/svelte/hooks/check-preset-update.mjs +4 -3
- package/presets/zcode/svelte/rules/agent-team-intake.md +1 -0
- package/presets/zcode/svelte/rules/agent-team-orchestrator.md +6 -2
- package/presets/zcode/svelte/rules/preset-pr-checklist.md +4 -4
- package/presets/zcode/svelte/rules/preset-twin-sync.md +1 -1
- package/scripts/aggregate-agent-task-metrics.mjs +48 -4
|
@@ -0,0 +1,1366 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The file-authoritative backlog store for `.ai.local/team/backlog/**`:
|
|
3
|
+
* items, the launch queue, the deterministic eligibility order and the import
|
|
4
|
+
* envelope.
|
|
5
|
+
*
|
|
6
|
+
* Files are authoritative and this module is the only writer of
|
|
7
|
+
* `backlog/items/*.json` and `backlog/queue/*.json` (I-1, I-2). The store is
|
|
8
|
+
* file-only by design: no verb here opens a database, so the kill switch
|
|
9
|
+
* (`AI_RULES_TEAM_DB_DISABLE=1`) never disables a backlog write — it stops the
|
|
10
|
+
* projection only (R3-7). A write verb projects afterwards on a best-effort
|
|
11
|
+
* bounded child so the read-only API sees fresh rows; a projection failure
|
|
12
|
+
* never fails the write.
|
|
13
|
+
*
|
|
14
|
+
* The stored status lattice (`planned|completed|cancelled|superseded`) is the
|
|
15
|
+
* only decision recorded; every operational status (`effectiveStatus`) is
|
|
16
|
+
* derived from the item, the queue entries and the hook-owned task state, and
|
|
17
|
+
* is never written to a file (I-3). `rank(item) = priority ASC → createdAt ASC
|
|
18
|
+
* → id ASC` is a total order and the only order (I-4, D-4). This module never
|
|
19
|
+
* writes a lifecycle, gate or metric file and never starts an agent run: the
|
|
20
|
+
* hook stop seam consumes `drain --claim` and owns the launch (I-5, D-5).
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import crypto from 'node:crypto';
|
|
24
|
+
import fs from 'node:fs';
|
|
25
|
+
import path from 'node:path';
|
|
26
|
+
import { fileURLToPath } from 'node:url';
|
|
27
|
+
import { spawnSync } from 'node:child_process';
|
|
28
|
+
|
|
29
|
+
import { DEFAULT_TEAM_ROOT, TeamDbError, teamDbFail } from './team-db-schema.mjs';
|
|
30
|
+
import { acquireLock, releaseLock } from './lock.mjs';
|
|
31
|
+
|
|
32
|
+
export const BACKLOG_DIR = 'backlog';
|
|
33
|
+
export const ITEMS_DIR = 'items';
|
|
34
|
+
export const QUEUE_DIR = 'queue';
|
|
35
|
+
export const CONFIG_FILE = 'config.json';
|
|
36
|
+
|
|
37
|
+
export const ITEM_SCHEMA_VERSION = 1;
|
|
38
|
+
export const ENTRY_SCHEMA_VERSION = 1;
|
|
39
|
+
export const CONFIG_SCHEMA_VERSION = 1;
|
|
40
|
+
|
|
41
|
+
/** One grammar across `backlog id`, `tasks/<slug>/` and `params.slug` (D-2). */
|
|
42
|
+
export const ITEM_ID_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
43
|
+
/** The scheduler's `RUN_ID_RE` shape, so one id grammar reads across the tree. */
|
|
44
|
+
export const ENTRY_ID_RE = /^[0-9]{8}T[0-9]{6}Z-[0-9a-f]{8}$/;
|
|
45
|
+
|
|
46
|
+
export const ITEM_STATUSES = ['planned', 'completed', 'cancelled', 'superseded'];
|
|
47
|
+
export const ITEM_TYPES = ['feature', 'bugfix', 'spike', 'chore', 'docs', 'refactor'];
|
|
48
|
+
export const ENTRY_STATUSES = ['queued', 'claimed', 'cancelled', 'expired'];
|
|
49
|
+
|
|
50
|
+
export const ITEM_HISTORY_TYPES = new Set([
|
|
51
|
+
'created',
|
|
52
|
+
'updated',
|
|
53
|
+
'status-changed',
|
|
54
|
+
'priority-changed',
|
|
55
|
+
'deps-changed',
|
|
56
|
+
'imported',
|
|
57
|
+
'cancelled',
|
|
58
|
+
'completed',
|
|
59
|
+
'reopened',
|
|
60
|
+
'superseded',
|
|
61
|
+
]);
|
|
62
|
+
export const ENTRY_HISTORY_TYPES = new Set(['enqueued', 'claimed', 'released', 'cancelled', 'expired', 'recovered']);
|
|
63
|
+
|
|
64
|
+
export const EFFECTIVE_ITEM_STATUSES = ['planned', 'queued', 'launched', 'completed', 'cancelled', 'superseded'];
|
|
65
|
+
export const EFFECTIVE_ENTRY_STATUSES = ['queued', 'claimed', 'active', 'done', 'cancelled', 'expired'];
|
|
66
|
+
|
|
67
|
+
/** WIP states that hold a launch slot; everything else is passive (R3-2). */
|
|
68
|
+
export const HOLDING_TASK_STATES = new Set(['in_progress', 'awaiting_artifact_receipt', 'blocked']);
|
|
69
|
+
|
|
70
|
+
/** A claim older than this with no task row is released on the next drain (the scheduler's lease). */
|
|
71
|
+
export const CLAIM_STALE_MS = 90 * 1000;
|
|
72
|
+
/** `createdAt` further in the future than this skew is `E_SCHEMA` (F-8). */
|
|
73
|
+
export const FUTURE_CREATED_AT_SKEW_MS = 5 * 60 * 1000;
|
|
74
|
+
|
|
75
|
+
export const MAX_TITLE_CHARS = 120;
|
|
76
|
+
export const MAX_DESCRIPTION_CHARS = 2000;
|
|
77
|
+
export const MAX_LABELS = 8;
|
|
78
|
+
export const MAX_LABEL_CHARS = 32;
|
|
79
|
+
export const MAX_ITEM_HISTORY = 64;
|
|
80
|
+
export const MAX_ENTRY_HISTORY = 32;
|
|
81
|
+
export const MAX_DEPENDENCIES = 32;
|
|
82
|
+
export const MAX_SOURCE_REFS = 16;
|
|
83
|
+
export const MAX_SOURCE_REF_CHARS = 40;
|
|
84
|
+
export const MAX_CANCEL_REASON_CHARS = 200;
|
|
85
|
+
export const MAX_REASON_CHARS = 200;
|
|
86
|
+
export const MAX_REQUESTED_BY_CHARS = 120;
|
|
87
|
+
export const MAX_COMMAND_CHARS = 200;
|
|
88
|
+
export const MAX_ACTIVE_MIN = 1;
|
|
89
|
+
export const MAX_ACTIVE_MAX = 8;
|
|
90
|
+
export const DEFAULT_MAX_ACTIVE = 1;
|
|
91
|
+
export const DEFAULT_PRUNE_DAYS = 90;
|
|
92
|
+
|
|
93
|
+
const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
94
|
+
|
|
95
|
+
const isTruthy = (value) => {
|
|
96
|
+
if (typeof value !== 'string') return false;
|
|
97
|
+
const normalized = value.trim().toLowerCase();
|
|
98
|
+
return normalized === '1' || normalized === 'true' || normalized === 'yes';
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
const nowIso = () => new Date().toISOString();
|
|
102
|
+
|
|
103
|
+
/** RFC 3339 with an explicit `Z`; anything else is a schema failure. */
|
|
104
|
+
const isIsoZ = (value) => typeof value === 'string' && /Z$/.test(value) && !Number.isNaN(Date.parse(value));
|
|
105
|
+
|
|
106
|
+
const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');
|
|
107
|
+
|
|
108
|
+
/** Canonical JSON with sorted keys, so content-hash equality is byte-stable. */
|
|
109
|
+
const canonicalJson = (value) => {
|
|
110
|
+
const walk = (node) => {
|
|
111
|
+
if (node === null || typeof node !== 'object') return node;
|
|
112
|
+
if (Array.isArray(node)) return node.map(walk);
|
|
113
|
+
const sorted = {};
|
|
114
|
+
for (const key of Object.keys(node).sort()) sorted[key] = walk(node[key]);
|
|
115
|
+
return sorted;
|
|
116
|
+
};
|
|
117
|
+
return JSON.stringify(walk(value));
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
const reject = (code, message) => teamDbFail(code, message, 1);
|
|
121
|
+
|
|
122
|
+
const capHistory = (history, max) => history.slice(Math.max(0, history.length - max));
|
|
123
|
+
|
|
124
|
+
/* --------------------------------- paths ---------------------------------- */
|
|
125
|
+
|
|
126
|
+
export const backlogPaths = (teamRoot) => {
|
|
127
|
+
const root = path.join(teamRoot, BACKLOG_DIR);
|
|
128
|
+
return {
|
|
129
|
+
root,
|
|
130
|
+
items: path.join(root, ITEMS_DIR),
|
|
131
|
+
queue: path.join(root, QUEUE_DIR),
|
|
132
|
+
config: path.join(root, CONFIG_FILE),
|
|
133
|
+
lock: path.join(root, '.lock'),
|
|
134
|
+
};
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
export const itemFilePath = (teamRoot, id) => path.join(backlogPaths(teamRoot).items, `${id}.json`);
|
|
138
|
+
export const entryFilePath = (teamRoot, entryId) => path.join(backlogPaths(teamRoot).queue, `${entryId}.json`);
|
|
139
|
+
|
|
140
|
+
/** Both directories are created on first write (`mkdir -p` inside the CLI). */
|
|
141
|
+
const ensureBacklogDirs = (teamRoot) => {
|
|
142
|
+
fs.mkdirSync(backlogPaths(teamRoot).items, { recursive: true });
|
|
143
|
+
fs.mkdirSync(backlogPaths(teamRoot).queue, { recursive: true });
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
const withBacklogLock = (teamRoot, run) => {
|
|
147
|
+
fs.mkdirSync(backlogPaths(teamRoot).root, { recursive: true });
|
|
148
|
+
const lockPath = backlogPaths(teamRoot).lock;
|
|
149
|
+
let token = null;
|
|
150
|
+
try {
|
|
151
|
+
token = acquireLock(lockPath, { timeoutMs: 5000 });
|
|
152
|
+
} catch (error) {
|
|
153
|
+
teamDbFail('E_BACKLOG_BUSY', `could not take the backlog lock at ${lockPath}: ${error.message}`, 4);
|
|
154
|
+
}
|
|
155
|
+
try {
|
|
156
|
+
return run();
|
|
157
|
+
} finally {
|
|
158
|
+
releaseLock(lockPath, token);
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
/* --------------------------------- reading -------------------------------- */
|
|
163
|
+
|
|
164
|
+
export const listItemIds = (teamRoot) => {
|
|
165
|
+
const dir = backlogPaths(teamRoot).items;
|
|
166
|
+
if (!fs.existsSync(dir)) return [];
|
|
167
|
+
return fs
|
|
168
|
+
.readdirSync(dir)
|
|
169
|
+
.filter((name) => name.endsWith('.json'))
|
|
170
|
+
.map((name) => name.slice(0, -'.json'.length))
|
|
171
|
+
.sort();
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
export const listEntryIds = (teamRoot) => {
|
|
175
|
+
const dir = backlogPaths(teamRoot).queue;
|
|
176
|
+
if (!fs.existsSync(dir)) return [];
|
|
177
|
+
return fs
|
|
178
|
+
.readdirSync(dir)
|
|
179
|
+
.filter((name) => name.endsWith('.json'))
|
|
180
|
+
.map((name) => name.slice(0, -'.json'.length))
|
|
181
|
+
.sort();
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
export const readItemFile = (teamRoot, id) => {
|
|
185
|
+
try {
|
|
186
|
+
return JSON.parse(fs.readFileSync(itemFilePath(teamRoot, id), 'utf8'));
|
|
187
|
+
} catch (error) {
|
|
188
|
+
if (error.code === 'ENOENT') return null;
|
|
189
|
+
teamDbFail('E_SCHEMA', `backlog item ${id} is unreadable: ${error.message}`, 1);
|
|
190
|
+
}
|
|
191
|
+
return null;
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
const readEntryFile = (teamRoot, entryId) => {
|
|
195
|
+
try {
|
|
196
|
+
return JSON.parse(fs.readFileSync(entryFilePath(teamRoot, entryId), 'utf8'));
|
|
197
|
+
} catch (error) {
|
|
198
|
+
if (error.code === 'ENOENT') return null;
|
|
199
|
+
teamDbFail('E_SCHEMA', `queue entry ${entryId} is unreadable: ${error.message}`, 1);
|
|
200
|
+
}
|
|
201
|
+
return null;
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
const readAllItems = (teamRoot) => {
|
|
205
|
+
const items = new Map();
|
|
206
|
+
for (const id of listItemIds(teamRoot)) {
|
|
207
|
+
const item = readItemFile(teamRoot, id);
|
|
208
|
+
if (item) items.set(id, item);
|
|
209
|
+
}
|
|
210
|
+
return items;
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
const readAllEntries = (teamRoot) => {
|
|
214
|
+
const entries = new Map();
|
|
215
|
+
for (const entryId of listEntryIds(teamRoot)) {
|
|
216
|
+
const entry = readEntryFile(teamRoot, entryId);
|
|
217
|
+
if (entry) entries.set(entryId, entry);
|
|
218
|
+
}
|
|
219
|
+
return entries;
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
/** The hook-owned `state` of every `tasks/<slug>/status.json`, read once. */
|
|
223
|
+
export const readTaskStates = (teamRoot) => {
|
|
224
|
+
const states = new Map();
|
|
225
|
+
const tasksDir = path.join(teamRoot, 'tasks');
|
|
226
|
+
if (!fs.existsSync(tasksDir)) return states;
|
|
227
|
+
for (const entry of fs.readdirSync(tasksDir, { withFileTypes: true })) {
|
|
228
|
+
if (!entry.isDirectory() || !ITEM_ID_RE.test(entry.name)) continue;
|
|
229
|
+
try {
|
|
230
|
+
const status = JSON.parse(fs.readFileSync(path.join(tasksDir, entry.name, 'status.json'), 'utf8'));
|
|
231
|
+
if (isRecord(status) && typeof status.state === 'string') states.set(entry.name, status.state);
|
|
232
|
+
} catch {
|
|
233
|
+
/* no status.json or unreadable — no task state, no launch evidence */
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return states;
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
/* ------------------------------- configuration ---------------------------- */
|
|
240
|
+
|
|
241
|
+
export function validateBacklogConfig(config) {
|
|
242
|
+
if (!isRecord(config) || config.schemaVersion !== CONFIG_SCHEMA_VERSION) {
|
|
243
|
+
reject('E_SCHEMA', `backlog config.json: schemaVersion must be ${CONFIG_SCHEMA_VERSION}`, 1);
|
|
244
|
+
}
|
|
245
|
+
if (!Number.isInteger(config.maxActive) || config.maxActive < MAX_ACTIVE_MIN || config.maxActive > MAX_ACTIVE_MAX) {
|
|
246
|
+
reject('E_SCHEMA', `backlog config.json: maxActive must be an integer between ${MAX_ACTIVE_MIN} and ${MAX_ACTIVE_MAX}`, 1);
|
|
247
|
+
}
|
|
248
|
+
return config;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** Operator-edited like `scheduler/jobs.json`; absent means the default. */
|
|
252
|
+
export const readBacklogConfig = (teamRoot) => {
|
|
253
|
+
const file = backlogPaths(teamRoot).config;
|
|
254
|
+
if (!fs.existsSync(file)) return { schemaVersion: CONFIG_SCHEMA_VERSION, maxActive: DEFAULT_MAX_ACTIVE };
|
|
255
|
+
let config;
|
|
256
|
+
try {
|
|
257
|
+
config = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
258
|
+
} catch (error) {
|
|
259
|
+
teamDbFail('E_SCHEMA', `backlog config.json is not valid JSON: ${error.message}`, 1);
|
|
260
|
+
}
|
|
261
|
+
return validateBacklogConfig(config);
|
|
262
|
+
};
|
|
263
|
+
|
|
264
|
+
/* -------------------------------- validation ------------------------------ */
|
|
265
|
+
|
|
266
|
+
const validateNullableTimestamp = (item, field, value) => {
|
|
267
|
+
if (value === null) return null;
|
|
268
|
+
if (!isIsoZ(value)) reject('E_SCHEMA', `item ${item.id}: ${field} must be an RFC 3339 timestamp ending in Z`);
|
|
269
|
+
return value;
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Schema phase: field shapes and bounds only. Validation order is schema →
|
|
274
|
+
* identity → graph; the first failure wins (the frozen outcome table).
|
|
275
|
+
*/
|
|
276
|
+
export function validateItemSchema(item) {
|
|
277
|
+
if (!isRecord(item)) reject('E_SCHEMA', 'backlog item must be an object');
|
|
278
|
+
if (item.schemaVersion !== ITEM_SCHEMA_VERSION) {
|
|
279
|
+
reject('E_SCHEMA', `item ${item.id ?? '?'}: schemaVersion must be ${ITEM_SCHEMA_VERSION}`);
|
|
280
|
+
}
|
|
281
|
+
const id = item.id;
|
|
282
|
+
if (typeof id !== 'string' || !ITEM_ID_RE.test(id) || id.length < 3 || id.length > 64) {
|
|
283
|
+
reject('E_SCHEMA', `item id must match ${ITEM_ID_RE.source} with 3-64 characters`);
|
|
284
|
+
}
|
|
285
|
+
if (!Number.isInteger(item.revision) || item.revision < 1) {
|
|
286
|
+
reject('E_SCHEMA', `item ${id}: revision must be an integer >= 1`);
|
|
287
|
+
}
|
|
288
|
+
if (
|
|
289
|
+
typeof item.title !== 'string' ||
|
|
290
|
+
item.title !== item.title.trim() ||
|
|
291
|
+
item.title.length < 1 ||
|
|
292
|
+
item.title.length > MAX_TITLE_CHARS ||
|
|
293
|
+
item.title.includes('\n')
|
|
294
|
+
) {
|
|
295
|
+
reject('E_SCHEMA', `item ${id}: title must be trimmed, one line, 1-${MAX_TITLE_CHARS} characters`);
|
|
296
|
+
}
|
|
297
|
+
if (!ITEM_STATUSES.includes(item.status)) {
|
|
298
|
+
reject('E_SCHEMA', `item ${id}: status must be one of ${ITEM_STATUSES.join('|')}`);
|
|
299
|
+
}
|
|
300
|
+
if (!isIsoZ(item.createdAt)) reject('E_SCHEMA', `item ${id}: createdAt must be an RFC 3339 timestamp ending in Z`);
|
|
301
|
+
if (Date.parse(item.createdAt) > Date.now() + FUTURE_CREATED_AT_SKEW_MS) {
|
|
302
|
+
reject('E_SCHEMA', `item ${id}: createdAt is in the future`);
|
|
303
|
+
}
|
|
304
|
+
if (!isIsoZ(item.updatedAt)) reject('E_SCHEMA', `item ${id}: updatedAt must be an RFC 3339 timestamp ending in Z`);
|
|
305
|
+
if (Date.parse(item.updatedAt) < Date.parse(item.createdAt)) {
|
|
306
|
+
reject('E_SCHEMA', `item ${id}: updatedAt must be >= createdAt`);
|
|
307
|
+
}
|
|
308
|
+
item.completedAt = validateNullableTimestamp(item, 'completedAt', item.completedAt);
|
|
309
|
+
item.cancelledAt = validateNullableTimestamp(item, 'cancelledAt', item.cancelledAt);
|
|
310
|
+
if (item.status === 'completed' && item.completedAt === null) {
|
|
311
|
+
reject('E_SCHEMA', `item ${id}: completedAt is required when status is completed`);
|
|
312
|
+
}
|
|
313
|
+
if (item.status === 'cancelled' && item.cancelledAt === null) {
|
|
314
|
+
reject('E_SCHEMA', `item ${id}: cancelledAt is required when status is cancelled`);
|
|
315
|
+
}
|
|
316
|
+
if (item.cancelReason !== null && !(typeof item.cancelReason === 'string' && item.cancelReason.length >= 1 && item.cancelReason.length <= MAX_CANCEL_REASON_CHARS)) {
|
|
317
|
+
reject('E_SCHEMA', `item ${id}: cancelReason must be 1-${MAX_CANCEL_REASON_CHARS} characters`);
|
|
318
|
+
}
|
|
319
|
+
if (item.supersededBy !== null && !(typeof item.supersededBy === 'string' && ITEM_ID_RE.test(item.supersededBy))) {
|
|
320
|
+
reject('E_SCHEMA', `item ${id}: supersededBy must match ${ITEM_ID_RE.source}`);
|
|
321
|
+
}
|
|
322
|
+
if (item.status === 'superseded' && item.supersededBy === null) {
|
|
323
|
+
reject('E_SCHEMA', `item ${id}: supersededBy is required when status is superseded`);
|
|
324
|
+
}
|
|
325
|
+
if (!Array.isArray(item.dependsOn) || item.dependsOn.length > MAX_DEPENDENCIES) {
|
|
326
|
+
reject('E_SCHEMA', `item ${id}: dependsOn must be an array of at most ${MAX_DEPENDENCIES} ids`);
|
|
327
|
+
}
|
|
328
|
+
if (new Set(item.dependsOn).size !== item.dependsOn.length) {
|
|
329
|
+
reject('E_SCHEMA', `item ${id}: dependsOn must not contain duplicates`);
|
|
330
|
+
}
|
|
331
|
+
for (const dep of item.dependsOn) {
|
|
332
|
+
if (typeof dep !== 'string' || !ITEM_ID_RE.test(dep)) {
|
|
333
|
+
reject('E_SCHEMA', `item ${id}: dependency "${String(dep)}" must match ${ITEM_ID_RE.source}`);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
if (!Number.isInteger(item.priority) || item.priority < 0 || item.priority > 9) {
|
|
337
|
+
reject('E_SCHEMA', `item ${id}: priority must be an integer between 0 and 9`);
|
|
338
|
+
}
|
|
339
|
+
if (item.sourceTask !== null && !(typeof item.sourceTask === 'string' && ITEM_ID_RE.test(item.sourceTask))) {
|
|
340
|
+
reject('E_SCHEMA', `item ${id}: sourceTask must match ${ITEM_ID_RE.source}`);
|
|
341
|
+
}
|
|
342
|
+
if (!Array.isArray(item.sourceRefs) || item.sourceRefs.length > MAX_SOURCE_REFS) {
|
|
343
|
+
reject('E_SCHEMA', `item ${id}: sourceRefs must be an array of at most ${MAX_SOURCE_REFS} refs`);
|
|
344
|
+
}
|
|
345
|
+
for (const ref of item.sourceRefs) {
|
|
346
|
+
if (!(typeof ref === 'string' && ref.length >= 1 && ref.length <= MAX_SOURCE_REF_CHARS)) {
|
|
347
|
+
reject('E_SCHEMA', `item ${id}: every sourceRef must be 1-${MAX_SOURCE_REF_CHARS} characters`);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
if (!ITEM_TYPES.includes(item.type)) {
|
|
351
|
+
reject('E_SCHEMA', `item ${id}: type must be one of ${ITEM_TYPES.join('|')}`);
|
|
352
|
+
}
|
|
353
|
+
if (item.description !== null && !(typeof item.description === 'string' && item.description.length <= MAX_DESCRIPTION_CHARS)) {
|
|
354
|
+
reject('E_SCHEMA', `item ${id}: description must be at most ${MAX_DESCRIPTION_CHARS} characters`);
|
|
355
|
+
}
|
|
356
|
+
if (!Array.isArray(item.labels) || item.labels.length > MAX_LABELS) {
|
|
357
|
+
reject('E_SCHEMA', `item ${id}: labels must be an array of at most ${MAX_LABELS} labels`);
|
|
358
|
+
}
|
|
359
|
+
for (const label of item.labels) {
|
|
360
|
+
if (!(typeof label === 'string' && label.length >= 1 && label.length <= MAX_LABEL_CHARS)) {
|
|
361
|
+
reject('E_SCHEMA', `item ${id}: every label must be 1-${MAX_LABEL_CHARS} characters`);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
if (!Array.isArray(item.history) || item.history.length > MAX_ITEM_HISTORY) {
|
|
365
|
+
reject('E_SCHEMA', `item ${id}: history must be an array capped at ${MAX_ITEM_HISTORY}`);
|
|
366
|
+
}
|
|
367
|
+
for (const event of item.history) {
|
|
368
|
+
validateHistoryEvent(`item ${id}`, event, ITEM_HISTORY_TYPES);
|
|
369
|
+
}
|
|
370
|
+
return item;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
const validateHistoryEvent = (where, event, types) => {
|
|
374
|
+
if (!isRecord(event) || !isIsoZ(event.at)) reject('E_SCHEMA', `${where}: every history event needs an RFC 3339 "at"`);
|
|
375
|
+
if (!types.has(event.type)) reject('E_SCHEMA', `${where}: history event type "${String(event.type)}" is unknown`);
|
|
376
|
+
if (typeof event.actor !== 'string') reject('E_SCHEMA', `${where}: every history event needs an "actor"`);
|
|
377
|
+
if (event.detail !== null && typeof event.detail !== 'string') {
|
|
378
|
+
reject('E_SCHEMA', `${where}: history "detail" must be a string or null`);
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
|
|
382
|
+
/** Identity phase: the file stem is the id (one file per id, D-2). */
|
|
383
|
+
export function validateItemIdentity(item, fileStem) {
|
|
384
|
+
if (item.id !== fileStem) {
|
|
385
|
+
reject('E_BACKLOG_DUPLICATE_ID', `item file "${fileStem}.json" holds id "${item.id}"`);
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
const detectsCycleThrough = (startId, itemsById) => {
|
|
390
|
+
const seen = new Set();
|
|
391
|
+
const stack = [startId];
|
|
392
|
+
while (stack.length > 0) {
|
|
393
|
+
const current = stack.pop();
|
|
394
|
+
if (seen.has(current)) continue;
|
|
395
|
+
seen.add(current);
|
|
396
|
+
for (const dep of itemsById.get(current)?.dependsOn ?? []) {
|
|
397
|
+
if (dep === startId) return true;
|
|
398
|
+
if (!seen.has(dep)) stack.push(dep);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
return false;
|
|
402
|
+
};
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* Graph phase: dependencies must exist, must not name the item itself, and the
|
|
406
|
+
* graph must stay acyclic (including 2-cycles). `supersededBy` must name an
|
|
407
|
+
* existing item. Broken files are a recorded error, never a cascade (D-3).
|
|
408
|
+
*/
|
|
409
|
+
export function validateItemGraph(item, itemsById) {
|
|
410
|
+
// The prospective record's own edges are part of the graph under test.
|
|
411
|
+
const merged = new Map(itemsById);
|
|
412
|
+
merged.set(item.id, item);
|
|
413
|
+
for (const dep of item.dependsOn ?? []) {
|
|
414
|
+
if (dep === item.id) reject('E_BACKLOG_SELF_DEP', `item ${item.id}: dependsOn contains itself`);
|
|
415
|
+
if (!merged.has(dep)) reject('E_BACKLOG_UNKNOWN_DEP', `item ${item.id}: dependency "${dep}" has no item file`);
|
|
416
|
+
}
|
|
417
|
+
if (item.supersededBy !== null && !merged.has(item.supersededBy)) {
|
|
418
|
+
reject('E_BACKLOG_UNKNOWN_DEP', `item ${item.id}: supersededBy "${item.supersededBy}" has no item file`);
|
|
419
|
+
}
|
|
420
|
+
if (detectsCycleThrough(item.id, merged)) {
|
|
421
|
+
reject('E_BACKLOG_CYCLE', `item ${item.id}: dependsOn contains a cycle`);
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* The stored lattice: planned → completed (reopen back to planned), planned →
|
|
427
|
+
* cancelled, planned → superseded. Terminal statuses never leave. A cancelled
|
|
428
|
+
* item needs its `cancelReason` (the frozen outcome table folds this into
|
|
429
|
+
* `E_BACKLOG_TRANSITION`).
|
|
430
|
+
*/
|
|
431
|
+
export function validateTransition(existing, next) {
|
|
432
|
+
const from = existing?.status ?? null;
|
|
433
|
+
const to = next.status;
|
|
434
|
+
const needsReason = () => {
|
|
435
|
+
if (to === 'cancelled' && !(typeof next.cancelReason === 'string' && next.cancelReason.length >= 1)) {
|
|
436
|
+
reject('E_BACKLOG_TRANSITION', `item ${next.id}: a cancelled item needs cancelReason`);
|
|
437
|
+
}
|
|
438
|
+
};
|
|
439
|
+
if (from === null) {
|
|
440
|
+
needsReason();
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
if (to === from) {
|
|
444
|
+
needsReason();
|
|
445
|
+
return;
|
|
446
|
+
}
|
|
447
|
+
const legal = {
|
|
448
|
+
planned: new Set(['planned', 'completed', 'cancelled', 'superseded']),
|
|
449
|
+
completed: new Set(['planned']),
|
|
450
|
+
cancelled: new Set(),
|
|
451
|
+
superseded: new Set(),
|
|
452
|
+
};
|
|
453
|
+
if (!legal[from]?.has(to)) {
|
|
454
|
+
reject('E_BACKLOG_TRANSITION', `item ${next.id}: transition ${from} -> ${to} is outside the stored lattice`);
|
|
455
|
+
}
|
|
456
|
+
needsReason();
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/* ------------------------------- queue schema ----------------------------- */
|
|
460
|
+
|
|
461
|
+
export function validateEntrySchema(entry) {
|
|
462
|
+
if (!isRecord(entry)) reject('E_SCHEMA', 'queue entry must be an object');
|
|
463
|
+
if (entry.schemaVersion !== ENTRY_SCHEMA_VERSION) {
|
|
464
|
+
reject('E_SCHEMA', `entry ${entry.entryId ?? '?'}: schemaVersion must be ${ENTRY_SCHEMA_VERSION}`);
|
|
465
|
+
}
|
|
466
|
+
if (typeof entry.entryId !== 'string' || !ENTRY_ID_RE.test(entry.entryId)) {
|
|
467
|
+
reject('E_SCHEMA', `entry id must match ${ENTRY_ID_RE.source}`);
|
|
468
|
+
}
|
|
469
|
+
if (typeof entry.itemId !== 'string' || !ITEM_ID_RE.test(entry.itemId)) {
|
|
470
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: itemId must match ${ITEM_ID_RE.source}`);
|
|
471
|
+
}
|
|
472
|
+
if (!ENTRY_STATUSES.includes(entry.status)) {
|
|
473
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: status must be one of ${ENTRY_STATUSES.join('|')}`);
|
|
474
|
+
}
|
|
475
|
+
if (!(typeof entry.reason === 'string' && entry.reason.length >= 1 && entry.reason.length <= MAX_REASON_CHARS)) {
|
|
476
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: reason must be 1-${MAX_REASON_CHARS} characters`);
|
|
477
|
+
}
|
|
478
|
+
if (!(typeof entry.requestedBy === 'string' && entry.requestedBy.length >= 1 && entry.requestedBy.length <= MAX_REQUESTED_BY_CHARS)) {
|
|
479
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: requestedBy must be 1-${MAX_REQUESTED_BY_CHARS} characters`);
|
|
480
|
+
}
|
|
481
|
+
if (entry.command !== null && !(typeof entry.command === 'string' && entry.command.length >= 1 && entry.command.length <= MAX_COMMAND_CHARS)) {
|
|
482
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: command must be null or 1-${MAX_COMMAND_CHARS} characters`);
|
|
483
|
+
}
|
|
484
|
+
if (!Number.isInteger(entry.revision) || entry.revision < 1) {
|
|
485
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: revision must be an integer >= 1`);
|
|
486
|
+
}
|
|
487
|
+
if (!isIsoZ(entry.requestedAt)) reject('E_SCHEMA', `entry ${entry.entryId}: requestedAt must be an RFC 3339 timestamp ending in Z`);
|
|
488
|
+
if (entry.claimedAt !== null && !isIsoZ(entry.claimedAt)) {
|
|
489
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: claimedAt must be null or an RFC 3339 timestamp`);
|
|
490
|
+
}
|
|
491
|
+
if (entry.status === 'claimed' && entry.claimedAt === null) {
|
|
492
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: claimedAt is required when status is claimed`);
|
|
493
|
+
}
|
|
494
|
+
if (entry.finishedAt !== null && !isIsoZ(entry.finishedAt)) {
|
|
495
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: finishedAt must be null or an RFC 3339 timestamp`);
|
|
496
|
+
}
|
|
497
|
+
if ((entry.status === 'cancelled' || entry.status === 'expired') && entry.finishedAt === null) {
|
|
498
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: finishedAt is required when status is ${entry.status}`);
|
|
499
|
+
}
|
|
500
|
+
if (!Array.isArray(entry.history) || entry.history.length > MAX_ENTRY_HISTORY) {
|
|
501
|
+
reject('E_SCHEMA', `entry ${entry.entryId}: history must be an array capped at ${MAX_ENTRY_HISTORY}`);
|
|
502
|
+
}
|
|
503
|
+
for (const event of entry.history) {
|
|
504
|
+
validateHistoryEvent(`entry ${entry.entryId}`, event, ENTRY_HISTORY_TYPES);
|
|
505
|
+
}
|
|
506
|
+
return entry;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/* ------------------------------ file writes ------------------------------- */
|
|
510
|
+
|
|
511
|
+
const writeAtomic = (file, content) => {
|
|
512
|
+
const tmp = `${file}.tmp`;
|
|
513
|
+
fs.writeFileSync(tmp, content, { encoding: 'utf8', mode: 0o600 });
|
|
514
|
+
fs.renameSync(tmp, file);
|
|
515
|
+
};
|
|
516
|
+
|
|
517
|
+
const writeItemFile = (teamRoot, item) => {
|
|
518
|
+
ensureBacklogDirs(teamRoot);
|
|
519
|
+
writeAtomic(itemFilePath(teamRoot, item.id), `${JSON.stringify(item, null, 2)}\n`);
|
|
520
|
+
};
|
|
521
|
+
|
|
522
|
+
const writeEntryFile = (teamRoot, entry) => {
|
|
523
|
+
ensureBacklogDirs(teamRoot);
|
|
524
|
+
writeAtomic(entryFilePath(teamRoot, entry.entryId), `${JSON.stringify(entry, null, 2)}\n`);
|
|
525
|
+
};
|
|
526
|
+
|
|
527
|
+
/** The scheduler's `newRunId` shape — duplicated so the queue stays file-only. */
|
|
528
|
+
export const newEntryId = () => {
|
|
529
|
+
const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}Z$/, 'Z');
|
|
530
|
+
return `${stamp}-${crypto.randomBytes(4).toString('hex')}`;
|
|
531
|
+
};
|
|
532
|
+
|
|
533
|
+
/* ---------------------------- derived statuses ---------------------------- */
|
|
534
|
+
|
|
535
|
+
/** The stored decision lattice plus the derived operational status (I-3). */
|
|
536
|
+
export const effectiveItemStatus = (item, taskState, nonTerminalEntryExists) => {
|
|
537
|
+
if (item.status === 'cancelled') return 'cancelled';
|
|
538
|
+
if (item.status === 'superseded') return 'superseded';
|
|
539
|
+
if (item.status === 'completed' || taskState === 'completed') return 'completed';
|
|
540
|
+
if (taskState !== null) return 'launched';
|
|
541
|
+
if (nonTerminalEntryExists) return 'queued';
|
|
542
|
+
return 'planned';
|
|
543
|
+
};
|
|
544
|
+
|
|
545
|
+
export const effectiveEntryStatus = (entry, taskState) => {
|
|
546
|
+
if (entry.status === 'cancelled') return 'cancelled';
|
|
547
|
+
if (entry.status === 'expired') return 'expired';
|
|
548
|
+
if (taskState === 'completed') return 'done';
|
|
549
|
+
if (taskState !== null) return 'active';
|
|
550
|
+
if (entry.status === 'claimed') return 'claimed';
|
|
551
|
+
return 'queued';
|
|
552
|
+
};
|
|
553
|
+
|
|
554
|
+
const isNonTerminalEntryStatus = (status) => !['cancelled', 'expired', 'done'].includes(status);
|
|
555
|
+
|
|
556
|
+
/* ------------------------------- ordering --------------------------------- */
|
|
557
|
+
|
|
558
|
+
/** The total order comparator: `priority ASC → createdAt ASC → id ASC` (R-3). */
|
|
559
|
+
export const rankCompare = (left, right) =>
|
|
560
|
+
left.priority - right.priority ||
|
|
561
|
+
(left.createdAt < right.createdAt ? -1 : left.createdAt > right.createdAt ? 1 : 0) ||
|
|
562
|
+
(left.id < right.id ? -1 : left.id > right.id ? 1 : 0);
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* One snapshot, one pass (D-4, R-1…R-6). Feed this the item, queue and task
|
|
566
|
+
* records the caller read once — files on the CLI path, projected rows on the
|
|
567
|
+
* API path — so the CLI and the SQL read plane can never disagree. No wall
|
|
568
|
+
* clock, readdir order or database row order may influence the output.
|
|
569
|
+
*/
|
|
570
|
+
export function deriveBacklogOrdering({ items, entries, taskStates, asOf }) {
|
|
571
|
+
const byId = new Map();
|
|
572
|
+
const entryStatuses = new Map();
|
|
573
|
+
for (const [entryId, entry] of entries) {
|
|
574
|
+
entryStatuses.set(entryId, effectiveEntryStatus(entry, taskStates.get(entry.itemId) ?? null));
|
|
575
|
+
}
|
|
576
|
+
const openEntriesByItem = new Map();
|
|
577
|
+
for (const [entryId, entry] of entries) {
|
|
578
|
+
const status = entryStatuses.get(entryId);
|
|
579
|
+
if (!isNonTerminalEntryStatus(status)) continue;
|
|
580
|
+
const list = openEntriesByItem.get(entry.itemId) ?? [];
|
|
581
|
+
list.push(entryId);
|
|
582
|
+
openEntriesByItem.set(entry.itemId, list);
|
|
583
|
+
}
|
|
584
|
+
for (const [id, item] of items) {
|
|
585
|
+
const taskState = taskStates.get(id) ?? null;
|
|
586
|
+
const openEntries = openEntriesByItem.get(id) ?? [];
|
|
587
|
+
const openEntryId = openEntries.length > 0 ? openEntries.sort()[0] : null;
|
|
588
|
+
const openEntry = openEntryId !== null ? entries.get(openEntryId) : null;
|
|
589
|
+
const effectiveStatus = effectiveItemStatus(item, taskState, openEntryId !== null);
|
|
590
|
+
byId.set(id, {
|
|
591
|
+
item,
|
|
592
|
+
effectiveStatus,
|
|
593
|
+
taskState,
|
|
594
|
+
openEntry,
|
|
595
|
+
queueEntryId: openEntryId,
|
|
596
|
+
queuedAt: openEntry?.requestedAt ?? null,
|
|
597
|
+
ready: false,
|
|
598
|
+
blocked: false,
|
|
599
|
+
waitingOn: [],
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
for (const [id, annotated] of byId) {
|
|
603
|
+
const unsatisfied = (annotated.item.dependsOn ?? []).filter((dep) => {
|
|
604
|
+
const depAnnotated = byId.get(dep);
|
|
605
|
+
return !depAnnotated || depAnnotated.effectiveStatus !== 'completed';
|
|
606
|
+
});
|
|
607
|
+
unsatisfied.sort((a, b) => rankCompare(byId.get(a).item, byId.get(b).item));
|
|
608
|
+
annotated.waitingOn = unsatisfied;
|
|
609
|
+
annotated.blocked = unsatisfied.length > 0;
|
|
610
|
+
// An enqueued item keeps its operational launchability: effective status
|
|
611
|
+
// `queued` is the planned state plus a recorded request, and reading it as
|
|
612
|
+
// "not ready" would empty the drain order for every input (D-5 requires
|
|
613
|
+
// the entry to "become claimable when the graph allows it").
|
|
614
|
+
annotated.ready = ['planned', 'queued'].includes(annotated.effectiveStatus) && !annotated.blocked;
|
|
615
|
+
}
|
|
616
|
+
const rankedItems = [...byId.values()].sort((a, b) => rankCompare(a.item, b.item));
|
|
617
|
+
const readyIds = rankedItems.filter((annotated) => annotated.ready).map((annotated) => annotated.item.id);
|
|
618
|
+
const drainOrderEntryIds = [...entries.values()]
|
|
619
|
+
.filter((entry) => {
|
|
620
|
+
if (entryStatuses.get(entry.entryId) !== 'queued') return false;
|
|
621
|
+
const annotated = byId.get(entry.itemId);
|
|
622
|
+
return annotated !== undefined && annotated.ready;
|
|
623
|
+
})
|
|
624
|
+
.sort((a, b) => rankCompare(byId.get(a.itemId).item, byId.get(b.itemId).item))
|
|
625
|
+
.map((entry) => entry.entryId);
|
|
626
|
+
return {
|
|
627
|
+
asOf,
|
|
628
|
+
byId,
|
|
629
|
+
readyIds,
|
|
630
|
+
drainOrderEntryIds,
|
|
631
|
+
criticalPathIds: computeCriticalPathIds(items, byId),
|
|
632
|
+
};
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
/** Longest chain of open items in item count; ties by the rank of the chain's first item. */
|
|
636
|
+
const computeCriticalPathIds = (items, byId) => {
|
|
637
|
+
const openIds = new Set(
|
|
638
|
+
[...byId.values()]
|
|
639
|
+
.filter((annotated) => ['planned', 'queued', 'launched'].includes(annotated.effectiveStatus))
|
|
640
|
+
.map((annotated) => annotated.item.id),
|
|
641
|
+
);
|
|
642
|
+
const memo = new Map();
|
|
643
|
+
const chainBetter = (a, b) => {
|
|
644
|
+
if (b.length === 0) return true;
|
|
645
|
+
if (a.length !== b.length) return a.length > b.length;
|
|
646
|
+
return rankCompare(items.get(a[0]), items.get(b[0])) < 0;
|
|
647
|
+
};
|
|
648
|
+
const longest = (id) => {
|
|
649
|
+
if (memo.has(id)) return memo.get(id);
|
|
650
|
+
const deps = (items.get(id)?.dependsOn ?? []).filter((dep) => openIds.has(dep));
|
|
651
|
+
let best = [id];
|
|
652
|
+
for (const dep of deps) {
|
|
653
|
+
const candidate = [id, ...longest(dep)];
|
|
654
|
+
if (chainBetter(candidate, best)) best = candidate;
|
|
655
|
+
}
|
|
656
|
+
memo.set(id, best);
|
|
657
|
+
return best;
|
|
658
|
+
};
|
|
659
|
+
let best = [];
|
|
660
|
+
for (const id of openIds) {
|
|
661
|
+
const candidate = longest(id);
|
|
662
|
+
if (chainBetter(candidate, best)) best = candidate;
|
|
663
|
+
}
|
|
664
|
+
return best;
|
|
665
|
+
};
|
|
666
|
+
|
|
667
|
+
/** Read the whole backlog tree once, under the tree lock (R-4). */
|
|
668
|
+
export function readBacklogSnapshot(teamRoot) {
|
|
669
|
+
return withBacklogLock(teamRoot, () => {
|
|
670
|
+
const asOf = nowIso();
|
|
671
|
+
const items = new Map();
|
|
672
|
+
const entries = new Map();
|
|
673
|
+
const errors = [];
|
|
674
|
+
for (const id of listItemIds(teamRoot)) {
|
|
675
|
+
try {
|
|
676
|
+
items.set(id, JSON.parse(fs.readFileSync(itemFilePath(teamRoot, id), 'utf8')));
|
|
677
|
+
} catch (error) {
|
|
678
|
+
errors.push({ path: `backlog/items/${id}.json`, reason: error.message });
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
for (const entryId of listEntryIds(teamRoot)) {
|
|
682
|
+
try {
|
|
683
|
+
entries.set(entryId, JSON.parse(fs.readFileSync(entryFilePath(teamRoot, entryId), 'utf8')));
|
|
684
|
+
} catch (error) {
|
|
685
|
+
errors.push({ path: `backlog/queue/${entryId}.json`, reason: error.message });
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
return { asOf, items, entries, taskStates: readTaskStates(teamRoot), errors };
|
|
689
|
+
});
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
export const countActiveTasks = (taskStates) => {
|
|
693
|
+
let count = 0;
|
|
694
|
+
for (const state of taskStates.values()) {
|
|
695
|
+
if (HOLDING_TASK_STATES.has(state)) count += 1;
|
|
696
|
+
}
|
|
697
|
+
return count;
|
|
698
|
+
};
|
|
699
|
+
|
|
700
|
+
/* ------------------------------- item writes ------------------------------ */
|
|
701
|
+
|
|
702
|
+
export function addBacklogItem(teamRoot, payload, options = {}) {
|
|
703
|
+
if (!isRecord(payload)) reject('E_SCHEMA', 'backlog add payload must be an object');
|
|
704
|
+
return withBacklogLock(teamRoot, () => {
|
|
705
|
+
const items = readAllItems(teamRoot);
|
|
706
|
+
const id = payload.id;
|
|
707
|
+
if (typeof id !== 'string' || !ITEM_ID_RE.test(id) || id.length < 3 || id.length > 64) {
|
|
708
|
+
reject('E_SCHEMA', `item id must match ${ITEM_ID_RE.source} with 3-64 characters`);
|
|
709
|
+
}
|
|
710
|
+
if (items.has(id)) reject('E_BACKLOG_DUPLICATE_ID', `item "${id}" already exists`);
|
|
711
|
+
// D-2: the id becomes the `/task` slug; an id that already names a task
|
|
712
|
+
// folder this item did not create is a collision.
|
|
713
|
+
if (fs.existsSync(path.join(teamRoot, 'tasks', id))) {
|
|
714
|
+
reject('E_ID_COLLISION', `id "${id}" already names a tasks/${id}/ directory`);
|
|
715
|
+
}
|
|
716
|
+
const now = nowIso();
|
|
717
|
+
const createdAt = payload.createdAt ?? now;
|
|
718
|
+
const item = {
|
|
719
|
+
schemaVersion: ITEM_SCHEMA_VERSION,
|
|
720
|
+
id,
|
|
721
|
+
revision: 1,
|
|
722
|
+
title: typeof payload.title === 'string' ? payload.title.trim() : payload.title,
|
|
723
|
+
status: payload.status ?? 'planned',
|
|
724
|
+
priority: payload.priority ?? 5,
|
|
725
|
+
sourceTask: payload.sourceTask ?? null,
|
|
726
|
+
sourceRefs: payload.sourceRefs ?? [],
|
|
727
|
+
createdAt,
|
|
728
|
+
updatedAt: now,
|
|
729
|
+
completedAt: payload.completedAt ?? null,
|
|
730
|
+
cancelledAt: payload.cancelledAt ?? null,
|
|
731
|
+
cancelReason: payload.cancelReason ?? null,
|
|
732
|
+
supersededBy: payload.supersededBy ?? null,
|
|
733
|
+
type: payload.type ?? 'feature',
|
|
734
|
+
description: payload.description ?? null,
|
|
735
|
+
labels: payload.labels ?? [],
|
|
736
|
+
dependsOn: payload.dependsOn ?? [],
|
|
737
|
+
history: [{ at: now, type: 'created', actor: options.actor ?? 'operator', detail: null }],
|
|
738
|
+
};
|
|
739
|
+
validateItemSchema(item);
|
|
740
|
+
validateItemIdentity(item, id);
|
|
741
|
+
validateItemGraph(item, items);
|
|
742
|
+
validateTransition(null, item);
|
|
743
|
+
writeItemFile(teamRoot, item);
|
|
744
|
+
return item;
|
|
745
|
+
});
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
export function setBacklogItem(teamRoot, id, payload, options = {}) {
|
|
749
|
+
if (!isRecord(payload)) reject('E_SCHEMA', 'backlog set payload must be an object');
|
|
750
|
+
return withBacklogLock(teamRoot, () => {
|
|
751
|
+
const existing = readItemFile(teamRoot, id);
|
|
752
|
+
if (!existing) reject('E_BACKLOG_UNKNOWN_DEP', `no backlog item "${id}"`);
|
|
753
|
+
if (!Number.isInteger(payload.revision) || payload.revision !== existing.revision) {
|
|
754
|
+
reject('E_BACKLOG_REVISION', `item ${id}: revision ${payload.revision ?? 'missing'} does not match the stored ${existing.revision}`);
|
|
755
|
+
}
|
|
756
|
+
const next = { ...existing };
|
|
757
|
+
for (const key of ['title', 'status', 'priority', 'dependsOn', 'type', 'description', 'labels', 'completedAt', 'cancelledAt', 'cancelReason', 'supersededBy']) {
|
|
758
|
+
if (payload[key] !== undefined) next[key] = payload[key];
|
|
759
|
+
}
|
|
760
|
+
if (payload.title !== undefined) next.title = typeof next.title === 'string' ? next.title.trim() : next.title;
|
|
761
|
+
const now = nowIso();
|
|
762
|
+
next.revision = existing.revision + 1;
|
|
763
|
+
next.updatedAt = now;
|
|
764
|
+
validateItemSchema(next);
|
|
765
|
+
validateItemIdentity(next, id);
|
|
766
|
+
validateItemGraph(next, readAllItems(teamRoot));
|
|
767
|
+
validateTransition(existing, next);
|
|
768
|
+
const actor = options.actor ?? 'operator';
|
|
769
|
+
let type = 'updated';
|
|
770
|
+
if (next.status !== existing.status) {
|
|
771
|
+
if (next.status === 'completed') type = 'completed';
|
|
772
|
+
else if (next.status === 'cancelled') type = 'cancelled';
|
|
773
|
+
else if (next.status === 'superseded') type = 'superseded';
|
|
774
|
+
else if (next.status === 'planned' && existing.status === 'completed') type = 'reopened';
|
|
775
|
+
else type = 'status-changed';
|
|
776
|
+
} else if (next.priority !== existing.priority) {
|
|
777
|
+
type = 'priority-changed';
|
|
778
|
+
} else if (canonicalJson(next.dependsOn) !== canonicalJson(existing.dependsOn)) {
|
|
779
|
+
type = 'deps-changed';
|
|
780
|
+
}
|
|
781
|
+
next.history = capHistory([...(existing.history ?? []), { at: now, type, actor, detail: null }], MAX_ITEM_HISTORY);
|
|
782
|
+
if (next.status === 'cancelled' || next.status === 'superseded') {
|
|
783
|
+
expireEntriesForItem(teamRoot, id, next.status === 'cancelled' ? 'item-cancelled' : 'item-superseded', actor);
|
|
784
|
+
}
|
|
785
|
+
writeItemFile(teamRoot, next);
|
|
786
|
+
return next;
|
|
787
|
+
});
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
/* ------------------------------ launch queue ------------------------------ */
|
|
791
|
+
|
|
792
|
+
const expireEntriesForItem = (teamRoot, itemId, detail, actor) => {
|
|
793
|
+
const at = nowIso();
|
|
794
|
+
for (const [entryId, entry] of readAllEntries(teamRoot)) {
|
|
795
|
+
if (entry.itemId !== itemId) continue;
|
|
796
|
+
if (entry.status === 'cancelled' || entry.status === 'expired') continue;
|
|
797
|
+
const next = {
|
|
798
|
+
...entry,
|
|
799
|
+
status: 'expired',
|
|
800
|
+
claimedAt: entry.status === 'claimed' ? entry.claimedAt : null,
|
|
801
|
+
finishedAt: at,
|
|
802
|
+
revision: entry.revision + 1,
|
|
803
|
+
history: capHistory([...(entry.history ?? []), { at, type: 'expired', actor, detail }], MAX_ENTRY_HISTORY),
|
|
804
|
+
};
|
|
805
|
+
validateEntrySchema(next);
|
|
806
|
+
writeEntryFile(teamRoot, next);
|
|
807
|
+
}
|
|
808
|
+
};
|
|
809
|
+
|
|
810
|
+
export function enqueueBacklogItem(teamRoot, payload, options = {}) {
|
|
811
|
+
if (!isRecord(payload)) reject('E_SCHEMA', 'backlog enqueue payload must be an object');
|
|
812
|
+
return withBacklogLock(teamRoot, () => {
|
|
813
|
+
const itemId = payload.itemId;
|
|
814
|
+
if (typeof itemId !== 'string' || !ITEM_ID_RE.test(itemId)) {
|
|
815
|
+
reject('E_SCHEMA', 'itemId must match the slug grammar');
|
|
816
|
+
}
|
|
817
|
+
const item = readItemFile(teamRoot, itemId);
|
|
818
|
+
if (!item) reject('E_BACKLOG_UNKNOWN_DEP', `no backlog item "${itemId}"`);
|
|
819
|
+
const taskStates = readTaskStates(teamRoot);
|
|
820
|
+
const entries = readAllEntries(teamRoot);
|
|
821
|
+
const openEntry = [...entries.values()].find((entry) => {
|
|
822
|
+
if (entry.itemId !== itemId) return false;
|
|
823
|
+
return isNonTerminalEntryStatus(effectiveEntryStatus(entry, taskStates.get(itemId) ?? null));
|
|
824
|
+
});
|
|
825
|
+
const effective = effectiveItemStatus(item, taskStates.get(itemId) ?? null, openEntry !== undefined);
|
|
826
|
+
if (['completed', 'cancelled', 'superseded'].includes(effective)) {
|
|
827
|
+
reject('E_BACKLOG_TRANSITION', `item ${itemId} is ${effective}; enqueue is refused`);
|
|
828
|
+
}
|
|
829
|
+
const actor = options.actor ?? 'operator';
|
|
830
|
+
if (openEntry) {
|
|
831
|
+
// R3-5: a duplicate enqueue appends the new reason to the history
|
|
832
|
+
// instead of dropping it; enqueue stays idempotent per item.
|
|
833
|
+
const reason = typeof payload.reason === 'string' && payload.reason.length >= 1 ? payload.reason : openEntry.reason;
|
|
834
|
+
const next = {
|
|
835
|
+
...openEntry,
|
|
836
|
+
revision: openEntry.revision + 1,
|
|
837
|
+
history: capHistory(
|
|
838
|
+
[...(openEntry.history ?? []), { at: nowIso(), type: 'enqueued', actor, detail: reason }],
|
|
839
|
+
MAX_ENTRY_HISTORY,
|
|
840
|
+
),
|
|
841
|
+
};
|
|
842
|
+
validateEntrySchema(next);
|
|
843
|
+
writeEntryFile(teamRoot, next);
|
|
844
|
+
return { entry: next, existing: true };
|
|
845
|
+
}
|
|
846
|
+
const now = nowIso();
|
|
847
|
+
const entry = {
|
|
848
|
+
schemaVersion: ENTRY_SCHEMA_VERSION,
|
|
849
|
+
entryId: newEntryId(),
|
|
850
|
+
itemId,
|
|
851
|
+
status: 'queued',
|
|
852
|
+
reason: payload.reason,
|
|
853
|
+
requestedBy: payload.requestedBy,
|
|
854
|
+
command: payload.command ?? null,
|
|
855
|
+
revision: 1,
|
|
856
|
+
requestedAt: now,
|
|
857
|
+
claimedAt: null,
|
|
858
|
+
finishedAt: null,
|
|
859
|
+
history: [{ at: now, type: 'enqueued', actor, detail: null }],
|
|
860
|
+
};
|
|
861
|
+
validateEntrySchema(entry);
|
|
862
|
+
writeEntryFile(teamRoot, entry);
|
|
863
|
+
return { entry, existing: false };
|
|
864
|
+
});
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
export function cancelBacklogEntry(teamRoot, entryId, options = {}) {
|
|
868
|
+
return withBacklogLock(teamRoot, () => {
|
|
869
|
+
const entry = readEntryFile(teamRoot, entryId);
|
|
870
|
+
if (!entry) reject('E_BACKLOG_UNKNOWN_DEP', `no queue entry "${entryId}"`);
|
|
871
|
+
const taskState = readTaskStates(teamRoot).get(entry.itemId) ?? null;
|
|
872
|
+
const effective = effectiveEntryStatus(entry, taskState);
|
|
873
|
+
if (effective === 'active') {
|
|
874
|
+
reject('E_BACKLOG_TRANSITION', `entry ${entryId} is active; an active run belongs to the hook`);
|
|
875
|
+
}
|
|
876
|
+
if (['cancelled', 'expired', 'done'].includes(effective)) return { entry, unchanged: true };
|
|
877
|
+
const at = nowIso();
|
|
878
|
+
const next = {
|
|
879
|
+
...entry,
|
|
880
|
+
status: 'cancelled',
|
|
881
|
+
claimedAt: entry.status === 'claimed' ? entry.claimedAt : null,
|
|
882
|
+
finishedAt: at,
|
|
883
|
+
revision: entry.revision + 1,
|
|
884
|
+
history: capHistory(
|
|
885
|
+
[...(entry.history ?? []), { at, type: 'cancelled', actor: options.actor ?? 'operator', detail: null }],
|
|
886
|
+
MAX_ENTRY_HISTORY,
|
|
887
|
+
),
|
|
888
|
+
};
|
|
889
|
+
validateEntrySchema(next);
|
|
890
|
+
writeEntryFile(teamRoot, next);
|
|
891
|
+
return { entry: next, unchanged: false };
|
|
892
|
+
});
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
/**
|
|
896
|
+
* A claim older than the stale window with no task row is never treated as
|
|
897
|
+
* evidence of a launch — the task row is the only such evidence (D-5). The
|
|
898
|
+
* next drain or an explicit recover writes it back to `queued`.
|
|
899
|
+
*/
|
|
900
|
+
const releaseStaleClaims = (teamRoot, actor) => {
|
|
901
|
+
let recovered = 0;
|
|
902
|
+
const taskStates = readTaskStates(teamRoot);
|
|
903
|
+
for (const [entryId, entry] of readAllEntries(teamRoot)) {
|
|
904
|
+
if (entry.status !== 'claimed' || entry.claimedAt === null) continue;
|
|
905
|
+
if (taskStates.has(entry.itemId)) continue;
|
|
906
|
+
if (Date.now() - Date.parse(entry.claimedAt) < CLAIM_STALE_MS) continue;
|
|
907
|
+
const at = nowIso();
|
|
908
|
+
const next = {
|
|
909
|
+
...entry,
|
|
910
|
+
status: 'queued',
|
|
911
|
+
claimedAt: null,
|
|
912
|
+
revision: entry.revision + 1,
|
|
913
|
+
history: capHistory(
|
|
914
|
+
[...(entry.history ?? []), { at, type: 'recovered', actor, detail: 'stale claim' }],
|
|
915
|
+
MAX_ENTRY_HISTORY,
|
|
916
|
+
),
|
|
917
|
+
};
|
|
918
|
+
validateEntrySchema(next);
|
|
919
|
+
writeEntryFile(teamRoot, next);
|
|
920
|
+
recovered += 1;
|
|
921
|
+
}
|
|
922
|
+
return recovered;
|
|
923
|
+
};
|
|
924
|
+
|
|
925
|
+
export function recoverBacklogEntries(teamRoot, options = {}) {
|
|
926
|
+
return withBacklogLock(teamRoot, () => ({ recovered: releaseStaleClaims(teamRoot, options.actor ?? 'operator') }));
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
export function drainBacklog(teamRoot, { claim = false, actor = 'operator' } = {}) {
|
|
930
|
+
return withBacklogLock(teamRoot, () => {
|
|
931
|
+
releaseStaleClaims(teamRoot, actor);
|
|
932
|
+
const snapshot = {
|
|
933
|
+
asOf: nowIso(),
|
|
934
|
+
items: readAllItems(teamRoot),
|
|
935
|
+
entries: readAllEntries(teamRoot),
|
|
936
|
+
taskStates: readTaskStates(teamRoot),
|
|
937
|
+
};
|
|
938
|
+
const ordering = deriveBacklogOrdering(snapshot);
|
|
939
|
+
const config = readBacklogConfig(teamRoot);
|
|
940
|
+
const activeCount = countActiveTasks(snapshot.taskStates);
|
|
941
|
+
const claimedOrActiveCount = [...snapshot.entries.values()].filter((entry) =>
|
|
942
|
+
['claimed', 'active'].includes(effectiveEntryStatus(entry, snapshot.taskStates.get(entry.itemId) ?? null)),
|
|
943
|
+
).length;
|
|
944
|
+
const claimable = activeCount < config.maxActive && claimedOrActiveCount < config.maxActive;
|
|
945
|
+
const base = {
|
|
946
|
+
asOf: snapshot.asOf,
|
|
947
|
+
ready: ordering.readyIds,
|
|
948
|
+
drainOrder: ordering.drainOrderEntryIds,
|
|
949
|
+
claimable,
|
|
950
|
+
maxActive: config.maxActive,
|
|
951
|
+
activeCount,
|
|
952
|
+
};
|
|
953
|
+
if (!claim) return base;
|
|
954
|
+
if (!claimable) {
|
|
955
|
+
const reason = activeCount >= config.maxActive ? 'capacity: active tasks' : 'capacity: claimed or active entries';
|
|
956
|
+
return { ok: true, claim: null, reason, ...base };
|
|
957
|
+
}
|
|
958
|
+
const headEntryId = ordering.drainOrderEntryIds[0];
|
|
959
|
+
if (!headEntryId) return { ok: true, claim: null, reason: 'empty drain order', ...base };
|
|
960
|
+
const entry = snapshot.entries.get(headEntryId);
|
|
961
|
+
const at = nowIso();
|
|
962
|
+
const next = {
|
|
963
|
+
...entry,
|
|
964
|
+
status: 'claimed',
|
|
965
|
+
claimedAt: at,
|
|
966
|
+
revision: entry.revision + 1,
|
|
967
|
+
history: capHistory([...(entry.history ?? []), { at, type: 'claimed', actor, detail: null }], MAX_ENTRY_HISTORY),
|
|
968
|
+
};
|
|
969
|
+
validateEntrySchema(next);
|
|
970
|
+
writeEntryFile(teamRoot, next);
|
|
971
|
+
return { ok: true, claim: { entryId: next.entryId, itemId: next.itemId, slug: next.itemId }, reason: null, ...base };
|
|
972
|
+
});
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
export function pruneBacklogEntries(teamRoot, { olderThanDays = DEFAULT_PRUNE_DAYS } = {}) {
|
|
976
|
+
return withBacklogLock(teamRoot, () => {
|
|
977
|
+
const cutoff = Date.now() - olderThanDays * 24 * 60 * 60 * 1000;
|
|
978
|
+
let pruned = 0;
|
|
979
|
+
for (const [entryId, entry] of readAllEntries(teamRoot)) {
|
|
980
|
+
if (entry.status !== 'cancelled' && entry.status !== 'expired') continue;
|
|
981
|
+
if (!entry.finishedAt || Date.parse(entry.finishedAt) >= cutoff) continue;
|
|
982
|
+
fs.rmSync(entryFilePath(teamRoot, entryId), { force: true });
|
|
983
|
+
pruned += 1;
|
|
984
|
+
}
|
|
985
|
+
return { pruned };
|
|
986
|
+
});
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
/* --------------------------------- import --------------------------------- */
|
|
990
|
+
|
|
991
|
+
const normalizeImportItem = (raw) => ({
|
|
992
|
+
schemaVersion: ITEM_SCHEMA_VERSION,
|
|
993
|
+
id: raw.id,
|
|
994
|
+
revision: raw.revision ?? 1,
|
|
995
|
+
title: typeof raw.title === 'string' ? raw.title.trim() : raw.title,
|
|
996
|
+
status: raw.status ?? 'planned',
|
|
997
|
+
priority: raw.priority ?? 5,
|
|
998
|
+
sourceTask: raw.sourceTask ?? null,
|
|
999
|
+
sourceRefs: raw.sourceRefs ?? [],
|
|
1000
|
+
createdAt: raw.createdAt,
|
|
1001
|
+
updatedAt: raw.updatedAt,
|
|
1002
|
+
completedAt: raw.completedAt ?? null,
|
|
1003
|
+
cancelledAt: raw.cancelledAt ?? null,
|
|
1004
|
+
cancelReason: raw.cancelReason ?? null,
|
|
1005
|
+
supersededBy: raw.supersededBy ?? null,
|
|
1006
|
+
type: raw.type ?? 'feature',
|
|
1007
|
+
description: raw.description ?? null,
|
|
1008
|
+
labels: raw.labels ?? [],
|
|
1009
|
+
dependsOn: raw.dependsOn ?? [],
|
|
1010
|
+
history: Array.isArray(raw.history) ? raw.history : [],
|
|
1011
|
+
});
|
|
1012
|
+
|
|
1013
|
+
/**
|
|
1014
|
+
* The envelope-driven fields — the content whose equality makes a re-import
|
|
1015
|
+
* idle. `revision` and `history` are store-owned bookkeeping, never part of
|
|
1016
|
+
* the comparison (D-8: content-hash equality, the projector's idiom).
|
|
1017
|
+
*/
|
|
1018
|
+
const envelopeFields = (item) => {
|
|
1019
|
+
const { revision, history, ...fields } = item;
|
|
1020
|
+
void revision;
|
|
1021
|
+
void history;
|
|
1022
|
+
return fields;
|
|
1023
|
+
};
|
|
1024
|
+
|
|
1025
|
+
/**
|
|
1026
|
+
* D-8: a versioned envelope `{schemaVersion, source: {task, generatedAt},
|
|
1027
|
+
* items[]}`, validated as one transaction — nothing is written unless every
|
|
1028
|
+
* item passes — upserted by id, `--dry-run` writes nothing, and an idle
|
|
1029
|
+
* re-import (content-hash equality) writes nothing.
|
|
1030
|
+
*/
|
|
1031
|
+
export function importBacklogItems(teamRoot, envelope, options = {}) {
|
|
1032
|
+
if (!isRecord(envelope)) reject('E_SCHEMA', 'import envelope must be an object');
|
|
1033
|
+
if (envelope.schemaVersion !== ITEM_SCHEMA_VERSION) {
|
|
1034
|
+
reject('E_SCHEMA', `import envelope schemaVersion must be ${ITEM_SCHEMA_VERSION}`);
|
|
1035
|
+
}
|
|
1036
|
+
const source = envelope.source;
|
|
1037
|
+
if (!isRecord(source) || typeof source.task !== 'string' || source.task.length < 1) {
|
|
1038
|
+
reject('E_SCHEMA', 'import envelope source.task is required');
|
|
1039
|
+
}
|
|
1040
|
+
if (!isIsoZ(source.generatedAt)) {
|
|
1041
|
+
reject('E_SCHEMA', 'import envelope source.generatedAt must be an RFC 3339 timestamp ending in Z');
|
|
1042
|
+
}
|
|
1043
|
+
if (!Array.isArray(envelope.items)) reject('E_SCHEMA', 'import envelope items must be an array');
|
|
1044
|
+
const dryRun = Boolean(options.dryRun);
|
|
1045
|
+
return withBacklogLock(teamRoot, () => {
|
|
1046
|
+
const existing = readAllItems(teamRoot);
|
|
1047
|
+
const byId = new Map(existing);
|
|
1048
|
+
const plan = [];
|
|
1049
|
+
// Validate the whole envelope before the first write: one transaction.
|
|
1050
|
+
for (const [index, raw] of envelope.items.entries()) {
|
|
1051
|
+
if (!isRecord(raw)) reject('E_SCHEMA', `import items[${index}] must be an object`);
|
|
1052
|
+
const item = normalizeImportItem(raw);
|
|
1053
|
+
if (item.id === undefined || item.id === null) {
|
|
1054
|
+
reject('E_SCHEMA', `import items[${index}]: id is required`);
|
|
1055
|
+
}
|
|
1056
|
+
if (plan.some((entry) => entry.item.id === item.id)) {
|
|
1057
|
+
reject('E_BACKLOG_DUPLICATE_ID', `import envelope: items[${index}] duplicates id "${item.id}"`);
|
|
1058
|
+
}
|
|
1059
|
+
validateItemSchema(item);
|
|
1060
|
+
const previous = byId.get(item.id) ?? null;
|
|
1061
|
+
if (!previous) {
|
|
1062
|
+
// D-2 collision guard applies to new ids, exactly as on `add`.
|
|
1063
|
+
if (fs.existsSync(path.join(teamRoot, 'tasks', item.id))) {
|
|
1064
|
+
reject('E_ID_COLLISION', `id "${item.id}" already names a tasks/${item.id}/ directory`);
|
|
1065
|
+
}
|
|
1066
|
+
} else {
|
|
1067
|
+
validateTransition(previous, item);
|
|
1068
|
+
}
|
|
1069
|
+
validateItemGraph(item, byId);
|
|
1070
|
+
const at = nowIso();
|
|
1071
|
+
const unchanged =
|
|
1072
|
+
previous !== null && canonicalJson(envelopeFields(item)) === canonicalJson(envelopeFields(previous));
|
|
1073
|
+
let target = null;
|
|
1074
|
+
if (unchanged) {
|
|
1075
|
+
target = previous;
|
|
1076
|
+
} else if (previous === null) {
|
|
1077
|
+
target = {
|
|
1078
|
+
...item,
|
|
1079
|
+
revision: 1,
|
|
1080
|
+
history: capHistory([...(item.history ?? []), { at, type: 'created', actor: source.task, detail: null }], MAX_ITEM_HISTORY),
|
|
1081
|
+
};
|
|
1082
|
+
} else {
|
|
1083
|
+
target = {
|
|
1084
|
+
...item,
|
|
1085
|
+
revision: previous.revision + 1,
|
|
1086
|
+
history: capHistory(
|
|
1087
|
+
[...(previous.history ?? []), { at, type: 'imported', actor: source.task, detail: null }],
|
|
1088
|
+
MAX_ITEM_HISTORY,
|
|
1089
|
+
),
|
|
1090
|
+
};
|
|
1091
|
+
}
|
|
1092
|
+
plan.push({ item: target, previous, unchanged });
|
|
1093
|
+
byId.set(item.id, { ...byId.get(item.id), ...target });
|
|
1094
|
+
}
|
|
1095
|
+
const result = { inserted: 0, updated: 0, unchanged: 0, dryRun };
|
|
1096
|
+
for (const step of plan) {
|
|
1097
|
+
if (step.unchanged) {
|
|
1098
|
+
result.unchanged += 1;
|
|
1099
|
+
continue;
|
|
1100
|
+
}
|
|
1101
|
+
if (step.previous === null) result.inserted += 1;
|
|
1102
|
+
else result.updated += 1;
|
|
1103
|
+
if (!dryRun) writeItemFile(teamRoot, step.item);
|
|
1104
|
+
}
|
|
1105
|
+
return result;
|
|
1106
|
+
});
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
/* ------------------------ whole-tree validation --------------------------- */
|
|
1110
|
+
|
|
1111
|
+
export function validateBacklogTree(teamRoot) {
|
|
1112
|
+
return withBacklogLock(teamRoot, () => {
|
|
1113
|
+
const errors = [];
|
|
1114
|
+
const items = readAllItems(teamRoot);
|
|
1115
|
+
readBacklogConfig(teamRoot);
|
|
1116
|
+
for (const id of listItemIds(teamRoot)) {
|
|
1117
|
+
const record = items.get(id);
|
|
1118
|
+
const collect = (code, message) => errors.push({ path: `backlog/items/${id}.json`, code, message });
|
|
1119
|
+
if (!record) {
|
|
1120
|
+
collect('E_SCHEMA', 'item file is not readable');
|
|
1121
|
+
continue;
|
|
1122
|
+
}
|
|
1123
|
+
try {
|
|
1124
|
+
validateItemSchema(record);
|
|
1125
|
+
} catch (error) {
|
|
1126
|
+
collect(error instanceof TeamDbError ? error.code : 'E_SCHEMA', error.message);
|
|
1127
|
+
continue;
|
|
1128
|
+
}
|
|
1129
|
+
try {
|
|
1130
|
+
validateItemIdentity(record, id);
|
|
1131
|
+
} catch (error) {
|
|
1132
|
+
collect(error instanceof TeamDbError ? error.code : 'E_SCHEMA', error.message);
|
|
1133
|
+
continue;
|
|
1134
|
+
}
|
|
1135
|
+
try {
|
|
1136
|
+
validateItemGraph(record, items);
|
|
1137
|
+
} catch (error) {
|
|
1138
|
+
collect(error instanceof TeamDbError ? error.code : 'E_SCHEMA', error.message);
|
|
1139
|
+
continue;
|
|
1140
|
+
}
|
|
1141
|
+
try {
|
|
1142
|
+
validateTransition(null, record);
|
|
1143
|
+
} catch (error) {
|
|
1144
|
+
collect(error instanceof TeamDbError ? error.code : 'E_SCHEMA', error.message);
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
for (const entryId of listEntryIds(teamRoot)) {
|
|
1148
|
+
try {
|
|
1149
|
+
validateEntrySchema(readEntryFile(teamRoot, entryId));
|
|
1150
|
+
} catch (error) {
|
|
1151
|
+
errors.push({
|
|
1152
|
+
path: `backlog/queue/${entryId}.json`,
|
|
1153
|
+
code: error instanceof TeamDbError ? error.code : 'E_SCHEMA',
|
|
1154
|
+
message: error.message,
|
|
1155
|
+
});
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
return { ok: errors.length === 0, items: items.size, errors };
|
|
1159
|
+
});
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
/* --------------------------- projection seam ------------------------------ */
|
|
1163
|
+
|
|
1164
|
+
/**
|
|
1165
|
+
* Best-effort bounded projection after a write, mirroring the manifest seam:
|
|
1166
|
+
* the child is `SIGKILL`-bounded, failures are silent, and the kill switch or
|
|
1167
|
+
* a missing `node:sqlite` skips it. Files stay authoritative; the next hook or
|
|
1168
|
+
* manifest projection reconciles.
|
|
1169
|
+
*/
|
|
1170
|
+
const projectAfterWrite = (teamRoot) => {
|
|
1171
|
+
const env = process.env;
|
|
1172
|
+
if (isTruthy(env.AI_RULES_TEAM_DB_DISABLE)) return;
|
|
1173
|
+
const script = path.join(path.dirname(fileURLToPath(import.meta.url)), 'team-db.mjs');
|
|
1174
|
+
if (!fs.existsSync(script)) return;
|
|
1175
|
+
const result = spawnSync(
|
|
1176
|
+
process.execPath,
|
|
1177
|
+
[script, 'sync', '--quiet', '--no-rebuild', '--deadline-ms', '4500', '--root', teamRoot],
|
|
1178
|
+
{ env, encoding: 'utf8', timeout: 5000, killSignal: 'SIGKILL', stdio: ['ignore', 'pipe', 'pipe'] },
|
|
1179
|
+
);
|
|
1180
|
+
void result;
|
|
1181
|
+
};
|
|
1182
|
+
|
|
1183
|
+
/* ------------------------------ CLI surface ------------------------------- */
|
|
1184
|
+
|
|
1185
|
+
export const BACKLOG_SUBCOMMANDS = new Set([
|
|
1186
|
+
'add',
|
|
1187
|
+
'set',
|
|
1188
|
+
'show',
|
|
1189
|
+
'list',
|
|
1190
|
+
'ready',
|
|
1191
|
+
'validate',
|
|
1192
|
+
'import',
|
|
1193
|
+
'enqueue',
|
|
1194
|
+
'cancel',
|
|
1195
|
+
'drain',
|
|
1196
|
+
'recover',
|
|
1197
|
+
'prune',
|
|
1198
|
+
]);
|
|
1199
|
+
|
|
1200
|
+
const SUBCOMMAND_FLAGS = {
|
|
1201
|
+
add: new Set(['file']),
|
|
1202
|
+
set: new Set(['file']),
|
|
1203
|
+
show: new Set(),
|
|
1204
|
+
list: new Set(['status', 'ready']),
|
|
1205
|
+
ready: new Set(),
|
|
1206
|
+
validate: new Set(),
|
|
1207
|
+
import: new Set(['file', 'dry-run']),
|
|
1208
|
+
enqueue: new Set(['file']),
|
|
1209
|
+
cancel: new Set(),
|
|
1210
|
+
drain: new Set(['claim']),
|
|
1211
|
+
recover: new Set(),
|
|
1212
|
+
prune: new Set(['older-than']),
|
|
1213
|
+
};
|
|
1214
|
+
|
|
1215
|
+
const WITH_ID = new Set(['set', 'show', 'cancel']);
|
|
1216
|
+
const WITH_FILE = new Set(['add', 'set', 'import', 'enqueue']);
|
|
1217
|
+
|
|
1218
|
+
export function runBacklogCommand(subcommand, positionalId, options = {}) {
|
|
1219
|
+
const teamRoot = path.resolve(options.root || DEFAULT_TEAM_ROOT);
|
|
1220
|
+
const json = Boolean(options.json);
|
|
1221
|
+
const quiet = Boolean(options.quiet);
|
|
1222
|
+
if (!BACKLOG_SUBCOMMANDS.has(subcommand)) teamDbFail('E_USAGE', `unknown backlog subcommand "${subcommand}"`, 3);
|
|
1223
|
+
const allowed = SUBCOMMAND_FLAGS[subcommand];
|
|
1224
|
+
const present = [];
|
|
1225
|
+
if (options.file !== undefined) present.push('file');
|
|
1226
|
+
if (options.dryRun) present.push('dry-run');
|
|
1227
|
+
if (options.olderThanDays !== undefined) present.push('older-than');
|
|
1228
|
+
if (options.claim) present.push('claim');
|
|
1229
|
+
if (options.status !== undefined) present.push('status');
|
|
1230
|
+
if (options.ready) present.push('ready');
|
|
1231
|
+
for (const flag of present) {
|
|
1232
|
+
if (!allowed.has(flag)) teamDbFail('E_USAGE', `flag --${flag} does not apply to backlog ${subcommand}`, 3);
|
|
1233
|
+
}
|
|
1234
|
+
if (WITH_ID.has(subcommand) && (typeof positionalId !== 'string' || positionalId === '')) {
|
|
1235
|
+
teamDbFail('E_USAGE', `backlog ${subcommand} needs an id`, 3);
|
|
1236
|
+
}
|
|
1237
|
+
if (!WITH_ID.has(subcommand) && positionalId !== null && positionalId !== undefined) {
|
|
1238
|
+
teamDbFail('E_USAGE', `backlog ${subcommand} takes no id argument`, 3);
|
|
1239
|
+
}
|
|
1240
|
+
const readPayload = () => {
|
|
1241
|
+
if (options.file === undefined) teamDbFail('E_USAGE', `backlog ${subcommand} needs --file <path|->`, 3);
|
|
1242
|
+
const text = options.file === '-' ? fs.readFileSync(0, 'utf8') : fs.readFileSync(path.resolve(options.file), 'utf8');
|
|
1243
|
+
try {
|
|
1244
|
+
return JSON.parse(text);
|
|
1245
|
+
} catch (error) {
|
|
1246
|
+
teamDbFail('E_SCHEMA', `--file payload is not valid JSON: ${error.message}`, 1);
|
|
1247
|
+
}
|
|
1248
|
+
return null;
|
|
1249
|
+
};
|
|
1250
|
+
const out = (text) => {
|
|
1251
|
+
if (json) return `${text}\n`;
|
|
1252
|
+
if (!quiet) return `${text}\n`;
|
|
1253
|
+
return '';
|
|
1254
|
+
};
|
|
1255
|
+
const itemLine = (item) => `backlog: id=${item.id} status=${item.status} revision=${item.revision}`;
|
|
1256
|
+
const entryLine = (entry) => `backlog: entry=${entry.entryId} item=${entry.itemId} status=${entry.status}`;
|
|
1257
|
+
const rankedItems = (ordering) =>
|
|
1258
|
+
[...ordering.byId.values()].sort((a, b) => rankCompare(a.item, b.item));
|
|
1259
|
+
|
|
1260
|
+
let output = '';
|
|
1261
|
+
let wrote = false;
|
|
1262
|
+
|
|
1263
|
+
if (subcommand === 'add') {
|
|
1264
|
+
const item = addBacklogItem(teamRoot, readPayload());
|
|
1265
|
+
wrote = true;
|
|
1266
|
+
output += out(json ? JSON.stringify({ ok: true, item }) : itemLine(item));
|
|
1267
|
+
} else if (subcommand === 'set') {
|
|
1268
|
+
const item = setBacklogItem(teamRoot, positionalId, readPayload());
|
|
1269
|
+
wrote = true;
|
|
1270
|
+
output += out(json ? JSON.stringify({ ok: true, item }) : itemLine(item));
|
|
1271
|
+
} else if (subcommand === 'show') {
|
|
1272
|
+
const snapshot = readBacklogSnapshot(teamRoot);
|
|
1273
|
+
const annotated = deriveBacklogOrdering(snapshot).byId.get(positionalId);
|
|
1274
|
+
if (!annotated) reject('E_BACKLOG_UNKNOWN_DEP', `no backlog item "${positionalId}"`);
|
|
1275
|
+
output += out(JSON.stringify(annotated, null, json ? 0 : 2));
|
|
1276
|
+
} else if (subcommand === 'list') {
|
|
1277
|
+
const snapshot = readBacklogSnapshot(teamRoot);
|
|
1278
|
+
const ordering = deriveBacklogOrdering(snapshot);
|
|
1279
|
+
const statuses = options.status !== undefined ? options.status.split(',').map((value) => value.trim()) : null;
|
|
1280
|
+
if (statuses) {
|
|
1281
|
+
for (const status of statuses) {
|
|
1282
|
+
if (!EFFECTIVE_ITEM_STATUSES.includes(status)) teamDbFail('E_USAGE', `--status "${status}" is not one of ${EFFECTIVE_ITEM_STATUSES.join(',')}`, 3);
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
const items = rankedItems(ordering)
|
|
1286
|
+
.filter((annotated) => (statuses ? statuses.includes(annotated.effectiveStatus) : true))
|
|
1287
|
+
.filter((annotated) => (options.ready ? annotated.ready : true))
|
|
1288
|
+
.map((annotated) => ({
|
|
1289
|
+
id: annotated.item.id,
|
|
1290
|
+
title: annotated.item.title,
|
|
1291
|
+
status: annotated.item.status,
|
|
1292
|
+
effectiveStatus: annotated.effectiveStatus,
|
|
1293
|
+
priority: annotated.item.priority,
|
|
1294
|
+
ready: annotated.ready,
|
|
1295
|
+
waitingOn: annotated.waitingOn,
|
|
1296
|
+
createdAt: annotated.item.createdAt,
|
|
1297
|
+
updatedAt: annotated.item.updatedAt,
|
|
1298
|
+
queueEntryId: annotated.queueEntryId,
|
|
1299
|
+
}));
|
|
1300
|
+
if (json) {
|
|
1301
|
+
output += out(JSON.stringify({ asOf: snapshot.asOf, items, total: items.length, readyCount: ordering.readyIds.length }));
|
|
1302
|
+
} else {
|
|
1303
|
+
for (const item of items) {
|
|
1304
|
+
output += `${item.id} ${item.effectiveStatus} p${item.priority}${item.ready ? ' ready' : item.waitingOn.length > 0 ? ` waiting_on ${item.waitingOn.join(',')}` : ''} ${item.title}\n`;
|
|
1305
|
+
}
|
|
1306
|
+
if (quiet) output = '';
|
|
1307
|
+
}
|
|
1308
|
+
} else if (subcommand === 'ready') {
|
|
1309
|
+
const snapshot = readBacklogSnapshot(teamRoot);
|
|
1310
|
+
const ordering = deriveBacklogOrdering(snapshot);
|
|
1311
|
+
output += json
|
|
1312
|
+
? out(JSON.stringify({ asOf: snapshot.asOf, ready: ordering.readyIds }))
|
|
1313
|
+
: out(ordering.readyIds.join('\n') || '(no ready items)');
|
|
1314
|
+
} else if (subcommand === 'validate') {
|
|
1315
|
+
const report = validateBacklogTree(teamRoot);
|
|
1316
|
+
if (!report.ok) {
|
|
1317
|
+
for (const error of report.errors) process.stderr.write(`${error.path}: ${error.code}: ${error.message}\n`);
|
|
1318
|
+
if (json) output += `${JSON.stringify({ ok: false, items: report.items, errors: report.errors })}\n`;
|
|
1319
|
+
return { output, exitCode: 1 };
|
|
1320
|
+
}
|
|
1321
|
+
output += out(json ? JSON.stringify({ ok: true, items: report.items, errors: [] }) : `backlog validate: ${report.items} items, all valid`);
|
|
1322
|
+
} else if (subcommand === 'import') {
|
|
1323
|
+
const result = importBacklogItems(teamRoot, readPayload(), { dryRun: options.dryRun });
|
|
1324
|
+
if (!options.dryRun) wrote = true;
|
|
1325
|
+
output += json
|
|
1326
|
+
? out(JSON.stringify({ ok: true, ...result }))
|
|
1327
|
+
: out(`backlog import: inserted=${result.inserted} updated=${result.updated} unchanged=${result.unchanged}${result.dryRun ? ' (dry run)' : ''}`);
|
|
1328
|
+
} else if (subcommand === 'enqueue') {
|
|
1329
|
+
const { entry, existing } = enqueueBacklogItem(teamRoot, readPayload());
|
|
1330
|
+
wrote = true;
|
|
1331
|
+
output += out(json ? JSON.stringify({ ok: true, entry, existing }) : `${entryLine(entry)}${existing ? ' (existing)' : ''}`);
|
|
1332
|
+
} else if (subcommand === 'cancel') {
|
|
1333
|
+
const { entry, unchanged } = cancelBacklogEntry(teamRoot, positionalId);
|
|
1334
|
+
wrote = true;
|
|
1335
|
+
output += out(json ? JSON.stringify({ ok: true, entry, unchanged }) : `${entryLine(entry)}${unchanged ? ' (unchanged)' : ''}`);
|
|
1336
|
+
} else if (subcommand === 'drain') {
|
|
1337
|
+
const result = drainBacklog(teamRoot, { claim: options.claim });
|
|
1338
|
+
if (json) {
|
|
1339
|
+
output += out(JSON.stringify(result));
|
|
1340
|
+
} else if (result.claim !== undefined) {
|
|
1341
|
+
output += out(
|
|
1342
|
+
result.claim
|
|
1343
|
+
? `backlog drain: claimed ${result.claim.entryId} for ${result.claim.slug}`
|
|
1344
|
+
: `backlog drain: no claim (${result.reason ?? 'nothing ready'})`,
|
|
1345
|
+
);
|
|
1346
|
+
} else {
|
|
1347
|
+
output += out(`backlog drain: ready=${result.ready.length} drainOrder=${result.drainOrder.length} claimable=${result.claimable}`);
|
|
1348
|
+
}
|
|
1349
|
+
} else if (subcommand === 'recover') {
|
|
1350
|
+
const { recovered } = recoverBacklogEntries(teamRoot);
|
|
1351
|
+
if (recovered > 0) wrote = true;
|
|
1352
|
+
output += out(json ? JSON.stringify({ ok: true, recovered }) : `backlog recover: ${recovered} stale claim(s) released`);
|
|
1353
|
+
} else if (subcommand === 'prune') {
|
|
1354
|
+
const days = options.olderThanDays === undefined ? DEFAULT_PRUNE_DAYS : Number(options.olderThanDays);
|
|
1355
|
+
if (!Number.isInteger(days) || days < 1) teamDbFail('E_USAGE', '--older-than must be a positive integer number of days', 3);
|
|
1356
|
+
const { pruned } = pruneBacklogEntries(teamRoot, { olderThanDays: days });
|
|
1357
|
+
if (pruned > 0) wrote = true;
|
|
1358
|
+
output += out(json ? JSON.stringify({ ok: true, pruned }) : `backlog prune: ${pruned} terminal entr${pruned === 1 ? 'y' : 'ies'} deleted`);
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
// The API's bounded child writes the file, then projects; the read-only
|
|
1362
|
+
// server re-reads the fresh rows. `drain` is the hook seam's verb and skips
|
|
1363
|
+
// this so the stop never pays a second projection child.
|
|
1364
|
+
if (wrote && subcommand !== 'drain') projectAfterWrite(teamRoot);
|
|
1365
|
+
return { output, exitCode: 0 };
|
|
1366
|
+
}
|