@moretea-labs/forge 1.6.0 → 1.7.1
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/AGENTS.md +4 -0
- package/CHANGELOG.md +39 -0
- package/CLAUDE.md +4 -0
- package/README.md +2 -2
- package/README.zh-CN.md +1 -1
- package/SKILL.md +2 -2
- package/THIRD_PARTY_NOTICES.md +1 -1
- package/agents/openai.yaml +1 -1
- package/assets/hooks/hook-input.sh +11 -8
- package/assets/hooks/lib/session-state.sh +10 -7
- package/assets/hooks/lib/workflow-state.sh +13 -177
- package/assets/hooks/post-tool-observer.sh +8 -2
- package/assets/hooks/prompt-guard.sh +5 -81
- package/assets/hooks/session-start-context.sh +56 -1
- package/assets/partials/05-workflow.partial.md +1 -1
- package/assets/partials-agents/02-operating-mode.partial.md +2 -0
- package/assets/partials-agents/03-orchestration.partial.md +1 -1
- package/assets/plugin-registry.v1.json +3 -3
- package/assets/reference-configs/document-generation.md +1 -1
- package/assets/reference-configs/harness-overview.md +1 -1
- package/assets/reference-configs/sprint-contracts.md +3 -3
- package/assets/skill-version.json +2 -2
- package/assets/templates/contract.template.md +2 -7
- package/assets/templates/helpers/capture-plan.sh +2 -2
- package/assets/templates/helpers/check-architecture-sync.sh +17 -0
- package/assets/templates/helpers/check-task-workflow.sh +4 -4
- package/assets/templates/helpers/contract-worktree.sh +1 -21
- package/assets/templates/helpers/ensure-task-workflow.sh +11 -36
- package/assets/templates/helpers/inspect-project-state.ts +8 -6
- package/assets/templates/helpers/migrate-project-template.sh +22 -45
- package/assets/templates/helpers/migrate-workflow-docs.ts +9 -7
- package/assets/templates/helpers/new-plan.sh +1 -1
- package/assets/templates/helpers/plan-to-todo.sh +12 -37
- package/assets/templates/helpers/ship-worktrees.sh +2 -29
- package/assets/templates/helpers/verify-contract.sh +1 -111
- package/assets/templates/helpers/verify-sprint.sh +3 -180
- package/assets/templates/helpers/workflow-contract.ts +5 -1
- package/assets/templates/plan.template.md +1 -1
- package/assets/templates/review.template.md +9 -34
- package/assets/workflow-contract.v1.json +10 -19
- package/docs/README.md +10 -10
- package/docs/architecture/CURRENT.md +178 -0
- package/docs/architecture/EVOLUTION.md +42 -0
- package/docs/architecture/current/README.md +4 -156
- package/docs/architecture/decisions/20260803-release-identity-binding-and-exit-policy.md +2 -2
- package/docs/architecture/decisions/20260823-immediate-controller-relay.md +53 -0
- package/docs/architecture/decisions/20260826-browser-runtime-v2.md +73 -0
- package/docs/architecture/history/README.md +7 -0
- package/docs/architecture/{chatgpt-handoff-facade.md → history/chatgpt-handoff-facade.md} +4 -0
- package/docs/architecture/{global-hook-runtime.md → history/global-hook-runtime.md} +7 -3
- package/docs/architecture/{ios-semantic-automation-provider-v2.md → history/ios-semantic-automation-provider-v2.md} +6 -2
- package/docs/architecture/history.md +3 -34
- package/docs/architecture/index.md +15 -98
- package/docs/architecture/modules/controller-runtime/transport-lifecycle.md +1 -1
- package/docs/architecture/reviews/2026-08-22-semantic-harness-convergence-acceptance.md +39 -0
- package/docs/architecture/versions/1.6.md +38 -0
- package/docs/architecture/versions/1.7.md +41 -0
- package/docs/forge-chatgpt-browser-engine.md +2 -2
- package/docs/forge-chatgpt-mcp-setup.md +4 -28
- package/docs/forge-chatgpt-supervised-automation.md +3 -3
- package/docs/forge-github-issue-launcher.md +1 -1
- package/docs/forge-plugin-management.md +1 -1
- package/docs/forge-runtime-self-healing-loop.md +1 -1
- package/docs/operations/controller-browser-plugin.md +26 -6
- package/docs/operations/controller-performance-and-502.md +143 -0
- package/docs/operations/controller-reliability-runbook.md +1 -1
- package/docs/operations/features.md +2 -2
- package/docs/operations/github-repository.md +1 -1
- package/docs/operations/homebrew.md +2 -2
- package/docs/operations/mcp-tool-exposure.md +5 -3
- package/docs/wiki/Architecture.md +6 -6
- package/docs/wiki/Implementation.md +2 -2
- package/docs/wiki/Integrations.md +2 -2
- package/docs/wiki/Work-Lifecycle.md +1 -1
- package/package.json +33 -11
- package/scripts/activate-source-baseline.ts +17 -13
- package/scripts/architecture-event.ts +2 -820
- package/scripts/architecture-queue.sh +2 -645
- package/scripts/archive-architecture-request.sh +2 -242
- package/scripts/archive-workflow.sh +1 -291
- package/scripts/benchmark-background-check-overlap.ts +228 -0
- package/scripts/benchmark-mcp-host.sh +117 -0
- package/scripts/benchmark-mcp-transport.ts +170 -0
- package/scripts/benchmark-quality-harness.ts +146 -0
- package/scripts/benchmark-route-session-concurrency.ts +207 -6
- package/scripts/benchmark-thin-harness-mcp-e2e.ts +7 -1
- package/scripts/benchmark-typescript-navigation.ts +186 -0
- package/scripts/benchmark-work-efficiency.ts +334 -0
- package/scripts/capability-config.ts +2 -392
- package/scripts/capability-resolver.ts +2 -503
- package/scripts/capture-plan.sh +1 -332
- package/scripts/check-agent-tooling.sh +2 -1558
- package/scripts/check-architecture-sync.sh +2 -371
- package/scripts/check-brain-manifest.sh +2 -253
- package/scripts/check-context-files.sh +2 -47
- package/scripts/check-deploy-sql-order.sh +2 -115
- package/scripts/check-mcp-compatibility.ts +14 -0
- package/scripts/check-runtime-architecture.mjs +349 -79
- package/scripts/check-skill-version.ts +3 -191
- package/scripts/check-source-duplication.mjs +61 -0
- package/scripts/check-stable-baseline.ts +92 -0
- package/scripts/check-task-sync.sh +2 -63
- package/scripts/check-task-workflow.sh +2 -1000
- package/scripts/codex-handoff-resume.sh +2 -267
- package/scripts/context-contract-sync.sh +2 -514
- package/scripts/contract-run.ts +2 -463
- package/scripts/contract-worktree.sh +1 -722
- package/scripts/ensure-task-workflow.sh +1 -1225
- package/scripts/host-temporary-cloud-mcp-e2e.sh +265 -0
- package/scripts/inspect-project-state.ts +4 -279
- package/scripts/install-standalone-recovery.ts +24 -0
- package/scripts/lib/project-init-lib.sh +22 -46
- package/scripts/lib/run-forge-helper.sh +19 -0
- package/scripts/lib/run-forge-helper.ts +26 -0
- package/scripts/migrate-project-template.sh +1 -1189
- package/scripts/migrate-workflow-docs.ts +4 -412
- package/scripts/new-plan.sh +1 -180
- package/scripts/new-spec.sh +1 -47
- package/scripts/new-sprint.sh +1 -46
- package/scripts/plan-to-todo.sh +1 -796
- package/scripts/prepare-codex-handoff.sh +2 -201
- package/scripts/prepare-handoff.sh +1 -78
- package/scripts/refresh-current-status.sh +2 -467
- package/scripts/run-governed-gate.ts +5 -1
- package/scripts/select-agent-context-blocks.sh +2 -64
- package/scripts/ship-worktrees.sh +1 -558
- package/scripts/smoke-ios-physical-device.ts +4 -2
- package/scripts/smoke-runtime-recovery.ts +1 -35
- package/scripts/smoke-schedule-engine.ts +1 -20
- package/scripts/sprint-backlog.sh +1 -834
- package/scripts/stage-runtime-release.ts +2 -1
- package/scripts/summarize-failures.sh +2 -123
- package/scripts/switch-plan.sh +1 -150
- package/scripts/sync-brain-docs.sh +2 -379
- package/scripts/sync-generated-authority.mjs +175 -0
- package/scripts/verify-contract.sh +2 -703
- package/scripts/verify-forge-runtime.sh +0 -1
- package/scripts/verify-sprint.sh +1 -677
- package/scripts/workflow-contract.ts +4 -205
- package/scripts/workstream-sync.sh +2 -261
- package/src/cli/agent-jobs/executor-health.ts +1 -1
- package/src/cli/commands/init-hook.ts +3 -3
- package/src/cli/commands/mcp.ts +9 -5
- package/src/cli/commands/plugin.ts +12 -3
- package/src/cli/commands/recovery.ts +25 -3
- package/src/cli/commands/runtime.ts +55 -3
- package/src/cli/commands/security.ts +12 -1
- package/src/cli/commands/setup-profile.ts +31 -21
- package/src/cli/controller/check-runner.ts +113 -5
- package/src/cli/controller/composite-result.ts +1 -1
- package/src/cli/controller/context/focus.ts +51 -0
- package/src/cli/controller/context/instruction-context.ts +114 -0
- package/src/cli/controller/context/known-paths.ts +76 -0
- package/src/cli/controller/context/query-planning.ts +110 -0
- package/src/cli/controller/context/rule-resolution.ts +532 -0
- package/src/cli/controller/context/source-materializer.ts +278 -0
- package/src/cli/controller/context/structural.ts +16 -0
- package/src/cli/controller/context/types.ts +286 -0
- package/src/cli/controller/context-pack.ts +828 -487
- package/src/cli/controller/launch-agents.ts +77 -2
- package/src/cli/controller/operational-plan.ts +2 -2
- package/src/cli/controller/work-mode.ts +6 -4
- package/src/cli/editing/edit-session.ts +60 -7
- package/src/cli/github/contracts.ts +16 -0
- package/src/cli/github/github.ts +135 -16
- package/src/cli/github/session.ts +2 -1
- package/src/cli/installer/managed-entries.ts +15 -1
- package/src/cli/local-bridge/console-automations.ts +54 -78
- package/src/cli/local-bridge/console-view-models.ts +1 -35
- package/src/cli/local-bridge/facade-api.ts +37 -264
- package/src/cli/local-bridge/frontend/src/App.tsx +3 -3
- package/src/cli/local-bridge/frontend/src/features/automations/AutomationsView.tsx +23 -13
- package/src/cli/local-bridge/frontend/src/features/capabilities/CapabilitiesView.tsx +37 -4
- package/src/cli/local-bridge/frontend/src/features/overview/OverviewView.tsx +6 -4
- package/src/cli/local-bridge/frontend/src/lib/api.ts +1 -6
- package/src/cli/local-bridge/frontend/src/lib/routes.ts +1 -1
- package/src/cli/local-bridge/frontend/src/shell/Sidebar.tsx +2 -2
- package/src/cli/local-bridge/frontend/src/styles.css +1 -1
- package/src/cli/local-bridge/frontend/src/types.ts +5 -8
- package/src/cli/local-bridge/job-store.ts +1 -490
- package/src/cli/local-bridge/server.ts +2 -515
- package/src/cli/local-bridge/ui-dist/app.css +1 -1
- package/src/cli/local-bridge/ui-dist/app.js +3703 -3757
- package/src/cli/mcp/auth.ts +5 -5
- package/src/cli/mcp/instructions.ts +3 -2
- package/src/cli/mcp/legacy-tool-service.ts +10 -222
- package/src/cli/mcp/multi-repository.ts +16 -5
- package/src/cli/mcp/oauth.ts +175 -26
- package/src/cli/mcp/post-finalize-work-attribution.ts +150 -0
- package/src/cli/mcp/repository-tools.ts +282 -146
- package/src/cli/mcp/server.ts +586 -116
- package/src/cli/mcp/tool-capability-cache.ts +1 -1
- package/src/cli/mcp/tool-contract.ts +14 -0
- package/src/cli/mcp/toolset-selection.ts +1 -1
- package/src/cli/mcp/toolset.ts +44 -7
- package/src/cli/mcp/transports/http.ts +124 -14
- package/src/cli/mcp/transports/session-registry.ts +43 -5
- package/src/cli/mcp/types.ts +3 -3
- package/src/cli/repositories/command-classifier.ts +103 -21
- package/src/cli/repositories/command-executor.ts +78 -526
- package/src/cli/repositories/command-process.ts +108 -0
- package/src/cli/repositories/command-scope.ts +99 -41
- package/src/cli/repositories/controller-home.ts +7 -8
- package/src/cli/repositories/git-command-executor.ts +2 -0
- package/src/cli/repositories/locks.ts +53 -16
- package/src/cli/repositories/repository-snapshot.ts +124 -0
- package/src/cli/repositories/selected-path-actions.ts +17 -9
- package/src/cli/repositories/structured-git.ts +118 -6
- package/src/cli/repository/inspector.ts +563 -65
- package/src/cli/repository/session-cache.ts +58 -17
- package/src/cli/v81-entry.ts +1 -4
- package/src/effects/fs-transaction.ts +85 -17
- package/src/runtime/context/codegraph-read-provider.ts +233 -2
- package/src/runtime/context/codegraph-sidecar.cjs +74 -40
- package/src/runtime/context/generic-lsp-provider.ts +355 -0
- package/src/runtime/context/lsp-client.ts +283 -0
- package/src/runtime/context/semantic-navigation-contract.ts +61 -0
- package/src/runtime/context/semantic-navigation.ts +223 -0
- package/src/runtime/context/swift-navigation.ts +565 -0
- package/src/runtime/context/typescript-navigation.ts +226 -0
- package/src/runtime/control-plane/dispatch-priority.ts +28 -0
- package/src/runtime/control-plane/execution/direct-edit-work-completion.ts +48 -16
- package/src/runtime/control-plane/execution/edit-validation-coordinator.ts +86 -24
- package/src/runtime/control-plane/execution/repository-work-attribution.ts +106 -0
- package/src/runtime/control-plane/execution/retained-work-resume.ts +203 -0
- package/src/runtime/control-plane/execution/session-store.ts +18 -0
- package/src/runtime/control-plane/execution/verification-evidence.ts +58 -3
- package/src/runtime/control-plane/execution/work-completion-authority.ts +58 -0
- package/src/runtime/control-plane/execution/work-evidence-policy.ts +200 -0
- package/src/runtime/control-plane/execution/work-execution-support.ts +386 -0
- package/src/runtime/control-plane/execution/work-finalization-service.ts +1913 -0
- package/src/runtime/control-plane/execution/work-handle-authority.ts +96 -0
- package/src/runtime/control-plane/execution/work-handle-store.ts +27 -2
- package/src/runtime/control-plane/execution/work-lifecycle-audit.ts +258 -0
- package/src/runtime/control-plane/execution/work-operation-service.ts +468 -0
- package/src/runtime/control-plane/execution/work-path-scope.ts +37 -0
- package/src/runtime/control-plane/execution/work-preparation-service.ts +479 -0
- package/src/runtime/control-plane/execution/work-process-evidence.ts +129 -0
- package/src/runtime/control-plane/execution/work-remote-delivery.ts +215 -0
- package/src/runtime/control-plane/execution/work-task-receipt.ts +22 -18
- package/src/runtime/control-plane/execution/work-terminal-cleanup.ts +156 -11
- package/src/runtime/control-plane/execution/work-validation-reconciler.ts +22 -14
- package/src/runtime/control-plane/execution/work-verification-context.ts +56 -0
- package/src/runtime/control-plane/execution/work-verification-service.ts +388 -0
- package/src/runtime/control-plane/execution/work-verification-snapshot.ts +90 -9
- package/src/runtime/control-plane/facade/capability-registry.ts +129 -25
- package/src/runtime/control-plane/facade/controller-round-relay.ts +1118 -0
- package/src/runtime/control-plane/facade/controller-session-store.ts +302 -12
- package/src/runtime/control-plane/facade/goal-workloop-access.ts +17 -1
- package/src/runtime/control-plane/facade/goal-workloop.ts +928 -190
- package/src/runtime/control-plane/facade/index.ts +3 -0
- package/src/runtime/control-plane/facade/plan-contract-store.ts +275 -42
- package/src/runtime/control-plane/facade/repository-work-admission.ts +147 -0
- package/src/runtime/control-plane/facade/requirement-authority.ts +83 -0
- package/src/runtime/control-plane/facade/semantic-admission.ts +205 -0
- package/src/runtime/control-plane/facade/suggested-actions.ts +5 -1
- package/src/runtime/control-plane/facade/types.ts +90 -10
- package/src/runtime/control-plane/facade/work-contract-store.ts +157 -261
- package/src/runtime/control-plane/facade/work-state-machine.ts +250 -0
- package/src/runtime/control-plane/generated-cache-retention.ts +271 -0
- package/src/runtime/control-plane/global-scheduler/config.ts +44 -0
- package/src/runtime/control-plane/global-scheduler/dispatch-capacity.ts +80 -0
- package/src/runtime/control-plane/global-scheduler/durable-admission.ts +46 -0
- package/src/runtime/control-plane/global-scheduler/maintenance.ts +152 -0
- package/src/runtime/control-plane/global-scheduler/projection-refresh.ts +84 -0
- package/src/runtime/control-plane/global-scheduler/reconciliation.ts +3 -3
- package/src/runtime/control-plane/global-scheduler/scheduler.ts +278 -543
- package/src/runtime/control-plane/global-scheduler/source-scan.ts +59 -0
- package/src/runtime/control-plane/global-scheduler/state.ts +88 -0
- package/src/runtime/control-plane/global-scheduler/worker-attachment.ts +57 -0
- package/src/runtime/control-plane/global-scheduler/worker-exit-decision.ts +38 -0
- package/src/runtime/control-plane/global-scheduler/worker-exit-reconciler.ts +175 -0
- package/src/runtime/control-plane/global-scheduler/worker-launch.ts +111 -0
- package/src/runtime/control-plane/global-scheduler/worker-lifecycle-store.ts +64 -0
- package/src/runtime/control-plane/global-scheduler/worker-lifecycle.ts +150 -0
- package/src/runtime/control-plane/global-scheduler/worker-process.ts +119 -0
- package/src/runtime/control-plane/global-scheduler/worker-stderr.ts +60 -0
- package/src/runtime/control-plane/launcher/chatgpt-work-binding-store.ts +63 -0
- package/src/runtime/control-plane/launcher/chatgpt-work-continuation.ts +365 -117
- package/src/runtime/control-plane/launcher/launch-reservation-store.ts +89 -0
- package/src/runtime/control-plane/launcher/thin-launcher.ts +244 -11
- package/src/runtime/control-plane/persistence/controller-home-migration.ts +487 -0
- package/src/runtime/control-plane/persistence/requirement-store.ts +0 -12
- package/src/runtime/control-plane/persistence/sqlite-store.ts +33 -2
- package/src/runtime/control-plane/release-retention.ts +62 -2
- package/src/runtime/control-plane/repo-actor/registry.ts +4 -2
- package/src/runtime/control-plane/routing/route-policy.ts +24 -21
- package/src/runtime/control-plane/routing/workspace-admission.ts +70 -0
- package/src/runtime/control-plane/runtime-status-client.ts +0 -2
- package/src/runtime/diagnostics/mcp-timing.ts +13 -0
- package/src/runtime/diagnostics/mcp-transport-benchmark.ts +129 -0
- package/src/runtime/diagnostics/performance.ts +24 -1
- package/src/runtime/evidence/event-ledger.ts +1 -1
- package/src/runtime/evidence/process-check-execution.ts +18 -0
- package/src/runtime/execution/jobs/child-reference.ts +6 -2
- package/src/runtime/execution/jobs/store.ts +58 -4
- package/src/runtime/execution/jobs/types.ts +1 -1
- package/src/runtime/execution/managed-workspace.ts +203 -1
- package/src/runtime/execution/process-runtime/check-facade.ts +51 -4
- package/src/runtime/execution/process-runtime/check-result.ts +88 -0
- package/src/runtime/execution/process-runtime/check-runner-sidecar.ts +7 -1
- package/src/runtime/execution/process-runtime/check-scheduling.ts +114 -0
- package/src/runtime/execution/process-runtime/command-facade.ts +367 -40
- package/src/runtime/execution/process-runtime/gc.ts +38 -6
- package/src/runtime/execution/process-runtime/lightweight-managed.ts +1201 -0
- package/src/runtime/execution/process-runtime/persisted-check.ts +51 -5
- package/src/runtime/execution/process-runtime/resource-claims.ts +10 -6
- package/src/runtime/execution/process-runtime/runtime.ts +53 -3
- package/src/runtime/execution/process-runtime/store.ts +1 -0
- package/src/runtime/execution/process-runtime/types.ts +4 -12
- package/src/runtime/execution/thin-harness/async-process.ts +12 -2
- package/src/runtime/execution/thin-harness/search-worker.ts +54 -5
- package/src/runtime/execution/work-activity.ts +21 -0
- package/src/runtime/execution/workers/executor.ts +18 -61
- package/src/runtime/gateway/mcp/execution-tools.ts +35 -1852
- package/src/runtime/gateway/mcp/legacy-ios-tool-adapter.ts +61 -0
- package/src/runtime/gateway/mcp/process-tools.ts +83 -37
- package/src/runtime/gateway/mcp/router.ts +186 -84
- package/src/runtime/gateway/mcp/runtime-tool-definitions.ts +565 -0
- package/src/runtime/gateway/mcp/runtime-tools.ts +2378 -1947
- package/src/runtime/plugins/app-store-connect-adapter.ts +216 -47
- package/src/runtime/plugins/browser-adapter.ts +2662 -829
- package/src/runtime/plugins/browser-automation-service.ts +10 -0
- package/src/runtime/plugins/browser-handoff-host.ts +2 -25
- package/src/runtime/plugins/browser-handoff.ts +110 -5
- package/src/runtime/plugins/browser-macos-bridge.ts +701 -63
- package/src/runtime/plugins/browser-manifest-surface.ts +603 -0
- package/src/runtime/plugins/browser-native-session-service.ts +222 -0
- package/src/runtime/plugins/browser-node-bridge.ts +6 -34
- package/src/runtime/plugins/browser-provider-registry.ts +109 -0
- package/src/runtime/plugins/browser-runtime-contract.ts +154 -0
- package/src/runtime/plugins/browser-runtime.ts +193 -0
- package/src/runtime/plugins/browser-session-authority.ts +332 -0
- package/src/runtime/plugins/browser-session-store.ts +121 -0
- package/src/runtime/plugins/browser-session-types.ts +98 -0
- package/src/runtime/plugins/capability-authorization-grants.ts +354 -0
- package/src/runtime/plugins/desktop-operator-registration.ts +10 -4
- package/src/runtime/plugins/external-adapter.ts +358 -3
- package/src/runtime/plugins/external-unix-socket.ts +7 -1
- package/src/runtime/plugins/first-party-registry.ts +2 -0
- package/src/runtime/plugins/github-adapter.ts +125 -0
- package/src/runtime/plugins/ios/agent-device-provider.ts +1 -1
- package/src/runtime/plugins/ios/agent-device-typed-provider.ts +52 -9
- package/src/runtime/plugins/ios/remote-xpc-hid.ts +1171 -0
- package/src/runtime/plugins/ios-adapter.ts +106 -16
- package/src/runtime/plugins/ios-agent-device.ts +234 -64
- package/src/runtime/plugins/ios-physical-device.ts +1143 -392
- package/src/runtime/plugins/lightweight-action.ts +153 -0
- package/src/runtime/plugins/local-system-adapter.ts +123 -6
- package/src/runtime/plugins/macos-capability-broker.ts +47 -9
- package/src/runtime/plugins/plugin-action-sidecar.ts +59 -0
- package/src/runtime/plugins/plugin-management-adapter.ts +49 -8
- package/src/runtime/plugins/resend-adapter.ts +1 -1
- package/src/runtime/plugins/store.ts +330 -33
- package/src/runtime/plugins/types.ts +38 -3
- package/src/runtime/plugins/xiaohongshu-publish.ts +515 -0
- package/src/runtime/projections/git-status-sampler.ts +16 -16
- package/src/runtime/projections/materialized-view.ts +28 -10
- package/src/runtime/recovery/maintenance-executor.ts +426 -25
- package/src/runtime/root/mcp-transport.ts +180 -10
- package/src/runtime/root/package-connector-service.ts +230 -10
- package/src/runtime/root/package-runtime-release.ts +143 -17
- package/src/runtime/root/package-runtime-service.ts +461 -22
- package/src/runtime/root/release-manifest.ts +144 -18
- package/src/runtime/root/release-materialize.ts +125 -32
- package/src/runtime/root/release-store.ts +48 -11
- package/src/runtime/root/runtime.ts +23 -5
- package/src/runtime/root/service.ts +100 -29
- package/src/runtime/root/types.ts +12 -0
- package/src/runtime/safe-tooling/ios-development.ts +321 -63
- package/src/runtime/shared/trusted-executable.ts +62 -0
- package/src/runtime/shared/trusted-node-executable.ts +48 -0
- package/src/runtime/standalone-recovery/core.ts +1079 -240
- package/src/runtime/standalone-recovery/entry.ts +100 -24
- package/src/runtime/standalone-recovery/installer.ts +20 -4
- package/src/runtime/standalone-recovery/service-labels.ts +2 -0
- package/src/runtime/standalone-recovery/watchdog-heartbeat.ts +160 -0
- package/src/runtime/workflow/schedules/browser-probe.ts +81 -3
- package/src/runtime/workflow/schedules/engine.ts +364 -202
- package/src/runtime/workflow/schedules/github-issue-watch.ts +158 -0
- package/src/runtime/workflow/schedules/settlement.ts +64 -17
- package/src/runtime/workflow/schedules/store.ts +209 -19
- package/src/runtime/workflow/schedules/types.ts +2 -4
- package/src/runtime/workflow/schedules/work-continuation.ts +26 -13
- package/src/testing/test-governance.ts +8 -40
- package/assets/reference-configs/heartbeat-triage.md +0 -57
- package/assets/templates/helpers/harness-trace-grade.sh +0 -150
- package/assets/templates/helpers/heartbeat-triage.sh +0 -361
- package/assets/templates/helpers/maintenance-triage.sh +0 -167
- package/docs/architecture/current/approved-target-architecture.zh-CN.md +0 -1501
- package/docs/architecture/current/architecture-invariants.md +0 -331
- package/docs/architecture/current/automation-and-schedule-engine.md +0 -459
- package/docs/architecture/current/codegraph-context-provider.md +0 -238
- package/docs/architecture/current/control-plane-authority-inventory.md +0 -94
- package/docs/architecture/current/controller-repository-decoupling.md +0 -148
- package/docs/architecture/current/dispatch-and-agent-strategy.md +0 -373
- package/docs/architecture/current/entity-model.md +0 -612
- package/docs/architecture/current/external-plugin-governance.md +0 -396
- package/docs/architecture/current/failure-recovery.md +0 -447
- package/docs/architecture/current/governance.md +0 -213
- package/docs/architecture/current/human-interaction-plane.md +0 -87
- package/docs/architecture/current/implementation-status.md +0 -128
- package/docs/architecture/current/job-and-run-lifecycle.md +0 -413
- package/docs/architecture/current/legacy-governance.md +0 -58
- package/docs/architecture/current/local-workspace-target-grants.md +0 -70
- package/docs/architecture/current/migration-roadmap.md +0 -105
- package/docs/architecture/current/multi-repository-execution.md +0 -371
- package/docs/architecture/current/operations-runbook.md +0 -45
- package/docs/architecture/current/peer-supercontroller-runtime.md +0 -32
- package/docs/architecture/current/personal-assistant-plugin-baseline.md +0 -206
- package/docs/architecture/current/repository-access-modes.md +0 -102
- package/docs/architecture/current/route-policy.md +0 -15
- package/docs/architecture/current/route-session-concurrency.md +0 -85
- package/docs/architecture/current/runtime-architecture-simplification.md +0 -214
- package/docs/architecture/current/runtime-directory-map.md +0 -49
- package/docs/architecture/current/runtime-health-and-resource-lifecycle.md +0 -85
- package/docs/architecture/current/scheduler-and-resource-claims.md +0 -422
- package/docs/architecture/current/session-aware-execution-and-authorization.md +0 -77
- package/docs/architecture/current/system-overview.md +0 -169
- package/docs/architecture/current/target-requirements-traceability.md +0 -202
- package/docs/architecture/current/thin-harness-governance-policy.md +0 -32
- package/docs/architecture/current/thin-harness-v1.md +0 -321
- package/docs/architecture/current/verification-and-release-gates.md +0 -391
- package/docs/forge-autonomous-goal-loop.md +0 -9
- package/docs/forge-provider-configuration.md +0 -7
- package/docs/operations/chatgpt-personal-assistant-runtime.md +0 -93
- package/docs/operations/gmail-assistant-routines.md +0 -186
- package/docs/operations/personal-assistant-operator-guide.md +0 -61
- package/docs/operations/provider-configuration.md +0 -31
- package/scripts/harness-trace-grade.sh +0 -150
- package/scripts/heartbeat-triage.sh +0 -361
- package/scripts/maintenance-triage.sh +0 -167
- package/src/cli/local-bridge/frontend/src/features/settings/SettingsView.tsx +0 -2
- package/src/cli/repositories/goal-registry.ts +0 -239
- package/src/runtime/assistant/action-proposals.ts +0 -279
- package/src/runtime/assistant/intent.ts +0 -395
- package/src/runtime/assistant/model-provider.ts +0 -460
- package/src/runtime/assistant/openapi.ts +0 -223
- package/src/runtime/assistant/policy.ts +0 -89
- package/src/runtime/assistant/readiness.ts +0 -258
- package/src/runtime/assistant/routine-runtime.ts +0 -477
- package/src/runtime/assistant/schedule-binding.ts +0 -171
- package/src/runtime/assistant/standing-grants.ts +0 -375
- package/src/runtime/assistant/store.ts +0 -243
- package/src/runtime/assistant/types.ts +0 -135
- package/src/runtime/control-plane/goal-loop/config-facade.ts +0 -700
- package/src/runtime/control-plane/goal-loop/config-store.ts +0 -570
- package/src/runtime/control-plane/goal-loop/config-types.ts +0 -213
- package/src/runtime/control-plane/goal-loop/executor-router.ts +0 -109
- package/src/runtime/control-plane/goal-loop/failure-taxonomy.ts +0 -149
- package/src/runtime/control-plane/goal-loop/goal-contract-store.ts +0 -304
- package/src/runtime/control-plane/goal-loop/goal-loop-engine.ts +0 -1001
- package/src/runtime/control-plane/goal-loop/handoff-packet.ts +0 -160
- package/src/runtime/control-plane/goal-loop/index.ts +0 -13
- package/src/runtime/control-plane/goal-loop/local-tools.ts +0 -290
- package/src/runtime/control-plane/goal-loop/policy-gates.ts +0 -203
- package/src/runtime/control-plane/goal-loop/provider-dispatch.ts +0 -93
- package/src/runtime/control-plane/goal-loop/provider-registry.ts +0 -545
- package/src/runtime/control-plane/goal-loop/types.ts +0 -378
- package/src/runtime/control-plane/startup-recovery.ts +0 -198
- package/src/runtime/gateway/mcp/resource-policy.ts +0 -186
- package/src/runtime/personal-assistant/gmail-triage-manager.ts +0 -231
- package/src/runtime/personal-assistant/reporting-runtime.ts +0 -344
- package/src/runtime/personal-assistant/triage-runtime.ts +0 -748
- package/src/runtime/workflow/findings/store.ts +0 -204
- package/src/runtime/workflow/findings/types.ts +0 -58
- package/src/runtime/workflow/portfolio/engine.ts +0 -20
- package/src/runtime/workflow/portfolio/store.ts +0 -185
- package/src/runtime/workflow/portfolio/types.ts +0 -29
|
@@ -0,0 +1,1201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lightweight process handles for ordinary local repository commands.
|
|
3
|
+
*
|
|
4
|
+
* Running state deliberately has no SQLite record, lease, recovery membership,
|
|
5
|
+
* runner indirection, or replay binding. Only a bounded terminal receipt is
|
|
6
|
+
* persisted so a controller restart can recover completed evidence; it must
|
|
7
|
+
* never re-execute a command to reconstruct a missing running handle.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { randomUUID } from 'crypto';
|
|
11
|
+
import { chmodSync, existsSync, mkdirSync, readdirSync, rmSync, statSync } from 'fs';
|
|
12
|
+
import { join } from 'path';
|
|
13
|
+
import { capProcessOutput, redactProcessOutput } from '../../../effects/process-runner';
|
|
14
|
+
import {
|
|
15
|
+
executeRepositoryCommandAsync,
|
|
16
|
+
type ExecuteRepositoryCommandInput,
|
|
17
|
+
} from '../../../cli/repositories/command-executor';
|
|
18
|
+
import {
|
|
19
|
+
releaseControllerCheckSubscription,
|
|
20
|
+
runControllerCheckAsync,
|
|
21
|
+
} from '../../../cli/controller/check-runner';
|
|
22
|
+
import { repositoryControllerRoot } from '../../../cli/repositories/controller-home';
|
|
23
|
+
import type { RepositoryRecord } from '../../../cli/repositories/types';
|
|
24
|
+
import { readJsonFile, sanitizeFileComponent, writeJsonAtomic } from '../../shared/json-files';
|
|
25
|
+
import {
|
|
26
|
+
defaultProcessIdentityProbe,
|
|
27
|
+
executableFingerprint,
|
|
28
|
+
processIdentityMatches,
|
|
29
|
+
type ExpectedProcessIdentity,
|
|
30
|
+
} from '../../shared/process-identity';
|
|
31
|
+
import { terminateProcessTree } from '../../shared/process-tree';
|
|
32
|
+
import { runBoundedProcess } from '../thin-harness/async-process';
|
|
33
|
+
import { PROCESS_LOG_TAIL_BYTES, type ProcessHandle, type ProcessLogSlice, type WaitProcessOptions } from './types';
|
|
34
|
+
|
|
35
|
+
const EMPTY_EFFECTS = {
|
|
36
|
+
executionJobCount: 0,
|
|
37
|
+
localJobCount: 0,
|
|
38
|
+
workerSpawnCount: 0,
|
|
39
|
+
projectionUpdateCount: 0,
|
|
40
|
+
};
|
|
41
|
+
const DEFAULT_MAX_OUTPUT_BYTES = 128 * 1024;
|
|
42
|
+
const TERMINAL_RETENTION_MS = 60 * 60_000;
|
|
43
|
+
const MAX_RETAINED_HANDLES = 256;
|
|
44
|
+
const TERMINAL_RECEIPT_RETENTION_MS = 6 * 60 * 60_000;
|
|
45
|
+
const MAX_TERMINAL_RECEIPTS = 256;
|
|
46
|
+
const RUNNING_RECEIPT_PERSIST_INTERVAL_MS = 250;
|
|
47
|
+
|
|
48
|
+
interface LightweightExecutionResult {
|
|
49
|
+
ok?: boolean;
|
|
50
|
+
exitCode?: number;
|
|
51
|
+
timedOut?: boolean;
|
|
52
|
+
cancelled?: boolean;
|
|
53
|
+
stdout?: string;
|
|
54
|
+
stderr?: string;
|
|
55
|
+
/** Child execution completed, but repository mutation evidence could not be proven. */
|
|
56
|
+
evidenceError?: { code: string; message: string };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
interface LightweightExitObservation {
|
|
60
|
+
ok: boolean;
|
|
61
|
+
exitCode: number;
|
|
62
|
+
timedOut: boolean;
|
|
63
|
+
cancelled: boolean;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
interface LightweightEntry {
|
|
67
|
+
processId: string;
|
|
68
|
+
controllerHome: string;
|
|
69
|
+
repoId: string;
|
|
70
|
+
workId?: string;
|
|
71
|
+
commandId: string;
|
|
72
|
+
requestFingerprint: string;
|
|
73
|
+
startedAt: string;
|
|
74
|
+
startedAtMs: number;
|
|
75
|
+
interactiveWaitMs: number;
|
|
76
|
+
timeoutMs: number;
|
|
77
|
+
maxOutputBytes: number;
|
|
78
|
+
pid?: number;
|
|
79
|
+
spawnedAtMs?: number;
|
|
80
|
+
identity?: ExpectedProcessIdentity;
|
|
81
|
+
runningReceiptUpdatedAtMs?: number;
|
|
82
|
+
exitObservation?: LightweightExitObservation;
|
|
83
|
+
stdout: string;
|
|
84
|
+
stderr: string;
|
|
85
|
+
stdoutTail: string;
|
|
86
|
+
stderrTail: string;
|
|
87
|
+
abort: AbortController;
|
|
88
|
+
promise: Promise<LightweightExecutionResult>;
|
|
89
|
+
result?: LightweightExecutionResult;
|
|
90
|
+
finishedAtMs?: number;
|
|
91
|
+
cancelRequested?: boolean;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const entries = new Map<string, LightweightEntry>();
|
|
95
|
+
|
|
96
|
+
interface LightweightRunningReceipt {
|
|
97
|
+
schemaVersion: 1;
|
|
98
|
+
repoId: string;
|
|
99
|
+
processId: string;
|
|
100
|
+
commandId?: string;
|
|
101
|
+
requestFingerprint?: string;
|
|
102
|
+
updatedAt: string;
|
|
103
|
+
handle: ProcessHandle;
|
|
104
|
+
identity?: ExpectedProcessIdentity;
|
|
105
|
+
exitObservation?: LightweightExitObservation;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
interface LightweightTerminalReceipt {
|
|
109
|
+
schemaVersion: 1;
|
|
110
|
+
repoId: string;
|
|
111
|
+
processId: string;
|
|
112
|
+
commandId?: string;
|
|
113
|
+
requestFingerprint?: string;
|
|
114
|
+
finishedAt: string;
|
|
115
|
+
handle: ProcessHandle;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function runningReceiptRoot(controllerHome: string, repoId: string): string {
|
|
119
|
+
return join(repositoryControllerRoot(controllerHome, repoId), 'process-runtime', 'lightweight-running');
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function runningReceiptPath(controllerHome: string, repoId: string, processId: string): string {
|
|
123
|
+
return join(runningReceiptRoot(controllerHome, repoId), `${sanitizeFileComponent(processId)}.json`);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function terminalReceiptRoot(controllerHome: string, repoId: string): string {
|
|
127
|
+
return join(repositoryControllerRoot(controllerHome, repoId), 'process-runtime', 'lightweight-terminal');
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function terminalReceiptPath(controllerHome: string, repoId: string, processId: string): string {
|
|
131
|
+
return join(terminalReceiptRoot(controllerHome, repoId), `${sanitizeFileComponent(processId)}.json`);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function boundedAppend(current: string, chunk: string, maxBytes: number): string {
|
|
135
|
+
if (current.endsWith(`[output truncated after ${maxBytes} bytes]`)) return current;
|
|
136
|
+
return capProcessOutput(`${current}${chunk}`, maxBytes);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function boundedTailAppend(current: string, chunk: string): string {
|
|
140
|
+
const combined = Buffer.from(`${current}${chunk}`, 'utf8');
|
|
141
|
+
return combined.length <= PROCESS_LOG_TAIL_BYTES
|
|
142
|
+
? combined.toString('utf8')
|
|
143
|
+
: combined.subarray(combined.length - PROCESS_LOG_TAIL_BYTES).toString('utf8');
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function visibleOutput(value: string, maxBytes: number): string {
|
|
147
|
+
return capProcessOutput(redactProcessOutput(value), maxBytes);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function visibleOutputTail(value: string): string {
|
|
151
|
+
const safe = redactProcessOutput(value);
|
|
152
|
+
const buffer = Buffer.from(safe, 'utf8');
|
|
153
|
+
return buffer.length <= PROCESS_LOG_TAIL_BYTES
|
|
154
|
+
? safe
|
|
155
|
+
: buffer.subarray(buffer.length - PROCESS_LOG_TAIL_BYTES).toString('utf8');
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function captureProcessIdentity(pid: number): ExpectedProcessIdentity | undefined {
|
|
159
|
+
const inspected = defaultProcessIdentityProbe.inspect?.(pid);
|
|
160
|
+
const command = inspected?.command ?? defaultProcessIdentityProbe.command(pid);
|
|
161
|
+
const processStartTime = inspected?.startTime ?? defaultProcessIdentityProbe.startTime(pid);
|
|
162
|
+
if (!command || !processStartTime) return undefined;
|
|
163
|
+
return { pid, processStartTime, executableFingerprint: executableFingerprint(command) };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function removeRunningReceipt(controllerHome: string, repoId: string, processId: string): void {
|
|
167
|
+
try { rmSync(runningReceiptPath(controllerHome, repoId, processId), { force: true }); } catch { /* best effort */ }
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function persistRunningReceipt(entry: LightweightEntry, force = false): void {
|
|
171
|
+
if (entry.result) return;
|
|
172
|
+
if (!entry.identity && entry.pid && !entry.exitObservation) {
|
|
173
|
+
entry.identity = captureProcessIdentity(entry.pid);
|
|
174
|
+
}
|
|
175
|
+
const now = Date.now();
|
|
176
|
+
if (!force && entry.runningReceiptUpdatedAtMs !== undefined
|
|
177
|
+
&& now - entry.runningReceiptUpdatedAtMs < RUNNING_RECEIPT_PERSIST_INTERVAL_MS) return;
|
|
178
|
+
try {
|
|
179
|
+
const root = runningReceiptRoot(entry.controllerHome, entry.repoId);
|
|
180
|
+
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
181
|
+
const path = runningReceiptPath(entry.controllerHome, entry.repoId, entry.processId);
|
|
182
|
+
const receipt: LightweightRunningReceipt = {
|
|
183
|
+
schemaVersion: 1,
|
|
184
|
+
repoId: entry.repoId,
|
|
185
|
+
processId: entry.processId,
|
|
186
|
+
commandId: entry.commandId,
|
|
187
|
+
requestFingerprint: entry.requestFingerprint,
|
|
188
|
+
updatedAt: new Date(now).toISOString(),
|
|
189
|
+
handle: entryHandle(entry),
|
|
190
|
+
...(entry.identity ? { identity: entry.identity } : {}),
|
|
191
|
+
...(entry.exitObservation ? { exitObservation: entry.exitObservation } : {}),
|
|
192
|
+
};
|
|
193
|
+
writeJsonAtomic(path, receipt);
|
|
194
|
+
try { chmodSync(path, 0o600); } catch { /* Windows or restricted filesystem. */ }
|
|
195
|
+
entry.runningReceiptUpdatedAtMs = now;
|
|
196
|
+
} catch {
|
|
197
|
+
// Running receipts are recovery hints only; the in-memory handle remains authoritative while this Runtime is alive.
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function readRunningReceipt(controllerHome: string, repoId: string, processId: string): LightweightRunningReceipt | undefined {
|
|
202
|
+
const path = runningReceiptPath(controllerHome, repoId, processId);
|
|
203
|
+
if (!existsSync(path)) return undefined;
|
|
204
|
+
try {
|
|
205
|
+
const receipt = readJsonFile<LightweightRunningReceipt>(path);
|
|
206
|
+
if (receipt.schemaVersion !== 1 || receipt.repoId !== repoId || receipt.processId !== processId) return undefined;
|
|
207
|
+
if (receipt.handle?.processId !== processId || receipt.handle.completed) return undefined;
|
|
208
|
+
return receipt;
|
|
209
|
+
} catch {
|
|
210
|
+
return undefined;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function terminalHandle(entry: LightweightEntry): ProcessHandle {
|
|
215
|
+
const handle = entryHandle(entry);
|
|
216
|
+
const stdout = capProcessOutput(redactProcessOutput(handle.stdout ?? ''), entry.maxOutputBytes);
|
|
217
|
+
const stderr = capProcessOutput(redactProcessOutput(handle.stderr ?? ''), entry.maxOutputBytes);
|
|
218
|
+
return {
|
|
219
|
+
...handle,
|
|
220
|
+
stdout,
|
|
221
|
+
stderr,
|
|
222
|
+
stdoutTail: visibleOutputTail(handle.stdoutTail ?? stdout),
|
|
223
|
+
stderrTail: visibleOutputTail(handle.stderrTail ?? stderr),
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function pruneTerminalReceipts(root: string, keepPath: string): void {
|
|
228
|
+
try {
|
|
229
|
+
const now = Date.now();
|
|
230
|
+
const retained: Array<{ path: string; mtimeMs: number }> = [];
|
|
231
|
+
for (const file of readdirSync(root)) {
|
|
232
|
+
if (!file.endsWith('.json')) continue;
|
|
233
|
+
const path = join(root, file);
|
|
234
|
+
try {
|
|
235
|
+
const mtimeMs = statSync(path).mtimeMs;
|
|
236
|
+
if (path !== keepPath && now - mtimeMs > TERMINAL_RECEIPT_RETENTION_MS) {
|
|
237
|
+
rmSync(path, { force: true });
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
retained.push({ path, mtimeMs });
|
|
241
|
+
} catch {
|
|
242
|
+
// A concurrently removed receipt is already pruned.
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
const excess = retained.length - MAX_TERMINAL_RECEIPTS;
|
|
246
|
+
if (excess <= 0) return;
|
|
247
|
+
const candidates = retained
|
|
248
|
+
.filter((entry) => entry.path !== keepPath)
|
|
249
|
+
.sort((left, right) => left.mtimeMs - right.mtimeMs);
|
|
250
|
+
for (const entry of candidates.slice(0, excess)) rmSync(entry.path, { force: true });
|
|
251
|
+
} catch {
|
|
252
|
+
// Terminal receipts are recovery evidence only; cleanup must not fail execution.
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function persistTerminalReceipt(controllerHome: string, entry: LightweightEntry): void {
|
|
257
|
+
if (!entry.result || !entry.finishedAtMs) return;
|
|
258
|
+
const existing = readTerminalReceipt(controllerHome, entry.repoId, entry.processId);
|
|
259
|
+
if (existing) {
|
|
260
|
+
removeRunningReceipt(controllerHome, entry.repoId, entry.processId);
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
try {
|
|
264
|
+
const root = terminalReceiptRoot(controllerHome, entry.repoId);
|
|
265
|
+
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
266
|
+
const path = terminalReceiptPath(controllerHome, entry.repoId, entry.processId);
|
|
267
|
+
const receipt: LightweightTerminalReceipt = {
|
|
268
|
+
schemaVersion: 1,
|
|
269
|
+
repoId: entry.repoId,
|
|
270
|
+
processId: entry.processId,
|
|
271
|
+
commandId: entry.commandId,
|
|
272
|
+
requestFingerprint: entry.requestFingerprint,
|
|
273
|
+
finishedAt: new Date(entry.finishedAtMs).toISOString(),
|
|
274
|
+
handle: terminalHandle(entry),
|
|
275
|
+
};
|
|
276
|
+
writeJsonAtomic(path, receipt);
|
|
277
|
+
try { chmodSync(path, 0o600); } catch { /* Windows or restricted filesystem. */ }
|
|
278
|
+
removeRunningReceipt(controllerHome, entry.repoId, entry.processId);
|
|
279
|
+
pruneTerminalReceipts(root, path);
|
|
280
|
+
} catch {
|
|
281
|
+
// A receipt failure must never turn a completed local command into a failure.
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function readTerminalReceipt(controllerHome: string, repoId: string, processId: string): LightweightTerminalReceipt | undefined {
|
|
286
|
+
const path = terminalReceiptPath(controllerHome, repoId, processId);
|
|
287
|
+
if (!existsSync(path)) return undefined;
|
|
288
|
+
try {
|
|
289
|
+
const receipt = readJsonFile<LightweightTerminalReceipt>(path);
|
|
290
|
+
if (receipt.schemaVersion !== 1 || receipt.repoId !== repoId || receipt.processId !== processId) return undefined;
|
|
291
|
+
if (!receipt.handle?.completed || receipt.handle.processId !== processId) return undefined;
|
|
292
|
+
const finishedAtMs = Date.parse(receipt.finishedAt);
|
|
293
|
+
if (!Number.isFinite(finishedAtMs) || Date.now() - finishedAtMs > TERMINAL_RECEIPT_RETENTION_MS) {
|
|
294
|
+
rmSync(path, { force: true });
|
|
295
|
+
return undefined;
|
|
296
|
+
}
|
|
297
|
+
return receipt;
|
|
298
|
+
} catch {
|
|
299
|
+
return undefined;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function recoveredRequestMetrics(): LightweightCommandMetrics {
|
|
304
|
+
return {
|
|
305
|
+
lane: 'lightweight_managed',
|
|
306
|
+
interactiveReturnMs: 0,
|
|
307
|
+
durableWrites: 0,
|
|
308
|
+
leaseOperations: 0,
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* A request id is a durable attachment key, not permission to replay a command.
|
|
314
|
+
* Receipts written before this identity was added deliberately fail closed: a
|
|
315
|
+
* caller can use a fresh request id, but a Runtime restart cannot duplicate an
|
|
316
|
+
* operation whose original payload cannot be verified.
|
|
317
|
+
*/
|
|
318
|
+
function findPersistedHandleForCommand(
|
|
319
|
+
controllerHome: string,
|
|
320
|
+
repoId: string,
|
|
321
|
+
commandId: string,
|
|
322
|
+
requestFingerprint: string,
|
|
323
|
+
): ProcessHandle | undefined {
|
|
324
|
+
const roots = [terminalReceiptRoot(controllerHome, repoId), runningReceiptRoot(controllerHome, repoId)];
|
|
325
|
+
for (const root of roots) {
|
|
326
|
+
if (!existsSync(root)) continue;
|
|
327
|
+
for (const file of readdirSync(root)) {
|
|
328
|
+
if (!file.endsWith('.json')) continue;
|
|
329
|
+
try {
|
|
330
|
+
const receipt = readJsonFile<LightweightRunningReceipt | LightweightTerminalReceipt>(join(root, file));
|
|
331
|
+
if (receipt.schemaVersion !== 1 || receipt.repoId !== repoId || !receipt.processId) continue;
|
|
332
|
+
const persistedCommandId = receipt.commandId ?? receipt.handle?.commandId;
|
|
333
|
+
if (persistedCommandId !== commandId) continue;
|
|
334
|
+
if (!receipt.requestFingerprint || receipt.requestFingerprint !== requestFingerprint) {
|
|
335
|
+
throw new Error(`PROCESS_REQUEST_CONFLICT: command id ${commandId} cannot be safely replayed after Runtime restart`);
|
|
336
|
+
}
|
|
337
|
+
return getLightweightProcessHandle(controllerHome, repoId, receipt.processId);
|
|
338
|
+
} catch (error) {
|
|
339
|
+
if (error instanceof Error && error.message.startsWith('PROCESS_REQUEST_CONFLICT:')) throw error;
|
|
340
|
+
// A corrupt or concurrently pruned receipt is not an execution result.
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
return undefined;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function recoveredRunningHandle(receipt: LightweightRunningReceipt, note?: string): ProcessHandle {
|
|
348
|
+
const stderrTail = note
|
|
349
|
+
? visibleOutputTail([receipt.handle.stderrTail, note].filter(Boolean).join('\n'))
|
|
350
|
+
: receipt.handle.stderrTail;
|
|
351
|
+
return {
|
|
352
|
+
...receipt.handle,
|
|
353
|
+
status: 'running_recovered',
|
|
354
|
+
contractStatus: 'running',
|
|
355
|
+
route: 'managed',
|
|
356
|
+
completed: false,
|
|
357
|
+
ok: undefined,
|
|
358
|
+
exitCode: undefined,
|
|
359
|
+
timedOut: undefined,
|
|
360
|
+
cancelled: undefined,
|
|
361
|
+
stdout: undefined,
|
|
362
|
+
stderr: undefined,
|
|
363
|
+
stderrTail,
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function inspectRecoveredRunningReceipt(receipt: LightweightRunningReceipt): { state: 'running' | 'dead' | 'unsafe'; reason?: string } {
|
|
368
|
+
const pid = receipt.handle.pid ?? receipt.identity?.pid;
|
|
369
|
+
if (!pid) return { state: 'unsafe', reason: 'identity_missing' };
|
|
370
|
+
if (!receipt.identity) {
|
|
371
|
+
return defaultProcessIdentityProbe.isAlive(pid)
|
|
372
|
+
? { state: 'unsafe', reason: 'identity_missing' }
|
|
373
|
+
: { state: 'dead', reason: 'process_dead' };
|
|
374
|
+
}
|
|
375
|
+
const result = processIdentityMatches(receipt.identity, pid);
|
|
376
|
+
if (result.matches) return { state: 'running' };
|
|
377
|
+
if (result.reason === 'identity_probe_unavailable') return { state: 'unsafe', reason: result.reason };
|
|
378
|
+
return { state: 'dead', reason: result.reason ?? 'identity_mismatch' };
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function recoveredInspectionFailureReason(
|
|
382
|
+
inspection: ReturnType<typeof inspectRecoveredRunningReceipt>,
|
|
383
|
+
): string | undefined {
|
|
384
|
+
if (inspection.state === 'running') return undefined;
|
|
385
|
+
if (inspection.state === 'unsafe') {
|
|
386
|
+
return `PROCESS_IDENTITY_UNTRUSTED: ${inspection.reason ?? 'unknown'}`;
|
|
387
|
+
}
|
|
388
|
+
return inspection.reason ?? 'process_dead';
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
function persistRecoveredTerminalReceipt(
|
|
392
|
+
controllerHome: string,
|
|
393
|
+
receipt: LightweightRunningReceipt,
|
|
394
|
+
handle: ProcessHandle,
|
|
395
|
+
): ProcessHandle {
|
|
396
|
+
const existing = readTerminalReceipt(controllerHome, receipt.repoId, receipt.processId);
|
|
397
|
+
if (existing) {
|
|
398
|
+
removeRunningReceipt(controllerHome, receipt.repoId, receipt.processId);
|
|
399
|
+
return existing.handle;
|
|
400
|
+
}
|
|
401
|
+
try {
|
|
402
|
+
const root = terminalReceiptRoot(controllerHome, receipt.repoId);
|
|
403
|
+
mkdirSync(root, { recursive: true, mode: 0o700 });
|
|
404
|
+
const path = terminalReceiptPath(controllerHome, receipt.repoId, receipt.processId);
|
|
405
|
+
const terminal: LightweightTerminalReceipt = {
|
|
406
|
+
schemaVersion: 1,
|
|
407
|
+
repoId: receipt.repoId,
|
|
408
|
+
processId: receipt.processId,
|
|
409
|
+
commandId: receipt.commandId,
|
|
410
|
+
requestFingerprint: receipt.requestFingerprint,
|
|
411
|
+
finishedAt: new Date().toISOString(),
|
|
412
|
+
handle,
|
|
413
|
+
};
|
|
414
|
+
writeJsonAtomic(path, terminal);
|
|
415
|
+
try { chmodSync(path, 0o600); } catch { /* Windows or restricted filesystem. */ }
|
|
416
|
+
removeRunningReceipt(controllerHome, receipt.repoId, receipt.processId);
|
|
417
|
+
pruneTerminalReceipts(root, path);
|
|
418
|
+
} catch {
|
|
419
|
+
// Recovery evidence persistence must not trigger command re-execution or unsafe signalling.
|
|
420
|
+
}
|
|
421
|
+
return handle;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
function completedObservedExitHandle(receipt: LightweightRunningReceipt): ProcessHandle {
|
|
425
|
+
const observation = receipt.exitObservation!;
|
|
426
|
+
const status = observation.cancelled
|
|
427
|
+
? 'cancelled'
|
|
428
|
+
: observation.timedOut
|
|
429
|
+
? 'timed_out'
|
|
430
|
+
: observation.ok
|
|
431
|
+
? 'succeeded'
|
|
432
|
+
: 'failed';
|
|
433
|
+
const stdout = visibleOutput(receipt.handle.stdoutTail ?? '', DEFAULT_MAX_OUTPUT_BYTES);
|
|
434
|
+
const stderr = visibleOutput(receipt.handle.stderrTail ?? '', DEFAULT_MAX_OUTPUT_BYTES);
|
|
435
|
+
return {
|
|
436
|
+
...receipt.handle,
|
|
437
|
+
status,
|
|
438
|
+
contractStatus: status === 'succeeded' ? 'succeeded' : status === 'cancelled' ? 'cancelled' : 'failed',
|
|
439
|
+
route: 'direct',
|
|
440
|
+
completed: true,
|
|
441
|
+
ok: observation.ok,
|
|
442
|
+
exitCode: observation.exitCode,
|
|
443
|
+
timedOut: observation.timedOut,
|
|
444
|
+
cancelled: observation.cancelled,
|
|
445
|
+
stdout,
|
|
446
|
+
stderr,
|
|
447
|
+
stdoutTail: visibleOutputTail(stdout),
|
|
448
|
+
stderrTail: visibleOutputTail(stderr),
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
function deterministicRecoveryFailureHandle(receipt: LightweightRunningReceipt, reason: string): ProcessHandle {
|
|
453
|
+
const message = `PROCESS_RESULT_UNAVAILABLE_AFTER_RUNTIME_RESTART: ${reason}; command was not replayed`;
|
|
454
|
+
const stderr = visibleOutput([receipt.handle.stderrTail, message].filter(Boolean).join('\n'), DEFAULT_MAX_OUTPUT_BYTES);
|
|
455
|
+
return {
|
|
456
|
+
...receipt.handle,
|
|
457
|
+
status: 'failed',
|
|
458
|
+
contractStatus: 'failed',
|
|
459
|
+
route: 'direct',
|
|
460
|
+
completed: true,
|
|
461
|
+
ok: false,
|
|
462
|
+
exitCode: 1,
|
|
463
|
+
timedOut: false,
|
|
464
|
+
cancelled: false,
|
|
465
|
+
stdout: receipt.handle.stdoutTail ?? '',
|
|
466
|
+
stderr,
|
|
467
|
+
stdoutTail: visibleOutputTail(receipt.handle.stdoutTail ?? ''),
|
|
468
|
+
stderrTail: visibleOutputTail(stderr),
|
|
469
|
+
};
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function cancelledRecoveredHandle(receipt: LightweightRunningReceipt): ProcessHandle {
|
|
473
|
+
const message = 'process cancelled after recovering a lightweight handle from persisted PID identity';
|
|
474
|
+
const stderr = visibleOutput([receipt.handle.stderrTail, message].filter(Boolean).join('\n'), DEFAULT_MAX_OUTPUT_BYTES);
|
|
475
|
+
return {
|
|
476
|
+
...receipt.handle,
|
|
477
|
+
status: 'cancelled',
|
|
478
|
+
contractStatus: 'cancelled',
|
|
479
|
+
route: 'direct',
|
|
480
|
+
completed: true,
|
|
481
|
+
ok: false,
|
|
482
|
+
exitCode: 1,
|
|
483
|
+
timedOut: false,
|
|
484
|
+
cancelled: true,
|
|
485
|
+
stdout: receipt.handle.stdoutTail ?? '',
|
|
486
|
+
stderr,
|
|
487
|
+
stdoutTail: visibleOutputTail(receipt.handle.stdoutTail ?? ''),
|
|
488
|
+
stderrTail: visibleOutputTail(stderr),
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
function sweep(): void {
|
|
493
|
+
const now = Date.now();
|
|
494
|
+
for (const [processId, entry] of entries) {
|
|
495
|
+
if (entry.finishedAtMs && now - entry.finishedAtMs > TERMINAL_RETENTION_MS) entries.delete(processId);
|
|
496
|
+
}
|
|
497
|
+
if (entries.size <= MAX_RETAINED_HANDLES) return;
|
|
498
|
+
const terminal = [...entries.values()]
|
|
499
|
+
.filter((entry) => entry.finishedAtMs !== undefined)
|
|
500
|
+
.sort((left, right) => (left.finishedAtMs ?? 0) - (right.finishedAtMs ?? 0));
|
|
501
|
+
for (const entry of terminal.slice(0, entries.size - MAX_RETAINED_HANDLES)) entries.delete(entry.processId);
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
function entryHandle(entry: LightweightEntry): ProcessHandle {
|
|
505
|
+
const execution = entry.result;
|
|
506
|
+
const completed = execution !== undefined;
|
|
507
|
+
const status = !completed
|
|
508
|
+
? 'running'
|
|
509
|
+
: execution.cancelled
|
|
510
|
+
? 'cancelled'
|
|
511
|
+
: execution.timedOut
|
|
512
|
+
? 'timed_out'
|
|
513
|
+
: execution.ok
|
|
514
|
+
? 'succeeded'
|
|
515
|
+
: 'failed';
|
|
516
|
+
const stdout = completed ? execution.stdout ?? '' : visibleOutput(entry.stdout, entry.maxOutputBytes);
|
|
517
|
+
const stderr = completed ? execution.stderr ?? '' : visibleOutput(entry.stderr, entry.maxOutputBytes);
|
|
518
|
+
const stdoutTail = entry.stdoutTail || visibleOutputTail(stdout);
|
|
519
|
+
const stderrTail = entry.stderrTail || visibleOutputTail(stderr);
|
|
520
|
+
return {
|
|
521
|
+
processId: entry.processId,
|
|
522
|
+
workId: entry.workId,
|
|
523
|
+
commandId: entry.commandId,
|
|
524
|
+
status,
|
|
525
|
+
contractStatus: status === 'running'
|
|
526
|
+
? 'running'
|
|
527
|
+
: status === 'succeeded'
|
|
528
|
+
? 'succeeded'
|
|
529
|
+
: status === 'cancelled'
|
|
530
|
+
? 'cancelled'
|
|
531
|
+
: 'failed',
|
|
532
|
+
route: completed ? 'direct' : 'managed',
|
|
533
|
+
pid: entry.pid,
|
|
534
|
+
startedAt: entry.startedAt,
|
|
535
|
+
interactiveWaitMs: entry.interactiveWaitMs,
|
|
536
|
+
timeoutMs: entry.timeoutMs,
|
|
537
|
+
completed,
|
|
538
|
+
ok: execution?.ok,
|
|
539
|
+
exitCode: execution?.exitCode,
|
|
540
|
+
timedOut: execution?.timedOut,
|
|
541
|
+
cancelled: execution?.cancelled,
|
|
542
|
+
stdout: completed ? stdout : undefined,
|
|
543
|
+
stderr: completed ? stderr : undefined,
|
|
544
|
+
stdoutTail: visibleOutputTail(stdoutTail),
|
|
545
|
+
stderrTail: visibleOutputTail(stderrTail),
|
|
546
|
+
durableSideEffects: EMPTY_EFFECTS,
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
export interface StartLightweightCommandInput {
|
|
551
|
+
controllerHome: string;
|
|
552
|
+
repository: RepositoryRecord;
|
|
553
|
+
execution: ExecuteRepositoryCommandInput;
|
|
554
|
+
interactiveWaitMs: number;
|
|
555
|
+
timeoutMs: number;
|
|
556
|
+
maxOutputBytes?: number;
|
|
557
|
+
workId?: string;
|
|
558
|
+
commandId?: string;
|
|
559
|
+
/** Start repository preparation on the next event-loop turn so the caller can receive a handle first. */
|
|
560
|
+
deferStart?: boolean;
|
|
561
|
+
/** Reuse an equivalent active local build/test even when a later caller has a different request id. */
|
|
562
|
+
reuseActiveEquivalent?: boolean;
|
|
563
|
+
/** Same-call lifecycle settlement after a repository command reaches a terminal result. */
|
|
564
|
+
onCompleted?: (result: LightweightExecutionResult) => void;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
export interface LightweightCommandMetrics {
|
|
568
|
+
lane: 'lightweight_managed';
|
|
569
|
+
preSpawnHarnessMs?: number;
|
|
570
|
+
childDurationMs?: number;
|
|
571
|
+
interactiveReturnMs: number;
|
|
572
|
+
durableWrites: 0;
|
|
573
|
+
leaseOperations: 0;
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
export interface StartLightweightCheckInput {
|
|
577
|
+
controllerHome: string;
|
|
578
|
+
repoId: string;
|
|
579
|
+
repoRoot: string;
|
|
580
|
+
checkId: string;
|
|
581
|
+
interactiveWaitMs: number;
|
|
582
|
+
timeoutMs: number;
|
|
583
|
+
workId?: string;
|
|
584
|
+
commandId?: string;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
export interface StartLightweightInternalProcessInput {
|
|
588
|
+
repoId: string;
|
|
589
|
+
executable: string;
|
|
590
|
+
args: readonly string[];
|
|
591
|
+
cwd: string;
|
|
592
|
+
env?: NodeJS.ProcessEnv;
|
|
593
|
+
interactiveWaitMs: number;
|
|
594
|
+
controllerHome: string;
|
|
595
|
+
timeoutMs: number;
|
|
596
|
+
maxOutputBytes?: number;
|
|
597
|
+
workId?: string;
|
|
598
|
+
commandId?: string;
|
|
599
|
+
signal?: AbortSignal;
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
export async function startLightweightRepositoryCommand(
|
|
603
|
+
input: StartLightweightCommandInput,
|
|
604
|
+
): Promise<{ handle: ProcessHandle; metrics: LightweightCommandMetrics }> {
|
|
605
|
+
sweep();
|
|
606
|
+
const stableCommandId = input.commandId?.trim();
|
|
607
|
+
const requestFingerprint = JSON.stringify({
|
|
608
|
+
repoId: input.repository.repoId,
|
|
609
|
+
command: input.execution.command,
|
|
610
|
+
cwd: input.execution.cwd ?? '.',
|
|
611
|
+
timeoutMs: input.timeoutMs,
|
|
612
|
+
maxOutputBytes: input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
|
|
613
|
+
});
|
|
614
|
+
if (stableCommandId) {
|
|
615
|
+
const existing = [...entries.values()].find((entry) => (
|
|
616
|
+
entry.controllerHome === input.controllerHome
|
|
617
|
+
&& entry.repoId === input.repository.repoId
|
|
618
|
+
&& entry.commandId === stableCommandId
|
|
619
|
+
));
|
|
620
|
+
if (existing) {
|
|
621
|
+
if (existing.requestFingerprint !== requestFingerprint) {
|
|
622
|
+
throw new Error(`PROCESS_REQUEST_CONFLICT: command id ${stableCommandId} already identifies a different lightweight command`);
|
|
623
|
+
}
|
|
624
|
+
return {
|
|
625
|
+
handle: entryHandle(existing),
|
|
626
|
+
metrics: {
|
|
627
|
+
lane: 'lightweight_managed',
|
|
628
|
+
preSpawnHarnessMs: existing.spawnedAtMs === undefined ? undefined : Math.max(0, existing.spawnedAtMs - existing.startedAtMs),
|
|
629
|
+
childDurationMs: existing.finishedAtMs === undefined || existing.spawnedAtMs === undefined
|
|
630
|
+
? undefined
|
|
631
|
+
: Math.max(0, existing.finishedAtMs - existing.spawnedAtMs),
|
|
632
|
+
interactiveReturnMs: 0,
|
|
633
|
+
durableWrites: 0,
|
|
634
|
+
leaseOperations: 0,
|
|
635
|
+
},
|
|
636
|
+
};
|
|
637
|
+
}
|
|
638
|
+
const recovered = findPersistedHandleForCommand(
|
|
639
|
+
input.controllerHome,
|
|
640
|
+
input.repository.repoId,
|
|
641
|
+
stableCommandId,
|
|
642
|
+
requestFingerprint,
|
|
643
|
+
);
|
|
644
|
+
if (recovered) return { handle: recovered, metrics: recoveredRequestMetrics() };
|
|
645
|
+
}
|
|
646
|
+
if (input.reuseActiveEquivalent) {
|
|
647
|
+
const existing = [...entries.values()].find((entry) => (
|
|
648
|
+
entry.repoId === input.repository.repoId
|
|
649
|
+
&& entry.requestFingerprint === requestFingerprint
|
|
650
|
+
&& entry.result === undefined
|
|
651
|
+
));
|
|
652
|
+
if (existing) {
|
|
653
|
+
return {
|
|
654
|
+
handle: entryHandle(existing),
|
|
655
|
+
metrics: {
|
|
656
|
+
lane: 'lightweight_managed',
|
|
657
|
+
preSpawnHarnessMs: existing.spawnedAtMs === undefined ? undefined : Math.max(0, existing.spawnedAtMs - existing.startedAtMs),
|
|
658
|
+
childDurationMs: undefined,
|
|
659
|
+
interactiveReturnMs: 0,
|
|
660
|
+
durableWrites: 0,
|
|
661
|
+
leaseOperations: 0,
|
|
662
|
+
},
|
|
663
|
+
};
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
const processId = `lightweight:${randomUUID()}`;
|
|
667
|
+
const abort = new AbortController();
|
|
668
|
+
const maxOutputBytes = Math.max(1_024, input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES);
|
|
669
|
+
const entry: LightweightEntry = {
|
|
670
|
+
processId,
|
|
671
|
+
controllerHome: input.controllerHome,
|
|
672
|
+
repoId: input.repository.repoId,
|
|
673
|
+
workId: input.workId,
|
|
674
|
+
commandId: stableCommandId || processId,
|
|
675
|
+
requestFingerprint,
|
|
676
|
+
startedAt: new Date().toISOString(),
|
|
677
|
+
startedAtMs: Date.now(),
|
|
678
|
+
interactiveWaitMs: Math.max(0, input.interactiveWaitMs),
|
|
679
|
+
timeoutMs: input.timeoutMs,
|
|
680
|
+
maxOutputBytes,
|
|
681
|
+
stdout: '',
|
|
682
|
+
stderr: '',
|
|
683
|
+
stdoutTail: '',
|
|
684
|
+
stderrTail: '',
|
|
685
|
+
abort,
|
|
686
|
+
promise: undefined as never,
|
|
687
|
+
};
|
|
688
|
+
const onCallerAbort = () => abort.abort();
|
|
689
|
+
input.execution.signal?.addEventListener('abort', onCallerAbort, { once: true });
|
|
690
|
+
const startExecution = () => executeRepositoryCommandAsync(
|
|
691
|
+
input.controllerHome,
|
|
692
|
+
input.repository,
|
|
693
|
+
{ ...input.execution, timeoutMs: input.timeoutMs, maxOutputBytes, signal: abort.signal },
|
|
694
|
+
{
|
|
695
|
+
signal: abort.signal,
|
|
696
|
+
onSpawn: (pid) => {
|
|
697
|
+
entry.pid = pid;
|
|
698
|
+
entry.spawnedAtMs = Date.now();
|
|
699
|
+
entry.identity = captureProcessIdentity(pid);
|
|
700
|
+
persistRunningReceipt(entry, true);
|
|
701
|
+
},
|
|
702
|
+
onStdout: (chunk) => {
|
|
703
|
+
entry.stdout = boundedAppend(entry.stdout, chunk, maxOutputBytes);
|
|
704
|
+
entry.stdoutTail = boundedTailAppend(entry.stdoutTail, chunk);
|
|
705
|
+
persistRunningReceipt(entry);
|
|
706
|
+
},
|
|
707
|
+
onStderr: (chunk) => {
|
|
708
|
+
entry.stderr = boundedAppend(entry.stderr, chunk, maxOutputBytes);
|
|
709
|
+
entry.stderrTail = boundedTailAppend(entry.stderrTail, chunk);
|
|
710
|
+
persistRunningReceipt(entry);
|
|
711
|
+
},
|
|
712
|
+
onExit: (result) => {
|
|
713
|
+
entry.exitObservation = {
|
|
714
|
+
ok: result.ok,
|
|
715
|
+
exitCode: result.exitCode,
|
|
716
|
+
timedOut: result.timedOut,
|
|
717
|
+
cancelled: result.cancelled,
|
|
718
|
+
};
|
|
719
|
+
// Child exit is the authoritative Process terminal boundary. Repository
|
|
720
|
+
// post-processing may continue, but it must never keep this Process
|
|
721
|
+
// logically running or make process_get/process_wait lose the exit fact.
|
|
722
|
+
entry.result = result;
|
|
723
|
+
entry.finishedAtMs = Date.now();
|
|
724
|
+
input.execution.signal?.removeEventListener('abort', onCallerAbort);
|
|
725
|
+
persistTerminalReceipt(input.controllerHome, entry);
|
|
726
|
+
},
|
|
727
|
+
},
|
|
728
|
+
).then((result) => {
|
|
729
|
+
// Enriched execution evidence may replace the compact child-exit result in
|
|
730
|
+
// memory. The already-persisted terminal Process identity remains stable.
|
|
731
|
+
// Work lifecycle settlement belongs here, after repository evidence has
|
|
732
|
+
// either been proven or explicitly marked unavailable.
|
|
733
|
+
entry.result = result;
|
|
734
|
+
input.onCompleted?.(result);
|
|
735
|
+
persistTerminalReceipt(input.controllerHome, entry);
|
|
736
|
+
return result;
|
|
737
|
+
}).catch((error) => {
|
|
738
|
+
// Once child exit has been observed, later bookkeeping failure cannot revoke
|
|
739
|
+
// the terminal Process fact or trigger command replay. Expected snapshot
|
|
740
|
+
// degradation is represented by RepositoryCommandExecution.evidenceError;
|
|
741
|
+
// this catch is the final fail-safe for any later post-processing exception.
|
|
742
|
+
if (entry.exitObservation && entry.result) return entry.result;
|
|
743
|
+
throw error;
|
|
744
|
+
});
|
|
745
|
+
entry.promise = input.deferStart
|
|
746
|
+
? new Promise<LightweightExecutionResult>((resolve, reject) => {
|
|
747
|
+
setTimeout(() => {
|
|
748
|
+
startExecution().then(resolve, reject);
|
|
749
|
+
}, 0);
|
|
750
|
+
})
|
|
751
|
+
: startExecution();
|
|
752
|
+
entries.set(processId, entry);
|
|
753
|
+
persistRunningReceipt(entry, true);
|
|
754
|
+
|
|
755
|
+
if (entry.interactiveWaitMs > 0) {
|
|
756
|
+
await Promise.race([
|
|
757
|
+
entry.promise,
|
|
758
|
+
new Promise<void>((resolve) => {
|
|
759
|
+
const timer = setTimeout(resolve, entry.interactiveWaitMs);
|
|
760
|
+
timer.unref?.();
|
|
761
|
+
}),
|
|
762
|
+
]);
|
|
763
|
+
}
|
|
764
|
+
const returnedAtMs = Date.now();
|
|
765
|
+
return {
|
|
766
|
+
handle: entryHandle(entry),
|
|
767
|
+
metrics: {
|
|
768
|
+
lane: 'lightweight_managed',
|
|
769
|
+
preSpawnHarnessMs: entry.spawnedAtMs === undefined ? undefined : Math.max(0, entry.spawnedAtMs - entry.startedAtMs),
|
|
770
|
+
childDurationMs: entry.finishedAtMs === undefined || entry.spawnedAtMs === undefined
|
|
771
|
+
? undefined
|
|
772
|
+
: Math.max(0, entry.finishedAtMs - entry.spawnedAtMs),
|
|
773
|
+
interactiveReturnMs: Math.max(0, returnedAtMs - entry.startedAtMs),
|
|
774
|
+
durableWrites: 0,
|
|
775
|
+
leaseOperations: 0,
|
|
776
|
+
},
|
|
777
|
+
};
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
export async function startLightweightInternalProcess(
|
|
781
|
+
input: StartLightweightInternalProcessInput,
|
|
782
|
+
): Promise<{ handle: ProcessHandle; metrics: LightweightCommandMetrics }> {
|
|
783
|
+
sweep();
|
|
784
|
+
const stableCommandId = input.commandId?.trim();
|
|
785
|
+
const requestFingerprint = JSON.stringify({
|
|
786
|
+
repoId: input.repoId,
|
|
787
|
+
executable: input.executable,
|
|
788
|
+
args: input.args,
|
|
789
|
+
cwd: input.cwd,
|
|
790
|
+
timeoutMs: input.timeoutMs,
|
|
791
|
+
});
|
|
792
|
+
if (stableCommandId) {
|
|
793
|
+
const existing = [...entries.values()].find((entry) => (
|
|
794
|
+
entry.controllerHome === input.controllerHome
|
|
795
|
+
&& entry.repoId === input.repoId
|
|
796
|
+
&& entry.commandId === stableCommandId
|
|
797
|
+
));
|
|
798
|
+
if (existing) {
|
|
799
|
+
if (existing.requestFingerprint !== requestFingerprint) {
|
|
800
|
+
throw new Error(`PROCESS_REQUEST_CONFLICT: command id ${stableCommandId} already identifies a different lightweight process`);
|
|
801
|
+
}
|
|
802
|
+
return {
|
|
803
|
+
handle: entryHandle(existing),
|
|
804
|
+
metrics: {
|
|
805
|
+
lane: 'lightweight_managed',
|
|
806
|
+
preSpawnHarnessMs: existing.spawnedAtMs === undefined ? undefined : Math.max(0, existing.spawnedAtMs - existing.startedAtMs),
|
|
807
|
+
childDurationMs: existing.finishedAtMs === undefined || existing.spawnedAtMs === undefined
|
|
808
|
+
? undefined
|
|
809
|
+
: Math.max(0, existing.finishedAtMs - existing.spawnedAtMs),
|
|
810
|
+
interactiveReturnMs: 0,
|
|
811
|
+
durableWrites: 0,
|
|
812
|
+
leaseOperations: 0,
|
|
813
|
+
},
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
const recovered = findPersistedHandleForCommand(
|
|
817
|
+
input.controllerHome,
|
|
818
|
+
input.repoId,
|
|
819
|
+
stableCommandId,
|
|
820
|
+
requestFingerprint,
|
|
821
|
+
);
|
|
822
|
+
if (recovered) return { handle: recovered, metrics: recoveredRequestMetrics() };
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
const processId = `lightweight:${randomUUID()}`;
|
|
826
|
+
const abort = new AbortController();
|
|
827
|
+
const maxOutputBytes = Math.max(1_024, input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES);
|
|
828
|
+
const entry: LightweightEntry = {
|
|
829
|
+
processId,
|
|
830
|
+
controllerHome: input.controllerHome,
|
|
831
|
+
repoId: input.repoId,
|
|
832
|
+
workId: input.workId,
|
|
833
|
+
commandId: stableCommandId || processId,
|
|
834
|
+
requestFingerprint,
|
|
835
|
+
startedAt: new Date().toISOString(),
|
|
836
|
+
startedAtMs: Date.now(),
|
|
837
|
+
interactiveWaitMs: Math.max(0, input.interactiveWaitMs),
|
|
838
|
+
timeoutMs: input.timeoutMs,
|
|
839
|
+
maxOutputBytes,
|
|
840
|
+
stdout: '',
|
|
841
|
+
stderr: '',
|
|
842
|
+
stdoutTail: '',
|
|
843
|
+
stderrTail: '',
|
|
844
|
+
abort,
|
|
845
|
+
promise: undefined as never,
|
|
846
|
+
};
|
|
847
|
+
const onCallerAbort = () => abort.abort();
|
|
848
|
+
input.signal?.addEventListener('abort', onCallerAbort, { once: true });
|
|
849
|
+
entry.promise = runBoundedProcess(input.executable, input.args, {
|
|
850
|
+
cwd: input.cwd,
|
|
851
|
+
env: input.env,
|
|
852
|
+
timeoutMs: input.timeoutMs,
|
|
853
|
+
maxOutputBytes,
|
|
854
|
+
signal: abort.signal,
|
|
855
|
+
onSpawn: (pid) => {
|
|
856
|
+
entry.pid = pid;
|
|
857
|
+
entry.spawnedAtMs = Date.now();
|
|
858
|
+
entry.identity = captureProcessIdentity(pid);
|
|
859
|
+
persistRunningReceipt(entry, true);
|
|
860
|
+
},
|
|
861
|
+
onStdout: (chunk) => {
|
|
862
|
+
entry.stdout = boundedAppend(entry.stdout, chunk, maxOutputBytes);
|
|
863
|
+
entry.stdoutTail = boundedTailAppend(entry.stdoutTail, chunk);
|
|
864
|
+
persistRunningReceipt(entry);
|
|
865
|
+
},
|
|
866
|
+
onStderr: (chunk) => {
|
|
867
|
+
entry.stderr = boundedAppend(entry.stderr, chunk, maxOutputBytes);
|
|
868
|
+
entry.stderrTail = boundedTailAppend(entry.stderrTail, chunk);
|
|
869
|
+
persistRunningReceipt(entry);
|
|
870
|
+
},
|
|
871
|
+
}).then((result) => {
|
|
872
|
+
entry.result = result;
|
|
873
|
+
entry.finishedAtMs = Date.now();
|
|
874
|
+
input.signal?.removeEventListener('abort', onCallerAbort);
|
|
875
|
+
persistTerminalReceipt(input.controllerHome, entry);
|
|
876
|
+
return result;
|
|
877
|
+
});
|
|
878
|
+
entries.set(processId, entry);
|
|
879
|
+
persistRunningReceipt(entry, true);
|
|
880
|
+
|
|
881
|
+
if (entry.interactiveWaitMs > 0) {
|
|
882
|
+
await Promise.race([
|
|
883
|
+
entry.promise,
|
|
884
|
+
new Promise<void>((resolve) => {
|
|
885
|
+
const timer = setTimeout(resolve, entry.interactiveWaitMs);
|
|
886
|
+
timer.unref?.();
|
|
887
|
+
}),
|
|
888
|
+
]);
|
|
889
|
+
}
|
|
890
|
+
const returnedAtMs = Date.now();
|
|
891
|
+
return {
|
|
892
|
+
handle: entryHandle(entry),
|
|
893
|
+
metrics: {
|
|
894
|
+
lane: 'lightweight_managed',
|
|
895
|
+
preSpawnHarnessMs: entry.spawnedAtMs === undefined ? undefined : Math.max(0, entry.spawnedAtMs - entry.startedAtMs),
|
|
896
|
+
childDurationMs: entry.finishedAtMs === undefined || entry.spawnedAtMs === undefined
|
|
897
|
+
? undefined
|
|
898
|
+
: Math.max(0, entry.finishedAtMs - entry.spawnedAtMs),
|
|
899
|
+
interactiveReturnMs: Math.max(0, returnedAtMs - entry.startedAtMs),
|
|
900
|
+
durableWrites: 0,
|
|
901
|
+
leaseOperations: 0,
|
|
902
|
+
},
|
|
903
|
+
};
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
export async function startLightweightControllerCheck(
|
|
907
|
+
input: StartLightweightCheckInput,
|
|
908
|
+
): Promise<{ handle: ProcessHandle; metrics: LightweightCommandMetrics }> {
|
|
909
|
+
sweep();
|
|
910
|
+
const stableCommandId = input.commandId?.trim();
|
|
911
|
+
const requestFingerprint = JSON.stringify({
|
|
912
|
+
repoId: input.repoId,
|
|
913
|
+
repoRoot: input.repoRoot,
|
|
914
|
+
checkId: input.checkId,
|
|
915
|
+
timeoutMs: input.timeoutMs,
|
|
916
|
+
});
|
|
917
|
+
if (stableCommandId) {
|
|
918
|
+
const existing = [...entries.values()].find((entry) => (
|
|
919
|
+
entry.controllerHome === input.controllerHome
|
|
920
|
+
&& entry.repoId === input.repoId
|
|
921
|
+
&& entry.commandId === stableCommandId
|
|
922
|
+
));
|
|
923
|
+
if (existing) {
|
|
924
|
+
if (existing.requestFingerprint !== requestFingerprint) {
|
|
925
|
+
throw new Error(`PROCESS_REQUEST_CONFLICT: command id ${stableCommandId} already identifies a different lightweight check`);
|
|
926
|
+
}
|
|
927
|
+
return {
|
|
928
|
+
handle: entryHandle(existing),
|
|
929
|
+
metrics: {
|
|
930
|
+
lane: 'lightweight_managed',
|
|
931
|
+
preSpawnHarnessMs: existing.spawnedAtMs === undefined ? undefined : Math.max(0, existing.spawnedAtMs - existing.startedAtMs),
|
|
932
|
+
childDurationMs: existing.finishedAtMs === undefined || existing.spawnedAtMs === undefined
|
|
933
|
+
? undefined
|
|
934
|
+
: Math.max(0, existing.finishedAtMs - existing.spawnedAtMs),
|
|
935
|
+
interactiveReturnMs: 0,
|
|
936
|
+
durableWrites: 0,
|
|
937
|
+
leaseOperations: 0,
|
|
938
|
+
},
|
|
939
|
+
};
|
|
940
|
+
}
|
|
941
|
+
const recovered = findPersistedHandleForCommand(
|
|
942
|
+
input.controllerHome,
|
|
943
|
+
input.repoId,
|
|
944
|
+
stableCommandId,
|
|
945
|
+
requestFingerprint,
|
|
946
|
+
);
|
|
947
|
+
if (recovered) return { handle: recovered, metrics: recoveredRequestMetrics() };
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
const processId = `lightweight:${randomUUID()}`;
|
|
951
|
+
const abort = new AbortController();
|
|
952
|
+
const entry: LightweightEntry = {
|
|
953
|
+
processId,
|
|
954
|
+
controllerHome: input.controllerHome,
|
|
955
|
+
repoId: input.repoId,
|
|
956
|
+
workId: input.workId,
|
|
957
|
+
commandId: stableCommandId || processId,
|
|
958
|
+
requestFingerprint,
|
|
959
|
+
startedAt: new Date().toISOString(),
|
|
960
|
+
startedAtMs: Date.now(),
|
|
961
|
+
interactiveWaitMs: Math.max(0, input.interactiveWaitMs),
|
|
962
|
+
timeoutMs: input.timeoutMs,
|
|
963
|
+
maxOutputBytes: DEFAULT_MAX_OUTPUT_BYTES,
|
|
964
|
+
stdout: '',
|
|
965
|
+
stderr: '',
|
|
966
|
+
stdoutTail: '',
|
|
967
|
+
stderrTail: '',
|
|
968
|
+
abort,
|
|
969
|
+
promise: undefined as never,
|
|
970
|
+
};
|
|
971
|
+
abort.signal.addEventListener('abort', () => {
|
|
972
|
+
entry.cancelRequested = true;
|
|
973
|
+
releaseControllerCheckSubscription(processId);
|
|
974
|
+
}, { once: true });
|
|
975
|
+
entry.promise = runControllerCheckAsync(input.repoRoot, input.checkId, {
|
|
976
|
+
requestedTimeoutMs: input.timeoutMs,
|
|
977
|
+
subscriberId: processId,
|
|
978
|
+
onSpawn: (pid) => {
|
|
979
|
+
entry.pid = pid;
|
|
980
|
+
entry.spawnedAtMs = Date.now();
|
|
981
|
+
entry.identity = captureProcessIdentity(pid);
|
|
982
|
+
persistRunningReceipt(entry, true);
|
|
983
|
+
},
|
|
984
|
+
}).then((result): LightweightExecutionResult => ({
|
|
985
|
+
ok: result.ok && !entry.cancelRequested,
|
|
986
|
+
exitCode: result.status,
|
|
987
|
+
timedOut: result.timedOut,
|
|
988
|
+
cancelled: entry.cancelRequested,
|
|
989
|
+
stdout: result.stdout,
|
|
990
|
+
stderr: result.stderr,
|
|
991
|
+
})).catch((error): LightweightExecutionResult => ({
|
|
992
|
+
ok: false,
|
|
993
|
+
exitCode: 1,
|
|
994
|
+
cancelled: entry.cancelRequested,
|
|
995
|
+
stderr: redactProcessOutput(error instanceof Error ? error.message : String(error)),
|
|
996
|
+
})).then((result) => {
|
|
997
|
+
entry.result = result;
|
|
998
|
+
entry.finishedAtMs = Date.now();
|
|
999
|
+
persistTerminalReceipt(input.controllerHome, entry);
|
|
1000
|
+
return result;
|
|
1001
|
+
});
|
|
1002
|
+
entries.set(processId, entry);
|
|
1003
|
+
persistRunningReceipt(entry, true);
|
|
1004
|
+
|
|
1005
|
+
if (entry.interactiveWaitMs > 0) {
|
|
1006
|
+
await Promise.race([
|
|
1007
|
+
entry.promise,
|
|
1008
|
+
new Promise<void>((resolve) => {
|
|
1009
|
+
const timer = setTimeout(resolve, entry.interactiveWaitMs);
|
|
1010
|
+
timer.unref?.();
|
|
1011
|
+
}),
|
|
1012
|
+
]);
|
|
1013
|
+
}
|
|
1014
|
+
const returnedAtMs = Date.now();
|
|
1015
|
+
return {
|
|
1016
|
+
handle: entryHandle(entry),
|
|
1017
|
+
metrics: {
|
|
1018
|
+
lane: 'lightweight_managed',
|
|
1019
|
+
preSpawnHarnessMs: entry.spawnedAtMs === undefined ? undefined : Math.max(0, entry.spawnedAtMs - entry.startedAtMs),
|
|
1020
|
+
childDurationMs: entry.finishedAtMs === undefined || entry.spawnedAtMs === undefined
|
|
1021
|
+
? undefined
|
|
1022
|
+
: Math.max(0, entry.finishedAtMs - entry.spawnedAtMs),
|
|
1023
|
+
interactiveReturnMs: Math.max(0, returnedAtMs - entry.startedAtMs),
|
|
1024
|
+
durableWrites: 0,
|
|
1025
|
+
leaseOperations: 0,
|
|
1026
|
+
},
|
|
1027
|
+
};
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
function requireEntry(repoId: string, processId: string): LightweightEntry {
|
|
1031
|
+
const entry = entries.get(processId);
|
|
1032
|
+
if (!entry) throw new Error(`PROCESS_NOT_FOUND: ${processId}`);
|
|
1033
|
+
if (entry.repoId !== repoId) throw new Error(`PROCESS_REPO_MISMATCH: process ${processId} belongs to ${entry.repoId}, not ${repoId}`);
|
|
1034
|
+
return entry;
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
export function isLightweightProcessId(processId: string): boolean {
|
|
1038
|
+
return processId.startsWith('lightweight:');
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
/** Test seam for proving terminal receipt recovery across Runtime-memory loss. */
|
|
1042
|
+
export function clearLightweightProcessMemoryForTest(): void {
|
|
1043
|
+
entries.clear();
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
export function getLightweightProcessHandle(controllerHome: string, repoId: string, processId: string): ProcessHandle | undefined {
|
|
1047
|
+
const entry = entries.get(processId);
|
|
1048
|
+
if (entry?.repoId === repoId) return entryHandle(entry);
|
|
1049
|
+
const terminal = readTerminalReceipt(controllerHome, repoId, processId);
|
|
1050
|
+
if (terminal) return terminal.handle;
|
|
1051
|
+
const running = readRunningReceipt(controllerHome, repoId, processId);
|
|
1052
|
+
if (!running) return undefined;
|
|
1053
|
+
if (running.exitObservation) {
|
|
1054
|
+
return persistRecoveredTerminalReceipt(controllerHome, running, completedObservedExitHandle(running));
|
|
1055
|
+
}
|
|
1056
|
+
const inspection = inspectRecoveredRunningReceipt(running);
|
|
1057
|
+
const failureReason = recoveredInspectionFailureReason(inspection);
|
|
1058
|
+
if (failureReason) {
|
|
1059
|
+
return persistRecoveredTerminalReceipt(controllerHome, running, deterministicRecoveryFailureHandle(running, failureReason));
|
|
1060
|
+
}
|
|
1061
|
+
return recoveredRunningHandle(running);
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
export async function waitForLightweightProcess(
|
|
1065
|
+
controllerHome: string,
|
|
1066
|
+
repoId: string,
|
|
1067
|
+
processId: string,
|
|
1068
|
+
options: WaitProcessOptions = {},
|
|
1069
|
+
): Promise<ProcessHandle> {
|
|
1070
|
+
const entry = entries.get(processId);
|
|
1071
|
+
if (!entry) {
|
|
1072
|
+
const terminal = readTerminalReceipt(controllerHome, repoId, processId);
|
|
1073
|
+
if (terminal) return terminal.handle;
|
|
1074
|
+
let running = readRunningReceipt(controllerHome, repoId, processId);
|
|
1075
|
+
if (!running) throw new Error(`PROCESS_NOT_FOUND: ${processId}`);
|
|
1076
|
+
const timeoutMs = Math.max(1, options.timeoutMs ?? 15_000);
|
|
1077
|
+
const deadline = Date.now() + timeoutMs;
|
|
1078
|
+
while (true) {
|
|
1079
|
+
const recoveredTerminal = readTerminalReceipt(controllerHome, repoId, processId);
|
|
1080
|
+
if (recoveredTerminal) return recoveredTerminal.handle;
|
|
1081
|
+
if (running.exitObservation) {
|
|
1082
|
+
return persistRecoveredTerminalReceipt(controllerHome, running, completedObservedExitHandle(running));
|
|
1083
|
+
}
|
|
1084
|
+
const inspection = inspectRecoveredRunningReceipt(running);
|
|
1085
|
+
const failureReason = recoveredInspectionFailureReason(inspection);
|
|
1086
|
+
if (failureReason) {
|
|
1087
|
+
return persistRecoveredTerminalReceipt(controllerHome, running, deterministicRecoveryFailureHandle(running, failureReason));
|
|
1088
|
+
}
|
|
1089
|
+
if (options.signal?.aborted || Date.now() >= deadline) {
|
|
1090
|
+
return recoveredRunningHandle(running);
|
|
1091
|
+
}
|
|
1092
|
+
await new Promise<void>((resolve) => {
|
|
1093
|
+
const timer = setTimeout(resolve, Math.min(50, Math.max(1, deadline - Date.now())));
|
|
1094
|
+
timer.unref?.();
|
|
1095
|
+
});
|
|
1096
|
+
running = readRunningReceipt(controllerHome, repoId, processId) ?? running;
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
if (entry.repoId !== repoId) throw new Error(`PROCESS_REPO_MISMATCH: process ${processId} belongs to ${entry.repoId}, not ${repoId}`);
|
|
1100
|
+
if (entry.result) return entryHandle(entry);
|
|
1101
|
+
const timeoutMs = Math.max(1, options.timeoutMs ?? 15_000);
|
|
1102
|
+
await Promise.race([
|
|
1103
|
+
entry.promise,
|
|
1104
|
+
new Promise<void>((resolve) => {
|
|
1105
|
+
const timer = setTimeout(resolve, timeoutMs);
|
|
1106
|
+
timer.unref?.();
|
|
1107
|
+
options.signal?.addEventListener('abort', () => resolve(), { once: true });
|
|
1108
|
+
}),
|
|
1109
|
+
]);
|
|
1110
|
+
return entryHandle(entry);
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
export async function cancelAllLightweightProcesses(controllerHome: string): Promise<number> {
|
|
1114
|
+
const active = [...entries.values()].filter((entry) => entry.controllerHome === controllerHome && entry.result === undefined);
|
|
1115
|
+
await Promise.allSettled(active.map(async (entry) => {
|
|
1116
|
+
entry.cancelRequested = true;
|
|
1117
|
+
entry.abort.abort();
|
|
1118
|
+
await entry.promise;
|
|
1119
|
+
}));
|
|
1120
|
+
return active.length;
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
export async function cancelLightweightProcess(controllerHome: string, repoId: string, processId: string): Promise<ProcessHandle> {
|
|
1124
|
+
const entry = entries.get(processId);
|
|
1125
|
+
if (!entry) {
|
|
1126
|
+
const terminal = readTerminalReceipt(controllerHome, repoId, processId);
|
|
1127
|
+
if (terminal) return terminal.handle;
|
|
1128
|
+
const running = readRunningReceipt(controllerHome, repoId, processId);
|
|
1129
|
+
if (!running) throw new Error(`PROCESS_NOT_FOUND: ${processId}`);
|
|
1130
|
+
if (running.exitObservation) {
|
|
1131
|
+
return persistRecoveredTerminalReceipt(controllerHome, running, completedObservedExitHandle(running));
|
|
1132
|
+
}
|
|
1133
|
+
const inspection = inspectRecoveredRunningReceipt(running);
|
|
1134
|
+
const failureReason = recoveredInspectionFailureReason(inspection);
|
|
1135
|
+
if (failureReason) {
|
|
1136
|
+
return persistRecoveredTerminalReceipt(controllerHome, running, deterministicRecoveryFailureHandle(running, failureReason));
|
|
1137
|
+
}
|
|
1138
|
+
const pid = running.handle.pid ?? running.identity?.pid;
|
|
1139
|
+
if (!pid) throw new Error(`PROCESS_IDENTITY_UNTRUSTED: refusing to signal ${processId}: pid missing`);
|
|
1140
|
+
await terminateProcessTree(pid, { gracePeriodMs: 200, killAfterMs: 1_000, pollIntervalMs: 25 });
|
|
1141
|
+
return persistRecoveredTerminalReceipt(controllerHome, running, cancelledRecoveredHandle(running));
|
|
1142
|
+
}
|
|
1143
|
+
if (entry.repoId !== repoId) throw new Error(`PROCESS_REPO_MISMATCH: process ${processId} belongs to ${entry.repoId}, not ${repoId}`);
|
|
1144
|
+
if (!entry.result) {
|
|
1145
|
+
entry.abort.abort();
|
|
1146
|
+
await entry.promise;
|
|
1147
|
+
}
|
|
1148
|
+
return entryHandle(entry);
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
export function readLightweightProcessLogs(
|
|
1152
|
+
controllerHome: string,
|
|
1153
|
+
repoId: string,
|
|
1154
|
+
processId: string,
|
|
1155
|
+
maxBytes = 32 * 1024,
|
|
1156
|
+
): ProcessLogSlice | undefined {
|
|
1157
|
+
const entry = entries.get(processId);
|
|
1158
|
+
if (!entry) {
|
|
1159
|
+
const terminal = readTerminalReceipt(controllerHome, repoId, processId);
|
|
1160
|
+
if (terminal) {
|
|
1161
|
+
const stdout = capProcessOutput(terminal.handle.stdout ?? '', maxBytes);
|
|
1162
|
+
const stderr = capProcessOutput(terminal.handle.stderr ?? '', maxBytes);
|
|
1163
|
+
return {
|
|
1164
|
+
processId,
|
|
1165
|
+
stdout,
|
|
1166
|
+
stderr,
|
|
1167
|
+
stdoutBytes: Buffer.byteLength(terminal.handle.stdout ?? '', 'utf8'),
|
|
1168
|
+
stderrBytes: Buffer.byteLength(terminal.handle.stderr ?? '', 'utf8'),
|
|
1169
|
+
truncated: Buffer.byteLength(terminal.handle.stdout ?? '', 'utf8') > maxBytes
|
|
1170
|
+
|| Buffer.byteLength(terminal.handle.stderr ?? '', 'utf8') > maxBytes,
|
|
1171
|
+
};
|
|
1172
|
+
}
|
|
1173
|
+
const running = readRunningReceipt(controllerHome, repoId, processId);
|
|
1174
|
+
if (!running) return undefined;
|
|
1175
|
+
const stdout = capProcessOutput(running.handle.stdoutTail ?? '', maxBytes);
|
|
1176
|
+
const stderr = capProcessOutput(running.handle.stderrTail ?? '', maxBytes);
|
|
1177
|
+
return {
|
|
1178
|
+
processId,
|
|
1179
|
+
stdout,
|
|
1180
|
+
stderr,
|
|
1181
|
+
stdoutBytes: Buffer.byteLength(running.handle.stdoutTail ?? '', 'utf8'),
|
|
1182
|
+
stderrBytes: Buffer.byteLength(running.handle.stderrTail ?? '', 'utf8'),
|
|
1183
|
+
truncated: Buffer.byteLength(running.handle.stdoutTail ?? '', 'utf8') > maxBytes
|
|
1184
|
+
|| Buffer.byteLength(running.handle.stderrTail ?? '', 'utf8') > maxBytes,
|
|
1185
|
+
};
|
|
1186
|
+
}
|
|
1187
|
+
if (entry.repoId !== repoId) return undefined;
|
|
1188
|
+
const rawStdout = entry.result?.stdout ?? entry.stdout;
|
|
1189
|
+
const rawStderr = entry.result?.stderr ?? entry.stderr;
|
|
1190
|
+
const visibleStdout = visibleOutput(rawStdout, maxBytes);
|
|
1191
|
+
const visibleStderr = visibleOutput(rawStderr, maxBytes);
|
|
1192
|
+
return {
|
|
1193
|
+
processId,
|
|
1194
|
+
stdout: visibleStdout,
|
|
1195
|
+
stderr: visibleStderr,
|
|
1196
|
+
stdoutBytes: Buffer.byteLength(visibleStdout, 'utf8'),
|
|
1197
|
+
stderrBytes: Buffer.byteLength(visibleStderr, 'utf8'),
|
|
1198
|
+
truncated: Buffer.byteLength(visibleStdout, 'utf8') > maxBytes
|
|
1199
|
+
|| Buffer.byteLength(visibleStderr, 'utf8') > maxBytes,
|
|
1200
|
+
};
|
|
1201
|
+
}
|