@bonesofspring/ai-rules 0.2.60 → 0.2.61
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 +77 -0
- package/README.md +59 -26
- package/bin/cli.js +368 -59
- package/bin/lib/ai-local-drift.js +18 -0
- package/bin/lib/engine-scripts.js +22 -5
- package/bin/lib/engine-upgrade.js +279 -0
- package/bin/lib/mcp/catalog.js +66 -5
- package/bin/lib/mcp/clients.js +4 -4
- package/bin/lib/mcp/credentials.js +88 -0
- package/bin/lib/mcp/doctor.js +100 -8
- package/bin/lib/mcp/npx.js +17 -0
- package/bin/lib/mcp/registry.js +2 -0
- package/bin/lib/merged-config.js +38 -0
- package/bin/lib/seed-ai-local-team.js +29 -14
- package/docs/MCP-CATALOG.md +30 -2
- package/docs/MCP-SETUP.md +30 -6
- package/docs/OPENCODE.md +22 -2
- package/docs/PLATFORMS.md +38 -0
- package/docs/PRESET-CONTRIBUTION.md +11 -1
- package/docs/TEAM-DB.md +187 -20
- package/docs/openapi/team-db.v1.json +4443 -2083
- package/mcp/defectdojo-mcp.mjs +353 -0
- package/mcp/gitlab.mjs +5 -1
- package/mcp/lib/defectdojo.mjs +249 -0
- package/mcp/lib/yandex.mjs +39 -15
- package/package.json +9 -3
- package/presets/_shared/ai-local/scripts/lock.mjs +139 -19
- package/presets/_shared/ai-local/scripts/signals.mjs +17 -1
- package/presets/_shared/ai-local/scripts/team-db-api.mjs +496 -67
- package/presets/_shared/ai-local/scripts/team-db-dashboard.mjs +816 -5
- package/presets/_shared/ai-local/scripts/team-db-openapi.mjs +761 -6
- package/presets/_shared/ai-local/scripts/team-db-project.mjs +10 -0
- package/presets/_shared/ai-local/scripts/team-db-scheduler.mjs +2360 -0
- package/presets/_shared/ai-local/scripts/team-db-schema.mjs +87 -0
- package/presets/_shared/ai-local/scripts/team-db.mjs +151 -9
- package/presets/_shared/ai-local/scripts/upstream-research.mjs +2961 -0
- package/presets/_shared/core/agent-team/agent-artifact-contracts.md +13 -0
- package/presets/_shared/hooks/README.md +23 -3
- package/presets/_shared/hooks/chain-team-phases.sh.tmpl +57 -3
- package/presets/{claude/nuxt/hooks/guard-shell-command.sh → _shared/hooks/guard-shell-command.mjs.tmpl} +29 -35
- package/presets/_shared/hooks/run-hook.mjs +102 -0
- package/presets/claude/android-kotlin/hooks/README.md +4 -3
- package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +57 -3
- package/presets/claude/android-kotlin/hooks/examples/README.md +2 -2
- package/presets/claude/android-kotlin/hooks/guard-shell-command.mjs +96 -0
- package/presets/claude/android-kotlin/hooks/run-hook.mjs +102 -0
- package/presets/claude/android-kotlin/settings.json +2 -2
- package/presets/claude/android-kotlin/team/README.md +5 -0
- package/presets/claude/go/hooks/README.md +4 -3
- package/presets/claude/go/hooks/chain-team-phases.sh +57 -3
- package/presets/claude/go/hooks/examples/README.md +2 -2
- package/presets/claude/go/hooks/guard-shell-command.mjs +95 -0
- package/presets/claude/go/hooks/run-hook.mjs +102 -0
- package/presets/claude/go/settings.json +2 -2
- package/presets/claude/go/team/README.md +5 -0
- package/presets/claude/ios-swift/hooks/README.md +4 -3
- package/presets/claude/ios-swift/hooks/chain-team-phases.sh +57 -3
- package/presets/claude/ios-swift/hooks/examples/README.md +2 -2
- package/presets/claude/ios-swift/hooks/guard-shell-command.mjs +95 -0
- package/presets/claude/ios-swift/hooks/run-hook.mjs +102 -0
- package/presets/claude/ios-swift/settings.json +2 -2
- package/presets/claude/ios-swift/team/README.md +5 -0
- package/presets/claude/java/hooks/README.md +4 -3
- package/presets/claude/java/hooks/chain-team-phases.sh +57 -3
- package/presets/claude/java/hooks/examples/README.md +2 -2
- package/presets/claude/java/hooks/{guard-shell-command.sh → guard-shell-command.mjs} +31 -38
- package/presets/claude/java/hooks/run-hook.mjs +102 -0
- package/presets/claude/java/settings.json +2 -2
- package/presets/claude/java/team/README.md +5 -0
- package/presets/claude/mcp-ts/hooks/README.md +4 -3
- package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +57 -3
- package/presets/claude/mcp-ts/hooks/examples/README.md +1 -1
- package/presets/claude/mcp-ts/hooks/guard-shell-command.mjs +95 -0
- package/presets/claude/mcp-ts/hooks/run-hook.mjs +102 -0
- package/presets/claude/mcp-ts/settings.json +2 -2
- package/presets/claude/mcp-ts/team/README.md +5 -0
- package/presets/claude/mol/hooks/README.md +20 -0
- package/presets/claude/mol/hooks/chain-team-phases.sh +57 -3
- package/presets/claude/{svelte/hooks/guard-shell-command.sh → mol/hooks/guard-shell-command.mjs} +29 -35
- package/presets/claude/mol/hooks/run-hook.mjs +102 -0
- package/presets/claude/mol/settings.json +2 -2
- package/presets/claude/mol/team/README.md +5 -0
- package/presets/claude/next/agents/build-verifier.md +2 -0
- package/presets/claude/next/agents/code-reviewer.md +2 -0
- package/presets/claude/next/agents/feature-developer.md +1 -0
- package/presets/claude/next/agents/task-analyst.md +4 -0
- package/presets/claude/next/agents/task-router.md +5 -3
- package/presets/claude/next/commands/README.md +1 -0
- package/presets/claude/next/commands/task-continue.md +1 -1
- package/presets/claude/next/commands/upstream-research.md +23 -0
- package/presets/claude/next/hooks/README.md +4 -3
- package/presets/claude/next/hooks/chain-team-phases.sh +57 -3
- package/presets/claude/next/hooks/examples/README.md +2 -2
- package/presets/claude/next/hooks/guard-shell-command.mjs +94 -0
- package/presets/claude/next/hooks/run-hook.mjs +102 -0
- package/presets/claude/next/settings.json +2 -2
- package/presets/claude/next/team/README.md +23 -0
- package/presets/claude/next/team/upstream/config.json +31 -0
- package/presets/claude/next/team/upstream/digest-template.md +55 -0
- package/presets/claude/next/team/upstream/opencode.json +34 -0
- package/presets/claude/next/team/upstream/projects.json +4 -0
- package/presets/claude/next/team/upstream/prompt.md +77 -0
- package/presets/claude/next/team/upstream/signatures.json +9 -0
- package/presets/claude/nuxt/hooks/README.md +4 -3
- package/presets/claude/nuxt/hooks/chain-team-phases.sh +57 -3
- package/presets/claude/nuxt/hooks/examples/README.md +2 -2
- package/presets/claude/{ios-swift/hooks/guard-shell-command.sh → nuxt/hooks/guard-shell-command.mjs} +29 -37
- package/presets/claude/nuxt/hooks/run-hook.mjs +102 -0
- package/presets/claude/nuxt/settings.json +2 -2
- package/presets/claude/nuxt/team/README.md +5 -0
- package/presets/claude/php-hexagonal/hooks/README.md +4 -3
- package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +57 -3
- package/presets/claude/php-hexagonal/hooks/examples/README.md +2 -2
- package/presets/claude/php-hexagonal/hooks/guard-shell-command.mjs +96 -0
- package/presets/claude/php-hexagonal/hooks/run-hook.mjs +102 -0
- package/presets/claude/php-hexagonal/settings.json +2 -2
- package/presets/claude/php-hexagonal/team/README.md +5 -0
- package/presets/claude/php-laravel/hooks/README.md +4 -3
- package/presets/claude/php-laravel/hooks/chain-team-phases.sh +57 -3
- package/presets/claude/php-laravel/hooks/examples/README.md +2 -2
- package/presets/claude/php-laravel/hooks/guard-shell-command.mjs +96 -0
- package/presets/claude/php-laravel/hooks/run-hook.mjs +102 -0
- package/presets/claude/php-laravel/settings.json +2 -2
- package/presets/claude/php-laravel/team/README.md +5 -0
- package/presets/claude/svelte/hooks/README.md +4 -3
- package/presets/claude/svelte/hooks/chain-team-phases.sh +57 -3
- package/presets/claude/svelte/hooks/examples/README.md +2 -2
- package/presets/claude/svelte/hooks/guard-shell-command.mjs +94 -0
- package/presets/claude/svelte/hooks/run-hook.mjs +102 -0
- package/presets/claude/svelte/settings.json +2 -2
- package/presets/claude/svelte/team/README.md +5 -0
- package/presets/cursor/android-kotlin/hooks/README.md +2 -1
- package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +57 -3
- package/presets/cursor/android-kotlin/hooks/examples/README.md +1 -1
- package/presets/cursor/android-kotlin/hooks/guard-shell-command.mjs +96 -0
- package/presets/cursor/android-kotlin/hooks/run-hook.mjs +102 -0
- package/presets/cursor/android-kotlin/hooks.json +2 -2
- package/presets/cursor/android-kotlin/team/README.md +5 -0
- package/presets/cursor/go/hooks/README.md +2 -1
- package/presets/cursor/go/hooks/chain-team-phases.sh +57 -3
- package/presets/cursor/go/hooks/examples/README.md +1 -1
- package/presets/cursor/go/hooks/guard-shell-command.mjs +95 -0
- package/presets/cursor/go/hooks/run-hook.mjs +102 -0
- package/presets/cursor/go/hooks.json +2 -2
- package/presets/cursor/go/team/README.md +5 -0
- package/presets/cursor/ios-swift/hooks/README.md +2 -1
- package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +57 -3
- package/presets/cursor/ios-swift/hooks/examples/README.md +1 -1
- package/presets/cursor/ios-swift/hooks/guard-shell-command.mjs +95 -0
- package/presets/cursor/ios-swift/hooks/run-hook.mjs +102 -0
- package/presets/cursor/ios-swift/hooks.json +2 -2
- package/presets/cursor/ios-swift/team/README.md +5 -0
- package/presets/cursor/java/hooks/README.md +2 -1
- package/presets/cursor/java/hooks/chain-team-phases.sh +57 -3
- package/presets/cursor/java/hooks/examples/README.md +1 -1
- package/presets/cursor/java/hooks/guard-shell-command.mjs +96 -0
- package/presets/cursor/java/hooks/run-hook.mjs +102 -0
- package/presets/cursor/java/hooks.json +2 -2
- package/presets/cursor/java/team/README.md +5 -0
- package/presets/cursor/mcp-ts/hooks/README.md +2 -1
- package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +57 -3
- package/presets/cursor/mcp-ts/hooks/guard-shell-command.mjs +95 -0
- package/presets/cursor/mcp-ts/hooks/run-hook.mjs +102 -0
- package/presets/cursor/mcp-ts/hooks.json +2 -2
- package/presets/cursor/mcp-ts/team/README.md +5 -0
- package/presets/cursor/mol/hooks/README.md +2 -1
- package/presets/cursor/mol/hooks/chain-team-phases.sh +57 -3
- package/presets/cursor/mol/hooks/examples/README.md +1 -1
- package/presets/{claude/next/hooks/guard-shell-command.sh → cursor/mol/hooks/guard-shell-command.mjs} +29 -35
- package/presets/cursor/mol/hooks/run-hook.mjs +102 -0
- package/presets/cursor/mol/hooks.json +2 -2
- package/presets/cursor/mol/team/README.md +5 -0
- package/presets/cursor/next/agents/build-verifier.md +2 -0
- package/presets/cursor/next/agents/code-reviewer.md +2 -0
- package/presets/cursor/next/agents/feature-developer.md +1 -0
- package/presets/cursor/next/agents/task-analyst.md +4 -0
- package/presets/cursor/next/agents/task-router.md +5 -3
- package/presets/cursor/next/commands/README.md +1 -0
- package/presets/cursor/next/commands/task-continue.md +1 -1
- package/presets/cursor/next/commands/upstream-research.md +23 -0
- package/presets/cursor/next/hooks/README.md +2 -1
- package/presets/cursor/next/hooks/chain-team-phases.sh +57 -3
- package/presets/cursor/next/hooks/examples/README.md +1 -1
- package/presets/cursor/next/hooks/guard-shell-command.mjs +94 -0
- package/presets/cursor/next/hooks/run-hook.mjs +102 -0
- package/presets/cursor/next/hooks.json +2 -2
- package/presets/cursor/next/team/README.md +23 -0
- package/presets/cursor/next/team/upstream/config.json +31 -0
- package/presets/cursor/next/team/upstream/digest-template.md +55 -0
- package/presets/cursor/next/team/upstream/opencode.json +34 -0
- package/presets/cursor/next/team/upstream/projects.json +4 -0
- package/presets/cursor/next/team/upstream/prompt.md +77 -0
- package/presets/cursor/next/team/upstream/signatures.json +9 -0
- package/presets/cursor/nuxt/hooks/README.md +2 -1
- package/presets/cursor/nuxt/hooks/chain-team-phases.sh +57 -3
- package/presets/cursor/nuxt/hooks/examples/README.md +1 -1
- package/presets/cursor/nuxt/hooks/guard-shell-command.mjs +94 -0
- package/presets/cursor/nuxt/hooks/run-hook.mjs +102 -0
- package/presets/cursor/nuxt/hooks.json +2 -2
- package/presets/cursor/nuxt/team/README.md +5 -0
- package/presets/cursor/php-hexagonal/hooks/README.md +2 -1
- package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +57 -3
- package/presets/cursor/php-hexagonal/hooks/examples/README.md +1 -1
- package/presets/cursor/php-hexagonal/hooks/guard-shell-command.mjs +96 -0
- package/presets/cursor/php-hexagonal/hooks/run-hook.mjs +102 -0
- package/presets/cursor/php-hexagonal/hooks.json +2 -2
- package/presets/cursor/php-hexagonal/team/README.md +5 -0
- package/presets/cursor/php-laravel/hooks/README.md +2 -1
- package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +57 -3
- package/presets/cursor/php-laravel/hooks/examples/README.md +1 -1
- package/presets/cursor/php-laravel/hooks/guard-shell-command.mjs +96 -0
- package/presets/cursor/php-laravel/hooks/run-hook.mjs +102 -0
- package/presets/cursor/php-laravel/hooks.json +2 -2
- package/presets/cursor/php-laravel/team/README.md +5 -0
- package/presets/cursor/svelte/hooks/README.md +2 -1
- package/presets/cursor/svelte/hooks/chain-team-phases.sh +57 -3
- package/presets/cursor/svelte/hooks/examples/README.md +1 -1
- package/presets/cursor/svelte/hooks/guard-shell-command.mjs +94 -0
- package/presets/cursor/svelte/hooks/run-hook.mjs +102 -0
- package/presets/cursor/svelte/hooks.json +2 -2
- package/presets/cursor/svelte/team/README.md +5 -0
- package/presets/mavis/android-kotlin/adapter-map.json +11 -3
- package/presets/mavis/android-kotlin/hooks/README.md +2 -1
- package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +57 -3
- package/presets/mavis/android-kotlin/team/README.md +5 -0
- package/presets/mavis/go/adapter-map.json +11 -3
- package/presets/mavis/go/hooks/README.md +2 -1
- package/presets/mavis/go/hooks/chain-team-phases.sh +57 -3
- package/presets/mavis/go/team/README.md +5 -0
- package/presets/mavis/ios-swift/adapter-map.json +11 -3
- package/presets/mavis/ios-swift/hooks/README.md +2 -1
- package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +57 -3
- package/presets/mavis/ios-swift/team/README.md +5 -0
- package/presets/mavis/java/adapter-map.json +11 -3
- package/presets/mavis/java/hooks/README.md +2 -1
- package/presets/mavis/java/hooks/chain-team-phases.sh +57 -3
- package/presets/mavis/java/team/README.md +5 -0
- package/presets/mavis/mcp-ts/adapter-map.json +11 -3
- package/presets/mavis/mcp-ts/hooks/README.md +2 -1
- package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +57 -3
- package/presets/mavis/mcp-ts/team/README.md +5 -0
- package/presets/mavis/mol/adapter-map.json +11 -3
- package/presets/mavis/mol/hooks/README.md +2 -1
- package/presets/mavis/mol/hooks/chain-team-phases.sh +57 -3
- package/presets/mavis/mol/team/README.md +5 -0
- package/presets/mavis/next/adapter-map.json +67 -3
- package/presets/mavis/next/agents/build-verifier.md +2 -0
- package/presets/mavis/next/agents/code-reviewer.md +2 -0
- package/presets/mavis/next/agents/feature-developer.md +1 -0
- package/presets/mavis/next/agents/task-analyst.md +4 -0
- package/presets/mavis/next/agents/task-router.md +5 -3
- package/presets/mavis/next/commands/README.md +1 -0
- package/presets/mavis/next/commands/task-continue.md +1 -1
- package/presets/mavis/next/commands/upstream-research.md +18 -0
- package/presets/mavis/next/hooks/README.md +2 -1
- package/presets/mavis/next/hooks/chain-team-phases.sh +57 -3
- package/presets/mavis/next/team/README.md +23 -0
- package/presets/mavis/next/team/upstream/config.json +31 -0
- package/presets/mavis/next/team/upstream/digest-template.md +55 -0
- package/presets/mavis/next/team/upstream/opencode.json +34 -0
- package/presets/mavis/next/team/upstream/projects.json +4 -0
- package/presets/mavis/next/team/upstream/prompt.md +77 -0
- package/presets/mavis/next/team/upstream/signatures.json +9 -0
- package/presets/mavis/nuxt/adapter-map.json +11 -3
- package/presets/mavis/nuxt/hooks/README.md +2 -1
- package/presets/mavis/nuxt/hooks/chain-team-phases.sh +57 -3
- package/presets/mavis/nuxt/team/README.md +5 -0
- package/presets/mavis/php-hexagonal/adapter-map.json +11 -3
- package/presets/mavis/php-hexagonal/hooks/README.md +2 -1
- package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +57 -3
- package/presets/mavis/php-hexagonal/team/README.md +5 -0
- package/presets/mavis/php-laravel/adapter-map.json +11 -3
- package/presets/mavis/php-laravel/hooks/README.md +2 -1
- package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +57 -3
- package/presets/mavis/php-laravel/team/README.md +5 -0
- package/presets/mavis/svelte/adapter-map.json +11 -3
- package/presets/mavis/svelte/hooks/README.md +2 -1
- package/presets/mavis/svelte/hooks/chain-team-phases.sh +57 -3
- package/presets/mavis/svelte/team/README.md +5 -0
- package/presets/opencode/android-kotlin/OPENCODE.md +1 -1
- package/presets/opencode/android-kotlin/README.md +1 -1
- package/presets/opencode/android-kotlin/adapter-map.json +11 -3
- package/presets/opencode/android-kotlin/hooks/README.md +3 -2
- package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +57 -3
- package/presets/opencode/android-kotlin/team/README.md +5 -0
- package/presets/opencode/go/OPENCODE.md +1 -1
- package/presets/opencode/go/README.md +1 -1
- package/presets/opencode/go/adapter-map.json +11 -3
- package/presets/opencode/go/hooks/README.md +3 -2
- package/presets/opencode/go/hooks/chain-team-phases.sh +57 -3
- package/presets/opencode/go/team/README.md +5 -0
- package/presets/opencode/ios-swift/OPENCODE.md +1 -1
- package/presets/opencode/ios-swift/README.md +1 -1
- package/presets/opencode/ios-swift/adapter-map.json +11 -3
- package/presets/opencode/ios-swift/hooks/README.md +3 -2
- package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +57 -3
- package/presets/opencode/ios-swift/team/README.md +5 -0
- package/presets/opencode/java/OPENCODE.md +1 -1
- package/presets/opencode/java/README.md +1 -1
- package/presets/opencode/java/adapter-map.json +11 -3
- package/presets/opencode/java/hooks/README.md +3 -2
- package/presets/opencode/java/hooks/chain-team-phases.sh +57 -3
- package/presets/opencode/java/team/README.md +5 -0
- package/presets/opencode/mcp-ts/OPENCODE.md +1 -1
- package/presets/opencode/mcp-ts/README.md +1 -1
- package/presets/opencode/mcp-ts/adapter-map.json +11 -3
- package/presets/opencode/mcp-ts/hooks/README.md +3 -2
- package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +57 -3
- package/presets/opencode/mcp-ts/team/README.md +5 -0
- package/presets/opencode/mol/OPENCODE.md +1 -1
- package/presets/opencode/mol/README.md +1 -1
- package/presets/opencode/mol/adapter-map.json +11 -3
- package/presets/opencode/mol/hooks/README.md +3 -2
- package/presets/opencode/mol/hooks/chain-team-phases.sh +57 -3
- package/presets/opencode/mol/team/README.md +5 -0
- package/presets/opencode/next/OPENCODE.md +1 -1
- package/presets/opencode/next/README.md +1 -1
- package/presets/opencode/next/adapter-map.json +67 -3
- package/presets/opencode/next/agents/build-verifier.md +2 -0
- package/presets/opencode/next/agents/code-reviewer.md +2 -0
- package/presets/opencode/next/agents/feature-developer.md +1 -0
- package/presets/opencode/next/agents/task-analyst.md +4 -0
- package/presets/opencode/next/agents/task-router.md +5 -3
- package/presets/opencode/next/commands/README.md +1 -0
- package/presets/opencode/next/commands/task-continue.md +1 -1
- package/presets/opencode/next/commands/upstream-research.md +26 -0
- package/presets/opencode/next/hooks/README.md +3 -2
- package/presets/opencode/next/hooks/chain-team-phases.sh +57 -3
- package/presets/opencode/next/team/README.md +23 -0
- package/presets/opencode/next/team/upstream/config.json +31 -0
- package/presets/opencode/next/team/upstream/digest-template.md +55 -0
- package/presets/opencode/next/team/upstream/opencode.json +34 -0
- package/presets/opencode/next/team/upstream/projects.json +4 -0
- package/presets/opencode/next/team/upstream/prompt.md +77 -0
- package/presets/opencode/next/team/upstream/signatures.json +9 -0
- package/presets/opencode/nuxt/OPENCODE.md +1 -1
- package/presets/opencode/nuxt/README.md +1 -1
- package/presets/opencode/nuxt/adapter-map.json +11 -3
- package/presets/opencode/nuxt/hooks/README.md +3 -2
- package/presets/opencode/nuxt/hooks/chain-team-phases.sh +57 -3
- package/presets/opencode/nuxt/team/README.md +5 -0
- package/presets/opencode/php-hexagonal/OPENCODE.md +1 -1
- package/presets/opencode/php-hexagonal/README.md +1 -1
- package/presets/opencode/php-hexagonal/adapter-map.json +11 -3
- package/presets/opencode/php-hexagonal/hooks/README.md +3 -2
- package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +57 -3
- package/presets/opencode/php-hexagonal/team/README.md +5 -0
- package/presets/opencode/php-laravel/OPENCODE.md +1 -1
- package/presets/opencode/php-laravel/README.md +1 -1
- package/presets/opencode/php-laravel/adapter-map.json +11 -3
- package/presets/opencode/php-laravel/hooks/README.md +3 -2
- package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +57 -3
- package/presets/opencode/php-laravel/team/README.md +5 -0
- package/presets/opencode/svelte/OPENCODE.md +1 -1
- package/presets/opencode/svelte/README.md +1 -1
- package/presets/opencode/svelte/adapter-map.json +11 -3
- package/presets/opencode/svelte/hooks/README.md +3 -2
- package/presets/opencode/svelte/hooks/chain-team-phases.sh +57 -3
- package/presets/opencode/svelte/team/README.md +5 -0
- package/presets/zcode/android-kotlin/adapter-map.json +11 -3
- package/presets/zcode/android-kotlin/hooks/README.md +2 -1
- package/presets/zcode/android-kotlin/hooks/chain-team-phases.sh +57 -3
- package/presets/zcode/android-kotlin/team/README.md +5 -0
- package/presets/zcode/go/adapter-map.json +11 -3
- package/presets/zcode/go/hooks/README.md +2 -1
- package/presets/zcode/go/hooks/chain-team-phases.sh +57 -3
- package/presets/zcode/go/team/README.md +5 -0
- package/presets/zcode/ios-swift/adapter-map.json +11 -3
- package/presets/zcode/ios-swift/hooks/README.md +2 -1
- package/presets/zcode/ios-swift/hooks/chain-team-phases.sh +57 -3
- package/presets/zcode/ios-swift/team/README.md +5 -0
- package/presets/zcode/java/adapter-map.json +11 -3
- package/presets/zcode/java/hooks/README.md +2 -1
- package/presets/zcode/java/hooks/chain-team-phases.sh +57 -3
- package/presets/zcode/java/team/README.md +5 -0
- package/presets/zcode/mcp-ts/adapter-map.json +11 -3
- package/presets/zcode/mcp-ts/hooks/README.md +2 -1
- package/presets/zcode/mcp-ts/hooks/chain-team-phases.sh +57 -3
- package/presets/zcode/mcp-ts/team/README.md +5 -0
- package/presets/zcode/mol/adapter-map.json +11 -3
- package/presets/zcode/mol/hooks/README.md +2 -1
- package/presets/zcode/mol/hooks/chain-team-phases.sh +57 -3
- package/presets/zcode/mol/team/README.md +5 -0
- package/presets/zcode/next/adapter-map.json +67 -3
- package/presets/zcode/next/agents/build-verifier.md +2 -0
- package/presets/zcode/next/agents/code-reviewer.md +2 -0
- package/presets/zcode/next/agents/feature-developer.md +1 -0
- package/presets/zcode/next/agents/task-analyst.md +4 -0
- package/presets/zcode/next/agents/task-router.md +5 -3
- package/presets/zcode/next/commands/README.md +1 -0
- package/presets/zcode/next/commands/task-continue.md +1 -1
- package/presets/zcode/next/commands/upstream-research.md +26 -0
- package/presets/zcode/next/hooks/README.md +2 -1
- package/presets/zcode/next/hooks/chain-team-phases.sh +57 -3
- package/presets/zcode/next/team/README.md +23 -0
- package/presets/zcode/next/team/upstream/config.json +31 -0
- package/presets/zcode/next/team/upstream/digest-template.md +55 -0
- package/presets/zcode/next/team/upstream/opencode.json +34 -0
- package/presets/zcode/next/team/upstream/projects.json +4 -0
- package/presets/zcode/next/team/upstream/prompt.md +77 -0
- package/presets/zcode/next/team/upstream/signatures.json +9 -0
- package/presets/zcode/nuxt/adapter-map.json +11 -3
- package/presets/zcode/nuxt/hooks/README.md +2 -1
- package/presets/zcode/nuxt/hooks/chain-team-phases.sh +57 -3
- package/presets/zcode/nuxt/team/README.md +5 -0
- package/presets/zcode/php-hexagonal/adapter-map.json +11 -3
- package/presets/zcode/php-hexagonal/hooks/README.md +2 -1
- package/presets/zcode/php-hexagonal/hooks/chain-team-phases.sh +57 -3
- package/presets/zcode/php-hexagonal/team/README.md +5 -0
- package/presets/zcode/php-laravel/adapter-map.json +11 -3
- package/presets/zcode/php-laravel/hooks/README.md +2 -1
- package/presets/zcode/php-laravel/hooks/chain-team-phases.sh +57 -3
- package/presets/zcode/php-laravel/team/README.md +5 -0
- package/presets/zcode/svelte/adapter-map.json +11 -3
- package/presets/zcode/svelte/hooks/README.md +2 -1
- package/presets/zcode/svelte/hooks/chain-team-phases.sh +57 -3
- package/presets/zcode/svelte/team/README.md +5 -0
- package/presets/claude/android-kotlin/hooks/guard-shell-command.sh +0 -103
- package/presets/claude/go/hooks/guard-shell-command.sh +0 -102
- package/presets/claude/mcp-ts/hooks/guard-shell-command.sh +0 -102
- package/presets/claude/php-hexagonal/hooks/guard-shell-command.sh +0 -103
- package/presets/claude/php-laravel/hooks/guard-shell-command.sh +0 -103
- package/presets/cursor/android-kotlin/hooks/guard-shell-command.sh +0 -80
- package/presets/cursor/go/hooks/guard-shell-command.sh +0 -79
- package/presets/cursor/ios-swift/hooks/guard-shell-command.sh +0 -79
- package/presets/cursor/java/hooks/guard-shell-command.sh +0 -80
- package/presets/cursor/mcp-ts/hooks/guard-shell-command.sh +0 -79
- package/presets/cursor/mol/hooks/guard-shell-command.sh +0 -77
- package/presets/cursor/next/hooks/guard-shell-command.sh +0 -77
- package/presets/cursor/nuxt/hooks/guard-shell-command.sh +0 -77
- package/presets/cursor/php-hexagonal/hooks/guard-shell-command.sh +0 -80
- package/presets/cursor/php-laravel/hooks/guard-shell-command.sh +0 -80
- package/presets/cursor/svelte/hooks/guard-shell-command.sh +0 -77
|
@@ -0,0 +1,2961 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* `upstream-research` — the engine module behind the shipped
|
|
4
|
+
* `upstream-research` scheduler job.
|
|
5
|
+
*
|
|
6
|
+
* The runner is the source of truth at
|
|
7
|
+
* `packages/ai-rules/presets/_shared/ai-local/scripts/upstream-research.mjs`;
|
|
8
|
+
* `.ai.local/scripts/upstream-research.mjs` is a generated dogfood mirror.
|
|
9
|
+
*
|
|
10
|
+
* Phase order (see `openspec/changes/2026-11-11-upstream-research-job/design.md`):
|
|
11
|
+
*
|
|
12
|
+
* 0. probe `opencode` on PATH and record its version — fail 10/11 first
|
|
13
|
+
* 1. load the registry, policy, cursor, prior art, and prior digests
|
|
14
|
+
* 2. select due projects (least recently scanned first) and name the tail
|
|
15
|
+
* 3. per project: resolve the clone, fetch, compute the window, cap the diff
|
|
16
|
+
* 4. compose the prompt, call the read-only agent, validate, verify evidence
|
|
17
|
+
* 5. dedupe against prior art, rank, cap at `budget.maxIdeas`
|
|
18
|
+
* 6. write `<runDir>/digest.md` and copy it to `docs/upstream/digest-<runId>.md`
|
|
19
|
+
* 7. commit `upstream/cursor.json` atomically, last
|
|
20
|
+
*
|
|
21
|
+
* The runner writes only `<runDir>/**`, `<teamRoot>/upstream/cursor.json`, and
|
|
22
|
+
* the committed digest copy. It never writes `status.json`, `metrics.json`,
|
|
23
|
+
* `run.json`, `stdout.log`, `stderr.log`, or `<runDir>/prompt.md` — the
|
|
24
|
+
* scheduler owns those.
|
|
25
|
+
*
|
|
26
|
+
* Exit codes: 0 ok, 2 usage, 10 `E_OPENCODE_MISSING`, 11 `E_OPENCODE_VERSION`,
|
|
27
|
+
* 12 `E_REGISTRY_INVALID` (registry, policy, or roots), 13
|
|
28
|
+
* `E_ALL_PROJECTS_FAILED`, 15 `E_DIGEST_WRITE_FAILED`, 16
|
|
29
|
+
* `E_WORKTREE_CHANGED`.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
import crypto from 'node:crypto';
|
|
33
|
+
import fs from 'node:fs';
|
|
34
|
+
import os from 'node:os';
|
|
35
|
+
import path from 'node:path';
|
|
36
|
+
import { spawnSync } from 'node:child_process';
|
|
37
|
+
import { fileURLToPath } from 'node:url';
|
|
38
|
+
|
|
39
|
+
/* --------------------------------- constants ------------------------------- */
|
|
40
|
+
|
|
41
|
+
export const SCHEMA_VERSION = 1;
|
|
42
|
+
export const PROJECTS_FILE = 'upstream/projects.json';
|
|
43
|
+
export const CONFIG_FILE = 'upstream/config.json';
|
|
44
|
+
export const CURSOR_FILE = 'upstream/cursor.json';
|
|
45
|
+
export const SIGNATURES_FILE = 'upstream/signatures.json';
|
|
46
|
+
export const PROMPT_FILE = 'upstream/prompt.md';
|
|
47
|
+
export const DIGEST_TEMPLATE_FILE = 'upstream/digest-template.md';
|
|
48
|
+
export const AGENT_CONFIG_FILE = 'upstream/opencode.json';
|
|
49
|
+
export const ATTRIBUTION_FILE = 'tasks/upstream-projects-attribution/upstream-sources.md';
|
|
50
|
+
export const RUNS_DIR = 'scheduler/runs/upstream-research';
|
|
51
|
+
export const DIGEST_DIR = 'docs/upstream';
|
|
52
|
+
|
|
53
|
+
export const EXIT_CODES = {
|
|
54
|
+
ok: 0,
|
|
55
|
+
usage: 2,
|
|
56
|
+
eOpencodeMissing: 10,
|
|
57
|
+
eOpencodeVersion: 11,
|
|
58
|
+
eRegistryInvalid: 12,
|
|
59
|
+
eAllProjectsFailed: 13,
|
|
60
|
+
eDigestWriteFailed: 15,
|
|
61
|
+
eWorktreeChanged: 16,
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
export const RUNNER_CODES = {
|
|
65
|
+
opencodeMissing: 'E_OPENCODE_MISSING',
|
|
66
|
+
opencodeVersion: 'E_OPENCODE_VERSION',
|
|
67
|
+
agentConfigInvalid: 'E_AGENT_CONFIG_INVALID',
|
|
68
|
+
registryInvalid: 'E_REGISTRY_INVALID',
|
|
69
|
+
allProjectsFailed: 'E_ALL_PROJECTS_FAILED',
|
|
70
|
+
digestWriteFailed: 'E_DIGEST_WRITE_FAILED',
|
|
71
|
+
worktreeChanged: 'E_WORKTREE_CHANGED',
|
|
72
|
+
projectNoClone: 'E_PROJECT_NO_CLONE',
|
|
73
|
+
fetchFailed: 'E_FETCH_FAILED',
|
|
74
|
+
refUnresolved: 'E_REF_UNRESOLVED',
|
|
75
|
+
agentTimeout: 'E_AGENT_TIMEOUT',
|
|
76
|
+
agentFailed: 'E_AGENT_FAILED',
|
|
77
|
+
agentOutputInvalid: 'E_AGENT_OUTPUT_INVALID',
|
|
78
|
+
upstreamDirty: 'E_UPSTREAM_DIRTY',
|
|
79
|
+
projectPromptTooLarge: 'E_PROJECT_PROMPT_TOO_LARGE',
|
|
80
|
+
evidenceUnverified: 'E_EVIDENCE_UNVERIFIED',
|
|
81
|
+
answerShape: 'E_ANSWER_SHAPE',
|
|
82
|
+
answerEnum: 'E_ANSWER_ENUM',
|
|
83
|
+
answerRange: 'E_ANSWER_RANGE',
|
|
84
|
+
answerEvidence: 'E_ANSWER_EVIDENCE',
|
|
85
|
+
priorArtUnmapped: 'E_PRIOR_ART_UNMAPPED',
|
|
86
|
+
illegalTransition: 'E_ILLEGAL_TRANSITION',
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
export const REMEDIES = {
|
|
90
|
+
[RUNNER_CODES.opencodeMissing]:
|
|
91
|
+
'opencode was not found on PATH; install it (https://opencode.ai/docs) or add its directory to PATH, then re-run.',
|
|
92
|
+
[RUNNER_CODES.opencodeVersion]:
|
|
93
|
+
'expected "opencode v<semver>"; upgrade opencode or remove the wrapper on PATH, then re-run.',
|
|
94
|
+
[RUNNER_CODES.agentConfigInvalid]:
|
|
95
|
+
'verify with `opencode debug agents` from .ai.local/team/upstream; upgrade `opencode`, reinstall with `ai-rules update`, or restore .ai.local/team/upstream/opencode.json from the preset, then re-run.',
|
|
96
|
+
[RUNNER_CODES.registryInvalid]:
|
|
97
|
+
'fix the named field in .ai.local/team/upstream/projects.json or config.json, then re-run; no partial digest was written.',
|
|
98
|
+
[RUNNER_CODES.digestWriteFailed]:
|
|
99
|
+
'make docs/upstream/ writable, then re-run; the run-tree digest exists and the cursor was not committed.',
|
|
100
|
+
[RUNNER_CODES.worktreeChanged]:
|
|
101
|
+
'commit or stash the repository change and re-run; set agent.worktreeGuard=false only when the change is expected.',
|
|
102
|
+
[RUNNER_CODES.projectNoClone]:
|
|
103
|
+
'clone the project into ../ai-rules-research/<id> (git clone --depth 50 <url>) or disable it in projects.json.',
|
|
104
|
+
[RUNNER_CODES.fetchFailed]:
|
|
105
|
+
'check the remote and the ref in projects.json; the cursor was left untouched and the next run rescans the same window.',
|
|
106
|
+
[RUNNER_CODES.refUnresolved]:
|
|
107
|
+
'check refs.branch in projects.json against the remote; the project keeps its previous cursor.',
|
|
108
|
+
[RUNNER_CODES.agentFailed]:
|
|
109
|
+
'run the project manually once to inspect the agent output; the project keeps its previous cursor.',
|
|
110
|
+
[RUNNER_CODES.agentOutputInvalid]:
|
|
111
|
+
'inspect the captured answer stream; one retry already ran and the project keeps its previous cursor.',
|
|
112
|
+
[RUNNER_CODES.upstreamDirty]:
|
|
113
|
+
'restore or commit the change inside the upstream clone; research is read-only.',
|
|
114
|
+
[RUNNER_CODES.projectPromptTooLarge]:
|
|
115
|
+
'lower the diff cap (scan.maxDiffBytes) or narrow scopeHints.paths for this project.',
|
|
116
|
+
[RUNNER_CODES.agentTimeout]:
|
|
117
|
+
'raise budget.projectTimeoutMs or agent.timeoutMs within their bounds, or disable the project.',
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
export const OPENCODE_VERSION_RE = /\bopencode\s+v(\d+\.\d+\.\d+)/;
|
|
121
|
+
|
|
122
|
+
const DEFAULT_VERSION_TIMEOUT_MS = 10_000;
|
|
123
|
+
|
|
124
|
+
/** The agent the job invokes; its resolved permission rules are asserted at run time. */
|
|
125
|
+
export const AGENT_ID = 'upstream-researcher';
|
|
126
|
+
|
|
127
|
+
/** Actions that must resolve to `deny` on the installed agent before any project runs. */
|
|
128
|
+
export const AGENT_READ_ONLY_ACTIONS = [
|
|
129
|
+
'edit',
|
|
130
|
+
'shell',
|
|
131
|
+
'webfetch',
|
|
132
|
+
'websearch',
|
|
133
|
+
'subagent',
|
|
134
|
+
'external_directory',
|
|
135
|
+
'read',
|
|
136
|
+
'glob',
|
|
137
|
+
'grep',
|
|
138
|
+
'list',
|
|
139
|
+
];
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* A synthetic tool name that is not one of the ten built-ins. Permission keys
|
|
143
|
+
* are matched against the underlying tool name, so MCP servers resolve as
|
|
144
|
+
* `<server>_<tool>` (e.g. `chrome-devtools_new_page`); this probe proves the
|
|
145
|
+
* installed config denies the whole namespace instead of an enumeration.
|
|
146
|
+
*/
|
|
147
|
+
export const AGENT_PROBE_ACTION = 'mcp_probe_unlisted_tool';
|
|
148
|
+
|
|
149
|
+
/** A conservative git ref name: `HEAD` or an alphanumeric-led branch/tag. */
|
|
150
|
+
export const REF_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._/-]*$/;
|
|
151
|
+
|
|
152
|
+
/** A full commit id as stored in the cursor and answers. */
|
|
153
|
+
export const COMMIT_SHA_RE = /^[0-9a-f]{40,64}$/i;
|
|
154
|
+
|
|
155
|
+
const USAGE = `usage:
|
|
156
|
+
upstream-research.mjs --prompt <runDir/prompt.md> --team-root <dir> --repo-root <dir>
|
|
157
|
+
upstream-research.mjs registry --check --team-root <dir> [--json]
|
|
158
|
+
upstream-research.mjs signatures --check --team-root <dir> [--repo-root <dir>] [--json]
|
|
159
|
+
upstream-research.mjs signatures --write --team-root <dir> [--repo-root <dir>] [--json]
|
|
160
|
+
upstream-research.mjs --help`;
|
|
161
|
+
|
|
162
|
+
/* ---------------------------------- errors --------------------------------- */
|
|
163
|
+
|
|
164
|
+
/** A runner failure with a stable code, an exit code, and one remedy line. */
|
|
165
|
+
export class UpstreamError extends Error {
|
|
166
|
+
/**
|
|
167
|
+
* @param {string} code one of `RUNNER_CODES`
|
|
168
|
+
* @param {string} message short human sentence
|
|
169
|
+
* @param {{ exitCode?: number, remedy?: string, findings?: Array<{code:string,field:string,message:string}> }} [options]
|
|
170
|
+
*/
|
|
171
|
+
constructor(code, message, options = {}) {
|
|
172
|
+
super(message);
|
|
173
|
+
this.name = 'UpstreamError';
|
|
174
|
+
this.code = code;
|
|
175
|
+
this.exitCode = options.exitCode ?? EXIT_CODES.eRegistryInvalid;
|
|
176
|
+
this.remedy = options.remedy ?? REMEDIES[code] ?? '';
|
|
177
|
+
this.findings = options.findings ?? [];
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/* --------------------------------- helpers --------------------------------- */
|
|
182
|
+
|
|
183
|
+
const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
184
|
+
|
|
185
|
+
/** Hex sha256 of a buffer or string. */
|
|
186
|
+
export function sha256(value) {
|
|
187
|
+
return crypto.createHash('sha256').update(value).digest('hex');
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Read JSON, returning `{ value }` or `{ error }` instead of throwing. */
|
|
191
|
+
export function readJsonFile(filePath) {
|
|
192
|
+
try {
|
|
193
|
+
return { value: JSON.parse(fs.readFileSync(filePath, 'utf8')) };
|
|
194
|
+
} catch (error) {
|
|
195
|
+
return { error: error instanceof Error ? error.message : String(error) };
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Write JSON with a trailing newline, creating the parent directory. */
|
|
200
|
+
export function writeJsonFile(filePath, value) {
|
|
201
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
202
|
+
fs.writeFileSync(filePath, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Write a file atomically enough for a single writer: temp file, then rename. */
|
|
206
|
+
export function writeFileAtomic(filePath, content) {
|
|
207
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
208
|
+
const temp = `${filePath}.tmp-${process.pid}-${Date.now()}`;
|
|
209
|
+
fs.writeFileSync(temp, content, 'utf8');
|
|
210
|
+
fs.renameSync(temp, filePath);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const defaultIo = () => ({
|
|
214
|
+
stdout: (line) => process.stdout.write(`${line}\n`),
|
|
215
|
+
stderr: (line) => process.stderr.write(`${line}\n`),
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
/** Parse the runner's own argv. No shell, no reordering. */
|
|
219
|
+
export function parseArgs(argv) {
|
|
220
|
+
const options = {
|
|
221
|
+
command: 'run',
|
|
222
|
+
prompt: null,
|
|
223
|
+
teamRoot: null,
|
|
224
|
+
repoRoot: null,
|
|
225
|
+
check: false,
|
|
226
|
+
write: false,
|
|
227
|
+
json: false,
|
|
228
|
+
help: false,
|
|
229
|
+
};
|
|
230
|
+
const args = [...argv];
|
|
231
|
+
if (args[0] === 'registry' || args[0] === 'signatures') {
|
|
232
|
+
options.command = args.shift();
|
|
233
|
+
}
|
|
234
|
+
const valueFlags = {
|
|
235
|
+
'--prompt': 'prompt',
|
|
236
|
+
'--team-root': 'teamRoot',
|
|
237
|
+
'--repo-root': 'repoRoot',
|
|
238
|
+
};
|
|
239
|
+
const booleanFlags = {
|
|
240
|
+
'--check': 'check',
|
|
241
|
+
'--write': 'write',
|
|
242
|
+
'--json': 'json',
|
|
243
|
+
'--help': 'help',
|
|
244
|
+
'-h': 'help',
|
|
245
|
+
};
|
|
246
|
+
while (args.length > 0) {
|
|
247
|
+
const arg = args.shift();
|
|
248
|
+
if (valueFlags[arg]) {
|
|
249
|
+
const value = args.shift();
|
|
250
|
+
if (value === undefined) throw new UpstreamError(RUNNER_CODES.registryInvalid, `${arg} needs a value`, { exitCode: EXIT_CODES.usage });
|
|
251
|
+
options[valueFlags[arg]] = value;
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
if (booleanFlags[arg]) {
|
|
255
|
+
options[booleanFlags[arg]] = true;
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
258
|
+
throw new UpstreamError(RUNNER_CODES.registryInvalid, `unknown argument: ${arg}`, { exitCode: EXIT_CODES.usage });
|
|
259
|
+
}
|
|
260
|
+
return options;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Resolve `name` on PATH without a shell. Returns an absolute path or `null`. */
|
|
264
|
+
export function resolveOnPath(name, { env = process.env } = {}) {
|
|
265
|
+
if (name.includes(path.sep) || (process.platform === 'win32' && name.includes('/'))) {
|
|
266
|
+
return fs.existsSync(name) ? path.resolve(name) : null;
|
|
267
|
+
}
|
|
268
|
+
const extensions =
|
|
269
|
+
process.platform === 'win32'
|
|
270
|
+
? (env.PATHEXT || '.EXE;.CMD;.BAT;.COM').split(';').filter(Boolean)
|
|
271
|
+
: [''];
|
|
272
|
+
for (const entry of (env.PATH || '').split(path.delimiter)) {
|
|
273
|
+
if (!entry) continue;
|
|
274
|
+
for (const extension of extensions) {
|
|
275
|
+
const candidate = path.join(entry, `${name}${extension}`);
|
|
276
|
+
try {
|
|
277
|
+
if (!fs.statSync(candidate).isFile()) continue;
|
|
278
|
+
fs.accessSync(candidate, fs.constants.X_OK);
|
|
279
|
+
return path.resolve(candidate);
|
|
280
|
+
} catch {
|
|
281
|
+
// Not this entry; keep walking.
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
return null;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* The child environment for every tool the runner spawns. Nothing else is
|
|
290
|
+
* inherited: a secret in the operator's environment must not reach `opencode`.
|
|
291
|
+
*/
|
|
292
|
+
export function minimalEnv(env) {
|
|
293
|
+
const childEnv = {};
|
|
294
|
+
for (const name of ['PATH', 'HOME', 'TMPDIR', 'LANG', 'TZ']) {
|
|
295
|
+
if (env[name] !== undefined) childEnv[name] = env[name];
|
|
296
|
+
}
|
|
297
|
+
return childEnv;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Probe the agent binary before any project, cursor, or digest write.
|
|
302
|
+
*
|
|
303
|
+
* @returns {{capability: {resolvedPath: string, version: string, versionRaw: string, probedAt: string, exitCode: number, durationMs: number}}}
|
|
304
|
+
* @throws {UpstreamError} `E_OPENCODE_MISSING` (10) or `E_OPENCODE_VERSION` (11)
|
|
305
|
+
*/
|
|
306
|
+
export function probeOpencode({ env = process.env, now = () => new Date().toISOString(), timeoutMs = DEFAULT_VERSION_TIMEOUT_MS } = {}) {
|
|
307
|
+
const probedAt = now();
|
|
308
|
+
const resolvedPath = resolveOnPath('opencode', { env });
|
|
309
|
+
if (!resolvedPath) {
|
|
310
|
+
throw new UpstreamError(RUNNER_CODES.opencodeMissing, 'opencode was not found on PATH', {
|
|
311
|
+
exitCode: EXIT_CODES.eOpencodeMissing,
|
|
312
|
+
remedy: REMEDIES[RUNNER_CODES.opencodeMissing],
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
const started = Date.now();
|
|
316
|
+
const result = spawnSync(resolvedPath, ['--version'], {
|
|
317
|
+
timeout: timeoutMs,
|
|
318
|
+
encoding: 'utf8',
|
|
319
|
+
env: minimalEnv(env),
|
|
320
|
+
});
|
|
321
|
+
const durationMs = Date.now() - started;
|
|
322
|
+
const raw = `${result.stdout || ''}`.trim().split('\n').find((line) => line.trim().length > 0) ?? 'no output';
|
|
323
|
+
const match = raw.match(OPENCODE_VERSION_RE);
|
|
324
|
+
const capability = {
|
|
325
|
+
resolvedPath,
|
|
326
|
+
version: match ? match[1] : null,
|
|
327
|
+
versionRaw: raw,
|
|
328
|
+
probedAt,
|
|
329
|
+
exitCode: result.status === null ? -1 : result.status,
|
|
330
|
+
durationMs,
|
|
331
|
+
};
|
|
332
|
+
if (result.error || result.status !== 0 || !match) {
|
|
333
|
+
const remedy = `${capability.versionRaw}; expected "opencode v<semver>". Upgrade opencode or remove the wrapper on PATH, then re-run.`;
|
|
334
|
+
throw Object.assign(
|
|
335
|
+
new UpstreamError(
|
|
336
|
+
RUNNER_CODES.opencodeVersion,
|
|
337
|
+
`opencode --version did not report "opencode v<semver>": ${capability.versionRaw}`,
|
|
338
|
+
{ exitCode: EXIT_CODES.eOpencodeVersion, remedy },
|
|
339
|
+
),
|
|
340
|
+
{ capability },
|
|
341
|
+
);
|
|
342
|
+
}
|
|
343
|
+
return { capability };
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Parse the `opencode debug agents` JSON and return one agent's resolved rules.
|
|
348
|
+
* `null` means the agent is absent or the output is not the expected array.
|
|
349
|
+
*/
|
|
350
|
+
export function readResolvedAgentPermissions(stdout, agentId = AGENT_ID) {
|
|
351
|
+
let agents;
|
|
352
|
+
try {
|
|
353
|
+
agents = JSON.parse(`${stdout}`);
|
|
354
|
+
} catch {
|
|
355
|
+
return null;
|
|
356
|
+
}
|
|
357
|
+
if (!Array.isArray(agents)) return null;
|
|
358
|
+
const agent = agents.find((entry) => isRecord(entry) && entry.id === agentId);
|
|
359
|
+
if (!agent || !Array.isArray(agent.permissions)) return null;
|
|
360
|
+
return agent.permissions.filter(
|
|
361
|
+
(rule) => isRecord(rule) && typeof rule.action === 'string' && typeof rule.effect === 'string',
|
|
362
|
+
);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Ordered rules: the last rule that matches the action decides its effect.
|
|
367
|
+
* Only a `deny` that covers every resource (`*`) counts, because a
|
|
368
|
+
* resource-scoped deny (e.g. `read: {"*.env": "deny"}`) leaves every other
|
|
369
|
+
* path at the preceding effect and must not pass the read-only assertion.
|
|
370
|
+
*/
|
|
371
|
+
export function isDeniedByResolvedRules(permissions, action) {
|
|
372
|
+
let deciding = null;
|
|
373
|
+
for (const rule of permissions) {
|
|
374
|
+
if (rule.action === action || rule.action === '*') deciding = rule;
|
|
375
|
+
}
|
|
376
|
+
return Boolean(deciding) && deciding.effect === 'deny' && deciding.resource === '*';
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* Assert that the installed (nested) agent config denies every tool: the ten
|
|
381
|
+
* built-ins and a synthetic non-built-in name, which only passes when the map
|
|
382
|
+
* carries a global `"*": "deny"`. A discovered config that appends an allow
|
|
383
|
+
* after the preset deny is caught here, before any project runs.
|
|
384
|
+
*
|
|
385
|
+
* @throws {UpstreamError} `E_AGENT_CONFIG_INVALID` (12)
|
|
386
|
+
*/
|
|
387
|
+
export function assertAgentReadOnly({
|
|
388
|
+
teamRoot,
|
|
389
|
+
binaryPath,
|
|
390
|
+
env = process.env,
|
|
391
|
+
timeoutMs = DEFAULT_VERSION_TIMEOUT_MS,
|
|
392
|
+
spawn = spawnSync,
|
|
393
|
+
}) {
|
|
394
|
+
const cwd = path.join(teamRoot, 'upstream');
|
|
395
|
+
const result = spawn(binaryPath, ['debug', 'agents'], {
|
|
396
|
+
cwd,
|
|
397
|
+
encoding: 'utf8',
|
|
398
|
+
timeout: timeoutMs,
|
|
399
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
400
|
+
env: minimalEnv(env),
|
|
401
|
+
});
|
|
402
|
+
const permissions =
|
|
403
|
+
result && result.status === 0 ? readResolvedAgentPermissions(result.stdout, AGENT_ID) : null;
|
|
404
|
+
if (permissions === null) {
|
|
405
|
+
throw new UpstreamError(
|
|
406
|
+
RUNNER_CODES.agentConfigInvalid,
|
|
407
|
+
`cannot resolve "${AGENT_ID}" with "opencode debug agents"; the read-only config was not installed or this opencode build is too old`,
|
|
408
|
+
{ exitCode: EXIT_CODES.eRegistryInvalid },
|
|
409
|
+
);
|
|
410
|
+
}
|
|
411
|
+
const required = [...AGENT_READ_ONLY_ACTIONS, AGENT_PROBE_ACTION];
|
|
412
|
+
const missing = required.filter((action) => !isDeniedByResolvedRules(permissions, action));
|
|
413
|
+
if (missing.length > 0) {
|
|
414
|
+
throw new UpstreamError(
|
|
415
|
+
RUNNER_CODES.agentConfigInvalid,
|
|
416
|
+
`the installed ${AGENT_ID} agent does not deny every tool (missing: ${missing.join(', ')}); its permission map must carry a global "*": "deny"`,
|
|
417
|
+
{ exitCode: EXIT_CODES.eRegistryInvalid },
|
|
418
|
+
);
|
|
419
|
+
}
|
|
420
|
+
return { agent: AGENT_ID, actions: required };
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/** Paths this run writes, all derived from the frozen job's argv. */
|
|
424
|
+
export function resolveRunPaths({ promptPath, teamRoot, repoRoot }) {
|
|
425
|
+
const absolutePrompt = path.resolve(promptPath);
|
|
426
|
+
const runDir = path.dirname(absolutePrompt);
|
|
427
|
+
const runId = path.basename(runDir);
|
|
428
|
+
return {
|
|
429
|
+
promptPath: absolutePrompt,
|
|
430
|
+
runDir,
|
|
431
|
+
runId,
|
|
432
|
+
teamRoot: path.resolve(teamRoot),
|
|
433
|
+
repoRoot: path.resolve(repoRoot),
|
|
434
|
+
projectsDir: path.join(runDir, 'projects'),
|
|
435
|
+
reportPath: path.join(runDir, 'report.json'),
|
|
436
|
+
digestPath: path.join(runDir, 'digest.md'),
|
|
437
|
+
progressPath: path.join(runDir, 'progress.jsonl'),
|
|
438
|
+
cursorPath: path.join(path.resolve(teamRoot), CURSOR_FILE),
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** The scheduler's run-id shape; also keeps control characters out of the digest header. */
|
|
443
|
+
export const RUN_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
444
|
+
|
|
445
|
+
/**
|
|
446
|
+
* Confine the run envelope: `--prompt` must be
|
|
447
|
+
* `<teamRoot>/scheduler/runs/upstream-research/<runId>/prompt.md`. A caller
|
|
448
|
+
* cannot move the run tree, the cursor sibling, or the digest target.
|
|
449
|
+
*/
|
|
450
|
+
export function validateRunPaths({ paths }) {
|
|
451
|
+
const runsRoot = path.join(paths.teamRoot, RUNS_DIR);
|
|
452
|
+
const relative = path.relative(runsRoot, paths.runDir);
|
|
453
|
+
const confined =
|
|
454
|
+
RUN_ID_RE.test(relative) &&
|
|
455
|
+
relative !== '.' &&
|
|
456
|
+
!relative.startsWith('..') &&
|
|
457
|
+
!path.isAbsolute(relative) &&
|
|
458
|
+
!relative.includes(path.sep);
|
|
459
|
+
if (!confined || path.basename(paths.promptPath) !== 'prompt.md') {
|
|
460
|
+
throw new UpstreamError(RUNNER_CODES.registryInvalid, 'invalid run envelope', {
|
|
461
|
+
exitCode: EXIT_CODES.eRegistryInvalid,
|
|
462
|
+
findings: [
|
|
463
|
+
{
|
|
464
|
+
code: RUNNER_CODES.registryInvalid,
|
|
465
|
+
field: '--prompt',
|
|
466
|
+
message: `must be ${RUNS_DIR}/<runId>/prompt.md inside --team-root`,
|
|
467
|
+
},
|
|
468
|
+
],
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** Validate the two roots before any write. */
|
|
474
|
+
export function validateRoots({ teamRoot, repoRoot }) {
|
|
475
|
+
const findings = [];
|
|
476
|
+
const teamRootOk = fs.existsSync(teamRoot) && fs.statSync(teamRoot).isDirectory();
|
|
477
|
+
const repoRootOk = fs.existsSync(repoRoot) && fs.statSync(repoRoot).isDirectory();
|
|
478
|
+
if (!teamRootOk) findings.push({ code: RUNNER_CODES.registryInvalid, field: 'teamRoot', message: `${teamRoot} is not a directory` });
|
|
479
|
+
if (!repoRootOk) findings.push({ code: RUNNER_CODES.registryInvalid, field: 'repoRoot', message: `${repoRoot} is not a directory` });
|
|
480
|
+
if (teamRootOk && repoRootOk) {
|
|
481
|
+
const relative = path.relative(repoRoot, teamRoot);
|
|
482
|
+
if (relative.startsWith('..') || path.isAbsolute(relative)) {
|
|
483
|
+
findings.push({ code: RUNNER_CODES.registryInvalid, field: 'teamRoot', message: `${teamRoot} is outside --repo-root ${repoRoot}` });
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
if (findings.length > 0) {
|
|
487
|
+
throw new UpstreamError(RUNNER_CODES.registryInvalid, 'invalid run roots', {
|
|
488
|
+
exitCode: EXIT_CODES.eRegistryInvalid,
|
|
489
|
+
findings,
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/** Write the run report; failures here must never mask the real code. */
|
|
495
|
+
export function writeReport(runDir, report) {
|
|
496
|
+
try {
|
|
497
|
+
writeJsonFile(path.join(runDir, 'report.json'), report);
|
|
498
|
+
return true;
|
|
499
|
+
} catch {
|
|
500
|
+
return false;
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** Read the scheduler's run manifest read-only, when it exists. */
|
|
505
|
+
export function readRunManifest(runDir) {
|
|
506
|
+
const file = path.join(runDir, 'run.json');
|
|
507
|
+
const result = readJsonFile(file);
|
|
508
|
+
if (result.error || !isRecord(result.value)) {
|
|
509
|
+
return { trigger: 'schedule', revision: 1 };
|
|
510
|
+
}
|
|
511
|
+
return {
|
|
512
|
+
trigger: typeof result.value.trigger === 'string' ? result.value.trigger : 'schedule',
|
|
513
|
+
revision: Number.isInteger(result.value.revision) ? result.value.revision : 1,
|
|
514
|
+
};
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/* ------------------------------ WP2 — schema ------------------------------- */
|
|
518
|
+
|
|
519
|
+
export const PROJECT_ID_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
520
|
+
export const FETCH_KINDS = ['clone', 'remote'];
|
|
521
|
+
export const CADENCES = ['weekly', 'biweekly', 'monthly'];
|
|
522
|
+
export const CADENCE_DAYS = { weekly: 7, biweekly: 14, monthly: 30 };
|
|
523
|
+
|
|
524
|
+
export const REGISTRY_BOUNDS = {
|
|
525
|
+
maxProjects: 100,
|
|
526
|
+
idMax: 48,
|
|
527
|
+
titleMax: 120,
|
|
528
|
+
urlMax: 300,
|
|
529
|
+
branchMax: 120,
|
|
530
|
+
scopePathsMax: 20,
|
|
531
|
+
scopePathMax: 200,
|
|
532
|
+
scopeNotesMax: 2000,
|
|
533
|
+
notesMax: 2000,
|
|
534
|
+
};
|
|
535
|
+
|
|
536
|
+
const PROJECT_KEYS = new Set([
|
|
537
|
+
'id',
|
|
538
|
+
'title',
|
|
539
|
+
'url',
|
|
540
|
+
'enabled',
|
|
541
|
+
'fetchStrategy',
|
|
542
|
+
'refs',
|
|
543
|
+
'cadence',
|
|
544
|
+
'priority',
|
|
545
|
+
'scopeHints',
|
|
546
|
+
'notes',
|
|
547
|
+
]);
|
|
548
|
+
const FETCH_KEYS = new Set(['kind', 'path']);
|
|
549
|
+
const REFS_KEYS = new Set(['branch', 'tags', 'releases']);
|
|
550
|
+
const SCOPE_KEYS = new Set(['paths', 'notes']);
|
|
551
|
+
|
|
552
|
+
/**
|
|
553
|
+
* Policy defaults and bounds, transcribed from `design.md` § Policy schema.
|
|
554
|
+
* A cap is data: every consumer reads it from the loaded `config`.
|
|
555
|
+
*/
|
|
556
|
+
export const CONFIG_BOUNDS = {
|
|
557
|
+
'budget.maxProjects': { default: 5, min: 1, max: 20, integer: true },
|
|
558
|
+
'budget.totalBudgetMs': { default: 3_600_000, min: 600_000, max: 7_200_000, integer: true },
|
|
559
|
+
'budget.projectTimeoutMs': { default: 1_200_000, min: 60_000, max: 1_800_000, integer: true },
|
|
560
|
+
'budget.minProjectBudgetMs': { default: 300_000, min: 60_000, max: 600_000, integer: true },
|
|
561
|
+
'budget.maxIdeas': { default: 3, min: 1, max: 10, integer: true },
|
|
562
|
+
'budget.maxIdeasPerProject': { default: 4, min: 1, max: 8, integer: true },
|
|
563
|
+
'budget.maxConsecutiveAgentFailures': { default: 2, min: 1, max: 5, integer: true },
|
|
564
|
+
'scan.baselineCommits': { default: 20, min: 1, max: 100, integer: true },
|
|
565
|
+
'scan.maxCommitsInWindow': { default: 100, min: 10, max: 500, integer: true },
|
|
566
|
+
'scan.maxDiffBytes': { default: 262_144, min: 16_384, max: 1_048_576, integer: true },
|
|
567
|
+
'scan.fetchTimeoutMs': { default: 120_000, min: 10_000, max: 600_000, integer: true },
|
|
568
|
+
'scan.maxChangelogBytes': { default: 32_768, min: 4_096, max: 262_144, integer: true },
|
|
569
|
+
'agent.timeoutMs': { default: 1_200_000, min: 60_000, max: 1_800_000, integer: true },
|
|
570
|
+
'agent.maxOutputBytes': { default: 1_048_576, min: 65_536, max: 8_388_608, integer: true },
|
|
571
|
+
'agent.model': { default: null, type: 'string-or-null', maxLength: 120 },
|
|
572
|
+
'agent.worktreeGuard': { default: true, type: 'boolean' },
|
|
573
|
+
'digest.path': { default: 'docs/upstream/digest-<runId>.md', type: 'string' },
|
|
574
|
+
'artifacts.maxRunBytes': { default: 8_388_608, min: 1, max: 67_108_864, integer: true },
|
|
575
|
+
};
|
|
576
|
+
|
|
577
|
+
const CONFIG_GROUPS = ['budget', 'scan', 'agent', 'digest', 'artifacts'];
|
|
578
|
+
|
|
579
|
+
function registryFailure(findings, message = 'registry failed validation') {
|
|
580
|
+
return new UpstreamError(RUNNER_CODES.registryInvalid, message, {
|
|
581
|
+
exitCode: EXIT_CODES.eRegistryInvalid,
|
|
582
|
+
findings,
|
|
583
|
+
});
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/** A conservative ref name: no leading option, no `..`, no `@{`, no whitespace. */
|
|
587
|
+
export function isValidRefName(value) {
|
|
588
|
+
return (
|
|
589
|
+
typeof value === 'string' &&
|
|
590
|
+
value.length > 0 &&
|
|
591
|
+
value.length <= REGISTRY_BOUNDS.branchMax &&
|
|
592
|
+
REF_NAME_RE.test(value) &&
|
|
593
|
+
!value.includes('..') &&
|
|
594
|
+
!value.includes('@{') &&
|
|
595
|
+
!value.includes('//') &&
|
|
596
|
+
!value.endsWith('/') &&
|
|
597
|
+
!value.endsWith('.lock')
|
|
598
|
+
);
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/** Validate and normalize `projects.json`. Unknown keys are refused at every level. */
|
|
602
|
+
export function validateRegistry(raw) {
|
|
603
|
+
const findings = [];
|
|
604
|
+
const add = (code, field, message) => findings.push({ code, field, message });
|
|
605
|
+
if (!isRecord(raw)) {
|
|
606
|
+
throw registryFailure([{ code: 'E_REGISTRY_SHAPE', field: 'projects.json', message: 'must be a JSON object' }]);
|
|
607
|
+
}
|
|
608
|
+
for (const key of Object.keys(raw)) {
|
|
609
|
+
if (!['schemaVersion', 'projects'].includes(key)) add('E_REGISTRY_KEY', key, 'unknown top-level key');
|
|
610
|
+
}
|
|
611
|
+
if (raw.schemaVersion !== SCHEMA_VERSION) {
|
|
612
|
+
add('E_REGISTRY_VERSION', 'schemaVersion', `must be ${SCHEMA_VERSION}; no silent migration is performed`);
|
|
613
|
+
}
|
|
614
|
+
if (!Array.isArray(raw.projects)) {
|
|
615
|
+
add('E_REGISTRY_SHAPE', 'projects', 'must be an array');
|
|
616
|
+
}
|
|
617
|
+
if (findings.length > 0) throw registryFailure(findings);
|
|
618
|
+
if (raw.projects.length > REGISTRY_BOUNDS.maxProjects) {
|
|
619
|
+
add('E_REGISTRY_COUNT', 'projects', `at most ${REGISTRY_BOUNDS.maxProjects} entries are allowed`);
|
|
620
|
+
}
|
|
621
|
+
const projects = [];
|
|
622
|
+
const seen = new Set();
|
|
623
|
+
for (const [index, entry] of raw.projects.entries()) {
|
|
624
|
+
const field = `projects[${index}]`;
|
|
625
|
+
if (!isRecord(entry)) {
|
|
626
|
+
add('E_REGISTRY_SHAPE', field, 'must be an object');
|
|
627
|
+
continue;
|
|
628
|
+
}
|
|
629
|
+
for (const key of Object.keys(entry)) {
|
|
630
|
+
if (!PROJECT_KEYS.has(key)) add('E_REGISTRY_KEY', `${field}.${key}`, 'unknown project key');
|
|
631
|
+
}
|
|
632
|
+
const id = entry.id;
|
|
633
|
+
if (typeof id !== 'string' || !PROJECT_ID_RE.test(id) || id.length > REGISTRY_BOUNDS.idMax) {
|
|
634
|
+
add('E_REGISTRY_ID', `${field}.id`, `must match ${PROJECT_ID_RE} and be at most ${REGISTRY_BOUNDS.idMax} chars`);
|
|
635
|
+
} else if (seen.has(id)) {
|
|
636
|
+
add('E_REGISTRY_DUPLICATE', `${field}.id`, `duplicate project id "${id}"`);
|
|
637
|
+
} else {
|
|
638
|
+
seen.add(id);
|
|
639
|
+
}
|
|
640
|
+
if (typeof entry.title !== 'string' || entry.title.length < 1 || entry.title.length > REGISTRY_BOUNDS.titleMax) {
|
|
641
|
+
add('E_REGISTRY_TITLE', `${field}.title`, `must be 1…${REGISTRY_BOUNDS.titleMax} chars`);
|
|
642
|
+
}
|
|
643
|
+
if (typeof entry.url !== 'string' || !entry.url.startsWith('https://') || entry.url.length > REGISTRY_BOUNDS.urlMax) {
|
|
644
|
+
add('E_REGISTRY_URL', `${field}.url`, `must start with https:// and be at most ${REGISTRY_BOUNDS.urlMax} chars`);
|
|
645
|
+
}
|
|
646
|
+
let fetchStrategy = null;
|
|
647
|
+
if (!isRecord(entry.fetchStrategy)) {
|
|
648
|
+
add('E_REGISTRY_FETCH', `${field}.fetchStrategy`, 'must be {kind:"clone",path} or {kind:"remote"}');
|
|
649
|
+
} else {
|
|
650
|
+
for (const key of Object.keys(entry.fetchStrategy)) {
|
|
651
|
+
if (!FETCH_KEYS.has(key)) add('E_REGISTRY_KEY', `${field}.fetchStrategy.${key}`, 'unknown fetchStrategy key');
|
|
652
|
+
}
|
|
653
|
+
const kind = entry.fetchStrategy.kind;
|
|
654
|
+
if (!FETCH_KINDS.includes(kind)) {
|
|
655
|
+
add('E_REGISTRY_FETCH', `${field}.fetchStrategy.kind`, `must be one of ${FETCH_KINDS.join(' | ')}`);
|
|
656
|
+
} else if (kind === 'clone') {
|
|
657
|
+
const clonePath = entry.fetchStrategy.path;
|
|
658
|
+
if (typeof clonePath !== 'string' || clonePath.length === 0) {
|
|
659
|
+
add('E_REGISTRY_FETCH', `${field}.fetchStrategy.path`, 'kind "clone" requires a non-empty path');
|
|
660
|
+
} else {
|
|
661
|
+
fetchStrategy = { kind, path: clonePath };
|
|
662
|
+
}
|
|
663
|
+
} else {
|
|
664
|
+
if (Object.hasOwn(entry.fetchStrategy, 'path')) {
|
|
665
|
+
add('E_REGISTRY_FETCH', `${field}.fetchStrategy.path`, 'kind "remote" does not take a path');
|
|
666
|
+
}
|
|
667
|
+
fetchStrategy = { kind };
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
let refs = { branch: null, tags: true, releases: false };
|
|
671
|
+
if (entry.refs !== undefined) {
|
|
672
|
+
if (!isRecord(entry.refs)) {
|
|
673
|
+
add('E_REGISTRY_REFS', `${field}.refs`, 'must be an object');
|
|
674
|
+
} else {
|
|
675
|
+
for (const key of Object.keys(entry.refs)) {
|
|
676
|
+
if (!REFS_KEYS.has(key)) add('E_REGISTRY_KEY', `${field}.refs.${key}`, 'unknown refs key');
|
|
677
|
+
}
|
|
678
|
+
if (entry.refs.branch !== undefined && entry.refs.branch !== null) {
|
|
679
|
+
if (!isValidRefName(entry.refs.branch)) {
|
|
680
|
+
add(
|
|
681
|
+
'E_REGISTRY_REFS',
|
|
682
|
+
`${field}.refs.branch`,
|
|
683
|
+
`must be a git ref name of at most ${REGISTRY_BOUNDS.branchMax} chars: no leading "-", whitespace, control characters, "..", or "@{"`,
|
|
684
|
+
);
|
|
685
|
+
} else {
|
|
686
|
+
refs.branch = entry.refs.branch;
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
if (entry.refs.tags !== undefined) {
|
|
690
|
+
if (typeof entry.refs.tags !== 'boolean') add('E_REGISTRY_REFS', `${field}.refs.tags`, 'must be a boolean');
|
|
691
|
+
else refs.tags = entry.refs.tags;
|
|
692
|
+
}
|
|
693
|
+
if (entry.refs.releases !== undefined) {
|
|
694
|
+
if (typeof entry.refs.releases !== 'boolean') add('E_REGISTRY_REFS', `${field}.refs.releases`, 'must be a boolean');
|
|
695
|
+
else refs.releases = entry.refs.releases;
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
const cadence = entry.cadence ?? 'weekly';
|
|
700
|
+
if (!CADENCES.includes(cadence)) add('E_REGISTRY_CADENCE', `${field}.cadence`, `must be one of ${CADENCES.join(' | ')}`);
|
|
701
|
+
const priority = entry.priority ?? 3;
|
|
702
|
+
if (!Number.isInteger(priority) || priority < 1 || priority > 5) {
|
|
703
|
+
add('E_REGISTRY_PRIORITY', `${field}.priority`, 'must be an integer 1…5');
|
|
704
|
+
}
|
|
705
|
+
let scopeHints = { paths: [], notes: '' };
|
|
706
|
+
if (entry.scopeHints !== undefined) {
|
|
707
|
+
if (!isRecord(entry.scopeHints)) {
|
|
708
|
+
add('E_REGISTRY_SCOPE', `${field}.scopeHints`, 'must be an object');
|
|
709
|
+
} else {
|
|
710
|
+
for (const key of Object.keys(entry.scopeHints)) {
|
|
711
|
+
if (!SCOPE_KEYS.has(key)) add('E_REGISTRY_KEY', `${field}.scopeHints.${key}`, 'unknown scopeHints key');
|
|
712
|
+
}
|
|
713
|
+
if (entry.scopeHints.paths !== undefined) {
|
|
714
|
+
const paths = entry.scopeHints.paths;
|
|
715
|
+
if (!Array.isArray(paths) || paths.length > REGISTRY_BOUNDS.scopePathsMax) {
|
|
716
|
+
add('E_REGISTRY_SCOPE', `${field}.scopeHints.paths`, `must be an array of at most ${REGISTRY_BOUNDS.scopePathsMax} paths`);
|
|
717
|
+
} else if (paths.some((item) => typeof item !== 'string' || item.length === 0 || item.length > REGISTRY_BOUNDS.scopePathMax)) {
|
|
718
|
+
add('E_REGISTRY_SCOPE', `${field}.scopeHints.paths`, `each path must be 1…${REGISTRY_BOUNDS.scopePathMax} chars`);
|
|
719
|
+
} else {
|
|
720
|
+
scopeHints.paths = [...paths];
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
if (entry.scopeHints.notes !== undefined) {
|
|
724
|
+
if (typeof entry.scopeHints.notes !== 'string' || entry.scopeHints.notes.length > REGISTRY_BOUNDS.scopeNotesMax) {
|
|
725
|
+
add('E_REGISTRY_SCOPE', `${field}.scopeHints.notes`, `must be a string of at most ${REGISTRY_BOUNDS.scopeNotesMax} chars`);
|
|
726
|
+
} else {
|
|
727
|
+
scopeHints.notes = entry.scopeHints.notes;
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
const notes = entry.notes ?? '';
|
|
733
|
+
if (typeof notes !== 'string' || notes.length > REGISTRY_BOUNDS.notesMax) {
|
|
734
|
+
add('E_REGISTRY_NOTES', `${field}.notes`, `must be a string of at most ${REGISTRY_BOUNDS.notesMax} chars`);
|
|
735
|
+
}
|
|
736
|
+
if (typeof entry.enabled !== 'undefined' && typeof entry.enabled !== 'boolean') {
|
|
737
|
+
add('E_REGISTRY_ENABLED', `${field}.enabled`, 'must be a boolean');
|
|
738
|
+
}
|
|
739
|
+
projects.push({
|
|
740
|
+
id,
|
|
741
|
+
title: entry.title,
|
|
742
|
+
url: entry.url,
|
|
743
|
+
enabled: entry.enabled ?? true,
|
|
744
|
+
fetchStrategy,
|
|
745
|
+
refs,
|
|
746
|
+
cadence,
|
|
747
|
+
priority,
|
|
748
|
+
scopeHints,
|
|
749
|
+
notes,
|
|
750
|
+
});
|
|
751
|
+
}
|
|
752
|
+
if (findings.length > 0) throw registryFailure(findings);
|
|
753
|
+
return { registry: { schemaVersion: SCHEMA_VERSION, projects } };
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
/** Load `upstream/projects.json`; a missing file is a registry failure, never empty. */
|
|
757
|
+
export function loadRegistry(teamRoot) {
|
|
758
|
+
const file = path.join(teamRoot, PROJECTS_FILE);
|
|
759
|
+
const result = readJsonFile(file);
|
|
760
|
+
if (result.error) {
|
|
761
|
+
throw registryFailure(
|
|
762
|
+
[{ code: 'E_REGISTRY_PARSE', field: PROJECTS_FILE, message: result.error }],
|
|
763
|
+
`cannot read ${PROJECTS_FILE}`,
|
|
764
|
+
);
|
|
765
|
+
}
|
|
766
|
+
return validateRegistry(result.value);
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
/** Validate and normalize `config.json`; a missing file uses the documented defaults. */
|
|
770
|
+
export function validateConfig(raw) {
|
|
771
|
+
const findings = [];
|
|
772
|
+
const add = (code, field, message) => findings.push({ code, field, message });
|
|
773
|
+
if (raw !== undefined && !isRecord(raw)) {
|
|
774
|
+
throw registryFailure([{ code: 'E_CONFIG_SHAPE', field: CONFIG_FILE, message: 'must be a JSON object' }]);
|
|
775
|
+
}
|
|
776
|
+
const source = raw ?? {};
|
|
777
|
+
for (const key of Object.keys(source)) {
|
|
778
|
+
if (!['schemaVersion', ...CONFIG_GROUPS].includes(key)) add('E_CONFIG_KEY', key, 'unknown top-level key');
|
|
779
|
+
}
|
|
780
|
+
if (source.schemaVersion !== undefined && source.schemaVersion !== SCHEMA_VERSION) {
|
|
781
|
+
add('E_CONFIG_VERSION', 'schemaVersion', `must be ${SCHEMA_VERSION}`);
|
|
782
|
+
}
|
|
783
|
+
const config = { schemaVersion: SCHEMA_VERSION, budget: {}, scan: {}, agent: {}, digest: {}, artifacts: {} };
|
|
784
|
+
for (const [flat, bounds] of Object.entries(CONFIG_BOUNDS)) {
|
|
785
|
+
const [group, key] = flat.split('.');
|
|
786
|
+
const groupRaw = source[group];
|
|
787
|
+
if (groupRaw !== undefined && !isRecord(groupRaw)) {
|
|
788
|
+
add('E_CONFIG_TYPE', group, 'must be an object');
|
|
789
|
+
continue;
|
|
790
|
+
}
|
|
791
|
+
const known = new Set(Object.keys(CONFIG_BOUNDS).filter((name) => name.startsWith(`${group}.`)).map((name) => name.split('.')[1]));
|
|
792
|
+
for (const entryKey of Object.keys(groupRaw ?? {})) {
|
|
793
|
+
if (!known.has(entryKey)) add('E_CONFIG_KEY', `${group}.${entryKey}`, 'unknown key');
|
|
794
|
+
}
|
|
795
|
+
const value = groupRaw?.[key];
|
|
796
|
+
if (value === undefined) {
|
|
797
|
+
config[group][key] = bounds.default;
|
|
798
|
+
continue;
|
|
799
|
+
}
|
|
800
|
+
if (bounds.integer) {
|
|
801
|
+
if (!Number.isInteger(value)) {
|
|
802
|
+
add('E_CONFIG_TYPE', flat, 'must be an integer');
|
|
803
|
+
config[group][key] = bounds.default;
|
|
804
|
+
} else if (value < bounds.min || value > bounds.max) {
|
|
805
|
+
add('E_CONFIG_BOUND', flat, `must be ${bounds.min}…${bounds.max}`);
|
|
806
|
+
config[group][key] = bounds.default;
|
|
807
|
+
} else {
|
|
808
|
+
config[group][key] = value;
|
|
809
|
+
}
|
|
810
|
+
continue;
|
|
811
|
+
}
|
|
812
|
+
if (bounds.type === 'boolean') {
|
|
813
|
+
if (typeof value !== 'boolean') add('E_CONFIG_TYPE', flat, 'must be a boolean');
|
|
814
|
+
else config[group][key] = value;
|
|
815
|
+
continue;
|
|
816
|
+
}
|
|
817
|
+
if (bounds.type === 'string-or-null') {
|
|
818
|
+
if (value !== null && (typeof value !== 'string' || value.length > bounds.maxLength)) {
|
|
819
|
+
add('E_CONFIG_TYPE', flat, `must be null or a string of at most ${bounds.maxLength} chars`);
|
|
820
|
+
} else {
|
|
821
|
+
config[group][key] = value;
|
|
822
|
+
}
|
|
823
|
+
continue;
|
|
824
|
+
}
|
|
825
|
+
if (typeof value !== 'string' || value.length === 0) {
|
|
826
|
+
add('E_CONFIG_TYPE', flat, 'must be a non-empty string');
|
|
827
|
+
continue;
|
|
828
|
+
}
|
|
829
|
+
config[group][key] = value;
|
|
830
|
+
}
|
|
831
|
+
if (
|
|
832
|
+
typeof config.digest.path === 'string' &&
|
|
833
|
+
config.digest.path.includes('docs/upstream') &&
|
|
834
|
+
!config.digest.path.includes('<runId>')
|
|
835
|
+
) {
|
|
836
|
+
add('E_CONFIG_DIGEST_PATH', 'digest.path', 'must contain <runId> when the path is under docs/upstream; one run must not overwrite another digest');
|
|
837
|
+
}
|
|
838
|
+
if (findings.length > 0) throw registryFailure(findings, 'policy failed validation');
|
|
839
|
+
return { config };
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
/** Load `upstream/config.json`; a consumer with no file gets the documented defaults. */
|
|
843
|
+
export function loadConfig(teamRoot) {
|
|
844
|
+
const file = path.join(teamRoot, CONFIG_FILE);
|
|
845
|
+
if (!fs.existsSync(file)) return validateConfig(undefined);
|
|
846
|
+
const result = readJsonFile(file);
|
|
847
|
+
if (result.error) {
|
|
848
|
+
throw registryFailure([{ code: 'E_CONFIG_PARSE', field: CONFIG_FILE, message: result.error }], `cannot read ${CONFIG_FILE}`);
|
|
849
|
+
}
|
|
850
|
+
return validateConfig(result.value);
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
/* ------------------------------ WP2 — cursor ------------------------------- */
|
|
854
|
+
|
|
855
|
+
/**
|
|
856
|
+
* Normalise one cursor entry. A malformed entry is kept (so a rename can still
|
|
857
|
+
* be detected) but degrades to a bounded baseline: `headSha: null` and `tags: []`.
|
|
858
|
+
*/
|
|
859
|
+
export function sanitiseCursorEntry(entry) {
|
|
860
|
+
if (!isRecord(entry)) return null;
|
|
861
|
+
return {
|
|
862
|
+
kind: typeof entry.kind === 'string' ? entry.kind : null,
|
|
863
|
+
headRef: typeof entry.headRef === 'string' ? entry.headRef : null,
|
|
864
|
+
headSha: typeof entry.headSha === 'string' && COMMIT_SHA_RE.test(entry.headSha) ? entry.headSha : null,
|
|
865
|
+
tags: Array.isArray(entry.tags)
|
|
866
|
+
? entry.tags.filter((tag) => typeof tag === 'string' && tag.length > 0 && tag.length <= 200).slice(0, 50)
|
|
867
|
+
: [],
|
|
868
|
+
changelogSha:
|
|
869
|
+
typeof entry.changelogSha === 'string' && COMMIT_SHA_RE.test(entry.changelogSha) ? entry.changelogSha : null,
|
|
870
|
+
scannedAt:
|
|
871
|
+
typeof entry.scannedAt === 'string' && Number.isFinite(Date.parse(entry.scannedAt)) ? entry.scannedAt : null,
|
|
872
|
+
runId: typeof entry.runId === 'string' ? entry.runId : null,
|
|
873
|
+
url: typeof entry.url === 'string' ? entry.url : null,
|
|
874
|
+
};
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
/** Read the cursor; a missing or unreadable file degrades to "no cursor". */
|
|
878
|
+
export function readCursor(teamRoot) {
|
|
879
|
+
const file = path.join(teamRoot, CURSOR_FILE);
|
|
880
|
+
const result = readJsonFile(file);
|
|
881
|
+
if (result.error || !isRecord(result.value) || result.value.schemaVersion !== SCHEMA_VERSION) {
|
|
882
|
+
return { schemaVersion: SCHEMA_VERSION, updatedAt: null, projects: {} };
|
|
883
|
+
}
|
|
884
|
+
const projects = {};
|
|
885
|
+
if (isRecord(result.value.projects)) {
|
|
886
|
+
for (const [id, entry] of Object.entries(result.value.projects)) {
|
|
887
|
+
if (!PROJECT_ID_RE.test(id)) continue;
|
|
888
|
+
const clean = sanitiseCursorEntry(entry);
|
|
889
|
+
if (clean) projects[id] = clean;
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
return {
|
|
893
|
+
schemaVersion: SCHEMA_VERSION,
|
|
894
|
+
updatedAt: typeof result.value.updatedAt === 'string' ? result.value.updatedAt : null,
|
|
895
|
+
projects,
|
|
896
|
+
};
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
/** Rebuild a lost cursor from the newest `report.json` per project. */
|
|
900
|
+
export function rebuildCursorFromReports({ teamRoot }) {
|
|
901
|
+
const runsRoot = path.join(teamRoot, RUNS_DIR);
|
|
902
|
+
const projects = {};
|
|
903
|
+
const scanned = {};
|
|
904
|
+
if (!fs.existsSync(runsRoot)) return { schemaVersion: SCHEMA_VERSION, updatedAt: null, projects };
|
|
905
|
+
for (const entry of fs.readdirSync(runsRoot, { withFileTypes: true })) {
|
|
906
|
+
if (!entry.isDirectory()) continue;
|
|
907
|
+
const result = readJsonFile(path.join(runsRoot, entry.name, 'report.json'));
|
|
908
|
+
if (result.error || !isRecord(result.value) || !isRecord(result.value.cursorAfter)) continue;
|
|
909
|
+
const generatedAt = typeof result.value.generatedAt === 'string' ? result.value.generatedAt : '';
|
|
910
|
+
for (const [id, cursorEntry] of Object.entries(result.value.cursorAfter)) {
|
|
911
|
+
if (!isRecord(cursorEntry) || !PROJECT_ID_RE.test(id)) continue;
|
|
912
|
+
if (scanned[id] !== undefined && scanned[id] >= generatedAt) continue;
|
|
913
|
+
scanned[id] = generatedAt;
|
|
914
|
+
const clean = sanitiseCursorEntry(cursorEntry);
|
|
915
|
+
if (clean) projects[id] = clean;
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
return { schemaVersion: SCHEMA_VERSION, updatedAt: null, projects };
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
/**
|
|
922
|
+
* Prune orphan cursor entries and describe a rename when the URL moved to a new id.
|
|
923
|
+
* The old key is never reused.
|
|
924
|
+
*/
|
|
925
|
+
export function reconcileCursor({ cursor, projects }) {
|
|
926
|
+
const ids = new Set(projects.map((project) => project.id));
|
|
927
|
+
const byUrl = new Map(projects.map((project) => [project.url, project.id]));
|
|
928
|
+
const pruned = [];
|
|
929
|
+
const renames = [];
|
|
930
|
+
const kept = {};
|
|
931
|
+
for (const [id, entry] of Object.entries(cursor.projects ?? {})) {
|
|
932
|
+
if (ids.has(id)) {
|
|
933
|
+
kept[id] = entry;
|
|
934
|
+
continue;
|
|
935
|
+
}
|
|
936
|
+
pruned.push(id);
|
|
937
|
+
const target = isRecord(entry) && typeof entry.url === 'string' ? byUrl.get(entry.url) : undefined;
|
|
938
|
+
if (target && !cursor.projects[target]) renames.push({ from: id, to: target });
|
|
939
|
+
}
|
|
940
|
+
return { cursor: { ...cursor, projects: kept }, pruned, renames };
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
/** Write `upstream/cursor.json` atomically; the only cursor writer. */
|
|
944
|
+
export function writeCursor(teamRoot, cursor, now) {
|
|
945
|
+
const next = { ...cursor, schemaVersion: SCHEMA_VERSION, updatedAt: now };
|
|
946
|
+
writeFileAtomic(path.join(teamRoot, CURSOR_FILE), `${JSON.stringify(next, null, 2)}\n`);
|
|
947
|
+
return next;
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
/* ----------------------------- WP2 — selection ----------------------------- */
|
|
951
|
+
|
|
952
|
+
/** Whether a project is due under its cadence. */
|
|
953
|
+
export function isCadenceDue({ project, cursorEntry, now }) {
|
|
954
|
+
const last = cursorEntry?.scannedAt;
|
|
955
|
+
if (!last) return true;
|
|
956
|
+
const lastMs = Date.parse(last);
|
|
957
|
+
if (!Number.isFinite(lastMs)) return true;
|
|
958
|
+
const days = CADENCE_DAYS[project.cadence ?? 'weekly'] ?? CADENCE_DAYS.weekly;
|
|
959
|
+
return Date.parse(now) - lastMs >= days * 24 * 60 * 60 * 1000;
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
/**
|
|
963
|
+
* Select due projects: least-recently-scanned first, then priority descending,
|
|
964
|
+
* then id ascending. The tail beyond `budget.maxProjects` is the deferred set.
|
|
965
|
+
*/
|
|
966
|
+
export function selectProjects({ projects, config, cursor, now }) {
|
|
967
|
+
const skipped = [];
|
|
968
|
+
const eligible = [];
|
|
969
|
+
for (const project of projects) {
|
|
970
|
+
const cursorEntry = cursor.projects?.[project.id];
|
|
971
|
+
if (project.enabled === false) {
|
|
972
|
+
skipped.push({ id: project.id, reason: 'disabled' });
|
|
973
|
+
continue;
|
|
974
|
+
}
|
|
975
|
+
if (!isCadenceDue({ project, cursorEntry, now })) {
|
|
976
|
+
skipped.push({ id: project.id, reason: 'cadence' });
|
|
977
|
+
continue;
|
|
978
|
+
}
|
|
979
|
+
eligible.push({ project, cursorEntry });
|
|
980
|
+
}
|
|
981
|
+
eligible.sort((left, right) => {
|
|
982
|
+
const leftScanned = left.cursorEntry?.scannedAt ? Date.parse(left.cursorEntry.scannedAt) : -Infinity;
|
|
983
|
+
const rightScanned = right.cursorEntry?.scannedAt ? Date.parse(right.cursorEntry.scannedAt) : -Infinity;
|
|
984
|
+
if (leftScanned !== rightScanned) return leftScanned - rightScanned;
|
|
985
|
+
const leftPriority = left.project.priority ?? 3;
|
|
986
|
+
const rightPriority = right.project.priority ?? 3;
|
|
987
|
+
if (leftPriority !== rightPriority) return rightPriority - leftPriority;
|
|
988
|
+
return left.project.id.localeCompare(right.project.id);
|
|
989
|
+
});
|
|
990
|
+
const selected = eligible.slice(0, config.budget.maxProjects);
|
|
991
|
+
const deferred = eligible.slice(config.budget.maxProjects);
|
|
992
|
+
return { selected, deferred, skipped };
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
/* ------------------------------- WP3 — scan -------------------------------- */
|
|
996
|
+
|
|
997
|
+
export const GIT_TIMEOUT_MS = 120_000;
|
|
998
|
+
|
|
999
|
+
/** Run git with argv only, no shell, and a credential prompt disabled. */
|
|
1000
|
+
export function runGit(args, { cwd, env = process.env, timeoutMs = GIT_TIMEOUT_MS } = {}) {
|
|
1001
|
+
const result = spawnSync('git', args, {
|
|
1002
|
+
cwd,
|
|
1003
|
+
encoding: 'utf8',
|
|
1004
|
+
timeout: timeoutMs,
|
|
1005
|
+
env: { ...env, GIT_TERMINAL_PROMPT: '0' },
|
|
1006
|
+
});
|
|
1007
|
+
return {
|
|
1008
|
+
status: result.status === null ? -1 : result.status,
|
|
1009
|
+
stdout: `${result.stdout || ''}`,
|
|
1010
|
+
stderr: `${result.stderr || ''}`,
|
|
1011
|
+
error: result.error ?? null,
|
|
1012
|
+
};
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
function projectFailure(code, message, remedy = REMEDIES[code] ?? '') {
|
|
1016
|
+
return new UpstreamError(code, message, { exitCode: EXIT_CODES.ok, remedy });
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
const asTagArray = (value) => (Array.isArray(value) ? value.filter((tag) => typeof tag === 'string') : []);
|
|
1020
|
+
|
|
1021
|
+
const sameTagSet = (left, right) => {
|
|
1022
|
+
const a = [...asTagArray(left)].sort();
|
|
1023
|
+
const b = [...asTagArray(right)].sort();
|
|
1024
|
+
return a.length === b.length && a.every((value, index) => value === b[index]);
|
|
1025
|
+
};
|
|
1026
|
+
|
|
1027
|
+
/**
|
|
1028
|
+
* The validated ref a fetch may use. A malformed ref never becomes a `git`
|
|
1029
|
+
* option: the project fails closed instead of falling back to `HEAD`.
|
|
1030
|
+
*/
|
|
1031
|
+
function fetchRef(project) {
|
|
1032
|
+
const ref = project.refs?.branch ?? 'HEAD';
|
|
1033
|
+
if (!isValidRefName(ref)) {
|
|
1034
|
+
throw projectFailure(
|
|
1035
|
+
RUNNER_CODES.refUnresolved,
|
|
1036
|
+
`invalid refs.branch for "${project.id}": expected a git ref name, never an option`,
|
|
1037
|
+
);
|
|
1038
|
+
}
|
|
1039
|
+
return ref;
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
/** Resolve a registry entry's clone path against `--repo-root`. */
|
|
1043
|
+
export function resolveClone({ project, repoRoot, env = process.env, config }) {
|
|
1044
|
+
if (project.fetchStrategy?.kind !== 'clone') {
|
|
1045
|
+
throw projectFailure(
|
|
1046
|
+
RUNNER_CODES.projectNoClone,
|
|
1047
|
+
`project "${project.id}" has no local clone (fetchStrategy.kind=${project.fetchStrategy?.kind ?? 'missing'})`,
|
|
1048
|
+
REMEDIES[RUNNER_CODES.projectNoClone].replace('<id>', project.id).replace('<url>', project.url),
|
|
1049
|
+
);
|
|
1050
|
+
}
|
|
1051
|
+
const raw = project.fetchStrategy.path;
|
|
1052
|
+
const cloneDir = path.isAbsolute(raw) ? raw : path.resolve(repoRoot, raw);
|
|
1053
|
+
if (!fs.existsSync(cloneDir) || !fs.statSync(cloneDir).isDirectory()) {
|
|
1054
|
+
throw projectFailure(
|
|
1055
|
+
RUNNER_CODES.projectNoClone,
|
|
1056
|
+
`clone directory for "${project.id}" is missing: ${cloneDir}`,
|
|
1057
|
+
`git clone --depth 50 ${project.url} ${path.join('..', 'ai-rules-research', project.id)}`,
|
|
1058
|
+
);
|
|
1059
|
+
}
|
|
1060
|
+
const probe = runGit(['rev-parse', '--git-dir'], {
|
|
1061
|
+
cwd: cloneDir,
|
|
1062
|
+
env,
|
|
1063
|
+
timeoutMs: config.scan.fetchTimeoutMs,
|
|
1064
|
+
});
|
|
1065
|
+
if (probe.status !== 0) {
|
|
1066
|
+
throw projectFailure(
|
|
1067
|
+
RUNNER_CODES.projectNoClone,
|
|
1068
|
+
`${cloneDir} is not a git repository for "${project.id}"`,
|
|
1069
|
+
`git clone --depth 50 ${project.url} ${path.join('..', 'ai-rules-research', project.id)}`,
|
|
1070
|
+
);
|
|
1071
|
+
}
|
|
1072
|
+
return cloneDir;
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
/** Fetch the configured ref with `--depth 1` and return the fetched tip. */
|
|
1076
|
+
export function fetchTip({ cloneDir, project, env = process.env, config, git = runGit }) {
|
|
1077
|
+
const ref = fetchRef(project);
|
|
1078
|
+
const fetch = git(['fetch', '--depth', '1', 'origin', '--', ref], {
|
|
1079
|
+
cwd: cloneDir,
|
|
1080
|
+
env,
|
|
1081
|
+
timeoutMs: config.scan.fetchTimeoutMs,
|
|
1082
|
+
});
|
|
1083
|
+
if (fetch.status !== 0) {
|
|
1084
|
+
throw projectFailure(
|
|
1085
|
+
RUNNER_CODES.fetchFailed,
|
|
1086
|
+
`git fetch --depth 1 origin -- ${ref} failed for "${project.id}": ${(fetch.stderr || fetch.stdout).trim().slice(0, 400)}`,
|
|
1087
|
+
);
|
|
1088
|
+
}
|
|
1089
|
+
for (const candidate of ['FETCH_HEAD', ref, 'HEAD']) {
|
|
1090
|
+
const tip = git(['rev-parse', candidate], { cwd: cloneDir, env, timeoutMs: config.scan.fetchTimeoutMs });
|
|
1091
|
+
if (tip.status === 0 && /^[0-9a-f]{40,64}$/.test(tip.stdout.trim())) {
|
|
1092
|
+
return { tip: tip.stdout.trim(), headRef: ref };
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
throw projectFailure(RUNNER_CODES.refUnresolved, `cannot resolve ${ref} in ${cloneDir}`);
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
/** Tags newest-by-creator-date, capped at 50. */
|
|
1099
|
+
export function readTags({ cloneDir, env = process.env, config }) {
|
|
1100
|
+
const result = runGit(['tag', '--sort=-creatordate'], {
|
|
1101
|
+
cwd: cloneDir,
|
|
1102
|
+
env,
|
|
1103
|
+
timeoutMs: config.scan.fetchTimeoutMs,
|
|
1104
|
+
});
|
|
1105
|
+
if (result.status !== 0) return [];
|
|
1106
|
+
return result.stdout
|
|
1107
|
+
.split('\n')
|
|
1108
|
+
.map((line) => line.trim())
|
|
1109
|
+
.filter(Boolean)
|
|
1110
|
+
.slice(0, 50);
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
/** The changelog blob hash and a bounded excerpt, when the registry asks for releases. */
|
|
1114
|
+
export function readChangelog({ cloneDir, tip, project, env = process.env, config }) {
|
|
1115
|
+
if (!project.refs?.releases) return { changelogSha: null, excerpt: '' };
|
|
1116
|
+
const resolved = runGit(['rev-parse', `${tip}:CHANGELOG.md`], {
|
|
1117
|
+
cwd: cloneDir,
|
|
1118
|
+
env,
|
|
1119
|
+
timeoutMs: config.scan.fetchTimeoutMs,
|
|
1120
|
+
});
|
|
1121
|
+
if (resolved.status !== 0) return { changelogSha: null, excerpt: '' };
|
|
1122
|
+
const shown = runGit(['show', `${tip}:CHANGELOG.md`], {
|
|
1123
|
+
cwd: cloneDir,
|
|
1124
|
+
env,
|
|
1125
|
+
timeoutMs: config.scan.fetchTimeoutMs,
|
|
1126
|
+
});
|
|
1127
|
+
const excerpt = shown.status === 0 ? capText(shown.stdout, config.scan.maxChangelogBytes).text : '';
|
|
1128
|
+
return { changelogSha: resolved.stdout.trim(), excerpt };
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
/** Cap text by UTF-8 bytes with an explicit marker. */
|
|
1132
|
+
export function capText(text, cap) {
|
|
1133
|
+
const buffer = Buffer.from(text, 'utf8');
|
|
1134
|
+
if (buffer.length <= cap) return { text, truncated: false };
|
|
1135
|
+
const marker = `\n[truncated at ${cap} bytes]\n`;
|
|
1136
|
+
const keep = Math.max(0, cap - Buffer.byteLength(marker));
|
|
1137
|
+
return { text: `${buffer.subarray(0, keep).toString('utf8')}${marker}`, truncated: true };
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
function readLog({ git = runGit, cloneDir, args, env, config }) {
|
|
1141
|
+
const result = git(['log', '--format=%H%x09%ad%x09%s', '--date=short', ...args], {
|
|
1142
|
+
cwd: cloneDir,
|
|
1143
|
+
env,
|
|
1144
|
+
timeoutMs: config.scan.fetchTimeoutMs,
|
|
1145
|
+
});
|
|
1146
|
+
if (result.status !== 0) return [];
|
|
1147
|
+
return result.stdout
|
|
1148
|
+
.split('\n')
|
|
1149
|
+
.filter(Boolean)
|
|
1150
|
+
.map((line) => {
|
|
1151
|
+
const [sha, date, subject] = line.split('\t');
|
|
1152
|
+
return { sha, date, subject };
|
|
1153
|
+
});
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
/**
|
|
1157
|
+
* Decide exactly one window label. Never invents a range: a shallow boundary or
|
|
1158
|
+
* a force-push is `unprovable`, a missing commit is `baseline` with `lost`.
|
|
1159
|
+
*/
|
|
1160
|
+
export function computeWindow({ cloneDir, project, cursorEntry, config, tip, tags, changelogSha, env = process.env, git = runGit }) {
|
|
1161
|
+
const previousHeadSha =
|
|
1162
|
+
typeof cursorEntry?.headSha === 'string' && COMMIT_SHA_RE.test(cursorEntry.headSha) ? cursorEntry.headSha : null;
|
|
1163
|
+
const previousTags = Array.isArray(cursorEntry?.tags) ? cursorEntry.tags : [];
|
|
1164
|
+
if (
|
|
1165
|
+
previousHeadSha &&
|
|
1166
|
+
previousHeadSha === tip &&
|
|
1167
|
+
sameTagSet(previousTags, tags) &&
|
|
1168
|
+
(cursorEntry.changelogSha ?? null) === (changelogSha ?? null)
|
|
1169
|
+
) {
|
|
1170
|
+
return {
|
|
1171
|
+
kind: 'no-change',
|
|
1172
|
+
from: previousHeadSha,
|
|
1173
|
+
to: tip,
|
|
1174
|
+
commits: [],
|
|
1175
|
+
tags,
|
|
1176
|
+
changelogSha,
|
|
1177
|
+
lost: false,
|
|
1178
|
+
};
|
|
1179
|
+
}
|
|
1180
|
+
const baseline = () => ({
|
|
1181
|
+
kind: 'baseline',
|
|
1182
|
+
from: null,
|
|
1183
|
+
to: tip,
|
|
1184
|
+
commits: readLog({ git, cloneDir, args: [`-n`, String(config.scan.baselineCommits), tip], env, config }),
|
|
1185
|
+
tags,
|
|
1186
|
+
changelogSha,
|
|
1187
|
+
lost: false,
|
|
1188
|
+
});
|
|
1189
|
+
if (!previousHeadSha) return baseline();
|
|
1190
|
+
const present = git(['cat-file', '-e', `${previousHeadSha}^{commit}`], {
|
|
1191
|
+
cwd: cloneDir,
|
|
1192
|
+
env,
|
|
1193
|
+
timeoutMs: config.scan.fetchTimeoutMs,
|
|
1194
|
+
});
|
|
1195
|
+
if (present.status !== 0) {
|
|
1196
|
+
const ref = fetchRef(project);
|
|
1197
|
+
git(['fetch', '--deepen', '50', 'origin', '--', ref], {
|
|
1198
|
+
cwd: cloneDir,
|
|
1199
|
+
env,
|
|
1200
|
+
timeoutMs: config.scan.fetchTimeoutMs,
|
|
1201
|
+
});
|
|
1202
|
+
const retry = git(['cat-file', '-e', `${previousHeadSha}^{commit}`], {
|
|
1203
|
+
cwd: cloneDir,
|
|
1204
|
+
env,
|
|
1205
|
+
timeoutMs: config.scan.fetchTimeoutMs,
|
|
1206
|
+
});
|
|
1207
|
+
if (retry.status !== 0) {
|
|
1208
|
+
return { ...baseline(), lost: true };
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
const ancestor = git(['merge-base', '--is-ancestor', previousHeadSha, tip], {
|
|
1212
|
+
cwd: cloneDir,
|
|
1213
|
+
env,
|
|
1214
|
+
timeoutMs: config.scan.fetchTimeoutMs,
|
|
1215
|
+
});
|
|
1216
|
+
if (ancestor.status === 0) {
|
|
1217
|
+
return {
|
|
1218
|
+
kind: 'range',
|
|
1219
|
+
from: previousHeadSha,
|
|
1220
|
+
to: tip,
|
|
1221
|
+
commits: readLog({
|
|
1222
|
+
git,
|
|
1223
|
+
cloneDir,
|
|
1224
|
+
args: [`${previousHeadSha}..${tip}`],
|
|
1225
|
+
env,
|
|
1226
|
+
config,
|
|
1227
|
+
}).slice(0, config.scan.maxCommitsInWindow),
|
|
1228
|
+
tags,
|
|
1229
|
+
changelogSha,
|
|
1230
|
+
lost: false,
|
|
1231
|
+
};
|
|
1232
|
+
}
|
|
1233
|
+
return {
|
|
1234
|
+
kind: 'unprovable',
|
|
1235
|
+
from: previousHeadSha,
|
|
1236
|
+
to: tip,
|
|
1237
|
+
commits: readLog({ git, cloneDir, args: ['-n', '20', tip], env, config }),
|
|
1238
|
+
tags,
|
|
1239
|
+
changelogSha,
|
|
1240
|
+
lost: false,
|
|
1241
|
+
};
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
/** A run-wide byte budget for runner-written evidence. */
|
|
1245
|
+
export function createRunBudget(maxRunBytes) {
|
|
1246
|
+
return { limit: maxRunBytes, used: 0, truncated: false };
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
/**
|
|
1250
|
+
* The next agent call timeout inside one project's deadline. `0` means the
|
|
1251
|
+
* shared `budget.projectTimeoutMs` (or the run deadline) is already spent.
|
|
1252
|
+
*/
|
|
1253
|
+
export function nextAgentTimeoutMs({ projectDeadlineMs, agentTimeoutMs, nowMs = Date.now() }) {
|
|
1254
|
+
const remaining = projectDeadlineMs - nowMs;
|
|
1255
|
+
if (remaining <= 0) return 0;
|
|
1256
|
+
return Math.max(1, Math.min(agentTimeoutMs, remaining));
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
/** Write one artifact, honouring the per-file cap and the run-wide budget. */
|
|
1260
|
+
export function writeArtifact(budget, filePath, content, perFileCap) {
|
|
1261
|
+
let body = `${content}`;
|
|
1262
|
+
let truncated = false;
|
|
1263
|
+
const perFile = capText(body, perFileCap);
|
|
1264
|
+
body = perFile.text;
|
|
1265
|
+
truncated = truncated || perFile.truncated;
|
|
1266
|
+
const remaining = Math.max(0, budget.limit - budget.used);
|
|
1267
|
+
const runCapped = capText(body, remaining);
|
|
1268
|
+
body = runCapped.text;
|
|
1269
|
+
truncated = truncated || runCapped.truncated;
|
|
1270
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
1271
|
+
fs.writeFileSync(filePath, body, 'utf8');
|
|
1272
|
+
const bytes = Buffer.byteLength(body);
|
|
1273
|
+
budget.used += bytes;
|
|
1274
|
+
if (truncated) budget.truncated = true;
|
|
1275
|
+
return { bytes, truncated };
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
/** Build the `git diff` argv for a window, filtered by `scopeHints.paths`. */
|
|
1279
|
+
export function windowDiffArgs(window, project) {
|
|
1280
|
+
if (window.kind === 'no-change' || window.kind === 'baseline' || !window.from) return null;
|
|
1281
|
+
const args = ['diff', window.from, window.to];
|
|
1282
|
+
const paths = project.scopeHints?.paths ?? [];
|
|
1283
|
+
if (paths.length > 0) args.push('--', ...paths);
|
|
1284
|
+
return args;
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
/**
|
|
1288
|
+
* Scan one project and write `window.json`, `diff.patch`, `diff.stat.txt`.
|
|
1289
|
+
* A failure throws; the caller isolates it and keeps the old cursor.
|
|
1290
|
+
*/
|
|
1291
|
+
export function scanProject({ project, repoRoot, runDir, config, cursorEntry, env = process.env, budget }) {
|
|
1292
|
+
const cloneDir = resolveClone({ project, repoRoot, env, config });
|
|
1293
|
+
const { tip, headRef } = fetchTip({ cloneDir, project, env, config });
|
|
1294
|
+
const tags = project.refs?.tags === false ? [] : readTags({ cloneDir, env, config });
|
|
1295
|
+
const { changelogSha, excerpt } = readChangelog({ cloneDir, tip, project, env, config });
|
|
1296
|
+
const window = computeWindow({ cloneDir, project, cursorEntry, config, tip, tags, changelogSha, env });
|
|
1297
|
+
if (window.kind === 'no-change') {
|
|
1298
|
+
return { status: 'no-change', cloneDir, window, headRef, artifacts: [] };
|
|
1299
|
+
}
|
|
1300
|
+
const projectDir = path.join(runDir, 'projects', project.id);
|
|
1301
|
+
const diffArgs = windowDiffArgs(window, project);
|
|
1302
|
+
let diffText = '';
|
|
1303
|
+
let statText = '';
|
|
1304
|
+
if (diffArgs) {
|
|
1305
|
+
const diff = runGit(diffArgs, { cwd: cloneDir, env, timeoutMs: config.scan.fetchTimeoutMs });
|
|
1306
|
+
if (diff.status !== 0) {
|
|
1307
|
+
throw projectFailure(
|
|
1308
|
+
RUNNER_CODES.refUnresolved,
|
|
1309
|
+
`git diff ${window.from} ${window.to} failed for "${project.id}": ${(diff.stderr || '').trim().slice(0, 400)}`,
|
|
1310
|
+
);
|
|
1311
|
+
}
|
|
1312
|
+
diffText = diff.stdout;
|
|
1313
|
+
const stat = runGit([...diffArgs, '--stat'], { cwd: cloneDir, env, timeoutMs: config.scan.fetchTimeoutMs });
|
|
1314
|
+
statText = stat.status === 0 ? stat.stdout : '';
|
|
1315
|
+
} else {
|
|
1316
|
+
diffText = `[no diff: window kind ${window.kind}]\n`;
|
|
1317
|
+
statText = '';
|
|
1318
|
+
}
|
|
1319
|
+
const windowPayload = {
|
|
1320
|
+
schemaVersion: SCHEMA_VERSION,
|
|
1321
|
+
project: project.id,
|
|
1322
|
+
kind: window.kind,
|
|
1323
|
+
from: window.from,
|
|
1324
|
+
to: window.to,
|
|
1325
|
+
headRef,
|
|
1326
|
+
commits: window.commits,
|
|
1327
|
+
tags: window.tags,
|
|
1328
|
+
changelogSha: window.changelogSha,
|
|
1329
|
+
changelogExcerpt: excerpt,
|
|
1330
|
+
cursor: window.lost ? 'lost' : window.kind,
|
|
1331
|
+
};
|
|
1332
|
+
const artifacts = [
|
|
1333
|
+
writeArtifact(
|
|
1334
|
+
budget,
|
|
1335
|
+
path.join(projectDir, 'window.json'),
|
|
1336
|
+
`${JSON.stringify(windowPayload, null, 2)}\n`,
|
|
1337
|
+
64 * 1024,
|
|
1338
|
+
),
|
|
1339
|
+
writeArtifact(budget, path.join(projectDir, 'diff.patch'), diffText, config.scan.maxDiffBytes),
|
|
1340
|
+
writeArtifact(budget, path.join(projectDir, 'diff.stat.txt'), statText, 32 * 1024),
|
|
1341
|
+
];
|
|
1342
|
+
return { status: 'changed', cloneDir, window, headRef, artifacts, windowPayload, diffText, statText };
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
/** Append one JSON line to the run's progress ledger. */
|
|
1346
|
+
export function appendProgress(runDir, entry) {
|
|
1347
|
+
fs.appendFileSync(path.join(runDir, 'progress.jsonl'), `${JSON.stringify(entry)}\n`, 'utf8');
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
/* ------------------------------ WP4 — agent -------------------------------- */
|
|
1351
|
+
|
|
1352
|
+
export const SURFACES = ['rule', 'agent', 'command', 'hook', 'script', 'scheduler', 'docs', 'install', 'schema'];
|
|
1353
|
+
export const CONFIDENCES = ['low', 'medium', 'high'];
|
|
1354
|
+
export const MECHANISM_KEY_RE = /^[a-z][a-z0-9]*(?:-[a-z0-9]+){1,5}$/;
|
|
1355
|
+
export const ANSWER_START = '===UPSTREAM-RESEARCH-JSON===';
|
|
1356
|
+
export const ANSWER_END = '===END-UPSTREAM-RESEARCH-JSON===';
|
|
1357
|
+
export const MAX_IDEAS_PER_ANSWER = 8;
|
|
1358
|
+
export const PROJECT_PROMPT_CAP_BYTES = 98_304;
|
|
1359
|
+
export const ANSWER_CAP_BYTES = 1024 * 1024;
|
|
1360
|
+
|
|
1361
|
+
/** The argv after `opencode`, with no `--worktree` and no pinned model. */
|
|
1362
|
+
export function buildOpencodeArgv({ projectId, runId, promptPath, model = null, instruction }) {
|
|
1363
|
+
const args = ['run', '--agent', 'upstream-researcher', '--format', 'json', '--archived', '--auto'];
|
|
1364
|
+
if (model) args.push('--model', model);
|
|
1365
|
+
args.push('--title', `upstream-research ${projectId} ${runId}`, '--file', promptPath, instruction);
|
|
1366
|
+
return args;
|
|
1367
|
+
}
|
|
1368
|
+
|
|
1369
|
+
/** Compose the static prompt plus the per-project block. */
|
|
1370
|
+
export function composeProjectPrompt({ staticPrompt, project, windowPayload, diffText, priorArtSection }) {
|
|
1371
|
+
const commits = windowPayload.commits
|
|
1372
|
+
.map((commit) => `- ${commit.sha.slice(0, 12)} ${commit.date} ${commit.subject}`)
|
|
1373
|
+
.join('\n');
|
|
1374
|
+
const tags = windowPayload.tags.length > 0 ? windowPayload.tags.join(', ') : '(none)';
|
|
1375
|
+
const paths = project.scopeHints?.paths?.length ? project.scopeHints.paths.join(', ') : '(all files)';
|
|
1376
|
+
const diff = diffText.length > 0 ? diffText : `[no diff: window kind ${windowPayload.kind}]\n`;
|
|
1377
|
+
const changelog =
|
|
1378
|
+
windowPayload.changelogExcerpt.length > 0
|
|
1379
|
+
? `\n### CHANGELOG excerpt\n\n\`\`\`\n${windowPayload.changelogExcerpt}\n\`\`\`\n`
|
|
1380
|
+
: '';
|
|
1381
|
+
return `${staticPrompt.trimEnd()}
|
|
1382
|
+
|
|
1383
|
+
## Project under review
|
|
1384
|
+
|
|
1385
|
+
- **id:** ${project.id}
|
|
1386
|
+
- **title:** ${project.title}
|
|
1387
|
+
- **url:** ${project.url}
|
|
1388
|
+
- **ref:** ${project.refs?.branch ?? 'HEAD'}
|
|
1389
|
+
- **scope paths:** ${paths}
|
|
1390
|
+
- **scope notes:** ${project.scopeHints?.notes || '(none)'}
|
|
1391
|
+
|
|
1392
|
+
## Window
|
|
1393
|
+
|
|
1394
|
+
- **kind:** ${windowPayload.kind}
|
|
1395
|
+
- **from:** ${windowPayload.from ?? '(first scan)'}
|
|
1396
|
+
- **to:** ${windowPayload.to}
|
|
1397
|
+
- **tags:** ${tags}
|
|
1398
|
+
- **commits:** ${windowPayload.commits.length}
|
|
1399
|
+
|
|
1400
|
+
${commits || '- (no commits in the window)'}
|
|
1401
|
+
${changelog}
|
|
1402
|
+
## Diff
|
|
1403
|
+
|
|
1404
|
+
\`\`\`diff
|
|
1405
|
+
${diff}
|
|
1406
|
+
\`\`\`
|
|
1407
|
+
|
|
1408
|
+
## Prior art
|
|
1409
|
+
|
|
1410
|
+
${priorArtSection}
|
|
1411
|
+
`;
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
/** Extract assistant text from the `--format json` event stream. */
|
|
1415
|
+
export function extractAssistantText(stdout) {
|
|
1416
|
+
const chunks = [];
|
|
1417
|
+
const collect = (node) => {
|
|
1418
|
+
if (!node || typeof node !== 'object') return;
|
|
1419
|
+
if (Array.isArray(node)) {
|
|
1420
|
+
for (const item of node) collect(item);
|
|
1421
|
+
return;
|
|
1422
|
+
}
|
|
1423
|
+
for (const [key, value] of Object.entries(node)) {
|
|
1424
|
+
if (typeof value === 'string' && ['text', 'content', 'message'].includes(key)) chunks.push(value);
|
|
1425
|
+
else if (value && typeof value === 'object') collect(value);
|
|
1426
|
+
}
|
|
1427
|
+
};
|
|
1428
|
+
for (const line of `${stdout}`.split('\n')) {
|
|
1429
|
+
const trimmed = line.trim();
|
|
1430
|
+
if (trimmed.length === 0) continue;
|
|
1431
|
+
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
|
|
1432
|
+
try {
|
|
1433
|
+
collect(JSON.parse(trimmed));
|
|
1434
|
+
continue;
|
|
1435
|
+
} catch {
|
|
1436
|
+
// Not a JSON event; treat it as plain text below.
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
chunks.push(line);
|
|
1440
|
+
}
|
|
1441
|
+
return chunks.join('\n');
|
|
1442
|
+
}
|
|
1443
|
+
|
|
1444
|
+
/** Parse the single marked JSON object. Throws `E_ANSWER_SHAPE` when absent or invalid. */
|
|
1445
|
+
export function parseMarkedJson(text) {
|
|
1446
|
+
const start = text.indexOf(ANSWER_START);
|
|
1447
|
+
const end = text.indexOf(ANSWER_END);
|
|
1448
|
+
if (start < 0 || end < 0 || end <= start) {
|
|
1449
|
+
throw new UpstreamError(RUNNER_CODES.answerShape, 'the answer has no marked JSON block', {
|
|
1450
|
+
exitCode: EXIT_CODES.ok,
|
|
1451
|
+
});
|
|
1452
|
+
}
|
|
1453
|
+
const body = text.slice(start + ANSWER_START.length, end).trim();
|
|
1454
|
+
try {
|
|
1455
|
+
return JSON.parse(body);
|
|
1456
|
+
} catch (error) {
|
|
1457
|
+
throw new UpstreamError(RUNNER_CODES.answerShape, `the marked block is not JSON: ${error instanceof Error ? error.message : String(error)}`, {
|
|
1458
|
+
exitCode: EXIT_CODES.ok,
|
|
1459
|
+
});
|
|
1460
|
+
}
|
|
1461
|
+
}
|
|
1462
|
+
|
|
1463
|
+
const isString = (value, max) => typeof value === 'string' && value.length > 0 && value.length <= max;
|
|
1464
|
+
|
|
1465
|
+
/** One line, no control characters: agent free text must not forge digest lines. */
|
|
1466
|
+
const isSingleLine = (value, max) => isString(value, max) && !/[\r\n\u0000-\u001f\u007f]/.test(value);
|
|
1467
|
+
|
|
1468
|
+
/**
|
|
1469
|
+
* Agent free text is data. Collapse newlines and control characters to one
|
|
1470
|
+
* line before any agent-controlled string reaches the committed digest.
|
|
1471
|
+
*/
|
|
1472
|
+
export function neutraliseInlineText(value) {
|
|
1473
|
+
return `${value ?? ''}`
|
|
1474
|
+
.replace(/\r\n?/g, '\n')
|
|
1475
|
+
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, ' ')
|
|
1476
|
+
.split('\n')
|
|
1477
|
+
.map((line) => line.trim())
|
|
1478
|
+
.filter(Boolean)
|
|
1479
|
+
.join(' ')
|
|
1480
|
+
.trim();
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
/** One-line text safe inside a Markdown code span. */
|
|
1484
|
+
export function neutraliseCodeText(value) {
|
|
1485
|
+
return neutraliseInlineText(value).replace(/`/g, "'");
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
/** Validate shape, enums, ranges, and evidence counts. Returns named findings. */
|
|
1489
|
+
export function validateAnswer(answer, { projectId, config }) {
|
|
1490
|
+
const findings = [];
|
|
1491
|
+
const add = (code, field, message) => findings.push({ code, field, message });
|
|
1492
|
+
if (!isRecord(answer)) {
|
|
1493
|
+
add(RUNNER_CODES.answerShape, 'answer', 'must be an object');
|
|
1494
|
+
return findings;
|
|
1495
|
+
}
|
|
1496
|
+
if (answer.schemaVersion !== SCHEMA_VERSION) add(RUNNER_CODES.answerShape, 'schemaVersion', `must be ${SCHEMA_VERSION}`);
|
|
1497
|
+
if (answer.projectId !== projectId) add(RUNNER_CODES.answerShape, 'projectId', `must be "${projectId}"`);
|
|
1498
|
+
if (!isRecord(answer.window) || !['range', 'baseline', 'unprovable'].includes(answer.window.kind)) {
|
|
1499
|
+
add(RUNNER_CODES.answerShape, 'window.kind', 'must be range | baseline | unprovable');
|
|
1500
|
+
}
|
|
1501
|
+
if (!Array.isArray(answer.ideas)) {
|
|
1502
|
+
add(RUNNER_CODES.answerShape, 'ideas', 'must be an array');
|
|
1503
|
+
return findings;
|
|
1504
|
+
}
|
|
1505
|
+
const maxIdeas = Math.min(MAX_IDEAS_PER_ANSWER, config.budget.maxIdeasPerProject);
|
|
1506
|
+
if (answer.ideas.length > maxIdeas) add(RUNNER_CODES.answerRange, 'ideas', `at most ${maxIdeas} ideas are allowed`);
|
|
1507
|
+
const seenKeys = new Set();
|
|
1508
|
+
for (const [index, idea] of answer.ideas.entries()) {
|
|
1509
|
+
const field = `ideas[${index}]`;
|
|
1510
|
+
if (!isRecord(idea)) {
|
|
1511
|
+
add(RUNNER_CODES.answerShape, field, 'must be an object');
|
|
1512
|
+
continue;
|
|
1513
|
+
}
|
|
1514
|
+
if (!isSingleLine(idea.title, 100)) add(RUNNER_CODES.answerRange, `${field}.title`, 'must be 1…100 chars on one line without control characters');
|
|
1515
|
+
if (!SURFACES.includes(idea.surface)) add(RUNNER_CODES.answerEnum, `${field}.surface`, `must be one of ${SURFACES.join(' | ')}`);
|
|
1516
|
+
if (!isSingleLine(idea.mechanism, 600)) add(RUNNER_CODES.answerRange, `${field}.mechanism`, 'must be 1…600 chars on one line without control characters');
|
|
1517
|
+
if (typeof idea.mechanismKey !== 'string' || !MECHANISM_KEY_RE.test(idea.mechanismKey)) {
|
|
1518
|
+
add(RUNNER_CODES.answerEnum, `${field}.mechanismKey`, `must match ${MECHANISM_KEY_RE}`);
|
|
1519
|
+
} else if (seenKeys.has(idea.mechanismKey)) {
|
|
1520
|
+
add(RUNNER_CODES.answerRange, `${field}.mechanismKey`, 'duplicate mechanismKey in one answer');
|
|
1521
|
+
} else {
|
|
1522
|
+
seenKeys.add(idea.mechanismKey);
|
|
1523
|
+
}
|
|
1524
|
+
if (!Array.isArray(idea.evidence) || idea.evidence.length < 1 || idea.evidence.length > 4) {
|
|
1525
|
+
add(RUNNER_CODES.answerEvidence, `${field}.evidence`, 'must hold 1…4 items');
|
|
1526
|
+
} else {
|
|
1527
|
+
for (const [evidenceIndex, evidence] of idea.evidence.entries()) {
|
|
1528
|
+
const evidenceField = `${field}.evidence[${evidenceIndex}]`;
|
|
1529
|
+
if (!isRecord(evidence)) {
|
|
1530
|
+
add(RUNNER_CODES.answerEvidence, evidenceField, 'must be an object');
|
|
1531
|
+
continue;
|
|
1532
|
+
}
|
|
1533
|
+
if (!isSingleLine(evidence.file, 400)) add(RUNNER_CODES.answerEvidence, `${evidenceField}.file`, 'must be 1…400 chars on one line without control characters');
|
|
1534
|
+
if (!Number.isInteger(evidence.line) || evidence.line < 1) add(RUNNER_CODES.answerEvidence, `${evidenceField}.line`, 'must be a positive integer');
|
|
1535
|
+
if (!isString(evidence.commit, 64) || !/^[0-9a-f]{7,64}$/i.test(evidence.commit)) {
|
|
1536
|
+
add(RUNNER_CODES.answerEvidence, `${evidenceField}.commit`, 'must be a hex commit id');
|
|
1537
|
+
}
|
|
1538
|
+
if (!isSingleLine(evidence.quote, 240)) add(RUNNER_CODES.answerEvidence, `${evidenceField}.quote`, 'must be 1…240 chars on one line without control characters');
|
|
1539
|
+
}
|
|
1540
|
+
}
|
|
1541
|
+
if (!isRecord(idea.whyNow) || !isString(idea.whyNow.commit, 64) || !isSingleLine(idea.whyNow.summary, 240)) {
|
|
1542
|
+
add(RUNNER_CODES.answerShape, `${field}.whyNow`, 'must carry a commit and a one-line summary without control characters');
|
|
1543
|
+
} else if (idea.whyNow.tag !== null && !isSingleLine(idea.whyNow.tag, 120)) {
|
|
1544
|
+
add(RUNNER_CODES.answerShape, `${field}.whyNow.tag`, 'must be null or a one-line tag string');
|
|
1545
|
+
}
|
|
1546
|
+
if (!isRecord(idea.scores)) {
|
|
1547
|
+
add(RUNNER_CODES.answerShape, `${field}.scores`, 'must be an object');
|
|
1548
|
+
} else {
|
|
1549
|
+
for (const score of ['fit', 'value', 'effort', 'risk']) {
|
|
1550
|
+
if (!Number.isInteger(idea.scores[score]) || idea.scores[score] < 1 || idea.scores[score] > 5) {
|
|
1551
|
+
add(RUNNER_CODES.answerRange, `${field}.scores.${score}`, 'must be an integer 1…5');
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
}
|
|
1555
|
+
if (!CONFIDENCES.includes(idea.confidence)) add(RUNNER_CODES.answerEnum, `${field}.confidence`, 'must be low | medium | high');
|
|
1556
|
+
if (!isSingleLine(idea.case, 1200)) add(RUNNER_CODES.answerRange, `${field}.case`, 'must be 1…1200 chars on one line without control characters');
|
|
1557
|
+
if (idea.invalidates !== null) {
|
|
1558
|
+
if (
|
|
1559
|
+
!isRecord(idea.invalidates) ||
|
|
1560
|
+
!isString(idea.invalidates.priorRow, 16) ||
|
|
1561
|
+
!isString(idea.invalidates.commit, 64) ||
|
|
1562
|
+
!/^[0-9a-f]{7,64}$/i.test(idea.invalidates.commit) ||
|
|
1563
|
+
!isSingleLine(idea.invalidates.reason, 240)
|
|
1564
|
+
) {
|
|
1565
|
+
add(RUNNER_CODES.answerShape, `${field}.invalidates`, 'must be null or {priorRow, commit (hex), reason (one line)}');
|
|
1566
|
+
}
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
return findings;
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
/** Check one evidence item inside the clone: the blob exists and the quote appears. */
|
|
1573
|
+
export function verifyEvidence({ cloneDir, evidence, env = process.env, config }) {
|
|
1574
|
+
const location = `${evidence.commit}:${evidence.file}`;
|
|
1575
|
+
const exists = runGit(['cat-file', '-e', location], {
|
|
1576
|
+
cwd: cloneDir,
|
|
1577
|
+
env,
|
|
1578
|
+
timeoutMs: config.scan.fetchTimeoutMs,
|
|
1579
|
+
});
|
|
1580
|
+
if (exists.status !== 0) return false;
|
|
1581
|
+
const shown = runGit(['show', location], {
|
|
1582
|
+
cwd: cloneDir,
|
|
1583
|
+
env,
|
|
1584
|
+
timeoutMs: config.scan.fetchTimeoutMs,
|
|
1585
|
+
});
|
|
1586
|
+
return shown.status === 0 && shown.stdout.includes(evidence.quote);
|
|
1587
|
+
}
|
|
1588
|
+
|
|
1589
|
+
/** Run the agent binary with the base environment only. */
|
|
1590
|
+
export function runAgent({ binaryPath, args, cwd, env = process.env, timeoutMs, maxOutputBytes }) {
|
|
1591
|
+
const result = spawnSync(binaryPath, args, {
|
|
1592
|
+
cwd,
|
|
1593
|
+
encoding: 'utf8',
|
|
1594
|
+
timeout: timeoutMs,
|
|
1595
|
+
maxBuffer: maxOutputBytes,
|
|
1596
|
+
env: minimalEnv(env),
|
|
1597
|
+
});
|
|
1598
|
+
if (result.error) {
|
|
1599
|
+
const code = result.error.code === 'ETIMEDOUT' ? RUNNER_CODES.agentTimeout : RUNNER_CODES.agentFailed;
|
|
1600
|
+
throw new UpstreamError(code, `agent call failed: ${result.error.message}`, {
|
|
1601
|
+
exitCode: EXIT_CODES.ok,
|
|
1602
|
+
remedy: REMEDIES[code] ?? '',
|
|
1603
|
+
});
|
|
1604
|
+
}
|
|
1605
|
+
if (result.status !== 0) {
|
|
1606
|
+
throw new UpstreamError(
|
|
1607
|
+
RUNNER_CODES.agentFailed,
|
|
1608
|
+
`agent exited with ${result.status}: ${`${result.stderr || ''}`.trim().slice(0, 400)}`,
|
|
1609
|
+
{ exitCode: EXIT_CODES.ok },
|
|
1610
|
+
);
|
|
1611
|
+
}
|
|
1612
|
+
return { stdout: `${result.stdout || ''}`, stderr: `${result.stderr || ''}` };
|
|
1613
|
+
}
|
|
1614
|
+
|
|
1615
|
+
/** `git status --porcelain`, or `null` when the path is not a repository. */
|
|
1616
|
+
export function porcelainStatus(dir, env = process.env) {
|
|
1617
|
+
const result = runGit(['status', '--porcelain'], { cwd: dir, env });
|
|
1618
|
+
return result.status === 0 ? result.stdout : null;
|
|
1619
|
+
}
|
|
1620
|
+
|
|
1621
|
+
/* ----------------------------- WP5 — prior art ----------------------------- */
|
|
1622
|
+
|
|
1623
|
+
/** Fixed stopword list for the documented fallback normalizer. */
|
|
1624
|
+
export const PRIOR_ART_STOPWORDS = new Set([
|
|
1625
|
+
'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from', 'in', 'into', 'is', 'it', 'its',
|
|
1626
|
+
'of', 'on', 'or', 'that', 'the', 'their', 'this', 'to', 'was', 'were', 'will', 'with', 'without',
|
|
1627
|
+
'via', 'per', 'not', 'no', 'only', 'any', 'every',
|
|
1628
|
+
]);
|
|
1629
|
+
|
|
1630
|
+
/** Lowercase, punctuation to spaces, stopwords dropped, first four tokens. */
|
|
1631
|
+
export function normalizeMechanismKey(text) {
|
|
1632
|
+
const tokens = `${text}`
|
|
1633
|
+
.toLowerCase()
|
|
1634
|
+
.replace(/[^a-z0-9]+/g, ' ')
|
|
1635
|
+
.trim()
|
|
1636
|
+
.split(/\s+/)
|
|
1637
|
+
.filter((token) => token.length > 0 && !PRIOR_ART_STOPWORDS.has(token));
|
|
1638
|
+
return tokens.slice(0, 4).join('-');
|
|
1639
|
+
}
|
|
1640
|
+
|
|
1641
|
+
/** Deterministic surface inference for a prior-art row without a pinned signature. */
|
|
1642
|
+
export function inferSurface(text) {
|
|
1643
|
+
const value = `${text}`.toLowerCase();
|
|
1644
|
+
const rules = [
|
|
1645
|
+
['scheduler', /schedul|cron|job run|timer/],
|
|
1646
|
+
['hook', /hook|chain|sentinel/],
|
|
1647
|
+
['install', /install|seed|init|upgrade|golden/],
|
|
1648
|
+
['schema', /schema|migration|contract/],
|
|
1649
|
+
['command', /command|slash|cli/],
|
|
1650
|
+
['agent', /agent|subagent|reviewer/],
|
|
1651
|
+
['rule', /rule|always-on|overlay/],
|
|
1652
|
+
['script', /script|engine|\.mjs|\.sh/],
|
|
1653
|
+
['docs', /docs|readme|changelog|adr/],
|
|
1654
|
+
];
|
|
1655
|
+
for (const [surface, pattern] of rules) {
|
|
1656
|
+
if (pattern.test(value)) return surface;
|
|
1657
|
+
}
|
|
1658
|
+
return 'docs';
|
|
1659
|
+
}
|
|
1660
|
+
|
|
1661
|
+
function splitTableRow(line) {
|
|
1662
|
+
return line
|
|
1663
|
+
.trim()
|
|
1664
|
+
.replace(/^\|/, '')
|
|
1665
|
+
.replace(/\|$/, '')
|
|
1666
|
+
.split('|')
|
|
1667
|
+
.map((cell) => cell.trim());
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
/** Tokens used for the adopted-row ↔ detail-block join and the near-miss check. */
|
|
1671
|
+
function keyTokens(text) {
|
|
1672
|
+
return new Set(
|
|
1673
|
+
`${text}`
|
|
1674
|
+
.toLowerCase()
|
|
1675
|
+
.replace(/[^a-z0-9]+/g, ' ')
|
|
1676
|
+
.trim()
|
|
1677
|
+
.split(/\s+/)
|
|
1678
|
+
.filter((token) => token.length > 0 && !PRIOR_ART_STOPWORDS.has(token)),
|
|
1679
|
+
);
|
|
1680
|
+
}
|
|
1681
|
+
|
|
1682
|
+
/** Parse both attribution table shapes by heading and named column. */
|
|
1683
|
+
export function parseAttribution(text) {
|
|
1684
|
+
const lines = `${text}`.split('\n');
|
|
1685
|
+
const adopted = [];
|
|
1686
|
+
const rejected = [];
|
|
1687
|
+
const details = [];
|
|
1688
|
+
const headers = {};
|
|
1689
|
+
let section = null;
|
|
1690
|
+
let inDetails = false;
|
|
1691
|
+
let detailProject = null;
|
|
1692
|
+
let currentDetail = null;
|
|
1693
|
+
const flushDetail = () => {
|
|
1694
|
+
if (currentDetail) details.push(currentDetail);
|
|
1695
|
+
currentDetail = null;
|
|
1696
|
+
};
|
|
1697
|
+
for (const line of lines) {
|
|
1698
|
+
if (/^##\s+Adopted\b/.test(line)) {
|
|
1699
|
+
flushDetail();
|
|
1700
|
+
section = 'adopted';
|
|
1701
|
+
inDetails = false;
|
|
1702
|
+
headers.adopted = null;
|
|
1703
|
+
continue;
|
|
1704
|
+
}
|
|
1705
|
+
if (/^##\s+Considered, not adopted\b/.test(line)) {
|
|
1706
|
+
flushDetail();
|
|
1707
|
+
section = 'rejected';
|
|
1708
|
+
inDetails = false;
|
|
1709
|
+
headers.rejected = null;
|
|
1710
|
+
continue;
|
|
1711
|
+
}
|
|
1712
|
+
if (/^##\s+Project details\b/.test(line)) {
|
|
1713
|
+
flushDetail();
|
|
1714
|
+
section = null;
|
|
1715
|
+
inDetails = true;
|
|
1716
|
+
continue;
|
|
1717
|
+
}
|
|
1718
|
+
if (/^##\s+/.test(line)) {
|
|
1719
|
+
flushDetail();
|
|
1720
|
+
section = null;
|
|
1721
|
+
inDetails = false;
|
|
1722
|
+
continue;
|
|
1723
|
+
}
|
|
1724
|
+
if (inDetails) {
|
|
1725
|
+
if (/^###\s+/.test(line)) {
|
|
1726
|
+
flushDetail();
|
|
1727
|
+
detailProject = line.replace(/^###\s+/, '').trim();
|
|
1728
|
+
continue;
|
|
1729
|
+
}
|
|
1730
|
+
const start = line.match(/^- \*\*(A\d+)\s*[—–-]\s*(.*?)\*\*\s*(.*)$/);
|
|
1731
|
+
if (start) {
|
|
1732
|
+
flushDetail();
|
|
1733
|
+
currentDetail = {
|
|
1734
|
+
rowId: start[1],
|
|
1735
|
+
project: detailProject,
|
|
1736
|
+
idea: `${start[2]} ${start[3]}`.trim(),
|
|
1737
|
+
};
|
|
1738
|
+
continue;
|
|
1739
|
+
}
|
|
1740
|
+
if (currentDetail && /^\s{2,}\S/.test(line)) {
|
|
1741
|
+
currentDetail.idea = `${currentDetail.idea} ${line.trim()}`.trim();
|
|
1742
|
+
continue;
|
|
1743
|
+
}
|
|
1744
|
+
continue;
|
|
1745
|
+
}
|
|
1746
|
+
if (!section) continue;
|
|
1747
|
+
if (!line.trim().startsWith('|')) continue;
|
|
1748
|
+
const cells = splitTableRow(line);
|
|
1749
|
+
if (cells.every((cell) => /^:?-{3,}:?$/.test(cell))) continue;
|
|
1750
|
+
if (!headers[section]) {
|
|
1751
|
+
headers[section] = cells.map((cell) => cell.toLowerCase().replace(/\*\*/g, '').trim());
|
|
1752
|
+
continue;
|
|
1753
|
+
}
|
|
1754
|
+
const mapped = {};
|
|
1755
|
+
headers[section].forEach((name, index) => {
|
|
1756
|
+
mapped[name] = cells[index] ?? '';
|
|
1757
|
+
});
|
|
1758
|
+
if (section === 'adopted') {
|
|
1759
|
+
adopted.push({
|
|
1760
|
+
project: mapped.project,
|
|
1761
|
+
idea: mapped['idea adopted'],
|
|
1762
|
+
status: mapped.status,
|
|
1763
|
+
evidence: mapped.evidence,
|
|
1764
|
+
});
|
|
1765
|
+
} else {
|
|
1766
|
+
rejected.push({
|
|
1767
|
+
rowId: mapped['#'],
|
|
1768
|
+
project: mapped.project,
|
|
1769
|
+
idea: mapped['idea considered'],
|
|
1770
|
+
whyNot: mapped['why not adopted'],
|
|
1771
|
+
status: mapped.status,
|
|
1772
|
+
evidence: mapped.evidence,
|
|
1773
|
+
});
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
flushDetail();
|
|
1777
|
+
const usedDetails = new Set();
|
|
1778
|
+
for (const row of adopted) {
|
|
1779
|
+
const rowTokens = keyTokens(row.idea);
|
|
1780
|
+
let best = null;
|
|
1781
|
+
let bestScore = 0;
|
|
1782
|
+
for (const detail of details) {
|
|
1783
|
+
if (detail.project !== row.project || usedDetails.has(detail.rowId)) continue;
|
|
1784
|
+
const detailTokens = keyTokens(detail.idea);
|
|
1785
|
+
let shared = 0;
|
|
1786
|
+
for (const token of rowTokens) if (detailTokens.has(token)) shared += 1;
|
|
1787
|
+
const score = shared / Math.max(1, Math.min(rowTokens.size, detailTokens.size));
|
|
1788
|
+
if (score > bestScore) {
|
|
1789
|
+
bestScore = score;
|
|
1790
|
+
best = detail;
|
|
1791
|
+
}
|
|
1792
|
+
}
|
|
1793
|
+
if (best && bestScore >= 0.45) {
|
|
1794
|
+
row.rowId = best.rowId;
|
|
1795
|
+
usedDetails.add(best.rowId);
|
|
1796
|
+
row.unmapped = false;
|
|
1797
|
+
} else {
|
|
1798
|
+
row.rowId = `project+idea:${row.project}:${normalizeMechanismKey(row.idea)}`;
|
|
1799
|
+
row.unmapped = true;
|
|
1800
|
+
}
|
|
1801
|
+
}
|
|
1802
|
+
return { adopted, rejected, details };
|
|
1803
|
+
}
|
|
1804
|
+
|
|
1805
|
+
/** Build the durable `signatures.json` payload from one attribution file. */
|
|
1806
|
+
export function buildSignaturesIndex({ text, sourcePath, cache = null }) {
|
|
1807
|
+
const parsed = parseAttribution(text);
|
|
1808
|
+
const pinned = new Map(
|
|
1809
|
+
(cache?.entries ?? []).filter((entry) => typeof entry.rowId === 'string').map((entry) => [entry.rowId, entry]),
|
|
1810
|
+
);
|
|
1811
|
+
const entries = [];
|
|
1812
|
+
let unmapped = 0;
|
|
1813
|
+
const push = (row, state) => {
|
|
1814
|
+
const existing = pinned.get(row.rowId);
|
|
1815
|
+
const signature =
|
|
1816
|
+
typeof existing?.signature === 'string'
|
|
1817
|
+
? existing.signature
|
|
1818
|
+
: `${inferSurface(row.idea)}:${normalizeMechanismKey(row.idea)}`;
|
|
1819
|
+
if (row.unmapped) unmapped += 1;
|
|
1820
|
+
entries.push({
|
|
1821
|
+
rowId: row.rowId,
|
|
1822
|
+
project: row.project,
|
|
1823
|
+
signature,
|
|
1824
|
+
state,
|
|
1825
|
+
idea: row.idea,
|
|
1826
|
+
evidence: row.evidence ?? '',
|
|
1827
|
+
});
|
|
1828
|
+
};
|
|
1829
|
+
for (const row of parsed.adopted) push(row, 'adopted');
|
|
1830
|
+
for (const row of parsed.rejected) push(row, 'rejected');
|
|
1831
|
+
return {
|
|
1832
|
+
schemaVersion: SCHEMA_VERSION,
|
|
1833
|
+
generatedFrom: { path: sourcePath, sha256: sha256(text), rows: entries.length },
|
|
1834
|
+
entries,
|
|
1835
|
+
unmapped,
|
|
1836
|
+
};
|
|
1837
|
+
}
|
|
1838
|
+
|
|
1839
|
+
const attributionPath = (teamRoot) => path.join(teamRoot, ATTRIBUTION_FILE);
|
|
1840
|
+
const signaturesPath = (teamRoot) => path.join(teamRoot, SIGNATURES_FILE);
|
|
1841
|
+
|
|
1842
|
+
/** Read the durable index, tolerating a missing or malformed file. */
|
|
1843
|
+
export function readSignaturesIndex(teamRoot) {
|
|
1844
|
+
const result = readJsonFile(signaturesPath(teamRoot));
|
|
1845
|
+
if (result.error || !isRecord(result.value) || !Array.isArray(result.value.entries)) return null;
|
|
1846
|
+
return result.value;
|
|
1847
|
+
}
|
|
1848
|
+
|
|
1849
|
+
/**
|
|
1850
|
+
* Prior-art state: `full` (file + matching cache), `cache-only` (one usable
|
|
1851
|
+
* input), or `missing` (neither). Never optimistic.
|
|
1852
|
+
*/
|
|
1853
|
+
export function loadPriorArt({ teamRoot }) {
|
|
1854
|
+
const file = attributionPath(teamRoot);
|
|
1855
|
+
const hasFile = fs.existsSync(file);
|
|
1856
|
+
const text = hasFile ? fs.readFileSync(file, 'utf8') : null;
|
|
1857
|
+
const cache = readSignaturesIndex(teamRoot);
|
|
1858
|
+
if (!hasFile && !cache) {
|
|
1859
|
+
return { state: 'missing', reason: 'attribution file and signature index are absent', entries: [], rows: 0 };
|
|
1860
|
+
}
|
|
1861
|
+
if (!hasFile) {
|
|
1862
|
+
return { state: 'cache-only', reason: 'attribution file absent', entries: cache.entries, rows: cache.entries.length };
|
|
1863
|
+
}
|
|
1864
|
+
const parsed = buildSignaturesIndex({ text, sourcePath: ATTRIBUTION_FILE, cache });
|
|
1865
|
+
if (!cache) {
|
|
1866
|
+
return { state: 'cache-only', reason: 'signature index absent', entries: parsed.entries, rows: parsed.entries.length, unmapped: parsed.unmapped };
|
|
1867
|
+
}
|
|
1868
|
+
if (cache.generatedFrom?.sha256 !== sha256(text)) {
|
|
1869
|
+
return { state: 'cache-only', reason: 'source hash differs', entries: cache.entries, rows: cache.entries.length };
|
|
1870
|
+
}
|
|
1871
|
+
const fileIds = new Set(parsed.entries.map((entry) => entry.rowId));
|
|
1872
|
+
const cacheIds = new Set(cache.entries.map((entry) => entry.rowId));
|
|
1873
|
+
const sameRows = fileIds.size === cacheIds.size && [...fileIds].every((id) => cacheIds.has(id));
|
|
1874
|
+
if (!sameRows || parsed.unmapped > 0) {
|
|
1875
|
+
return {
|
|
1876
|
+
state: 'cache-only',
|
|
1877
|
+
reason: parsed.unmapped > 0 ? 'unmapped rows' : 'row set differs',
|
|
1878
|
+
entries: cache.entries,
|
|
1879
|
+
rows: cache.entries.length,
|
|
1880
|
+
};
|
|
1881
|
+
}
|
|
1882
|
+
return { state: 'full', reason: null, entries: cache.entries, rows: cache.entries.length };
|
|
1883
|
+
}
|
|
1884
|
+
|
|
1885
|
+
/** `signatures --check` / `--write`: report drift and optionally refresh the cache. */
|
|
1886
|
+
export function refreshSignatures({ teamRoot, write }) {
|
|
1887
|
+
const file = attributionPath(teamRoot);
|
|
1888
|
+
if (!fs.existsSync(file)) {
|
|
1889
|
+
return { state: 'missing', rows: 0, written: false, reason: 'attribution file absent' };
|
|
1890
|
+
}
|
|
1891
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
1892
|
+
const cache = readSignaturesIndex(teamRoot);
|
|
1893
|
+
const index = buildSignaturesIndex({ text, sourcePath: ATTRIBUTION_FILE, cache });
|
|
1894
|
+
const cacheIds = new Set((cache?.entries ?? []).map((entry) => entry.rowId));
|
|
1895
|
+
const fileIds = new Set(index.entries.map((entry) => entry.rowId));
|
|
1896
|
+
const drift = {
|
|
1897
|
+
added: [...fileIds].filter((id) => !cacheIds.has(id)),
|
|
1898
|
+
removed: [...cacheIds].filter((id) => !fileIds.has(id)),
|
|
1899
|
+
};
|
|
1900
|
+
let written = false;
|
|
1901
|
+
if (write) {
|
|
1902
|
+
writeJsonFile(signaturesPath(teamRoot), index);
|
|
1903
|
+
written = true;
|
|
1904
|
+
}
|
|
1905
|
+
const state =
|
|
1906
|
+
cache && cache.generatedFrom?.sha256 === index.generatedFrom.sha256 && drift.added.length === 0 && drift.removed.length === 0
|
|
1907
|
+
? 'full'
|
|
1908
|
+
: 'cache-only';
|
|
1909
|
+
return { state, rows: index.entries.length, written, drift };
|
|
1910
|
+
}
|
|
1911
|
+
|
|
1912
|
+
/** Parse the committed digest corpus into items with a `State:` line. */
|
|
1913
|
+
export function parseDigest(text, runId) {
|
|
1914
|
+
const items = [];
|
|
1915
|
+
let inProposals = false;
|
|
1916
|
+
let current = null;
|
|
1917
|
+
const flush = () => {
|
|
1918
|
+
if (current?.signature) items.push(current);
|
|
1919
|
+
current = null;
|
|
1920
|
+
};
|
|
1921
|
+
for (const line of `${text}`.split('\n')) {
|
|
1922
|
+
if (/^##\s+Proposals\b/.test(line)) {
|
|
1923
|
+
flush();
|
|
1924
|
+
inProposals = true;
|
|
1925
|
+
continue;
|
|
1926
|
+
}
|
|
1927
|
+
if (/^##\s+/.test(line)) {
|
|
1928
|
+
flush();
|
|
1929
|
+
inProposals = false;
|
|
1930
|
+
continue;
|
|
1931
|
+
}
|
|
1932
|
+
if (!inProposals) continue;
|
|
1933
|
+
if (/^###\s+/.test(line)) {
|
|
1934
|
+
flush();
|
|
1935
|
+
current = { signature: null, state: null, task: null, runId };
|
|
1936
|
+
continue;
|
|
1937
|
+
}
|
|
1938
|
+
if (!current) continue;
|
|
1939
|
+
const signature = line.match(/^- \*\*Signature:\*\*\s*`([^`]+)`/);
|
|
1940
|
+
if (signature) current.signature = signature[1];
|
|
1941
|
+
const state = line.match(/^- \*\*State:\*\*\s*(\S+)/);
|
|
1942
|
+
if (state) current.state = state[1].replace(/[.,;]+$/, '');
|
|
1943
|
+
const task = line.match(/^- \*\*Task:\*\*\s*(.+)$/);
|
|
1944
|
+
if (task && !/^[—–-]$/.test(task[1].trim())) current.task = task[1].trim();
|
|
1945
|
+
const invalidates = line.match(/^- \*\*Invalidates:\*\*\s*`?([^`]+)`?/);
|
|
1946
|
+
if (invalidates) current.invalidates = invalidates[1].trim();
|
|
1947
|
+
}
|
|
1948
|
+
flush();
|
|
1949
|
+
return { runId, items };
|
|
1950
|
+
}
|
|
1951
|
+
|
|
1952
|
+
/** Load every committed digest, oldest first (the runId sorts). */
|
|
1953
|
+
export function loadPriorDigests(repoRoot) {
|
|
1954
|
+
const dir = path.join(repoRoot, DIGEST_DIR);
|
|
1955
|
+
if (!fs.existsSync(dir)) return [];
|
|
1956
|
+
return fs
|
|
1957
|
+
.readdirSync(dir)
|
|
1958
|
+
.filter((name) => /^digest-.+\.md$/.test(name))
|
|
1959
|
+
.sort()
|
|
1960
|
+
.map((name) => {
|
|
1961
|
+
const runId = name.replace(/^digest-/, '').replace(/\.md$/, '');
|
|
1962
|
+
return parseDigest(fs.readFileSync(path.join(dir, name), 'utf8'), runId);
|
|
1963
|
+
});
|
|
1964
|
+
}
|
|
1965
|
+
|
|
1966
|
+
/** The promotion state machine, applied to consecutive appearances of one signature. */
|
|
1967
|
+
export function isLegalTransition(from, to, { invalidates = false } = {}) {
|
|
1968
|
+
if (from === to) return true;
|
|
1969
|
+
if (from === 'new') return ['promoted', 'rejected', 'deferred'].includes(to);
|
|
1970
|
+
if (from === 'deferred') return ['new', 'promoted', 'rejected'].includes(to);
|
|
1971
|
+
if (from === 'rejected') return to === 'new' && invalidates;
|
|
1972
|
+
return false;
|
|
1973
|
+
}
|
|
1974
|
+
|
|
1975
|
+
/** Validate the whole prior-digest corpus; the result is non-fatal by design. */
|
|
1976
|
+
export function validateTransitions(digests) {
|
|
1977
|
+
const bySignature = new Map();
|
|
1978
|
+
for (const digest of digests) {
|
|
1979
|
+
for (const item of digest.items) {
|
|
1980
|
+
if (!item.signature || !item.state) continue;
|
|
1981
|
+
if (!bySignature.has(item.signature)) bySignature.set(item.signature, []);
|
|
1982
|
+
bySignature.get(item.signature).push(item);
|
|
1983
|
+
}
|
|
1984
|
+
}
|
|
1985
|
+
const illegal = [];
|
|
1986
|
+
for (const [signature, items] of bySignature) {
|
|
1987
|
+
for (let index = 1; index < items.length; index += 1) {
|
|
1988
|
+
const previous = items[index - 1];
|
|
1989
|
+
const next = items[index];
|
|
1990
|
+
if (!isLegalTransition(previous.state, next.state, { invalidates: Boolean(next.invalidates) })) {
|
|
1991
|
+
illegal.push({ signature, from: previous.state, to: next.state, runId: next.runId, code: RUNNER_CODES.illegalTransition });
|
|
1992
|
+
}
|
|
1993
|
+
}
|
|
1994
|
+
}
|
|
1995
|
+
return { illegal };
|
|
1996
|
+
}
|
|
1997
|
+
|
|
1998
|
+
/** The per-project prior-art block appended to the prompt. */
|
|
1999
|
+
export function buildPriorArtSection({ projectId, priorArt, digests }) {
|
|
2000
|
+
const rows = priorArt.entries
|
|
2001
|
+
.filter((entry) => entry.project === projectId || entry.rowId?.startsWith(`${projectId}:`))
|
|
2002
|
+
.map((entry) => `- ${entry.rowId} (${entry.state}) \`${entry.signature}\` — ${entry.idea}`);
|
|
2003
|
+
const all = priorArt.entries.map((entry) => `- ${entry.rowId} (${entry.state}) \`${entry.signature}\``);
|
|
2004
|
+
const recent = digests
|
|
2005
|
+
.flatMap((digest) => digest.items.map((item) => `- ${digest.runId} \`${item.signature}\` → ${item.state}`))
|
|
2006
|
+
.slice(-40);
|
|
2007
|
+
return [
|
|
2008
|
+
`Prior-art state: ${priorArt.state}${priorArt.reason ? ` (${priorArt.reason})` : ''}`,
|
|
2009
|
+
'',
|
|
2010
|
+
'### This project',
|
|
2011
|
+
rows.length > 0 ? rows.join('\n') : '- (no adopted or rejected rows for this project)',
|
|
2012
|
+
'',
|
|
2013
|
+
'### All known signatures',
|
|
2014
|
+
all.length > 0 ? all.join('\n') : '- (none)',
|
|
2015
|
+
'',
|
|
2016
|
+
'### Recent digest states',
|
|
2017
|
+
recent.length > 0 ? recent.join('\n') : '- (none)',
|
|
2018
|
+
].join('\n');
|
|
2019
|
+
}
|
|
2020
|
+
|
|
2021
|
+
/** Accept an invalidation only when its commit is in this window and exists in the clone. */
|
|
2022
|
+
export function validInvalidation({ idea, window, cloneDir, env = process.env, config }) {
|
|
2023
|
+
const commit = idea.invalidates?.commit;
|
|
2024
|
+
if (typeof commit !== 'string' || !/^[0-9a-f]{7,64}$/i.test(commit)) return null;
|
|
2025
|
+
const inWindow =
|
|
2026
|
+
commit === window.to ||
|
|
2027
|
+
window.commits.some((entry) => entry.sha === commit || entry.sha.startsWith(commit) || commit.startsWith(entry.sha.slice(0, 12)));
|
|
2028
|
+
if (!inWindow) return null;
|
|
2029
|
+
const exists = runGit(['cat-file', '-e', `${commit}^{commit}`], {
|
|
2030
|
+
cwd: cloneDir,
|
|
2031
|
+
env,
|
|
2032
|
+
timeoutMs: config.scan.fetchTimeoutMs,
|
|
2033
|
+
});
|
|
2034
|
+
return exists.status === 0 ? commit : null;
|
|
2035
|
+
}
|
|
2036
|
+
|
|
2037
|
+
function nearMiss(signature, entries) {
|
|
2038
|
+
const [surface, key] = signature.split(':');
|
|
2039
|
+
const tokens = new Set(key.split('-'));
|
|
2040
|
+
for (const entry of entries) {
|
|
2041
|
+
if (typeof entry.signature !== 'string') continue;
|
|
2042
|
+
const [entrySurface, entryKey] = entry.signature.split(':');
|
|
2043
|
+
if (entrySurface !== surface) continue;
|
|
2044
|
+
const shared = entryKey.split('-').filter((token) => tokens.has(token)).length;
|
|
2045
|
+
if (shared >= 2) return entry;
|
|
2046
|
+
}
|
|
2047
|
+
return null;
|
|
2048
|
+
}
|
|
2049
|
+
|
|
2050
|
+
/**
|
|
2051
|
+
* Dedupe by mechanism. `missing` keeps everything but marks it unverified and
|
|
2052
|
+
* never labels it new; adopted and unrevisited rejections never reach the digest.
|
|
2053
|
+
*/
|
|
2054
|
+
export function dedupeIdeas({ ideas, priorArt, digests, window, cloneDir, env = process.env, config }) {
|
|
2055
|
+
if (priorArt.state === 'missing') {
|
|
2056
|
+
return {
|
|
2057
|
+
kept: ideas.map((idea) => ({ ...idea, dedupe: { status: 'unverified' } })),
|
|
2058
|
+
dropped: [],
|
|
2059
|
+
unverified: true,
|
|
2060
|
+
};
|
|
2061
|
+
}
|
|
2062
|
+
const exact = new Map(priorArt.entries.map((entry) => [entry.signature, entry]));
|
|
2063
|
+
const digestItems = (digests ?? []).flatMap((digest) => digest.items.map((item) => ({ ...item })));
|
|
2064
|
+
const kept = [];
|
|
2065
|
+
const dropped = [];
|
|
2066
|
+
for (const idea of ideas) {
|
|
2067
|
+
const signature = `${idea.surface}:${idea.mechanismKey}`;
|
|
2068
|
+
const hit = exact.get(signature);
|
|
2069
|
+
if (hit?.state === 'adopted') {
|
|
2070
|
+
dropped.push({ signature, reason: 'adopted-signature', rowId: hit.rowId });
|
|
2071
|
+
continue;
|
|
2072
|
+
}
|
|
2073
|
+
if (hit?.state === 'rejected') {
|
|
2074
|
+
const invalidation = validInvalidation({ idea, window, cloneDir, env, config });
|
|
2075
|
+
if (!invalidation) {
|
|
2076
|
+
dropped.push({ signature, reason: 'rejected-no-invalidation', rowId: hit.rowId });
|
|
2077
|
+
continue;
|
|
2078
|
+
}
|
|
2079
|
+
kept.push({ ...idea, dedupe: { status: 'revisited', rowId: hit.rowId, commit: invalidation } });
|
|
2080
|
+
continue;
|
|
2081
|
+
}
|
|
2082
|
+
const digestHit = digestItems.find((item) => item.signature === signature);
|
|
2083
|
+
if (digestHit) {
|
|
2084
|
+
if (['new', 'deferred', 'promoted'].includes(digestHit.state)) {
|
|
2085
|
+
dropped.push({ signature, reason: `seen-in: ${digestHit.runId}` });
|
|
2086
|
+
continue;
|
|
2087
|
+
}
|
|
2088
|
+
if (digestHit.state === 'rejected') {
|
|
2089
|
+
const invalidation = validInvalidation({ idea, window, cloneDir, env, config });
|
|
2090
|
+
if (!invalidation) {
|
|
2091
|
+
dropped.push({ signature, reason: 'rejected-no-invalidation', rowId: digestHit.runId });
|
|
2092
|
+
continue;
|
|
2093
|
+
}
|
|
2094
|
+
kept.push({ ...idea, dedupe: { status: 'revisited', rowId: digestHit.runId, commit: invalidation } });
|
|
2095
|
+
continue;
|
|
2096
|
+
}
|
|
2097
|
+
}
|
|
2098
|
+
const near = nearMiss(signature, priorArt.entries);
|
|
2099
|
+
kept.push({ ...idea, dedupe: near ? { status: 'near-miss', rowId: near.rowId } : { status: 'none' } });
|
|
2100
|
+
}
|
|
2101
|
+
return { kept, dropped, unverified: false };
|
|
2102
|
+
}
|
|
2103
|
+
|
|
2104
|
+
/* ------------------------------ WP6 — digest ------------------------------- */
|
|
2105
|
+
|
|
2106
|
+
export const CONFIDENCE_BONUS = { high: 1, medium: 0, low: -1 };
|
|
2107
|
+
|
|
2108
|
+
/** `score = 2·value + fit − effort − risk + confidenceBonus`. */
|
|
2109
|
+
export function scoreIdea(idea) {
|
|
2110
|
+
return (
|
|
2111
|
+
2 * idea.scores.value +
|
|
2112
|
+
idea.scores.fit -
|
|
2113
|
+
idea.scores.effort -
|
|
2114
|
+
idea.scores.risk +
|
|
2115
|
+
(CONFIDENCE_BONUS[idea.confidence] ?? 0)
|
|
2116
|
+
);
|
|
2117
|
+
}
|
|
2118
|
+
|
|
2119
|
+
/** Rank by score, value, projectId, mechanismKey. */
|
|
2120
|
+
export function rankIdeas(ideas) {
|
|
2121
|
+
return [...ideas].sort((left, right) => {
|
|
2122
|
+
const score = scoreIdea(right) - scoreIdea(left);
|
|
2123
|
+
if (score !== 0) return score;
|
|
2124
|
+
if (right.scores.value !== left.scores.value) return right.scores.value - left.scores.value;
|
|
2125
|
+
const project = `${left.projectId ?? ''}`.localeCompare(`${right.projectId ?? ''}`);
|
|
2126
|
+
if (project !== 0) return project;
|
|
2127
|
+
return `${left.mechanismKey}`.localeCompare(`${right.mechanismKey}`);
|
|
2128
|
+
});
|
|
2129
|
+
}
|
|
2130
|
+
|
|
2131
|
+
/** Resolve `config.digest.path` under `--repo-root`, refusing an escape. */
|
|
2132
|
+
export function digestDestination({ repoRoot, config, runId }) {
|
|
2133
|
+
const relative = `${config.digest.path}`.replaceAll('<runId>', runId);
|
|
2134
|
+
const destination = path.resolve(repoRoot, relative);
|
|
2135
|
+
const confined = path.relative(repoRoot, destination);
|
|
2136
|
+
if (confined.startsWith('..') || path.isAbsolute(confined)) {
|
|
2137
|
+
throw new UpstreamError(
|
|
2138
|
+
RUNNER_CODES.digestWriteFailed,
|
|
2139
|
+
`digest.path escapes --repo-root: ${config.digest.path}`,
|
|
2140
|
+
{ exitCode: EXIT_CODES.eDigestWriteFailed },
|
|
2141
|
+
);
|
|
2142
|
+
}
|
|
2143
|
+
return destination;
|
|
2144
|
+
}
|
|
2145
|
+
|
|
2146
|
+
const priorArtLabel = (priorArt) => {
|
|
2147
|
+
if (priorArt.state === 'missing') {
|
|
2148
|
+
return 'prior art missing — dedupe unverified; nothing here is confirmed new';
|
|
2149
|
+
}
|
|
2150
|
+
if (priorArt.state === 'cache-only') return `cache-only (${priorArt.reason})`;
|
|
2151
|
+
return 'full';
|
|
2152
|
+
};
|
|
2153
|
+
|
|
2154
|
+
/** Render the committed digest. Pure: every input is data. */
|
|
2155
|
+
export function renderDigest({
|
|
2156
|
+
runId,
|
|
2157
|
+
trigger,
|
|
2158
|
+
jobRevision,
|
|
2159
|
+
capability,
|
|
2160
|
+
promptSha,
|
|
2161
|
+
priorArt,
|
|
2162
|
+
config,
|
|
2163
|
+
budget,
|
|
2164
|
+
registry,
|
|
2165
|
+
selection,
|
|
2166
|
+
projectReports,
|
|
2167
|
+
gaps,
|
|
2168
|
+
illegalTransitions,
|
|
2169
|
+
}) {
|
|
2170
|
+
const ideas = rankIdeas(
|
|
2171
|
+
projectReports.flatMap((project) => (project.ideas ?? []).map((idea) => ({ ...idea, projectId: project.id }))),
|
|
2172
|
+
);
|
|
2173
|
+
const proposals = ideas.slice(0, config.budget.maxIdeas);
|
|
2174
|
+
const below = ideas.slice(config.budget.maxIdeas);
|
|
2175
|
+
const enabled = registry.projects.filter((project) => project.enabled !== false).length;
|
|
2176
|
+
const scanned = selection.selected.length;
|
|
2177
|
+
const changed = projectReports.filter((project) => project.status === 'researched' && project.window?.kind !== 'no-change').length;
|
|
2178
|
+
const failed = projectReports.filter((project) => project.status === 'failed').length;
|
|
2179
|
+
const noChange = projectReports.filter((project) => project.status === 'no-change');
|
|
2180
|
+
const failedProjects = projectReports.filter((project) => project.status === 'failed');
|
|
2181
|
+
const skippedProjects = projectReports.filter((project) => project.status === 'skipped');
|
|
2182
|
+
const dropped = projectReports.flatMap((project) => project.dropped ?? []);
|
|
2183
|
+
const deferred = selection.deferred;
|
|
2184
|
+
const windowCells = projectReports
|
|
2185
|
+
.filter((project) => project.window && typeof project.window.to === 'string')
|
|
2186
|
+
.map((project) => {
|
|
2187
|
+
const from = project.window.kind === 'baseline' ? 'first scan' : project.window.from ?? 'first scan';
|
|
2188
|
+
return `\`${neutraliseCodeText(project.id)}\` \`${neutraliseCodeText(from)}\` → \`${neutraliseCodeText(project.window.to)}\``;
|
|
2189
|
+
});
|
|
2190
|
+
const lines = [];
|
|
2191
|
+
lines.push(`# Upstream research digest — ${runId}`);
|
|
2192
|
+
lines.push('');
|
|
2193
|
+
lines.push(`- **Run:** \`${runId}\``);
|
|
2194
|
+
lines.push(`- **Trigger:** \`${trigger}\``);
|
|
2195
|
+
lines.push(`- **Job revision:** \`${jobRevision}\``);
|
|
2196
|
+
lines.push(`- **Window:** ${windowCells.length > 0 ? windowCells.join(' · ') : '`none`'}`);
|
|
2197
|
+
lines.push(
|
|
2198
|
+
`- **Counts:** enabled \`${enabled}\` · scanned \`${scanned}\` · changed \`${changed}\` · deferred \`${deferred.length}\` · failed \`${failed}\``,
|
|
2199
|
+
);
|
|
2200
|
+
lines.push(
|
|
2201
|
+
`- **opencode:** \`${capability?.version ? `v${neutraliseCodeText(capability.version)}` : 'unknown'}\` (probed \`${neutraliseCodeText(capability?.probedAt ?? 'unknown')}\`)`,
|
|
2202
|
+
);
|
|
2203
|
+
lines.push(`- **Prompt sha256:** \`${promptSha.slice(0, 12)}\``);
|
|
2204
|
+
lines.push(`- **Prior art:** \`${priorArtLabel(priorArt)}\``);
|
|
2205
|
+
lines.push(
|
|
2206
|
+
`- **Budget:** \`${budget.used}\` of \`${budget.limit}\` bytes${budget.truncated ? ' · truncated' : ''}`,
|
|
2207
|
+
);
|
|
2208
|
+
lines.push(`- **Gaps:** ${gaps.length > 0 ? gaps.join('; ') : 'none'}`);
|
|
2209
|
+
lines.push(
|
|
2210
|
+
`- **Deferred:** ${
|
|
2211
|
+
deferred.length > 0
|
|
2212
|
+
? deferred.map((item) => `\`${item.project.id}\` (last scanned ${item.cursorEntry?.scannedAt ?? 'never'}, priority ${item.project.priority ?? 3})`).join(', ')
|
|
2213
|
+
: 'none'
|
|
2214
|
+
}`,
|
|
2215
|
+
);
|
|
2216
|
+
lines.push('');
|
|
2217
|
+
lines.push('## Proposals');
|
|
2218
|
+
lines.push('');
|
|
2219
|
+
if (proposals.length === 0) {
|
|
2220
|
+
lines.push('_No proposals this run. A silent week is signal; the window and the counts above are the record._');
|
|
2221
|
+
lines.push('');
|
|
2222
|
+
}
|
|
2223
|
+
proposals.forEach((idea, index) => {
|
|
2224
|
+
const signature = `${idea.surface}:${idea.mechanismKey}`;
|
|
2225
|
+
const state = idea.dedupe?.status === 'unverified' ? 'unverified' : 'new';
|
|
2226
|
+
const evidence = idea.evidence
|
|
2227
|
+
.map(
|
|
2228
|
+
(item) =>
|
|
2229
|
+
`\`${neutraliseCodeText(item.file)}:${item.line}\` @ \`${neutraliseCodeText(item.commit)}\` — "${neutraliseInlineText(item.quote)}"`,
|
|
2230
|
+
)
|
|
2231
|
+
.join('; ');
|
|
2232
|
+
lines.push(`### ${index + 1}. ${neutraliseInlineText(idea.title)} — score ${scoreIdea(idea)}`);
|
|
2233
|
+
lines.push('');
|
|
2234
|
+
lines.push(`- **Signature:** \`${signature}\``);
|
|
2235
|
+
lines.push(`- **Surface:** ${idea.surface}`);
|
|
2236
|
+
lines.push(
|
|
2237
|
+
`- **Why now:** \`${neutraliseCodeText(idea.whyNow.commit)}\` \`${idea.whyNow.tag === null ? '—' : neutraliseCodeText(idea.whyNow.tag)}\` — ${neutraliseInlineText(idea.whyNow.summary)}`,
|
|
2238
|
+
);
|
|
2239
|
+
lines.push(`- **Mechanism:** ${neutraliseInlineText(idea.mechanism)}`);
|
|
2240
|
+
lines.push(`- **Evidence:** ${evidence}`);
|
|
2241
|
+
lines.push(`- **Case:** ${neutraliseInlineText(idea.case)}`);
|
|
2242
|
+
lines.push(
|
|
2243
|
+
`- **Prior art:** ${
|
|
2244
|
+
idea.dedupe?.status === 'near-miss'
|
|
2245
|
+
? `near-miss ${idea.dedupe.rowId}`
|
|
2246
|
+
: idea.dedupe?.status === 'revisited'
|
|
2247
|
+
? `revisited (${idea.dedupe.rowId} @ ${idea.dedupe.commit})`
|
|
2248
|
+
: idea.dedupe?.status === 'unverified'
|
|
2249
|
+
? 'unverified'
|
|
2250
|
+
: 'none exact'
|
|
2251
|
+
}`,
|
|
2252
|
+
);
|
|
2253
|
+
lines.push(`- **State:** ${state}`);
|
|
2254
|
+
lines.push('- **Task:** —');
|
|
2255
|
+
if (idea.dedupe?.status === 'revisited') lines.push(`- **Invalidates:** \`${idea.dedupe.commit}\``);
|
|
2256
|
+
lines.push('');
|
|
2257
|
+
});
|
|
2258
|
+
lines.push('## Below the cap');
|
|
2259
|
+
lines.push('');
|
|
2260
|
+
if (below.length === 0) {
|
|
2261
|
+
lines.push('_None._');
|
|
2262
|
+
} else {
|
|
2263
|
+
for (const idea of below) {
|
|
2264
|
+
lines.push(`- ${neutraliseInlineText(idea.title)} — score ${scoreIdea(idea)} — \`${idea.surface}:${idea.mechanismKey}\``);
|
|
2265
|
+
}
|
|
2266
|
+
}
|
|
2267
|
+
lines.push('');
|
|
2268
|
+
lines.push('## No change');
|
|
2269
|
+
lines.push('');
|
|
2270
|
+
if (noChange.length === 0) {
|
|
2271
|
+
lines.push('_None._');
|
|
2272
|
+
} else {
|
|
2273
|
+
for (const project of noChange) {
|
|
2274
|
+
lines.push(`- ${project.id} — tip \`${project.window.to}\` — since \`${project.previousScannedAt ?? 'first scan'}\``);
|
|
2275
|
+
}
|
|
2276
|
+
}
|
|
2277
|
+
lines.push('');
|
|
2278
|
+
lines.push('## Failed');
|
|
2279
|
+
lines.push('');
|
|
2280
|
+
if (failedProjects.length === 0) {
|
|
2281
|
+
lines.push('_None._');
|
|
2282
|
+
} else {
|
|
2283
|
+
for (const project of failedProjects) {
|
|
2284
|
+
lines.push(
|
|
2285
|
+
`- ${project.id} — \`${project.code}\` — ${neutraliseInlineText(project.remedy ?? project.message ?? '')}`,
|
|
2286
|
+
);
|
|
2287
|
+
}
|
|
2288
|
+
}
|
|
2289
|
+
lines.push('');
|
|
2290
|
+
lines.push('## Deferred');
|
|
2291
|
+
lines.push('');
|
|
2292
|
+
if (deferred.length === 0) {
|
|
2293
|
+
lines.push('_None._');
|
|
2294
|
+
} else {
|
|
2295
|
+
for (const item of deferred) {
|
|
2296
|
+
lines.push(`- ${item.project.id} — last scanned ${item.cursorEntry?.scannedAt ?? 'never'} — priority ${item.project.priority ?? 3}`);
|
|
2297
|
+
}
|
|
2298
|
+
}
|
|
2299
|
+
lines.push('');
|
|
2300
|
+
if (skippedProjects.length > 0) {
|
|
2301
|
+
lines.push('## Skipped');
|
|
2302
|
+
lines.push('');
|
|
2303
|
+
for (const project of skippedProjects) {
|
|
2304
|
+
lines.push(`- ${project.id} — skipped: ${project.reason}`);
|
|
2305
|
+
}
|
|
2306
|
+
lines.push('');
|
|
2307
|
+
}
|
|
2308
|
+
lines.push('## Dropped before the digest');
|
|
2309
|
+
lines.push('');
|
|
2310
|
+
if (dropped.length === 0) {
|
|
2311
|
+
lines.push('_None._');
|
|
2312
|
+
} else {
|
|
2313
|
+
for (const item of dropped) {
|
|
2314
|
+
lines.push(
|
|
2315
|
+
`- \`${neutraliseCodeText(item.signature ?? item.title ?? 'unknown')}\` — ${neutraliseInlineText(item.reason)}`,
|
|
2316
|
+
);
|
|
2317
|
+
}
|
|
2318
|
+
}
|
|
2319
|
+
lines.push('');
|
|
2320
|
+
if (illegalTransitions.length > 0) {
|
|
2321
|
+
lines.push('## Illegal transitions');
|
|
2322
|
+
lines.push('');
|
|
2323
|
+
for (const item of illegalTransitions) {
|
|
2324
|
+
lines.push(`- \`${item.signature}\` — ${item.from} → ${item.to} (in ${item.runId})`);
|
|
2325
|
+
}
|
|
2326
|
+
lines.push('');
|
|
2327
|
+
}
|
|
2328
|
+
lines.push('---');
|
|
2329
|
+
lines.push('');
|
|
2330
|
+
lines.push('Rank: `2·value + fit − effort − risk + confidenceBonus` (high `+1`, medium `0`, low `−1`).');
|
|
2331
|
+
lines.push('');
|
|
2332
|
+
return lines.join('\n');
|
|
2333
|
+
}
|
|
2334
|
+
|
|
2335
|
+
/** Write the run-tree digest and the committed copy. Throws on an unwritable destination. */
|
|
2336
|
+
export function writeDigestFiles({ runDir, repoRoot, config, runId, text }) {
|
|
2337
|
+
const runDigest = path.join(runDir, 'digest.md');
|
|
2338
|
+
writeFileAtomic(runDigest, text);
|
|
2339
|
+
const committed = digestDestination({ repoRoot, config, runId });
|
|
2340
|
+
writeFileAtomic(committed, text);
|
|
2341
|
+
return { runDigest, committed };
|
|
2342
|
+
}
|
|
2343
|
+
|
|
2344
|
+
/* ---------------------------------- main ----------------------------------- */
|
|
2345
|
+
|
|
2346
|
+
|
|
2347
|
+
/**
|
|
2348
|
+
* Run the CLI. Returns the process exit code; never calls `process.exit`.
|
|
2349
|
+
*
|
|
2350
|
+
* @param {string[]} argv
|
|
2351
|
+
* @param {{env?: Record<string,string>, cwd?: string, io?: {stdout: Function, stderr: Function}, now?: () => string}} [options]
|
|
2352
|
+
* @returns {number}
|
|
2353
|
+
*/
|
|
2354
|
+
export function main(argv, options = {}) {
|
|
2355
|
+
const env = options.env ?? process.env;
|
|
2356
|
+
const cwd = options.cwd ?? process.cwd();
|
|
2357
|
+
const io = options.io ?? defaultIo();
|
|
2358
|
+
const now = options.now ?? (() => new Date().toISOString());
|
|
2359
|
+
let parsed;
|
|
2360
|
+
try {
|
|
2361
|
+
parsed = parseArgs(argv);
|
|
2362
|
+
} catch (error) {
|
|
2363
|
+
io.stderr(`upstream-research: ${error instanceof Error ? error.message : String(error)}`);
|
|
2364
|
+
io.stderr(USAGE);
|
|
2365
|
+
return error instanceof UpstreamError ? error.exitCode : EXIT_CODES.usage;
|
|
2366
|
+
}
|
|
2367
|
+
if (parsed.help) {
|
|
2368
|
+
io.stdout(USAGE);
|
|
2369
|
+
return EXIT_CODES.ok;
|
|
2370
|
+
}
|
|
2371
|
+
if (parsed.command === 'registry') {
|
|
2372
|
+
return commandRegistry(parsed, { env, cwd, io, now });
|
|
2373
|
+
}
|
|
2374
|
+
if (parsed.command === 'signatures') {
|
|
2375
|
+
return commandSignatures(parsed, { env, cwd, io, now });
|
|
2376
|
+
}
|
|
2377
|
+
return runResearch(parsed, { env, cwd, io, now });
|
|
2378
|
+
}
|
|
2379
|
+
|
|
2380
|
+
function commandRegistry(parsed, context) {
|
|
2381
|
+
const teamRoot = path.resolve(parsed.teamRoot ?? path.join(context.cwd, '.ai.local', 'team'));
|
|
2382
|
+
try {
|
|
2383
|
+
const { registry } = loadRegistry(teamRoot);
|
|
2384
|
+
context.io.stdout(
|
|
2385
|
+
parsed.json
|
|
2386
|
+
? JSON.stringify({ ok: true, schemaVersion: registry.schemaVersion, projects: registry.projects.length })
|
|
2387
|
+
: `registry: ok (${registry.projects.length} project${registry.projects.length === 1 ? '' : 's'})`,
|
|
2388
|
+
);
|
|
2389
|
+
return EXIT_CODES.ok;
|
|
2390
|
+
} catch (error) {
|
|
2391
|
+
if (!(error instanceof UpstreamError)) throw error;
|
|
2392
|
+
for (const finding of error.findings) {
|
|
2393
|
+
context.io.stderr(`${finding.code} ${finding.field}: ${finding.message}`);
|
|
2394
|
+
}
|
|
2395
|
+
context.io.stderr(`upstream-research: ${error.code} — ${error.remedy}`);
|
|
2396
|
+
return error.exitCode;
|
|
2397
|
+
}
|
|
2398
|
+
}
|
|
2399
|
+
|
|
2400
|
+
function commandSignatures(parsed, context) {
|
|
2401
|
+
const teamRoot = path.resolve(parsed.teamRoot ?? path.join(context.cwd, '.ai.local', 'team'));
|
|
2402
|
+
const repoRoot = path.resolve(parsed.repoRoot ?? path.join(teamRoot, '..', '..'));
|
|
2403
|
+
try {
|
|
2404
|
+
const result = refreshSignatures({ teamRoot, repoRoot, write: Boolean(parsed.write) });
|
|
2405
|
+
context.io.stdout(
|
|
2406
|
+
parsed.json
|
|
2407
|
+
? JSON.stringify(result)
|
|
2408
|
+
: `signatures: ${result.state} (${result.rows} row${result.rows === 1 ? '' : 's'}; written: ${result.written ? 'yes' : 'no'})`,
|
|
2409
|
+
);
|
|
2410
|
+
return EXIT_CODES.ok;
|
|
2411
|
+
} catch (error) {
|
|
2412
|
+
if (!(error instanceof UpstreamError)) throw error;
|
|
2413
|
+
context.io.stderr(`upstream-research: ${error.code} — ${error.remedy}`);
|
|
2414
|
+
return error.exitCode;
|
|
2415
|
+
}
|
|
2416
|
+
}
|
|
2417
|
+
|
|
2418
|
+
/**
|
|
2419
|
+
* The job path. Phase 0 runs before anything is read or written; later phases
|
|
2420
|
+
* are added by their work packages.
|
|
2421
|
+
*/
|
|
2422
|
+
function runResearch(parsed, context) {
|
|
2423
|
+
if (!parsed.prompt || !parsed.teamRoot || !parsed.repoRoot) {
|
|
2424
|
+
context.io.stderr('upstream-research: --prompt, --team-root, and --repo-root are required');
|
|
2425
|
+
context.io.stderr(USAGE);
|
|
2426
|
+
return EXIT_CODES.usage;
|
|
2427
|
+
}
|
|
2428
|
+
const paths = resolveRunPaths({
|
|
2429
|
+
promptPath: parsed.prompt,
|
|
2430
|
+
teamRoot: parsed.teamRoot,
|
|
2431
|
+
repoRoot: parsed.repoRoot,
|
|
2432
|
+
});
|
|
2433
|
+
const startedAt = context.now();
|
|
2434
|
+
let capability = null;
|
|
2435
|
+
let failure = null;
|
|
2436
|
+
try {
|
|
2437
|
+
validateRunPaths({ paths });
|
|
2438
|
+
} catch (error) {
|
|
2439
|
+
if (!(error instanceof UpstreamError)) throw error;
|
|
2440
|
+
for (const finding of error.findings) context.io.stderr(`${finding.code} ${finding.field}: ${finding.message}`);
|
|
2441
|
+
context.io.stderr(`upstream-research: ${error.code} — ${error.remedy}`);
|
|
2442
|
+
return error.exitCode;
|
|
2443
|
+
}
|
|
2444
|
+
try {
|
|
2445
|
+
validateRoots({ teamRoot: paths.teamRoot, repoRoot: paths.repoRoot });
|
|
2446
|
+
} catch (error) {
|
|
2447
|
+
if (!(error instanceof UpstreamError)) throw error;
|
|
2448
|
+
failure = error;
|
|
2449
|
+
for (const finding of error.findings) context.io.stderr(`${finding.code} ${finding.field}: ${finding.message}`);
|
|
2450
|
+
writeReport(paths.runDir, {
|
|
2451
|
+
schemaVersion: SCHEMA_VERSION,
|
|
2452
|
+
runId: paths.runId,
|
|
2453
|
+
generatedAt: startedAt,
|
|
2454
|
+
capability,
|
|
2455
|
+
failure: { code: error.code, message: error.message, remedy: error.remedy, findings: error.findings },
|
|
2456
|
+
projects: [],
|
|
2457
|
+
});
|
|
2458
|
+
context.io.stderr(`upstream-research: ${error.code} — ${error.remedy}`);
|
|
2459
|
+
return error.exitCode;
|
|
2460
|
+
}
|
|
2461
|
+
try {
|
|
2462
|
+
({ capability } = probeOpencode({ env: context.env, now: context.now }));
|
|
2463
|
+
assertAgentReadOnly({ teamRoot: paths.teamRoot, binaryPath: capability.resolvedPath, env: context.env });
|
|
2464
|
+
} catch (error) {
|
|
2465
|
+
if (!(error instanceof UpstreamError)) throw error;
|
|
2466
|
+
capability = error.capability ?? capability;
|
|
2467
|
+
writeReport(paths.runDir, {
|
|
2468
|
+
schemaVersion: SCHEMA_VERSION,
|
|
2469
|
+
runId: paths.runId,
|
|
2470
|
+
generatedAt: startedAt,
|
|
2471
|
+
capability,
|
|
2472
|
+
failure: { code: error.code, message: error.message, remedy: error.remedy, findings: error.findings },
|
|
2473
|
+
projects: [],
|
|
2474
|
+
});
|
|
2475
|
+
for (const finding of error.findings ?? []) context.io.stderr(`${finding.code} ${finding.field}: ${finding.message}`);
|
|
2476
|
+
context.io.stderr(`upstream-research: ${error.code} — ${error.remedy}`);
|
|
2477
|
+
return error.exitCode;
|
|
2478
|
+
}
|
|
2479
|
+
return continueResearch(paths, { ...context, capability, startedAt, parsed });
|
|
2480
|
+
}
|
|
2481
|
+
|
|
2482
|
+
/** Phases 1–7; completed by later work packages. */
|
|
2483
|
+
function continueResearch(paths, context) {
|
|
2484
|
+
let registry;
|
|
2485
|
+
let config;
|
|
2486
|
+
let cursor;
|
|
2487
|
+
try {
|
|
2488
|
+
({ registry } = loadRegistry(paths.teamRoot));
|
|
2489
|
+
({ config } = loadConfig(paths.teamRoot));
|
|
2490
|
+
cursor = readCursor(paths.teamRoot);
|
|
2491
|
+
const rebuilt = rebuildCursorFromReports({ teamRoot: paths.teamRoot });
|
|
2492
|
+
if (Object.keys(cursor.projects).length === 0 && Object.keys(rebuilt.projects).length > 0) {
|
|
2493
|
+
cursor = { ...rebuilt, updatedAt: cursor.updatedAt };
|
|
2494
|
+
}
|
|
2495
|
+
} catch (error) {
|
|
2496
|
+
if (!(error instanceof UpstreamError)) throw error;
|
|
2497
|
+
writeReport(paths.runDir, {
|
|
2498
|
+
schemaVersion: SCHEMA_VERSION,
|
|
2499
|
+
runId: paths.runId,
|
|
2500
|
+
generatedAt: context.startedAt,
|
|
2501
|
+
capability: context.capability,
|
|
2502
|
+
failure: { code: error.code, message: error.message, remedy: error.remedy, findings: error.findings },
|
|
2503
|
+
projects: [],
|
|
2504
|
+
});
|
|
2505
|
+
for (const finding of error.findings) context.io.stderr(`${finding.code} ${finding.field}: ${finding.message}`);
|
|
2506
|
+
context.io.stderr(`upstream-research: ${error.code} — ${error.remedy}`);
|
|
2507
|
+
return error.exitCode;
|
|
2508
|
+
}
|
|
2509
|
+
const reconciled = reconcileCursor({ cursor, projects: registry.projects });
|
|
2510
|
+
const selection = selectProjects({ projects: registry.projects, config, cursor: reconciled.cursor, now: context.startedAt });
|
|
2511
|
+
const gaps = [];
|
|
2512
|
+
let priorArt;
|
|
2513
|
+
try {
|
|
2514
|
+
priorArt = loadPriorArt({ teamRoot: paths.teamRoot });
|
|
2515
|
+
} catch (error) {
|
|
2516
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2517
|
+
priorArt = { state: 'missing', reason: `prior art unreadable: ${message}`, entries: [], rows: 0 };
|
|
2518
|
+
gaps.push(`prior art unreadable: ${message}`);
|
|
2519
|
+
}
|
|
2520
|
+
let digests = [];
|
|
2521
|
+
try {
|
|
2522
|
+
digests = loadPriorDigests(paths.repoRoot);
|
|
2523
|
+
} catch (error) {
|
|
2524
|
+
gaps.push(`prior digests unreadable: ${error instanceof Error ? error.message : String(error)}`);
|
|
2525
|
+
}
|
|
2526
|
+
const transitions = validateTransitions(digests);
|
|
2527
|
+
const budget = createRunBudget(config.artifacts.maxRunBytes);
|
|
2528
|
+
const projectReports = [];
|
|
2529
|
+
const staged = { ...reconciled.cursor.projects };
|
|
2530
|
+
let succeeded = 0;
|
|
2531
|
+
let runLevelError = null;
|
|
2532
|
+
let staticPrompt;
|
|
2533
|
+
try {
|
|
2534
|
+
staticPrompt = fs.readFileSync(paths.promptPath, 'utf8');
|
|
2535
|
+
} catch (error) {
|
|
2536
|
+
writeReport(paths.runDir, {
|
|
2537
|
+
schemaVersion: SCHEMA_VERSION,
|
|
2538
|
+
runId: paths.runId,
|
|
2539
|
+
generatedAt: context.startedAt,
|
|
2540
|
+
capability: context.capability,
|
|
2541
|
+
failure: {
|
|
2542
|
+
code: RUNNER_CODES.registryInvalid,
|
|
2543
|
+
message: `cannot read the rendered prompt: ${error instanceof Error ? error.message : String(error)}`,
|
|
2544
|
+
remedy: REMEDIES[RUNNER_CODES.registryInvalid],
|
|
2545
|
+
},
|
|
2546
|
+
projects: [],
|
|
2547
|
+
});
|
|
2548
|
+
context.io.stderr(`upstream-research: ${RUNNER_CODES.registryInvalid} — ${REMEDIES[RUNNER_CODES.registryInvalid]}`);
|
|
2549
|
+
return EXIT_CODES.eRegistryInvalid;
|
|
2550
|
+
}
|
|
2551
|
+
const promptSha = sha256(staticPrompt);
|
|
2552
|
+
const agentUnusableCodes = new Set([
|
|
2553
|
+
RUNNER_CODES.agentOutputInvalid,
|
|
2554
|
+
RUNNER_CODES.agentFailed,
|
|
2555
|
+
RUNNER_CODES.agentTimeout,
|
|
2556
|
+
]);
|
|
2557
|
+
let consecutiveAgentFailures = 0;
|
|
2558
|
+
let stopStarting = null;
|
|
2559
|
+
const runStartedMs = Date.now();
|
|
2560
|
+
const runDeadlineMs = runStartedMs + config.budget.totalBudgetMs;
|
|
2561
|
+
for (let selectedIndex = 0; selectedIndex < selection.selected.length; selectedIndex += 1) {
|
|
2562
|
+
const { project, cursorEntry } = selection.selected[selectedIndex];
|
|
2563
|
+
if (
|
|
2564
|
+
stopStarting === null &&
|
|
2565
|
+
Date.now() - runStartedMs > config.budget.totalBudgetMs - config.budget.minProjectBudgetMs
|
|
2566
|
+
) {
|
|
2567
|
+
stopStarting = 'budget';
|
|
2568
|
+
}
|
|
2569
|
+
if (stopStarting !== null) {
|
|
2570
|
+
for (const rest of selection.selected.slice(selectedIndex)) {
|
|
2571
|
+
appendProgress(paths.runDir, {
|
|
2572
|
+
project: rest.project.id,
|
|
2573
|
+
status: 'skipped',
|
|
2574
|
+
reason: stopStarting,
|
|
2575
|
+
at: context.startedAt,
|
|
2576
|
+
});
|
|
2577
|
+
projectReports.push({ id: rest.project.id, status: 'skipped', reason: stopStarting });
|
|
2578
|
+
}
|
|
2579
|
+
break;
|
|
2580
|
+
}
|
|
2581
|
+
try {
|
|
2582
|
+
const projectDeadlineMs = Math.min(Date.now() + config.budget.projectTimeoutMs, runDeadlineMs);
|
|
2583
|
+
const scan = scanProject({
|
|
2584
|
+
project,
|
|
2585
|
+
repoRoot: paths.repoRoot,
|
|
2586
|
+
runDir: paths.runDir,
|
|
2587
|
+
config,
|
|
2588
|
+
cursorEntry,
|
|
2589
|
+
env: context.env,
|
|
2590
|
+
budget,
|
|
2591
|
+
});
|
|
2592
|
+
const stagedEntry = {
|
|
2593
|
+
kind: scan.window.kind,
|
|
2594
|
+
headRef: scan.headRef,
|
|
2595
|
+
headSha: scan.window.to,
|
|
2596
|
+
tags: [...scan.window.tags].slice(0, 50),
|
|
2597
|
+
changelogSha: scan.window.changelogSha ?? null,
|
|
2598
|
+
scannedAt: context.startedAt,
|
|
2599
|
+
runId: paths.runId,
|
|
2600
|
+
url: project.url,
|
|
2601
|
+
};
|
|
2602
|
+
if (scan.status === 'no-change') {
|
|
2603
|
+
staged[project.id] = stagedEntry;
|
|
2604
|
+
appendProgress(paths.runDir, {
|
|
2605
|
+
project: project.id,
|
|
2606
|
+
status: scan.status,
|
|
2607
|
+
window: scan.window.kind,
|
|
2608
|
+
headSha: scan.window.to,
|
|
2609
|
+
at: context.startedAt,
|
|
2610
|
+
});
|
|
2611
|
+
projectReports.push({
|
|
2612
|
+
id: project.id,
|
|
2613
|
+
status: scan.status,
|
|
2614
|
+
window: {
|
|
2615
|
+
kind: scan.window.kind,
|
|
2616
|
+
from: scan.window.from,
|
|
2617
|
+
to: scan.window.to,
|
|
2618
|
+
commits: scan.window.commits.length,
|
|
2619
|
+
tags: scan.window.tags,
|
|
2620
|
+
lost: scan.window.lost,
|
|
2621
|
+
},
|
|
2622
|
+
previousScannedAt: cursorEntry?.scannedAt ?? null,
|
|
2623
|
+
});
|
|
2624
|
+
succeeded += 1;
|
|
2625
|
+
consecutiveAgentFailures = 0;
|
|
2626
|
+
continue;
|
|
2627
|
+
}
|
|
2628
|
+
const projectDir = path.join(paths.runDir, 'projects', project.id);
|
|
2629
|
+
const promptText = composeProjectPrompt({
|
|
2630
|
+
staticPrompt,
|
|
2631
|
+
project,
|
|
2632
|
+
windowPayload: scan.windowPayload,
|
|
2633
|
+
diffText: scan.diffText,
|
|
2634
|
+
priorArtSection: buildPriorArtSection({ projectId: project.id, priorArt, digests }),
|
|
2635
|
+
});
|
|
2636
|
+
if (Buffer.byteLength(promptText) > PROJECT_PROMPT_CAP_BYTES) {
|
|
2637
|
+
throw projectFailure(
|
|
2638
|
+
RUNNER_CODES.projectPromptTooLarge,
|
|
2639
|
+
`the composed prompt for "${project.id}" exceeds ${PROJECT_PROMPT_CAP_BYTES} bytes`,
|
|
2640
|
+
);
|
|
2641
|
+
}
|
|
2642
|
+
const projectPromptPath = path.join(projectDir, 'prompt.md');
|
|
2643
|
+
writeArtifact(budget, projectPromptPath, promptText, PROJECT_PROMPT_CAP_BYTES);
|
|
2644
|
+
const agentCwd = path.join(paths.teamRoot, 'upstream');
|
|
2645
|
+
if (!fs.existsSync(agentCwd)) {
|
|
2646
|
+
throw projectFailure(
|
|
2647
|
+
RUNNER_CODES.agentFailed,
|
|
2648
|
+
`the upstream agent directory is missing: ${agentCwd}`,
|
|
2649
|
+
'run `ai-rules init`/`update` to install .ai.local/team/upstream/opencode.json.',
|
|
2650
|
+
);
|
|
2651
|
+
}
|
|
2652
|
+
const repoBefore = config.agent.worktreeGuard ? porcelainStatus(paths.repoRoot, context.env) : null;
|
|
2653
|
+
if (config.agent.worktreeGuard && repoBefore === null) {
|
|
2654
|
+
gaps.push('worktree guard disabled: --repo-root is not a git repository');
|
|
2655
|
+
}
|
|
2656
|
+
const upstreamBefore = porcelainStatus(scan.cloneDir, context.env);
|
|
2657
|
+
let answer = null;
|
|
2658
|
+
let attempts = 0;
|
|
2659
|
+
let lastFindings = [];
|
|
2660
|
+
let answerRaw = '';
|
|
2661
|
+
for (let attempt = 1; attempt <= 2 && answer === null; attempt += 1) {
|
|
2662
|
+
attempts = attempt;
|
|
2663
|
+
const timeoutMs = nextAgentTimeoutMs({
|
|
2664
|
+
projectDeadlineMs,
|
|
2665
|
+
agentTimeoutMs: config.agent.timeoutMs,
|
|
2666
|
+
});
|
|
2667
|
+
if (timeoutMs === 0) {
|
|
2668
|
+
lastFindings = [
|
|
2669
|
+
{
|
|
2670
|
+
code: RUNNER_CODES.agentTimeout,
|
|
2671
|
+
field: 'agent',
|
|
2672
|
+
message: `the project exceeded budget.projectTimeoutMs (${config.budget.projectTimeoutMs} ms)`,
|
|
2673
|
+
},
|
|
2674
|
+
];
|
|
2675
|
+
break;
|
|
2676
|
+
}
|
|
2677
|
+
const instruction =
|
|
2678
|
+
attempt === 1
|
|
2679
|
+
? 'Return the marked JSON for the attached prompt.'
|
|
2680
|
+
: `Previous answer failed validation: ${lastFindings
|
|
2681
|
+
.map((finding) => `${finding.code} ${finding.field}`)
|
|
2682
|
+
.join('; ')}. Return only the marked JSON.`;
|
|
2683
|
+
const args = buildOpencodeArgv({
|
|
2684
|
+
projectId: project.id,
|
|
2685
|
+
runId: paths.runId,
|
|
2686
|
+
promptPath: projectPromptPath,
|
|
2687
|
+
model: config.agent.model,
|
|
2688
|
+
instruction,
|
|
2689
|
+
});
|
|
2690
|
+
const output = runAgent({
|
|
2691
|
+
binaryPath: context.capability.resolvedPath,
|
|
2692
|
+
args,
|
|
2693
|
+
cwd: agentCwd,
|
|
2694
|
+
env: context.env,
|
|
2695
|
+
timeoutMs,
|
|
2696
|
+
maxOutputBytes: config.agent.maxOutputBytes,
|
|
2697
|
+
});
|
|
2698
|
+
answerRaw += output.stdout;
|
|
2699
|
+
const cappedAnswer = capText(answerRaw, ANSWER_CAP_BYTES);
|
|
2700
|
+
fs.writeFileSync(path.join(projectDir, 'answer.jsonl'), cappedAnswer.text, 'utf8');
|
|
2701
|
+
budget.used += Buffer.byteLength(cappedAnswer.text);
|
|
2702
|
+
if (cappedAnswer.truncated) budget.truncated = true;
|
|
2703
|
+
if (config.agent.worktreeGuard && repoBefore !== null) {
|
|
2704
|
+
const repoAfter = porcelainStatus(paths.repoRoot, context.env);
|
|
2705
|
+
if (repoAfter !== null && repoAfter !== repoBefore) {
|
|
2706
|
+
throw new UpstreamError(
|
|
2707
|
+
RUNNER_CODES.worktreeChanged,
|
|
2708
|
+
'the repository worktree changed during an agent call',
|
|
2709
|
+
{ exitCode: EXIT_CODES.eWorktreeChanged },
|
|
2710
|
+
);
|
|
2711
|
+
}
|
|
2712
|
+
}
|
|
2713
|
+
const upstreamAfter = porcelainStatus(scan.cloneDir, context.env);
|
|
2714
|
+
if (upstreamBefore !== null && upstreamAfter !== null && upstreamAfter !== upstreamBefore) {
|
|
2715
|
+
throw projectFailure(RUNNER_CODES.upstreamDirty, `the upstream clone "${project.id}" changed during the agent call`);
|
|
2716
|
+
}
|
|
2717
|
+
try {
|
|
2718
|
+
const text = extractAssistantText(output.stdout);
|
|
2719
|
+
const parsed = parseMarkedJson(text);
|
|
2720
|
+
const validation = validateAnswer(parsed, { projectId: project.id, config });
|
|
2721
|
+
if (validation.length === 0) {
|
|
2722
|
+
answer = parsed;
|
|
2723
|
+
lastFindings = [];
|
|
2724
|
+
} else {
|
|
2725
|
+
lastFindings = validation;
|
|
2726
|
+
}
|
|
2727
|
+
} catch (error) {
|
|
2728
|
+
lastFindings =
|
|
2729
|
+
error instanceof UpstreamError
|
|
2730
|
+
? [{ code: error.code, field: 'answer', message: error.message }]
|
|
2731
|
+
: [{ code: RUNNER_CODES.answerShape, field: 'answer', message: String(error) }];
|
|
2732
|
+
}
|
|
2733
|
+
}
|
|
2734
|
+
if (answer === null) {
|
|
2735
|
+
const timedOut = lastFindings.some((finding) => finding.code === RUNNER_CODES.agentTimeout);
|
|
2736
|
+
throw projectFailure(
|
|
2737
|
+
timedOut ? RUNNER_CODES.agentTimeout : RUNNER_CODES.agentOutputInvalid,
|
|
2738
|
+
`no valid answer for "${project.id}" after one retry: ${lastFindings
|
|
2739
|
+
.map((finding) => `${finding.code} ${finding.field}`)
|
|
2740
|
+
.join('; ')}`,
|
|
2741
|
+
);
|
|
2742
|
+
}
|
|
2743
|
+
const ideas = [];
|
|
2744
|
+
const dropped = [];
|
|
2745
|
+
for (const idea of answer.ideas) {
|
|
2746
|
+
const verified = idea.evidence.filter((evidence) =>
|
|
2747
|
+
verifyEvidence({ cloneDir: scan.cloneDir, evidence, env: context.env, config }),
|
|
2748
|
+
);
|
|
2749
|
+
if (verified.length === 0) {
|
|
2750
|
+
dropped.push({
|
|
2751
|
+
title: idea.title,
|
|
2752
|
+
signature: `${idea.surface}:${idea.mechanismKey}`,
|
|
2753
|
+
reason: 'evidence-unverified',
|
|
2754
|
+
code: RUNNER_CODES.evidenceUnverified,
|
|
2755
|
+
});
|
|
2756
|
+
continue;
|
|
2757
|
+
}
|
|
2758
|
+
ideas.push({ ...idea, evidence: verified, projectId: project.id, window: answer.window });
|
|
2759
|
+
}
|
|
2760
|
+
const deduped = dedupeIdeas({
|
|
2761
|
+
ideas,
|
|
2762
|
+
priorArt,
|
|
2763
|
+
digests,
|
|
2764
|
+
window: scan.window,
|
|
2765
|
+
cloneDir: scan.cloneDir,
|
|
2766
|
+
env: context.env,
|
|
2767
|
+
config,
|
|
2768
|
+
});
|
|
2769
|
+
const allDropped = [...dropped, ...deduped.dropped];
|
|
2770
|
+
staged[project.id] = stagedEntry;
|
|
2771
|
+
appendProgress(paths.runDir, {
|
|
2772
|
+
project: project.id,
|
|
2773
|
+
status: 'researched',
|
|
2774
|
+
window: scan.window.kind,
|
|
2775
|
+
headSha: scan.window.to,
|
|
2776
|
+
ideas: deduped.kept.length,
|
|
2777
|
+
at: context.startedAt,
|
|
2778
|
+
});
|
|
2779
|
+
projectReports.push({
|
|
2780
|
+
id: project.id,
|
|
2781
|
+
status: 'researched',
|
|
2782
|
+
window: {
|
|
2783
|
+
kind: scan.window.kind,
|
|
2784
|
+
from: scan.window.from,
|
|
2785
|
+
to: scan.window.to,
|
|
2786
|
+
commits: scan.window.commits.length,
|
|
2787
|
+
tags: scan.window.tags,
|
|
2788
|
+
lost: scan.window.lost,
|
|
2789
|
+
},
|
|
2790
|
+
artifacts: scan.artifacts,
|
|
2791
|
+
agent: { attempts, ideas: deduped.kept.length, dropped: allDropped.length },
|
|
2792
|
+
ideas: deduped.kept,
|
|
2793
|
+
dropped: allDropped,
|
|
2794
|
+
dedupe: { unverified: deduped.unverified },
|
|
2795
|
+
previousScannedAt: cursorEntry?.scannedAt ?? null,
|
|
2796
|
+
});
|
|
2797
|
+
succeeded += 1;
|
|
2798
|
+
consecutiveAgentFailures = 0;
|
|
2799
|
+
} catch (error) {
|
|
2800
|
+
if (!(error instanceof UpstreamError)) throw error;
|
|
2801
|
+
if (error.exitCode === EXIT_CODES.eWorktreeChanged) {
|
|
2802
|
+
runLevelError = error;
|
|
2803
|
+
break;
|
|
2804
|
+
}
|
|
2805
|
+
appendProgress(paths.runDir, {
|
|
2806
|
+
project: project.id,
|
|
2807
|
+
status: 'failed',
|
|
2808
|
+
code: error.code,
|
|
2809
|
+
at: context.startedAt,
|
|
2810
|
+
});
|
|
2811
|
+
projectReports.push({
|
|
2812
|
+
id: project.id,
|
|
2813
|
+
status: 'failed',
|
|
2814
|
+
code: error.code,
|
|
2815
|
+
message: error.message,
|
|
2816
|
+
remedy: error.remedy,
|
|
2817
|
+
});
|
|
2818
|
+
if (agentUnusableCodes.has(error.code)) {
|
|
2819
|
+
consecutiveAgentFailures += 1;
|
|
2820
|
+
if (consecutiveAgentFailures >= config.budget.maxConsecutiveAgentFailures) {
|
|
2821
|
+
stopStarting = 'agent-unavailable';
|
|
2822
|
+
}
|
|
2823
|
+
}
|
|
2824
|
+
}
|
|
2825
|
+
}
|
|
2826
|
+
const manifest = readRunManifest(paths.runDir);
|
|
2827
|
+
const digestText = renderDigest({
|
|
2828
|
+
runId: paths.runId,
|
|
2829
|
+
trigger: manifest.trigger,
|
|
2830
|
+
jobRevision: manifest.revision,
|
|
2831
|
+
capability: context.capability,
|
|
2832
|
+
promptSha,
|
|
2833
|
+
priorArt,
|
|
2834
|
+
config,
|
|
2835
|
+
budget,
|
|
2836
|
+
registry,
|
|
2837
|
+
selection,
|
|
2838
|
+
projectReports: runLevelError
|
|
2839
|
+
? [
|
|
2840
|
+
...projectReports,
|
|
2841
|
+
{ id: '(run)', status: 'failed', code: runLevelError.code, remedy: runLevelError.remedy },
|
|
2842
|
+
]
|
|
2843
|
+
: projectReports,
|
|
2844
|
+
gaps,
|
|
2845
|
+
illegalTransitions: transitions.illegal,
|
|
2846
|
+
});
|
|
2847
|
+
if (runLevelError) {
|
|
2848
|
+
try {
|
|
2849
|
+
writeFileAtomic(paths.digestPath, digestText);
|
|
2850
|
+
} catch {
|
|
2851
|
+
// The run-tree digest is best-effort on a run-level failure.
|
|
2852
|
+
}
|
|
2853
|
+
writeReport(paths.runDir, {
|
|
2854
|
+
schemaVersion: SCHEMA_VERSION,
|
|
2855
|
+
runId: paths.runId,
|
|
2856
|
+
generatedAt: context.startedAt,
|
|
2857
|
+
capability: context.capability,
|
|
2858
|
+
failure: { code: runLevelError.code, message: runLevelError.message, remedy: runLevelError.remedy },
|
|
2859
|
+
cursorBefore: reconciled.cursor.projects,
|
|
2860
|
+
selection: {
|
|
2861
|
+
selected: selection.selected.map((item) => item.project.id),
|
|
2862
|
+
deferred: selection.deferred.map((item) => item.project.id),
|
|
2863
|
+
skipped: selection.skipped,
|
|
2864
|
+
},
|
|
2865
|
+
digest: { runDigest: path.relative(paths.teamRoot, paths.digestPath) },
|
|
2866
|
+
projects: projectReports,
|
|
2867
|
+
});
|
|
2868
|
+
context.io.stderr(`upstream-research: ${runLevelError.code} — ${runLevelError.remedy}`);
|
|
2869
|
+
return runLevelError.exitCode;
|
|
2870
|
+
}
|
|
2871
|
+
let digestPaths;
|
|
2872
|
+
try {
|
|
2873
|
+
digestPaths = writeDigestFiles({
|
|
2874
|
+
runDir: paths.runDir,
|
|
2875
|
+
repoRoot: paths.repoRoot,
|
|
2876
|
+
config,
|
|
2877
|
+
runId: paths.runId,
|
|
2878
|
+
text: digestText,
|
|
2879
|
+
});
|
|
2880
|
+
} catch (error) {
|
|
2881
|
+
writeReport(paths.runDir, {
|
|
2882
|
+
schemaVersion: SCHEMA_VERSION,
|
|
2883
|
+
runId: paths.runId,
|
|
2884
|
+
generatedAt: context.startedAt,
|
|
2885
|
+
capability: context.capability,
|
|
2886
|
+
failure: {
|
|
2887
|
+
code: RUNNER_CODES.digestWriteFailed,
|
|
2888
|
+
message: error instanceof Error ? error.message : String(error),
|
|
2889
|
+
remedy: REMEDIES[RUNNER_CODES.digestWriteFailed],
|
|
2890
|
+
},
|
|
2891
|
+
cursorBefore: reconciled.cursor.projects,
|
|
2892
|
+
selection: {
|
|
2893
|
+
selected: selection.selected.map((item) => item.project.id),
|
|
2894
|
+
deferred: selection.deferred.map((item) => item.project.id),
|
|
2895
|
+
skipped: selection.skipped,
|
|
2896
|
+
},
|
|
2897
|
+
digest: { runDigest: path.relative(paths.teamRoot, paths.digestPath) },
|
|
2898
|
+
projects: projectReports,
|
|
2899
|
+
});
|
|
2900
|
+
context.io.stderr(`upstream-research: ${RUNNER_CODES.digestWriteFailed} — ${REMEDIES[RUNNER_CODES.digestWriteFailed]}`);
|
|
2901
|
+
return EXIT_CODES.eDigestWriteFailed;
|
|
2902
|
+
}
|
|
2903
|
+
if (succeeded > 0) {
|
|
2904
|
+
writeCursor(paths.teamRoot, { schemaVersion: SCHEMA_VERSION, projects: staged }, context.startedAt);
|
|
2905
|
+
}
|
|
2906
|
+
const runFailed = selection.selected.length > 0 && succeeded === 0;
|
|
2907
|
+
const exitCode = runFailed ? EXIT_CODES.eAllProjectsFailed : EXIT_CODES.ok;
|
|
2908
|
+
writeReport(paths.runDir, {
|
|
2909
|
+
schemaVersion: SCHEMA_VERSION,
|
|
2910
|
+
runId: paths.runId,
|
|
2911
|
+
generatedAt: context.startedAt,
|
|
2912
|
+
capability: context.capability,
|
|
2913
|
+
run: { state: runFailed ? 'failed' : 'succeeded', exitCode },
|
|
2914
|
+
prompt: { path: path.relative(paths.teamRoot, paths.promptPath), sha256: promptSha },
|
|
2915
|
+
registry: { schemaVersion: registry.schemaVersion, projects: registry.projects.length },
|
|
2916
|
+
config: { budget: config.budget, scan: config.scan, agent: config.agent, digest: config.digest, artifacts: config.artifacts },
|
|
2917
|
+
cursorBefore: reconciled.cursor.projects,
|
|
2918
|
+
cursorAfter: staged,
|
|
2919
|
+
cursor: { pruned: reconciled.pruned, renames: reconciled.renames },
|
|
2920
|
+
priorArt: { state: priorArt.state, reason: priorArt.reason, rows: priorArt.rows },
|
|
2921
|
+
illegalTransitions: transitions.illegal,
|
|
2922
|
+
selection: {
|
|
2923
|
+
selected: selection.selected.map((item) => item.project.id),
|
|
2924
|
+
deferred: selection.deferred.map((item) => item.project.id),
|
|
2925
|
+
skipped: selection.skipped,
|
|
2926
|
+
},
|
|
2927
|
+
budget: { used: budget.used, limit: budget.limit, truncated: budget.truncated },
|
|
2928
|
+
gaps,
|
|
2929
|
+
digest: {
|
|
2930
|
+
runDigest: path.relative(paths.teamRoot, digestPaths.runDigest),
|
|
2931
|
+
committed: path.relative(paths.repoRoot, digestPaths.committed),
|
|
2932
|
+
},
|
|
2933
|
+
projects: projectReports,
|
|
2934
|
+
});
|
|
2935
|
+
return exitCode;
|
|
2936
|
+
}
|
|
2937
|
+
|
|
2938
|
+
/* ---------------------------------- entry ---------------------------------- */
|
|
2939
|
+
|
|
2940
|
+
/** A documented runner error keeps its own code; anything else is a crash (Node's default 1). */
|
|
2941
|
+
const ENTRY_UNEXPECTED_EXIT_CODE = 1;
|
|
2942
|
+
|
|
2943
|
+
/**
|
|
2944
|
+
* Execute the CLI only when this file is the process entry point. A suite that
|
|
2945
|
+
* imports the module gets the definitions and no side effect.
|
|
2946
|
+
*
|
|
2947
|
+
* @param {{argv?: string[], moduleUrl?: string, run?: Function}} [options]
|
|
2948
|
+
* @returns {number|null} the exit code when the entry ran, otherwise `null`
|
|
2949
|
+
*/
|
|
2950
|
+
function runEntry({ argv = process.argv, moduleUrl = import.meta.url, run = main } = {}) {
|
|
2951
|
+
if (!argv[1] || path.resolve(argv[1]) !== fileURLToPath(moduleUrl)) return null;
|
|
2952
|
+
try {
|
|
2953
|
+
process.exitCode = run(argv.slice(2));
|
|
2954
|
+
} catch (error) {
|
|
2955
|
+
process.stderr.write(`upstream-research: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
2956
|
+
process.exitCode = error instanceof UpstreamError ? error.exitCode : ENTRY_UNEXPECTED_EXIT_CODE;
|
|
2957
|
+
}
|
|
2958
|
+
return process.exitCode;
|
|
2959
|
+
}
|
|
2960
|
+
|
|
2961
|
+
runEntry();
|