pi-better-server 0.5.0 → 0.7.0
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/package.json +7 -3
- package/scripts/copy-pi-test-providers.mjs +10 -0
- package/scripts/event-publication/README.md +26 -0
- package/scripts/event-publication/commit.mjs +21 -0
- package/scripts/event-publication/measure.mjs +37 -5
- package/scripts/event-publication/writer.mjs +3 -8
- package/scripts/measure-full-runtime/frontend.ts +10 -2
- package/scripts/measure-full-runtime/probe.mjs +4 -2
- package/scripts/measure-full-runtime/recovery-trace-loader.mjs +51 -0
- package/scripts/measure-full-runtime/recovery-trace.mjs +16 -0
- package/scripts/measure-full-runtime.mjs +2 -0
- package/scripts/measure-shared-reads.mjs +2 -1
- package/scripts/private-runtime/package-lock.json +18 -0
- package/scripts/private-runtime/package.json +4 -1
- package/scripts/source-provenance.mjs +2 -2
- package/scripts/test-on-pi.sh +2 -9
- package/src/handshake.ts +1 -1
- package/src/hosted-session.ts +32 -4
- package/src/maintenance.ts +35 -7
- package/src/registry.ts +28 -4
- package/src/runtime/attempt-invalidation.ts +54 -0
- package/src/runtime/background-history.ts +151 -45
- package/src/runtime/background-policy.ts +9 -4
- package/src/runtime/background-tools.ts +181 -27
- package/src/runtime/background.ts +365 -70
- package/src/runtime/cancellation.ts +28 -7
- package/src/runtime/catalog-sources.ts +199 -0
- package/src/runtime/catalog.ts +53 -21
- package/src/runtime/client.ts +22 -2
- package/src/runtime/domain/assignment-inbox.mjs +119 -0
- package/src/runtime/domain/assignment-observation.d.mts +1 -1
- package/src/runtime/domain/assignment-observation.mjs +43 -35
- package/src/runtime/domain/background/process-identity.mjs +20 -2
- package/src/runtime/domain/background/process.mjs +52 -14
- package/src/runtime/domain/background/registry.mjs +61 -3
- package/src/runtime/domain/background/supervisor/store.mjs +3 -3
- package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -3
- package/src/runtime/domain/background/types.mjs +1 -0
- package/src/runtime/domain/background-service/adapter-contract.domain.mjs +1 -1
- package/src/runtime/domain/background-service/adapter-contract.ts +1 -1
- package/src/runtime/domain/background-service/goal-provider.domain.mjs +35 -16
- package/src/runtime/domain/background-service/goal-provider.ts +31 -16
- package/src/runtime/domain/background-service/index.domain.mjs +25 -9
- package/src/runtime/domain/background-service/index.ts +25 -9
- package/src/runtime/domain/background-service/managed-authority.domain.mjs +6 -3
- package/src/runtime/domain/background-service/managed-authority.ts +5 -3
- package/src/runtime/domain/background-service/managed-client.domain.mjs +21 -7
- package/src/runtime/domain/background-service/managed-client.ts +20 -7
- package/src/runtime/domain/background-service/managed-frontend.domain.mjs +159 -19
- package/src/runtime/domain/background-service/managed-frontend.ts +135 -19
- package/src/runtime/domain/background-service/navigator-provider.domain.mjs +21 -5
- package/src/runtime/domain/background-service/navigator-provider.ts +19 -5
- package/src/runtime/domain/background-service/observed-wait-client.domain.mjs +6 -0
- package/src/runtime/domain/background-service/observed-wait-client.ts +10 -0
- package/src/runtime/domain/background-service/observed-waits.domain.mjs +372 -57
- package/src/runtime/domain/background-service/observed-waits.ts +321 -53
- package/src/runtime/domain/background-service/process-identity.domain.mjs +20 -2
- package/src/runtime/domain/background-service/process-identity.ts +18 -2
- package/src/runtime/domain/background-service/process.domain.mjs +52 -14
- package/src/runtime/domain/background-service/process.ts +48 -14
- package/src/runtime/domain/background-service/registry.domain.mjs +61 -3
- package/src/runtime/domain/background-service/registry.ts +53 -5
- package/src/runtime/domain/background-service/review-settings.domain.mjs +16 -0
- package/src/runtime/domain/background-service/review-settings.ts +18 -0
- package/src/runtime/domain/background-service/runtime.domain.mjs +40 -86
- package/src/runtime/domain/background-service/runtime.ts +27 -82
- package/src/runtime/domain/background-service/sandbox.domain.mjs +14 -15
- package/src/runtime/domain/background-service/sandbox.ts +14 -11
- package/src/runtime/domain/background-service/shared-callback-batcher.domain.mjs +8 -1
- package/src/runtime/domain/background-service/shared-callback-batcher.ts +11 -2
- package/src/runtime/domain/background-service/shared-navigator-panels.domain.mjs +24 -2
- package/src/runtime/domain/background-service/shared-navigator-panels.ts +26 -4
- package/src/runtime/domain/background-service/shared-navigator.domain.mjs +273 -41
- package/src/runtime/domain/background-service/shared-navigator.ts +244 -40
- package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +144 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +53 -41
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +73 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.ts +14 -3
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +5 -3
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +44 -4
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +50 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +12 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.domain.mjs +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.ts +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +42 -21
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +40 -24
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +26 -4
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +40 -8
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.ts +24 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.domain.mjs +1 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.ts +5 -1
- package/src/runtime/domain/background-service/shared-sandbox-core.ts +1 -1
- package/src/runtime/domain/background-service/shared-work-client.mjs +174 -7
- package/src/runtime/domain/background-service/stall.domain.mjs +5 -3
- package/src/runtime/domain/background-service/stall.ts +7 -4
- package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
- package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
- package/src/runtime/domain/background-service/supervisor/README.md +1 -4
- package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
- package/src/runtime/domain/background-service/supervisor/generated/process-identity.mjs +20 -2
- package/src/runtime/domain/background-service/supervisor/generated/process.mjs +52 -14
- package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
- package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
- package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
- package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
- package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
- package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
- package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
- package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
- package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -3
- package/src/runtime/domain/background-service/task-diagnostics.domain.mjs +1 -1
- package/src/runtime/domain/background-service/task-diagnostics.ts +1 -1
- package/src/runtime/domain/background-service/tools.domain.mjs +53 -40
- package/src/runtime/domain/background-service/tools.ts +67 -54
- package/src/runtime/domain/background-service/types.domain.mjs +1 -0
- package/src/runtime/domain/background-service/types.ts +7 -3
- package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
- package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
- package/src/runtime/domain/background-service/work-observation.domain.mjs +46 -20
- package/src/runtime/domain/background-service/work-observation.ts +46 -19
- package/src/runtime/domain/catalog/catalog-store.d.mts +9 -1
- package/src/runtime/domain/catalog/catalog-store.mjs +20 -22
- package/src/runtime/domain/coordinator/src/assignment-changes.mjs +75 -0
- package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +2 -0
- package/src/runtime/domain/coordinator/src/background-requests.mjs +11 -2
- package/src/runtime/domain/coordinator/src/discovery.mjs +4 -2
- package/src/runtime/domain/coordinator/src/operations.mjs +44 -4
- package/src/runtime/domain/coordinator/src/outbox.mjs +7 -0
- package/src/runtime/domain/coordinator/src/result-supervision.mjs +12 -0
- package/src/runtime/domain/coordinator/src/rows.mjs +2 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +42 -21
- package/src/runtime/domain/coordinator/src/store.mjs +26 -4
- package/src/runtime/domain/coordinator/src/subagent-launch.mjs +23 -1
- package/src/runtime/domain/coordinator/src/types.mjs +1 -1
- package/src/runtime/domain/health-observation.d.mts +3 -1
- package/src/runtime/domain/health-observation.mjs +189 -190
- package/src/runtime/domain/log-cursor.d.mts +2 -0
- package/src/runtime/domain/log-cursor.mjs +85 -16
- package/src/runtime/domain/log-paths.mjs +8 -1
- package/src/runtime/domain/parse.d.mts +4 -1
- package/src/runtime/domain/parse.mjs +58 -9
- package/src/runtime/domain/sandbox-policy/README.md +63 -65
- package/src/runtime/domain/sandbox-policy/commands.domain.mjs +11 -8
- package/src/runtime/domain/sandbox-policy/commands.ts +12 -7
- package/src/runtime/domain/sandbox-policy/index.domain.mjs +53 -9
- package/src/runtime/domain/sandbox-policy/index.ts +52 -9
- package/src/runtime/domain/sandbox-policy/package.json +1 -1
- package/src/runtime/domain/sandbox-policy/permission-settings.domain.mjs +5 -2
- package/src/runtime/domain/sandbox-policy/permission-settings.ts +9 -2
- package/src/runtime/domain/sandbox-policy/permissions-page.domain.mjs +56 -137
- package/src/runtime/domain/sandbox-policy/permissions-page.ts +52 -130
- package/src/runtime/domain/sandbox-policy/permissions.domain.mjs +1 -6
- package/src/runtime/domain/sandbox-policy/permissions.ts +1 -6
- package/src/runtime/domain/sandbox-policy/shared-sandbox-core.ts +1 -1
- package/src/runtime/domain/sandbox-policy/shared-task-exec.domain.mjs +14 -1
- package/src/runtime/domain/sandbox-policy/shared-task-exec.ts +12 -1
- package/src/runtime/domain/sandbox-policy/shared-task-process-identity.domain.mjs +140 -0
- package/src/runtime/domain/sandbox-policy/shared-task-process-identity.ts +126 -0
- package/src/runtime/domain/sandbox-policy/shared-task-process-list.domain.mjs +3 -2
- package/src/runtime/domain/sandbox-policy/shared-task-process-list.ts +8 -2
- package/src/runtime/domain/sandbox-policy/shared-task-sandbox.domain.mjs +4 -3
- package/src/runtime/domain/sandbox-policy/shared-task-sandbox.ts +5 -3
- package/src/runtime/domain/sandbox-policy/shared-task-tools.domain.mjs +8 -5
- package/src/runtime/domain/sandbox-policy/shared-task-tools.ts +8 -5
- package/src/runtime/domain/session-store.mjs +7 -0
- package/src/runtime/domain/subagents/README.md +13 -11
- package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +10 -7
- package/src/runtime/domain/subagents/assignment-outcomes.ts +9 -6
- package/src/runtime/domain/subagents/assignment-report.domain.mjs +109 -24
- package/src/runtime/domain/subagents/assignment-report.ts +103 -19
- package/src/runtime/domain/subagents/batch.mjs +13 -5
- package/src/runtime/domain/subagents/catalog-host-admission.domain.mjs +21 -3
- package/src/runtime/domain/subagents/catalog-host-admission.ts +19 -3
- package/src/runtime/domain/subagents/catalog-preferences.ts +1 -1
- package/src/runtime/domain/subagents/catalog-resolver.domain.mjs +35 -1
- package/src/runtime/domain/subagents/catalog-resolver.ts +35 -1
- package/src/runtime/domain/subagents/catalog-store.domain.mjs +20 -22
- package/src/runtime/domain/subagents/catalog-store.ts +27 -20
- package/src/runtime/domain/subagents/child-apply-patch.domain.mjs +13 -0
- package/src/runtime/domain/subagents/child-apply-patch.ts +13 -0
- package/src/runtime/domain/subagents/child-dependencies.mjs +27 -15
- package/src/runtime/domain/subagents/child-operations.domain.mjs +80 -2
- package/src/runtime/domain/subagents/child-operations.ts +80 -1
- package/src/runtime/domain/subagents/child-preflight.mjs +9 -2
- package/src/runtime/domain/subagents/child-process-list.domain.mjs +7 -0
- package/src/runtime/domain/subagents/child-process-list.ts +8 -0
- package/src/runtime/domain/subagents/cleanup.domain.mjs +11 -2
- package/src/runtime/domain/subagents/cleanup.ts +10 -2
- package/src/runtime/domain/subagents/config.domain.mjs +54 -2
- package/src/runtime/domain/subagents/config.ts +53 -3
- package/src/runtime/domain/subagents/continuation-authority.domain.mjs +5 -1
- package/src/runtime/domain/subagents/continuation-authority.ts +3 -1
- package/src/runtime/domain/subagents/continuation-runtime.domain.mjs +89 -0
- package/src/runtime/domain/subagents/continuation-runtime.ts +88 -0
- package/src/runtime/domain/subagents/continuation.domain.mjs +4 -2
- package/src/runtime/domain/subagents/continuation.ts +4 -2
- package/src/runtime/domain/subagents/extensions.mjs +11 -13
- package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
- package/src/runtime/domain/subagents/failures.ts +10 -2
- package/src/runtime/domain/subagents/finalization.domain.mjs +16 -1
- package/src/runtime/domain/subagents/finalization.ts +21 -1
- package/src/runtime/domain/subagents/goal-provider.domain.mjs +44 -2
- package/src/runtime/domain/subagents/goal-provider.ts +44 -2
- package/src/runtime/domain/subagents/health-observation.domain.mjs +189 -190
- package/src/runtime/domain/subagents/health-observation.ts +43 -48
- package/src/runtime/domain/subagents/index.domain.mjs +457 -182
- package/src/runtime/domain/subagents/index.ts +417 -155
- package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +515 -0
- package/src/runtime/domain/subagents/isolated-workspace.ts +557 -0
- package/src/runtime/domain/subagents/launch-context.domain.mjs +24 -0
- package/src/runtime/domain/subagents/launch-context.ts +23 -0
- package/src/runtime/domain/subagents/launch-digest.mjs +6 -0
- package/src/runtime/domain/subagents/list.mjs +2 -2
- package/src/runtime/domain/subagents/log-cursor.domain.mjs +85 -16
- package/src/runtime/domain/subagents/log-cursor.ts +91 -15
- package/src/runtime/domain/subagents/managed-launch-bootstrap.mjs +2 -2
- package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +27 -7
- package/src/runtime/domain/subagents/managed-launch-client.ts +28 -8
- package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +222 -14
- package/src/runtime/domain/subagents/managed-launch-host.ts +168 -15
- package/src/runtime/domain/subagents/managed-launch-journal.mjs +1 -5
- package/src/runtime/domain/subagents/managed-launch-port.ts +4 -0
- package/src/runtime/domain/subagents/operation-bridge-types.domain.mjs +27 -2
- package/src/runtime/domain/subagents/operation-bridge-types.ts +27 -2
- package/src/runtime/domain/subagents/output-payload.domain.mjs +24 -9
- package/src/runtime/domain/subagents/output-payload.ts +26 -12
- package/src/runtime/domain/subagents/owned-exit.domain.mjs +12 -0
- package/src/runtime/domain/subagents/owned-exit.ts +12 -0
- package/src/runtime/domain/subagents/package.json +4 -2
- package/src/runtime/domain/subagents/parse.domain.mjs +58 -9
- package/src/runtime/domain/subagents/parse.ts +57 -10
- package/src/runtime/domain/subagents/permission-policy.domain.mjs +32 -8
- package/src/runtime/domain/subagents/permission-policy.ts +41 -8
- package/src/runtime/domain/subagents/process-identity.mjs +33 -0
- package/src/runtime/domain/subagents/registry.domain.mjs +71 -51
- package/src/runtime/domain/subagents/registry.ts +77 -38
- package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
- package/src/runtime/domain/subagents/retained-result.ts +65 -0
- package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
- package/src/runtime/domain/subagents/session-selection.ts +2 -1
- package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
- package/src/runtime/domain/subagents/session-store.ts +9 -0
- package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
- package/src/runtime/domain/subagents/settings-page.ts +147 -108
- package/src/runtime/domain/subagents/shared-callback-batcher.domain.mjs +8 -1
- package/src/runtime/domain/subagents/shared-callback-batcher.ts +11 -2
- package/src/runtime/domain/subagents/shared-catalog.domain.mjs +28 -29
- package/src/runtime/domain/subagents/shared-catalog.ts +29 -21
- package/src/runtime/domain/subagents/shared-navigator-panels.domain.mjs +24 -2
- package/src/runtime/domain/subagents/shared-navigator-panels.ts +26 -4
- package/src/runtime/domain/subagents/shared-navigator.domain.mjs +273 -41
- package/src/runtime/domain/subagents/shared-navigator.ts +244 -40
- package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +144 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +53 -41
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +73 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.ts +14 -3
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +5 -3
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +44 -4
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +50 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +12 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.domain.mjs +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.ts +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +42 -21
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +40 -24
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +26 -4
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +40 -8
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.ts +24 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.domain.mjs +1 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.ts +5 -1
- package/src/runtime/domain/subagents/shared-sandbox-core.ts +1 -1
- package/src/runtime/domain/subagents/shared-task-exec.domain.mjs +14 -1
- package/src/runtime/domain/subagents/shared-task-exec.ts +12 -1
- package/src/runtime/domain/subagents/shared-task-process-identity.domain.mjs +140 -0
- package/src/runtime/domain/subagents/shared-task-process-identity.ts +126 -0
- package/src/runtime/domain/subagents/shared-task-process-list.domain.mjs +3 -2
- package/src/runtime/domain/subagents/shared-task-process-list.ts +8 -2
- package/src/runtime/domain/subagents/shared-task-sandbox.domain.mjs +4 -3
- package/src/runtime/domain/subagents/shared-task-sandbox.ts +5 -3
- package/src/runtime/domain/subagents/shared-task-tools.domain.mjs +8 -5
- package/src/runtime/domain/subagents/shared-task-tools.ts +8 -5
- package/src/runtime/domain/subagents/shared-work-client.mjs +174 -7
- package/src/runtime/domain/subagents/subagent-tools.domain.mjs +22 -38
- package/src/runtime/domain/subagents/subagent-tools.ts +28 -34
- package/src/runtime/domain/subagents/task-guard.domain.mjs +14 -1
- package/src/runtime/domain/subagents/task-guard.ts +13 -1
- package/src/runtime/domain/subagents/task-policy.domain.mjs +3 -2
- package/src/runtime/domain/subagents/task-policy.ts +8 -2
- package/src/runtime/domain/subagents/timing.domain.mjs +10 -1
- package/src/runtime/domain/subagents/timing.ts +10 -1
- package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
- package/src/runtime/domain/subagents/tools.ts +4 -7
- package/src/runtime/domain/subagents/work-observation.domain.mjs +102 -17
- package/src/runtime/domain/subagents/work-observation.ts +91 -17
- package/src/runtime/domain/subagents/worker-operations-host.domain.mjs +9 -4
- package/src/runtime/domain/subagents/worker-operations-host.ts +12 -4
- package/src/runtime/domain/subagents/worker-waits.domain.mjs +89 -35
- package/src/runtime/domain/subagents/worker-waits.ts +93 -34
- package/src/runtime/domain/subagents/workspace-files.domain.mjs +103 -0
- package/src/runtime/domain/subagents/workspace-files.ts +114 -0
- package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
- package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
- package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
- package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
- package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
- package/src/runtime/health-config.ts +27 -11
- package/src/runtime/log-checkpoints.ts +117 -0
- package/src/runtime/mutation-store.ts +5 -4
- package/src/runtime/queries.ts +25 -2
- package/src/runtime/query-executor.ts +149 -28
- package/src/runtime/query-worker.mjs +106 -21
- package/src/runtime/read-model.ts +849 -121
- package/src/runtime/read-watchdog-probe.ts +4 -0
- package/src/runtime/result-supervision.ts +188 -16
- package/src/runtime/root.ts +5 -2
- package/src/runtime/source-watch.ts +175 -0
- package/src/runtime/subagent-launch.ts +11 -4
- package/src/runtime/work-budget.ts +130 -0
- package/src/runtime/work-client.d.mts +8 -0
- package/src/runtime/work-client.mjs +150 -7
- package/src/server.ts +104 -23
- package/src/session-activity.ts +26 -4
- package/src/version.ts +1 -1
|
@@ -1,28 +1,52 @@
|
|
|
1
1
|
import { processMatchesStart } from "../daemon-owner.ts";
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
|
-
import { readFileSync, statSync } from "node:fs";
|
|
3
|
+
import { readFileSync, statSync, mkdirSync, watch, type FSWatcher } from "node:fs";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
6
6
|
// @ts-expect-error Generated canonical passive runner observation.
|
|
7
7
|
import { snapshot } from "./domain/background/snapshot.mjs";
|
|
8
8
|
// @ts-expect-error Generated canonical registry queries.
|
|
9
|
-
import { observeMetasForOrigin, belongsToOrigin, readMeta } from "./domain/background/registry.mjs";
|
|
9
|
+
import { observeMetasForOrigin, observeRecentMetasForOrigin, recentMetaDeadline, observationRevisionForOrigin, belongsToOrigin, readMeta, getRegistryIoMetrics } from "./domain/background/registry.mjs";
|
|
10
|
+
// @ts-expect-error Generated canonical progress policy.
|
|
11
|
+
import { supervisedProgress } from "./domain/background-service/supervised-progress.domain.mjs";
|
|
10
12
|
import { BackgroundHistory } from "./background-history.ts";
|
|
11
13
|
import type { WorkScope } from "./read-model.ts";
|
|
14
|
+
import { ENTITY_BUDGET } from "./work-budget.ts";
|
|
15
|
+
import { isSqliteLockContention } from "./log-checkpoints.ts";
|
|
16
|
+
// @ts-expect-error Shared durable observation inbox, not execution authority.
|
|
17
|
+
import { AssignmentInbox } from "./domain/assignment-inbox.mjs";
|
|
12
18
|
|
|
13
19
|
type BackgroundScope = { origin: { cwd: string; sessionId?: string }; rows: any[]; references: number;
|
|
14
20
|
pending: any[]; pendingRevision?: number; recent: any[]; recentRevision?: number };
|
|
15
21
|
const DISCOVERY_PAGE_SIZE = 256;
|
|
22
|
+
const malformedHistoryContext = Symbol("malformed terminal history context");
|
|
16
23
|
|
|
17
24
|
/** Root-owned query connection; never opens a supervisor or mutates source facts. */
|
|
18
25
|
export class BackgroundObservation {
|
|
19
26
|
private ownDb: any;
|
|
20
27
|
private readConnection?: (refresh?: boolean) => any;
|
|
21
28
|
private get db(): any { return this.readConnection ? this.readConnection(false) : this.ownDb; }
|
|
29
|
+
private get observationActive() { return Boolean(this.db?.observationActive); }
|
|
22
30
|
private identity?: string;
|
|
23
31
|
private knownCoordinator = false;
|
|
24
32
|
private rows: any[] = [];
|
|
25
|
-
private terminalProjections = new Map<string, { version: string; row: any }>();
|
|
33
|
+
private terminalProjections = new Map<string, { version: string; authority: string; operation: any; inspection: any; row: any; dependencyVersion?: number }>();
|
|
34
|
+
private hasInputVersions = false;
|
|
35
|
+
private inbox: any;
|
|
36
|
+
private indexDb: any;
|
|
37
|
+
private initialized = false;
|
|
38
|
+
get ready() { return this.initialized && !this.closed; }
|
|
39
|
+
private dirtyOperations = new Set<string>();
|
|
40
|
+
private scopeVersions = new Map<string, number>();
|
|
41
|
+
private watchers = new Map<string, FSWatcher>();
|
|
42
|
+
private repairAfter = "";
|
|
43
|
+
private repairIds = new Set<string>();
|
|
44
|
+
private changedOperations = new Map<string, any>();
|
|
45
|
+
private scheduled = false;
|
|
46
|
+
private expiry?: ReturnType<typeof setTimeout>;
|
|
47
|
+
private closed = false;
|
|
48
|
+
private repairComplete = false;
|
|
49
|
+
private changed: () => void;
|
|
26
50
|
private signature = "";
|
|
27
51
|
private root: string;
|
|
28
52
|
private directory: string;
|
|
@@ -32,24 +56,67 @@ export class BackgroundObservation {
|
|
|
32
56
|
private legacy = new Map<string, BackgroundScope>();
|
|
33
57
|
private recentRevision?: number;
|
|
34
58
|
private recent: any[] = [];
|
|
35
|
-
status: "ready" | "degraded" = "
|
|
59
|
+
status: "ready" | "rebuilding" | "degraded" = "rebuilding";
|
|
36
60
|
reason?: string;
|
|
37
61
|
get connectionCount() { return this.readConnection ? 0 : this.ownDb ? 1 : 0; }
|
|
38
62
|
get scopeCount() { return this.legacy.size; }
|
|
63
|
+
prepareQuery(): void {
|
|
64
|
+
if (!this.ready) return;
|
|
65
|
+
if (this.observationActive) return;
|
|
66
|
+
if (!this.enabled || !this.db || !this.hasInputVersions) return;
|
|
67
|
+
// Native mutations can commit between the last scheduled observation and
|
|
68
|
+
// the next list. Reuse the durable bounded inbox before cache validation.
|
|
69
|
+
const batch = this.inbox.receive(this.db, this.identity);
|
|
70
|
+
if (batch.size && this.refresh()) this.changed();
|
|
71
|
+
if (this.inbox.metrics.more || this.inbox.metrics.pending) this.schedule();
|
|
72
|
+
}
|
|
73
|
+
sourceRevision(scope: WorkScope): string[] {
|
|
74
|
+
if (!this.ready) return [];
|
|
75
|
+
if (!scope.cwd) return [];
|
|
76
|
+
return [observationRevisionForOrigin({ cwd: scope.cwd, sessionId: scope.sessionId }),
|
|
77
|
+
...(scope.sessionId ? [observationRevisionForOrigin({ cwd: scope.cwd })] : [])];
|
|
78
|
+
}
|
|
79
|
+
nextDeadline(scope: WorkScope): number | null {
|
|
80
|
+
if (!this.ready) return null;
|
|
81
|
+
if (!scope.cwd) return null;
|
|
82
|
+
const deadlines = [...recentMetaDeadline({ cwd: scope.cwd, sessionId: scope.sessionId }),
|
|
83
|
+
...(scope.sessionId ? recentMetaDeadline({ cwd: scope.cwd }) : [])];
|
|
84
|
+
return deadlines.length ? Math.min(...deadlines) : null;
|
|
85
|
+
}
|
|
86
|
+
get registryMetrics() { return getRegistryIoMetrics(); }
|
|
87
|
+
private get inboxMetrics() {
|
|
88
|
+
if (this.ready) {
|
|
89
|
+
try { return this.inbox.metrics; }
|
|
90
|
+
catch (error) { if (!isSqliteLockContention(error)) throw error; }
|
|
91
|
+
}
|
|
92
|
+
return { available: false, received: null, applied: null, pending: null };
|
|
93
|
+
}
|
|
94
|
+
get changeMetrics() { const metrics = this.inboxMetrics, available = this.ready && metrics.available !== false;
|
|
95
|
+
return { ...metrics, coverage: this.hasInputVersions ? "cooperative-journal-and-exact-files" : "legacy-bounded-repair",
|
|
96
|
+
operationRepairComplete: available && this.repairComplete, repairAfter: available ? this.repairAfter : null, queuedHints: this.dirtyOperations.size,
|
|
97
|
+
fileCoverage: "active-and-retained; historical-files-only-when-history-requested" }; }
|
|
39
98
|
livenessReasons(options: { refresh?: boolean } = {}) {
|
|
99
|
+
if (!this.ready) throw new Error("Background inbox coverage is unverified");
|
|
40
100
|
if (options.refresh !== false) {
|
|
41
101
|
this.enabled = true;
|
|
42
102
|
this.refresh();
|
|
43
103
|
}
|
|
44
104
|
if (!this.db) return [];
|
|
45
|
-
const version = this.db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value;
|
|
46
|
-
if (!["1", "2", "3", "4"].includes(version)) return [];
|
|
47
105
|
let operations: any[] = [];
|
|
48
|
-
try {
|
|
106
|
+
try {
|
|
107
|
+
// The file may be visible before its writer commits the initial schema.
|
|
108
|
+
// Keep publication alive and report unverified background state until refresh.
|
|
109
|
+
const version = this.db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value;
|
|
110
|
+
if (!["1", "2", "3", "4"].includes(version)) return [];
|
|
111
|
+
operations = this.db.prepare("SELECT * FROM operations WHERE phase = 'running' AND observer_kind = 'local-supervisor' AND terminal_revision = 0").all();
|
|
112
|
+
}
|
|
49
113
|
catch (error) { this.status = "degraded"; this.reason = String(error); return []; }
|
|
50
114
|
return operations.flatMap((op: any) => {
|
|
51
115
|
try {
|
|
52
|
-
const
|
|
116
|
+
const directory = this.directoryFor(op);
|
|
117
|
+
const cached = this.terminalProjections.get(op.operation_id);
|
|
118
|
+
const inspection = cached?.authority === JSON.stringify([op, directory]) ? cached.inspection : snapshot(directory, op.task_id);
|
|
119
|
+
if (!cached || cached.authority !== JSON.stringify([op, directory])) this.metrics.runnerSnapshots++;
|
|
53
120
|
const claim = inspection?.claim;
|
|
54
121
|
return claim && !inspection.terminal && inspection.token === op.launch_token && processMatchesStart(claim.pid, claim.pidStartTime)
|
|
55
122
|
? [{ kind: "runner", id: op.task_id, owner: { kind: op.owner_kind, sessionId: op.owner_session_id, workspace: op.owner_workspace }, operationId: op.operation_id,
|
|
@@ -59,7 +126,41 @@ export class BackgroundObservation {
|
|
|
59
126
|
} catch (error) { this.status = "degraded"; this.reason = String(error); return []; }
|
|
60
127
|
});
|
|
61
128
|
}
|
|
62
|
-
readonly metrics = { runnerSnapshots: 0, activeQueries: 0, historyQueries: 0
|
|
129
|
+
readonly metrics = { runnerSnapshots: 0, activeQueries: 0, historyQueries: 0, inputStats: 0, dependencyQueries: 0, projectionHits: 0,
|
|
130
|
+
repairEntries: 0, exactHints: 0, journalEntities: 0, overflows: 0, activeRows: 0, exactOperationQueries: 0,
|
|
131
|
+
sourceWork: { active: { stats: 0, waits: 0, snapshots: 0 }, repair: { stats: 0, waits: 0, snapshots: 0 }, history: { stats: 0, waits: 0, snapshots: 0 } } };
|
|
132
|
+
private schedule() {
|
|
133
|
+
if (!this.ready || this.scheduled) return;
|
|
134
|
+
this.scheduled = true;
|
|
135
|
+
setImmediate(() => { this.scheduled = false; if (!this.closed && this.refresh()) this.changed(); });
|
|
136
|
+
}
|
|
137
|
+
private oweRepair() {
|
|
138
|
+
this.inbox.db.prepare(`INSERT OR REPLACE INTO ${this.inbox.prefix}background_file_repair VALUES(1,?,'',0)`).run(this.identity ?? "");
|
|
139
|
+
this.repairAfter = ""; this.repairComplete = false;
|
|
140
|
+
}
|
|
141
|
+
private observeDirectory(directory: string) {
|
|
142
|
+
if (this.watchers.has(directory)) return;
|
|
143
|
+
try {
|
|
144
|
+
const watcher = watch(directory, { recursive: true }, (_event, file) => {
|
|
145
|
+
if (this.closed) return;
|
|
146
|
+
// Progress changes only the active overlay. Historical rows and wait inputs stay cached.
|
|
147
|
+
if (file && /^tasks[/\\][^/\\]+[/\\]progress\.json$/.test(String(file))) { this.schedule(); return; }
|
|
148
|
+
const match = file && /^(?:observed[/\\]([^/\\]+)\.json|tasks[/\\]([^/\\]+)[/\\](?:launch|claim|command|result|lost|stop|cleanup)\.json)$/.exec(String(file));
|
|
149
|
+
if (match) {
|
|
150
|
+
const op = this.db?.prepare("SELECT operation_id FROM operations WHERE task_id=? AND observer_kind='local-supervisor'").get(match[1] ?? match[2]);
|
|
151
|
+
if (op) {
|
|
152
|
+
if (this.dirtyOperations.size < 256) this.dirtyOperations.add(op.operation_id);
|
|
153
|
+
else { this.oweRepair(); this.metrics.overflows++; }
|
|
154
|
+
this.history?.invalidateOperation(op.operation_id); this.metrics.exactHints++;
|
|
155
|
+
}
|
|
156
|
+
} else if (!file) { this.oweRepair(); this.metrics.overflows++; }
|
|
157
|
+
else return;
|
|
158
|
+
this.schedule();
|
|
159
|
+
});
|
|
160
|
+
watcher.on("error", () => { watcher.close(); this.watchers.delete(directory); this.status = "degraded"; this.reason = "Background watcher failed; bounded repair required"; this.oweRepair(); this.schedule(); });
|
|
161
|
+
this.watchers.set(directory, watcher);
|
|
162
|
+
} catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
163
|
+
}
|
|
63
164
|
private directoryFor(op: any): string {
|
|
64
165
|
if (!op.supervision_host_id?.startsWith("server:")) return this.directory;
|
|
65
166
|
const row = this.db.prepare("SELECT value FROM coordinator_state WHERE key = ?").get(`result-supervision-v1:${op.operation_id}`);
|
|
@@ -68,42 +169,119 @@ export class BackgroundObservation {
|
|
|
68
169
|
if (grant.launchToken !== op.launch_token || typeof grant.directory !== "string") throw new Error("Captured runner execution identity differs");
|
|
69
170
|
return grant.directory;
|
|
70
171
|
}
|
|
71
|
-
constructor(root: string, directory = join(tmpdir(), process.env.VITEST_POOL_ID ? `pi-better-background-tasks-vitest-${process.env.VITEST_POOL_ID}` : "pi-better-background-tasks", "supervisor"), indexDb?: any, changed = () => {}, readConnection?: (refresh?: boolean) => any) {
|
|
172
|
+
constructor(root: string, directory = join(tmpdir(), process.env.VITEST_POOL_ID ? `pi-better-background-tasks-vitest-${process.env.VITEST_POOL_ID}` : "pi-better-background-tasks", "supervisor"), indexDb?: any, changed = () => {}, readConnection?: (refresh?: boolean) => any, options: { defer?: boolean } = {}) {
|
|
72
173
|
this.readConnection = readConnection;
|
|
174
|
+
this.changed = changed;
|
|
73
175
|
this.root = root; this.directory = directory;
|
|
176
|
+
this.indexDb = indexDb;
|
|
177
|
+
mkdirSync(join(root, "runtime-read-repair"), { recursive: true });
|
|
178
|
+
// Create the owner's in-memory history tables once, never per acquisition attempt.
|
|
74
179
|
if (indexDb) this.history = new BackgroundHistory(indexDb, directory, () => {
|
|
180
|
+
if (!this.ready) throw new Error("Background inbox coverage is unverified");
|
|
75
181
|
if (this.status === "degraded") throw new Error(this.reason);
|
|
76
182
|
return this.db;
|
|
77
|
-
}, operations => this.project(operations, false), changed);
|
|
183
|
+
}, operations => this.project(operations, false), changed, op => this.directoryFor(op));
|
|
184
|
+
if (!options.defer) this.initialize();
|
|
185
|
+
}
|
|
186
|
+
initialize(): void {
|
|
187
|
+
if (this.closed) throw new Error("Background observation is closed");
|
|
188
|
+
if (this.ready) return;
|
|
189
|
+
if (this.indexDb?.isTransaction) throw new Error("Background initialization requires an unpinned owner");
|
|
190
|
+
if (this.inbox) throw new Error("Background inbox cleanup is incomplete");
|
|
191
|
+
const inbox = this.indexDb
|
|
192
|
+
? new AssignmentInbox(join(this.root, "runtime-read-repair", "background.sqlite"), this.indexDb, { entityPrefix: "background:" })
|
|
193
|
+
: new AssignmentInbox(join(this.root, "runtime-read-repair", "background.sqlite"), { entityPrefix: "background:" });
|
|
194
|
+
try {
|
|
195
|
+
inbox.db.exec(`CREATE TABLE IF NOT EXISTS ${inbox.prefix}background_file_repair(singleton INTEGER PRIMARY KEY CHECK(singleton=1), identity TEXT, after_id TEXT, complete INTEGER)`);
|
|
196
|
+
const repair = inbox.db.prepare(`SELECT * FROM ${inbox.prefix}background_file_repair WHERE singleton=1`).get();
|
|
197
|
+
if (repair) { this.identity = repair.identity || undefined; this.knownCoordinator = Boolean(this.identity); this.repairAfter = repair.after_id; this.repairComplete = Boolean(repair.complete); }
|
|
198
|
+
this.inbox = inbox;
|
|
199
|
+
this.initialized = true;
|
|
200
|
+
} catch (error) {
|
|
201
|
+
try { inbox.close(); }
|
|
202
|
+
catch (cleanup) {
|
|
203
|
+
this.inbox = inbox;
|
|
204
|
+
throw new AggregateError([error, cleanup], "Background initialization and owned cleanup failed");
|
|
205
|
+
}
|
|
206
|
+
throw error;
|
|
207
|
+
}
|
|
78
208
|
}
|
|
79
209
|
refresh(): boolean {
|
|
210
|
+
if (!this.ready) return false;
|
|
211
|
+
if (this.observationActive) return false;
|
|
80
212
|
if (!this.enabled) return false;
|
|
213
|
+
let observation: { commit(): void; release(): void } | undefined;
|
|
214
|
+
const previous = { rows: this.rows, signature: this.signature, legacy: new Map([...this.legacy].map(([key, value]) => [key, { ...value }])),
|
|
215
|
+
terminalProjections: new Map(this.terminalProjections), scopeVersions: new Map(this.scopeVersions), recent: this.recent,
|
|
216
|
+
recentRevision: this.recentRevision, repairAfter: this.repairAfter, repairComplete: this.repairComplete,
|
|
217
|
+
dirtyOperations: new Set(this.dirtyOperations), changedOperations: new Map(this.changedOperations) };
|
|
81
218
|
try {
|
|
82
219
|
const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
|
|
83
220
|
const path = join(this.root, "operation-coordinator.sqlite");
|
|
84
221
|
let identity;
|
|
85
222
|
try { const info = statSync(path, { bigint: true }); identity = `${info.dev}:${info.ino}`; }
|
|
86
223
|
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
87
|
-
if (identity !== this.identity) { this.terminalProjections.clear(); this.recentRevision = undefined; this.recent = []; for (const entry of this.legacy.values()) { entry.pendingRevision = undefined; entry.recentRevision = undefined; entry.recent = []; } this.history?.invalidate(); this.ownDb?.close(); this.ownDb = undefined; this.identity = identity; }
|
|
224
|
+
if (identity !== this.identity) { this.repairAfter = ""; this.repairComplete = false; this.scopeVersions.clear(); this.terminalProjections.clear(); this.recentRevision = undefined; this.recent = []; for (const entry of this.legacy.values()) { entry.pendingRevision = undefined; entry.recentRevision = undefined; entry.recent = []; } this.history?.invalidate(); this.ownDb?.close(); this.ownDb = undefined; this.identity = identity; }
|
|
88
225
|
if (!identity && this.knownCoordinator) throw new Error("Coordinator source disappeared; retaining the previous observation");
|
|
89
226
|
if (identity) {
|
|
90
|
-
if (this.readConnection)
|
|
227
|
+
if (this.readConnection) {
|
|
228
|
+
const source = this.readConnection();
|
|
229
|
+
observation = source?.beginSnapshot?.();
|
|
230
|
+
}
|
|
91
231
|
else this.ownDb ??= new DatabaseSync(path, { readOnly: true });
|
|
92
232
|
this.knownCoordinator = true;
|
|
93
233
|
const version = this.db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value;
|
|
94
234
|
if (!["1", "2", "3", "4"].includes(version)) throw new Error("Unsupported coordinator schema");
|
|
235
|
+
this.hasInputVersions = Boolean(this.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='background_input_versions'").get());
|
|
95
236
|
}
|
|
96
237
|
this.metrics.activeQueries++;
|
|
97
|
-
|
|
238
|
+
let batch: any;
|
|
239
|
+
if (this.db && this.hasInputVersions) {
|
|
240
|
+
batch = this.inbox.receive(this.db, this.identity);
|
|
241
|
+
for (const [scope, seq] of batch) if (scope !== "*") {
|
|
242
|
+
const [session, workspace, operationId] = JSON.parse(scope);
|
|
243
|
+
this.dirtyOperations.add(operationId);
|
|
244
|
+
this.scopeVersions.set(JSON.stringify([workspace, session]), Number(seq));
|
|
245
|
+
this.history?.invalidateOperation(operationId);
|
|
246
|
+
this.metrics.journalEntities++;
|
|
247
|
+
}
|
|
248
|
+
if (batch.has("*")) { this.terminalProjections.clear(); this.recentRevision = undefined; for (const entry of this.legacy.values()) { entry.recentRevision = undefined; entry.pendingRevision = undefined; } this.history?.invalidate(); }
|
|
249
|
+
}
|
|
250
|
+
const revision = this.hasInputVersions ? Math.max(0, ...this.scopeVersions.values())
|
|
251
|
+
: Number(this.db?.prepare("SELECT value FROM coordinator_state WHERE key = 'change_revision'").get()?.value ?? 0);
|
|
252
|
+
this.repairIds.clear();
|
|
253
|
+
if (this.db) {
|
|
254
|
+
const repair = this.db.prepare("SELECT operation_id FROM operations WHERE observer_kind='local-supervisor' AND operation_id>? ORDER BY operation_id LIMIT ?").all(this.repairAfter, ENTITY_BUDGET);
|
|
255
|
+
for (const op of repair) { this.repairIds.add(op.operation_id); this.metrics.repairEntries++; }
|
|
256
|
+
this.repairAfter = repair.length === ENTITY_BUDGET ? repair.at(-1).operation_id : "";
|
|
257
|
+
if (!this.repairAfter) this.repairComplete = true;
|
|
258
|
+
const saved = this.inbox.db.prepare(`SELECT * FROM ${this.inbox.prefix}background_file_repair WHERE singleton=1`).get();
|
|
259
|
+
if (!saved || saved.identity !== (this.identity ?? "") || saved.after_id !== this.repairAfter || saved.complete !== Number(this.repairComplete))
|
|
260
|
+
this.inbox.db.prepare(`INSERT OR REPLACE INTO ${this.inbox.prefix}background_file_repair VALUES(1,?,?,?)`).run(this.identity ?? "", this.repairAfter, Number(this.repairComplete));
|
|
261
|
+
}
|
|
98
262
|
const hasPendingIndex = Boolean(this.db?.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='background_parent_callbacks'").get());
|
|
263
|
+
this.changedOperations.clear();
|
|
264
|
+
if (this.db) for (const id of new Set([...this.dirtyOperations, ...this.repairIds])) {
|
|
265
|
+
this.metrics.exactOperationQueries++;
|
|
266
|
+
this.changedOperations.set(id, this.db.prepare("SELECT * FROM operations WHERE operation_id=?").get(id));
|
|
267
|
+
}
|
|
99
268
|
const operations = this.db ? this.db.prepare("SELECT * FROM operations WHERE phase = 'running' AND observer_kind = 'local-supervisor'").all() : [];
|
|
269
|
+
this.metrics.activeRows += operations.length;
|
|
100
270
|
// Active snapshots retain a bounded recent window. Complete history is
|
|
101
271
|
// available through the separately paginated history index.
|
|
102
|
-
if (this.allRequested && this.db && this.recentRevision !== revision) {
|
|
272
|
+
if (this.allRequested && this.db && (this.recentRevision === undefined || !this.hasInputVersions && this.recentRevision !== revision)) {
|
|
103
273
|
this.recent = this.db.prepare(`SELECT * FROM operations WHERE observer_kind='local-supervisor'
|
|
104
274
|
AND terminal_at >= ? AND terminal_revision > 0
|
|
105
275
|
ORDER BY terminal_at DESC, operation_id DESC LIMIT ?`).all(Date.now() - 30000, DISCOVERY_PAGE_SIZE);
|
|
106
276
|
this.recentRevision = revision;
|
|
277
|
+
} else if (this.allRequested) {
|
|
278
|
+
const recent = new Map(this.recent.map(op => [op.operation_id, op]));
|
|
279
|
+
for (const [id, op] of this.changedOperations) {
|
|
280
|
+
if (op?.observer_kind === "local-supervisor" && op.terminal_revision > 0 && Date.now() - op.terminal_at < 30000) recent.set(id, op);
|
|
281
|
+
else recent.delete(id);
|
|
282
|
+
}
|
|
283
|
+
this.recent = [...recent.values()].sort((a, b) => b.terminal_at - a.terminal_at || b.operation_id.localeCompare(a.operation_id)).slice(0, DISCOVERY_PAGE_SIZE);
|
|
284
|
+
this.recentRevision = revision;
|
|
107
285
|
}
|
|
108
286
|
this.recent = this.recent.filter(op => Date.now() - op.terminal_at < 30000);
|
|
109
287
|
operations.push(...this.recent);
|
|
@@ -112,100 +290,200 @@ export class BackgroundObservation {
|
|
|
112
290
|
// Invalidate history on that exact state transition, not on scope/projection
|
|
113
291
|
// churn (which would continually restart a yielding history build).
|
|
114
292
|
const previousRows = new Map(this.rows.map(row => [row.id, row]));
|
|
115
|
-
|
|
116
|
-
&& (previous.status !== row.status || previous.active !== row.active)
|
|
293
|
+
for (const row of rows) { const previous = previousRows.get(row.id); if (previous
|
|
294
|
+
&& (previous.status !== row.status || previous.active !== row.active)) this.history?.invalidateOperation(row.operationId); }
|
|
117
295
|
for (const entry of this.legacy.values()) {
|
|
118
|
-
|
|
119
|
-
this.
|
|
120
|
-
|
|
296
|
+
const scopedRevision = this.hasInputVersions ? this.scopeVersions.get(JSON.stringify([entry.origin.cwd, entry.origin.sessionId])) ?? 0 : revision;
|
|
297
|
+
if (hasPendingIndex) this.refreshPending(entry, scopedRevision);
|
|
298
|
+
this.refreshRecent(entry, scopedRevision);
|
|
299
|
+
const active = this.visibleLegacy(entry.origin);
|
|
121
300
|
const retained = entry.rows.map(row => readMeta(row.id)).filter((row: any) => row && row.dismissedAt === undefined
|
|
122
301
|
&& row.status !== "running" && (!row.endedAt || Date.now() - row.endedAt < 30000));
|
|
123
|
-
entry.rows = [...
|
|
302
|
+
entry.rows = [...new Map([...retained, ...active].map(row => [row.id, row])).values()];
|
|
124
303
|
}
|
|
125
304
|
const signature = JSON.stringify([rows, [...this.legacy.values()].flatMap(entry => [...entry.rows, ...entry.recent, ...this.pendingRows(entry)]).sort((a, b) => a.id.localeCompare(b.id))]);
|
|
126
305
|
const changed = signature !== this.signature || this.status !== "ready";
|
|
127
306
|
// Projection churn must not cancel a yielding history build. Its own
|
|
128
307
|
// source versions and watchers invalidate only changed source facts.
|
|
129
308
|
this.rows = rows; this.signature = signature; this.status = "ready"; this.reason = undefined;
|
|
309
|
+
// History's source fence must see this newly verified observation, not
|
|
310
|
+
// reject recovery because the previous pass found a partial legacy write.
|
|
311
|
+
for (const id of this.repairIds) this.history?.repairOperation(this.changedOperations.get(id), id);
|
|
130
312
|
this.history?.reconcile();
|
|
313
|
+
if (batch) this.inbox.acknowledge(batch, true);
|
|
314
|
+
this.dirtyOperations.clear();
|
|
315
|
+
if (this.inbox.metrics.more || this.inbox.metrics.pending) this.schedule();
|
|
316
|
+
if (this.expiry) clearTimeout(this.expiry);
|
|
317
|
+
const deadlines = [...rows.flatMap(row => row.progress?.nextDeadline ?? []), ...this.recent.map(op => op.terminal_at + 30000), ...[...this.legacy.values()].flatMap(entry => [
|
|
318
|
+
...entry.recent.map(row => row.endedAt + 30000), ...recentMetaDeadline(entry.origin),
|
|
319
|
+
...(entry.origin.sessionId ? recentMetaDeadline({ cwd: entry.origin.cwd }) : [])])].filter(Number.isFinite);
|
|
320
|
+
if (deadlines.length) {
|
|
321
|
+
const delay = Math.max(1, Math.min(2_147_483_647, Math.min(...deadlines) - Date.now()));
|
|
322
|
+
this.expiry = setTimeout(() => this.schedule(), delay);
|
|
323
|
+
this.expiry.unref();
|
|
324
|
+
}
|
|
325
|
+
observation?.commit();
|
|
131
326
|
return changed;
|
|
132
327
|
} catch (error) {
|
|
328
|
+
observation?.release();
|
|
329
|
+
Object.assign(this, previous);
|
|
133
330
|
const reason = String(error);
|
|
134
331
|
const changed = this.status !== "degraded" || this.reason !== reason;
|
|
135
332
|
this.status = "degraded"; this.reason = reason;
|
|
136
333
|
return changed;
|
|
334
|
+
} finally { observation?.release(); }
|
|
335
|
+
}
|
|
336
|
+
/** Captured assignment, never the newest assignment in a reused conversation. */
|
|
337
|
+
private workerParent(op: any, context: any): any {
|
|
338
|
+
if (op.owner_kind !== "worker-conversation") return undefined;
|
|
339
|
+
if (!this.db.prepare("SELECT 1 FROM sqlite_master WHERE name='assignment_bindings'").get()) return undefined;
|
|
340
|
+
let bindings: any[];
|
|
341
|
+
if (typeof context.workerAttemptId === "string") {
|
|
342
|
+
bindings = this.db.prepare(`SELECT b.* FROM assignment_bindings b JOIN assignment_attempts a
|
|
343
|
+
ON a.assignment_id=b.assignment_id WHERE a.attempt_id=?`).all(context.workerAttemptId);
|
|
344
|
+
} else {
|
|
345
|
+
// Older launches are visible only when a durable wait proves the assignment.
|
|
346
|
+
bindings = this.db.prepare(`SELECT DISTINCT b.* FROM assignment_bindings b JOIN waits w
|
|
347
|
+
ON json_extract(w.origin_json,'$.assignmentRef')=b.assignment_id
|
|
348
|
+
JOIN wait_dependencies d ON d.wait_id=w.wait_id AND d.generation=w.generation
|
|
349
|
+
WHERE d.operation_id=?`).all(op.operation_id);
|
|
137
350
|
}
|
|
351
|
+
if (bindings.length !== 1) return undefined;
|
|
352
|
+
const owner = JSON.parse(bindings[0].owner_json), recipient = JSON.parse(bindings[0].recipient_json);
|
|
353
|
+
if (owner.kind !== op.owner_kind || owner.sessionId !== op.owner_session_id || owner.workspace !== op.owner_workspace
|
|
354
|
+
|| (owner.branchId ?? null) !== (op.owner_branch_id ?? null) || (owner.goalId ?? null) !== (op.owner_goal_id ?? null) || recipient.kind !== "parent-session") return undefined;
|
|
355
|
+
return {parentAgentId: owner.sessionId, parentRecipient: recipient, readOnly: true};
|
|
138
356
|
}
|
|
139
357
|
private project(operations: any[], useCache = true) {
|
|
140
|
-
const revision = this.db?.prepare("SELECT value FROM coordinator_state WHERE key = 'change_revision'").get()?.value;
|
|
141
|
-
const directories = new Map<string, string>();
|
|
142
358
|
return operations.map((op: any) => {
|
|
359
|
+
try {
|
|
143
360
|
const directory = this.directoryFor(op);
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
361
|
+
this.observeDirectory(directory);
|
|
362
|
+
const saved = this.terminalProjections.get(op.operation_id);
|
|
363
|
+
const cached = saved && { ...saved };
|
|
364
|
+
const authority = JSON.stringify([op, directory]);
|
|
365
|
+
const work = !useCache ? this.metrics.sourceWork.history : this.repairIds.has(op.operation_id) && !this.dirtyOperations.has(op.operation_id)
|
|
366
|
+
? this.metrics.sourceWork.repair : this.metrics.sourceWork.active;
|
|
367
|
+
const dependencyVersion = this.hasInputVersions
|
|
368
|
+
? Number(this.db.prepare("SELECT revision FROM background_input_versions WHERE operation_id=?").get(op.operation_id)?.revision ?? 0)
|
|
369
|
+
: undefined;
|
|
370
|
+
const observedPath = join(directory, "observed", `${op.task_id}.json`);
|
|
371
|
+
const paths = [observedPath,
|
|
372
|
+
...["launch.json", "claim.json", "command.json", "result.json", "lost.json", "stop.json", "cleanup.json"]
|
|
373
|
+
.map(name => join(directory, "tasks", op.task_id, name))];
|
|
374
|
+
const identities = paths.map(path => {
|
|
375
|
+
this.metrics.inputStats++;
|
|
376
|
+
work.stats++;
|
|
377
|
+
try { const info = statSync(path, { bigint: true }); return `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`; }
|
|
147
378
|
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
148
|
-
|
|
379
|
+
return "missing";
|
|
380
|
+
});
|
|
381
|
+
let waits = cached?.row.waits;
|
|
382
|
+
if (dependencyVersion === undefined || !cached || cached.authority !== authority || cached.dependencyVersion !== dependencyVersion) {
|
|
383
|
+
this.metrics.dependencyQueries++;
|
|
384
|
+
work.waits++;
|
|
385
|
+
waits = this.db.prepare(`SELECT w.wait_id, w.generation, w.phase FROM waits w JOIN wait_dependencies d
|
|
386
|
+
ON w.wait_id = d.wait_id AND w.generation = d.generation WHERE d.operation_id = ?
|
|
387
|
+
AND w.owner_kind = ? AND w.owner_session_id = ? AND w.owner_workspace = ?
|
|
388
|
+
AND w.phase NOT IN ('consumed', 'cancelled') AND w.dispatch_disarmed = 0
|
|
389
|
+
ORDER BY w.wait_id, w.generation`).all(op.operation_id, op.owner_kind, op.owner_session_id, op.owner_workspace)
|
|
390
|
+
.map((w: any) => ({ waitId: w.wait_id, generation: w.generation, phase: w.phase }));
|
|
149
391
|
}
|
|
150
|
-
const
|
|
151
|
-
|
|
392
|
+
const readContext = () => {
|
|
393
|
+
try { return JSON.parse(readFileSync(observedPath, "utf8")); }
|
|
394
|
+
catch (error) {
|
|
395
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
|
|
396
|
+
if (!useCache && op.terminal_revision > 0 && error instanceof SyntaxError) return malformedHistoryContext;
|
|
397
|
+
throw error;
|
|
398
|
+
}
|
|
399
|
+
};
|
|
400
|
+
const workerContext = op.owner_kind === "worker-conversation" ? readContext() : undefined;
|
|
401
|
+
const parent = workerContext && this.workerParent(op, workerContext);
|
|
402
|
+
const version = JSON.stringify([op, directory, identities, waits, parent]);
|
|
403
|
+
// Both paths validate authority, file identities and dependencies above.
|
|
404
|
+
// History mode changes accounting/invalidation, not projection identity.
|
|
405
|
+
if (cached?.version === version) { cached.dependencyVersion = dependencyVersion; this.terminalProjections.set(op.operation_id, cached); this.metrics.projectionHits++; return cached.row; }
|
|
406
|
+
if (useCache) this.history?.invalidateOperation(op.operation_id);
|
|
152
407
|
this.metrics.runnerSnapshots++;
|
|
408
|
+
work.snapshots++;
|
|
153
409
|
const inspection = snapshot(directory, op.task_id);
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
|
|
410
|
+
const context = workerContext ?? readContext();
|
|
411
|
+
if (context === malformedHistoryContext) return { id: op.task_id, unreadable: true };
|
|
157
412
|
const terminal = inspection?.terminal === true || op.terminal_revision > 0;
|
|
158
413
|
const status = inspection?.terminal ? inspection.status : op.terminal_revision > 0 ? op.terminal_outcome : inspection?.status ?? "running";
|
|
159
|
-
const
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
.map((w: any) => ({ waitId: w.wait_id, generation: w.generation, phase: w.phase }));
|
|
164
|
-
const row = { durable: true, id: op.task_id, operationId: op.operation_id, kind: context.kind ?? inspection?.kind ?? "process",
|
|
165
|
-
status, active: !terminal, terminal, attention: terminal && status !== "succeeded", waits,
|
|
166
|
-
owner: { kind: op.owner_kind, sessionId: op.owner_session_id, workspace: op.owner_workspace },
|
|
414
|
+
const row = { ...parent, durable: true, id: op.task_id, operationId: op.operation_id, kind: context.kind ?? inspection?.kind ?? "process",
|
|
415
|
+
callback: Boolean(context.kind && context.callback !== false), status, active: !terminal, terminal, attention: terminal && status !== "succeeded", waits,
|
|
416
|
+
terminalRevision: op.terminal_revision, terminalOutcome: op.terminal_outcome,
|
|
417
|
+
owner: { kind: op.owner_kind, sessionId: op.owner_session_id, workspace: op.owner_workspace, branchId: op.owner_branch_id ?? null },
|
|
167
418
|
startedAt: inspection?.result?.startedAt ?? inspection?.launch.createdAt ?? op.created_at,
|
|
168
419
|
endedAt: inspection?.result?.endedAt ?? op.terminal_at ?? undefined,
|
|
169
420
|
cwd: inspection?.launch.cwd ?? op.owner_workspace, name: context.name, command: context.command, argv: context.argv,
|
|
170
|
-
dismissedAt: context.dismissedAt, exitCode: inspection?.result?.exitCode ?? null,
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
}
|
|
421
|
+
dismissedAt: context.dismissedAt, exitCode: inspection?.result?.exitCode ?? null,
|
|
422
|
+
signal: inspection?.result?.signal ?? null, logPaths: inspection?.logs ?? {} };
|
|
423
|
+
this.terminalProjections.delete(op.operation_id);
|
|
424
|
+
this.terminalProjections.set(op.operation_id, { version, authority, operation: op, inspection, row, dependencyVersion });
|
|
425
|
+
if (this.terminalProjections.size > 4096) this.terminalProjections.delete(this.terminalProjections.keys().next().value!);
|
|
176
426
|
return row;
|
|
177
|
-
|
|
427
|
+
} catch (error) { this.dirtyOperations.add(op.operation_id); throw error; }
|
|
428
|
+
}).filter(Boolean).map(row => {
|
|
429
|
+
if (!row.active) return row;
|
|
430
|
+
const inspection = this.terminalProjections.get(row.operationId)?.inspection;
|
|
431
|
+
return { ...row, progress: supervisedProgress(inspection) };
|
|
432
|
+
});
|
|
178
433
|
}
|
|
179
434
|
private pendingRows(entry: BackgroundScope): any[] { return entry.pending; }
|
|
180
435
|
private refreshPending(entry: BackgroundScope, revision: number): void {
|
|
181
436
|
if (!entry.origin.sessionId || entry.pendingRevision === revision) return;
|
|
182
437
|
// These compact pointers only notify the frontend that obligations exist.
|
|
183
438
|
// The canonical manager independently pages and resolves every obligation.
|
|
184
|
-
entry.pending = this.db.prepare(`SELECT o.operation_id,o.task_id,o.owner_kind,o.owner_workspace,o.owner_session_id,
|
|
439
|
+
entry.pending = this.db.prepare(`SELECT o.operation_id,o.task_id,o.owner_kind,o.owner_workspace,o.owner_session_id,o.owner_branch_id,
|
|
185
440
|
o.terminal_outcome,o.terminal_at,o.created_at FROM background_parent_callbacks c
|
|
186
441
|
JOIN operations o ON o.operation_id=c.operation_id
|
|
187
442
|
WHERE c.owner_kind='parent-session' AND c.owner_workspace=? AND c.owner_session_id=? AND o.terminal_revision>0
|
|
188
443
|
ORDER BY c.operation_id LIMIT ?`).all(entry.origin.cwd, entry.origin.sessionId, DISCOVERY_PAGE_SIZE)
|
|
189
444
|
.map((op: any) => ({ durable: true, id: op.task_id, operationId: op.operation_id, callbackPending: true,
|
|
190
|
-
owner: { kind: op.owner_kind, workspace: op.owner_workspace, sessionId: op.owner_session_id },
|
|
445
|
+
owner: { kind: op.owner_kind, workspace: op.owner_workspace, sessionId: op.owner_session_id, branchId: op.owner_branch_id ?? null },
|
|
191
446
|
status: op.terminal_outcome, terminal: true, active: false, startedAt: op.created_at, endedAt: op.terminal_at }));
|
|
192
447
|
entry.pendingRevision = revision;
|
|
193
448
|
}
|
|
449
|
+
private belongsToDurableOrigin(row: any, origin: { cwd?: string; sessionId?: string }): boolean {
|
|
450
|
+
return row.owner.kind === "parent-session"
|
|
451
|
+
? row.owner.workspace === origin.cwd && row.owner.sessionId === origin.sessionId
|
|
452
|
+
: row.parentRecipient?.workspace === origin.cwd && row.parentRecipient?.sessionId === origin.sessionId;
|
|
453
|
+
}
|
|
194
454
|
private refreshRecent(entry: BackgroundScope, revision: number): void {
|
|
195
455
|
if (!this.db) return;
|
|
196
|
-
if (entry.recentRevision !== revision) {
|
|
197
|
-
const operations = this.db.prepare(`SELECT * FROM operations WHERE
|
|
198
|
-
|
|
199
|
-
|
|
456
|
+
if (entry.recentRevision === undefined || !this.hasInputVersions && entry.recentRevision !== revision) {
|
|
457
|
+
const operations = this.db.prepare(`SELECT * FROM operations o WHERE observer_kind='local-supervisor' AND (
|
|
458
|
+
(owner_kind='parent-session' AND owner_workspace=?1 AND owner_session_id=?2) OR
|
|
459
|
+
${this.db.prepare("SELECT 1 FROM sqlite_master WHERE name='assignment_bindings'").get() ? `(owner_kind='worker-conversation' AND EXISTS (SELECT 1 FROM assignment_bindings b
|
|
460
|
+
WHERE json_extract(b.owner_json,'$.sessionId')=o.owner_session_id
|
|
461
|
+
AND json_extract(b.owner_json,'$.workspace')=o.owner_workspace
|
|
462
|
+
AND json_extract(b.recipient_json,'$.workspace')=?1 AND json_extract(b.recipient_json,'$.sessionId')=?2))` : '0'})
|
|
463
|
+
AND terminal_revision>0 AND terminal_at>=?3 ORDER BY terminal_at DESC,operation_id DESC LIMIT ?4`)
|
|
200
464
|
.all(entry.origin.cwd, entry.origin.sessionId ?? "", Date.now() - 30000, DISCOVERY_PAGE_SIZE);
|
|
201
|
-
entry.recent = this.project(operations);
|
|
465
|
+
entry.recent = this.project(operations).filter(row => this.belongsToDurableOrigin(row, entry.origin));
|
|
202
466
|
entry.recentRevision = revision;
|
|
203
467
|
} else {
|
|
204
|
-
|
|
205
|
-
//
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
468
|
+
const rows = new Map(entry.recent.filter(row => Date.now() - row.endedAt < 30000).map(row => [row.operationId, row]));
|
|
469
|
+
// Retained visible terminals must observe atomic file replacement even
|
|
470
|
+
// before a watcher hint arrives or the historical repair cursor reaches them.
|
|
471
|
+
for (const id of rows.keys()) if (!this.changedOperations.has(id)) {
|
|
472
|
+
let op = this.terminalProjections.get(id)?.operation;
|
|
473
|
+
if (!op) { this.metrics.exactOperationQueries++; op = this.db.prepare("SELECT * FROM operations WHERE operation_id=?").get(id); }
|
|
474
|
+
const row = op && this.project([op])[0];
|
|
475
|
+
if (row && this.belongsToDurableOrigin(row, entry.origin)) rows.set(id, row);
|
|
476
|
+
else rows.delete(id);
|
|
477
|
+
}
|
|
478
|
+
for (const [id, op] of this.changedOperations) {
|
|
479
|
+
const direct = op?.owner_kind === "parent-session" && op.owner_workspace === entry.origin.cwd && op.owner_session_id === (entry.origin.sessionId ?? "");
|
|
480
|
+
const row = (direct || op?.owner_kind === "worker-conversation") && op.observer_kind === "local-supervisor"
|
|
481
|
+
&& op.terminal_revision > 0 && Date.now() - op.terminal_at < 30000 && this.project([op])[0];
|
|
482
|
+
if (row && this.belongsToDurableOrigin(row, entry.origin)) rows.set(id, row);
|
|
483
|
+
else rows.delete(id);
|
|
484
|
+
}
|
|
485
|
+
entry.recent = [...rows.values()].sort((a, b) => b.endedAt - a.endedAt || b.operationId.localeCompare(a.operationId)).slice(0, DISCOVERY_PAGE_SIZE);
|
|
486
|
+
entry.recentRevision = revision;
|
|
209
487
|
}
|
|
210
488
|
}
|
|
211
489
|
private legacyScope(scope: { cwd?: string; sessionId?: string }) {
|
|
@@ -219,41 +497,58 @@ export class BackgroundObservation {
|
|
|
219
497
|
this.legacy.delete(oldest[0]);
|
|
220
498
|
}
|
|
221
499
|
const origin = { cwd: scope.cwd, sessionId: scope.sessionId };
|
|
222
|
-
entry = { origin, rows:
|
|
223
|
-
if (this.db?.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='background_parent_callbacks'").get())
|
|
500
|
+
entry = { origin, rows: this.ready ? this.visibleLegacy(origin) : [], references: 0, pending: [], recent: [] };
|
|
501
|
+
if (this.ready && this.status !== "degraded" && this.db?.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='background_parent_callbacks'").get())
|
|
224
502
|
this.refreshPending(entry, Number(this.db.prepare("SELECT value FROM coordinator_state WHERE key='change_revision'").get()?.value ?? 0));
|
|
225
|
-
if (this.db) this.refreshRecent(entry, Number(this.db.prepare("SELECT value FROM coordinator_state WHERE key='change_revision'").get()?.value ?? 0));
|
|
503
|
+
if (this.ready && this.status !== "degraded" && this.db) this.refreshRecent(entry, Number(this.db.prepare("SELECT value FROM coordinator_state WHERE key='change_revision'").get()?.value ?? 0));
|
|
226
504
|
}
|
|
227
505
|
this.legacy.delete(key); this.legacy.set(key, entry);
|
|
228
506
|
return entry;
|
|
229
507
|
}
|
|
508
|
+
private visibleLegacy(origin: { cwd: string; sessionId?: string }): any[] {
|
|
509
|
+
return [...new Map([...observeMetasForOrigin(origin), ...observeRecentMetasForOrigin(origin),
|
|
510
|
+
...(origin.sessionId ? observeRecentMetasForOrigin({ cwd: origin.cwd }).filter((row: any) => !row.callbackOrigin) : [])]
|
|
511
|
+
.map((row: any) => [row.id, row])).values()];
|
|
512
|
+
}
|
|
230
513
|
retain(scope: { cwd?: string; sessionId?: string }) {
|
|
514
|
+
if (!this.ready) this.enabled = true;
|
|
231
515
|
const entry = this.legacyScope(scope);
|
|
232
516
|
entry.references++;
|
|
233
517
|
let released = false;
|
|
234
518
|
return () => { if (!released) { released = true; entry.references--; } };
|
|
235
519
|
}
|
|
236
520
|
read(scope: WorkScope, index?: any): any[] {
|
|
521
|
+
if (!this.ready) { this.enabled = true; return []; }
|
|
237
522
|
const newlyGlobal = scope.backgroundAll && !this.allRequested;
|
|
238
523
|
if (scope.backgroundAll) this.allRequested = true;
|
|
239
524
|
if (!this.enabled || newlyGlobal) { this.enabled = true; this.refresh(); }
|
|
240
525
|
const legacy = this.legacyScope(scope);
|
|
241
526
|
if (scope.backgroundHistory) { this.metrics.historyQueries++; return index.records.map((record: any) => record.meta); }
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
527
|
+
// Retained terminals stay visible by default, but a sidecar dismissal must
|
|
528
|
+
// be observed even before its watcher notification is delivered.
|
|
529
|
+
if (!this.observationActive && this.status !== "degraded" && this.db) this.refreshRecent(legacy, legacy.recentRevision ?? 0);
|
|
530
|
+
const legacyRows = this.observationActive || this.status === "degraded" ? legacy.rows : this.visibleLegacy(legacy.origin);
|
|
531
|
+
const exact = scope.id && this.status !== "degraded" && this.db
|
|
532
|
+
? this.project(this.db.prepare("SELECT * FROM operations WHERE task_id=? AND observer_kind='local-supervisor'").all(scope.id)) : [];
|
|
533
|
+
const rows = [...new Map([...this.pendingRows(legacy), ...this.rows, ...(scope.backgroundAll ? [] : legacy.recent), ...exact].map(row => [row.id, row])).values()];
|
|
534
|
+
return [...rows.filter(row => (!scope.id || row.id === scope.id) && row.dismissedAt === undefined
|
|
535
|
+
&& (scope.backgroundAll ? row.owner.kind === "parent-session" : this.belongsToDurableOrigin(row, scope)) && (!scope.active || row.active)),
|
|
536
|
+
...legacyRows.filter((row: any) => (!scope.id || row.id === scope.id) && (scope.backgroundAll || !row.callbackOrigin || belongsToOrigin(row, legacy.origin)
|
|
247
537
|
&& (scope.sessionId || row.spawnPid === scope.processId)) && (!scope.active || row.status === "running"))];
|
|
248
538
|
}
|
|
249
539
|
close(): Promise<void> {
|
|
250
|
-
|
|
251
|
-
this.
|
|
540
|
+
this.closed = true;
|
|
541
|
+
if (this.expiry) clearTimeout(this.expiry);
|
|
542
|
+
for (const watcher of this.watchers.values()) watcher.close();
|
|
543
|
+
this.watchers.clear(); this.inbox?.close(); this.inbox = undefined;
|
|
544
|
+
if (this.history) return this.history.close().then(() => { this.ownDb?.close(); this.ownDb = undefined; });
|
|
545
|
+
this.ownDb?.close(); this.ownDb = undefined; return Promise.resolve();
|
|
252
546
|
}
|
|
253
|
-
get historyStatus() { return this.history?.
|
|
547
|
+
get historyStatus() { return this.history?.queryStatus ?? "degraded"; }
|
|
254
548
|
get historyReason() { return this.history?.reason; }
|
|
255
549
|
get historyMetrics() { return this.history?.metrics; }
|
|
256
550
|
historyIndex(scope: WorkScope) {
|
|
551
|
+
if (!this.ready) throw new Error("Background inbox coverage is unverified");
|
|
257
552
|
this.read({ ...scope, backgroundHistory: false });
|
|
258
553
|
if (!this.history) throw new Error("Background history requires the shared root index");
|
|
259
554
|
return this.history.read(scope);
|