toolroll 0.9.133 → 0.9.135
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 +66 -0
- package/dist/acp-agents.js +1 -1
- package/dist/acp-check-repo-schema.js +52 -0
- package/dist/acp-check.js +1 -1
- package/dist/acp-client.js +3 -3
- package/dist/acp-inspect.js +2 -1
- package/dist/acp-providers-schema.js +1 -1
- package/dist/agent-detect.js +1 -1
- package/dist/agent-fence.js +4 -4
- package/dist/agent-handoff.js +11 -0
- package/dist/agent-thread/acp-chat.js +1 -0
- package/dist/agent-thread/acp-turn.js +4 -0
- package/dist/agent-thread/chat-credential.js +1 -0
- package/dist/agent-thread/chat-home.js +1 -0
- package/dist/agent-thread/chat-spend.js +7 -0
- package/dist/agent-thread/chat-tools.js +1 -0
- package/dist/agent-thread/chat-turn.js +4 -0
- package/dist/agent-thread/custody.js +1 -1
- package/dist/agent-thread/direct-host.js +13 -8
- package/dist/agent-thread/fence.js +2 -2
- package/dist/agent-thread/gemini-chat.js +1 -0
- package/dist/agent-thread/git-workspace.js +3 -3
- package/dist/agent-thread/guards.js +1 -1
- package/dist/agent-thread/openrouter-chat.js +1 -0
- package/dist/agent-thread/providers.js +3 -3
- package/dist/agent-thread/ship.js +2 -2
- package/dist/agentconfig.js +1 -1
- package/dist/agents-live.js +2 -2
- package/dist/approval-decision.js +1 -0
- package/dist/approval-password.js +1 -1
- package/dist/approval-summary.js +1 -1
- package/dist/assignment.js +1 -1
- package/dist/attest.js +1 -1
- package/dist/batch-checks.js +2 -2
- package/dist/boot-identity.js +1 -1
- package/dist/bounded-spawn.js +2 -2
- package/dist/brief-fence.js +3 -1
- package/dist/browser/{chunk-agents-live-view.6fd2938ef96a85a4127cddb99dbc700b3201c58351d9f07dbcd8a2f7d7dfef22.js → chunk-agents-live-view.9f4367c89c6366769a567e729ac9181ccaa898bf3a168d3dc618f3cface887c7.js} +5 -5
- package/dist/browser/chunk-agents-live-view.9f4367c89c6366769a567e729ac9181ccaa898bf3a168d3dc618f3cface887c7.js.br +0 -0
- package/dist/browser/chunk-agents-live-view.9f4367c89c6366769a567e729ac9181ccaa898bf3a168d3dc618f3cface887c7.js.gz +0 -0
- package/dist/browser/chunk-bundle.ac5952c82c76e2efcdcf5a097c4fa235d6f1045dcc36d02ee921ff4be976a46a.js +2 -0
- package/dist/browser/chunk-bundle.ac5952c82c76e2efcdcf5a097c4fa235d6f1045dcc36d02ee921ff4be976a46a.js.br +0 -0
- package/dist/browser/chunk-bundle.ac5952c82c76e2efcdcf5a097c4fa235d6f1045dcc36d02ee921ff4be976a46a.js.gz +0 -0
- package/dist/browser/chunk-chat-parts.2a0b0b723508c5c48379f6a3d441f07a18c8b91ed64fd018962931c5ae43331e.js +4 -0
- package/dist/browser/chunk-chat-parts.2a0b0b723508c5c48379f6a3d441f07a18c8b91ed64fd018962931c5ae43331e.js.br +0 -0
- package/dist/browser/chunk-chat-parts.2a0b0b723508c5c48379f6a3d441f07a18c8b91ed64fd018962931c5ae43331e.js.gz +0 -0
- package/dist/browser/chunk-core.5490609e81c3a5f78da3e06b9795d71c287016ebc7fd02794b1122b474ebb07f.js +116 -0
- package/dist/browser/chunk-core.5490609e81c3a5f78da3e06b9795d71c287016ebc7fd02794b1122b474ebb07f.js.br +0 -0
- package/dist/browser/chunk-core.5490609e81c3a5f78da3e06b9795d71c287016ebc7fd02794b1122b474ebb07f.js.gz +0 -0
- package/dist/browser/{chunk-flow-view.71a0a3360292445ab70d67253bb9003163bbb7b1b03f14d1892cca83debd9b2c.js → chunk-flow-view.f5d74c7f072b739a7a0ed86ff35cafa7b8a041233372d1eeaab9eb941ddfc11e.js} +7 -7
- package/dist/browser/chunk-flow-view.f5d74c7f072b739a7a0ed86ff35cafa7b8a041233372d1eeaab9eb941ddfc11e.js.br +0 -0
- package/dist/browser/chunk-flow-view.f5d74c7f072b739a7a0ed86ff35cafa7b8a041233372d1eeaab9eb941ddfc11e.js.gz +0 -0
- package/dist/browser/chunk-flows-extra-view.01ebf93780b729363eda11ba21c764fe593bcd3e684aa833c9b86147f780fd41.js +4 -0
- package/dist/browser/chunk-flows-extra-view.01ebf93780b729363eda11ba21c764fe593bcd3e684aa833c9b86147f780fd41.js.br +0 -0
- package/dist/browser/chunk-flows-extra-view.01ebf93780b729363eda11ba21c764fe593bcd3e684aa833c9b86147f780fd41.js.gz +0 -0
- package/dist/browser/chunk-pages-bundle.e18059f0cb4fbb63e3698971d4c1830ad0945c3645235babc93010cd0b725c1d.js +6 -0
- package/dist/browser/chunk-pages-bundle.e18059f0cb4fbb63e3698971d4c1830ad0945c3645235babc93010cd0b725c1d.js.br +0 -0
- package/dist/browser/chunk-pages-bundle.e18059f0cb4fbb63e3698971d4c1830ad0945c3645235babc93010cd0b725c1d.js.gz +0 -0
- package/dist/browser/chunk-result-view.fc6a6494b316aa786807b7d17035c59defae1bfb0c03bf9c3795679b3a35dd77.js +2 -0
- package/dist/browser/chunk-result-view.fc6a6494b316aa786807b7d17035c59defae1bfb0c03bf9c3795679b3a35dd77.js.br +0 -0
- package/dist/browser/chunk-result-view.fc6a6494b316aa786807b7d17035c59defae1bfb0c03bf9c3795679b3a35dd77.js.gz +0 -0
- package/dist/browser/chunk-settings-view.6dd3a64ded7bd8c047650270918dfb455c9a514a5a40b84c7eb5f443f76fe66f.js +20 -0
- package/dist/browser/chunk-settings-view.6dd3a64ded7bd8c047650270918dfb455c9a514a5a40b84c7eb5f443f76fe66f.js.br +0 -0
- package/dist/browser/chunk-settings-view.6dd3a64ded7bd8c047650270918dfb455c9a514a5a40b84c7eb5f443f76fe66f.js.gz +0 -0
- package/dist/browser/chunk-shared.02c0b692de21a9bb80d1761aa887d8532431171945c02e663884c9f45b796753.js +3 -0
- package/dist/browser/chunk-shared.02c0b692de21a9bb80d1761aa887d8532431171945c02e663884c9f45b796753.js.br +0 -0
- package/dist/browser/chunk-shared.02c0b692de21a9bb80d1761aa887d8532431171945c02e663884c9f45b796753.js.gz +0 -0
- package/dist/browser/chunk-shared.0874336833f8101a63b169d8c2e55ca0f281e43e65d4bd6604555c791ea9dd87.js +2 -0
- package/dist/browser/chunk-shared.0874336833f8101a63b169d8c2e55ca0f281e43e65d4bd6604555c791ea9dd87.js.br +0 -0
- package/dist/browser/chunk-shared.0874336833f8101a63b169d8c2e55ca0f281e43e65d4bd6604555c791ea9dd87.js.gz +0 -0
- package/dist/browser/chunk-shared.2413dd78f32995fbca67f51ac8c21baf4727cd64f185ea739aa2a058e569b0ed.js +2 -0
- package/dist/browser/chunk-shared.2413dd78f32995fbca67f51ac8c21baf4727cd64f185ea739aa2a058e569b0ed.js.br +0 -0
- package/dist/browser/chunk-shared.2413dd78f32995fbca67f51ac8c21baf4727cd64f185ea739aa2a058e569b0ed.js.gz +0 -0
- package/dist/browser/chunk-shared.26bb0114998968cccb7bae5f6ffa8979ddecfafd8bc18bb6985760f6bcc030e6.js +5 -0
- package/dist/browser/chunk-shared.26bb0114998968cccb7bae5f6ffa8979ddecfafd8bc18bb6985760f6bcc030e6.js.br +0 -0
- package/dist/browser/chunk-shared.26bb0114998968cccb7bae5f6ffa8979ddecfafd8bc18bb6985760f6bcc030e6.js.gz +0 -0
- package/dist/browser/chunk-shared.6d0b8728b3e309886cfb6eaf596d3f20592939e521bb60bb090824f34da6b086.js +2 -0
- package/dist/browser/chunk-shared.6d0b8728b3e309886cfb6eaf596d3f20592939e521bb60bb090824f34da6b086.js.br +0 -0
- package/dist/browser/chunk-shared.6d0b8728b3e309886cfb6eaf596d3f20592939e521bb60bb090824f34da6b086.js.gz +0 -0
- package/dist/browser/chunk-shared.c3e5be1c5f441e94905a4bc2005d816d2a0b0e4108bae43e37ec274a911c6847.js +2 -0
- package/dist/browser/chunk-shared.c3e5be1c5f441e94905a4bc2005d816d2a0b0e4108bae43e37ec274a911c6847.js.br +0 -0
- package/dist/browser/chunk-shared.c3e5be1c5f441e94905a4bc2005d816d2a0b0e4108bae43e37ec274a911c6847.js.gz +0 -0
- package/dist/browser/chunk-shared.d1f25785c8c168cc75aa99c4be8ca56abfc5eafa3490f8817ff15e61cb901915.js +2 -0
- package/dist/browser/chunk-shared.d1f25785c8c168cc75aa99c4be8ca56abfc5eafa3490f8817ff15e61cb901915.js.br +0 -0
- package/dist/browser/chunk-shared.d1f25785c8c168cc75aa99c4be8ca56abfc5eafa3490f8817ff15e61cb901915.js.gz +0 -0
- package/dist/browser/chunk-shared.fd5f2699d3b0017797e5b5e1e1d92eb98818740ebf20a95364bbb7deea0c8242.js +4 -0
- package/dist/browser/chunk-shared.fd5f2699d3b0017797e5b5e1e1d92eb98818740ebf20a95364bbb7deea0c8242.js.br +0 -0
- package/dist/browser/chunk-shared.fd5f2699d3b0017797e5b5e1e1d92eb98818740ebf20a95364bbb7deea0c8242.js.gz +0 -0
- package/dist/browser/{chunk-sonner.da05d41088ec46a49ef6b86f4afa71fccd5462f1befa713ca930aa231e35349b.js → chunk-sonner.2472e1da55de10b11dc002c80a840966061e817c47793f5e216f1af6c6dbedff.js} +1 -1
- package/dist/browser/chunk-sonner.2472e1da55de10b11dc002c80a840966061e817c47793f5e216f1af6c6dbedff.js.br +0 -0
- package/dist/browser/chunk-sonner.2472e1da55de10b11dc002c80a840966061e817c47793f5e216f1af6c6dbedff.js.gz +0 -0
- package/dist/browser/chunk-task-view.bbeddc793a5e8a6d1f66b6cc5f0ce1da18414137e85c49ccd07be0e20f61ac12.js +2 -0
- package/dist/browser/chunk-task-view.bbeddc793a5e8a6d1f66b6cc5f0ce1da18414137e85c49ccd07be0e20f61ac12.js.br +0 -0
- package/dist/browser/chunk-task-view.bbeddc793a5e8a6d1f66b6cc5f0ce1da18414137e85c49ccd07be0e20f61ac12.js.gz +0 -0
- package/dist/browser/chunk-team-chat.c3255a5a1d94e39d559c07438c4690543602b1552b2c2bf57b8791d7f989141d.js +2 -0
- package/dist/browser/chunk-team-chat.c3255a5a1d94e39d559c07438c4690543602b1552b2c2bf57b8791d7f989141d.js.br +0 -0
- package/dist/browser/chunk-team-chat.c3255a5a1d94e39d559c07438c4690543602b1552b2c2bf57b8791d7f989141d.js.gz +0 -0
- package/dist/browser/manifest.json +204 -204
- package/dist/browser/{terminal.1ab49cbf9b9363f0f520b85e4125d40a302dffc10489e77b04ff1c620831eefe.js → terminal.18295f7cbf70d84b5564f3784b9630bec594fc558a7bf0303e34cde9b027eff9.js} +1 -1
- package/dist/browser/terminal.18295f7cbf70d84b5564f3784b9630bec594fc558a7bf0303e34cde9b027eff9.js.br +0 -0
- package/dist/browser/{terminal.1ab49cbf9b9363f0f520b85e4125d40a302dffc10489e77b04ff1c620831eefe.js.gz → terminal.18295f7cbf70d84b5564f3784b9630bec594fc558a7bf0303e34cde9b027eff9.js.gz} +0 -0
- package/dist/browser/workspace.3043c4a6df23ed1c0c8be3fb816fa9410a2ab99053eb54476f22a1735c03ca97.css +4 -0
- package/dist/browser/workspace.3043c4a6df23ed1c0c8be3fb816fa9410a2ab99053eb54476f22a1735c03ca97.css.br +0 -0
- package/dist/browser/workspace.3043c4a6df23ed1c0c8be3fb816fa9410a2ab99053eb54476f22a1735c03ca97.css.gz +0 -0
- package/dist/browser/{workspace.d6a38fe66b5ee0b74d8ea4b026148c285f664732511bc528c934309bbad1e5e4.js → workspace.aebb60d4e5ef4509a80cfaccf0af5f7246867ec7531a1734dd8e28c59594950e.js} +4 -4
- package/dist/browser/workspace.aebb60d4e5ef4509a80cfaccf0af5f7246867ec7531a1734dd8e28c59594950e.js.br +0 -0
- package/dist/browser/workspace.aebb60d4e5ef4509a80cfaccf0af5f7246867ec7531a1734dd8e28c59594950e.js.gz +0 -0
- package/dist/browser-open.js +1 -1
- package/dist/build-review.js +2 -2
- package/dist/builder-revision.js +4 -0
- package/dist/builder.js +31 -17
- package/dist/canvas-capture.js +2 -2
- package/dist/canvas-freshness.js +1 -1
- package/dist/central-recovery-stage.js +1 -1
- package/dist/chat-actions.js +11 -7
- package/dist/chat-channel.js +1 -1
- package/dist/chat-decide.js +8 -4
- package/dist/chat-review.js +1 -1
- package/dist/chat-terms.js +2 -2
- package/dist/check-levels.js +1 -1
- package/dist/cli-help.js +142 -13
- package/dist/cli.js +4 -3
- package/dist/companion/bonjour.js +1 -1
- package/dist/companion/daemon.js +1 -1
- package/dist/companion/passkey-gate.js +1 -1
- package/dist/companion/reads.js +1 -1
- package/dist/companion/store.js +1 -1
- package/dist/companion/webauthn.js +1 -1
- package/dist/companion/work.js +1 -1
- package/dist/container-state.js +2 -2
- package/dist/containment.js +2 -2
- package/dist/contracts/chat-actions.js +1 -1
- package/dist/contracts/console-api.js +1 -1
- package/dist/contracts/engine-api.js +1 -1
- package/dist/contracts/lead-tools.js +1 -1
- package/dist/contracts/project-memory.js +1 -1
- package/dist/contracts/provider.js +1 -1
- package/dist/controller-supervisor.js +2 -2
- package/dist/converse.js +1 -1
- package/dist/credential-broker.js +1 -1
- package/dist/decision.js +1 -1
- package/dist/demo.js +2 -2
- package/dist/dispatch.js +2 -2
- package/dist/dispose.js +1 -1
- package/dist/easy-start.js +2 -2
- package/dist/egress.js +1 -1
- package/dist/engine-chat.js +1 -1
- package/dist/engine-handoff.js +1 -1
- package/dist/engine-reads.js +3 -3
- package/dist/evals.js +2 -2
- package/dist/every-agent-schema.js +105 -0
- package/dist/evidence-pack.js +1 -1
- package/dist/evidence.js +1 -1
- package/dist/exec.js +5 -4
- package/dist/fallback.js +1 -1
- package/dist/fast-owner-schema.js +33 -0
- package/dist/fast-start.js +1 -1
- package/dist/flow-unattended.js +2 -2
- package/dist/git-identity.js +2 -2
- package/dist/github-import.js +1 -1
- package/dist/github-read.js +1 -1
- package/dist/handoff-relay.js +2 -0
- package/dist/install-mode.js +2 -3
- package/dist/invoke.js +9 -7
- package/dist/keys.js +1 -1
- package/dist/laptop-background.js +1 -1
- package/dist/lead-capabilities.js +1 -1
- package/dist/lead-cli.js +2 -2
- package/dist/lead-contract.js +1 -1
- package/dist/lead-debrief.js +7 -0
- package/dist/lead-doors.js +1 -1
- package/dist/lead-tools.js +5 -5
- package/dist/lead.js +2 -2
- package/dist/live-backup-change.js +2 -2
- package/dist/live-backup.js +2 -2
- package/dist/live-records.js +3 -3
- package/dist/live-terminal.js +4 -4
- package/dist/local-checks.js +1 -1
- package/dist/local-landing.js +22 -3
- package/dist/local-owner-acts.js +2 -2
- package/dist/local-owner.js +1 -1
- package/dist/machine-identity.js +1 -1
- package/dist/memory-pass.js +3 -3
- package/dist/model-catalog.js +8 -5
- package/dist/model-choices.js +3 -3
- package/dist/model-routing.js +1 -1
- package/dist/models-cli.js +2 -2
- package/dist/names.js +1 -1
- package/dist/needs-you.js +1 -1
- package/dist/onboard.js +1 -1
- package/dist/openrouter-key.js +2 -0
- package/dist/operate-commands.js +1 -1
- package/dist/operate-remote-arguments.js +1 -1
- package/dist/operate-remote.js +1 -1
- package/dist/operate.js +46 -19
- package/dist/orphan-sweep.js +1 -1
- package/dist/owner-mode.js +4 -0
- package/dist/panels.js +6 -0
- package/dist/peek-cli.js +2 -2
- package/dist/phase-routing.js +1 -1
- package/dist/pi-build.js +4 -0
- package/dist/pi-rpc.js +10 -0
- package/dist/pi-tools-extension.js +4 -0
- package/dist/plan-login.js +2 -2
- package/dist/plane-review.js +1 -1
- package/dist/planner-source.js +2 -2
- package/dist/planner.js +2 -2
- package/dist/plugin-bundle-source.js +1 -0
- package/dist/plugin-bundles-schema.js +43 -0
- package/dist/policy.js +1 -1
- package/dist/pre-run-phase.js +2 -0
- package/dist/presence-hold.js +1 -1
- package/dist/process-liveness.js +1 -1
- package/dist/process-tree.js +1 -1
- package/dist/project-knowledge.js +2 -2
- package/dist/project-learning.js +6 -5
- package/dist/project-memory.js +1 -1
- package/dist/project-skills.js +1 -1
- package/dist/project-tools.js +3 -3
- package/dist/prompt.js +1 -1
- package/dist/proposal.js +1 -1
- package/dist/protected-storage.js +2 -2
- package/dist/provider-auth.js +1 -1
- package/dist/provider-connection.js +2 -2
- package/dist/provider-home.js +1 -1
- package/dist/provider-limits.js +1 -1
- package/dist/provider.js +2 -2
- package/dist/public-access.js +1 -1
- package/dist/pull-request-flow.js +2 -2
- package/dist/read-executor.js +1 -1
- package/dist/release-adapters.js +2 -2
- package/dist/release-carry.js +3 -3
- package/dist/release-resume.js +2 -2
- package/dist/release-start.js +1 -0
- package/dist/reported-usage.js +1 -1
- package/dist/repository-context.js +1 -1
- package/dist/result-follow-ups.js +2 -2
- package/dist/result-projection.js +1 -1
- package/dist/review-switch.js +1 -1
- package/dist/route-change.js +25 -3
- package/dist/run-closeout.js +2 -2
- package/dist/runner.js +2 -2
- package/dist/sandbox-launch.js +2 -2
- package/dist/sandbox-runtime.js +1 -1
- package/dist/scope.js +1 -1
- package/dist/scout-browser.js +1 -1
- package/dist/scout.js +2 -2
- package/dist/serve.js +3 -3
- package/dist/server/chat-projection.js +1 -1
- package/dist/server/chat.js +3 -3
- package/dist/server/direct-chat.js +1 -1
- package/dist/server/engine-api.js +1 -1
- package/dist/server/handoff.js +1 -0
- package/dist/server/http.js +1 -1
- package/dist/server/live.js +1 -1
- package/dist/server/merge-ready-view.js +1 -1
- package/dist/server/one-time-secret.js +1 -1
- package/dist/server/panels.js +1 -0
- package/dist/server/people-tokens.js +1 -1
- package/dist/server/route-table.js +1 -1
- package/dist/server/runtime.js +1 -1
- package/dist/server/send-back-build.js +1 -1
- package/dist/server/settings-phone.js +1 -1
- package/dist/server/settings-section-table.js +1 -1
- package/dist/server/settings-sections.js +1 -1
- package/dist/server/settings.js +3 -2
- package/dist/server/task-overview.js +1 -0
- package/dist/server/task-view-data.js +3 -3
- package/dist/server/task-views.js +1 -1
- package/dist/server/tasks.js +6 -6
- package/dist/server/terminals.js +1 -1
- package/dist/settings-data.js +1 -1
- package/dist/settings-proofs.js +1 -1
- package/dist/setup-guide.js +1 -1
- package/dist/shared-deps.js +4 -4
- package/dist/sign-in-page.js +2 -2
- package/dist/skill-library.js +13 -22
- package/dist/skills-manifest.js +1 -1
- package/dist/spend-report.js +2 -1
- package/dist/spend.js +6 -4
- package/dist/ssr-workspace.js +89 -89
- package/dist/staged-runtimes.js +1 -1
- package/dist/status-probe.js +2 -2
- package/dist/stop-proof.js +2 -2
- package/dist/storage-sweep-child.js +2 -2
- package/dist/storage-sweep-process.js +1 -1
- package/dist/storage.js +2 -2
- package/dist/store-baseline.js +17 -79
- package/dist/store.js +24 -19
- package/dist/structured-json.js +1 -0
- package/dist/structured-output.js +1 -1
- package/dist/subscription-chat.js +16 -4
- package/dist/subscription-usage.js +3 -4
- package/dist/surface.js +1 -1
- package/dist/task-outcome-cli.js +5 -2
- package/dist/task-overview.js +1 -0
- package/dist/task-review-brief.js +1 -1
- package/dist/task-status.js +1 -1
- package/dist/teardown-git.js +4 -4
- package/dist/test-temp.js +1 -1
- package/dist/text-limits.js +1 -1
- package/dist/tool-broker.js +1 -1
- package/dist/toolroll-update.js +3 -3
- package/dist/trusted-path.js +1 -1
- package/dist/tui/darwin-arm64/toolroll-tui +0 -0
- package/dist/tui/darwin-x64/toolroll-tui +0 -0
- package/dist/tui/linux-arm64/toolroll-tui +0 -0
- package/dist/tui/linux-x64/toolroll-tui +0 -0
- package/dist/tui-contract.js +1 -1
- package/dist/tui-launch.js +2 -1
- package/dist/verification-evidence.js +1 -1
- package/dist/welcome-facts.js +1 -1
- package/dist/work-index.js +13 -5
- package/package.json +2 -1
- package/dist/browser/chunk-agents-live-view.6fd2938ef96a85a4127cddb99dbc700b3201c58351d9f07dbcd8a2f7d7dfef22.js.br +0 -0
- package/dist/browser/chunk-agents-live-view.6fd2938ef96a85a4127cddb99dbc700b3201c58351d9f07dbcd8a2f7d7dfef22.js.gz +0 -0
- package/dist/browser/chunk-bundle.77cfd5ccd851cf1fb8597d1d0eb12fc30913417f13b699d5b8ac61a4116274ef.js +0 -2
- package/dist/browser/chunk-bundle.77cfd5ccd851cf1fb8597d1d0eb12fc30913417f13b699d5b8ac61a4116274ef.js.br +0 -0
- package/dist/browser/chunk-bundle.77cfd5ccd851cf1fb8597d1d0eb12fc30913417f13b699d5b8ac61a4116274ef.js.gz +0 -0
- package/dist/browser/chunk-chat-parts.0e3997ddbeed8305b18353060e93f2a330d95ccb23b960f182dee211d205bb13.js +0 -4
- package/dist/browser/chunk-chat-parts.0e3997ddbeed8305b18353060e93f2a330d95ccb23b960f182dee211d205bb13.js.br +0 -0
- package/dist/browser/chunk-chat-parts.0e3997ddbeed8305b18353060e93f2a330d95ccb23b960f182dee211d205bb13.js.gz +0 -0
- package/dist/browser/chunk-core.23e919124df20f363902dc6e256d2408e103af285ebffbf0059fad7369c6ee8f.js +0 -116
- package/dist/browser/chunk-core.23e919124df20f363902dc6e256d2408e103af285ebffbf0059fad7369c6ee8f.js.br +0 -0
- package/dist/browser/chunk-core.23e919124df20f363902dc6e256d2408e103af285ebffbf0059fad7369c6ee8f.js.gz +0 -0
- package/dist/browser/chunk-flow-view.71a0a3360292445ab70d67253bb9003163bbb7b1b03f14d1892cca83debd9b2c.js.br +0 -0
- package/dist/browser/chunk-flow-view.71a0a3360292445ab70d67253bb9003163bbb7b1b03f14d1892cca83debd9b2c.js.gz +0 -0
- package/dist/browser/chunk-flows-extra-view.ebf20d864bea14592b61ce628afc066997e1f0a566abbfe6fc91f4db47245696.js +0 -4
- package/dist/browser/chunk-flows-extra-view.ebf20d864bea14592b61ce628afc066997e1f0a566abbfe6fc91f4db47245696.js.br +0 -0
- package/dist/browser/chunk-flows-extra-view.ebf20d864bea14592b61ce628afc066997e1f0a566abbfe6fc91f4db47245696.js.gz +0 -0
- package/dist/browser/chunk-pages-bundle.2fbb3d6de09f521a8ded75bd48b567d60bbfde351cae3492179714d76fc91ee5.js +0 -6
- package/dist/browser/chunk-pages-bundle.2fbb3d6de09f521a8ded75bd48b567d60bbfde351cae3492179714d76fc91ee5.js.br +0 -0
- package/dist/browser/chunk-pages-bundle.2fbb3d6de09f521a8ded75bd48b567d60bbfde351cae3492179714d76fc91ee5.js.gz +0 -0
- package/dist/browser/chunk-result-view.7527d4ed9c70c023b63821c87f8db00c374fddd8674f984cc7c03fae050e6ff0.js +0 -2
- package/dist/browser/chunk-result-view.7527d4ed9c70c023b63821c87f8db00c374fddd8674f984cc7c03fae050e6ff0.js.br +0 -0
- package/dist/browser/chunk-result-view.7527d4ed9c70c023b63821c87f8db00c374fddd8674f984cc7c03fae050e6ff0.js.gz +0 -0
- package/dist/browser/chunk-settings-view.129efb77f2d459e2254d17ab338dac474d14b86383fe024798dc61b9460d169c.js +0 -20
- package/dist/browser/chunk-settings-view.129efb77f2d459e2254d17ab338dac474d14b86383fe024798dc61b9460d169c.js.br +0 -0
- package/dist/browser/chunk-settings-view.129efb77f2d459e2254d17ab338dac474d14b86383fe024798dc61b9460d169c.js.gz +0 -0
- package/dist/browser/chunk-shared.01f5db9cab3e903447bac5a6484cbae518232a074542c5128a0ce8cac9fe5e7d.js +0 -3
- package/dist/browser/chunk-shared.01f5db9cab3e903447bac5a6484cbae518232a074542c5128a0ce8cac9fe5e7d.js.br +0 -0
- package/dist/browser/chunk-shared.01f5db9cab3e903447bac5a6484cbae518232a074542c5128a0ce8cac9fe5e7d.js.gz +0 -0
- package/dist/browser/chunk-shared.1cf4e4820f8c03a04d548d8b21b6169eda3354229b4feccdeb95534b3cc2ed09.js +0 -2
- package/dist/browser/chunk-shared.1cf4e4820f8c03a04d548d8b21b6169eda3354229b4feccdeb95534b3cc2ed09.js.br +0 -0
- package/dist/browser/chunk-shared.1cf4e4820f8c03a04d548d8b21b6169eda3354229b4feccdeb95534b3cc2ed09.js.gz +0 -0
- package/dist/browser/chunk-shared.408770b5e547bce6c67ad743638b8ef16381b092d71fc1a2b2b801cad9bd900f.js +0 -5
- package/dist/browser/chunk-shared.408770b5e547bce6c67ad743638b8ef16381b092d71fc1a2b2b801cad9bd900f.js.br +0 -0
- package/dist/browser/chunk-shared.408770b5e547bce6c67ad743638b8ef16381b092d71fc1a2b2b801cad9bd900f.js.gz +0 -0
- package/dist/browser/chunk-shared.47c9cc79ee85c5d6ebb9759b9d7f261ddd7aee78c7f70f2bc559d5b97444936d.js +0 -2
- package/dist/browser/chunk-shared.47c9cc79ee85c5d6ebb9759b9d7f261ddd7aee78c7f70f2bc559d5b97444936d.js.br +0 -0
- package/dist/browser/chunk-shared.47c9cc79ee85c5d6ebb9759b9d7f261ddd7aee78c7f70f2bc559d5b97444936d.js.gz +0 -0
- package/dist/browser/chunk-shared.60b718ab56ab520275f68f0378efa38941dc2d739c1284f842a19e6a25456e7d.js +0 -2
- package/dist/browser/chunk-shared.60b718ab56ab520275f68f0378efa38941dc2d739c1284f842a19e6a25456e7d.js.br +0 -0
- package/dist/browser/chunk-shared.60b718ab56ab520275f68f0378efa38941dc2d739c1284f842a19e6a25456e7d.js.gz +0 -0
- package/dist/browser/chunk-shared.9974523cbe568c3669da1b1a266aa7de741e2edcce3e4a943e73242c61324004.js +0 -2
- package/dist/browser/chunk-shared.9974523cbe568c3669da1b1a266aa7de741e2edcce3e4a943e73242c61324004.js.br +0 -0
- package/dist/browser/chunk-shared.9974523cbe568c3669da1b1a266aa7de741e2edcce3e4a943e73242c61324004.js.gz +0 -0
- package/dist/browser/chunk-shared.b536969256589ccff71a29b37eff95fccfd5a8f4fa4138ff503cb0e8fb10b4d0.js +0 -2
- package/dist/browser/chunk-shared.b536969256589ccff71a29b37eff95fccfd5a8f4fa4138ff503cb0e8fb10b4d0.js.br +0 -0
- package/dist/browser/chunk-shared.b536969256589ccff71a29b37eff95fccfd5a8f4fa4138ff503cb0e8fb10b4d0.js.gz +0 -0
- package/dist/browser/chunk-shared.cbc3fd4e985ceccf27c731d77030830edbf96dd0197424584ebb202eb6993ebd.js +0 -4
- package/dist/browser/chunk-shared.cbc3fd4e985ceccf27c731d77030830edbf96dd0197424584ebb202eb6993ebd.js.br +0 -0
- package/dist/browser/chunk-shared.cbc3fd4e985ceccf27c731d77030830edbf96dd0197424584ebb202eb6993ebd.js.gz +0 -0
- package/dist/browser/chunk-sonner.da05d41088ec46a49ef6b86f4afa71fccd5462f1befa713ca930aa231e35349b.js.br +0 -0
- package/dist/browser/chunk-sonner.da05d41088ec46a49ef6b86f4afa71fccd5462f1befa713ca930aa231e35349b.js.gz +0 -0
- package/dist/browser/chunk-task-view.9b9f418a71547aeea43a8acb26e8d48d486463b71b940eb72f3856038e27fa90.js +0 -2
- package/dist/browser/chunk-task-view.9b9f418a71547aeea43a8acb26e8d48d486463b71b940eb72f3856038e27fa90.js.br +0 -0
- package/dist/browser/chunk-task-view.9b9f418a71547aeea43a8acb26e8d48d486463b71b940eb72f3856038e27fa90.js.gz +0 -0
- package/dist/browser/chunk-team-chat.2be52f36796d5cd7ca8ea47a2aeb68c550625150ccc4186805bdecd87747138c.js +0 -2
- package/dist/browser/chunk-team-chat.2be52f36796d5cd7ca8ea47a2aeb68c550625150ccc4186805bdecd87747138c.js.br +0 -0
- package/dist/browser/chunk-team-chat.2be52f36796d5cd7ca8ea47a2aeb68c550625150ccc4186805bdecd87747138c.js.gz +0 -0
- package/dist/browser/terminal.1ab49cbf9b9363f0f520b85e4125d40a302dffc10489e77b04ff1c620831eefe.js.br +0 -0
- package/dist/browser/workspace.d6a38fe66b5ee0b74d8ea4b026148c285f664732511bc528c934309bbad1e5e4.js.br +0 -0
- package/dist/browser/workspace.d6a38fe66b5ee0b74d8ea4b026148c285f664732511bc528c934309bbad1e5e4.js.gz +0 -0
- package/dist/browser/workspace.d818fa094b8793160991ca784f4897c6d1862c02fbcbeebae637d8b855ab03d5.css +0 -4
- package/dist/browser/workspace.d818fa094b8793160991ca784f4897c6d1862c02fbcbeebae637d8b855ab03d5.css.br +0 -0
- package/dist/browser/workspace.d818fa094b8793160991ca784f4897c6d1862c02fbcbeebae637d8b855ab03d5.css.gz +0 -0
package/dist/local-landing.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{lstatSync,mkdtempSync,realpathSync,rmSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{join}from"node:path";import{run as execRun}from"./exec.js";import{hardenedGit}from"./teardown-git.js";import{assignmentOf}from"./assignment.js";import{projectCheckSet,quickVerifyKey}from"./check-levels.js";import{recordActionWhole}from"./action-ledger.js";import{reproveApprover,verifyApproverStanding}from"./principal.js";import{localActNow,LOCAL_OWNER_LAPSED}from"./local-owner.js";import{publishingOf}from"./pull-request-flow.js";import{readGit,wholeChangeBaseOf}from"./task-base.js";import{catchUpConflictOf}from"./revision-catch-up.js";import{checkPasskeyAction,consumePasskeyAction}from"./companion/passkey-gate.js";import{passkeyProofDetail}from"./companion/webauthn.js";import{deviceAccountStands,getPairedDevice}from"./companion/store.js";export const LAND_DESTINATION="land destination",LAND_INTENT="land intent",LAND_PROVED_ACTION="land proved",LAND_SETTLED="land settled",LAND_HANDOFF="land handoff",LAND_HANDOFF_SETTLED="land handoff settled";function checkBindingsOf(store,repo){return{full:store.liveVerifyCommand(repo)?.digest??null,quick:store.liveVerifyCommand(quickVerifyKey(repo))?.digest??null,setup:store.liveWorktreeSetup(repo)?.digest??null,access:String(store.projectCheckAccess(repo))}}const OID=/^[0-9a-f]{40}$/,refuse=(reason,message)=>({ok:!1,reason,message}),short=oid=>oid.slice(0,7),keyOf=value=>createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0,16);export function landableBranch(name){return name===""||name==="HEAD"||name.startsWith("-")||name.length>100||!/^[A-Za-z0-9._/-]+$/.test(name)||name.startsWith("toolroll/")?!1:name.split("/").every(part=>part!==""&&!part.startsWith(".")&&!part.startsWith("-")&&!part.endsWith(".lock")&&!part.endsWith("."))&&!name.includes("..")}function commonDirOf(repo){try{const dotgit=join(realpathSync(repo),".git"),held=lstatSync(dotgit);return held.isDirectory()&&!held.isSymbolicLink()?realpathSync(dotgit):null}catch{return null}}function gitFor(repo,given){const git=hardenedGit(given??execRun,"build",{repo});return(args,cwd=repo,timeoutMs=6e4)=>git("git",args,{cwd,timeoutMs})}function rows(store,where,args){return store.handle.prepare(`SELECT id,at,actor,outcome,detail FROM action_ledger WHERE ${where} ORDER BY id DESC`).all(...args).flatMap(row=>{try{const detail=JSON.parse(String(row.detail??"null"));return detail!==null&&typeof detail=="object"?[{id:Number(row.id),at:String(row.at),actor:String(row.actor),outcome:String(row.outcome),detail}]:[]}catch{return[]}})}function recordedDestination(store,repo){const row=rows(store,"repo = ? AND action = ? AND source = 'request'",[repo,LAND_DESTINATION])[0],ref=row?.detail.ref,common=row?.detail.common;return typeof ref=="string"&&typeof common=="string"?{ref,common}:null}function intentOf(row){const d=row.detail;if(d.v!==1||typeof d.ref!="string"||typeof d.old!="string"||typeof d.commit!="string"||!OID.test(d.old)||!OID.test(d.commit)||d.mode!=="files"&&d.mode!=="ref"||typeof d.key!="string"||d.kind!=="land"&&d.kind!=="undo")return null;const candidate=typeof d.candidate=="string"&&OID.test(d.candidate)?d.candidate:d.commit;return{id:row.id,at:row.at,repo:row.repo,task:row.task,run:row.run,kind:d.kind,ref:d.ref,old:d.old,commit:d.commit,candidate,mode:d.mode,key:d.key,reverts:typeof d.reverts=="number"||typeof d.reverts=="string"?d.reverts:null,fromHandoff:typeof d.fromHandoff=="number"?d.fromHandoff:null}}function intents(store,where,args){return store.handle.prepare(`SELECT id,at,actor,outcome,detail,repo,task_id,run_id FROM action_ledger WHERE ${where} AND action = ? ORDER BY id DESC`).all(...args,LAND_INTENT).flatMap(row=>{try{const detail=JSON.parse(String(row.detail??"null")),one=intentOf({id:Number(row.id),at:String(row.at),actor:String(row.actor),outcome:String(row.outcome),detail,repo:String(row.repo),task:String(row.task_id),run:Number(row.run_id)});return one===null?[]:[one]}catch{return[]}})}function settledOf(store,intent){const row=rows(store,"action = ? AND outcome LIKE ?",[LAND_SETTLED,`${intent}:%`])[0];return row===void 0?null:{outcome:row.outcome.slice(String(intent).length+1),at:row.at,detail:row.detail}}export function landingOf(store,rootId){const all=intents(store,"task_id = ?",[rootId]),landed=all.find(one=>one.kind==="land"&&settledOf(store,one.id)?.outcome.startsWith("landed")===!0);if(landed===void 0)return null;const name=landed.fromHandoff!==null?`handoff:${landed.fromHandoff}`:`intent:${landed.id}`,undone=all.some(one=>one.kind==="undo"&&(one.reverts===name||one.reverts===landed.id)&&settledOf(store,one.id)?.outcome.startsWith("landed")===!0);return{intent:landed,at:settledOf(store,landed.id).at,undone}}async function treeProblem(git,commit){const listed=await git(["ls-tree","-r","-z","--full-tree",commit]);if(listed.code!==0)return"its files couldn't be read";for(const entry of listed.stdout.split("\0")){if(entry==="")continue;const match=/^(\d{6}) (\w+) ([0-9a-f]{40})\t(.*)$/s.exec(entry);if(match===null)return"its files couldn't be read";const[,mode,,oid,path]=match;if(mode==="160000")return"it holds a submodule";if(path===".gitattributes"||path.endsWith("/.gitattributes")){const blob=await git(["cat-file","blob",oid]);if(blob.code!==0)return"its .gitattributes couldn't be read";if(/\b(filter|working-tree-encoding)\s*=/.test(blob.stdout)||/(^|\s)filter(\s|$)/m.test(blob.stdout))return"its files use a Git filter (like Git LFS) or an encoding"}if(path===".gitmodules")return"it holds a submodule"}return null}async function checkoutsOn(git,ref){const listed=await git(["worktree","list","--porcelain","-z"]);if(listed.code!==0)return null;const found=[];let path=null;for(const line of listed.stdout.split("\0"))if(line.startsWith("worktree "))path=line.slice(9);else if(line===`branch ${ref}`&&path!==null)try{found.push(realpathSync(path))}catch{found.push(path)}return found}async function placeOf(git,project,ref,old){const branch=ref.slice(11),symbolic=await git(["symbolic-ref","-q",ref]);if(symbolic.code===0)return{kind:"problem",reason:"destination",message:`${branch} points at another branch (${symbolic.stdout.trim().replace(/^refs\/heads\//,"")}), so Toolroll won't move it. Land it with git yourself.`};if(symbolic.code!==1)return{kind:"problem",reason:"git",message:`Toolroll couldn't read ${branch}.`};if(old!==null){const read=await git(["rev-parse","--verify","-q",`${ref}^{commit}`]);if(read.code!==0||read.stdout.trim()!==old)return{kind:"problem",reason:"moved",message:`${branch} moved since you looked. Look again, then land it.`}}const on=await checkoutsOn(git,ref);if(on===null)return{kind:"problem",reason:"git",message:"Toolroll couldn't list this project's checkouts."};if(on.length===0)return{kind:"free"};let repoReal=project.repo;try{repoReal=realpathSync(project.repo)}catch{}return on.length!==1||on[0]!==repoReal?{kind:"problem",reason:"occupied",message:`${branch} is checked out in another folder, so Toolroll won't move it or suggest a command to run there. Switch that folder to another branch, then land it.`}:{kind:"folder"}}function handoffRefOf(taskId,commit){return`refs/toolroll/land/${/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(taskId)&&!taskId.includes("..")&&!taskId.endsWith(".lock")&&!taskId.endsWith(".")?taskId:createHash("sha256").update(taskId).digest("hex").slice(0,16)}/${oidOrThrow(commit)}`}function projectOf(store,repo){if(repo===null||!store.knownRepos().includes(repo))return null;const common=commonDirOf(repo);return common===null?null:{repo,common}}export function publishesThroughPullRequests(store,repo){try{return publishingOf(store,repo).on||store.publicationGrantFor(repo)!==null}catch{return!0}}export const PULL_REQUESTS_INSTEAD="This project publishes through pull requests; open one from the task instead.";const ALREADY_MSG=(ref,commit)=>`Already on ${ref.replace(/^refs\/heads\//,"")} (${short(commit)}).`,MOVED_MSG=(branch,old)=>`${branch} moved on since this work started (it's at ${short(old)} now). Send it back: Toolroll builds it again on the current ${branch} with this work merged in, and its checks run on both together.`,CONFLICT_MSG=(branch,old,files,candidate)=>{const named=files.slice(0,3).map(one=>shownName(one)).join(", ");return`${branch} moved on since this work started (it's at ${short(old)} now), and its newer changes conflict with this work${named===""?"":` in ${named}${files.length>3?", …":""}`}. Toolroll can't merge them by itself. To land it, merge ${short(candidate)} into ${branch} yourself and resolve the conflicts, or file a new task on the current ${branch}.`};export function landingBranchOf(store,repo,fallback){const recorded=recordedDestination(store,repo);return recorded!==null&&recorded.common===commonDirOf(repo)?recorded.ref.slice(11):fallback}export async function readLanding(store,taskId,access,now,options){const assignment=assignmentOf(store,taskId,now,{principal:"operator",repos:access.repos,includeUnplaced:!1},options.root);if(assignment===null)return refuse("not-found",`No task \`${taskId}\` in your projects.`);if(assignment.repo!==null&&publishesThroughPullRequests(store,assignment.repo))return refuse("pull-requests",PULL_REQUESTS_INSTEAD);const project=projectOf(store,assignment.repo);if(project===null)return refuse("destination","This task's project isn't a local Git folder Toolroll can land in.");const git=gitFor(project.repo,options.git);if(options.undo===!0)return readUndo(store,assignment.rootId,project,git,options);const receipt=assignment.receipt;if(assignment.state!=="complete"||assignment.completion===null||receipt===null)return refuse("not-complete","Accept it first: only accepted work lands.");const later=assignment.completion.digest!==receipt.digest;if(later&&assignment.completion.historical!==!0)return refuse("checks","This result changed since you accepted it. Look at it again, then land it.");const candidate=receipt.head;if(candidate===null||!OID.test(candidate)||receipt.completionKind==="research-report")return refuse("nothing","This result has no commit to land.");const landed=landingOf(store,assignment.rootId);if(landed!==null&&!landed.undone&&landed.intent.candidate===candidate){const reverted=landedStanding(store,assignment.rootId,readGit)?.reverted===!0;return{ok:!0,landed:{at:landed.at,ref:landed.intent.ref,commit:landed.intent.commit,mode:landed.intent.mode,...reverted?{reverted}:{}}}}const checks=receipt.checks.status==="passed"?"passed":!projectCheckSet(store,project.repo)&&receipt.checks.status==="not-run"?"none":null;if(checks===null)return receipt.checks.status==="failed"?refuse("checks",later?`Its checks failed when they ran again after you accepted it (${receipt.checks.detail.replace(/\.$/,"")}). It stays Complete; it can't land until they pass on its exact commit.`:"Its checks failed. Only work whose checks passed on its exact commit lands."):refuse("checks",later?"Its checks changed since you accepted it and haven't run on its exact commit since. Run checks (it stays Complete), then land it.":"Its checks haven't passed on its exact commit. Run checks, then land it.");const destination=await destinationOf(store,project,git,options.into);if(!destination.ok)return destination;const run=store.getRun(receipt.runId),base=run===null||run.branch===null?null:wholeChangeBaseOf(store,run.taskRef,run.branch)??run.baseRevision,read=await planFor(git,project,destination,{kind:"land",taskId:receipt.taskId,rootId:assignment.rootId,runId:receipt.runId,receipt:receipt.digest,completion:assignment.completion.digest,candidate,checks,bindings:checkBindingsOf(store,project.repo)},{base,message:squashMessage(store.getTask(receipt.taskId)?.title??null,receipt.taskId),time:Math.max(0,Math.floor(Date.parse(assignment.completion.at)/1e3)||0),handedOff:handoffsOf(store,project.repo,assignment.rootId).filter(one=>one.candidate===candidate).map(one=>one.commit)});if(!read.ok&&read.reason==="nothing"){const seen=recognisedOnBranch(store,project.repo,assignment.rootId,candidate,readGit);if(seen!==null&&seen.reverted)return refuse("nothing",`${seen.words}.`)}if(!read.ok&&read.reason==="moved"){const now2=await git(["rev-parse","--verify","-q",`${destination.ref}^{commit}`]),old=now2.stdout.trim(),files=now2.code===0&&OID.test(old)?catchUpConflictOf(store,receipt.taskId,old):null;if(files!==null)return refuse("moved",CONFLICT_MSG(destination.ref.slice(11),old,files,candidate))}return read}export function landedLine(landed){return`Landed on ${landed.ref.replace(/^refs\/heads\//,"")} (${short(landed.commit)})${landed.reverted===!0?" · a later commit reverted it":""}.`}async function destinationOf(store,project,git,into){const recorded=recordedDestination(store,project.repo);if(into!==void 0){if(!landableBranch(into))return refuse("destination",`\`${into}\` isn't a branch Toolroll can land on.`);const ref2=`refs/heads/${into}`;return{ok:!0,ref:ref2,recorded:recorded?.ref===ref2&&recorded.common===project.common}}if(recorded!==null&&recorded.common===project.common)return{ok:!0,ref:recorded.ref,recorded:!0};const head=await git(["symbolic-ref","-q","HEAD"]),ref=head.stdout.trim();return head.code!==0||!ref.startsWith("refs/heads/")||!landableBranch(ref.slice(11))?refuse("destination","Your project folder isn't on a branch Toolroll can land on. Name one: --into <branch>."):{ok:!0,ref,recorded:!1}}const UNSAFE_MESSAGE=/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u061c\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]+/g;function squashMessage(title,taskId){const plain=text=>text.replace(UNSAFE_MESSAGE," ").replace(/\s+/g," ").trim(),line=plain(title??"").slice(0,200),id=plain(taskId).slice(0,100);return line===""?`Toolroll task ${id}`:`${line} (Toolroll task ${id})`}async function changesOf(git,old,candidate){const stat=await git(["diff","--numstat","-z","--no-renames","--no-ext-diff","--no-textconv",old,candidate]);if(stat.code!==0)return null;const files=[];let added=0,removed=0;for(const entry of stat.stdout.split("\0")){const match=/^(\d+|-)\t(\d+|-)\t(.+)$/s.exec(entry);match!==null&&(added+=match[1]==="-"?0:Number(match[1]),removed+=match[2]==="-"?0:Number(match[2]),files.push(match[3]))}return{files:files.slice(0,20),fileCount:files.length,added,removed}}async function planFor(git,project,destination,fixed,squashing=null){const{ref}=destination,branch=ref.slice(11),read=await git(["rev-parse","--verify","-q",`${ref}^{commit}`]),old=read.stdout.trim();if(read.code!==0||!OID.test(old))return refuse("destination",`There's no branch \`${branch}\` in this project.`);if(fixed.candidate!==null){if(old===fixed.candidate)return refuse("nothing",ALREADY_MSG(ref,old));const type=await git(["cat-file","-t",fixed.candidate]);if(type.code!==0||type.stdout.trim()!=="commit")return refuse("git",`This result's commit ${short(fixed.candidate)} is no longer in the project.`);for(const landed of[fixed.candidate,...squashing?.handedOff??[]])if((await git(["merge-base","--is-ancestor",landed,old])).code===0)return refuse("nothing",ALREADY_MSG(ref,landed));const ancestor=await git(["merge-base","--is-ancestor",old,fixed.candidate]);if(ancestor.code===1)return refuse("moved",MOVED_MSG(branch,old));if(ancestor.code!==0)return refuse("git","Toolroll couldn't compare the commits.");const problem=await treeProblem(git,fixed.candidate)??await treeProblem(git,old);if(problem!==null)return refuse("unsupported",`This project can't be landed by Toolroll: ${problem}. Land it with git yourself.`)}let squash=null;if(fixed.candidate!==null){const tree=await git(["rev-parse","--verify","-q",`${fixed.candidate}^{tree}`]),changes=await changesOf(git,old,fixed.candidate);if(tree.code!==0||!OID.test(tree.stdout.trim())||changes===null)return refuse("git",`Toolroll couldn't read what ${short(fixed.candidate)} changes.`);const message=squashing?.message??`Toolroll task ${fixed.taskId}`,time=squashing?.time??0,treeId=tree.stdout.trim();squash={policy:"squash",base:squashing?.base??null,commit:commitIdOf(squashBody(treeId,old,time,message)),tree:treeId,checkedTree:treeId,time,message,...changes}}const place=await placeOf(git,project,ref,old);if(place.kind==="problem")return refuse(place.reason,place.message);if(place.kind==="folder"&&fixed.kind==="undo"){const command=gitCommand(project.repo,["revert","--no-edit",`${oidOrThrow(fixed.reverts.old)}..${oidOrThrow(fixed.reverts.landed)}`]);return refuse("occupied",`${branch} is checked out in your project folder, so Toolroll won't touch its files. ${command===null?UNSAFE_FOLDER(`git revert --no-edit ${fixed.reverts.old}..${fixed.reverts.landed}`):`To do it yourself there: ${command}`}`)}const mode=place.kind==="free"?"ref":"handoff",plan={...fixed,squash,repo:project.repo,ref,branch,old,mode,...place.kind==="folder"?{handoff:{folder:project.repo}}:{},recorded:destination.recorded};return{ok:!0,plan:{...plan,key:keyOf({v:1,...plan,common:project.common})}}}async function readUndo(store,rootId,project,git,options){const landed=landingOf(store,rootId);if(landed!==null&&landed.undone)return refuse("nothing","This landing was already undone.");const brought=landed===null?await broughtIn(store,git,project.repo,rootId):null,source=landed!==null?{key:landed.intent.key,task:landed.intent.task,run:landed.intent.run,ref:landed.intent.ref,old:landed.intent.old,commit:landed.intent.commit,name:landed.intent.fromHandoff!==null?`handoff:${landed.intent.fromHandoff}`:`intent:${landed.intent.id}`}:brought===null?null:{key:brought.key,task:brought.task,run:brought.run,ref:brought.ref,old:brought.old,commit:brought.commit,name:`handoff:${brought.id}`};return source===null?refuse("nothing","This task hasn't landed, so there's nothing to undo."):planFor(git,project,{ref:source.ref,recorded:!0},{kind:"undo",taskId:source.task,rootId,runId:source.run,receipt:source.key,completion:source.key,candidate:null,checks:"none",reverts:{source:source.name,old:source.old,landed:source.commit},bindings:checkBindingsOf(store,project.repo)})}function landedCommits(store,rootId){return new Set(intents(store,"task_id = ?",[rootId]).filter(one=>one.kind==="land"&&settledOf(store,one.id)?.outcome.startsWith("landed")===!0).map(one=>one.commit))}async function broughtIn(store,git,repo,rootId){const landed=landedCommits(store,rootId);for(const one of handoffsOf(store,repo,rootId))if(!landed.has(one.commit)&&(await git(["merge-base","--is-ancestor",one.commit,one.ref])).code===0)return one;return null}function squashBody(tree,parent,time,message){const who=`Toolroll <land@toolroll.invalid> ${time} +0000`;return`tree ${tree}
|
|
1
|
+
import{createHash}from"node:crypto";import{existsSync,lstatSync,mkdtempSync,readFileSync,realpathSync,rmSync,writeFileSync}from"node:fs";import{tmpdir}from"node:os";import{isAbsolute,join}from"node:path";import{liveInstallOwner,ownerMode,ownerModeSetting}from"./owner-mode.js";import{run as execRun}from"./exec.js";import{hardenedGit}from"./teardown-git.js";import{assignmentOf}from"./assignment.js";import{projectCheckSet,quickVerifyKey}from"./check-levels.js";import{recordActionWhole}from"./action-ledger.js";import{reproveApprover,verifyApproverStanding}from"./principal.js";import{asLocalOwner,localActNow,localBindingStands,localModeOn,LOCAL_OWNER_LAPSED}from"./local-owner.js";import{publishingOf}from"./pull-request-flow.js";import{readGit,wholeChangeBaseOf}from"./task-base.js";import{catchUpConflictOf}from"./revision-catch-up.js";import{checkPasskeyAction,consumePasskeyAction}from"./companion/passkey-gate.js";import{passkeyProofDetail}from"./companion/webauthn.js";import{deviceAccountStands,getPairedDevice}from"./companion/store.js";export const LAND_DESTINATION="land destination",LAND_INTENT="land intent",LAND_PROVED_ACTION="land proved",LAND_SETTLED="land settled",LAND_HANDOFF="land handoff",LAND_HANDOFF_SETTLED="land handoff settled";const LAND_WHEN_CLEAN_QUEUED="land when clean queued",LAND_WHEN_CLEAN_CANCELLED="land when clean cancelled";function checkBindingsOf(store,repo){return{full:store.liveVerifyCommand(repo)?.digest??null,quick:store.liveVerifyCommand(quickVerifyKey(repo))?.digest??null,setup:store.liveWorktreeSetup(repo)?.digest??null,access:String(store.projectCheckAccess(repo))}}const OID=/^[0-9a-f]{40}$/,refuse=(reason,message)=>({ok:!1,reason,message}),short=oid=>oid.slice(0,7),keyOf=value=>createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0,16);export function landableBranch(name){return name===""||name==="HEAD"||name.startsWith("-")||name.length>100||!/^[A-Za-z0-9._/-]+$/.test(name)||name.startsWith("toolroll/")?!1:name.split("/").every(part=>part!==""&&!part.startsWith(".")&&!part.startsWith("-")&&!part.endsWith(".lock")&&!part.endsWith("."))&&!name.includes("..")}function commonDirOf(repo){try{const dotgit=join(realpathSync(repo),".git"),held=lstatSync(dotgit);return held.isDirectory()&&!held.isSymbolicLink()?realpathSync(dotgit):null}catch{return null}}function gitFor(repo,given){const git=hardenedGit(given??execRun,"build",{repo});return(args,cwd=repo,timeoutMs=6e4)=>git("git",args,{cwd,timeoutMs})}function rows(store,where,args){return store.handle.prepare(`SELECT id,at,actor,outcome,detail FROM action_ledger WHERE ${where} ORDER BY id DESC`).all(...args).flatMap(row=>{try{const detail=JSON.parse(String(row.detail??"null"));return detail!==null&&typeof detail=="object"?[{id:Number(row.id),at:String(row.at),actor:String(row.actor),outcome:String(row.outcome),detail}]:[]}catch{return[]}})}function recordedDestination(store,repo){const row=rows(store,"repo = ? AND action = ? AND source = 'request'",[repo,LAND_DESTINATION])[0],ref=row?.detail.ref,common=row?.detail.common;return typeof ref=="string"&&typeof common=="string"?{ref,common}:null}function intentOf(row){const d=row.detail;if(d.v!==1||typeof d.ref!="string"||typeof d.old!="string"||typeof d.commit!="string"||!OID.test(d.old)||!OID.test(d.commit)||d.mode!=="files"&&d.mode!=="ref"||typeof d.key!="string"||d.kind!=="land"&&d.kind!=="undo")return null;const candidate=typeof d.candidate=="string"&&OID.test(d.candidate)?d.candidate:d.commit;return{id:row.id,at:row.at,repo:row.repo,task:row.task,run:row.run,kind:d.kind,ref:d.ref,old:d.old,commit:d.commit,candidate,mode:d.mode,key:d.key,reverts:typeof d.reverts=="number"||typeof d.reverts=="string"?d.reverts:null,fromHandoff:typeof d.fromHandoff=="number"?d.fromHandoff:null}}function intents(store,where,args){return store.handle.prepare(`SELECT id,at,actor,outcome,detail,repo,task_id,run_id FROM action_ledger WHERE ${where} AND action = ? ORDER BY id DESC`).all(...args,LAND_INTENT).flatMap(row=>{try{const detail=JSON.parse(String(row.detail??"null")),one=intentOf({id:Number(row.id),at:String(row.at),actor:String(row.actor),outcome:String(row.outcome),detail,repo:String(row.repo),task:String(row.task_id),run:Number(row.run_id)});return one===null?[]:[one]}catch{return[]}})}function settledOf(store,intent){const row=rows(store,"action = ? AND outcome LIKE ?",[LAND_SETTLED,`${intent}:%`])[0];return row===void 0?null:{outcome:row.outcome.slice(String(intent).length+1),at:row.at,detail:row.detail}}export function landingOf(store,rootId){const all=intents(store,"task_id = ?",[rootId]),landed=all.find(one=>one.kind==="land"&&settledOf(store,one.id)?.outcome.startsWith("landed")===!0);if(landed===void 0)return null;const name=landed.fromHandoff!==null?`handoff:${landed.fromHandoff}`:`intent:${landed.id}`,undone=all.some(one=>one.kind==="undo"&&(one.reverts===name||one.reverts===landed.id)&&settledOf(store,one.id)?.outcome.startsWith("landed")===!0);return{intent:landed,at:settledOf(store,landed.id).at,undone}}async function treeProblem(git,commit){const listed=await git(["ls-tree","-r","-z","--full-tree",commit]);if(listed.code!==0)return"its files couldn't be read";for(const entry of listed.stdout.split("\0")){if(entry==="")continue;const match=/^(\d{6}) (\w+) ([0-9a-f]{40})\t(.*)$/s.exec(entry);if(match===null)return"its files couldn't be read";const[,mode,,oid,path]=match;if(mode==="160000")return"it holds a submodule";if(path===".gitattributes"||path.endsWith("/.gitattributes")){const blob=await git(["cat-file","blob",oid]);if(blob.code!==0)return"its .gitattributes couldn't be read";if(/\b(filter|working-tree-encoding)\s*=/.test(blob.stdout)||/(^|\s)filter(\s|$)/m.test(blob.stdout))return"its files use a Git filter (like Git LFS) or an encoding"}if(path===".gitmodules")return"it holds a submodule"}return null}async function checkoutsOn(git,ref){const listed=await git(["worktree","list","--porcelain","-z"]);if(listed.code!==0)return null;const found=[];let path=null;for(const line of listed.stdout.split("\0"))if(line.startsWith("worktree "))path=line.slice(9);else if(line===`branch ${ref}`&&path!==null)try{found.push(realpathSync(path))}catch{found.push(path)}return found}const IN_PROGRESS_GIT_OPS=[["MERGE_HEAD","merge in progress"],["REBASE_HEAD","rebase in progress"],["rebase-merge","rebase in progress"],["rebase-apply","rebase in progress"],["CHERRY_PICK_HEAD","cherry-pick in progress"],["REVERT_HEAD","revert in progress"],["BISECT_LOG","bisect in progress"]];async function inProgressOpsOf(git,repo){const gitDir=await git(["rev-parse","--git-dir"]);if(gitDir.code!==0||gitDir.stdout.trim()==="")return{ok:!1};const resolvedGitDir=isAbsolute(gitDir.stdout.trim())?gitDir.stdout.trim():join(repo,gitDir.stdout.trim()),ops=[];for(const[marker,label]of IN_PROGRESS_GIT_OPS)existsSync(join(resolvedGitDir,marker))&&!ops.includes(label)&&ops.push(label);return{ok:!0,ops}}async function dirtyFilesOf(git,repo){const status=await git(["status","--porcelain=v1","-z","--untracked-files=normal"]);if(status.code!==0)return{ok:!1};const parts=status.stdout.split("\0"),files=[];for(let i=0;i<parts.length;i+=1){const entry=parts[i];if(entry===""||entry.length<4)continue;const x=entry[0],y=entry[1],path=entry.slice(3);path!==""&&files.push(path),(x==="R"||x==="C"||y==="R"||y==="C")&&i+1<parts.length&&(i+=1)}const ops=await inProgressOpsOf(git,repo);if(!ops.ok)return{ok:!1};for(const label of ops.ops)files.includes(label)||files.push(label);return{ok:!0,files}}const HEAD_LOCK_MARK="toolroll-land ";async function holdHeadLock(git){const dir=await git(["rev-parse","--absolute-git-dir"]);if(dir.code!==0||dir.stdout.trim()==="")return{ok:!1};const path=join(dir.stdout.trim(),"HEAD.lock");try{writeFileSync(path,`${HEAD_LOCK_MARK}${process.pid}
|
|
2
|
+
`,{flag:"wx",mode:420})}catch{return{ok:!1}}return{ok:!0,release:()=>{try{rmSync(path,{force:!0})}catch{}}}}export function releaseLeftoverHeadLock(gitDir){const path=join(gitDir,"HEAD.lock");try{readFileSync(path,"utf8").startsWith(HEAD_LOCK_MARK)&&rmSync(path,{force:!0})}catch{}}async function inspectInPlaceState(git,project,ref,old,commit){const symbolic=await git(["symbolic-ref","-q",ref]),refSymbolic=symbolic.code===0,refReadable=symbolic.code===1,atRead=await git(["rev-parse","--verify","-q",`${ref}^{commit}`]),refAt=atRead.code===0&&OID.test(atRead.stdout.trim())?atRead.stdout.trim():null,headSymRead=await git(["symbolic-ref","-q","HEAD"]),headSym=headSymRead.code===0?headSymRead.stdout.trim():null,headAtRead=await git(["rev-parse","--verify","-q","HEAD^{commit}"]),headAt=headAtRead.code===0&&OID.test(headAtRead.stdout.trim())?headAtRead.stdout.trim():null,checkouts=await checkoutsOn(git,ref);let repoReal=project.repo;try{repoReal=realpathSync(project.repo)}catch{}const indexMatchesOld=(await git(["diff-index","--cached","--quiet",old])).code===0,indexMatchesCommit=(await git(["diff-index","--cached","--quiet",commit])).code===0,worktreeMatchesCommit=(await git(["diff-index","--quiet",commit])).code===0,dirty=await dirtyFilesOf(git,project.repo),ops=await inProgressOpsOf(git,project.repo);return{refSymbolic,refReadable,refAt,headSym,headAt,checkouts,repoReal,indexMatchesOld,indexMatchesCommit,worktreeMatchesCommit,dirtyFiles:dirty.ok?dirty.files:null,inProgressOps:ops.ok?ops.ops:null}}function isProvenInPlaceLanded(state,ref,commit){return!state.refSymbolic&&state.refReadable&&state.refAt===commit&&state.headSym===ref&&state.headAt===commit&&state.checkouts!==null&&state.checkouts.length===1&&state.checkouts[0]===state.repoReal&&state.indexMatchesCommit&&state.worktreeMatchesCommit&&state.inProgressOps!==null&&state.inProgressOps.length===0}function stateSummaryOf(state){return{refSymbolic:state.refSymbolic,refAt:state.refAt,headSym:state.headSym,headAt:state.headAt,indexMatchesOld:state.indexMatchesOld,indexMatchesCommit:state.indexMatchesCommit,worktreeMatchesCommit:state.worktreeMatchesCommit,dirtyCount:state.dirtyFiles?.length??null,inProgressOps:state.inProgressOps}}function toUnresolved(intent,settled){const words=typeof settled.detail.words=="string"&&settled.detail.words.trim()!==""?settled.detail.words:`An earlier landing on ${intent.ref.replace(/^refs\/heads\//,"")} stopped partway through. Choose how to resolve it below.`;return{intentId:intent.id,taskId:intent.task,runId:intent.run,repo:intent.repo,ref:intent.ref,branch:intent.ref.replace(/^refs\/heads\//,""),old:intent.old,commit:intent.commit,candidate:intent.candidate,words,at:settled.at}}function unresolvedLandingForRepo(store,repo){for(const intent of intents(store,"repo = ?",[repo])){const settled=settledOf(store,intent.id);if(settled?.outcome==="unresolved")return toUnresolved(intent,settled)}return null}export function unresolvedLandingOf(store,rootId){for(const intent of intents(store,"task_id = ?",[rootId])){const settled=settledOf(store,intent.id);if(settled?.outcome==="unresolved")return toUnresolved(intent,settled)}return null}function dirtyRefuse(branch,files){const shown=files.slice(0,5).map(shownName).join(", "),extra=files.length>5?` and ${files.length-5} more`:"";return{ok:!1,reason:"dirty",message:`${branch} is checked out with uncommitted changes in ${shown}${extra}. Choose "Land when clean" or "Open PR".`,dirtyFiles:files}}async function placeOf(git,project,ref,old){const branch=ref.slice(11),symbolic=await git(["symbolic-ref","-q",ref]);if(symbolic.code===0)return{kind:"problem",reason:"destination",message:`${branch} points at another branch (${symbolic.stdout.trim().replace(/^refs\/heads\//,"")}), so Toolroll won't move it. Land it with git yourself.`};if(symbolic.code!==1)return{kind:"problem",reason:"git",message:`Toolroll couldn't read ${branch}.`};if(old!==null){const read=await git(["rev-parse","--verify","-q",`${ref}^{commit}`]);if(read.code!==0||read.stdout.trim()!==old)return{kind:"problem",reason:"moved",message:`${branch} moved since you looked. Look again, then land it.`}}const on=await checkoutsOn(git,ref);if(on===null)return{kind:"problem",reason:"git",message:"Toolroll couldn't list this project's checkouts."};if(on.length===0)return{kind:"free"};let repoReal=project.repo;try{repoReal=realpathSync(project.repo)}catch{}if(on.length!==1||on[0]!==repoReal)return{kind:"problem",reason:"occupied",message:`${branch} is checked out in another folder, so Toolroll won't move it or suggest a command to run there. Switch that folder to another branch, then land it.`};const dirty=await dirtyFilesOf(git,project.repo);return dirty.ok?{kind:"folder",dirty:dirty.files}:{kind:"problem",reason:"git",message:"Toolroll couldn't check whether your project folder has uncommitted changes."}}function handoffRefOf(taskId,commit){return`refs/toolroll/land/${/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/.test(taskId)&&!taskId.includes("..")&&!taskId.endsWith(".lock")&&!taskId.endsWith(".")?taskId:createHash("sha256").update(taskId).digest("hex").slice(0,16)}/${oidOrThrow(commit)}`}function projectOf(store,repo){if(repo===null||!store.knownRepos().includes(repo))return null;const common=commonDirOf(repo);return common===null?null:{repo,common}}export function publishesThroughPullRequests(store,repo){try{return publishingOf(store,repo).on||store.publicationGrantFor(repo)!==null}catch{return!0}}export const PULL_REQUESTS_INSTEAD="This project publishes through pull requests; open one from the task instead.";const ALREADY_MSG=(ref,commit)=>`Already on ${ref.replace(/^refs\/heads\//,"")} (${short(commit)}).`,MOVED_MSG=(branch,old)=>`${branch} moved on since this work started (it's at ${short(old)} now). Send it back: Toolroll builds it again on the current ${branch} with this work merged in, and its checks run on both together.`,CONFLICT_MSG=(branch,old,files,candidate)=>{const named=files.slice(0,3).map(one=>shownName(one)).join(", ");return`${branch} moved on since this work started (it's at ${short(old)} now), and its newer changes conflict with this work${named===""?"":` in ${named}${files.length>3?", …":""}`}. Toolroll can't merge them by itself. To land it, merge ${short(candidate)} into ${branch} yourself and resolve the conflicts, or file a new task on the current ${branch}.`};export function landingBranchOf(store,repo,fallback){const recorded=recordedDestination(store,repo);return recorded!==null&&recorded.common===commonDirOf(repo)?recorded.ref.slice(11):fallback}export async function readLanding(store,taskId,access,now,options){const assignment=assignmentOf(store,taskId,now,{principal:"operator",repos:access.repos,includeUnplaced:!1},options.root);if(assignment===null)return refuse("not-found",`No task \`${taskId}\` in your projects.`);if(assignment.repo!==null&&publishesThroughPullRequests(store,assignment.repo))return refuse("pull-requests",PULL_REQUESTS_INSTEAD);const project=projectOf(store,assignment.repo);if(project===null)return refuse("destination","This task's project isn't a local Git folder Toolroll can land in.");const unresolved=unresolvedLandingForRepo(store,project.repo);if(unresolved!==null)return{ok:!1,reason:"unresolved",message:unresolved.words,unresolved};const git=gitFor(project.repo,options.git);if(options.undo===!0)return readUndo(store,assignment.rootId,project,git,options);const receipt=assignment.receipt;if(assignment.state!=="complete"||assignment.completion===null||receipt===null)return refuse("not-complete","Accept it first: only accepted work lands.");const later=assignment.completion.digest!==receipt.digest;if(later&&assignment.completion.historical!==!0)return refuse("checks","This result changed since you accepted it. Look at it again, then land it.");const candidate=receipt.head;if(candidate===null||!OID.test(candidate)||receipt.completionKind==="research-report")return refuse("nothing","This result has no commit to land.");const landed=landingOf(store,assignment.rootId);if(landed!==null&&!landed.undone&&landed.intent.candidate===candidate){const reverted=landedStanding(store,assignment.rootId,readGit)?.reverted===!0;return{ok:!0,landed:{at:landed.at,ref:landed.intent.ref,commit:landed.intent.commit,mode:landed.intent.mode,...reverted?{reverted}:{}}}}const checks=receipt.checks.status==="passed"?"passed":!projectCheckSet(store,project.repo)&&receipt.checks.status==="not-run"?"none":null;if(checks===null)return receipt.checks.status==="failed"?refuse("checks",later?`Its checks failed when they ran again after you accepted it (${receipt.checks.detail.replace(/\.$/,"")}). It stays Complete; it can't land until they pass on its exact commit.`:"Its checks failed. Only work whose checks passed on its exact commit lands."):refuse("checks",later?"Its checks changed since you accepted it and haven't run on its exact commit since. Run checks (it stays Complete), then land it.":"Its checks haven't passed on its exact commit. Run checks, then land it.");const destination=await destinationOf(store,project,git,options.into);if(!destination.ok)return destination;const run=store.getRun(receipt.runId),base=run===null||run.branch===null?null:wholeChangeBaseOf(store,run.taskRef,run.branch)??run.baseRevision,read=await planFor(git,project,destination,{kind:"land",taskId:receipt.taskId,rootId:assignment.rootId,runId:receipt.runId,receipt:receipt.digest,completion:assignment.completion.digest,candidate,checks,bindings:checkBindingsOf(store,project.repo)},{base,message:squashMessage(store.getTask(receipt.taskId)?.title??null,receipt.taskId),time:Math.max(0,Math.floor(Date.parse(assignment.completion.at)/1e3)||0),handedOff:handoffsOf(store,project.repo,assignment.rootId).filter(one=>one.candidate===candidate).map(one=>one.commit)},ownerMode(store,now)==="fast");if(!read.ok&&read.reason==="nothing"){const seen=recognisedOnBranch(store,project.repo,assignment.rootId,candidate,readGit);if(seen!==null&&seen.reverted)return refuse("nothing",`${seen.words}.`)}if(!read.ok&&read.reason==="moved"){const now2=await git(["rev-parse","--verify","-q",`${destination.ref}^{commit}`]),old=now2.stdout.trim(),files=now2.code===0&&OID.test(old)?catchUpConflictOf(store,receipt.taskId,old):null;if(files!==null)return refuse("moved",CONFLICT_MSG(destination.ref.slice(11),old,files,candidate))}return read}export function landedLine(landed){return`Landed on ${landed.ref.replace(/^refs\/heads\//,"")} (${short(landed.commit)})${landed.reverted===!0?" · a later commit reverted it":""}.`}async function destinationOf(store,project,git,into){const recorded=recordedDestination(store,project.repo);if(into!==void 0){if(!landableBranch(into))return refuse("destination",`\`${into}\` isn't a branch Toolroll can land on.`);const ref2=`refs/heads/${into}`;return{ok:!0,ref:ref2,recorded:recorded?.ref===ref2&&recorded.common===project.common}}if(recorded!==null&&recorded.common===project.common)return{ok:!0,ref:recorded.ref,recorded:!0};const head=await git(["symbolic-ref","-q","HEAD"]),ref=head.stdout.trim();return head.code!==0||!ref.startsWith("refs/heads/")||!landableBranch(ref.slice(11))?refuse("destination","Your project folder isn't on a branch Toolroll can land on. Name one: --into <branch>."):{ok:!0,ref,recorded:!1}}const UNSAFE_MESSAGE=/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u061c\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]+/g;function squashMessage(title,taskId){const plain=text=>text.replace(UNSAFE_MESSAGE," ").replace(/\s+/g," ").trim(),line=plain(title??"").slice(0,200),id=plain(taskId).slice(0,100);return line===""?`Toolroll task ${id}`:`${line} (Toolroll task ${id})`}async function changesOf(git,old,candidate){const stat=await git(["diff","--numstat","-z","--no-renames","--no-ext-diff","--no-textconv",old,candidate]);if(stat.code!==0)return null;const files=[];let added=0,removed=0;for(const entry of stat.stdout.split("\0")){const match=/^(\d+|-)\t(\d+|-)\t(.+)$/s.exec(entry);match!==null&&(added+=match[1]==="-"?0:Number(match[1]),removed+=match[2]==="-"?0:Number(match[2]),files.push(match[3]))}return{files:files.slice(0,20),fileCount:files.length,added,removed}}async function planFor(git,project,destination,fixed,squashing=null,inPlace=!1){const{ref}=destination,branch=ref.slice(11),read=await git(["rev-parse","--verify","-q",`${ref}^{commit}`]),old=read.stdout.trim();if(read.code!==0||!OID.test(old))return refuse("destination",`There's no branch \`${branch}\` in this project.`);if(fixed.candidate!==null){if(old===fixed.candidate)return refuse("nothing",ALREADY_MSG(ref,old));const type=await git(["cat-file","-t",fixed.candidate]);if(type.code!==0||type.stdout.trim()!=="commit")return refuse("git",`This result's commit ${short(fixed.candidate)} is no longer in the project.`);for(const landed of[fixed.candidate,...squashing?.handedOff??[]])if((await git(["merge-base","--is-ancestor",landed,old])).code===0)return refuse("nothing",ALREADY_MSG(ref,landed));const ancestor=await git(["merge-base","--is-ancestor",old,fixed.candidate]);if(ancestor.code===1)return refuse("moved",MOVED_MSG(branch,old));if(ancestor.code!==0)return refuse("git","Toolroll couldn't compare the commits.");const problem=await treeProblem(git,fixed.candidate)??await treeProblem(git,old);if(problem!==null)return refuse("unsupported",`This project can't be landed by Toolroll: ${problem}. Land it with git yourself.`)}let squash=null;if(fixed.candidate!==null){const tree=await git(["rev-parse","--verify","-q",`${fixed.candidate}^{tree}`]),changes=await changesOf(git,old,fixed.candidate);if(tree.code!==0||!OID.test(tree.stdout.trim())||changes===null)return refuse("git",`Toolroll couldn't read what ${short(fixed.candidate)} changes.`);const message=squashing?.message??`Toolroll task ${fixed.taskId}`,time=squashing?.time??0,treeId=tree.stdout.trim();squash={policy:"squash",base:squashing?.base??null,commit:commitIdOf(squashBody(treeId,old,time,message)),tree:treeId,checkedTree:treeId,time,message,...changes}}const place=await placeOf(git,project,ref,old);if(place.kind==="problem")return refuse(place.reason,place.message);if(place.kind==="folder"&&fixed.kind==="undo"){const command=gitCommand(project.repo,["revert","--no-edit",`${oidOrThrow(fixed.reverts.old)}..${oidOrThrow(fixed.reverts.landed)}`]);return refuse("occupied",`${branch} is checked out in your project folder, so Toolroll won't touch its files. ${command===null?UNSAFE_FOLDER(`git revert --no-edit ${fixed.reverts.old}..${fixed.reverts.landed}`):`To do it yourself there: ${command}`}`)}if(place.kind==="folder"&&fixed.kind==="land"&&inPlace&&place.dirty.length>0)return dirtyRefuse(branch,place.dirty);const mode=place.kind==="free"?"ref":inPlace?"files":"handoff",plan={...fixed,squash,repo:project.repo,ref,branch,old,mode,recorded:destination.recorded};return{ok:!0,plan:{...plan,key:keyOf({v:1,...plan,common:project.common})}}}async function readUndo(store,rootId,project,git,options){const landed=landingOf(store,rootId);if(landed!==null&&landed.undone)return refuse("nothing","This landing was already undone.");const brought=landed===null?await broughtIn(store,git,project.repo,rootId):null,source=landed!==null?{key:landed.intent.key,task:landed.intent.task,run:landed.intent.run,ref:landed.intent.ref,old:landed.intent.old,commit:landed.intent.commit,name:landed.intent.fromHandoff!==null?`handoff:${landed.intent.fromHandoff}`:`intent:${landed.intent.id}`}:brought===null?null:{key:brought.key,task:brought.task,run:brought.run,ref:brought.ref,old:brought.old,commit:brought.commit,name:`handoff:${brought.id}`};return source===null?refuse("nothing","This task hasn't landed, so there's nothing to undo."):planFor(git,project,{ref:source.ref,recorded:!0},{kind:"undo",taskId:source.task,rootId,runId:source.run,receipt:source.key,completion:source.key,candidate:null,checks:"none",reverts:{source:source.name,old:source.old,landed:source.commit},bindings:checkBindingsOf(store,project.repo)})}function landedCommits(store,rootId){return new Set(intents(store,"task_id = ?",[rootId]).filter(one=>one.kind==="land"&&settledOf(store,one.id)?.outcome.startsWith("landed")===!0).map(one=>one.commit))}async function broughtIn(store,git,repo,rootId){const landed=landedCommits(store,rootId);for(const one of handoffsOf(store,repo,rootId))if(!landed.has(one.commit)&&(await git(["merge-base","--is-ancestor",one.commit,one.ref])).code===0)return one;return null}function squashBody(tree,parent,time,message){const who=`Toolroll <land@toolroll.invalid> ${time} +0000`;return`tree ${tree}
|
|
2
3
|
parent ${parent}
|
|
3
4
|
author ${who}
|
|
4
5
|
committer ${who}
|
|
5
6
|
|
|
6
7
|
${message}
|
|
7
|
-
`}function commitIdOf(body){return createHash("sha1").update(`commit ${Buffer.byteLength(body,"utf8")}\0`).update(body,"utf8").digest("hex")}const UNSAFE_SHOWN=/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u061c\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff\\]/g;export function shownName(name){return name.replace(UNSAFE_SHOWN,ch=>ch==="\\"?"\\\\":`\\u{${ch.codePointAt(0).toString(16)}}`)}export function landingWords(plan){const how=plan.mode==="handoff"?`your project folder has ${plan.branch} checked out, so Toolroll won't touch its files: Land makes the commit and shows the one git command that brings it in`:`no folder has ${plan.branch} checked out; only the branch moves`;if(plan.kind==="undo")return[`Undo the landing of ${short(plan.reverts.landed)} on ${plan.branch} in ${shownName(plan.repo)} (${how}).`,"A new commit reverts exactly what it changed; nothing is rewritten. No check runs on the undo."];const squash=plan.squash,names=squash.files.slice(0,3).map(shownName).join(", ")+(squash.fileCount>3?` and ${squash.fileCount-3} more`:"");return[`Lands 1 commit on ${plan.branch}: ${squash.fileCount===0?"no file changes":names} (+${squash.added} −${squash.removed}).`,`${short(squash.commit)} "${shownName(squash.message)}", on top of ${short(plan.old)} in ${shownName(plan.repo)} (${how}).`,plan.checks==="passed"?`Checks ran on these exact files: they passed on ${short(plan.candidate)}, and ${short(squash.commit)} carries the same tree.`:"No check ran: this project has no check command.",...plan.recorded?[]:[`Toolroll remembers ${plan.branch} as where this project's work lands.`]]}async function settleUnfinished(store,repo,now,options){if(projectOf(store,repo)===null)return;const git=gitFor(repo,options.git);for(const intent of intents(store,"repo = ?",[repo]).filter(one=>settledOf(store,one.id)===null)){const symbolic=await git(["symbolic-ref","-q",intent.ref]),at=(await git(["rev-parse","--verify","-q",`${intent.ref}^{commit}`])).stdout.trim();let outcome,words;symbolic.code!==1?(outcome="needs-person",words=`${intent.ref.replace(/^refs\/heads\//,"")} now points at another branch or can't be read. Look at ${repo} with git log.`):at===intent.old?(outcome="abandoned",words="It stopped before the branch moved; nothing changed."):at===intent.commit&&intent.mode==="files"?(outcome="needs-person",words=`The branch moved to ${short(intent.commit)}; check your folder's files with git status in ${repo}.`):at===intent.commit?(outcome="landed:recovered",words="It had finished; recorded now."):(outcome="needs-person",words=`The branch is at ${OID.test(at)?short(at):"an unreadable commit"} now, neither before nor after the landing. Look at ${repo} with git log.`),recordActionWhole(store.handle,{at:now.toISOString(),actor:"toolroll",repo,taskId:intent.task,runId:intent.run,action:LAND_SETTLED,outcome:`${intent.id}:${outcome}`,source:"work"},{v:1,words})}}function standing(store,authority,repo){if(authority.kind==="local"){const local=localActNow(store,"land-task");return local===null?refuse("authority",LOCAL_OWNER_LAPSED):!verifyApproverStanding(store,local.account,local.accountGeneration,store.knownRepos().filter(one=>store.accountCanAccess(local.account,one))).ok||!store.accountCanAccess(local.account,repo)?refuse("authority",LOCAL_OWNER_LAPSED):{ok:!0,actor:`operator:${local.account}`}}if(!reproveApprover(store,authority.who).ok||!authority.who.repos.includes(repo)||!store.accountCanAccess(authority.who.name,repo))return refuse("authority","Your access changed. Sign in again.");if(authority.kind==="passkey"){const dev=getPairedDevice(store.handle,authority.proof.deviceId),identity=store.workspaceIdentity();if(dev===null||dev.revokedAt!==null||dev.activatedAt===null||dev.accountName!==authority.who.name||dev.recoveryGeneration!==identity.recoveryGeneration||!deviceAccountStands(dev,store.accountOf(authority.who.name)))return refuse("authority","This iPhone is no longer paired or your account changed.")}return{ok:!0,actor:`operator:${authority.who.name}`}}const projectLocks=new Map;async function locked(repo,body){const before=projectLocks.get(repo)??Promise.resolve();let release;const mine=new Promise(resolve=>{release=resolve}),chained=before.then(()=>mine);projectLocks.set(repo,chained),await before.catch(()=>{});try{return await body()}finally{release(),projectLocks.get(repo)===chained&&projectLocks.delete(repo)}}export async function land(store,taskId,input,authority,access,now,options){if(!/^[0-9a-f]{16}$/.test(input.key))return refuse("stale","That landing isn't the one on screen. Look again, then land it.");const repo=store.lookupRef(taskId)?.repo??null;if(repo===null||access.repos!==null&&!access.repos.includes(repo))return refuse("not-found",`No task \`${taskId}\` in your projects.`);const first=standing(store,authority,repo);if(!first.ok)return first;if(publishesThroughPullRequests(store,repo))return refuse("pull-requests",PULL_REQUESTS_INSTEAD);const named=input.into!==void 0&&landableBranch(input.into)?`refs/heads/${input.into}`:recordedDestination(store,repo)?.ref??null;return named!==null&&projectOf(store,repo)!==null&&(await gitFor(repo,options.git)(["symbolic-ref","-q",named])).code===0?refuse("destination",`${named.replace(/^refs\/heads\//,"")} points at another branch, so Toolroll won't move it. Land it with git yourself.`):locked(repo,async()=>{const done=intents(store,"repo = ? AND task_id IS NOT NULL",[repo]).find(one=>one.key===input.key);if(done!==void 0&&settledOf(store,done.id)?.outcome.startsWith("landed")===!0){const who=standing(store,authority,repo);return who.ok?{ok:!0,replayed:!0,kind:done.kind,ref:done.ref,branch:done.ref.slice(11),commit:done.commit,old:done.old,mode:done.mode,warning:null,handoff:null}:who}const handedOff=input.undo===!0?void 0:handoffRows(store,repo).find(one=>one.key===input.key);if(handedOff!==void 0){const who=standing(store,authority,repo);if(!who.ok)return who;const git2=gitFor(repo,options.git),there=await git2(["cat-file","-t",handedOff.commit]);return there.code!==0||there.stdout.trim()!=="commit"?refuse("git","The landing commit Toolroll kept for this is gone. Look again, then land it."):await keepAt(git2,handedOff.keep,handedOff.commit,`toolroll: landing commit for ${taskId}`)?(handedOff.settled||recordActionWhole(store.handle,{at:now.toISOString(),actor:"toolroll",repo,taskId:handedOff.task,runId:handedOff.run,action:LAND_HANDOFF_SETTLED,outcome:`${handedOff.id}:kept`,source:"work"},{v:1,keep:handedOff.keep,commit:handedOff.commit}),{ok:!0,replayed:handedOff.settled,kind:"land",ref:handedOff.ref,branch:handedOff.ref.slice(11),commit:handedOff.commit,old:handedOff.old,mode:"handoff",warning:null,handoff:{ref:handedOff.keep,command:handoffCommand(repo,handedOff.commit)}}):refuse("git","Toolroll couldn't keep the landing commit. Look again, then land it.")}await settleUnfinished(store,repo,now,options);const read=await readLanding(store,taskId,access,now,{...options,...input.into===void 0?{}:{into:input.into},...input.undo===!0?{undo:!0}:{}});if(!read.ok)return read;if(!("plan"in read))return refuse("nothing",read.landed.reverted===!0?landedLine(read.landed):ALREADY_MSG(read.landed.ref,read.landed.commit));const plan=read.plan;if(plan.key!==input.key)return refuse("stale","Something changed since you looked (the branch, the checks or the result). Look again, then land it.");const project=projectOf(store,plan.repo),git=gitFor(plan.repo,options.git),handoffSource=plan.kind==="undo"?/^handoff:(\d+)$/.exec(plan.reverts?.source??""):null;if(handoffSource!==null&&!await reconcileHandoff(store,git,plan.repo,plan.rootId,Number(handoffSource[1]),first.actor,now))return refuse("stale","That landing changed since you looked. Look again.");const stillStands=()=>{const who=standing(store,authority,plan.repo);if(!who.ok)return who;if(publishesThroughPullRequests(store,plan.repo))return refuse("pull-requests",PULL_REQUESTS_INSTEAD);if(plan.kind==="land"){const again=assignmentOf(store,taskId,now,{principal:"operator",repos:access.repos},options.root);if(again?.state!=="complete"||again.receipt?.digest!==plan.receipt||again.completion?.digest!==plan.completion)return refuse("stale","This result changed since you looked. Look again, then land it.")}else{const landed=landingOf(store,plan.rootId),name=landed===null?null:landed.intent.fromHandoff!==null?`handoff:${landed.intent.fromHandoff}`:`intent:${landed.intent.id}`;if(landed===null||landed.undone||name!==plan.reverts?.source)return refuse("stale","That landing changed since you looked. Look again.")}return JSON.stringify(checkBindingsOf(store,plan.repo))!==JSON.stringify(plan.bindings)?refuse("stale","The project's checks changed since you looked. Look again, then land it."):who},pre=standing(store,authority,plan.repo);if(!pre.ok)return pre;const landBinding={verb:"land",taskId,planKey:plan.key,into:input.into??null,undo:input.undo===!0},passkeyChecked=authority.kind!=="passkey"?null:checkPasskeyAction(store,{accountName:authority.who.name,repo:plan.repo,verb:"land",expectedBinding:landBinding,proof:authority.proof,now});if(passkeyChecked!==null&&!passkeyChecked.ok)return refuse("authority",passkeyChecked.message);const consumeLandPasskey=()=>{if(authority.kind!=="passkey"||passkeyChecked===null||!passkeyChecked.ok)return;const at=authority.clock(),consumed=consumePasskeyAction(store,passkeyChecked,{repo:plan.repo,now:at});if(!consumed.ok)throw new Refused(refuse("authority",consumed.message));store.recordAction({at:at.toISOString(),actor:authority.who.name,repo:plan.repo,taskId:plan.rootId,runId:plan.runId,action:LAND_PROVED_ACTION,outcome:"passkey",source:"request",detail:passkeyProofDetail({at,generation:consumed.accountGeneration,digest:plan.key,verb:"land",credentialId:consumed.credentialId,pairedDeviceId:consumed.deviceId,be:consumed.be,bs:consumed.bs})})},made=plan.kind==="undo"?await revertCommit(git,plan,options.scratch):await squashCommit(git,plan,options.scratch);if(!made.ok)return made;const commit=made.commit,keep=handoffRefOf(plan.rootId,commit);if(plan.kind==="land"&&!await keepAt(git,keep,commit,`toolroll: landing commit for ${plan.taskId}`))return refuse("git","Toolroll made the landing commit but couldn't keep it. Nothing landed; look again, then land it.");if(plan.mode==="handoff"){const place2=await placeOf(git,project,plan.ref,plan.old);if(place2.kind!=="folder")return refuse(place2.kind==="problem"?place2.reason:"stale",place2.kind==="problem"?place2.message:"Your project folder changed since you looked. Look again, then land it.");let handoffId,replayed=!1;try{handoffId=store.transact(()=>{const who=stillStands();if(!who.ok)throw new Refused(who);const earlier=handoffRows(store,plan.repo).find(one=>one.key===plan.key&&one.commit===commit);return earlier!==void 0?(replayed=earlier.settled,earlier.id):(consumeLandPasskey(),plan.recorded||recordActionWhole(store.handle,{at:now.toISOString(),actor:who.actor,repo:plan.repo,taskId:null,runId:null,action:LAND_DESTINATION,outcome:plan.ref,source:"request"},{v:1,ref:plan.ref,common:project.common}),recordActionWhole(store.handle,{at:now.toISOString(),actor:who.actor,repo:plan.repo,taskId:plan.rootId,runId:plan.runId,action:LAND_HANDOFF,outcome:"pending",source:"request"},{v:1,key:plan.key,ref:plan.ref,old:plan.old,commit,keep,folder:project.repo,policy:"squash",candidate:plan.candidate,base:plan.squash.base,tree:plan.squash.tree,checkedTree:plan.squash.checkedTree,checks:plan.checks}))})}catch(error){if(error instanceof Refused)return error.result;throw error}const at=await git(["rev-parse","--verify","-q",`${keep}^{commit}`]);return at.code!==0||at.stdout.trim()!==commit?refuse("git","Toolroll couldn't keep the landing commit. Nothing landed; look again, then land it."):(replayed||recordActionWhole(store.handle,{at:now.toISOString(),actor:"toolroll",repo:plan.repo,taskId:plan.rootId,runId:plan.runId,action:LAND_HANDOFF_SETTLED,outcome:`${handoffId}:kept`,source:"work"},{v:1,keep,commit}),{ok:!0,replayed,kind:"land",ref:plan.ref,branch:plan.branch,commit,old:plan.old,mode:"handoff",warning:null,handoff:{ref:keep,command:handoffCommand(project.repo,commit)}})}let intentId;try{intentId=store.transact(()=>{const who=stillStands();if(!who.ok)throw new Refused(who);if(intents(store,"repo = ?",[plan.repo]).some(one=>settledOf(store,one.id)===null))throw new Refused(refuse("busy","Another landing in this project hasn't finished. Try again in a moment."));return consumeLandPasskey(),plan.recorded||recordActionWhole(store.handle,{at:now.toISOString(),actor:who.actor,repo:plan.repo,taskId:null,runId:null,action:LAND_DESTINATION,outcome:plan.ref,source:"request"},{v:1,ref:plan.ref,common:project.common}),recordActionWhole(store.handle,{at:now.toISOString(),actor:who.actor,repo:plan.repo,taskId:plan.rootId,runId:plan.runId,action:LAND_INTENT,outcome:"pending",source:"request"},{v:1,kind:plan.kind,key:plan.key,ref:plan.ref,old:plan.old,commit,mode:"ref",...plan.reverts===void 0?{}:{reverts:plan.reverts.source},...plan.squash===null?{}:{policy:"squash",candidate:plan.candidate,base:plan.squash.base,tree:plan.squash.tree,checkedTree:plan.squash.checkedTree,keep,checks:plan.checks}})})}catch(error){if(error instanceof Refused)return error.result;throw error}const settle=(outcome,words)=>recordActionWhole(store.handle,{at:now.toISOString(),actor:"toolroll",repo:plan.repo,taskId:plan.rootId,runId:plan.runId,action:LAND_SETTLED,outcome:`${intentId}:${outcome}`,source:"work"},{v:1,words}),place=await placeOf(git,project,plan.ref,plan.old);if(place.kind!=="free"){const words=place.kind==="problem"?place.message:`${plan.branch} is checked out in your project folder now, so Toolroll won't move it. Look again, then land it.`;return settle("refused",words),refuse(place.kind==="problem"?place.reason:"occupied",words)}const last=store.transact(stillStands);if(!last.ok)return settle("refused",last.message),last;if((await git(["update-ref","--no-deref","-m",`toolroll: land ${plan.taskId}`,plan.ref,commit,plan.old])).code!==0){const words=`${plan.branch} moved while landing, so nothing changed. Look again, then land it.`;return settle("refused",words),refuse("moved",words)}return settle("landed",plan.kind==="undo"?"Undone.":"Landed."),{ok:!0,replayed:!1,kind:plan.kind,ref:plan.ref,branch:plan.branch,commit,old:plan.old,mode:"ref",warning:null,handoff:null}})}async function keepAt(git,ref,commit,why){const was=await git(["rev-parse","--verify","-q",ref]),old=was.code===0?was.stdout.trim():"0".repeat(40);return old===commit?!0:was.code===0&&!OID.test(old)?!1:(await git(["update-ref","--no-deref","-m",why,ref,commit,old])).code===0}async function reconcileHandoff(store,git,repo,rootId,id,actor,now){const one=handoffsOf(store,repo,rootId).find(row=>row.id===id);return one===void 0||(await git(["merge-base","--is-ancestor",one.commit,one.ref])).code!==0?!1:store.transact(()=>{const recorded=intents(store,"task_id = ?",[rootId]).find(intent2=>intent2.fromHandoff===one.id);if(recorded!==void 0)return settledOf(store,recorded.id)?.outcome.startsWith("landed")===!0;if(landedCommits(store,rootId).has(one.commit))return!1;const intent=recordActionWhole(store.handle,{at:now.toISOString(),actor,repo,taskId:rootId,runId:one.run,action:LAND_INTENT,outcome:"pending",source:"request"},{v:1,kind:"land",key:one.key,ref:one.ref,old:one.old,commit:one.commit,mode:"ref",policy:"squash",candidate:one.candidate,fromHandoff:one.id});return recordActionWhole(store.handle,{at:now.toISOString(),actor:"toolroll",repo,taskId:rootId,runId:one.run,action:LAND_SETTLED,outcome:`${intent}:landed:brought-in`,source:"work"},{v:1,words:"The person brought in the landing commit Toolroll made; recorded as landed."}),!0})}function oidOrThrow(oid){if(!OID.test(oid))throw new Error("not a commit id");return oid}const UNSAFE_IN_COMMAND=/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u061c\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\ufeff]/;export const unsafeInCommand=text=>UNSAFE_IN_COMMAND.test(text);export function gitCommand(folder,args){return UNSAFE_IN_COMMAND.test(folder)?null:["git","-C",`'${folder.replace(/'/g,"'\\''")}'`,...args].join(" ")}export const UNSAFE_FOLDER=what=>`Toolroll can't write a safe command for this folder's name; run ${what} in your project folder.`;function handoffCommand(folder,commit){return gitCommand(folder,["merge","--ff-only",oidOrThrow(commit)])}export function handoffWords(handoff,commit){return handoff.command===null?UNSAFE_FOLDER(`git merge --ff-only ${commit}`):`To bring it in: ${handoff.command}`}function handoffRows(store,repo,taskId){return store.handle.prepare(`SELECT id,detail,task_id,run_id FROM action_ledger WHERE repo = ? AND action = ?${taskId===void 0?"":" AND task_id = ?"} ORDER BY id DESC`).all(...taskId===void 0?[repo,LAND_HANDOFF]:[repo,LAND_HANDOFF,taskId]).flatMap(row=>{try{const d=JSON.parse(String(row.detail??"null")),ok=d.v===1&&typeof d.key=="string"&&typeof d.ref=="string"&&typeof d.old=="string"&&OID.test(d.old)&&typeof d.commit=="string"&&OID.test(d.commit)&&typeof d.keep=="string"&&typeof d.folder=="string"&&typeof d.candidate=="string"&&OID.test(d.candidate),id=Number(row.id),settled=ok&&store.handle.prepare("SELECT 1 AS hit FROM action_ledger WHERE action = ? AND outcome = ? LIMIT 1").get(LAND_HANDOFF_SETTLED,`${id}:kept`)!==void 0;return ok?[{id,task:String(row.task_id),run:Number(row.run_id),key:d.key,ref:d.ref,old:d.old,commit:d.commit,keep:d.keep,folder:d.folder,candidate:d.candidate,settled}]:[]}catch{return[]}})}export function handoffsOf(store,repo,taskId){return handoffRows(store,repo,taskId).filter(one=>one.settled)}export function keptHandoffOf(store,repo,rootId,candidate){if(candidate===null||!OID.test(candidate))return null;const one=handoffsOf(store,repo,rootId).find(row=>row.candidate===candidate);if(one===void 0)return null;const command=handoffCommand(one.folder,one.commit);return{commit:one.commit,branch:one.ref.replace(/^refs\/heads\//,""),command,words:handoffWords({command},one.commit)}}class Refused extends Error{result;constructor(result){super(result.message),this.result=result}}async function squashCommit(git,plan,scratch){const squash=plan.squash;if(squash.tree!==squash.checkedTree)return refuse("checks","The commit Toolroll would land doesn't carry the files its checks ran on. Nothing landed.");const verified=await git(["rev-parse","--verify","-q",`${plan.candidate}^{tree}`]);if(verified.code!==0||verified.stdout.trim()!==squash.checkedTree)return refuse("checks","The result's files aren't the ones its checks ran on any more. Nothing landed.");const folder=mkdtempSync(join(scratch??tmpdir(),"toolroll-land-"));let written;try{const file=join(folder,"commit");writeFileSync(file,squashBody(squash.tree,plan.old,squash.time,squash.message),{encoding:"utf8",mode:384,flag:"wx"}),written=await git(["hash-object","-t","commit","-w","--",file])}finally{rmSync(folder,{recursive:!0,force:!0})}const commit=written.stdout.trim();if(written.code!==0||commit!==squash.commit)return refuse("stale","The commit Toolroll would land isn't the one you read. Nothing landed; look again.");const shown=await git(["cat-file","commit",commit]),header=shown.stdout.split(`
|
|
8
|
+
`}function commitIdOf(body){return createHash("sha1").update(`commit ${Buffer.byteLength(body,"utf8")}\0`).update(body,"utf8").digest("hex")}const UNSAFE_SHOWN=/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u061c\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff\\]/g;export function shownName(name){return name.replace(UNSAFE_SHOWN,ch=>ch==="\\"?"\\\\":`\\u{${ch.codePointAt(0).toString(16)}}`)}export function landingWords(plan){const how=plan.mode==="files"?`your project folder has ${plan.branch} checked out and clean; Land fast-forwards it in place`:plan.mode==="handoff"?`your project folder has ${plan.branch} checked out, so Toolroll won't touch its files: Land makes the commit and shows the one git command that brings it in`:`no folder has ${plan.branch} checked out; only the branch moves`;if(plan.kind==="undo")return[`Undo the landing of ${short(plan.reverts.landed)} on ${plan.branch} in ${shownName(plan.repo)} (${how}).`,"A new commit reverts exactly what it changed; nothing is rewritten. No check runs on the undo."];const squash=plan.squash,names=squash.files.slice(0,3).map(shownName).join(", ")+(squash.fileCount>3?` and ${squash.fileCount-3} more`:"");return[`Lands 1 commit on ${plan.branch}: ${squash.fileCount===0?"no file changes":names} (+${squash.added} −${squash.removed}).`,`${short(squash.commit)} "${shownName(squash.message)}", on top of ${short(plan.old)} in ${shownName(plan.repo)} (${how}).`,plan.checks==="passed"?`Checks ran on these exact files: they passed on ${short(plan.candidate)}, and ${short(squash.commit)} carries the same tree.`:"No check ran: this project has no check command.",...plan.recorded?[]:[`Toolroll remembers ${plan.branch} as where this project's work lands.`]]}async function settleUnfinished(store,repo,now,options){const project=projectOf(store,repo);if(project===null)return;const git=gitFor(repo,options.git);for(const intent of intents(store,"repo = ?",[repo]).filter(one=>settledOf(store,one.id)===null)){const branch=intent.ref.replace(/^refs\/heads\//,""),state=await inspectInPlaceState(git,project,intent.ref,intent.old,intent.commit);let outcome,words,extra={};!state.refReadable||state.refAt===null?(outcome="unresolved",words=`${branch} now points at another branch or can't be read. Choose how to resolve this unfinished landing below.`,extra={state:stateSummaryOf(state)}):state.refAt===intent.old?intent.mode==="files"&&state.headSym===intent.ref&&!state.indexMatchesOld?(outcome="unresolved",words=`A previous landing on ${branch} stopped before moving the branch, but your checkout index doesn't match ${short(intent.old)}. Choose how to resolve it below.`,extra={state:stateSummaryOf(state)}):(outcome="abandoned",words="It stopped before the branch moved; nothing changed."):state.refAt===intent.commit?intent.mode==="files"?isProvenInPlaceLanded(state,intent.ref,intent.commit)?(outcome="landed:recovered",words="It had finished in place; recorded now."):(outcome="unresolved",words=`${branch} moved to ${short(intent.commit)}, but your project folder's index or files don't match that commit yet. Choose how to resolve it below.`,extra={state:stateSummaryOf(state)}):(outcome="landed:recovered",words="It had finished; recorded now."):(outcome="unresolved",words=`${branch} is at ${short(state.refAt)} now, neither before nor after the unfinished landing. Choose how to resolve it below.`,extra={state:stateSummaryOf(state)}),recordActionWhole(store.handle,{at:now.toISOString(),actor:"toolroll",repo,taskId:intent.task,runId:intent.run,action:LAND_SETTLED,outcome:`${intent.id}:${outcome}`,source:"work"},{v:1,words,...extra})}}export async function reconcileUnfinishedLandings(store,repo,authority,access,now,options){return access.repos!==null&&!access.repos.includes(repo)||!standing(store,authority,repo).ok?!1:(await locked(repo,async()=>{const project=projectOf(store,repo);return project!==null&&releaseLeftoverHeadLock(project.common),settleUnfinished(store,repo,now,options)}),!0)}export async function resolveUnresolvedLanding(store,taskId,action,authority,access,now,options,shown=null){const repo=store.lookupRef(taskId)?.repo??null;if(repo===null||access.repos!==null&&!access.repos.includes(repo))return refuse("not-found",`No task \`${taskId}\` in your projects.`);const first=standing(store,authority,repo);if(!first.ok)return first;const project=projectOf(store,repo);if(project===null)return refuse("destination","This task's project isn't a local Git folder Toolroll can land in.");const rootId=store.taskFamilyOf(taskId,null,!0)?.root.id??taskId;return locked(repo,async()=>{await settleUnfinished(store,repo,now,options);const unresolved=unresolvedLandingOf(store,rootId)??unresolvedLandingForRepo(store,repo);if(unresolved===null)return{ok:!0,outcome:"already-clear",message:"No unfinished landing needs attention."};if(shown===null||shown.intentId!==unresolved.intentId||shown.commit!==unresolved.commit||shown.old!==unresolved.old)return{ok:!1,reason:"unresolved",message:"This page showed a different unfinished landing than the one there now; nothing changed. Look again, then choose.",unresolved};const git=gitFor(repo,options.git),settleNew=(outcome,words,extra={})=>store.transact(()=>{const who=standing(store,authority,repo);return who.ok?(recordActionWhole(store.handle,{at:now.toISOString(),actor:who.actor,repo,taskId:unresolved.taskId,runId:unresolved.runId,action:LAND_SETTLED,outcome:`${unresolved.intentId}:${outcome}`,source:"request"},{v:1,words,...extra}),{ok:!0}):who});if(action==="dismiss"){const wrote=settleNew("dismissed","Cleared by operator; landing was not recorded as completed.");return wrote.ok?{ok:!0,outcome:"dismissed",message:"Cleared the unfinished landing notice. The task is not marked as landed."}:wrote}const state=await inspectInPlaceState(git,project,unresolved.ref,unresolved.old,unresolved.commit);if(action==="complete"){if(isProvenInPlaceLanded(state,unresolved.ref,unresolved.commit)){const wrote=settleNew("landed:recovered","Confirmed completed landing in place.");return wrote.ok?{ok:!0,outcome:"landed",message:`Confirmed landing on ${unresolved.branch} (${short(unresolved.commit)}).`}:wrote}if(!state.refSymbolic&&state.refReadable&&state.refAt===unresolved.commit&&state.headSym===unresolved.ref&&state.headAt===unresolved.commit&&state.checkouts!==null&&state.checkouts.length===1&&state.checkouts[0]===state.repoReal&&state.indexMatchesOld&&state.inProgressOps!==null&&state.inProgressOps.length===0){const checkBefore=standing(store,authority,repo);if(!checkBefore.ok)return checkBefore;const updated=await git(["read-tree","-m","-u",unresolved.old,unresolved.commit]),after=await inspectInPlaceState(git,project,unresolved.ref,unresolved.old,unresolved.commit);if(updated.code===0&&isProvenInPlaceLanded(after,unresolved.ref,unresolved.commit)){const wrote=settleNew("landed:recovered","Finished updating files in place and recorded the landing.");return wrote.ok?{ok:!0,outcome:"landed",message:`Finished landing on ${unresolved.branch} (${short(unresolved.commit)}).`}:wrote}return{ok:!1,reason:"unresolved",message:"Your project folder has local changes that stop this landing from finishing automatically. Choose Restore branch or Clear notice.",unresolved}}return{ok:!1,reason:"unresolved",message:"The branch or checkout state changed too far to finish this landing automatically. Choose Restore branch or Clear notice.",unresolved}}if(!state.refSymbolic&&state.refReadable&&state.refAt===unresolved.old&&(state.headSym!==unresolved.ref||state.indexMatchesOld)){const wrote=settleNew("abandoned","Confirmed branch is back at its previous commit.");return wrote.ok?{ok:!0,outcome:"rolled-back",message:`${unresolved.branch} is back at ${short(unresolved.old)}.`}:wrote}if(!state.refSymbolic&&state.refReadable&&state.refAt===unresolved.commit){const checkBefore=standing(store,authority,repo);if(!checkBefore.ok)return checkBefore;if(state.headSym===unresolved.ref&&state.indexMatchesCommit&&state.worktreeMatchesCommit&&state.inProgressOps!==null&&state.inProgressOps.length===0){if((await git(["read-tree","-m","-u",unresolved.commit,unresolved.old])).code!==0)return{ok:!1,reason:"unresolved",message:"Couldn't restore the project folder's files cleanly. Choose Clear notice if you want to handle it manually.",unresolved}}else if(state.headSym===unresolved.ref&&!state.indexMatchesOld)return{ok:!1,reason:"unresolved",message:"Your project folder has staged or modified files, so Toolroll won't overwrite them during rollback. Choose Clear notice after checking them.",unresolved};const rolled=await git(["update-ref","--no-deref","-m",`toolroll: rollback land ${unresolved.taskId}`,unresolved.ref,unresolved.old,unresolved.commit]),after=await inspectInPlaceState(git,project,unresolved.ref,unresolved.old,unresolved.commit);if(rolled.code===0&&after.refAt===unresolved.old&&(after.headSym!==unresolved.ref||after.indexMatchesOld)){const wrote=settleNew("abandoned",`Restored ${unresolved.branch} to ${short(unresolved.old)}.`);return wrote.ok?{ok:!0,outcome:"rolled-back",message:`Restored ${unresolved.branch} to ${short(unresolved.old)}.`}:wrote}}return{ok:!1,reason:"unresolved",message:`${unresolved.branch} moved past the unfinished landing, so Toolroll won't roll it back automatically. Choose Clear notice to clear this blocker.`,unresolved}})}function standing(store,authority,repo){if(authority.kind==="local"){const local=localActNow(store,"land-task");return local===null?refuse("authority",LOCAL_OWNER_LAPSED):!verifyApproverStanding(store,local.account,local.accountGeneration,store.knownRepos().filter(one=>store.accountCanAccess(local.account,one))).ok||!store.accountCanAccess(local.account,repo)?refuse("authority",LOCAL_OWNER_LAPSED):{ok:!0,actor:`operator:${local.account}`}}if(!reproveApprover(store,authority.who).ok||!authority.who.repos.includes(repo)||!store.accountCanAccess(authority.who.name,repo))return refuse("authority","Your access changed. Sign in again.");if(authority.kind==="passkey"){const dev=getPairedDevice(store.handle,authority.proof.deviceId),identity=store.workspaceIdentity();if(dev===null||dev.revokedAt!==null||dev.activatedAt===null||dev.accountName!==authority.who.name||dev.recoveryGeneration!==identity.recoveryGeneration||!deviceAccountStands(dev,store.accountOf(authority.who.name)))return refuse("authority","This iPhone is no longer paired or your account changed.")}return{ok:!0,actor:`operator:${authority.who.name}`}}const projectLocks=new Map;async function locked(repo,body){const before=projectLocks.get(repo)??Promise.resolve();let release;const mine=new Promise(resolve=>{release=resolve}),chained=before.then(()=>mine);projectLocks.set(repo,chained),await before.catch(()=>{});try{return await body()}finally{release(),projectLocks.get(repo)===chained&&projectLocks.delete(repo)}}export async function land(store,taskId,input,authority,access,now,options){if(!/^[0-9a-f]{16}$/.test(input.key))return refuse("stale","That landing isn't the one on screen. Look again, then land it.");const repo=store.lookupRef(taskId)?.repo??null;if(repo===null||access.repos!==null&&!access.repos.includes(repo))return refuse("not-found",`No task \`${taskId}\` in your projects.`);const first=standing(store,authority,repo);if(!first.ok)return first;if(publishesThroughPullRequests(store,repo))return refuse("pull-requests",PULL_REQUESTS_INSTEAD);const named=input.into!==void 0&&landableBranch(input.into)?`refs/heads/${input.into}`:recordedDestination(store,repo)?.ref??null;return named!==null&&projectOf(store,repo)!==null&&(await gitFor(repo,options.git)(["symbolic-ref","-q",named])).code===0?refuse("destination",`${named.replace(/^refs\/heads\//,"")} points at another branch, so Toolroll won't move it. Land it with git yourself.`):locked(repo,async()=>{const done=intents(store,"repo = ? AND task_id IS NOT NULL",[repo]).find(one=>one.key===input.key);if(done!==void 0&&settledOf(store,done.id)?.outcome.startsWith("landed")===!0){const who=standing(store,authority,repo);return who.ok?{ok:!0,replayed:!0,kind:done.kind,ref:done.ref,branch:done.ref.slice(11),commit:done.commit,old:done.old,mode:done.mode,warning:null,handoff:null}:who}const handedOff=input.undo===!0||input.requireInPlace===!0?void 0:handoffRows(store,repo).find(one=>one.key===input.key);if(handedOff!==void 0){const who=standing(store,authority,repo);if(!who.ok)return who;const git2=gitFor(repo,options.git),there=await git2(["cat-file","-t",handedOff.commit]);return there.code!==0||there.stdout.trim()!=="commit"?refuse("git","The landing commit Toolroll kept for this is gone. Look again, then land it."):await keepAt(git2,handedOff.keep,handedOff.commit,`toolroll: landing commit for ${taskId}`)?(handedOff.settled||recordActionWhole(store.handle,{at:now.toISOString(),actor:"toolroll",repo,taskId:handedOff.task,runId:handedOff.run,action:LAND_HANDOFF_SETTLED,outcome:`${handedOff.id}:kept`,source:"work"},{v:1,keep:handedOff.keep,commit:handedOff.commit}),{ok:!0,replayed:handedOff.settled,kind:"land",ref:handedOff.ref,branch:handedOff.ref.slice(11),commit:handedOff.commit,old:handedOff.old,mode:"handoff",warning:null,handoff:{ref:handedOff.keep,command:handoffCommand(repo,handedOff.commit)}}):refuse("git","Toolroll couldn't keep the landing commit. Look again, then land it.")}await settleUnfinished(store,repo,now,options);const read=await readLanding(store,taskId,access,now,{...options,...input.into===void 0?{}:{into:input.into},...input.undo===!0?{undo:!0}:{}});if(!read.ok)return read;if(!("plan"in read))return refuse("nothing",read.landed.reverted===!0?landedLine(read.landed):ALREADY_MSG(read.landed.ref,read.landed.commit));const plan=read.plan;if(plan.key!==input.key)return refuse("stale","Something changed since you looked (the branch, the checks or the result). Look again, then land it.");if(input.requireInPlace===!0&&(ownerMode(store,now)!=="fast"||plan.mode==="handoff"))return refuse("stale","In-place landing requires Fast mode; nothing landed.");const project=projectOf(store,plan.repo),git=gitFor(plan.repo,options.git),handoffSource=plan.kind==="undo"?/^handoff:(\d+)$/.exec(plan.reverts?.source??""):null;if(handoffSource!==null&&!await reconcileHandoff(store,git,plan.repo,plan.rootId,Number(handoffSource[1]),first.actor,now))return refuse("stale","That landing changed since you looked. Look again.");const stillStands=()=>{const who=standing(store,authority,plan.repo);if(!who.ok)return who;if(publishesThroughPullRequests(store,plan.repo))return refuse("pull-requests",PULL_REQUESTS_INSTEAD);if(plan.kind==="land"){const again=assignmentOf(store,taskId,now,{principal:"operator",repos:access.repos},options.root);if(again?.state!=="complete"||again.receipt?.digest!==plan.receipt||again.completion?.digest!==plan.completion)return refuse("stale","This result changed since you looked. Look again, then land it.")}else{const landed=landingOf(store,plan.rootId),name=landed===null?null:landed.intent.fromHandoff!==null?`handoff:${landed.intent.fromHandoff}`:`intent:${landed.intent.id}`;if(landed===null||landed.undone||name!==plan.reverts?.source)return refuse("stale","That landing changed since you looked. Look again.")}return JSON.stringify(checkBindingsOf(store,plan.repo))!==JSON.stringify(plan.bindings)?refuse("stale","The project's checks changed since you looked. Look again, then land it."):who},pre=standing(store,authority,plan.repo);if(!pre.ok)return pre;const landBinding={verb:"land",taskId,planKey:plan.key,into:input.into??null,undo:input.undo===!0},passkeyChecked=authority.kind!=="passkey"?null:checkPasskeyAction(store,{accountName:authority.who.name,repo:plan.repo,verb:"land",expectedBinding:landBinding,proof:authority.proof,now});if(passkeyChecked!==null&&!passkeyChecked.ok)return refuse("authority",passkeyChecked.message);const consumeLandPasskey=()=>{if(authority.kind!=="passkey"||passkeyChecked===null||!passkeyChecked.ok)return;const at=authority.clock(),consumed=consumePasskeyAction(store,passkeyChecked,{repo:plan.repo,now:at});if(!consumed.ok)throw new Refused(refuse("authority",consumed.message));store.recordAction({at:at.toISOString(),actor:authority.who.name,repo:plan.repo,taskId:plan.rootId,runId:plan.runId,action:LAND_PROVED_ACTION,outcome:"passkey",source:"request",detail:passkeyProofDetail({at,generation:consumed.accountGeneration,digest:plan.key,verb:"land",credentialId:consumed.credentialId,pairedDeviceId:consumed.deviceId,be:consumed.be,bs:consumed.bs})})},made=plan.kind==="undo"?await revertCommit(git,plan,options.scratch):await squashCommit(git,plan,options.scratch);if(!made.ok)return made;const commit=made.commit,keep=handoffRefOf(plan.rootId,commit);if(plan.kind==="land"&&!await keepAt(git,keep,commit,`toolroll: landing commit for ${plan.taskId}`))return refuse("git","Toolroll made the landing commit but couldn't keep it. Nothing landed; look again, then land it.");if(plan.mode==="handoff"){const place2=await placeOf(git,project,plan.ref,plan.old);if(place2.kind!=="folder")return refuse(place2.kind==="problem"?place2.reason:"stale",place2.kind==="problem"?place2.message:"Your project folder changed since you looked. Look again, then land it.");let handoffId,replayed=!1;try{handoffId=store.transact(()=>{const who=stillStands();if(!who.ok)throw new Refused(who);const earlier=handoffRows(store,plan.repo).find(one=>one.key===plan.key&&one.commit===commit);return earlier!==void 0?(replayed=earlier.settled,earlier.id):(consumeLandPasskey(),plan.recorded||recordActionWhole(store.handle,{at:now.toISOString(),actor:who.actor,repo:plan.repo,taskId:null,runId:null,action:LAND_DESTINATION,outcome:plan.ref,source:"request"},{v:1,ref:plan.ref,common:project.common}),recordActionWhole(store.handle,{at:now.toISOString(),actor:who.actor,repo:plan.repo,taskId:plan.rootId,runId:plan.runId,action:LAND_HANDOFF,outcome:"pending",source:"request"},{v:1,key:plan.key,ref:plan.ref,old:plan.old,commit,keep,folder:project.repo,policy:"squash",candidate:plan.candidate,base:plan.squash.base,tree:plan.squash.tree,checkedTree:plan.squash.checkedTree,checks:plan.checks}))})}catch(error){if(error instanceof Refused)return error.result;throw error}const at=await git(["rev-parse","--verify","-q",`${keep}^{commit}`]);return at.code!==0||at.stdout.trim()!==commit?refuse("git","Toolroll couldn't keep the landing commit. Nothing landed; look again, then land it."):(replayed||recordActionWhole(store.handle,{at:now.toISOString(),actor:"toolroll",repo:plan.repo,taskId:plan.rootId,runId:plan.runId,action:LAND_HANDOFF_SETTLED,outcome:`${handoffId}:kept`,source:"work"},{v:1,keep,commit}),{ok:!0,replayed,kind:"land",ref:plan.ref,branch:plan.branch,commit,old:plan.old,mode:"handoff",warning:null,handoff:{ref:keep,command:handoffCommand(project.repo,commit)}})}let intentId;try{intentId=store.transact(()=>{const who=stillStands();if(!who.ok)throw new Refused(who);if(intents(store,"repo = ?",[plan.repo]).some(one=>settledOf(store,one.id)===null))throw new Refused(refuse("busy","Another landing in this project hasn't finished. Try again in a moment."));return consumeLandPasskey(),plan.recorded||recordActionWhole(store.handle,{at:now.toISOString(),actor:who.actor,repo:plan.repo,taskId:null,runId:null,action:LAND_DESTINATION,outcome:plan.ref,source:"request"},{v:1,ref:plan.ref,common:project.common}),recordActionWhole(store.handle,{at:now.toISOString(),actor:who.actor,repo:plan.repo,taskId:plan.rootId,runId:plan.runId,action:LAND_INTENT,outcome:"pending",source:"request"},{v:1,kind:plan.kind,key:plan.key,ref:plan.ref,old:plan.old,commit,mode:plan.mode,...plan.reverts===void 0?{}:{reverts:plan.reverts.source},...plan.squash===null?{}:{policy:"squash",candidate:plan.candidate,base:plan.squash.base,tree:plan.squash.tree,checkedTree:plan.squash.checkedTree,keep,checks:plan.checks}})})}catch(error){if(error instanceof Refused)return error.result;throw error}const settle=(outcome,words,extra={})=>recordActionWhole(store.handle,{at:now.toISOString(),actor:"toolroll",repo:plan.repo,taskId:plan.rootId,runId:plan.runId,action:LAND_SETTLED,outcome:`${intentId}:${outcome}`,source:"work"},{v:1,words,...extra}),place=await placeOf(git,project,plan.ref,plan.old);if(plan.mode==="files"){if(place.kind!=="folder"){const words2=place.kind==="problem"?place.message:`${plan.branch} is no longer checked out in your project folder. Look again, then land it.`;return settle("refused",words2),refuse(place.kind==="problem"?place.reason:"stale",words2)}if(place.dirty.length>0){const dirty=dirtyRefuse(plan.branch,place.dirty);return settle("refused",dirty.message),dirty}if(ownerMode(store,now)!=="fast"){const words2="Fast mode was turned off before landing in place; nothing landed. Look again, then land it.";return settle("refused",words2),refuse("stale",words2)}const headSymBefore=await git(["symbolic-ref","-q","HEAD"]),headAtBefore=await git(["rev-parse","--verify","-q","HEAD^{commit}"]),idxBefore=await git(["diff-index","--cached","--quiet",plan.old]);if(headSymBefore.code!==0||headSymBefore.stdout.trim()!==plan.ref||headAtBefore.code!==0||headAtBefore.stdout.trim()!==plan.old||idxBefore.code!==0){const words2="Your project folder's branch or index changed before landing; nothing landed. Look again, then land it.";return settle("refused",words2),refuse(idxBefore.code!==0?"dirty":"stale",words2)}const last2=store.transact(stillStands);if(!last2.ok)return settle("refused",last2.message),last2;if((await git(["update-ref","--no-deref","-m",`toolroll: land ${plan.taskId}`,plan.ref,commit,plan.old])).code!==0){const words2=`${plan.branch} moved while landing, so nothing changed. Look again, then land it.`;return settle("refused",words2),refuse("moved",words2)}const headLock=await holdHeadLock(git),headSymMid=await git(["symbolic-ref","-q","HEAD"]),idxMid=await git(["diff-index","--cached","--quiet",plan.old]);if(!headLock.ok||headSymMid.code!==0||headSymMid.stdout.trim()!==plan.ref||idxMid.code!==0){headLock.ok&&headLock.release();const rolled=await git(["update-ref","--no-deref","-m",`toolroll: rollback land ${plan.taskId}`,plan.ref,plan.old,commit]),midState=await inspectInPlaceState(git,project,plan.ref,plan.old,commit);if(rolled.code===0&&midState.refAt===plan.old){const words3="Your project folder switched branches or staged changes while landing, so nothing landed. Look again, then land it.";return settle("refused",words3),refuse("stale",words3)}const words2=`Landing on ${plan.branch} stopped after updating the branch because your project folder switched branches or staged changes. Resolve it below.`;settle("unresolved",words2,{state:stateSummaryOf(midState)});const unresolved2=unresolvedLandingForRepo(store,plan.repo)??void 0;return{ok:!1,reason:"unresolved",message:words2,...unresolved2===void 0?{}:{unresolved:unresolved2}}}const updated=await git(["read-tree","-m","-u",plan.old,commit]);if(headLock.release(),updated.code!==0){const rolled=await git(["update-ref","--no-deref","-m",`toolroll: rollback land ${plan.taskId}`,plan.ref,plan.old,commit]),failState=await inspectInPlaceState(git,project,plan.ref,plan.old,commit);if(rolled.code===0&&failState.refAt===plan.old&&(failState.headSym!==plan.ref||failState.indexMatchesOld)){const words3="Your project folder changed while landing, so nothing landed. Look again, then land it.";return settle("refused",words3),refuse(failState.dirtyFiles!==null&&failState.dirtyFiles.length>0?"dirty":"stale",words3)}const words2=`Landing on ${plan.branch} stopped partway through (${plan.branch} moved to ${short(commit)}, but your checkout files couldn't all be updated). Resolve it below.`;settle("unresolved",words2,{state:stateSummaryOf(failState)});const unresolved2=unresolvedLandingForRepo(store,plan.repo)??void 0;return{ok:!1,reason:"unresolved",message:words2,...unresolved2===void 0?{}:{unresolved:unresolved2}}}const after=await inspectInPlaceState(git,project,plan.ref,plan.old,commit);if(isProvenInPlaceLanded(after,plan.ref,commit))return settle("landed","Landed in place."),{ok:!0,replayed:!1,kind:plan.kind,ref:plan.ref,branch:plan.branch,commit,old:plan.old,mode:"files",warning:null,handoff:null};const words=`Landing on ${plan.branch} wrote changes, but the final checkout state didn't match ${short(commit)} cleanly. Resolve it below.`;settle("unresolved",words,{state:stateSummaryOf(after)});const unresolved=unresolvedLandingForRepo(store,plan.repo)??void 0;return{ok:!1,reason:"unresolved",message:words,...unresolved===void 0?{}:{unresolved}}}if(place.kind!=="free"){const words=place.kind==="problem"?place.message:`${plan.branch} is checked out in your project folder now. Look again, then land it.`;return settle("refused",words),refuse(place.kind==="problem"?place.reason:"occupied",words)}const last=store.transact(stillStands);if(!last.ok)return settle("refused",last.message),last;if((await git(["update-ref","--no-deref","-m",`toolroll: land ${plan.taskId}`,plan.ref,commit,plan.old])).code!==0){const words=`${plan.branch} moved while landing, so nothing changed. Look again, then land it.`;return settle("refused",words),refuse("moved",words)}return settle("landed",plan.kind==="undo"?"Undone.":"Landed."),{ok:!0,replayed:!1,kind:plan.kind,ref:plan.ref,branch:plan.branch,commit,old:plan.old,mode:"ref",warning:null,handoff:null}})}async function keepAt(git,ref,commit,why){const was=await git(["rev-parse","--verify","-q",ref]),old=was.code===0?was.stdout.trim():"0".repeat(40);return old===commit?!0:was.code===0&&!OID.test(old)?!1:(await git(["update-ref","--no-deref","-m",why,ref,commit,old])).code===0}async function reconcileHandoff(store,git,repo,rootId,id,actor,now){const one=handoffsOf(store,repo,rootId).find(row=>row.id===id);return one===void 0||(await git(["merge-base","--is-ancestor",one.commit,one.ref])).code!==0?!1:store.transact(()=>{const recorded=intents(store,"task_id = ?",[rootId]).find(intent2=>intent2.fromHandoff===one.id);if(recorded!==void 0)return settledOf(store,recorded.id)?.outcome.startsWith("landed")===!0;if(landedCommits(store,rootId).has(one.commit))return!1;const intent=recordActionWhole(store.handle,{at:now.toISOString(),actor,repo,taskId:rootId,runId:one.run,action:LAND_INTENT,outcome:"pending",source:"request"},{v:1,kind:"land",key:one.key,ref:one.ref,old:one.old,commit:one.commit,mode:"ref",policy:"squash",candidate:one.candidate,fromHandoff:one.id});return recordActionWhole(store.handle,{at:now.toISOString(),actor:"toolroll",repo,taskId:rootId,runId:one.run,action:LAND_SETTLED,outcome:`${intent}:landed:brought-in`,source:"work"},{v:1,words:"The person brought in the landing commit Toolroll made; recorded as landed."}),!0})}function oidOrThrow(oid){if(!OID.test(oid))throw new Error("not a commit id");return oid}const UNSAFE_IN_COMMAND=/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u061c\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\ufeff]/;export const unsafeInCommand=text=>UNSAFE_IN_COMMAND.test(text);export function gitCommand(folder,args){return UNSAFE_IN_COMMAND.test(folder)?null:["git","-C",`'${folder.replace(/'/g,"'\\''")}'`,...args].join(" ")}export const UNSAFE_FOLDER=what=>`Toolroll can't write a safe command for this folder's name; run ${what} in your project folder.`;function handoffCommand(folder,commit){return gitCommand(folder,["merge","--ff-only",oidOrThrow(commit)])}export function handoffWords(handoff,commit){return handoff.command===null?UNSAFE_FOLDER(`git merge --ff-only ${commit}`):`To bring it in: ${handoff.command}`}function handoffRows(store,repo,taskId){return store.handle.prepare(`SELECT id,detail,task_id,run_id FROM action_ledger WHERE repo = ? AND action = ?${taskId===void 0?"":" AND task_id = ?"} ORDER BY id DESC`).all(...taskId===void 0?[repo,LAND_HANDOFF]:[repo,LAND_HANDOFF,taskId]).flatMap(row=>{try{const d=JSON.parse(String(row.detail??"null")),ok=d.v===1&&typeof d.key=="string"&&typeof d.ref=="string"&&typeof d.old=="string"&&OID.test(d.old)&&typeof d.commit=="string"&&OID.test(d.commit)&&typeof d.keep=="string"&&typeof d.folder=="string"&&typeof d.candidate=="string"&&OID.test(d.candidate),id=Number(row.id),settled=ok&&store.handle.prepare("SELECT 1 AS hit FROM action_ledger WHERE action = ? AND outcome = ? LIMIT 1").get(LAND_HANDOFF_SETTLED,`${id}:kept`)!==void 0;return ok?[{id,task:String(row.task_id),run:Number(row.run_id),key:d.key,ref:d.ref,old:d.old,commit:d.commit,keep:d.keep,folder:d.folder,candidate:d.candidate,settled}]:[]}catch{return[]}})}export function handoffsOf(store,repo,taskId){return handoffRows(store,repo,taskId).filter(one=>one.settled)}export function keptHandoffOf(store,repo,rootId,candidate){if(candidate===null||!OID.test(candidate))return null;const one=handoffsOf(store,repo,rootId).find(row=>row.candidate===candidate);if(one===void 0)return null;const command=handoffCommand(one.folder,one.commit);return{commit:one.commit,branch:one.ref.replace(/^refs\/heads\//,""),command,words:handoffWords({command},one.commit)}}class Refused extends Error{result;constructor(result){super(result.message),this.result=result}}async function squashCommit(git,plan,scratch){const squash=plan.squash;if(squash.tree!==squash.checkedTree)return refuse("checks","The commit Toolroll would land doesn't carry the files its checks ran on. Nothing landed.");const verified=await git(["rev-parse","--verify","-q",`${plan.candidate}^{tree}`]);if(verified.code!==0||verified.stdout.trim()!==squash.checkedTree)return refuse("checks","The result's files aren't the ones its checks ran on any more. Nothing landed.");const folder=mkdtempSync(join(scratch??tmpdir(),"toolroll-land-"));let written;try{const file=join(folder,"commit");writeFileSync(file,squashBody(squash.tree,plan.old,squash.time,squash.message),{encoding:"utf8",mode:384,flag:"wx"}),written=await git(["hash-object","-t","commit","-w","--",file])}finally{rmSync(folder,{recursive:!0,force:!0})}const commit=written.stdout.trim();if(written.code!==0||commit!==squash.commit)return refuse("stale","The commit Toolroll would land isn't the one you read. Nothing landed; look again.");const shown=await git(["cat-file","commit",commit]),header=shown.stdout.split(`
|
|
8
9
|
|
|
9
10
|
`)[0]??"",parents=header.split(`
|
|
10
11
|
`).filter(line=>line.startsWith("parent ")).map(line=>line.slice(7));return shown.code!==0||!header.startsWith(`tree ${squash.checkedTree}
|
|
@@ -12,4 +13,22 @@ ${message}
|
|
|
12
13
|
`).filter(line=>line.startsWith(":")),keys=[];for(const line of lines){const match=/^:(\d{6}) (\d{6}) ([0-9a-f]{40}|[0-9a-f]{64}) ([0-9a-f]{40}|[0-9a-f]{64}) [A-Z]\d*\t(.+)$/.exec(line);if(match===null)return null;keys.push(`${match[1]} ${match[2]} ${match[3]} ${match[4]} ${match[5]}`)}return keys.sort()},own=read(repo,["diff-tree","-r","--no-renames","--no-abbrev","--no-commit-id","--no-ext-diff","--no-textconv",landing.commit]),mine=own===null?null:changes(own);if(mine===null||mine.length===0)return!1;const inverse=mine.map(key=>{const[modes,path]=key.split(" "),[m1,m2,s1,s2]=modes.split(" ");return`${m2} ${m1} ${s2} ${s1} ${path}`}).sort().join(`
|
|
13
14
|
`),later=read(repo,["log","--no-show-signature","--no-merges","--ancestry-path","-n","50","--format=%x01%H","--raw","--no-renames","--no-abbrev","--no-ext-diff","--no-textconv",`${landing.commit}..${ref}`]);return later===null?!1:later.split("").slice(1).some(entry=>changes(entry.slice(entry.indexOf(`
|
|
14
15
|
`)+1))?.join(`
|
|
15
|
-
`)===inverse)}export function recognisedOnBranch(store,repo,rootId,candidate,read){if(candidate===null||!OID.test(candidate))return null;const ref=recordedDestination(store,repo)?.ref??null??(()=>{const head=read(repo,["symbolic-ref","-q","HEAD"]);return head!==null&&head.startsWith("refs/heads/")?head:null})();if(ref===null||!landableBranch(ref.slice(11)))return null;const handed=handoffsOf(store,repo,rootId).filter(one=>one.candidate===candidate&&one.ref===ref),found=[{commit:candidate,old:null},...handed.map(one=>({commit:one.commit,old:one.old}))].find(one=>read(repo,["merge-base","--is-ancestor",one.commit,ref])!==null);if(found===void 0)return null;const reverted=found.old!==null&&revertedOnBranch(repo,ref,{old:found.old,commit:found.commit},read),where=`Landed on ${ref.slice(11)} (${short(found.commit)})`;return{words:reverted?`${where} · a later commit reverted it`:where,reverted}}export function landingHistoryOf(store,repo,rootId,candidate,read){const record=landingOf(store,rootId);if(record===null||record.undone){const onBranch=recognisedOnBranch(store,repo,rootId,candidate,read);if(onBranch!==null)return{...onBranch,landed:!0,recorded:!1}}const standing2=landedStanding(store,rootId,read);return standing2===null?null:{...standing2,landed:record!==null&&!record.undone&&candidate!==null&&record.intent.candidate===candidate,recorded:!0}}export function broughtInOnBranch(store,repo,rootId,read){const landed=landedCommits(store,rootId);return handoffsOf(store,repo,rootId).some(one=>!landed.has(one.commit)&&read(repo,["merge-base","--is-ancestor",one.commit,one.ref])!==null)}
|
|
16
|
+
`)===inverse)}export function recognisedOnBranch(store,repo,rootId,candidate,read){if(candidate===null||!OID.test(candidate))return null;const ref=recordedDestination(store,repo)?.ref??null??(()=>{const head=read(repo,["symbolic-ref","-q","HEAD"]);return head!==null&&head.startsWith("refs/heads/")?head:null})();if(ref===null||!landableBranch(ref.slice(11)))return null;const handed=handoffsOf(store,repo,rootId).filter(one=>one.candidate===candidate&&one.ref===ref),found=[{commit:candidate,old:null},...handed.map(one=>({commit:one.commit,old:one.old}))].find(one=>read(repo,["merge-base","--is-ancestor",one.commit,ref])!==null);if(found===void 0)return null;const reverted=found.old!==null&&revertedOnBranch(repo,ref,{old:found.old,commit:found.commit},read),where=`Landed on ${ref.slice(11)} (${short(found.commit)})`;return{words:reverted?`${where} · a later commit reverted it`:where,reverted}}export function landingHistoryOf(store,repo,rootId,candidate,read){const record=landingOf(store,rootId);if(record===null||record.undone){const onBranch=recognisedOnBranch(store,repo,rootId,candidate,read);if(onBranch!==null)return{...onBranch,landed:!0,recorded:!1}}const standing2=landedStanding(store,rootId,read);return standing2===null?null:{...standing2,landed:record!==null&&!record.undone&&candidate!==null&&record.intent.candidate===candidate,recorded:!0}}export function broughtInOnBranch(store,repo,rootId,read){const landed=landedCommits(store,rootId);return handoffsOf(store,repo,rootId).some(one=>!landed.has(one.commit)&&read(repo,["merge-base","--is-ancestor",one.commit,one.ref])!==null)}function readPendingRow(raw){if(raw===void 0)return null;const kind=raw.authority_kind;return kind!=="person"&&kind!=="local"&&kind!=="passkey"?null:{taskId:String(raw.task_id),repo:String(raw.repo),ref:String(raw.ref),candidate:String(raw.candidate),receipt:String(raw.receipt),completion:String(raw.completion),bindingsJson:String(raw.bindings_json),requestedBy:String(raw.requested_by),requestedAt:String(raw.requested_at),accountGen:Number(raw.account_gen),authorityKind:kind,localGen:raw.local_gen==null?null:Number(raw.local_gen),lastError:raw.last_error==null?null:String(raw.last_error),lastTryAt:raw.last_try_at==null?null:String(raw.last_try_at)}}export function pendingLocalLandOf(store,taskId){return readPendingRow(store.handle.prepare("SELECT * FROM pending_local_land WHERE task_id = ?").get(taskId))}export async function queueLandWhenClean(store,taskId,input,authority,access,now,options){if(authority.kind==="passkey")return refuse("authority","Land when clean isn't available for one-time passkey requests.");if(ownerMode(store,now)!=="fast")return refuse("stale","Land when clean is only available in Fast mode.");const assignment=assignmentOf(store,taskId,now,{principal:"operator",repos:access.repos,includeUnplaced:!1},options.root);if(assignment===null)return refuse("not-found",`No task \`${taskId}\` in your projects.`);const repo=assignment.repo;if(repo===null)return refuse("destination","This task's project isn't a local Git folder Toolroll can land in.");const who=standing(store,authority,repo);if(!who.ok)return who;if(publishesThroughPullRequests(store,repo))return refuse("pull-requests",PULL_REQUESTS_INSTEAD);const project=projectOf(store,repo);if(project===null)return refuse("destination","This task's project isn't a local Git folder Toolroll can land in.");const receipt=assignment.receipt;if(assignment.state!=="complete"||assignment.completion===null||receipt===null)return refuse("not-complete","Accept it first: only accepted work lands.");const candidate=receipt.head;if(candidate===null||!OID.test(candidate)||receipt.completionKind==="research-report")return refuse("nothing","This result has no commit to land.");if(!(receipt.checks.status==="passed"||!projectCheckSet(store,project.repo)&&receipt.checks.status==="not-run"))return refuse("checks","Only work whose checks passed on its exact commit lands.");const git=gitFor(project.repo,options.git),destination=await destinationOf(store,project,git,input.into);if(!destination.ok)return destination;const branch=destination.ref.slice(11),oldRead=await git(["rev-parse","--verify","-q",`${destination.ref}^{commit}`]),old=oldRead.stdout.trim();if(oldRead.code!==0||!OID.test(old))return refuse("destination",`There's no branch \`${branch}\` in this project.`);const ancestor=await git(["merge-base","--is-ancestor",old,candidate]);if(ancestor.code===1)return refuse("moved",MOVED_MSG(branch,old));if(ancestor.code!==0)return refuse("git","Toolroll couldn't compare the commits.");const bindingsJson=JSON.stringify(checkBindingsOf(store,project.repo)),stamp=now.toISOString();let pending;try{pending=store.transact(()=>{const modeNow=ownerModeSetting(store,now);if(modeNow.mode!=="fast"||modeNow.owner===null)throw new Refused(refuse("stale","Land when clean is only available in Fast mode."));const again=standing(store,authority,repo);if(!again.ok)throw new Refused(again);const accountName=again.actor.replace(/^operator:/,"");if(modeNow.owner!==accountName)throw new Refused(refuse("authority","Only the install owner can queue Land when clean."));const account=store.accountOf(accountName);if(account===null||account.revokedAt!==null||account.role!=="approver")throw new Refused(refuse("authority","Your access changed. Sign in again."));let accountGen=account.generation,localGen=null;if(authority.kind==="local"){const local=localActNow(store,"land-task");if(local===null||local.account!==accountName)throw new Refused(refuse("authority",LOCAL_OWNER_LAPSED));accountGen=local.accountGeneration,localGen=local.localGeneration}else accountGen=authority.who.generation;return store.handle.prepare(`
|
|
17
|
+
INSERT INTO pending_local_land
|
|
18
|
+
(task_id, repo, ref, candidate, receipt, completion, bindings_json, requested_by, requested_at, account_gen, authority_kind, local_gen, last_error, last_try_at)
|
|
19
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL)
|
|
20
|
+
ON CONFLICT(task_id) DO UPDATE SET
|
|
21
|
+
repo = excluded.repo,
|
|
22
|
+
ref = excluded.ref,
|
|
23
|
+
candidate = excluded.candidate,
|
|
24
|
+
receipt = excluded.receipt,
|
|
25
|
+
completion = excluded.completion,
|
|
26
|
+
bindings_json = excluded.bindings_json,
|
|
27
|
+
requested_by = excluded.requested_by,
|
|
28
|
+
requested_at = excluded.requested_at,
|
|
29
|
+
account_gen = excluded.account_gen,
|
|
30
|
+
authority_kind = excluded.authority_kind,
|
|
31
|
+
local_gen = excluded.local_gen,
|
|
32
|
+
last_error = NULL,
|
|
33
|
+
last_try_at = NULL
|
|
34
|
+
`).run(taskId,project.repo,destination.ref,candidate,receipt.digest,assignment.completion.digest,bindingsJson,accountName,stamp,accountGen,authority.kind,localGen),store.recordAction({at:stamp,actor:again.actor,repo:project.repo,taskId:assignment.rootId,runId:receipt.runId,action:LAND_WHEN_CLEAN_QUEUED,outcome:destination.ref,source:"work",detail:`${short(candidate)} queued to land on ${branch} once clean (${authority.kind})`}),pendingLocalLandOf(store,taskId)})}catch(error){if(error instanceof Refused)return error.result;throw error}return{ok:!0,pending,message:`Queued to land on ${branch} automatically once your project folder is clean.`}}function readLocalModeRow(store){const row=store.handle.prepare("SELECT owner, generation, enabled, initialized_at, changed_at FROM local_mode WHERE id = 1").get();return row===void 0?null:{owner:String(row.owner),generation:Number(row.generation),enabled:Number(row.enabled)===1,initializedAt:String(row.initialized_at),changedAt:String(row.changed_at)}}export async function runPendingLocalLands(store,now,options){const pendingRows=store.handle.prepare("SELECT * FROM pending_local_land ORDER BY requested_at ASC").all().map(readPendingRow).filter(one=>one!==null),landed=[],waiting=[],cancelled=[],cancelRow=(row,why)=>{store.transact(()=>{store.handle.prepare("DELETE FROM pending_local_land WHERE task_id = ?").run(row.taskId),store.recordAction({at:now.toISOString(),actor:"toolroll",repo:row.repo,taskId:row.taskId,runId:null,action:LAND_WHEN_CLEAN_CANCELLED,outcome:"cancelled",source:"work",detail:why.slice(0,500)})}),cancelled.push(row.taskId)};for(const row of pendingRows){if(publishesThroughPullRequests(store,row.repo)){cancelRow(row,PULL_REQUESTS_INSTEAD);continue}const modeNow=ownerModeSetting(store,now),live=liveInstallOwner(store,now);if(modeNow.mode!=="fast"||!live.ok||live.owner!==row.requestedBy){cancelRow(row,"Fast mode is off or ownership changed since Land when clean was requested.");continue}if(row.authorityKind!=="person"&&row.authorityKind!=="local"){cancelRow(row,"Saved authority kind can't be retried automatically.");continue}const verified=verifyApproverStanding(store,row.requestedBy,row.accountGen,[row.repo]);if(!verified.ok){cancelRow(row,"Approver standing or account generation changed.");continue}if(row.authorityKind==="local"){const localMode=readLocalModeRow(store);if(row.localGen===null||!localModeOn(store)||!localBindingStands(localMode,{account:row.requestedBy,localGeneration:row.localGen})){cancelRow(row,LOCAL_OWNER_LAPSED);continue}}await locked(row.repo,()=>settleUnfinished(store,row.repo,now,options));const unresolved=unresolvedLandingForRepo(store,row.repo);if(unresolved!==null){store.handle.prepare("UPDATE pending_local_land SET last_error = ?, last_try_at = ? WHERE task_id = ?").run(unresolved.words,now.toISOString(),row.taskId),waiting.push(row.taskId);continue}const branch=row.ref.startsWith("refs/heads/")?row.ref.slice(11):row.ref,read=await readLanding(store,row.taskId,{repos:[row.repo]},now,{...options,into:branch});if(!read.ok){if(read.reason==="dirty"||read.reason==="unresolved"){store.handle.prepare("UPDATE pending_local_land SET last_error = ?, last_try_at = ? WHERE task_id = ?").run(read.message,now.toISOString(),row.taskId),waiting.push(row.taskId);continue}if(read.reason==="nothing"){store.handle.prepare("DELETE FROM pending_local_land WHERE task_id = ?").run(row.taskId),landed.push(row.taskId);continue}cancelRow(row,read.message);continue}if(!("plan"in read)){store.handle.prepare("DELETE FROM pending_local_land WHERE task_id = ?").run(row.taskId),landed.push(row.taskId);continue}const plan=read.plan;if(plan.mode==="handoff"){cancelRow(row,"In-place landing is no longer available (Fast mode is off).");continue}if(plan.candidate!==row.candidate||plan.receipt!==row.receipt||plan.completion!==row.completion||plan.ref!==row.ref||JSON.stringify(plan.bindings)!==row.bindingsJson){cancelRow(row,"The task result, destination, or project checks changed since Land when clean was requested.");continue}const done=row.authorityKind==="local"?await asLocalOwner({account:row.requestedBy,localGeneration:row.localGen,accountGeneration:row.accountGen,transport:"browser",act:"land-task",sessionHash:null,request:null},()=>land(store,row.taskId,{key:plan.key,into:branch,requireInPlace:!0},{kind:"local"},{repos:[row.repo]},now,options)):await land(store,row.taskId,{key:plan.key,into:branch,requireInPlace:!0},{kind:"person",who:verified.who},{repos:[row.repo]},now,options);done.ok?done.handoff!==null||done.mode==="handoff"?cancelRow(row,"Landing produced a manual handoff instead of completing in place."):(store.handle.prepare("DELETE FROM pending_local_land WHERE task_id = ?").run(row.taskId),landed.push(row.taskId)):done.reason==="dirty"||done.reason==="unresolved"?(store.handle.prepare("UPDATE pending_local_land SET last_error = ?, last_try_at = ? WHERE task_id = ?").run(done.message,now.toISOString(),row.taskId),waiting.push(row.taskId)):cancelRow(row,done.message)}return{landed,waiting,cancelled}}
|
package/dist/local-owner-acts.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{PLAN_AGAIN_ACTIONS,planAgain,refArchived,requeueEligibility}from"./store.js";import{asLocalOwner,LOCAL_OWNER_LAPSED,localActNow}from"./local-owner.js";import{agentChangeToolsUnchanged,approve,approverStanding,localWorkEligible,personApprovalOf}from"./scope.js";import{agentOnlyChange}from"./agent-change-check.js";import{agentChoicesFor,routeOfTask}from"./agentconfig.js";import{legOf,routeFromJson}from"./phase-routing.js";import{providerName}from"./provider-auth.js";import{requestTaskStop}from"./task-control.js";import{activeRemote}from"./remote-run.js";import{currentActor}from"./actor.js";import{plannerContractOf,plannerSourceDigest}from"./planner-source.js";import{scopeApprovedForDispatch}from"./dispatch.js";export const LOCAL_PLAN_ACTION="task plan (local owner)",LOCAL_TASK_CHANGED="This task changed. Look at it again.";export function planSourceOf(store,taskId){const contract=plannerContractOf(store,taskId);return contract.ok?plannerSourceDigest(contract.contract):null}export function requestPlanAsLocalOwner(store,taskId,source,now){try{return store.transact(()=>{const local=localActNow(store,"request-plan");if(local===null)return{ok:!1,reason:"local-owner",message:LOCAL_OWNER_LAPSED};const ref=store.lookupRef(taskId);if(ref===null||store.getTask(taskId)===null)return{ok:!1,reason:"not-found",message:"That task is unavailable in your projects."};if(!approverStanding(store,local.account,ref.repo).ok)return{ok:!1,reason:"not-found",message:"That task is unavailable in your projects."};if(refArchived(store,ref.id))return{ok:!1,reason:"archived",message:"This task is put away. Restore it first."};const eligible=localWorkEligible(store,local.account,taskId,{act:"plan"});if(!eligible.ok)return{ok:!1,reason:"refused",message:eligible.message};if(ref.planProvider!==null||ref.planModel!==null)return{ok:!1,reason:"refused",message:"This task names its own planning agent, so planning it needs your password."};if(planSourceOf(store,taskId)!==source)return{ok:!1,reason:"stale",message:LOCAL_TASK_CHANGED};const armed=store.handle.prepare("SELECT signed_by, basis FROM plan_authorization WHERE task_id = ?").get(taskId);if(armed!==void 0&&(store.handle.prepare("DELETE FROM plan_authorization WHERE task_id = ?").run(taskId),store.recordAction({at:now.toISOString(),actor:`operator:${local.account}`,repo:ref.repo,taskId,runId:null,source:"request",action:"unchanged plan pre-authorization withdrawn",outcome:"withdrawn",detail:JSON.stringify({v:1,signedBy:String(armed.signed_by),basis:String(armed.basis),why:"the local owner asked for the plan"})})),ref.plan==="requested"||ref.plan==="drafted")return{ok:!0,replayed:!0};const asked=store.requestPlan(ref.id,now);if(!asked.ok)throw new Undone({ok:!1,reason:"refused",message:`This task can't be planned now: ${asked.reason}.`});return store.recordAction({at:now.toISOString(),actor:`operator:${local.account}`,repo:ref.repo,taskId,runId:null,action:LOCAL_PLAN_ACTION,outcome:"requested",source:"request",detail:JSON.stringify({v:1,source,via:local.transport})}),{ok:!0,replayed:!1}})}catch(error){if(error instanceof Undone)return error.result;if(error instanceof Error&&error.message===LOCAL_OWNER_LAPSED)return{ok:!1,reason:"local-owner",message:LOCAL_OWNER_LAPSED};throw error}}export const LOCAL_RETRY_ACTION="task requeue (local owner)";const LOCAL_RETRY_LIMIT=3;export const LOCAL_RETRY_SPENT=`You've retried this ${LOCAL_RETRY_LIMIT} times. Send it back with a note, or sign in with your password to retry again.`;const LOCAL_RETRY_STOPPING="The last build is still stopping. Try again in a moment.",sameSeal=(a,b)=>{const one=a;return one!==null&&typeof one=="object"&&one.by===b.by&&one.at===b.at&&one.digest===b.digest};export function retryPinsOf(store,taskId){const ref=store.lookupRef(taskId),scope=store.getScope(taskId),state=store.getTask(taskId)?.state;if(ref===null||scope===null||scope.approvedAt===null||scope.approvedDigest!==scope.digest||state!=="failed"&&state!=="done")return null;const last=store.lastBuilderRun(ref.id);return last===null?null:{run:last.id,digest:scope.digest}}function localRetriesOf(store,taskId,account,seal){const rows=store.handle.prepare("SELECT run_id, detail FROM action_ledger WHERE action = ? AND task_id = ? AND actor = ? ORDER BY id").all(LOCAL_RETRY_ACTION,taskId,`operator:${account}`),runs=[];for(const row of rows){let detail;try{detail=JSON.parse(String(row.detail??""))}catch{continue}const bound=detail;bound.v===1&&sameSeal(bound.seal,seal)&&runs.push(Number(row.run_id))}return runs}export function retryAsLocalOwner(store,taskId,pins,now){try{return store.transact(()=>{const local=localActNow(store,"retry-build");if(local===null)return{ok:!1,reason:"local-owner",message:LOCAL_OWNER_LAPSED};const ref=store.lookupRef(taskId);if(ref===null||store.getTask(taskId)===null||!approverStanding(store,local.account,ref.repo).ok)return{ok:!1,reason:"not-found",message:"That task is unavailable in your projects."};const person=personApprovalOf(store,taskId);if(!person.ok||person.by!==local.account)return{ok:!1,reason:"refused",message:"Only a build of your own approval can be retried without a password. Sign in with your password to retry it."};const scope=store.getScope(taskId),seal={by:scope.approvedBy,at:scope.approvedAt,digest:scope.approvedDigest};if(scope.digest!==pins.digest)return{ok:!1,reason:"stale",message:LOCAL_TASK_CHANGED};if(!scopeApprovedForDispatch(store,ref.id,now))return{ok:!1,reason:"refused",message:"This approval no longer stands. Approve the plan again, or sign in with your password."};const eligible=localWorkEligible(store,local.account,taskId,{act:"retry"});if(!eligible.ok)return{ok:!1,reason:"refused",message:eligible.message};const latest=store.lastBuilderRun(ref.id),retried=localRetriesOf(store,taskId,local.account,seal),state=store.getTask(taskId).state;if(retried.includes(pins.run)&&latest?.id===pins.run&&(state==="queued"||state==="running"))return{ok:!0,replayed:!0,retries:retried.length};if(store.handle.prepare("SELECT 1 AS hit FROM run WHERE task_ref = ? AND finished_at IS NULL LIMIT 1").get(ref.id)!==void 0)return{ok:!1,reason:"stopping",message:LOCAL_RETRY_STOPPING};if(latest===null||latest.id!==pins.run||store.handle.prepare("SELECT 1 AS hit FROM run WHERE task_ref = ? AND id > ? LIMIT 1").get(ref.id,pins.run)!==void 0)return{ok:!1,reason:"stale",message:LOCAL_TASK_CHANGED};for(const run of store.runsFor(ref.id))if(store.stopQuiescenceFact(run.id)!==null)return{ok:!1,reason:"stopping",message:LOCAL_RETRY_STOPPING};if(store.finalResultReason(pins.run)!==null)return{ok:!1,reason:"final",message:"This result was accepted or published, so it isn't built again. Send it back with a note instead."};const eligibility=requeueEligibility(store,taskId,now);if(!eligibility.ok)return eligibility.reason==="archived"?{ok:!1,reason:"archived",message:"This task is put away. Restore it first."}:eligibility.reason==="claimed"?{ok:!1,reason:"stopping",message:LOCAL_RETRY_STOPPING}:{ok:!1,reason:"refused",message:"This task has nothing to retry."};if(eligibility.state!=="failed"&&!(eligibility.state==="done"&&eligibility.rejectedRun===pins.run))return{ok:!1,reason:"refused",message:"This task has nothing to retry."};if(retried.length>=LOCAL_RETRY_LIMIT)return{ok:!1,reason:"limit",message:LOCAL_RETRY_SPENT};if(!store.requeueTask(taskId,local.account,now).ok)throw new Undone({ok:!1,reason:"refused",message:"This task has nothing to retry."});return store.recordAction({at:now.toISOString(),actor:`operator:${local.account}`,repo:ref.repo,taskId,runId:pins.run,action:LOCAL_RETRY_ACTION,outcome:"requeued",source:"request",detail:JSON.stringify({v:1,seal,via:local.transport})}),{ok:!0,replayed:!1,retries:retried.length+1}})}catch(error){if(error instanceof Undone)return error.result;if(error instanceof Error&&error.message===LOCAL_OWNER_LAPSED)return{ok:!1,reason:"local-owner",message:LOCAL_OWNER_LAPSED};throw error}}class Undone extends Error{result;constructor(result){super(result.message),this.result=result}}export const PLAN_AGAIN_FIRST="The plan didn't pass its checks. Use Plan again first.",RESOLVE_INCIDENT_FIRST="Resolve the incident first.";export function planAgainAsLocalOwner(store,taskId,pins,now){try{return store.transact(()=>{const local=localActNow(store,"request-plan");if(local===null)return{ok:!1,reason:"local-owner",message:LOCAL_OWNER_LAPSED};const ref=store.lookupRef(taskId);if(ref===null||store.getTask(taskId)===null||!approverStanding(store,local.account,ref.repo).ok)return{ok:!1,reason:"not-found",message:"That task is unavailable in your projects."};if(refArchived(store,ref.id))return{ok:!1,reason:"archived",message:"This task is put away. Restore it first."};const eligible=localWorkEligible(store,local.account,taskId,{act:"plan"});if(!eligible.ok)return{ok:!1,reason:"refused",message:eligible.message};if(ref.planProvider!==null||ref.planModel!==null)return{ok:!1,reason:"refused",message:"This task names its own planning agent, so planning it again needs your password."};if(planSourceOf(store,taskId)!==pins.source)return{ok:!1,reason:"stale",message:LOCAL_TASK_CHANGED};const done=planAgain(store,{taskId,incident:pins.incident,by:local.account,actor:`operator:${local.account}`,action:PLAN_AGAIN_ACTIONS.local,detail:{source:pins.source,via:local.transport},now,before:()=>withdrawPlanAuthorization(store,taskId,ref.repo,local.account,now,"the local owner asked to plan again")});return done.ok?done:{ok:!1,reason:done.reason,message:done.message}})}catch(error){if(error instanceof Error&&error.message===LOCAL_OWNER_LAPSED)return{ok:!1,reason:"local-owner",message:LOCAL_OWNER_LAPSED};throw error}}function withdrawPlanAuthorization(store,taskId,repo,account,now,why){const armed=store.handle.prepare("SELECT signed_by, basis FROM plan_authorization WHERE task_id = ?").get(taskId);armed!==void 0&&(store.handle.prepare("DELETE FROM plan_authorization WHERE task_id = ?").run(taskId),store.recordAction({at:now.toISOString(),actor:`operator:${account}`,repo,taskId,runId:null,source:"request",action:"unchanged plan pre-authorization withdrawn",outcome:"withdrawn",detail:JSON.stringify({v:1,signedBy:String(armed.signed_by),basis:String(armed.basis),why})}))}export const TASK_RUNNING_NOW="This task is running right now.",AGENTS_PICK_AGAIN="The plan changed since you picked — pick again.",AGENTS_DRIFTED="Your model setup changed since you approved — approve again.",AGENTS_TOOLS_CHANGED="The project's tools changed since you approved — approve again to use them.",LOCAL_AGENT_CHANGE_ACTION="task agents (local owner)";const LOCAL_AGENT_PENDING_ACTION="task agents pending (local owner)";class Unpicked extends Error{result;constructor(result){super(result.message),this.result=result}}const ROLE_NOUN={plan:"planner",build:"builder"},agentNamed=one=>`${providerName(one.provider)} ${one.model}`,UNAVAILABLE={ok:!1,status:404,message:"That task is unavailable in your projects."};export function pendingAgentChangeOf(store,taskRef){const row=store.handle.prepare("SELECT phase, provider, model, apply_when, by, at, problem FROM pending_agent_change WHERE task_ref = ?").get(taskRef);return row===void 0?null:{phase:row.phase==="plan"?"plan":"build",provider:String(row.provider),model:String(row.model),when:row.apply_when==="restart"?"restart":"next-run",by:String(row.by),at:String(row.at),problem:row.problem==null?null:String(row.problem)}}function pickConfiguredProblem(store,taskId,ref,pick,now){const routed=routeOfTask(store,taskId,ref,now),offered=agentChoicesFor(store,ref.repo,routed?.kind==="route"?routed.route:null)[pick.phase].filter(one=>one.selectable);return offered.some(one=>one.provider===pick.provider&&one.model===pick.model)?null:offered.length===0?`No configured agent can be the ${ROLE_NOUN[pick.phase]} for this task right now.`:`${agentNamed(pick)} isn't one of the configured ${ROLE_NOUN[pick.phase]}s right now. Pick again.`}function currentAgentOf(store,taskId,phase){const route=routeFromJson(store.getScope(taskId)?.proposedRouteJson??null);return route===null?null:{provider:legOf(route,phase).provider,model:legOf(route,phase).model}}function pickProblem(store,account,taskId,ref,pick,now){if(store.getTask(taskId)?.state==="cancelled")return{ok:!1,status:409,message:"This task was cancelled."};const eligible=localWorkEligible(store,account,taskId,{act:"agents"});if(!eligible.ok)return{ok:!1,status:403,message:eligible.message};const scope=store.getScope(taskId);if(scope===null||scope.digest!==pick.sawDigest)return{ok:!1,status:409,message:AGENTS_PICK_AGAIN};const configured=pickConfiguredProblem(store,taskId,ref,pick,now);return configured===null?null:{ok:!1,status:400,message:configured}}function carryRefusalWords(result){return!result.ok&&"message"in result&&typeof result.message=="string"?result.message:!result.ok&&result.reason==="second-approver"?"This task needs a second person's yes, so its models weren't changed.":"Your approval couldn't carry over to the new model, so nothing changed."}function applyPickInside(store,local,taskId,pick,how,now){const ref=store.lookupRef(taskId);if(ref===null||store.getTask(taskId)===null||!approverStanding(store,local.account,ref.repo).ok)return UNAVAILABLE;if(refArchived(store,ref.id))return{ok:!1,status:409,message:"This task is put away. Restore it first."};if(store.hasLiveClaim(ref.id,now))return{ok:!1,status:409,message:TASK_RUNNING_NOW};const problem=pickProblem(store,local.account,taskId,ref,pick,now);if(problem!==null)return problem;const role=ROLE_NOUN[pick.phase],to={provider:pick.provider,model:pick.model},from=currentAgentOf(store,taskId,pick.phase);if(from!==null&&from.provider===to.provider&&from.model===to.model)return store.handle.prepare("DELETE FROM pending_agent_change WHERE task_ref = ?").run(ref.id),{ok:!0,outcome:"kept",words:`${agentNamed(to)} is already the ${role}.`,sealed:null};const before=store.getScope(taskId),edited=store.editTaskRoute(ref.id,{by:local.account,authenticate:()=>approverStanding(store,local.account,ref.repo).ok?{ok:!0}:{ok:!1,reason:"That task is unavailable in your projects."},override:{phase:pick.phase,provider:pick.provider,model:pick.model},expectDigest:pick.sawDigest,configured:!0},now);if(!edited.ok)return edited.reason==="changed"?{ok:!1,status:409,message:AGENTS_PICK_AGAIN}:edited.reason==="live-claim"?{ok:!1,status:409,message:TASK_RUNNING_NOW}:edited.reason==="unauthenticated"||edited.reason==="no-task"?UNAVAILABLE:{ok:!1,status:400,message:edited.detail};let outcome="changed",sealed=null,toolsMoved=!1;if(edited.replanned)outcome="replanned";else if(edited.staled){const refiled=store.getScope(taskId),ownYes=before.approvedBy===local.account&&(before.approvalBasis==="password"||before.approvalBasis==="chat"),only=refiled===null?null:agentOnlyChange({routeJson:refiled.approvedRouteJson,profile:refiled.approvedProfile,chainJson:refiled.approvedChainJson},{routeJson:refiled.proposedRouteJson,profile:refiled.profile,chainJson:refiled.proposedChainJson},provider=>store.agentsFor([provider])[0]?.billing??null);if(!ownYes)outcome="approve-again";else if(refiled===null||only===null||!only.ok||only.phase!==pick.phase)outcome="drifted";else if(before.approvedDigest===null||!agentChangeToolsUnchanged(store,taskId,before.approvedDigest))outcome="drifted",toolsMoved=!0;else{const carried=approve(store,taskId,local.account,now,refiled.digest,"");if(!carried.ok)throw new Unpicked({ok:!1,status:409,message:carryRefusalWords(carried)});outcome="resealed",sealed=refiled.digest}}const after=store.getScope(taskId);after!==null&&store.recordScopeAuthor(taskId,after.digest,local.account,now),store.handle.prepare("DELETE FROM pending_agent_change WHERE task_ref = ?").run(ref.id),store.recordAction({at:now.toISOString(),actor:`operator:${local.account}`,repo:ref.repo,taskId,runId:null,action:LOCAL_AGENT_CHANGE_ACTION,outcome,source:"request",detail:JSON.stringify({v:1,phase:pick.phase,from,to,sealed,act:"change-task-agents",how,via:local.transport})});const changed=`The ${role} is now ${agentNamed(to)}.`,words=outcome==="resealed"?`${changed} Still approved.`:outcome==="replanned"?`${changed} A new plan is coming; approve it when it's ready.`:outcome==="approve-again"?`${changed} Approve it again to build with it.`:outcome==="drifted"?`${changed} ${toolsMoved?AGENTS_TOOLS_CHANGED:AGENTS_DRIFTED}`:changed;return{ok:!0,outcome,words,sealed}}function liveAttemptOf(store,taskRef,now){const lease=store.currentLiveLease(taskRef,now);if(lease===null)return null;const row=store.handle.prepare(`SELECT r.id AS id FROM run r WHERE r.task_ref = ? AND r.lease_id = ? AND r.outcome IS NULL
|
|
1
|
+
import{PLAN_AGAIN_ACTIONS,planAgain,refArchived,requeueEligibility}from"./store.js";import{asLocalOwner,LOCAL_OWNER_LAPSED,localActNow}from"./local-owner.js";import{agentChangeToolsUnchanged,approve,approverStanding,localWorkEligible,personApprovalOf}from"./scope.js";import{agentOnlyChange}from"./agent-change-check.js";import{agentChoicesFor,routeOfTask}from"./agentconfig.js";import{legOf,routeFromJson}from"./phase-routing.js";import{providerName}from"./provider-auth.js";import{requestTaskStop}from"./task-control.js";import{clearWaitingHandoffNote,fileWaitingHandoffNote,noteBelongsTo,noteSettledBy,sweepWaitingHandoffNotes,waitingHandoffNoteOf}from"./handoff-relay.js";import{activeRemote}from"./remote-run.js";import{currentActor}from"./actor.js";import{plannerContractOf,plannerSourceDigest}from"./planner-source.js";import{scopeApprovedForDispatch}from"./dispatch.js";export const LOCAL_PLAN_ACTION="task plan (local owner)",LOCAL_TASK_CHANGED="This task changed. Look at it again.";export function planSourceOf(store,taskId){const contract=plannerContractOf(store,taskId);return contract.ok?plannerSourceDigest(contract.contract):null}export function requestPlanAsLocalOwner(store,taskId,source,now){try{return store.transact(()=>{const local=localActNow(store,"request-plan");if(local===null)return{ok:!1,reason:"local-owner",message:LOCAL_OWNER_LAPSED};const ref=store.lookupRef(taskId);if(ref===null||store.getTask(taskId)===null)return{ok:!1,reason:"not-found",message:"That task is unavailable in your projects."};if(!approverStanding(store,local.account,ref.repo).ok)return{ok:!1,reason:"not-found",message:"That task is unavailable in your projects."};if(refArchived(store,ref.id))return{ok:!1,reason:"archived",message:"This task is put away. Restore it first."};const eligible=localWorkEligible(store,local.account,taskId,{act:"plan"});if(!eligible.ok)return{ok:!1,reason:"refused",message:eligible.message};if(ref.planProvider!==null||ref.planModel!==null)return{ok:!1,reason:"refused",message:"This task names its own planning agent, so planning it needs your password."};if(planSourceOf(store,taskId)!==source)return{ok:!1,reason:"stale",message:LOCAL_TASK_CHANGED};const armed=store.handle.prepare("SELECT signed_by, basis FROM plan_authorization WHERE task_id = ?").get(taskId);if(armed!==void 0&&(store.handle.prepare("DELETE FROM plan_authorization WHERE task_id = ?").run(taskId),store.recordAction({at:now.toISOString(),actor:`operator:${local.account}`,repo:ref.repo,taskId,runId:null,source:"request",action:"unchanged plan pre-authorization withdrawn",outcome:"withdrawn",detail:JSON.stringify({v:1,signedBy:String(armed.signed_by),basis:String(armed.basis),why:"the local owner asked for the plan"})})),ref.plan==="requested"||ref.plan==="drafted")return{ok:!0,replayed:!0};const asked=store.requestPlan(ref.id,now);if(!asked.ok)throw new Undone({ok:!1,reason:"refused",message:`This task can't be planned now: ${asked.reason}.`});return store.recordAction({at:now.toISOString(),actor:`operator:${local.account}`,repo:ref.repo,taskId,runId:null,action:LOCAL_PLAN_ACTION,outcome:"requested",source:"request",detail:JSON.stringify({v:1,source,via:local.transport})}),{ok:!0,replayed:!1}})}catch(error){if(error instanceof Undone)return error.result;if(error instanceof Error&&error.message===LOCAL_OWNER_LAPSED)return{ok:!1,reason:"local-owner",message:LOCAL_OWNER_LAPSED};throw error}}export const LOCAL_RETRY_ACTION="task requeue (local owner)";const LOCAL_RETRY_LIMIT=3;export const LOCAL_RETRY_SPENT=`You've retried this ${LOCAL_RETRY_LIMIT} times. Send it back with a note, or sign in with your password to retry again.`;const LOCAL_RETRY_STOPPING="The last build is still stopping. Try again in a moment.",sameSeal=(a,b)=>{const one=a;return one!==null&&typeof one=="object"&&one.by===b.by&&one.at===b.at&&one.digest===b.digest};export function retryPinsOf(store,taskId){const ref=store.lookupRef(taskId),scope=store.getScope(taskId),state=store.getTask(taskId)?.state;if(ref===null||scope===null||scope.approvedAt===null||scope.approvedDigest!==scope.digest||state!=="failed"&&state!=="done")return null;const last=store.lastBuilderRun(ref.id);return last===null?null:{run:last.id,digest:scope.digest}}function localRetriesOf(store,taskId,account,seal){const rows=store.handle.prepare("SELECT run_id, detail FROM action_ledger WHERE action = ? AND task_id = ? AND actor = ? ORDER BY id").all(LOCAL_RETRY_ACTION,taskId,`operator:${account}`),runs=[];for(const row of rows){let detail;try{detail=JSON.parse(String(row.detail??""))}catch{continue}const bound=detail;bound.v===1&&sameSeal(bound.seal,seal)&&runs.push(Number(row.run_id))}return runs}export function retryAsLocalOwner(store,taskId,pins,now){try{return store.transact(()=>{const local=localActNow(store,"retry-build");if(local===null)return{ok:!1,reason:"local-owner",message:LOCAL_OWNER_LAPSED};const ref=store.lookupRef(taskId);if(ref===null||store.getTask(taskId)===null||!approverStanding(store,local.account,ref.repo).ok)return{ok:!1,reason:"not-found",message:"That task is unavailable in your projects."};const person=personApprovalOf(store,taskId);if(!person.ok||person.by!==local.account)return{ok:!1,reason:"refused",message:"Only a build of your own approval can be retried without a password. Sign in with your password to retry it."};const scope=store.getScope(taskId),seal={by:scope.approvedBy,at:scope.approvedAt,digest:scope.approvedDigest};if(scope.digest!==pins.digest)return{ok:!1,reason:"stale",message:LOCAL_TASK_CHANGED};if(!scopeApprovedForDispatch(store,ref.id,now))return{ok:!1,reason:"refused",message:"This approval no longer stands. Approve the plan again, or sign in with your password."};const eligible=localWorkEligible(store,local.account,taskId,{act:"retry"});if(!eligible.ok)return{ok:!1,reason:"refused",message:eligible.message};const latest=store.lastBuilderRun(ref.id),retried=localRetriesOf(store,taskId,local.account,seal),state=store.getTask(taskId).state;if(retried.includes(pins.run)&&latest?.id===pins.run&&(state==="queued"||state==="running"))return{ok:!0,replayed:!0,retries:retried.length};if(store.handle.prepare("SELECT 1 AS hit FROM run WHERE task_ref = ? AND finished_at IS NULL LIMIT 1").get(ref.id)!==void 0)return{ok:!1,reason:"stopping",message:LOCAL_RETRY_STOPPING};if(latest===null||latest.id!==pins.run||store.handle.prepare("SELECT 1 AS hit FROM run WHERE task_ref = ? AND id > ? LIMIT 1").get(ref.id,pins.run)!==void 0)return{ok:!1,reason:"stale",message:LOCAL_TASK_CHANGED};for(const run of store.runsFor(ref.id))if(store.stopQuiescenceFact(run.id)!==null)return{ok:!1,reason:"stopping",message:LOCAL_RETRY_STOPPING};if(store.finalResultReason(pins.run)!==null)return{ok:!1,reason:"final",message:"This result was accepted or published, so it isn't built again. Send it back with a note instead."};const eligibility=requeueEligibility(store,taskId,now);if(!eligibility.ok)return eligibility.reason==="archived"?{ok:!1,reason:"archived",message:"This task is put away. Restore it first."}:eligibility.reason==="claimed"?{ok:!1,reason:"stopping",message:LOCAL_RETRY_STOPPING}:{ok:!1,reason:"refused",message:"This task has nothing to retry."};if(eligibility.state!=="failed"&&!(eligibility.state==="done"&&eligibility.rejectedRun===pins.run))return{ok:!1,reason:"refused",message:"This task has nothing to retry."};if(retried.length>=LOCAL_RETRY_LIMIT)return{ok:!1,reason:"limit",message:LOCAL_RETRY_SPENT};if(!store.requeueTask(taskId,local.account,now).ok)throw new Undone({ok:!1,reason:"refused",message:"This task has nothing to retry."});return store.recordAction({at:now.toISOString(),actor:`operator:${local.account}`,repo:ref.repo,taskId,runId:pins.run,action:LOCAL_RETRY_ACTION,outcome:"requeued",source:"request",detail:JSON.stringify({v:1,seal,via:local.transport})}),{ok:!0,replayed:!1,retries:retried.length+1}})}catch(error){if(error instanceof Undone)return error.result;if(error instanceof Error&&error.message===LOCAL_OWNER_LAPSED)return{ok:!1,reason:"local-owner",message:LOCAL_OWNER_LAPSED};throw error}}class Undone extends Error{result;constructor(result){super(result.message),this.result=result}}export const PLAN_AGAIN_FIRST="The plan didn't pass its checks. Use Plan again first.",RESOLVE_INCIDENT_FIRST="Resolve the incident first.";export function planAgainAsLocalOwner(store,taskId,pins,now){try{return store.transact(()=>{const local=localActNow(store,"request-plan");if(local===null)return{ok:!1,reason:"local-owner",message:LOCAL_OWNER_LAPSED};const ref=store.lookupRef(taskId);if(ref===null||store.getTask(taskId)===null||!approverStanding(store,local.account,ref.repo).ok)return{ok:!1,reason:"not-found",message:"That task is unavailable in your projects."};if(refArchived(store,ref.id))return{ok:!1,reason:"archived",message:"This task is put away. Restore it first."};const eligible=localWorkEligible(store,local.account,taskId,{act:"plan"});if(!eligible.ok)return{ok:!1,reason:"refused",message:eligible.message};if(ref.planProvider!==null||ref.planModel!==null)return{ok:!1,reason:"refused",message:"This task names its own planning agent, so planning it again needs your password."};if(planSourceOf(store,taskId)!==pins.source)return{ok:!1,reason:"stale",message:LOCAL_TASK_CHANGED};const done=planAgain(store,{taskId,incident:pins.incident,by:local.account,actor:`operator:${local.account}`,action:PLAN_AGAIN_ACTIONS.local,detail:{source:pins.source,via:local.transport},now,before:()=>withdrawPlanAuthorization(store,taskId,ref.repo,local.account,now,"the local owner asked to plan again")});return done.ok?done:{ok:!1,reason:done.reason,message:done.message}})}catch(error){if(error instanceof Error&&error.message===LOCAL_OWNER_LAPSED)return{ok:!1,reason:"local-owner",message:LOCAL_OWNER_LAPSED};throw error}}function withdrawPlanAuthorization(store,taskId,repo,account,now,why){const armed=store.handle.prepare("SELECT signed_by, basis FROM plan_authorization WHERE task_id = ?").get(taskId);armed!==void 0&&(store.handle.prepare("DELETE FROM plan_authorization WHERE task_id = ?").run(taskId),store.recordAction({at:now.toISOString(),actor:`operator:${account}`,repo,taskId,runId:null,source:"request",action:"unchanged plan pre-authorization withdrawn",outcome:"withdrawn",detail:JSON.stringify({v:1,signedBy:String(armed.signed_by),basis:String(armed.basis),why})}))}export const TASK_RUNNING_NOW="This task is running right now.",AGENTS_PICK_AGAIN="The plan changed since you picked — pick again.",AGENTS_DRIFTED="Your model setup changed since you approved — approve again.",AGENTS_TOOLS_CHANGED="The project's tools changed since you approved — approve again to use them.",LOCAL_AGENT_CHANGE_ACTION="task agents (local owner)";const LOCAL_AGENT_PENDING_ACTION="task agents pending (local owner)";class Unpicked extends Error{result;constructor(result){super(result.message),this.result=result}}const ROLE_NOUN={plan:"planner",build:"builder"},agentNamed=one=>`${providerName(one.provider)} ${one.model}`,UNAVAILABLE={ok:!1,status:404,message:"That task is unavailable in your projects."};export function pendingAgentChangeOf(store,taskRef){const row=store.handle.prepare("SELECT phase, provider, model, apply_when, by, at, problem FROM pending_agent_change WHERE task_ref = ?").get(taskRef);return row===void 0?null:{phase:row.phase==="plan"?"plan":"build",provider:String(row.provider),model:String(row.model),when:row.apply_when==="restart"?"restart":"next-run",by:String(row.by),at:String(row.at),problem:row.problem==null?null:String(row.problem)}}function pickConfiguredProblem(store,taskId,ref,pick,now){const routed=routeOfTask(store,taskId,ref,now),offered=agentChoicesFor(store,ref.repo,routed?.kind==="route"?routed.route:null)[pick.phase].filter(one=>one.selectable);return offered.some(one=>one.provider===pick.provider&&one.model===pick.model)?null:offered.length===0?`No configured agent can be the ${ROLE_NOUN[pick.phase]} for this task right now.`:`${agentNamed(pick)} isn't one of the configured ${ROLE_NOUN[pick.phase]}s right now. Pick again.`}function currentAgentOf(store,taskId,phase){const route=routeFromJson(store.getScope(taskId)?.proposedRouteJson??null);return route===null?null:{provider:legOf(route,phase).provider,model:legOf(route,phase).model}}function pickProblem(store,account,taskId,ref,pick,now){if(store.getTask(taskId)?.state==="cancelled")return{ok:!1,status:409,message:"This task was cancelled."};const eligible=localWorkEligible(store,account,taskId,{act:"agents"});if(!eligible.ok)return{ok:!1,status:403,message:eligible.message};const scope=store.getScope(taskId);if(scope===null||scope.digest!==pick.sawDigest)return{ok:!1,status:409,message:AGENTS_PICK_AGAIN};const configured=pickConfiguredProblem(store,taskId,ref,pick,now);return configured===null?null:{ok:!1,status:400,message:configured}}function carryRefusalWords(result){return!result.ok&&"message"in result&&typeof result.message=="string"?result.message:!result.ok&&result.reason==="second-approver"?"This task needs a second person's yes, so its models weren't changed.":"Your approval couldn't carry over to the new model, so nothing changed."}function applyPickInside(store,local,taskId,pick,how,now){const ref=store.lookupRef(taskId);if(ref===null||store.getTask(taskId)===null||!approverStanding(store,local.account,ref.repo).ok)return UNAVAILABLE;if(refArchived(store,ref.id))return{ok:!1,status:409,message:"This task is put away. Restore it first."};if(store.hasLiveClaim(ref.id,now))return{ok:!1,status:409,message:TASK_RUNNING_NOW};const problem=pickProblem(store,local.account,taskId,ref,pick,now);if(problem!==null)return problem;const role=ROLE_NOUN[pick.phase],to={provider:pick.provider,model:pick.model},from=currentAgentOf(store,taskId,pick.phase);if(from!==null&&from.provider===to.provider&&from.model===to.model)return store.handle.prepare("DELETE FROM pending_agent_change WHERE task_ref = ?").run(ref.id),{ok:!0,outcome:"kept",words:`${agentNamed(to)} is already the ${role}.`,sealed:null};const before=store.getScope(taskId),edited=store.editTaskRoute(ref.id,{by:local.account,authenticate:()=>approverStanding(store,local.account,ref.repo).ok?{ok:!0}:{ok:!1,reason:"That task is unavailable in your projects."},override:{phase:pick.phase,provider:pick.provider,model:pick.model},expectDigest:pick.sawDigest,configured:!0},now);if(!edited.ok)return edited.reason==="changed"?{ok:!1,status:409,message:AGENTS_PICK_AGAIN}:edited.reason==="live-claim"?{ok:!1,status:409,message:TASK_RUNNING_NOW}:edited.reason==="unauthenticated"||edited.reason==="no-task"?UNAVAILABLE:{ok:!1,status:400,message:edited.detail};let outcome="changed",sealed=null,toolsMoved=!1;if(edited.replanned)outcome="replanned";else if(edited.staled){const refiled=store.getScope(taskId),ownYes=before.approvedBy===local.account&&(before.approvalBasis==="password"||before.approvalBasis==="chat"),only=refiled===null?null:agentOnlyChange({routeJson:refiled.approvedRouteJson,profile:refiled.approvedProfile,chainJson:refiled.approvedChainJson},{routeJson:refiled.proposedRouteJson,profile:refiled.profile,chainJson:refiled.proposedChainJson},provider=>store.agentsFor([provider])[0]?.billing??null);if(!ownYes)outcome="approve-again";else if(refiled===null||only===null||!only.ok||only.phase!==pick.phase)outcome="drifted";else if(before.approvedDigest===null||!agentChangeToolsUnchanged(store,taskId,before.approvedDigest))outcome="drifted",toolsMoved=!0;else{const carried=approve(store,taskId,local.account,now,refiled.digest,"");if(!carried.ok)throw new Unpicked({ok:!1,status:409,message:carryRefusalWords(carried)});outcome="resealed",sealed=refiled.digest}}const after=store.getScope(taskId);after!==null&&store.recordScopeAuthor(taskId,after.digest,local.account,now),store.handle.prepare("DELETE FROM pending_agent_change WHERE task_ref = ?").run(ref.id),store.recordAction({at:now.toISOString(),actor:`operator:${local.account}`,repo:ref.repo,taskId,runId:null,action:LOCAL_AGENT_CHANGE_ACTION,outcome,source:"request",detail:JSON.stringify({v:1,phase:pick.phase,from,to,sealed,act:"change-task-agents",how,via:local.transport})});const changed=`The ${role} is now ${agentNamed(to)}.`,words=outcome==="resealed"?`${changed} Still approved.`:outcome==="replanned"?`${changed} A new plan is coming; approve it when it's ready.`:outcome==="approve-again"?`${changed} Approve it again to build with it.`:outcome==="drifted"?`${changed} ${toolsMoved?AGENTS_TOOLS_CHANGED:AGENTS_DRIFTED}`:changed;return{ok:!0,outcome,words,sealed}}function liveAttemptOf(store,taskRef,now){const lease=store.currentLiveLease(taskRef,now);if(lease===null)return null;const row=store.handle.prepare(`SELECT r.id AS id FROM run r WHERE r.task_ref = ? AND r.lease_id = ? AND r.outcome IS NULL
|
|
2
2
|
AND (r.parent_run IS NULL OR NOT EXISTS (SELECT 1 FROM run p WHERE p.id = r.parent_run AND p.lease_id = r.lease_id)) ORDER BY r.id LIMIT 1`).get(taskRef,lease);return row===void 0?null:Number(row.id)}export function localOwnerChangeAgents(store,taskId,pick,when,now){let signal=null;try{const result=store.transact(()=>{const local=localActNow(store,"change-task-agents");if(local===null)return{ok:!1,status:403,message:LOCAL_OWNER_LAPSED};const ref=store.lookupRef(taskId);if(ref===null||store.getTask(taskId)===null||!approverStanding(store,local.account,ref.repo).ok)return UNAVAILABLE;if(refArchived(store,ref.id))return{ok:!1,status:409,message:"This task is put away. Restore it first."};if(!store.hasLiveClaim(ref.id,now))return applyPickInside(store,local,taskId,pick,"now",now);if(when==="now")return{ok:!1,status:409,message:TASK_RUNNING_NOW};const problem=pickProblem(store,local.account,taskId,ref,pick,now);if(problem!==null)return problem;const run=liveAttemptOf(store,ref.id,now);if(when==="restart"){if(run===null)return{ok:!1,status:409,message:TASK_RUNNING_NOW};const asked=requestTaskStop(store,{taskId,runId:run,by:local.account,via:local.transport==="terminal"?"cli":"web",deferSignal:one=>{signal=one}},now);if(!asked.ok)throw new Unpicked({ok:!1,status:409,message:`${TASK_RUNNING_NOW} It can't be stopped: ${asked.detail}.`})}return store.handle.prepare(`INSERT INTO pending_agent_change (task_ref, phase, provider, model, apply_when, saw_digest, run, by, local_generation, account_generation, transport, at, problem)
|
|
3
3
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)
|
|
4
4
|
ON CONFLICT (task_ref) DO UPDATE SET phase = excluded.phase, provider = excluded.provider, model = excluded.model, apply_when = excluded.apply_when,
|
|
5
5
|
saw_digest = excluded.saw_digest, run = excluded.run, by = excluded.by, local_generation = excluded.local_generation,
|
|
6
|
-
account_generation = excluded.account_generation, transport = excluded.transport, at = excluded.at, problem = NULL`).run(ref.id,pick.phase,pick.provider,pick.model,when,pick.sawDigest,run,local.account,local.localGeneration,local.accountGeneration,local.transport,now.toISOString()),store.recordAction({at:now.toISOString(),actor:`operator:${local.account}`,repo:ref.repo,taskId,runId:run,action:LOCAL_AGENT_PENDING_ACTION,outcome:when,source:"request",detail:JSON.stringify({v:1,phase:pick.phase,to:{provider:pick.provider,model:pick.model},sawDigest:pick.sawDigest,via:local.transport})}),{ok:!0,outcome:"pending",words:when==="restart"?`Stopping the run; it starts again on ${agentNamed(pick)}.`:`Switches to ${agentNamed(pick)} when this run ends.`,sealed:null}});return result.ok&&signal?.(),result}catch(error){if(error instanceof Unpicked)return error.result;if(error instanceof Error&&error.message===LOCAL_OWNER_LAPSED)return{ok:!1,status:403,message:LOCAL_OWNER_LAPSED};throw error}}export function applyPendingAgentChanges(store,now){if(activeRemote()!==null||currentActor()!==null)return 0;const rows=store.handle.prepare("SELECT p.*, r.external_id AS task_id FROM pending_agent_change p JOIN task_ref r ON r.id = p.task_ref WHERE p.problem IS NULL ORDER BY p.at").all();let applied=0;for(const row of rows){const taskRef=Number(row.task_ref),taskId=String(row.task_id);if(store.getTask(taskId)?.state==="cancelled"||refArchived(store,taskRef)){store.handle.prepare("DELETE FROM pending_agent_change WHERE task_ref = ?").run(taskRef);continue}if(store.hasLiveClaim(taskRef,now))continue;const run=row.run==null?null:Number(row.run),when=row.apply_when==="restart"?"restart":"next-run";if(when==="restart"&&run!==null){const stop=store.stopOf(run);if(stop!==null&&stop.resumedAt===null&&(stop.settledAt===null||store.getRun(run)?.outcome==null))continue}const pending={taskRef,taskId,when,run,at:String(row.at),pick:{phase:row.phase==="plan"?"plan":"build",provider:String(row.provider),model:String(row.model),sawDigest:String(row.saw_digest)},principal:{account:String(row.by),localGeneration:Number(row.local_generation),accountGeneration:Number(row.account_generation),transport:row.transport==="terminal"?"terminal":"browser",act:"change-task-agents",sessionHash:null,request:null}};let done;try{done=asLocalOwner(pending.principal,()=>applyPendingAsOwner(store,pending,now))}catch(error){done={ok:!1,status:500,message:`This change couldn't be applied: ${error instanceof Error?error.message:String(error)}`}}if(done==="wait")continue;if(done.ok){applied
|
|
6
|
+
account_generation = excluded.account_generation, transport = excluded.transport, at = excluded.at, problem = NULL`).run(ref.id,pick.phase,pick.provider,pick.model,when,pick.sawDigest,run,local.account,local.localGeneration,local.accountGeneration,local.transport,now.toISOString()),store.recordAction({at:now.toISOString(),actor:`operator:${local.account}`,repo:ref.repo,taskId,runId:run,action:LOCAL_AGENT_PENDING_ACTION,outcome:when,source:"request",detail:JSON.stringify({v:1,phase:pick.phase,to:{provider:pick.provider,model:pick.model},sawDigest:pick.sawDigest,via:local.transport})}),{ok:!0,outcome:"pending",words:when==="restart"?`Stopping the run; it starts again on ${agentNamed(pick)}.`:`Switches to ${agentNamed(pick)} when this run ends.`,sealed:null}});return result.ok&&signal?.(),result}catch(error){if(error instanceof Unpicked)return error.result;if(error instanceof Error&&error.message===LOCAL_OWNER_LAPSED)return{ok:!1,status:403,message:LOCAL_OWNER_LAPSED};throw error}}export function applyPendingAgentChanges(store,now){if(activeRemote()!==null||currentActor()!==null)return 0;const rows=store.handle.prepare("SELECT p.*, r.external_id AS task_id FROM pending_agent_change p JOIN task_ref r ON r.id = p.task_ref WHERE p.problem IS NULL ORDER BY p.at").all();let applied=0;for(const row of rows){const taskRef=Number(row.task_ref),taskId=String(row.task_id);if(store.getTask(taskId)?.state==="cancelled"||refArchived(store,taskRef)){store.handle.prepare("DELETE FROM pending_agent_change WHERE task_ref = ?").run(taskRef);continue}if(store.hasLiveClaim(taskRef,now))continue;const run=row.run==null?null:Number(row.run),when=row.apply_when==="restart"?"restart":"next-run";if(when==="restart"&&run!==null){const stop=store.stopOf(run);if(stop!==null&&stop.resumedAt===null&&(stop.settledAt===null||store.getRun(run)?.outcome==null))continue}const pending={taskRef,taskId,when,run,at:String(row.at),pick:{phase:row.phase==="plan"?"plan":"build",provider:String(row.provider),model:String(row.model),sawDigest:String(row.saw_digest)},principal:{account:String(row.by),localGeneration:Number(row.local_generation),accountGeneration:Number(row.account_generation),transport:row.transport==="terminal"?"terminal":"browser",act:"change-task-agents",sessionHash:null,request:null}},held=waitingHandoffNoteOf(store,taskId),note=held!==null&¬eBelongsTo(held,{...pending.pick,at:pending.at})?held:null;let done;try{done=asLocalOwner(pending.principal,()=>applyPendingAsOwner(store,pending,note,now))}catch(error){done={ok:!1,status:500,message:`This change couldn't be applied: ${error instanceof Error?error.message:String(error)}`}}if(done==="wait")continue;if(done.ok){applied++,held!==null&¬eSettledBy(held,pending.at)&&clearWaitingHandoffNote(store,taskId,held);continue}const words=done.message.slice(0,500);store.transact(()=>store.handle.prepare("UPDATE pending_agent_change SET problem = ? WHERE task_ref = ? AND at = ? AND problem IS NULL").run(words,taskRef,pending.at))}return sweepWaitingHandoffNotes(store,now),applied}function applyPendingAsOwner(store,pending,note,now){try{return store.transact(()=>{const local=localActNow(store,"change-task-agents");if(local===null||local.account!==pending.principal.account)throw new Unpicked({ok:!1,status:403,message:LOCAL_OWNER_LAPSED});if(store.handle.prepare("SELECT 1 AS hit FROM pending_agent_change WHERE task_ref = ? AND at = ? AND problem IS NULL").get(pending.taskRef,pending.at)===void 0||store.hasLiveClaim(pending.taskRef,now))return"wait";const stop=pending.when==="restart"&&pending.run!==null?store.stopOf(pending.run):null;if(stop!==null&&stop.resumedAt===null&&(stop.settledAt===null||store.getRun(pending.run)?.outcome==null))return"wait";const done=applyPickInside(store,local,pending.taskId,pending.pick,pending.when,now);if(!done.ok)throw new Unpicked(done);if(note!==null&&fileWaitingHandoffNote(store,pending.taskId,note,now),stop!==null&&stop.resumedAt===null){const resumed=store.resumeRunStop({runId:pending.run,taskRef:pending.taskRef,by:local.account,via:local.transport==="terminal"?"cli":"web"},now);if(!resumed.ok)throw new Unpicked({ok:!1,status:409,message:`The stopped run can't start again yet: ${resumed.detail}.`})}return done})}catch(error){if(error instanceof Unpicked)return error.result;if(error instanceof Error&&error.message===LOCAL_OWNER_LAPSED)return{ok:!1,status:403,message:LOCAL_OWNER_LAPSED};throw error}}
|
package/dist/local-owner.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AsyncLocalStorage}from"node:async_hooks";import{currentActor}from"./actor.js";import{activeRemote}from"./remote-run.js";export function authorityOf(value){return value==="full"||value==="local-owner"?value:null}export const LOCAL_OWNER_ACTS=Object.freeze(["file-task","lead-send","approve-plan","build-now","answer-question","stop-run","pause-run","resume-run","complete-task","land-task","request-revision","archive-task","add-project","choose-default-agent","mark-seen","watch-agent","read","routing-turn-off","dismiss-suggestion","trial-stop","code-map-switch","skill-library","memory-review","request-plan","retry-build","run-checks","view-preference","take-over","start-thread","reply-thread","stop-thread","end-thread","check-agents","agent-sign-in","agent-install","change-models","task-sizing-switch","flexible-switch","ship-thread","cancel-ship","save-thread","flexible-sign-in-save","flexible-sign-in-check","flexible-sign-in-clear","project-flexible","project-network","project-live-view","change-task-agents","trigger-pause","trigger-resume","trigger-run","direct-chat-start","direct-chat-send","direct-chat-stop","direct-chat-manage","direct-chat-ship","manage-directions","shared-browser"]),LOCAL_PASSWORD_ACTS=new Set(["flexible-switch","flexible-sign-in-save","flexible-sign-in-check","project-flexible","project-network","project-live-view"]);const ACT_SET=new Set(LOCAL_OWNER_ACTS);export function localOwnerAct(value){return typeof value=="string"&&ACT_SET.has(value)}export const LOCAL_OWNER_PROPOSALS=Object.freeze({task:"allow",answer:"allow",steer:"allow",cancel:"allow",hold:"allow",unhold:"allow",action:"allow",task_action:"allow",next:"refuse",reserve:"refuse",scope:"refuse",repair:"refuse",agents:"refuse",review:"
|
|
1
|
+
import{AsyncLocalStorage}from"node:async_hooks";import{currentActor}from"./actor.js";import{activeRemote}from"./remote-run.js";export function authorityOf(value){return value==="full"||value==="local-owner"?value:null}export const LOCAL_OWNER_ACTS=Object.freeze(["file-task","lead-send","approve-plan","build-now","answer-question","stop-run","pause-run","resume-run","complete-task","land-task","request-revision","archive-task","add-project","choose-default-agent","mark-seen","watch-agent","read","routing-turn-off","dismiss-suggestion","trial-stop","code-map-switch","skill-library","memory-review","request-plan","retry-build","run-checks","view-preference","take-over","start-thread","reply-thread","stop-thread","end-thread","check-agents","agent-sign-in","agent-install","change-models","task-sizing-switch","flexible-switch","ship-thread","cancel-ship","save-thread","flexible-sign-in-save","flexible-sign-in-check","flexible-sign-in-clear","project-flexible","project-network","project-live-view","change-task-agents","trigger-pause","trigger-resume","trigger-run","direct-chat-start","direct-chat-send","direct-chat-stop","direct-chat-manage","direct-chat-ship","manage-directions","shared-browser","mode-sign","check-agent","pr-merge","project-check-access","project-sandbox","start-release"]),LOCAL_PASSWORD_ACTS=new Set(["flexible-switch","flexible-sign-in-save","flexible-sign-in-check","project-flexible","project-network","project-live-view"]),FAST_ONLY_LOCAL_ACTS=new Set(["mode-sign","check-agent","pr-merge","project-check-access","project-sandbox","start-release"]);const ACT_SET=new Set(LOCAL_OWNER_ACTS);export function localOwnerAct(value){return typeof value=="string"&&ACT_SET.has(value)}export const LOCAL_OWNER_PROPOSALS=Object.freeze({task:"allow",answer:"allow",steer:"allow",cancel:"allow",hold:"allow",unhold:"allow",action:"allow",task_action:"allow",next:"refuse",reserve:"refuse",scope:"refuse",repair:"refuse",agents:"refuse",review:"allow",control:"refuse"}),OPERATION_KINDS=new Set(["action","task_action"]);export function localOwnerMayConfirm(kind,act=null){return typeof kind!="string"||!Object.prototype.hasOwnProperty.call(LOCAL_OWNER_PROPOSALS,kind)||LOCAL_OWNER_PROPOSALS[kind]!=="allow"?!1:OPERATION_KINDS.has(kind)?localOwnerAct(act):!0}export function localBindingStands(mode,binding){return mode!==null&&mode.enabled&&binding.localGeneration!==null&&mode.generation===binding.localGeneration&&mode.owner===binding.account}const localOwnerScope=new AsyncLocalStorage;export function currentLocalOwner(){return localOwnerScope.getStore()??null}export function localOwnerInFlight(principal){return principal.request===null||!principal.request.ended}export function asLocalOwner(principal,body){return localOwnerScope.run(Object.freeze({...principal}),body)}export function withLocalAct(act,body){const current=currentLocalOwner();return current===null?body():localOwnerScope.run(Object.freeze({...current,act}),body)}const terminalRequest=new AsyncLocalStorage;export function runAsLocalOwner(fn){return terminalRequest.run(!0,fn)}export function localOwnerRequested(){return terminalRequest.getStore()===!0}export const PROPOSAL_LOCAL_ACTS=Object.freeze({task:"file-task",answer:"answer-question",steer:"lead-send",cancel:"stop-run",hold:"pause-run",unhold:"resume-run",action:null,task_action:null,next:null,reserve:null,scope:null,repair:null,agents:null,review:"request-revision",control:null}),CHAT_ACTION_LOCAL_ACTS=Object.freeze({plugin_install:"skill-library",skill_import:null,skill_enable:null,skill_disable:null,skill_restore:null,skill_test:null,knowledge_instructions:null,knowledge_save:null,knowledge_remove:null,knowledge_restore:null,tool_add:null,tool_remove:null,flow_create:null,flow_starter:null,sweep_file:null,sweep_cancel_rest:null,flow_edit:null,flow_card_add:null,flow_card_move:null,flow_card_approve:null,flow_card_send_back:null,flow_card_choose:null,flow_card_cancel:null,flow_card_comment:null,flow_card_assign:null,flow_card_watch:null,flow_script_save:null,flow_trigger_add:null,flow_trigger_pause:null,flow_trigger_resume:null,flow_trigger_remove:null,flow_browser:null,flow_browser_off:null,subagent_create:null,subagent_soul:null,subagent_state:null,subagent_note:null,subagent_ask:null,subagent_answer:null,subagent_tools:null,subagent_memory:null,subagent_routine:null,subagent_undo:null,kit_setup:null,decision_record:null,decision_retire:null,lead_about_you:null,mode_revoke:null,flow_unattended_off:null,flow_archive:null,provider_resume:null,worker_note:null,lead_identity:null,task_archive:null,task_restore:null,incident_resolve:null,memory_decide:null,finding_send:null,finding_resend:null,task_reopen:null,revision_accept:null,revision_reject:null,flow_unattended:null,suggestion_not_now:"dismiss-suggestion",trial_stop:"trial-stop",code_map_switch:"code-map-switch",code_map_holdout_end:null,scope_approve:"approve-plan",result_accept:"complete-task",task_cancel:"stop-run",task_resume:"resume-run",task_start:"build-now",direct_chat_start:"direct-chat-start",direct_chat_reply:"direct-chat-send",direct_chat_promote:"file-task",direct_chat_ship:"direct-chat-ship",task_handoff:"change-task-agents",workflow_orchestrate:"file-task",release_start:"start-release"}),CHAT_TASK_ACTION_LOCAL_ACTS=Object.freeze({stop:"stop-run",resume:"resume-run",retry:null,plan:null,wait_for:null,stop_waiting:null,run_checks:null,run_full_checks:null,add_tests:null});export function proposalLocalAct(kind,operation){if(typeof kind!="string"||!Object.prototype.hasOwnProperty.call(PROPOSAL_LOCAL_ACTS,kind))return null;const own=table=>typeof operation=="string"&&Object.prototype.hasOwnProperty.call(table,operation)?table[operation]??null:null,act=kind==="action"?own(CHAT_ACTION_LOCAL_ACTS):kind==="task_action"?own(CHAT_TASK_ACTION_LOCAL_ACTS):PROPOSAL_LOCAL_ACTS[kind];return act!==null&&localOwnerMayConfirm(kind,act)?act:null}export function localOwnerRefusal(passwordSet,returnTo){return passwordSet?{message:"Sign in with your password to do this.",action:"Sign in with your password",href:`/login?return=${encodeURIComponent(returnTo)}`}:{message:"Set a password to do this.",action:"Set a password",href:returnTo==="/"?"/password/set":`/password/set?next=${encodeURIComponent(returnTo)}`}}export function localModeOn(store){const row=store.handle.prepare("SELECT enabled FROM local_mode WHERE id = 1").get();return row!==void 0&&Number(row.enabled)===1}export function localOwnerStandsNow(store,principal){const mode=store.handle.prepare("SELECT owner, generation, enabled FROM local_mode WHERE id = 1").get();if(mode===void 0||Number(mode.enabled)!==1||Number(mode.generation)!==principal.localGeneration||String(mode.owner)!==principal.account)return!1;const account=store.accountOf(principal.account);return account===null||account.revokedAt!==null||account.role!=="approver"||account.generation!==principal.accountGeneration?!1:principal.sessionHash===null||store.webSession(principal.sessionHash)!==null}export const LOCAL_OWNER_LAPSED="This local sign-in no longer stands. Run `toolroll` to sign in again.",LOCAL_MODE_CONFINES="Turn off local mode first.",LOCAL_OWNER_ELSEWHERE="This sign-in works only on the computer running Toolroll. To use Toolroll from here, set a password on that computer (run `toolroll password set`) and sign in with it.";export function localActNow(store,act){if(activeRemote()!==null||currentActor()?.lead===!0)return null;const local=currentLocalOwner();return local===null||local.act!==act||!localOwnerInFlight(local)||!localOwnerStandsNow(store,local)?null:local}
|
package/dist/machine-identity.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{execFileSync}from"node:child_process";import{createHash}from"node:crypto";import{existsSync,readFileSync}from"node:fs";import{hostname}from"node:os";const defaultRun=(file,args)=>execFileSync(file,args,{encoding:"utf8",timeout:3e3,stdio:["ignore","pipe","ignore"]});export function hashMachineId(source,raw){return createHash("sha256").update(`toolroll machine identity v1\0${source}\0${raw.trim().toLowerCase()}`).digest("hex").slice(0,32)}export function readMachineIdentity(readers={}){const platform=readers.platform??process.platform,readFile=readers.readFile??(path=>readFileSync(path,"utf8")),exists=readers.exists??existsSync,run=readers.run??defaultRun;try{if(platform==="darwin"){const raw=/"IOPlatformUUID"\s*=\s*"([0-9A-Fa-f-]{36})"/.exec(run("/usr/sbin/ioreg",["-rd1","-c","IOPlatformExpertDevice"]))?.[1];return raw===void 0||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(raw)?{ok:!1,reason:"malformed",detail:"ioreg named no IOPlatformUUID"}:{ok:!0,id:hashMachineId("darwin-platform-uuid",raw),source:"darwin-platform-uuid"}}if(platform==="linux"){if(exists("/.dockerenv")||exists("/run/.containerenv"))return{ok:!1,reason:"container",detail:"a container's machine-id can be shared with other containers"};let raw=null;for(const path of["/etc/machine-id","/var/lib/dbus/machine-id"])try{raw=readFile(path).trim();break}catch{}return raw===null?{ok:!1,reason:"unreadable",detail:"no machine-id could be read"}:!/^[0-9a-f]{32}$/i.test(raw)||/^0+$/.test(raw)?{ok:!1,reason:"malformed",detail:"the machine-id was not 32 hex digits"}:{ok:!0,id:hashMachineId("linux-machine-id",raw),source:"linux-machine-id"}}if(platform==="win32"){const out=run("reg",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid"]),raw=/MachineGuid\s+REG_SZ\s+([0-9A-Fa-f-]{36})/.exec(out)?.[1];return raw===void 0?{ok:!1,reason:"malformed",detail:"the registry named no MachineGuid"}:{ok:!0,id:hashMachineId("win32-machine-guid",raw),source:"win32-machine-guid"}}return{ok:!1,reason:"unsupported-platform",detail:`${platform} exposes no machine identity this build trusts`}}catch(error){return{ok:!1,reason:"unreadable",detail:`the machine identity could not be read: ${error instanceof Error?error.message:String(error)}`}}}export function readConfiguredHostNames(readers={}){if((readers.platform??process.platform)!=="darwin")return[];const run=readers.run??defaultRun,names=[],one=key=>{try{const value=run("/usr/
|
|
1
|
+
import{execFileSync}from"node:child_process";import{createHash}from"node:crypto";import{existsSync,readFileSync}from"node:fs";import{hostname}from"node:os";import{withoutLeadTokenEnv}from"./names.js";const defaultRun=(file,args)=>execFileSync(file,args,{encoding:"utf8",timeout:3e3,stdio:["ignore","pipe","ignore"],env:withoutLeadTokenEnv(process.env)});export function hashMachineId(source,raw){return createHash("sha256").update(`toolroll machine identity v1\0${source}\0${raw.trim().toLowerCase()}`).digest("hex").slice(0,32)}export function readMachineIdentity(readers={}){const platform=readers.platform??process.platform,readFile=readers.readFile??(path=>readFileSync(path,"utf8")),exists=readers.exists??existsSync,run=readers.run??defaultRun;try{if(platform==="darwin"){const raw=/"IOPlatformUUID"\s*=\s*"([0-9A-Fa-f-]{36})"/.exec(run("/usr/sbin/ioreg",["-rd1","-c","IOPlatformExpertDevice"]))?.[1];return raw===void 0||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(raw)?{ok:!1,reason:"malformed",detail:"ioreg named no IOPlatformUUID"}:{ok:!0,id:hashMachineId("darwin-platform-uuid",raw),source:"darwin-platform-uuid"}}if(platform==="linux"){if(exists("/.dockerenv")||exists("/run/.containerenv"))return{ok:!1,reason:"container",detail:"a container's machine-id can be shared with other containers"};let raw=null;for(const path of["/etc/machine-id","/var/lib/dbus/machine-id"])try{raw=readFile(path).trim();break}catch{}return raw===null?{ok:!1,reason:"unreadable",detail:"no machine-id could be read"}:!/^[0-9a-f]{32}$/i.test(raw)||/^0+$/.test(raw)?{ok:!1,reason:"malformed",detail:"the machine-id was not 32 hex digits"}:{ok:!0,id:hashMachineId("linux-machine-id",raw),source:"linux-machine-id"}}if(platform==="win32"){const out=run("reg",["query","HKLM\\SOFTWARE\\Microsoft\\Cryptography","/v","MachineGuid"]),raw=/MachineGuid\s+REG_SZ\s+([0-9A-Fa-f-]{36})/.exec(out)?.[1];return raw===void 0?{ok:!1,reason:"malformed",detail:"the registry named no MachineGuid"}:{ok:!0,id:hashMachineId("win32-machine-guid",raw),source:"win32-machine-guid"}}return{ok:!1,reason:"unsupported-platform",detail:`${platform} exposes no machine identity this build trusts`}}catch(error){return{ok:!1,reason:"unreadable",detail:`the machine identity could not be read: ${error instanceof Error?error.message:String(error)}`}}}const SYSTEM_CONFIGURATION_PREFERENCES="/Library/Preferences/SystemConfiguration/preferences.plist";export function readConfiguredHostNames(readers={}){if((readers.platform??process.platform)!=="darwin")return[];const run=readers.run??defaultRun,names=[],one=key=>{try{const value=run("/usr/bin/plutil",["-extract",key,"raw","-o","-",SYSTEM_CONFIGURATION_PREFERENCES]).trim();return/^[A-Za-z0-9][A-Za-z0-9.-]{0,252}$/.test(value)?value:null}catch{return null}},host=one("System.System.HostName");host!==null&&names.push(host);const local=one("System.Network.HostNames.LocalHostName");return local!==null&&!local.includes(".")&&names.push(`${local}.local`),names}let cachedIdentity=null,cachedConfigured=null;const remembered=new Map;function machineIdentity(){return cachedIdentity===null&&(cachedIdentity=readMachineIdentity()),cachedIdentity}export function currentMachineId(){const identity=machineIdentity();return identity.ok?identity.id:null}export function injectMachineIdentity(identity,configured=identity===null?null:[]){cachedIdentity=identity,cachedConfigured=configured,remembered.clear()}export function rememberHostAliases(id,hosts){let set=remembered.get(id);set===void 0&&remembered.set(id,set=new Set);for(const host of hosts)host!==""&&set.add(host)}export function liveHostAliases(){return cachedConfigured===null&&(cachedConfigured=readConfiguredHostNames()),[...new Set([hostname(),...cachedConfigured])]}export function thisMachine(extra=[]){const id=currentMachineId(),hosts=new Set(liveHostAliases());if(id!==null){for(const host of remembered.get(id)??[])hosts.add(host);for(const host of extra)hosts.add(host)}return{id,hosts:[...hosts]}}export function isThisMachine(witness,here=thisMachine()){return witness.machineId!==null&&witness.machineId!==void 0?here.id!==null&&witness.machineId===here.id:here.hosts.includes(witness.host)}export function sameMachineHost(seen,here=hostname(),machineId){return machineId!=null?here===hostname()&&isThisMachine({host:seen,machineId}):seen===here?!0:here===hostname()&&isThisMachine({host:seen})}
|
package/dist/memory-pass.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{inEvalWorld}from"./eval-gate.js";import{createHash}from"node:crypto";import{existsSync,readdirSync,readFileSync,statSync}from"node:fs";import{homedir}from"node:os";import{join}from"node:path";import{scanForSecrets,readVerifiedArtifact}from"./evidence.js";import{changeKnowledge,knowledgeView}from"./project-knowledge.js";import{listDecisions,recordDecision,refuseLeadMemoryWrite}from"./project-memory.js";import{composeLeadRequest,performLeadRequest,isDirectChatProvider,CHAT_KEY_ENV}from"./converse.js";import{performSubscriptionLeadRequest}from"./subscription-chat.js";import{routeWorkerModel}from"./model-routing.js";import{TEXT_LIMITS}from"./text-limits.js";import{lastIncludedWords,memoryUseOf}from"./memory-use.js";import{lessonNoteOf,lessonNoteSourceRef,NOTE_SURFACE,watchNote}from"./lesson-notes.js";import{currentLocalOwner}from"./local-owner.js";import{CONTRADICTION_SCHEMA}from"./memory-tidy.js";import{contractError,parseContract}from"./contracts/contract.js";import{MEMORY_VERDICT_MODEL_SCHEMA,MEMORY_VERDICT_VERSION,memoryEvidenceSchema,memoryProposalSchema,memoryVerdictReadSchema,readSavedVerdict,savedVerdictSchema}from"./contracts/memory-pass.js";const MEMORY_TRACE_BYTES=TEXT_LIMITS.memoryTrace,MEMORY_MIN_SESSIONS=2,MEMORY_MAX_PROPOSALS=6,INSTRUCTION_BUDGET_BYTES=TEXT_LIMITS.knowledgeInstructionsBytes,VERDICT_ITEMS=20,MEMORY_GAP_MAX_AGE_MS=2160*36e5,sha=text=>createHash("sha256").update(text).digest("hex");export const claudeProjectDir=(cwd,home=homedir())=>join(home,".claude","projects",cwd.replaceAll("/","-"));function redact(text){const hits=new Map(scanForSecrets(text).map(hit=>[hit.line,hit.name]));return hits.size===0?text:text.split(`
|
|
1
|
+
import{inEvalWorld}from"./eval-gate.js";import{createHash}from"node:crypto";import{existsSync,readdirSync,readFileSync,statSync}from"node:fs";import{homedir}from"node:os";import{join}from"node:path";import{adoptLeadOpenRouterKey,readOpenRouterKey}from"./openrouter-key.js";import{scanForSecrets,readVerifiedArtifact}from"./evidence.js";import{changeKnowledge,knowledgeView}from"./project-knowledge.js";import{listDecisions,recordDecision,refuseLeadMemoryWrite}from"./project-memory.js";import{composeLeadRequest,performLeadRequest,isDirectChatProvider,CHAT_KEY_ENV}from"./converse.js";import{performSubscriptionLeadRequest}from"./subscription-chat.js";import{routeWorkerModel}from"./model-routing.js";import{TEXT_LIMITS}from"./text-limits.js";import{lastIncludedWords,memoryUseOf}from"./memory-use.js";import{lessonNoteOf,lessonNoteSourceRef,NOTE_SURFACE,watchNote}from"./lesson-notes.js";import{currentLocalOwner}from"./local-owner.js";import{CONTRADICTION_SCHEMA}from"./memory-tidy.js";import{contractError,parseContract}from"./contracts/contract.js";import{MEMORY_VERDICT_MODEL_SCHEMA,MEMORY_VERDICT_VERSION,memoryEvidenceSchema,memoryProposalSchema,memoryVerdictReadSchema,readSavedVerdict,savedVerdictSchema}from"./contracts/memory-pass.js";const MEMORY_TRACE_BYTES=TEXT_LIMITS.memoryTrace,MEMORY_MIN_SESSIONS=2,MEMORY_MAX_PROPOSALS=6,INSTRUCTION_BUDGET_BYTES=TEXT_LIMITS.knowledgeInstructionsBytes,VERDICT_ITEMS=20,MEMORY_GAP_MAX_AGE_MS=2160*36e5,sha=text=>createHash("sha256").update(text).digest("hex");export const claudeProjectDir=(cwd,home=homedir())=>join(home,".claude","projects",cwd.replaceAll("/","-"));function redact(text){const hits=new Map(scanForSecrets(text).map(hit=>[hit.line,hit.name]));return hits.size===0?text:text.split(`
|
|
2
2
|
`).map((line,index)=>hits.has(index+1)?`[redacted ${hits.get(index+1)}]`:line).join(`
|
|
3
3
|
`)}const clip=(text,max)=>text.length>max?`${text.slice(0,max)}…`:text,jsonLines=path=>readFileSync(path,"utf8").split(`
|
|
4
4
|
`).flatMap(line=>{try{return line.trim()?[JSON.parse(line)]:[]}catch{return[]}}),obj=v=>v!==null&&typeof v=="object"&&!Array.isArray(v)?v:{};function distillClaude(path){const lines=[];for(const raw of jsonLines(path)){const row=obj(raw),message=obj(row.message);if(row.type!=="user"&&row.type!=="assistant")continue;const content=message.content;if(typeof content=="string"){lines.push(`${row.type}: ${clip(content,4e3)}`);continue}for(const block of Array.isArray(content)?content.map(obj):[])if(block.type==="text"&&typeof block.text=="string")lines.push(`${row.type}: ${clip(block.text,4e3)}`);else if(block.type==="tool_use")lines.push(`tool ${String(block.name)}: ${clip(JSON.stringify(block.input??{}),160)}`);else if(block.type==="tool_result"){const c=block.content;lines.push(`result: ${clip(typeof c=="string"?c:JSON.stringify(c??""),200)}`)}}return redact(lines.join(`
|
|
@@ -9,8 +9,8 @@ import{inEvalWorld}from"./eval-gate.js";import{createHash}from"node:crypto";impo
|
|
|
9
9
|
`))})}const runs=store.handle.prepare("SELECT r.id, r.role, r.finished_at, r.handoff, t.external_id FROM run r JOIN task_ref t ON t.id=r.task_ref WHERE t.repo=? AND r.role IN ('builder','repair') AND r.outcome IS NOT NULL ORDER BY r.id DESC LIMIT 100").all(repo);for(const row of runs){const id=Number(row.id);out.push({id:`crew:${id}`,repo,kind:"crew",source:`run:${id}`,at:String(row.finished_at??""),trace:()=>{const parts=[`task ${String(row.external_id)} · ${String(row.role)} run ${id}`,`handoff: ${clip(String(row.handoff??""),6e3)}`];if(evidenceRoot!==void 0)for(const artifact of store.artifactsFor(id).filter(a=>a.kind==="check-log"||a.kind==="report")){const read=readVerifiedArtifact(evidenceRoot,artifact);read.ok&&parts.push(`${artifact.kind}: ${clip(read.content.toString("utf8").slice(-6e3),6e3)}`)}const proof=store.proofVerdictFor(id);return proof&&parts.push(`verdict: ${proof.verdict}${proof.reasons.length?` — ${proof.reasons.join("; ")}`:""}`),redact(parts.join(`
|
|
10
10
|
`))}})}return out}function collectSessions(store,repo,options={}){const home=options.home??homedir();return[...planeSources(store,repo,options.evidenceRoot),...options.local===!1?[]:[...fileSources(repo,"claude",home),...fileSources(repo,"codex",home)]].sort((a,b)=>b.at.localeCompare(a.at))}export function memorySurface(store,repo,actor){const instructions=knowledgeView(store,repo,actor).knowledge.instructions.split(`
|
|
11
11
|
`).map(line=>line.trim()).filter(Boolean).map((text,index)=>({id:`IN-${String(index+1).padStart(3,"0")}`,text})),decisions=listDecisions(store,repo,actor,{limit:50}).map(d=>({id:`DE-${d.id}`,claim:d.claim}));return{version:sha(JSON.stringify({instructions,decisions})).slice(0,16),instructions,decisions}}function analysisPrompt(surface,openGaps){return["You are auditing one past session of an agent working on this project against the project memory it was given. Do not review the code. Measure how the memory steered the session and spot mistakes an instruction or a recorded decision could have prevented.","INSTRUCTIONS (refer to them ONLY by id):",...surface.instructions.map(i=>`[${i.id}] ${i.text}`),"DECISIONS on record (refer by id):",...surface.decisions.map(d=>`[${d.id}] ${d.claim}`),"GAPS ALREADY ON THE BOOKS (cite the key in matchesGap when the same underlying gap):",...openGaps.map(g=>`[${g.key}] ${g.mistake}`),`Return ONE JSON object and nothing else, matching this JSON Schema: ${JSON.stringify(MEMORY_VERDICT_MODEL_SCHEMA)}`,"Rules: every item needs a verbatim quote copied from the trace or it is discarded; negative evidence outranks positive; class harm means following the instruction caused damage, non-compliance means it was ignored; a mistake caused by the harness or task framing is domain orchestration; report nothing rather than something weak; an empty array is a good answer."].join(`
|
|
12
|
-
`)}function memoryPassModel(store,provider,fallback){return routeWorkerModel(store,{taskKind:"memory-extract",provider,fallbackModel:fallback}).model}export function defaultAnalyzer(store,options){return async input=>{if(inEvalWorld())return{ok:!1,problem:"The backward pass makes no provider call in an eval world."};const config=store.getChatConfig();if(config===null)return{ok:!1,problem:"Chat is not configured; the backward pass uses the chat model."};const model=memoryPassModel(store,config.provider,config.model),system=analysisPrompt(input.surface,input.openGaps),dataDocument=`TRACE (${input.kind} session):
|
|
13
|
-
${input.trace}`,history=[{role:"operator",text:"Audit the trace above and return the JSON object."}];if(isDirectChatProvider(config.provider)){
|
|
12
|
+
`)}function memoryPassModel(store,provider,fallback){return routeWorkerModel(store,{taskKind:"memory-extract",provider,fallbackModel:fallback}).model}function leadKeyOf(store,provider,options,env){if(provider==="openrouter-api")return adoptLeadOpenRouterKey(store,{...options.configDir===void 0?{}:{configDir:options.configDir},...options.home===void 0?{}:{home:options.home},env}),readOpenRouterKey({...options.home===void 0?{}:{home:options.home},env})?.key??"";let key=env[CHAT_KEY_ENV[provider]]??"";if(!key&&options.configDir!==void 0)try{key=readFileSync(join(options.configDir,`chat-key-${provider}`),"utf8").trim()}catch{key=""}return key}export function defaultAnalyzer(store,options){return async input=>{if(inEvalWorld())return{ok:!1,problem:"The backward pass makes no provider call in an eval world."};const config=store.getChatConfig();if(config===null)return{ok:!1,problem:"Chat is not configured; the backward pass uses the chat model."};const model=memoryPassModel(store,config.provider,config.model),system=analysisPrompt(input.surface,input.openGaps),dataDocument=`TRACE (${input.kind} session):
|
|
13
|
+
${input.trace}`,history=[{role:"operator",text:"Audit the trace above and return the JSON object."}];if(isDirectChatProvider(config.provider)){const env=options.env??process.env,key=leadKeyOf(store,config.provider,options,env);if(!key)return{ok:!1,problem:`No ${config.provider} key is available for the backward pass.`};const request=composeLeadRequest({provider:config.provider,model,key,system,dataDocument,history,tools:[]}),answer2=await performLeadRequest(request,config.provider,AbortSignal.timeout(options.timeoutMs??12e4),options.fetcher);return answer2.ok?{ok:!0,text:answer2.answer.text}:{ok:!1,problem:answer2.problem}}const answer=await performSubscriptionLeadRequest({provider:config.provider,model,system,dataDocument,history,tools:[],outputSchema:MEMORY_VERDICT_MODEL_SCHEMA,effort:"low",cacheTtl:"5m",timeoutMs:options.timeoutMs??18e4},options.runner);return answer.ok?{ok:!0,text:answer.answer.text}:{ok:!1,problem:answer.problem}}}export function defaultTidyAnalyzer(store,options={}){return async input=>{if(inEvalWorld())return{ok:!1,problem:"Clean up makes no provider call in an eval world."};const config=store.getChatConfig();if(config===null)return{ok:!1,problem:"Chat is not configured, so contradictions were not looked for."};const model=memoryPassModel(store,config.provider,config.model),history=[{role:"operator",text:"Read the decisions above and return the JSON object."}];if(isDirectChatProvider(config.provider)){const env=options.env??process.env,key=leadKeyOf(store,config.provider,options,env);if(!key)return{ok:!1,problem:`No ${config.provider} key is available, so contradictions were not looked for.`};const request=composeLeadRequest({provider:config.provider,model,key,system:input.system,dataDocument:input.data,history,tools:[]}),answer2=await performLeadRequest(request,config.provider,AbortSignal.timeout(options.timeoutMs??12e4),options.fetcher);return answer2.ok?{ok:!0,text:answer2.answer.text}:{ok:!1,problem:answer2.problem}}const answer=await performSubscriptionLeadRequest({provider:config.provider,model,system:input.system,dataDocument:input.data,history,tools:[],outputSchema:CONTRADICTION_SCHEMA,effort:"low",cacheTtl:"5m",timeoutMs:options.timeoutMs??18e4},options.runner);return answer.ok?{ok:!0,text:answer.answer.text}:{ok:!1,problem:answer.problem}}}const UNREADABLE="The analysis was not a readable verdict.";export function parseVerdict(text,trace,surface){const start=text.indexOf("{"),end=text.lastIndexOf("}");if(start<0||end<=start)return{ok:!1,problem:UNREADABLE};let raw;try{raw=JSON.parse(text.slice(start,end+1))}catch{return{ok:!1,problem:UNREADABLE}}const read=parseContract(memoryVerdictReadSchema,raw);if(!read.ok)return{ok:!1,problem:`${UNREADABLE.slice(0,-1)}: ${read.issues.slice(0,5).map(issue=>issue.line).join("; ")}`};const ids=new Set(surface.instructions.map(i=>i.id)),quoted=item=>item.quote.trim().length>=12&&trace.includes(item.quote.trim()),list=items=>items.filter(item=>item!==null&"ed(item)).slice(0,VERDICT_ITEMS).flatMap(item=>item===null||item.claim===null?[]:[{...item.claim,quote:item.quote.trim()}]);return{ok:!0,verdict:{positive:list(read.value.positive).filter(i=>ids.has(i.instruction)),negative:list(read.value.negative).filter(i=>ids.has(i.instruction)),gaps:list(read.value.gaps)}}}const keptVerdict=verdict=>JSON.stringify(savedVerdictSchema.parse({version:MEMORY_VERDICT_VERSION,...verdict})),gapKey=mistake=>sha(mistake.toLowerCase().replace(/[^\p{L}\p{N}]+/gu," ").trim()).slice(0,16);export async function runMemoryPass(store,args,now=new Date){const surface=memorySurface(store,args.repo,args.actor),sessions=collectSessions(store,args.repo,{...args.evidenceRoot===void 0?{}:{evidenceRoot:args.evidenceRoot},...args.home===void 0?{}:{home:args.home},...args.local===void 0?{}:{local:args.local}}).slice(0,args.maxSessions??100),report={repo:args.repo,surface:surface.version,sessions:sessions.length,analyzed:0,cached:0,failed:0,problems:[],gaps:0,proposals:0},openGaps=()=>store.handle.prepare("SELECT key, mistake FROM memory_gap WHERE repo=? AND retired_at IS NULL AND last_seen>=?").all(args.repo,new Date(now.getTime()-MEMORY_GAP_MAX_AGE_MS).toISOString()).map(row=>({key:String(row.key),mistake:String(row.mistake)}));for(const session of sessions){const existing=store.handle.prepare("SELECT surface, analyzed_at, verdict FROM memory_session WHERE id=?").get(session.id);if(existing&&existing.surface===surface.version&&existing.analyzed_at!==null&&existing.verdict!==null){report.cached++;continue}let trace;try{trace=session.trace()}catch(error){report.failed++,report.problems.push(`${session.id}: ${error instanceof Error?error.message:"unreadable"}`);continue}if(trace.length>MEMORY_TRACE_BYTES&&(trace=trace.slice(0,MEMORY_TRACE_BYTES)),trace.trim().length<40)continue;store.handle.prepare(`INSERT INTO memory_session(id,repo,kind,source,seen_at,surface,trace_sha) VALUES (?,?,?,?,?,?,?)
|
|
14
14
|
ON CONFLICT(id) DO UPDATE SET surface=excluded.surface, trace_sha=excluded.trace_sha, analyzed_at=NULL, verdict=NULL, problem=NULL`).run(session.id,args.repo,session.kind,session.source,session.at||now.toISOString(),surface.version,sha(trace));const gaps=openGaps(),answer=await args.analyzer({trace,surface,openGaps:gaps,kind:session.kind}),parsed=answer.ok?parseVerdict(answer.text,trace,surface):null;if(parsed===null||!parsed.ok){report.failed++;const problem=parsed===null?answer.ok?UNREADABLE:answer.problem:parsed.problem;report.problems.push(`${session.id}: ${problem}`),store.handle.prepare("UPDATE memory_session SET problem=? WHERE id=?").run(problem,session.id);continue}const verdict=parsed.verdict;store.transact(()=>{store.handle.prepare("UPDATE memory_session SET analyzed_at=?, verdict=?, problem=NULL WHERE id=?").run(now.toISOString(),keptVerdict(verdict),session.id);for(const gap of verdict.gaps){if(gap.domain==="orchestration")continue;const key=gap.matchesGap!==null&&gaps.some(g=>g.key===gap.matchesGap)?gap.matchesGap:gapKey(gap.mistake);store.handle.prepare(`INSERT INTO memory_gap(repo,key,mistake,proposed,domain,first_seen,last_seen) VALUES (?,?,?,?,?,?,?)
|
|
15
15
|
ON CONFLICT(repo,key) DO UPDATE SET last_seen=excluded.last_seen, retired_at=NULL, retired_reason=NULL`).run(args.repo,key,gap.mistake,gap.proposedInstruction,gap.domain,now.toISOString(),now.toISOString());const id=Number(store.handle.prepare("SELECT id FROM memory_gap WHERE repo=? AND key=?").get(args.repo,key).id);store.handle.prepare("INSERT OR IGNORE INTO memory_sighting(gap,session,at,quote) VALUES (?,?,?,?)").run(id,session.id,now.toISOString(),gap.quote)}}),report.analyzed++}return report.gaps=Number(store.handle.prepare("SELECT COUNT(*) AS n FROM memory_gap WHERE repo=? AND retired_at IS NULL").get(args.repo)?.n??0),report.proposals=synthesizeProposals(store,args.repo,args.actor,surface,now),report}function proposalOf(row){const read=memoryProposalSchema.safeParse({id:Number(row.id),repo:String(row.repo),kind:row.kind,fingerprint:String(row.fingerprint),title:String(row.title),rationale:String(row.rationale),beforeText:row.before_text===null?null:String(row.before_text),afterText:String(row.after_text),evidence:JSON.parse(String(row.evidence)),sessions:Number(row.sessions),status:String(row.status),createdAt:String(row.created_at),surface:String(row.surface)},{reportInput:!0});if(!read.success)throw Error(`Memory proposal ${String(row.id)} could not be read: ${contractError(read.error).join("; ")}`);return read.data}export function synthesizeProposals(store,repo,actor,surface,now=new Date){const view=knowledgeView(store,repo,actor),budgetLeft=INSTRUCTION_BUDGET_BYTES-Buffer.byteLength(view.knowledge.instructions);let made=0;return store.transact(()=>{store.handle.prepare("UPDATE memory_proposal SET status='stale' WHERE repo=? AND status='pending' AND surface<>? AND surface<>?").run(repo,surface.version,NOTE_SURFACE);const pendingFingerprints=new Set(store.handle.prepare("SELECT fingerprint FROM memory_proposal WHERE repo=? AND status='pending'").all(repo).map(row=>String(row.fingerprint))),rejected=new Map(store.handle.prepare("SELECT fingerprint, sessions FROM memory_rejection WHERE repo=?").all(repo).map(row=>[String(row.fingerprint),Number(row.sessions)])),consider=(kind,fingerprint,title,rationale,beforeText,afterText,evidence)=>{if(made>=MEMORY_MAX_PROPOSALS||pendingFingerprints.has(fingerprint))return;const sessions=new Set(evidence.map(e=>e.session)).size;sessions<MEMORY_MIN_SESSIONS||(rejected.get(fingerprint)??-1)>=sessions||(store.handle.prepare("INSERT INTO memory_proposal(repo,kind,fingerprint,title,rationale,before_text,after_text,evidence,sessions,status,created_at,surface) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)").run(repo,kind,fingerprint,title,rationale,beforeText,afterText,JSON.stringify(memoryEvidenceSchema.parse(evidence.slice(0,6))),sessions,"pending",now.toISOString(),surface.version),pendingFingerprints.add(fingerprint),made++)},gaps=store.handle.prepare("SELECT g.id, g.key, g.mistake, g.proposed FROM memory_gap g WHERE g.repo=? AND g.retired_at IS NULL AND g.domain='project' ORDER BY g.last_seen DESC").all(repo);for(const gap of gaps){const sightings=store.handle.prepare("SELECT session, quote FROM memory_sighting WHERE gap=? ORDER BY at").all(Number(gap.id)).map(row=>({session:String(row.session),quote:String(row.quote)}));if(new Set(sightings.map(s=>s.session)).size<MEMORY_MIN_SESSIONS)continue;const proposed=String(gap.proposed).trim();if(surface.instructions.some(i=>i.text.toLowerCase()===proposed.toLowerCase())){store.handle.prepare("UPDATE memory_gap SET retired_at=?, retired_reason='covered by an instruction' WHERE id=?").run(now.toISOString(),Number(gap.id));continue}if(Buffer.byteLength(proposed)+1>budgetLeft){consider("decision-add",`budget:${String(gap.key)}`,`Over budget: ${clip(proposed,80)}`,`The instructions are at their 4 KB budget. Record this as a decision instead, or remove an instruction first. Mistake seen: ${String(gap.mistake)}`,null,proposed,sightings);continue}consider("instruction-add",`add:${String(gap.key)}`,`Add: ${clip(proposed,80)}`,`Mistake seen in ${new Set(sightings.map(s=>s.session)).size} sessions: ${String(gap.mistake)}`,null,proposed,sightings)}const harm=new Map;for(const row of store.handle.prepare("SELECT id, verdict FROM memory_session WHERE repo=? AND surface=? AND verdict IS NOT NULL").all(repo,surface.version)){let kept;try{kept=JSON.parse(String(row.verdict))}catch{continue}const verdict=readSavedVerdict(kept);if(verdict.ok)for(const item of verdict.value.negative)item.class==="harm"&&harm.set(item.instruction,[...harm.get(item.instruction)??[],{session:String(row.id),quote:item.quote}])}for(const[instruction,evidence]of harm){const line=surface.instructions.find(i=>i.id===instruction);line!==void 0&&consider("instruction-remove",`remove:${sha(line.text).slice(0,16)}`,`Remove: ${clip(line.text,80)}`,`Following this instruction caused harm in ${new Set(evidence.map(e=>e.session)).size} sessions.`,line.text,"",evidence)}}),made}export function listProposals(store,repo,status="pending"){return store.handle.prepare("SELECT * FROM memory_proposal WHERE repo=? AND (?='all' OR status=?) ORDER BY id DESC LIMIT 100").all(repo,status,status).map(row=>proposalOf(row))}export function decideProposal(store,args,now=new Date){return refuseLeadMemoryWrite(),store.transact(()=>{if(refuseLeadMemoryWrite(),!store.accountCanAccess(args.actor,args.repo)||store.accountOf(args.actor)?.role!=="approver")throw Error("Project memory is outside your access.");const row=store.handle.prepare("SELECT * FROM memory_proposal WHERE id=? AND repo=?").get(args.id,args.repo);if(!row)throw Error("That proposal is unavailable.");const proposal=proposalOf(row);if(proposal.status!=="pending")throw Error("That proposal was already decided.");const note=lessonNoteOf(store,proposal.id),local=currentLocalOwner();if(local!==null&&(note===null||local.act!=="memory-review"))throw Error("Sign in with your password to do this.");const surface=memorySurface(store,args.repo,args.actor);if(note===null&&surface.version!==proposal.surface)throw store.handle.prepare("UPDATE memory_proposal SET status='stale' WHERE id=?").run(proposal.id),Error("Project memory changed since this was proposed. Run the pass again.");if(args.decision==="reject")store.handle.prepare("INSERT INTO memory_rejection(repo,fingerprint,rejected_at,rejected_by,sessions) VALUES (?,?,?,?,?) ON CONFLICT(repo,fingerprint) DO UPDATE SET rejected_at=excluded.rejected_at, rejected_by=excluded.rejected_by, sessions=excluded.sessions").run(args.repo,proposal.fingerprint,now.toISOString(),args.actor,proposal.sessions);else if(note!==null){const claim=(args.claim??"").trim();if(claim===""||claim===proposal.afterText.trim())throw Error("Write the note in your own words before accepting it.");recordDecision(store,{repo:args.repo,actor:args.actor,draft:{claim,why:clip(proposal.rationale,1500),sourceKind:"result",sourceRef:lessonNoteSourceRef(proposal.id)}},now),watchNote(store,{repo:args.repo,proposal:proposal.id,identities:note.identities,now})}else{const view=knowledgeView(store,args.repo,args.actor);proposal.kind==="instruction-add"?changeKnowledge(store,{repo:args.repo,actor:args.actor,identity:view.identity,revision:view.revision,action:"instructions",draft:{instructions:`${view.knowledge.instructions.trimEnd()}
|
|
16
16
|
${proposal.afterText}`.trim()}},now):proposal.kind==="instruction-remove"?changeKnowledge(store,{repo:args.repo,actor:args.actor,identity:view.identity,revision:view.revision,action:"instructions",draft:{instructions:view.knowledge.instructions.split(`
|