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,21 +1,27 @@
|
|
|
1
|
+
import { discoveryWorkspace } from "./domain/subagents/workspace-scope.domain.mjs";
|
|
2
|
+
import { affectedAttempts } from "./attempt-invalidation.ts";
|
|
1
3
|
import { processMatchesStart } from "../daemon-owner.ts";
|
|
2
4
|
import { createHash } from "node:crypto";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { join, resolve, sep } from "node:path";
|
|
6
|
-
import { realpathSync, statSync } from "node:fs";
|
|
5
|
+
import { opendir, readFile, stat, writeFile, mkdir, rename } from "node:fs/promises";
|
|
6
|
+
import { watchSource, type SourceWatch, type SourceWatcher as FSWatcher } from "./source-watch.ts";
|
|
7
|
+
import { basename, dirname, relative, join, resolve, sep } from "node:path";
|
|
8
|
+
import { realpathSync, statSync, mkdirSync } from "node:fs";
|
|
7
9
|
import { tmpdir } from "node:os";
|
|
8
10
|
import { createRequire } from "node:module";
|
|
9
11
|
import { setImmediate as yieldTurn } from "node:timers/promises";
|
|
12
|
+
import type { InventoryPhase } from "./read-watchdog-probe.ts";
|
|
10
13
|
import { performance } from "node:perf_hooks";
|
|
11
14
|
import { createAssignmentProjector } from "./domain/assignment-projection.mjs";
|
|
12
15
|
import { createAssignmentReader } from "./domain/assignment-observation.mjs";
|
|
13
16
|
import { parseArchivedAttempt, parseArchivedSessionState } from "./domain/session-store.mjs";
|
|
14
|
-
import { parseRun, readRunTranscript } from "./domain/parse.mjs";
|
|
17
|
+
import { parseRun, parseRunDisplay, readRunTranscript, encodeParseLogState, decodeParseLogState } from "./domain/parse.mjs";
|
|
18
|
+
import { withLogReadBatch, logReadMetrics } from "./domain/log-cursor.mjs";
|
|
15
19
|
import { fmtSpend } from "./domain/widget.mjs";
|
|
16
20
|
import { effectiveStatus } from "./domain/process-status.mjs";
|
|
17
|
-
import { extractChildEventFactsFromLog, healthThresholdsForConfig } from "./domain/health-observation.mjs";
|
|
21
|
+
import { extractChildEventFactsFromLog, healthThresholdsForConfig, encodeHealthLogState, decodeHealthLogState } from "./domain/health-observation.mjs";
|
|
22
|
+
import { LogCheckpoints, isSqliteLockContention } from "./log-checkpoints.ts";
|
|
18
23
|
import { BackgroundObservation } from "./background.ts";
|
|
24
|
+
import { workPage, createWorkBudget } from "./work-budget.ts";
|
|
19
25
|
// @ts-expect-error Generated canonical read-only failure projection.
|
|
20
26
|
import { readFailureStateReadOnly, pendingFailureAttention } from "./domain/subagents/shared-failure-observations.domain.mjs";
|
|
21
27
|
import { readHealthConfig } from "./health-config.ts";
|
|
@@ -25,7 +31,7 @@ export interface WorkSnapshot {
|
|
|
25
31
|
instanceId: string; runtimeEpoch: string; scopeRevision: string; seq: number;
|
|
26
32
|
observedRevisionVector: { inventory: number; coordinator: string; healthConfig: string };
|
|
27
33
|
status: "ready" | "rebuilding" | "degraded"; reason?: string;
|
|
28
|
-
rows: Array<{ meta: any; assignment: any; sourceRevision: string }>;
|
|
34
|
+
rows: Array<{ meta: any; assignment: any; sourceRevision: string; recipientPending?: boolean }>;
|
|
29
35
|
nextCursor?: string; activity: { active: number }; nextDeadline: number | null;
|
|
30
36
|
totalMatching: number;
|
|
31
37
|
backgroundIndex?: any;
|
|
@@ -34,55 +40,126 @@ export interface WorkSnapshot {
|
|
|
34
40
|
const hash = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
35
41
|
const safeId = /^[A-Za-z0-9_-]+$/;
|
|
36
42
|
|
|
43
|
+
function healthWithThresholds(health: any, config: any, meta: any) {
|
|
44
|
+
if (!health) return undefined;
|
|
45
|
+
const value = { ...health, thresholds: healthThresholdsForConfig(config) };
|
|
46
|
+
return { ...value, nextDeadline: nextHealthDeadline(value, meta) };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function nextHealthDeadline(health: any, meta: any, now = Date.now()): number | null {
|
|
50
|
+
if (!health) return null;
|
|
51
|
+
const { thresholds } = health;
|
|
52
|
+
const facts = health.facts;
|
|
53
|
+
const tool = facts.activeTools.at(-1);
|
|
54
|
+
const toolStart = tool?.startedAt ?? facts.lastToolAt ?? facts.lastMeaningfulAt;
|
|
55
|
+
const compactionStart = facts.compactionStartedAt ?? facts.lastMeaningfulAt;
|
|
56
|
+
const anchor = facts.lastMeaningfulAt ?? meta.startedAt;
|
|
57
|
+
const deadlines: number[] = [];
|
|
58
|
+
if (["running", "orphaned"].includes(meta.status)) {
|
|
59
|
+
if (tool && Number.isFinite(toolStart)) deadlines.push(toolStart + thresholds.longToolMs);
|
|
60
|
+
if (facts.compacting && Number.isFinite(compactionStart)) deadlines.push(compactionStart + thresholds.longCompactionMs);
|
|
61
|
+
if (!tool && !facts.compacting && !["retrying", "error"].includes(facts.model.state) && Number.isFinite(anchor)) {
|
|
62
|
+
deadlines.push(anchor + thresholds.quietMs, anchor + thresholds.staleMs);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const future = deadlines.filter(deadline => deadline > now);
|
|
66
|
+
return future.length ? Math.min(...future) : null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const healthDeadlineExpired = (row: { health?: any }, now: number) => typeof row.health?.nextDeadline === "number" && row.health.nextDeadline <= now;
|
|
70
|
+
|
|
37
71
|
/** Reconstructable query state. It never authorizes execution or writes source records. */
|
|
38
72
|
export class WorkReadModel {
|
|
73
|
+
private budget: ReturnType<typeof createWorkBudget>;
|
|
39
74
|
onTerminalLogsChanged?: () => void;
|
|
40
75
|
private background: BackgroundObservation;
|
|
41
76
|
private db: any;
|
|
42
|
-
private reader
|
|
77
|
+
private reader!: ReturnType<typeof createAssignmentReader>;
|
|
43
78
|
private files = new Map<string, { signature: string; meta: any }>();
|
|
44
|
-
private projected = new Map<string, { meta: any; assignment: any; sourceRevision: string; display?: { spend: string; tool: string }; health?: any; recipientPending?: boolean; failurePending?: boolean }>();
|
|
79
|
+
private projected = new Map<string, { meta: any; assignment: any; sourceRevision: string; display?: { spend: string; tool: string; diagnostics?: string[]; coverage?: any }; health?: any; recipientPending?: boolean; failurePending?: boolean }>();
|
|
45
80
|
private logs = new Map<string, string>();
|
|
81
|
+
private parseStates = new Map();
|
|
82
|
+
private healthStates = new Map();
|
|
83
|
+
private checkpoints: LogCheckpoints;
|
|
84
|
+
private checkpointAttemptAllowed = true;
|
|
85
|
+
private checkpointFailure = false;
|
|
86
|
+
private initialization = { attempts: 0, contentions: 0 };
|
|
87
|
+
private get observationInitialized() { return this.checkpoints.ready && Boolean(this.reader) && this.background.ready; }
|
|
46
88
|
private failureJournals = new Map<string, string>();
|
|
47
89
|
private processes = new Map<string, string>();
|
|
48
90
|
private staged?: {
|
|
49
91
|
files: WorkReadModel["files"]; projected: WorkReadModel["projected"];
|
|
50
92
|
logs: Map<string, string>; failureJournals: Map<string, string>; processes: Map<string, string>; healthRevision: string;
|
|
51
|
-
coordinator: string;
|
|
93
|
+
coordinator: string;
|
|
94
|
+
assignmentChanges?: Map<string, string>; assignmentGeneration: string;
|
|
52
95
|
};
|
|
53
96
|
private healthRevision = "";
|
|
54
97
|
private details = new Map<string, { revision: string; value: any }>();
|
|
55
98
|
private watchers = new Map<string, FSWatcher>();
|
|
99
|
+
private rootParents = new Map<string, { path: string; identity: string; watcher: FSWatcher }>();
|
|
56
100
|
private rootWatchIdentities = new Map<string, string>();
|
|
57
101
|
private listeners = new Set<() => void>();
|
|
58
102
|
private timer?: ReturnType<typeof setInterval>;
|
|
59
103
|
private pending?: Promise<void>;
|
|
60
104
|
private dirty = false;
|
|
105
|
+
private sourceConflicts = 0;
|
|
106
|
+
private conflictRetry?: ReturnType<typeof setTimeout>;
|
|
107
|
+
private conflictDelay = 100;
|
|
108
|
+
private hints = new Map<string, number>();
|
|
109
|
+
private repair?: AsyncGenerator<string[]>;
|
|
110
|
+
private repairOwed = false;
|
|
111
|
+
private imported = false;
|
|
112
|
+
private repairWrite: Promise<void> = Promise.resolve();
|
|
113
|
+
private repairPersistencePending = false;
|
|
114
|
+
private sourceErrors = new Map<string, string>();
|
|
115
|
+
private sourceRace?: { reason: string; paths: Set<string>; rows: any[] };
|
|
116
|
+
private sourceStats = 0;
|
|
117
|
+
private sourceWork = { entity: { batches: 0, paths: 0, stats: 0, metadataReads: 0, logBytes: 0, logReads: 0 }, repair: { batches: 0, paths: 0, stats: 0, metadataReads: 0, logBytes: 0, logReads: 0 } };
|
|
118
|
+
private scheduling = { entityBatches: 0, repairBatches: 0, repairEntries: 0, overflows: 0, maxQueueAgeMs: 0, maxPublicationMs: 0 };
|
|
61
119
|
private closed = false;
|
|
62
120
|
private inventory = 0;
|
|
63
121
|
private coordinator = "unknown";
|
|
64
|
-
private
|
|
122
|
+
private assignmentBaseline?: { key: string; seq: string };
|
|
123
|
+
private assignmentFault?: { state: WorkSnapshot["status"]; reason?: string };
|
|
124
|
+
private unsupportedAssignmentRevision?: string;
|
|
65
125
|
private revision = 0;
|
|
126
|
+
private scopeSequence = 0;
|
|
127
|
+
private scopes = new Map<string, { scope: WorkScope; token: number; revision: number; used: number; status: string }>();
|
|
128
|
+
private changedRows: Array<{ before?: any; after?: any }> = [];
|
|
66
129
|
private foldQueueSequence = 0;
|
|
67
130
|
private state: WorkSnapshot["status"] = "rebuilding";
|
|
68
131
|
private reason: string | undefined = "Initial source inventory is rebuilding.";
|
|
69
|
-
private counters = { inventories: 0, metadataReads: 0, projections: 0 };
|
|
132
|
+
private counters = { inventories: 0, metadataReads: 0, projections: 0, assignmentProjections: 0, logProjections: 0, healthProjections: 0, failureProjections: 0, healthRecomputations: 0, healthConfigInvalidations: 0 };
|
|
133
|
+
private invalidations = { assignmentInput: 0, process: 0, log: 0, failureAttention: 0, healthConfig: 0, healthDeadline: 0, unverified: 0, initial: 0 };
|
|
134
|
+
private get assignmentMetrics() {
|
|
135
|
+
if (this.observationInitialized) {
|
|
136
|
+
try { return this.reader.changeMetrics; }
|
|
137
|
+
catch (error) { if (!isSqliteLockContention(error)) throw error; }
|
|
138
|
+
}
|
|
139
|
+
return { available: false, received: null, applied: null, pending: null };
|
|
140
|
+
}
|
|
70
141
|
get metrics() {
|
|
71
|
-
return { ...this.counters, coordinatorConnections: Number(Boolean(this.reader
|
|
72
|
-
indexConnections: this.closed ? 0 : 1, sourceWatchers: this.watchers.size };
|
|
142
|
+
return { ...this.counters, assignments: this.assignmentMetrics, initialization: { ...this.initialization }, checkpoints: { ...this.checkpoints.metrics, hotDisplay: this.parseStates.size, hotHealth: this.healthStates.size }, sourceWork: structuredClone(this.sourceWork), scheduling: { ...this.scheduling, queued: this.hints.size }, invalidations: { ...this.invalidations }, logReads: { ...logReadMetrics }, coordinatorConnections: Number(Boolean(this.reader?.connection(false))) + this.background.connectionCount,
|
|
143
|
+
indexConnections: this.closed ? 0 : 1, sourceWatchers: this.watchers.size, sourceParentWatchers: this.rootParents.size, rootParentWatchers: this.rootParents.size };
|
|
73
144
|
}
|
|
74
145
|
readonly runs: string;
|
|
75
146
|
readonly archives: string;
|
|
76
147
|
readonly markers: string;
|
|
77
148
|
readonly agentDir: string;
|
|
78
149
|
readonly instanceId: string;
|
|
150
|
+
private readonly inventoryPhase?: (phase: InventoryPhase) => void;
|
|
79
151
|
|
|
80
|
-
|
|
152
|
+
private watch: SourceWatch;
|
|
153
|
+
constructor(agentDir: string, instanceId: string, options: { supervisorDirectory?: string; baseDir?: string; durableDir?: string; intervalMs?: number; watch?: SourceWatch; budgetBuffer?: SharedArrayBuffer; inventoryPhase?: (phase: InventoryPhase) => void } = {}) {
|
|
154
|
+
this.budget = createWorkBudget(options.budgetBuffer);
|
|
155
|
+
this.watch = options.watch ?? watchSource;
|
|
81
156
|
this.agentDir = agentDir; this.instanceId = instanceId;
|
|
157
|
+
this.inventoryPhase = options.inventoryPhase;
|
|
82
158
|
const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
|
|
83
159
|
this.db = new DatabaseSync(":memory:");
|
|
84
|
-
this.
|
|
85
|
-
|
|
160
|
+
this.checkpoints = new LogCheckpoints(join(agentDir, "runtime-log-checkpoints.sqlite"), this.db, { defer: true });
|
|
161
|
+
mkdirSync(join(agentDir, "runtime-read-repair"), { recursive: true });
|
|
162
|
+
this.background = new BackgroundObservation(agentDir, options.supervisorDirectory, this.db, () => this.publish(true), refresh => this.reader?.connection(refresh), { defer: true });
|
|
86
163
|
this.db.exec(`CREATE TABLE rows (id TEXT PRIMARY KEY, cwd TEXT, origin_cwd TEXT, origin_session TEXT,
|
|
87
164
|
started REAL, state TEXT, active INTEGER, ended REAL, recipient_pending INTEGER, payload TEXT);
|
|
88
165
|
CREATE INDEX work_folder ON rows(cwd, started DESC, id DESC);
|
|
@@ -91,6 +168,8 @@ export class WorkReadModel {
|
|
|
91
168
|
CREATE INDEX work_terminal ON rows(active, ended, started DESC, id DESC);
|
|
92
169
|
CREATE INDEX work_recipient_pending ON rows(origin_cwd, origin_session, recipient_pending, started DESC, id DESC);
|
|
93
170
|
CREATE INDEX work_state ON rows(state, started DESC, id DESC);
|
|
171
|
+
CREATE TABLE assignment_members (scope TEXT NOT NULL, id TEXT NOT NULL, PRIMARY KEY(scope,id));
|
|
172
|
+
CREATE INDEX assignment_member_id ON assignment_members(id);
|
|
94
173
|
CREATE TABLE terminal_log_folds (id TEXT PRIMARY KEY, revision TEXT NOT NULL, pending INTEGER NOT NULL, queue_position INTEGER NOT NULL);
|
|
95
174
|
CREATE INDEX pending_terminal_log_folds ON terminal_log_folds(pending, queue_position, id);`);
|
|
96
175
|
this.runs = join(options.baseDir ?? join(realpathSync(tmpdir()), "pi-better-subagents"), "runs");
|
|
@@ -99,50 +178,189 @@ export class WorkReadModel {
|
|
|
99
178
|
// Watch directory entries, not file inodes. Node's Linux recursive watcher
|
|
100
179
|
// can retain a replaced file's old inode after atomic rename and miss later
|
|
101
180
|
// commits. Flat archives need one watcher; raw runs use one per directory.
|
|
102
|
-
for (const path of [this.runs, this.archives, this.markers]) this.watchDirectory(path);
|
|
103
|
-
this.timer = setInterval(() => { if (!this.pending) void this.reconcile(); }, options.intervalMs ?? 1000);
|
|
181
|
+
for (const path of [this.runs, this.archives, this.markers]) { this.watchRootParent(path); this.watchDirectory(path); }
|
|
182
|
+
this.timer = setInterval(() => { this.checkpointAttemptAllowed = true; this.repairOwed = true; if (!this.pending) void this.reconcile(false); }, options.intervalMs ?? 1000);
|
|
104
183
|
this.timer.unref();
|
|
105
184
|
}
|
|
106
185
|
|
|
107
186
|
private unwatchDirectory(path: string) {
|
|
108
187
|
this.watchers.get(path)?.close(); this.watchers.delete(path);
|
|
109
188
|
}
|
|
189
|
+
private watchRootParent(root: string) {
|
|
190
|
+
if (this.closed) return;
|
|
191
|
+
// A watch follows an inode, not the source pathname. Keep an independent
|
|
192
|
+
// parent entry watch so recreation after an observed ENOENT remains visible.
|
|
193
|
+
for (let parent = dirname(root); ; parent = dirname(parent)) {
|
|
194
|
+
const previous = this.rootParents.get(root);
|
|
195
|
+
try {
|
|
196
|
+
const info = statSync(parent, { bigint: true });
|
|
197
|
+
const identity = `${info.dev}:${info.ino}`;
|
|
198
|
+
if (previous?.path === parent && previous.identity === identity) return;
|
|
199
|
+
const entry = relative(parent, root).split(sep)[0];
|
|
200
|
+
const watcher = this.watch(parent, (_event, filename) => {
|
|
201
|
+
if (this.closed || this.rootParents.get(root)?.watcher !== watcher) return;
|
|
202
|
+
if (!filename || String(filename) === entry || String(filename) === relative(dirname(parent), parent)) void this.reconcile();
|
|
203
|
+
});
|
|
204
|
+
watcher.on("error", () => {
|
|
205
|
+
if (this.rootParents.get(root)?.watcher !== watcher) return;
|
|
206
|
+
watcher.close(); this.rootParents.delete(root);
|
|
207
|
+
this.invalidate("Source parent watcher failed; reconciling source inventory.");
|
|
208
|
+
});
|
|
209
|
+
previous?.watcher.close();
|
|
210
|
+
this.rootParents.set(root, { path: parent, identity, watcher });
|
|
211
|
+
return;
|
|
212
|
+
} catch { /* Missing source ancestors are watched from their nearest existing parent. */ }
|
|
213
|
+
if (dirname(parent) === parent) return;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
110
216
|
private watchDirectory(path: string) {
|
|
111
|
-
if (this.closed
|
|
217
|
+
if (this.closed) return;
|
|
218
|
+
let identity: string | undefined;
|
|
219
|
+
if ([this.runs, this.archives, this.markers].includes(path)) {
|
|
220
|
+
try {
|
|
221
|
+
const info = statSync(path, { bigint: true });
|
|
222
|
+
identity = `${info.dev}:${info.ino}`;
|
|
223
|
+
} catch (error) {
|
|
224
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") return;
|
|
225
|
+
}
|
|
226
|
+
if (!identity || this.rootWatchIdentities.get(path) !== identity) {
|
|
227
|
+
this.unwatchDirectory(path); this.rootWatchIdentities.delete(path);
|
|
228
|
+
if (path === this.runs) for (const child of this.watchers.keys()) if (child.startsWith(this.runs + sep)) this.unwatchDirectory(child);
|
|
229
|
+
}
|
|
230
|
+
if (!identity) return;
|
|
231
|
+
}
|
|
232
|
+
if (this.watchers.has(path)) return;
|
|
112
233
|
try {
|
|
113
|
-
const watcher = watch(path, (_event, filename) => {
|
|
234
|
+
const watcher = this.watch(path, (_event, filename) => {
|
|
235
|
+
if (this.closed || this.watchers.get(path) !== watcher) return;
|
|
114
236
|
if (path === this.runs) {
|
|
115
237
|
// A raw directory may itself have been removed/replaced. Reattach
|
|
116
238
|
// from the shared inventory, never retain its preceding inode.
|
|
117
239
|
if (filename && safeId.test(String(filename))) this.unwatchDirectory(join(this.runs, String(filename)));
|
|
118
240
|
else for (const watched of this.watchers.keys()) if (watched.startsWith(this.runs + sep)) this.unwatchDirectory(watched);
|
|
119
241
|
}
|
|
120
|
-
|
|
121
|
-
});
|
|
242
|
+
this.fileHint(path, filename ? String(filename) : undefined);
|
|
243
|
+
}, dirname(path) === this.runs);
|
|
122
244
|
watcher.on("error", () => {
|
|
123
245
|
if (this.watchers.get(path) !== watcher) return;
|
|
124
246
|
this.unwatchDirectory(path);
|
|
125
247
|
this.invalidate("Watcher overflow or failure; reconciling source inventory.");
|
|
126
248
|
});
|
|
127
249
|
this.watchers.set(path, watcher);
|
|
250
|
+
if (identity) this.rootWatchIdentities.set(path, identity);
|
|
128
251
|
} catch { /* Missing roots are discovered by the existing compatibility inventory. */ }
|
|
129
252
|
}
|
|
130
253
|
|
|
254
|
+
/** File notifications are hints, never authority. Unknown names owe scoped repair. */
|
|
255
|
+
fileHint(directory: string, name?: string) {
|
|
256
|
+
// Some fs.watch backends report the watched directory's own name for a
|
|
257
|
+
// contained write. It identifies a source to verify, not a child entry.
|
|
258
|
+
if (name === basename(directory)) {
|
|
259
|
+
name = directory.startsWith(this.runs + sep) ? "meta.json" : undefined;
|
|
260
|
+
}
|
|
261
|
+
let path: string | undefined;
|
|
262
|
+
if (directory === this.runs && name && safeId.test(name)) path = join(directory, name, "meta.json");
|
|
263
|
+
else if ([this.archives, this.markers].includes(directory) && name && /^[A-Za-z0-9_-]+\.json$/.test(name)) path = join(directory, name);
|
|
264
|
+
else if (directory.startsWith(this.runs + sep) && name && ["meta.json", "output.log", "failures.jsonl", "failures.jsonl.observed"].includes(name)) path = join(directory, "meta.json");
|
|
265
|
+
else if (name) return; // Locks, temporary files and coordinator controls are not task inputs.
|
|
266
|
+
if (!path) { this.repairOwed = true; void this.reconcile(false); return; }
|
|
267
|
+
if (!this.hints.has(path)) {
|
|
268
|
+
if (this.hints.size >= 256) {
|
|
269
|
+
this.scheduling.overflows++; this.repairOwed = true;
|
|
270
|
+
// Persist the bounded source scope before discarding the individual hint.
|
|
271
|
+
if (!this.repairPersistencePending) {
|
|
272
|
+
this.repairPersistencePending = true;
|
|
273
|
+
this.repairWrite = this.persistRepair().finally(() => { this.repairPersistencePending = false; });
|
|
274
|
+
void this.repairWrite.then(() => this.reconcile(false)).catch(error => this.invalidate(String(error)));
|
|
275
|
+
}
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
this.hints.set(path, Date.now());
|
|
279
|
+
}
|
|
280
|
+
void this.reconcile(false);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
private async persistRepair() {
|
|
284
|
+
const directory = join(this.agentDir, "runtime-read-repair");
|
|
285
|
+
await mkdir(directory, { recursive: true });
|
|
286
|
+
const path = join(directory, "subagents.json");
|
|
287
|
+
await writeFile(path + ".tmp", JSON.stringify({ version: 1, roots: [this.runs, this.archives, this.markers] }));
|
|
288
|
+
await rename(path + ".tmp", path);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
private async *repairPaths(): AsyncGenerator<string[]> {
|
|
292
|
+
// Check known paths too: an incomplete walk never deletes unseen records.
|
|
293
|
+
// Discovery and failed-source repair can overlap these paths. Retry each
|
|
294
|
+
// source once per pass, not once per inventory route.
|
|
295
|
+
const seen = new Set<string>();
|
|
296
|
+
let batch: string[] = [];
|
|
297
|
+
for (const path of this.files.keys()) {
|
|
298
|
+
seen.add(path);
|
|
299
|
+
batch.push(path);
|
|
300
|
+
if (batch.length === 128) { yield batch; batch = []; }
|
|
301
|
+
}
|
|
302
|
+
// Failed first reads have no verified file entry, but still owe repair.
|
|
303
|
+
for (const path of this.sourceErrors.keys()) {
|
|
304
|
+
if (seen.has(path)) continue;
|
|
305
|
+
seen.add(path);
|
|
306
|
+
batch.push(path);
|
|
307
|
+
if (batch.length === 128) { yield batch; batch = []; }
|
|
308
|
+
}
|
|
309
|
+
for (const directory of [this.markers, this.archives, this.runs]) {
|
|
310
|
+
this.watchRootParent(directory);
|
|
311
|
+
let handle;
|
|
312
|
+
try {
|
|
313
|
+
const info = await stat(directory, { bigint: true });
|
|
314
|
+
const identity = `${info.dev}:${info.ino}`;
|
|
315
|
+
if (this.rootWatchIdentities.get(directory) !== identity) {
|
|
316
|
+
this.unwatchDirectory(directory);
|
|
317
|
+
if (directory === this.runs) for (const path of this.watchers.keys()) if (path.startsWith(this.runs + sep)) this.unwatchDirectory(path);
|
|
318
|
+
}
|
|
319
|
+
this.watchDirectory(directory);
|
|
320
|
+
handle = await opendir(directory);
|
|
321
|
+
} catch (error) {
|
|
322
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
323
|
+
this.unwatchDirectory(directory);
|
|
324
|
+
this.rootWatchIdentities.delete(directory);
|
|
325
|
+
if (directory === this.runs) for (const path of this.watchers.keys()) if (path.startsWith(this.runs + sep)) this.unwatchDirectory(path);
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
for await (const entry of handle) {
|
|
329
|
+
if (directory === this.runs ? safeId.test(entry.name) : /^[A-Za-z0-9_-]+\.json$/.test(entry.name)) {
|
|
330
|
+
const path = directory === this.runs ? join(directory, entry.name, "meta.json") : join(directory, entry.name);
|
|
331
|
+
if (seen.has(path)) continue;
|
|
332
|
+
seen.add(path);
|
|
333
|
+
batch.push(path);
|
|
334
|
+
if (batch.length === 128) { yield batch; batch = []; }
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
if (batch.length) yield batch;
|
|
339
|
+
}
|
|
340
|
+
|
|
131
341
|
onChange(listener: () => void, scope?: WorkScope) {
|
|
342
|
+
if (scope) scope = { ...scope, cursor: undefined };
|
|
132
343
|
const release = scope?.background ? this.background.retain(scope) : undefined;
|
|
133
|
-
this.
|
|
134
|
-
|
|
344
|
+
let revision = scope ? this.contentRevision(scope) : undefined;
|
|
345
|
+
const notify = () => {
|
|
346
|
+
const next = scope ? this.contentRevision(scope) : undefined;
|
|
347
|
+
if (scope && next === revision) return;
|
|
348
|
+
revision = next; listener();
|
|
349
|
+
};
|
|
350
|
+
this.listeners.add(notify);
|
|
351
|
+
return () => { this.listeners.delete(notify); release?.(); };
|
|
135
352
|
}
|
|
136
|
-
get backgroundMetrics() { return { ...this.background.metrics, scopes: this.background.scopeCount, history: this.background.historyMetrics }; }
|
|
137
|
-
observation(reasons = this.livenessReasons({ refresh: false })) {
|
|
353
|
+
get backgroundMetrics() { return { ...this.background.metrics, registry: this.background.registryMetrics, changes: this.background.changeMetrics, scopes: this.background.scopeCount, history: this.background.historyMetrics }; }
|
|
354
|
+
observation(reasons = this.observationInitialized ? this.livenessReasons({ refresh: false }) : []) {
|
|
138
355
|
return { status: this.state, reason: this.reason, observedAt: Date.now(), reasons };
|
|
139
356
|
}
|
|
140
357
|
livenessReasons(options: { refresh?: boolean } = {}) {
|
|
358
|
+
if (!this.observationInitialized) throw new Error(`Runtime observation ${this.state}: checkpoint coverage is unverified (including assignment and Background inboxes)`);
|
|
141
359
|
return [
|
|
142
360
|
...[...this.projected.values()].filter(row => row.meta.status === "running"
|
|
143
361
|
&& processMatchesStart(row.meta.pid, row.meta.pidStartTime))
|
|
144
362
|
.map(row => ({ kind: "worker", id: row.meta.id, owner: row.meta.callbackOrigin,
|
|
145
|
-
lastProgressAt: row.meta.startedAt, nextDeadline:
|
|
363
|
+
lastProgressAt: row.meta.startedAt, nextDeadline: nextHealthDeadline(row.health, row.meta), recovery: "observe-existing-worker" })),
|
|
146
364
|
...this.background.livenessReasons(options),
|
|
147
365
|
];
|
|
148
366
|
}
|
|
@@ -164,7 +382,7 @@ export class WorkReadModel {
|
|
|
164
382
|
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
165
383
|
try {
|
|
166
384
|
return await Promise.race([
|
|
167
|
-
this.
|
|
385
|
+
(this.fileHint(this.runs, id), this.pending ?? Promise.resolve()).then(() => !!this.db.prepare("SELECT id FROM rows WHERE id = ?").get(id)),
|
|
168
386
|
new Promise<false>(resolve => { timeout = setTimeout(() => resolve(false), 100); }),
|
|
169
387
|
]);
|
|
170
388
|
} finally {
|
|
@@ -172,62 +390,325 @@ export class WorkReadModel {
|
|
|
172
390
|
}
|
|
173
391
|
}
|
|
174
392
|
invalidate(reason: string) {
|
|
393
|
+
const changed = this.state !== "degraded" || this.reason !== reason;
|
|
175
394
|
this.state = "degraded"; this.reason = reason;
|
|
176
|
-
this.publish();
|
|
395
|
+
if (changed) this.publish();
|
|
177
396
|
void this.reconcile();
|
|
178
397
|
}
|
|
179
|
-
private
|
|
398
|
+
private scopeKey(scope: WorkScope) { return hash({ ...scope, cursor: undefined }); }
|
|
399
|
+
private scopeEntry(scope: WorkScope) {
|
|
400
|
+
const key = this.scopeKey(scope), now = Date.now();
|
|
401
|
+
for (const [id, entry] of this.scopes) if (now - entry.used >= 300000) this.scopes.delete(id);
|
|
402
|
+
let entry = this.scopes.get(key);
|
|
403
|
+
if (!entry) {
|
|
404
|
+
if (scope.cursor) throw new Error("resync_required: cursor retention expired");
|
|
405
|
+
if (this.scopes.size >= 128) this.scopes.delete(this.scopes.keys().next().value!);
|
|
406
|
+
entry = { scope: { ...scope, cursor: undefined }, token: ++this.scopeSequence, revision: 0, used: now, status: hash(this.scopeStatus(scope)) };
|
|
407
|
+
this.scopes.set(key, entry);
|
|
408
|
+
}
|
|
409
|
+
entry.used = now;
|
|
410
|
+
return entry;
|
|
411
|
+
}
|
|
412
|
+
contentRevision(scope: WorkScope = {}) {
|
|
413
|
+
if (scope.background) {
|
|
414
|
+
if (scope.backgroundHistory) return String(this.revision);
|
|
415
|
+
this.background.prepareQuery();
|
|
416
|
+
return hash([this.revision, this.background.sourceRevision(scope)]);
|
|
417
|
+
}
|
|
418
|
+
const entry = this.scopeEntry(scope);
|
|
419
|
+
return `${entry.token}:${entry.revision}`;
|
|
420
|
+
}
|
|
421
|
+
private matchesScope(scope: WorkScope, row: any, activity = false) {
|
|
422
|
+
if (!row) return false;
|
|
423
|
+
const m = row.meta;
|
|
424
|
+
if (scope.id && scope.id !== m.id) return false;
|
|
425
|
+
if (scope.sessionId) {
|
|
426
|
+
if (scope.sessionId !== m.callbackOrigin?.sessionId || scope.cwd !== (m.callbackOrigin?.cwd ?? m.cwd)) return false;
|
|
427
|
+
} else if (scope.cwd) {
|
|
428
|
+
const cwd = resolve(scope.cwd), prefix = cwd.endsWith(sep) ? cwd : cwd + sep;
|
|
429
|
+
const folder = discoveryWorkspace(m);
|
|
430
|
+
if (folder !== cwd && !folder.startsWith(prefix)) return false;
|
|
431
|
+
}
|
|
432
|
+
const active = ["running", "waiting"].includes(row.assignment.state);
|
|
433
|
+
if (activity) return active;
|
|
434
|
+
return (scope.active === undefined || scope.active === active)
|
|
435
|
+
&& (scope.pendingRecipient === undefined || scope.pendingRecipient === !!row.recipientPending)
|
|
436
|
+
&& (scope.endedAfter === undefined || (m.endedAt ?? m.lostAt ?? Infinity) >= scope.endedAfter)
|
|
437
|
+
&& (!scope.statuses?.length || scope.statuses.includes(row.assignment.state));
|
|
438
|
+
}
|
|
439
|
+
private publish(backgroundOnly = false) {
|
|
440
|
+
this.revision++;
|
|
441
|
+
for (const entry of this.scopes.values()) {
|
|
442
|
+
if (backgroundOnly) continue;
|
|
443
|
+
const status = hash(this.scopeStatus(entry.scope));
|
|
444
|
+
if (entry.status !== status || this.changedRows.some(({ before, after }) =>
|
|
445
|
+
this.matchesScope(entry.scope, before) || this.matchesScope(entry.scope, after)
|
|
446
|
+
|| this.matchesScope(entry.scope, before, true) !== this.matchesScope(entry.scope, after, true))) entry.revision++;
|
|
447
|
+
entry.status = status;
|
|
448
|
+
}
|
|
449
|
+
this.changedRows = [];
|
|
450
|
+
for (const listener of this.listeners) listener();
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/** Ordinary coordinator commits use the reverse scope index, not the source inventory. */
|
|
454
|
+
private refreshAssignments(baselineOnly = false) {
|
|
455
|
+
if ((!this.imported && !baselineOnly) || this.staged || this.reader.snapshotActive) return;
|
|
456
|
+
let release: (() => void) | undefined;
|
|
457
|
+
let revision: string | undefined;
|
|
458
|
+
try {
|
|
459
|
+
if (this.unsupportedAssignmentRevision && this.unsupportedAssignmentRevision === this.reader.revision()) return;
|
|
460
|
+
this.unsupportedAssignmentRevision = undefined;
|
|
461
|
+
const changes = this.reader.changes();
|
|
462
|
+
const snapshot = this.reader.beginSnapshot(); release = snapshot.release;
|
|
463
|
+
revision = snapshot.revision;
|
|
464
|
+
if (changes.has("*")) {
|
|
465
|
+
const key = `${this.reader.changeMetrics.generation}:${changes.get("*")}`;
|
|
466
|
+
if (baselineOnly) {
|
|
467
|
+
this.assignmentBaseline = { key, seq: changes.get("*")! };
|
|
468
|
+
this.coordinator = snapshot.revision;
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
if (this.assignmentBaseline?.key === key) return;
|
|
472
|
+
this.imported = false; this.repairOwed = true;
|
|
473
|
+
if (!this.sourceErrors.size) { this.state = "rebuilding"; this.reason = "Assignment source baseline is rebuilding."; }
|
|
474
|
+
this.publish(); return;
|
|
475
|
+
}
|
|
476
|
+
const selected = new Map<string, any>();
|
|
477
|
+
const select = this.db.prepare("SELECT r.payload FROM assignment_members m JOIN rows r ON r.id=m.id WHERE m.scope=?");
|
|
478
|
+
for (const scope of changes.keys()) for (const record of select.all(scope)) {
|
|
479
|
+
const row = JSON.parse(record.payload); selected.set(row.meta.id, row);
|
|
480
|
+
}
|
|
481
|
+
const project = createAssignmentProjector({ attempts: [...selected.values()].map(row => row.meta), observe: (owner: any) => this.reader.read(owner) });
|
|
482
|
+
const updated: any[] = [];
|
|
483
|
+
for (const row of selected.values()) {
|
|
484
|
+
const meta = row.meta;
|
|
485
|
+
const assignment = project(meta, this.processes.get(meta.id) ?? meta.status);
|
|
486
|
+
if (!assignment.verified) throw new Error(`Assignment observation is unverified: ${meta.id}`);
|
|
487
|
+
const outcome = meta.assignment ? this.reader.read({ ...meta.assignment.owner, assignmentId: meta.assignment.assignmentId }).outcome : undefined;
|
|
488
|
+
const recipientPending = Boolean(row.failurePending || meta.timing?.pendingWakes?.length
|
|
489
|
+
|| (meta.status === "orphaned" && meta.orphanedCallbackSentAt === undefined && meta.orphanedCallbackSuppressedAt === undefined)
|
|
490
|
+
|| (meta.status === "lost" && meta.lostCallbackSentAt === undefined && meta.lostCallbackSuppressedAt === undefined)
|
|
491
|
+
|| (meta.callback !== false && (meta.assignment ? outcome && !outcome.deliveryReceipt && !outcome.disposition
|
|
492
|
+
: meta.completionCallbackPendingAt !== undefined && meta.completionCallbackSentAt === undefined && meta.completionCallbackSuppressedAt === undefined)));
|
|
493
|
+
updated.push({ ...row, assignment, recipientPending, sourceRevision: hash([meta, assignment.revision, row.display, row.health, recipientPending, row.failurePending, this.failureJournals.get(meta.id)]) });
|
|
494
|
+
}
|
|
495
|
+
let changed = false;
|
|
496
|
+
const changedRows: WorkReadModel["changedRows"] = [];
|
|
497
|
+
this.db.exec("SAVEPOINT assignment_refresh");
|
|
498
|
+
try {
|
|
499
|
+
const update = this.db.prepare("UPDATE rows SET state=?, active=?, recipient_pending=?, payload=? WHERE id=?");
|
|
500
|
+
for (const row of updated) {
|
|
501
|
+
if (row.sourceRevision === this.projected.get(row.meta.id)?.sourceRevision) continue;
|
|
502
|
+
update.run(row.assignment.state, ["running", "waiting"].includes(row.assignment.state) ? 1 : 0, row.recipientPending ? 1 : 0, JSON.stringify(row), row.meta.id);
|
|
503
|
+
changedRows.push({ before: this.projected.get(row.meta.id), after: row });
|
|
504
|
+
changed = true;
|
|
505
|
+
}
|
|
506
|
+
this.db.exec("RELEASE assignment_refresh");
|
|
507
|
+
} catch (error) { this.db.exec("ROLLBACK TO assignment_refresh; RELEASE assignment_refresh"); throw error; }
|
|
508
|
+
// A crash after application but before acknowledgement safely repeats this batch.
|
|
509
|
+
this.reader.acknowledgeChanges(changes, false);
|
|
510
|
+
snapshot.commit();
|
|
511
|
+
for (const row of updated) this.projected.set(row.meta.id, row);
|
|
512
|
+
if (this.reader.changeMetrics.more || this.reader.changeMetrics.pending) this.dirty = true;
|
|
513
|
+
this.coordinator = snapshot.revision;
|
|
514
|
+
this.counters.assignmentProjections += updated.length; this.counters.projections += updated.length;
|
|
515
|
+
this.invalidations.assignmentInput += updated.length;
|
|
516
|
+
this.changedRows = changedRows;
|
|
517
|
+
if (this.assignmentFault) {
|
|
518
|
+
this.state = this.assignmentFault.state; this.reason = this.assignmentFault.reason;
|
|
519
|
+
this.assignmentFault = undefined; this.changedRows = []; changed = true;
|
|
520
|
+
}
|
|
521
|
+
if (changed) this.publish();
|
|
522
|
+
} catch (error) {
|
|
523
|
+
release?.(); release = undefined;
|
|
524
|
+
if (!this.projected.size) return;
|
|
525
|
+
// A coordinator has never been required for plain archived/log-only runs.
|
|
526
|
+
// Losing an already observed database still degrades the existing coverage.
|
|
527
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT" && this.coordinator === "unknown") return;
|
|
528
|
+
if (error instanceof Error && error.message === "Unsupported assignment source schema") this.unsupportedAssignmentRevision = revision;
|
|
529
|
+
this.assignmentFault ??= { state: this.state, reason: this.reason };
|
|
530
|
+
if (/no such table: (?:coordinator_source\.)?assignment_change_source$/.test(String(error))) {
|
|
531
|
+
// Old sources have no feed. Finish one budgeted compatibility pass;
|
|
532
|
+
// continuous legacy writes do not restart a pass already in progress.
|
|
533
|
+
this.imported = false; this.repairOwed = true; this.state = "rebuilding";
|
|
534
|
+
} else this.state = "degraded";
|
|
535
|
+
this.reason = String(error).slice(0, 512); this.publish();
|
|
536
|
+
} finally { release?.(); }
|
|
537
|
+
}
|
|
180
538
|
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
539
|
+
private scopeStatus(scope: WorkScope): { status: WorkSnapshot["status"]; reason?: string } {
|
|
540
|
+
const race = this.sourceRace;
|
|
541
|
+
// Only a validated, entity-attributed retry can leave another scope ready.
|
|
542
|
+
// Root, coordinator, unattributed and initial-import failures stay global.
|
|
543
|
+
if (this.imported && this.state === "degraded" && race && this.reason === race.reason
|
|
544
|
+
&& [...this.sourceErrors.keys()].every(path => race.paths.has(path))
|
|
545
|
+
&& !race.rows.some(row => this.matchesScope({ id: scope.id, cwd: scope.cwd, sessionId: scope.sessionId }, row))) {
|
|
546
|
+
return { status: "ready" };
|
|
547
|
+
}
|
|
548
|
+
return { status: this.state, reason: this.reason };
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
private rejectUnsupportedAssignmentRevision(): boolean {
|
|
552
|
+
let release: (() => void) | undefined;
|
|
553
|
+
try {
|
|
554
|
+
if (this.unsupportedAssignmentRevision) {
|
|
555
|
+
if (this.unsupportedAssignmentRevision === this.reader.revision()) return true;
|
|
556
|
+
this.unsupportedAssignmentRevision = undefined;
|
|
557
|
+
}
|
|
558
|
+
const connection = this.reader.connection(false);
|
|
559
|
+
const supported = (version: unknown) => version === undefined || (typeof version === "string" && ["1", "2", "3", "4"].includes(version));
|
|
560
|
+
if (!connection || supported(connection.prepare("SELECT value FROM schema_meta WHERE key='schema_version'").get()?.value)) return false;
|
|
561
|
+
const snapshot = this.reader.beginSnapshot(); release = snapshot.release;
|
|
562
|
+
const version = this.reader.connection(false).prepare("SELECT value FROM schema_meta WHERE key='schema_version'").get()?.value;
|
|
563
|
+
if (!supported(version)) {
|
|
564
|
+
this.unsupportedAssignmentRevision = snapshot.revision;
|
|
565
|
+
const reason = "Unsupported assignment source schema";
|
|
566
|
+
const changed = this.state !== "degraded" || this.reason !== reason;
|
|
567
|
+
this.state = "degraded"; this.reason = reason;
|
|
568
|
+
if (changed) this.publish();
|
|
569
|
+
return true;
|
|
570
|
+
}
|
|
571
|
+
} catch {
|
|
572
|
+
// Missing/initializing sources still follow the ordinary verification path.
|
|
573
|
+
this.unsupportedAssignmentRevision = undefined;
|
|
574
|
+
} finally { release?.(); }
|
|
575
|
+
return false;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
reconcile(drain = true): Promise<void> {
|
|
579
|
+
if (this.closed || this.conflictRetry) return Promise.resolve();
|
|
580
|
+
if (this.pending) {
|
|
581
|
+
return drain && this.observationInitialized ? this.pending.then(() => this.reconcile()) : this.pending;
|
|
582
|
+
}
|
|
583
|
+
const release = this.budget.enter("repair");
|
|
584
|
+
if (!release) return Promise.resolve();
|
|
184
585
|
this.pending = (async () => {
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
if (!this.
|
|
586
|
+
await this.watchRegistrations();
|
|
587
|
+
if (this.closed) return;
|
|
588
|
+
if (!this.observationInitialized) {
|
|
589
|
+
if (!this.checkpointAttemptAllowed || this.checkpointFailure) return;
|
|
590
|
+
this.checkpointAttemptAllowed = false;
|
|
591
|
+
this.initialization.attempts++;
|
|
592
|
+
let initialized: boolean;
|
|
593
|
+
try {
|
|
594
|
+
if (this.db.isTransaction) throw new Error("Derived observation initialization requires an unpinned owner");
|
|
595
|
+
initialized = this.checkpoints.initialize();
|
|
596
|
+
if (initialized) this.reader ??= createAssignmentReader(join(this.agentDir, "operation-coordinator.sqlite"),
|
|
597
|
+
join(this.agentDir, "runtime-read-repair", "assignments.sqlite"), this.db, { composed: true });
|
|
598
|
+
if (initialized) this.background.initialize();
|
|
599
|
+
} catch (error) {
|
|
600
|
+
if (isSqliteLockContention(error)) initialized = false;
|
|
601
|
+
else { this.checkpointFailure = true; throw error; }
|
|
602
|
+
}
|
|
603
|
+
if (!initialized) {
|
|
604
|
+
this.initialization.contentions++;
|
|
605
|
+
const reason = "Derived checkpoint, assignment or Background inbox acquisition is contended; source coverage remains unverified.";
|
|
606
|
+
if (this.reason !== reason) { this.state = "rebuilding"; this.reason = reason; this.publish(); }
|
|
607
|
+
return;
|
|
608
|
+
}
|
|
189
609
|
}
|
|
190
|
-
|
|
610
|
+
let resetRepair = drain;
|
|
611
|
+
do {
|
|
612
|
+
this.dirty = false;
|
|
613
|
+
// Background progress is independent of whether Subagent repair finds files.
|
|
614
|
+
this.inventoryPhase?.("background");
|
|
615
|
+
if (this.background.refresh()) this.publish(true);
|
|
616
|
+
if (this.rejectUnsupportedAssignmentRevision()) break;
|
|
617
|
+
this.refreshAssignments();
|
|
618
|
+
// Metadata repair cannot verify an incompatible coordinator. Keep its
|
|
619
|
+
// obligations and last verified rows until a different source revision.
|
|
620
|
+
if (this.unsupportedAssignmentRevision) break;
|
|
621
|
+
if (resetRepair && this.repair) { await this.repair.return(undefined); this.repair = undefined; }
|
|
622
|
+
resetRepair = false;
|
|
623
|
+
if (this.hints.size) {
|
|
624
|
+
const entries = workPage(this.hints);
|
|
625
|
+
for (const [path, queued] of entries) { this.hints.delete(path); this.scheduling.maxQueueAgeMs = Math.max(this.scheduling.maxQueueAgeMs, Date.now() - queued); }
|
|
626
|
+
this.scheduling.entityBatches++;
|
|
627
|
+
const started = performance.now();
|
|
628
|
+
await this.measuredScan("entity", entries.map(([path]) => path));
|
|
629
|
+
this.scheduling.maxPublicationMs = Math.max(this.scheduling.maxPublicationMs, performance.now() - started);
|
|
630
|
+
if (this.sourceConflicts > 1) break;
|
|
631
|
+
}
|
|
632
|
+
if (!this.repair && this.imported && !drain && !this.repairOwed) {
|
|
633
|
+
if (this.hints.size) { await yieldTurn(); continue; }
|
|
634
|
+
break;
|
|
635
|
+
}
|
|
636
|
+
this.repair ??= this.repairPaths();
|
|
637
|
+
const next = await this.repair.next();
|
|
638
|
+
if (next.done) {
|
|
639
|
+
await this.watchRegistrations();
|
|
640
|
+
this.repair = undefined; this.repairOwed = false;
|
|
641
|
+
// An empty metadata inventory still needs a journal baseline before
|
|
642
|
+
// later exact hints can be treated as incremental updates.
|
|
643
|
+
if (!this.imported && !this.assignmentBaseline && !this.files.size && !this.sourceErrors.size) this.refreshAssignments(true);
|
|
644
|
+
if (this.assignmentBaseline && !this.sourceErrors.size && ![...this.projected.values()].some(row => !row.assignment.verified)) this.reader.acknowledgeChanges(new Map([["*", this.assignmentBaseline.seq]]), true);
|
|
645
|
+
if (!this.imported) {
|
|
646
|
+
this.imported = true;
|
|
647
|
+
const degraded = this.state === "degraded" || this.sourceErrors.size || [...this.projected.values()].some(row => !row.assignment.verified);
|
|
648
|
+
this.state = degraded ? "degraded" : "ready";
|
|
649
|
+
this.reason = this.state === "ready" ? undefined : this.sourceErrors.values().next().value ?? this.reason ?? "Some assignment sources could not be verified.";
|
|
650
|
+
this.publish();
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
else { this.scheduling.repairBatches++; this.scheduling.repairEntries += next.value.length; await this.measuredScan("repair", next.value); }
|
|
654
|
+
await yieldTurn();
|
|
655
|
+
if (this.closed || this.sourceConflicts > 1 || (!drain && !this.hints.size)) break;
|
|
656
|
+
} while (this.repair || this.hints.size);
|
|
657
|
+
})().catch(error => {
|
|
658
|
+
this.repair = undefined; this.state = "degraded"; this.reason = String(error).slice(0, 512); this.publish();
|
|
659
|
+
}).finally(() => {
|
|
660
|
+
this.inventoryPhase?.("idle");
|
|
661
|
+
release();
|
|
191
662
|
this.pending = undefined;
|
|
192
|
-
if (this.
|
|
663
|
+
if (this.observationInitialized && (this.hints.size || this.dirty) && !this.closed && !this.unsupportedAssignmentRevision) {
|
|
664
|
+
this.dirty = false;
|
|
665
|
+
if (this.sourceConflicts > 1) {
|
|
666
|
+
this.conflictRetry = setTimeout(() => {
|
|
667
|
+
this.conflictRetry = undefined;
|
|
668
|
+
void this.reconcile(false);
|
|
669
|
+
}, this.conflictDelay);
|
|
670
|
+
this.conflictRetry.unref();
|
|
671
|
+
this.conflictDelay = Math.min(1000, this.conflictDelay * 2);
|
|
672
|
+
} else void this.reconcile(false);
|
|
673
|
+
}
|
|
193
674
|
});
|
|
194
675
|
return this.pending;
|
|
195
676
|
}
|
|
196
677
|
|
|
197
|
-
private async
|
|
678
|
+
private async measuredScan(kind: "entity" | "repair", paths: string[]) {
|
|
679
|
+
const before = { stats: this.sourceStats, metadataReads: this.counters.metadataReads, logBytes: logReadMetrics.bytes, logReads: logReadMetrics.reads };
|
|
680
|
+
await this.scan(paths);
|
|
681
|
+
const counter = this.sourceWork[kind]; counter.batches++; counter.paths += paths.length;
|
|
682
|
+
counter.stats += this.sourceStats - before.stats; counter.metadataReads += this.counters.metadataReads - before.metadataReads;
|
|
683
|
+
counter.logBytes += logReadMetrics.bytes - before.logBytes; counter.logReads += logReadMetrics.reads - before.logReads;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
private async watchRegistrations() {
|
|
687
|
+
await Promise.all([...this.watchers.values(), ...[...this.rootParents.values()].map(value => value.watcher)].map(watcher => watcher.ready));
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
private async scan(paths: string[]) {
|
|
691
|
+
let sourceConflict = false;
|
|
692
|
+
this.assignmentFault = undefined;
|
|
693
|
+
const sourceStat: typeof stat = ((...args: any[]) => { this.sourceStats++; return (stat as any)(...args); }) as typeof stat;
|
|
198
694
|
this.counters.inventories++;
|
|
199
|
-
if (this.background.refresh()) this.publish();
|
|
200
695
|
let releaseCoordinator: (() => void) | undefined;
|
|
696
|
+
let commitCoordinator: (() => void) | undefined;
|
|
697
|
+
const checkpointWrites: Array<[string, unknown]> = [];
|
|
698
|
+
const parseBefore = new Map(this.parseStates), healthBefore = new Map(this.healthStates);
|
|
699
|
+
let sourceRace: WorkReadModel["sourceRace"];
|
|
201
700
|
const baseline = this.staged ?? { files: this.files, projected: this.projected, logs: this.logs, failureJournals: this.failureJournals, processes: this.processes,
|
|
202
|
-
healthRevision: this.healthRevision, coordinator: this.coordinator
|
|
701
|
+
healthRevision: this.healthRevision, coordinator: this.coordinator };
|
|
203
702
|
try {
|
|
204
|
-
|
|
703
|
+
this.inventoryPhase?.("metadata");
|
|
704
|
+
const next = new Map(baseline.files);
|
|
705
|
+
const failedPaths = new Map<string, string>();
|
|
706
|
+
const malformedPaths = new Set<string>();
|
|
205
707
|
let batch = 0;
|
|
206
708
|
let sliceStarted = performance.now();
|
|
207
709
|
for (const [directory, archived] of [[this.markers, true], [this.archives, true], [this.runs, false]] as const) {
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
catch (error) {
|
|
211
|
-
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
212
|
-
this.unwatchDirectory(directory); this.rootWatchIdentities.delete(directory);
|
|
213
|
-
if (!archived) for (const watched of this.watchers.keys()) if (watched.startsWith(this.runs + sep)) this.unwatchDirectory(watched);
|
|
214
|
-
continue;
|
|
215
|
-
}
|
|
216
|
-
// Three root identities per inventory, independent of archive/client
|
|
217
|
-
// cardinality. A root can be replaced without an observed ENOENT gap.
|
|
218
|
-
const rootInfo = await stat(directory, { bigint: true });
|
|
219
|
-
const rootIdentity = `${rootInfo.dev}:${rootInfo.ino}`;
|
|
220
|
-
const previousRootIdentity = this.rootWatchIdentities.get(directory);
|
|
221
|
-
if (previousRootIdentity !== undefined && previousRootIdentity !== rootIdentity) {
|
|
222
|
-
this.unwatchDirectory(directory);
|
|
223
|
-
if (!archived) for (const watched of this.watchers.keys()) if (watched.startsWith(this.runs + sep)) this.unwatchDirectory(watched);
|
|
224
|
-
}
|
|
225
|
-
this.rootWatchIdentities.set(directory, rootIdentity);
|
|
226
|
-
this.watchDirectory(directory);
|
|
227
|
-
if (!archived) {
|
|
228
|
-
const present = new Set(names.filter(name => safeId.test(name)).map(name => join(directory, name)));
|
|
229
|
-
for (const watched of this.watchers.keys()) if (watched.startsWith(this.runs + sep) && !present.has(watched)) this.unwatchDirectory(watched);
|
|
230
|
-
}
|
|
710
|
+
const names = paths.filter(path => archived ? path.startsWith(directory + sep) && !path.slice(directory.length + 1).includes(sep)
|
|
711
|
+
: path.startsWith(directory + sep)).map(path => archived ? path.slice(directory.length + 1) : path.slice(directory.length + 1).split(sep)[0]!);
|
|
231
712
|
// Bound filesystem concurrency without serializing every archive round trip.
|
|
232
713
|
const candidates = names.filter(name => safeId.test(archived ? name.replace(/\.json$/, "") : name)
|
|
233
714
|
&& (!archived || name.endsWith(".json")));
|
|
@@ -236,7 +717,7 @@ export class WorkReadModel {
|
|
|
236
717
|
const observations = await Promise.all(group.map(async name => {
|
|
237
718
|
if (!archived) this.watchDirectory(join(directory, name));
|
|
238
719
|
const path = archived ? join(directory, name) : join(directory, name, "meta.json");
|
|
239
|
-
try { return { info: await
|
|
720
|
+
try { return { info: await sourceStat(path, { bigint: true }) }; }
|
|
240
721
|
catch (error) { return { error }; }
|
|
241
722
|
}));
|
|
242
723
|
for (const [index, name] of group.entries()) {
|
|
@@ -247,8 +728,9 @@ export class WorkReadModel {
|
|
|
247
728
|
if (!observation.info) throw observation.error;
|
|
248
729
|
const info = observation.info;
|
|
249
730
|
const signature = `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
|
|
250
|
-
let entry =
|
|
731
|
+
let entry = next.get(path);
|
|
251
732
|
if (entry?.signature !== signature) {
|
|
733
|
+
if (info.size > 1024n * 1024n) throw new Error(`Run metadata exceeds the 1 MiB observation budget: ${id}`);
|
|
252
734
|
this.counters.metadataReads++;
|
|
253
735
|
const raw = await readFile(path, "utf8");
|
|
254
736
|
if (directory === this.markers) {
|
|
@@ -264,7 +746,29 @@ export class WorkReadModel {
|
|
|
264
746
|
}
|
|
265
747
|
next.set(path, entry!);
|
|
266
748
|
} catch (error) {
|
|
267
|
-
if (
|
|
749
|
+
if (!archived && error instanceof SyntaxError && this.files.has(path)) malformedPaths.add(path);
|
|
750
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
|
751
|
+
try {
|
|
752
|
+
await sourceStat(directory);
|
|
753
|
+
next.delete(path);
|
|
754
|
+
if (!archived) {
|
|
755
|
+
// A mkdir notification can arrive before its metadata commit.
|
|
756
|
+
// Retire the inode watcher only when the directory is gone.
|
|
757
|
+
try { await sourceStat(join(directory, name)); }
|
|
758
|
+
catch (error) {
|
|
759
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
760
|
+
this.unwatchDirectory(join(directory, name));
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
} catch {
|
|
764
|
+
failedPaths.set(path, `Source directory unavailable; retaining verified records: ${directory}`);
|
|
765
|
+
}
|
|
766
|
+
} else failedPaths.set(path, String(error).slice(0, 512));
|
|
767
|
+
if (failedPaths.has(path)) {
|
|
768
|
+
const verified = this.files.get(path);
|
|
769
|
+
if (verified) next.set(path, verified);
|
|
770
|
+
else next.delete(path);
|
|
771
|
+
}
|
|
268
772
|
}
|
|
269
773
|
if (++batch % 256 === 0 || performance.now() - sliceStarted >= 8) {
|
|
270
774
|
await yieldTurn(); sliceStarted = performance.now();
|
|
@@ -273,12 +777,26 @@ export class WorkReadModel {
|
|
|
273
777
|
}
|
|
274
778
|
}
|
|
275
779
|
}
|
|
780
|
+
this.inventoryPhase?.("coordinator");
|
|
781
|
+
let assignmentChanges: Map<string, string> | undefined;
|
|
782
|
+
try { assignmentChanges = this.reader.changes(); } catch { /* Legacy sources retain bounded repair. */ }
|
|
276
783
|
let coordinator: string;
|
|
277
784
|
try {
|
|
278
785
|
const snapshot = this.reader.beginSnapshot();
|
|
279
|
-
coordinator = snapshot.revision; releaseCoordinator = snapshot.release;
|
|
786
|
+
coordinator = snapshot.revision; releaseCoordinator = snapshot.release; commitCoordinator = snapshot.commit;
|
|
280
787
|
} catch { coordinator = "unknown"; }
|
|
281
|
-
|
|
788
|
+
if (assignmentChanges?.has("*")) {
|
|
789
|
+
const seq = assignmentChanges.get("*")!;
|
|
790
|
+
const key = `${this.reader.changeMetrics.generation}:${seq}`;
|
|
791
|
+
if (this.assignmentBaseline?.key !== key) {
|
|
792
|
+
this.assignmentBaseline = { key, seq };
|
|
793
|
+
if (this.imported) {
|
|
794
|
+
this.imported = false; this.repairOwed = true;
|
|
795
|
+
await this.repair?.return(undefined); this.repair = undefined;
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
this.inventoryPhase?.("log-stats");
|
|
282
800
|
const logs = new Map<string, string>();
|
|
283
801
|
const failureJournals = new Map<string, string>();
|
|
284
802
|
const processes = new Map<string, string>();
|
|
@@ -286,63 +804,169 @@ export class WorkReadModel {
|
|
|
286
804
|
const terminalLogChanges: string[] = [];
|
|
287
805
|
for (const [path, entry] of next) {
|
|
288
806
|
if (!path.startsWith(this.runs + sep)) continue;
|
|
807
|
+
if (failedPaths.has(path)) {
|
|
808
|
+
const id = entry.meta.id;
|
|
809
|
+
if (this.logs.has(id)) logs.set(id, this.logs.get(id)!);
|
|
810
|
+
if (this.failureJournals.has(id)) failureJournals.set(id, this.failureJournals.get(id)!);
|
|
811
|
+
if (this.processes.has(id)) processes.set(id, this.processes.get(id)!);
|
|
812
|
+
continue;
|
|
813
|
+
}
|
|
814
|
+
if (!paths.includes(path)) {
|
|
815
|
+
const id = entry.meta.id;
|
|
816
|
+
if (baseline.logs.has(id)) logs.set(id, baseline.logs.get(id)!);
|
|
817
|
+
if (baseline.failureJournals.has(id)) failureJournals.set(id, baseline.failureJournals.get(id)!);
|
|
818
|
+
if (baseline.processes.has(id)) processes.set(id, baseline.processes.get(id)!);
|
|
819
|
+
continue;
|
|
820
|
+
}
|
|
289
821
|
let signature = baseline.logs.get(entry.meta.id);
|
|
290
822
|
{
|
|
291
823
|
try {
|
|
292
|
-
const info = await
|
|
824
|
+
const info = await sourceStat(join(this.runs, entry.meta.id, "output.log"), { bigint: true });
|
|
293
825
|
signature = `${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
|
|
294
826
|
} catch (error) { signature = (error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "unverified"; }
|
|
295
827
|
}
|
|
296
828
|
logs.set(entry.meta.id, signature);
|
|
297
829
|
if ((signature !== this.logs.get(entry.meta.id) || this.files.get(path)?.meta.status !== entry.meta.status) && entry.meta.status !== "running"
|
|
298
830
|
&& entry.meta.management?.root === this.agentDir) terminalLogChanges.push(entry.meta.id);
|
|
299
|
-
if (signature !== baseline.logs.get(entry.meta.id)) logFamilies.add(
|
|
831
|
+
if (signature !== baseline.logs.get(entry.meta.id)) logFamilies.add(entry.meta.id);
|
|
300
832
|
const failureSignature = (await Promise.all(["failures.jsonl", "failures.jsonl.observed"].map(async name => {
|
|
301
|
-
try { const info = await
|
|
833
|
+
try { const info = await sourceStat(join(this.runs, entry.meta.id, name), { bigint: true }); return `${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`; }
|
|
302
834
|
catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "unverified"; }
|
|
303
835
|
}))).join(":");
|
|
304
836
|
failureJournals.set(entry.meta.id, failureSignature);
|
|
305
|
-
if (failureSignature !== baseline.failureJournals.get(entry.meta.id)) logFamilies.add(
|
|
837
|
+
if (failureSignature !== baseline.failureJournals.get(entry.meta.id)) logFamilies.add(entry.meta.id);
|
|
306
838
|
|
|
307
839
|
const status = effectiveStatus(entry.meta); processes.set(entry.meta.id, status);
|
|
308
|
-
if (status !== baseline.processes.get(entry.meta.id)) logFamilies.add(
|
|
840
|
+
if (status !== baseline.processes.get(entry.meta.id)) logFamilies.add(entry.meta.id);
|
|
309
841
|
if (performance.now() - sliceStarted >= 8) { await yieldTurn(); sliceStarted = performance.now(); }
|
|
310
842
|
}
|
|
311
843
|
const healthConfig = await readHealthConfig(this.agentDir, next.size > 0);
|
|
844
|
+
if (healthConfig.revision !== baseline.healthRevision) this.counters.healthConfigInvalidations++;
|
|
312
845
|
const changed = next.size !== baseline.files.size || [...next].some(([path, entry]) => baseline.files.get(path)?.signature !== entry.signature);
|
|
313
|
-
|
|
846
|
+
const now = Date.now();
|
|
847
|
+
const deadlineExpired = [...baseline.projected.values()].some(row => healthDeadlineExpired(row, now));
|
|
848
|
+
const rawDirectories = [...new Set(paths.filter(path => path.startsWith(this.runs + sep) && next.has(path)).map(path => dirname(path)))];
|
|
849
|
+
const rearmRawDirectories = () => {
|
|
850
|
+
if (!rawDirectories.length) return;
|
|
851
|
+
this.watchDirectory(this.runs);
|
|
852
|
+
for (const directory of rawDirectories) this.watchDirectory(directory);
|
|
853
|
+
};
|
|
854
|
+
// A delayed mkdir notification may retire a watch during the awaited reads.
|
|
855
|
+
rearmRawDirectories();
|
|
856
|
+
await this.watchRegistrations();
|
|
857
|
+
if (!this.staged && !changed && !failedPaths.size && !this.sourceErrors.size && !logFamilies.size && !assignmentChanges?.size && !deadlineExpired && coordinator === this.coordinator && healthConfig.revision === this.healthRevision && !healthConfig.reason && this.state === "ready") return;
|
|
314
858
|
const metas = new Map<string, any>();
|
|
315
859
|
const markers = new Map([...next].filter(([path]) => path.startsWith(this.markers + sep)).map(([, entry]) => [entry.meta.sessionId, entry.meta]));
|
|
316
860
|
for (const [path, entry] of next) {
|
|
317
861
|
if (path.startsWith(this.markers + sep)) continue;
|
|
862
|
+
// Compact archives omit volatile delivery markers. A verified live
|
|
863
|
+
// record wins independently of which source was discovered last.
|
|
864
|
+
if (path.startsWith(this.archives + sep) && next.has(join(this.runs, entry.meta.id, "meta.json"))) continue;
|
|
318
865
|
const marker = markers.get(entry.meta.sessionId);
|
|
319
866
|
if (path.startsWith(this.archives + sep) && marker && marker.attemptId !== entry.meta.id && marker.startedAt >= entry.meta.startedAt) continue;
|
|
320
867
|
metas.set(entry.meta.id, entry.meta);
|
|
321
868
|
}
|
|
869
|
+
this.inventoryPhase?.("projection");
|
|
322
870
|
const attempts = [...metas.values()];
|
|
323
|
-
const
|
|
324
|
-
const family = (meta: any) => JSON.stringify([meta.sessionId, meta.cwd]);
|
|
871
|
+
const changedAttempts = new Set<any>();
|
|
325
872
|
for (const [path, entry] of [...baseline.files, ...next]) {
|
|
326
|
-
if (baseline.files.get(path)?.signature !== next.get(path)?.signature)
|
|
873
|
+
if (baseline.files.get(path)?.signature !== next.get(path)?.signature) {
|
|
874
|
+
if (path.startsWith(this.markers + sep)) {
|
|
875
|
+
for (const meta of attempts) if (meta.sessionId === entry.meta.sessionId) changedAttempts.add(meta);
|
|
876
|
+
} else changedAttempts.add(entry.meta);
|
|
877
|
+
}
|
|
327
878
|
}
|
|
328
|
-
|
|
879
|
+
const assignmentGeneration = this.reader.changeMetrics.generation;
|
|
880
|
+
// An unpublished retry may reuse a verified projection only at the same
|
|
881
|
+
// durable source generation and per-scope position. Receipt stays pending.
|
|
882
|
+
const changedScope = (scope: string) => assignmentChanges?.has(scope)
|
|
883
|
+
&& (!this.staged || this.staged.assignmentGeneration !== assignmentGeneration
|
|
884
|
+
|| this.staged.assignmentChanges?.get(scope) !== assignmentChanges.get(scope));
|
|
885
|
+
for (const meta of attempts) {
|
|
329
886
|
if (!(meta.assignment || meta.operations || meta.park)) continue;
|
|
330
|
-
const
|
|
331
|
-
|
|
332
|
-
|
|
887
|
+
const session = meta.assignment?.owner?.sessionId ?? meta.operations?.conversationId ?? meta.sessionId;
|
|
888
|
+
const workspace = meta.assignment?.owner?.workspace ?? meta.operations?.workspace ?? meta.cwd;
|
|
889
|
+
if ((changedScope("*") && paths.some(path => next.get(path)?.meta.id === meta.id))
|
|
890
|
+
|| changedScope(JSON.stringify([session, workspace, meta.assignment?.assignmentId ?? null]))
|
|
891
|
+
|| changedScope(JSON.stringify([session, workspace, null]))
|
|
892
|
+
|| (!assignmentChanges && paths.some(path => next.get(path)?.meta.id === meta.id))) changedAttempts.add(meta);
|
|
333
893
|
}
|
|
894
|
+
const affected = await affectedAttempts(
|
|
895
|
+
[...baseline.projected.values()].map(row => row.meta).concat(attempts), changedAttempts);
|
|
896
|
+
if (this.closed) return;
|
|
334
897
|
const project = createAssignmentProjector({ attempts, observe: (owner: any) => this.reader.read(owner) });
|
|
898
|
+
const touched = new Set(paths.map(path => next.get(path)?.meta.id));
|
|
335
899
|
const rows = [];
|
|
336
900
|
for (const meta of attempts) {
|
|
337
901
|
let row = baseline.projected.get(meta.id);
|
|
338
|
-
|
|
902
|
+
const assignmentChanged = !row || (!row.assignment.verified && touched.has(meta.id)) || affected.has(meta.id) || processes.get(meta.id) !== baseline.processes.get(meta.id);
|
|
903
|
+
const logChanged = !row || logs.get(meta.id) !== baseline.logs.get(meta.id);
|
|
904
|
+
const failureChanged = !row || failureJournals.get(meta.id) !== baseline.failureJournals.get(meta.id);
|
|
905
|
+
const deadlineChanged = row && healthDeadlineExpired(row, now);
|
|
906
|
+
if (row && !assignmentChanged && !logChanged && !failureChanged && (healthConfig.revision !== baseline.healthRevision || deadlineChanged)) {
|
|
907
|
+
if (healthConfig.revision !== baseline.healthRevision) this.invalidations.healthConfig++;
|
|
908
|
+
if (deadlineChanged) this.invalidations.healthDeadline++;
|
|
909
|
+
this.counters.healthRecomputations++;
|
|
910
|
+
const health = healthWithThresholds(row.health, healthConfig.config, meta);
|
|
911
|
+
row = { ...row, health, sourceRevision: hash([meta, row.assignment.revision, row.display, health, row.recipientPending, row.failurePending, failureJournals.get(meta.id)]) };
|
|
912
|
+
} else if (assignmentChanged || logChanged || failureChanged) {
|
|
913
|
+
if (!row) this.invalidations.initial++;
|
|
914
|
+
else {
|
|
915
|
+
if (affected.has(meta.id)) this.invalidations.assignmentInput++;
|
|
916
|
+
if (!row.assignment.verified) this.invalidations.unverified++;
|
|
917
|
+
if (processes.get(meta.id) !== baseline.processes.get(meta.id)) this.invalidations.process++;
|
|
918
|
+
if (logChanged) this.invalidations.log++;
|
|
919
|
+
if (failureChanged) this.invalidations.failureAttention++;
|
|
920
|
+
if (healthConfig.revision !== baseline.healthRevision) this.invalidations.healthConfig++;
|
|
921
|
+
if (deadlineChanged) this.invalidations.healthDeadline++;
|
|
922
|
+
}
|
|
339
923
|
this.counters.projections++;
|
|
340
|
-
|
|
341
|
-
const
|
|
342
|
-
|
|
343
|
-
|
|
924
|
+
if (assignmentChanged) this.counters.assignmentProjections++;
|
|
925
|
+
const assignment = assignmentChanged ? project(meta, processes.get(meta.id) ?? meta.status) : row!.assignment;
|
|
926
|
+
let display = row?.display, health = row?.health;
|
|
927
|
+
if (logChanged) withLogReadBatch(() => {
|
|
928
|
+
this.counters.logProjections++; this.counters.healthProjections++;
|
|
929
|
+
const logPath = join(this.runs, meta.id, "output.log");
|
|
930
|
+
const priorDisplay = parseBefore.get(logPath), priorHealth = healthBefore.get(logPath);
|
|
931
|
+
if (priorDisplay && this.parseStates.get(logPath) === priorDisplay)
|
|
932
|
+
this.parseStates.set(logPath, decodeParseLogState(structuredClone(encodeParseLogState(priorDisplay))));
|
|
933
|
+
if (priorHealth && this.healthStates.get(logPath) === priorHealth)
|
|
934
|
+
this.healthStates.set(logPath, decodeHealthLogState(structuredClone(encodeHealthLogState(priorHealth))));
|
|
935
|
+
if (!this.parseStates.has(logPath) || !this.healthStates.has(logPath)) {
|
|
936
|
+
const saved = this.checkpoints.load(logPath);
|
|
937
|
+
if (saved) {
|
|
938
|
+
try {
|
|
939
|
+
if (!Number.isSafeInteger(saved.display.cursor.offset) || !Number.isSafeInteger(saved.health.cursor.offset)) throw new Error("Invalid checkpoint offset");
|
|
940
|
+
this.parseStates.set(logPath, decodeParseLogState(saved.display));
|
|
941
|
+
this.healthStates.set(logPath, decodeHealthLogState(saved.health));
|
|
942
|
+
} catch { this.parseStates.delete(logPath); this.healthStates.delete(logPath); }
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
const parsed = logs.get(meta.id) && logs.get(meta.id) !== "missing" ? parseRunDisplay(meta.id, { logPath, states: this.parseStates, summaryOnly: true }) : undefined;
|
|
946
|
+
display = { spend: parsed ? fmtSpend(parsed.usage) : "", tool: parsed?.tool ?? "" };
|
|
947
|
+
health = logs.has(meta.id) ? extractChildEventFactsFromLog(meta.id, { logPath, states: this.healthStates }) : undefined;
|
|
948
|
+
const displayState = this.parseStates.get(logPath), healthState = this.healthStates.get(logPath);
|
|
949
|
+
display = { ...display!, diagnostics: parsed?.diagnostics, coverage: displayState ? {
|
|
950
|
+
start: displayState.cursor.coverageStart ?? 0, offset: displayState.cursor.offset,
|
|
951
|
+
totalBytes: displayState.totalBytes, missing: displayState.cursor.missing,
|
|
952
|
+
complete: !displayState.catchingUp && !displayState.windowTruncated && displayState.cursor.offset === displayState.totalBytes,
|
|
953
|
+
} : undefined };
|
|
954
|
+
if (health && healthState) health = { ...health, coverage: { start: healthState.cursor.coverageStart ?? 0,
|
|
955
|
+
offset: healthState.cursor.offset, missing: healthState.cursor.missing } };
|
|
956
|
+
if (displayState?.catchingUp) logs.set(meta.id, `${logs.get(meta.id)}:catching-up`);
|
|
957
|
+
if (displayState && healthState) checkpointWrites.push([logPath, {
|
|
958
|
+
display: encodeParseLogState(displayState), health: encodeHealthLogState(healthState),
|
|
959
|
+
}]);
|
|
960
|
+
while (this.parseStates.size > 64) this.parseStates.delete(this.parseStates.keys().next().value);
|
|
961
|
+
while (this.healthStates.size > 64) this.healthStates.delete(this.healthStates.keys().next().value);
|
|
962
|
+
});
|
|
963
|
+
if (logChanged || assignmentChanged || deadlineChanged || healthConfig.revision !== baseline.healthRevision) {
|
|
964
|
+
this.counters.healthRecomputations++;
|
|
965
|
+
health = healthWithThresholds(health, healthConfig.config, meta);
|
|
966
|
+
}
|
|
344
967
|
const outcome = meta.assignment ? this.reader.read({ ...meta.assignment.owner, assignmentId: meta.assignment.assignmentId }).outcome : undefined;
|
|
345
|
-
|
|
968
|
+
if (failureChanged || assignmentChanged) this.counters.failureProjections++;
|
|
969
|
+
const failurePending = !failureChanged && !assignmentChanged ? row!.failurePending : meta.callback !== false && failureJournals.has(meta.id) && Boolean(pendingFailureAttention(
|
|
346
970
|
readFailureStateReadOnly(join(this.runs, meta.id, "failures.jsonl")), Date.now(),
|
|
347
971
|
{ terminal: !["running", "orphaned"].includes(meta.status), deferObservationGaps: meta.status === "running" }));
|
|
348
972
|
const recipientPending = Boolean(failurePending || meta.timing?.pendingWakes?.length
|
|
@@ -352,35 +976,64 @@ export class WorkReadModel {
|
|
|
352
976
|
: meta.completionCallbackPendingAt !== undefined && meta.completionCallbackSentAt === undefined && meta.completionCallbackSuppressedAt === undefined)));
|
|
353
977
|
row = { meta, assignment, display, health, recipientPending, failurePending, sourceRevision: hash([meta, assignment.revision, display, health, recipientPending, failurePending, failureJournals.get(meta.id)]) };
|
|
354
978
|
}
|
|
355
|
-
rows.push(row);
|
|
979
|
+
rows.push(row!);
|
|
356
980
|
if (++batch % 256 === 0 || performance.now() - sliceStarted >= 8) {
|
|
357
981
|
await yieldTurn(); sliceStarted = performance.now();
|
|
358
982
|
}
|
|
359
983
|
}
|
|
984
|
+
this.inventoryPhase?.("verify");
|
|
985
|
+
// The pinned source snapshot is a valid baseline even while writers advance.
|
|
986
|
+
// Subsequent commits remain beyond the durable received position.
|
|
987
|
+
const globallyUnverified = !!healthConfig.reason || rows.some(row => !row.assignment.verified);
|
|
360
988
|
let after: string;
|
|
361
989
|
try { after = this.reader.revision(); } catch { after = "unknown"; }
|
|
362
|
-
if (after !== coordinator) {
|
|
990
|
+
if (after !== coordinator) {
|
|
991
|
+
sourceConflict = true;
|
|
992
|
+
this.dirty = true;
|
|
993
|
+
throw new Error("Coordinator changed during observation; retrying.");
|
|
994
|
+
}
|
|
363
995
|
// Retry caches are never queryable. Validate all unpublished families again before committing them.
|
|
364
996
|
this.staged = { files: next, projected: new Map(rows.map(row => [row.meta.id, row])), logs, failureJournals, processes,
|
|
365
|
-
healthRevision: healthConfig.revision, coordinator,
|
|
997
|
+
healthRevision: healthConfig.revision, coordinator, assignmentChanges: assignmentChanges && new Map(assignmentChanges),
|
|
998
|
+
assignmentGeneration };
|
|
366
999
|
const uncommitted = new Set(affected);
|
|
367
1000
|
for (const [path, entry] of [...this.files, ...next]) {
|
|
368
|
-
if (this.files.get(path)?.signature !== next.get(path)?.signature) uncommitted.add(
|
|
1001
|
+
if (this.files.get(path)?.signature !== next.get(path)?.signature) uncommitted.add(entry.meta.id);
|
|
369
1002
|
}
|
|
370
|
-
const verify = [...next].filter(([, entry]) => uncommitted.has(
|
|
1003
|
+
const verify = [...next].filter(([path, entry]) => !failedPaths.has(path) && uncommitted.has(entry.meta.id));
|
|
371
1004
|
for (let offset = 0; offset < verify.length; offset += 32) {
|
|
372
1005
|
const group = verify.slice(offset, offset + 32);
|
|
373
1006
|
const observations = await Promise.all(group.map(async ([path]) => {
|
|
374
|
-
try { return { info: await
|
|
1007
|
+
try { return { info: await sourceStat(path, { bigint: true }) }; }
|
|
375
1008
|
catch (error) { return { error }; }
|
|
376
1009
|
}));
|
|
377
|
-
for (const [index, [, entry]] of group.entries()) {
|
|
1010
|
+
for (const [index, [path, entry]] of group.entries()) {
|
|
378
1011
|
const observation = observations[index]!;
|
|
379
1012
|
if (!observation.info) throw observation.error;
|
|
380
1013
|
const info = observation.info;
|
|
381
1014
|
if (`${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}` !== entry.signature) {
|
|
1015
|
+
sourceConflict = true;
|
|
382
1016
|
this.dirty = true;
|
|
383
|
-
|
|
1017
|
+
const error = new Error("Source changed during observation; retaining the previous snapshot while reconciling.");
|
|
1018
|
+
if (!globallyUnverified && (this.state === "ready" || this.sourceRace && this.reason === this.sourceRace.reason)
|
|
1019
|
+
&& path.startsWith(this.runs + sep) && info.size <= 1024n * 1024n && !failedPaths.size && [...this.sourceErrors].every(([path, reason]) =>
|
|
1020
|
+
this.sourceRace?.paths.has(path) && reason === this.sourceRace.reason)) {
|
|
1021
|
+
// Recheck only for error routing: a concurrent move can affect a
|
|
1022
|
+
// new workspace/recipient. Never publish this uncommitted row.
|
|
1023
|
+
try {
|
|
1024
|
+
this.counters.metadataReads++;
|
|
1025
|
+
const current = JSON.parse(await readFile(path, "utf8"));
|
|
1026
|
+
const checked = await sourceStat(path, { bigint: true });
|
|
1027
|
+
if (current?.id === entry.meta.id && typeof current.cwd === "string" && Number.isFinite(current.startedAt)
|
|
1028
|
+
&& typeof current.status === "string" && checked.size <= 1024n * 1024n
|
|
1029
|
+
&& `${checked.dev}:${checked.ino}:${checked.size}:${checked.mtimeNs}:${checked.ctimeNs}` === `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`) {
|
|
1030
|
+
sourceRace = { reason: String(error), paths: new Set(paths), rows: [
|
|
1031
|
+
...[...uncommitted].flatMap(id => [this.projected.get(id), this.staged?.projected.get(id)].filter(Boolean)),
|
|
1032
|
+
{ meta: current, assignment: { state: current.status } }] };
|
|
1033
|
+
}
|
|
1034
|
+
} catch { /* Unreadable/unstable routing evidence keeps degradation global. */ }
|
|
1035
|
+
}
|
|
1036
|
+
throw error;
|
|
384
1037
|
}
|
|
385
1038
|
if (++batch % 256 === 0 || performance.now() - sliceStarted >= 8) {
|
|
386
1039
|
await yieldTurn(); sliceStarted = performance.now();
|
|
@@ -388,36 +1041,83 @@ export class WorkReadModel {
|
|
|
388
1041
|
}
|
|
389
1042
|
}
|
|
390
1043
|
if (this.closed) return;
|
|
391
|
-
|
|
1044
|
+
rearmRawDirectories();
|
|
1045
|
+
await this.watchRegistrations();
|
|
1046
|
+
this.inventoryPhase?.("commit");
|
|
1047
|
+
if (!commitCoordinator) this.db.exec("BEGIN");
|
|
392
1048
|
const insert = this.db.prepare("INSERT OR REPLACE INTO rows VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
|
|
393
1049
|
const remove = this.db.prepare("DELETE FROM rows WHERE id = ?");
|
|
394
1050
|
let semanticChange = false;
|
|
1051
|
+
const changedRows: WorkReadModel["changedRows"] = [];
|
|
1052
|
+
const publishCheckpoints: Array<() => void> = [];
|
|
395
1053
|
try {
|
|
396
|
-
for (const id of this.projected.keys()) if (!metas.has(id)) { remove.run(id); this.db.prepare("DELETE FROM terminal_log_folds WHERE id=?").run(id); semanticChange = true; }
|
|
1054
|
+
for (const id of this.projected.keys()) if (!metas.has(id)) { changedRows.push({ before: this.projected.get(id) }); remove.run(id); this.db.prepare("DELETE FROM assignment_members WHERE id=?").run(id); this.db.prepare("DELETE FROM terminal_log_folds WHERE id=?").run(id); semanticChange = true; }
|
|
397
1055
|
for (const id of terminalLogChanges) this.db.prepare("INSERT INTO terminal_log_folds VALUES (?, ?, 1, ?) ON CONFLICT(id) DO UPDATE SET revision=excluded.revision, pending=1, queue_position=CASE WHEN terminal_log_folds.pending=0 THEN excluded.queue_position ELSE terminal_log_folds.queue_position END").run(id, hash([logs.get(id), metas.get(id)?.status]), ++this.foldQueueSequence);
|
|
398
1056
|
for (const row of rows) {
|
|
399
1057
|
if (this.projected.get(row.meta.id)?.sourceRevision === row.sourceRevision) continue;
|
|
400
1058
|
semanticChange = true;
|
|
1059
|
+
changedRows.push({ before: this.projected.get(row.meta.id), after: row });
|
|
401
1060
|
const m = row.meta;
|
|
402
1061
|
if (m.management?.root !== this.agentDir || m.status === "running") this.db.prepare("DELETE FROM terminal_log_folds WHERE id=?").run(m.id);
|
|
403
|
-
insert.run(m.id, m
|
|
1062
|
+
insert.run(m.id, discoveryWorkspace(m), m.callbackOrigin?.cwd ?? m.cwd, m.callbackOrigin?.sessionId ?? null,
|
|
404
1063
|
m.startedAt, row.assignment.state, ["running", "waiting"].includes(row.assignment.state) ? 1 : 0, m.endedAt ?? m.lostAt ?? null, row.recipientPending ? 1 : 0, JSON.stringify(row));
|
|
1064
|
+
this.db.prepare("DELETE FROM assignment_members WHERE id=?").run(m.id);
|
|
1065
|
+
const session = m.assignment?.owner?.sessionId ?? m.operations?.conversationId ?? m.sessionId;
|
|
1066
|
+
const workspace = m.assignment?.owner?.workspace ?? m.operations?.workspace ?? m.cwd;
|
|
1067
|
+
for (const assignmentId of new Set([m.assignment?.assignmentId ?? null, null])) this.db.prepare("INSERT INTO assignment_members VALUES(?,?)").run(JSON.stringify([session, workspace, assignmentId]), m.id);
|
|
405
1068
|
}
|
|
406
|
-
this.
|
|
407
|
-
|
|
1069
|
+
for (const [path, checkpoint] of checkpointWrites) publishCheckpoints.push(this.checkpoints.save(path, checkpoint, true));
|
|
1070
|
+
// Application and its exact acknowledgement share the owner commit.
|
|
1071
|
+
if (assignmentChanges && rows.every(row => row.assignment.verified)) this.reader.acknowledgeChanges(assignmentChanges, false);
|
|
1072
|
+
if (commitCoordinator) commitCoordinator(); else this.db.exec("COMMIT");
|
|
1073
|
+
} catch (error) {
|
|
1074
|
+
if (releaseCoordinator) releaseCoordinator(); else this.db.exec("ROLLBACK");
|
|
1075
|
+
throw error;
|
|
1076
|
+
}
|
|
1077
|
+
for (const publish of publishCheckpoints) publish();
|
|
408
1078
|
this.files = next; this.logs = logs; this.failureJournals = failureJournals; this.processes = processes; this.healthRevision = healthConfig.revision; this.coordinator = coordinator; this.inventory++;
|
|
409
|
-
this.coordinatorConversations = coordinatorConversations;
|
|
410
1079
|
this.projected = new Map(rows.map(row => [row.meta.id, row]));
|
|
1080
|
+
for (const states of [this.parseStates, this.healthStates]) for (const path of states.keys()) {
|
|
1081
|
+
if (!metas.has(path.slice(this.runs.length + 1).split(sep)[0])) states.delete(path);
|
|
1082
|
+
}
|
|
411
1083
|
this.staged = undefined;
|
|
1084
|
+
this.sourceConflicts = 0; this.conflictDelay = 100;
|
|
412
1085
|
if (terminalLogChanges.length) this.onTerminalLogsChanged?.();
|
|
413
1086
|
const previousState = this.state;
|
|
414
1087
|
const previousReason = this.reason;
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
1088
|
+
for (const path of paths) {
|
|
1089
|
+
const error = failedPaths.get(path);
|
|
1090
|
+
if (error) this.sourceErrors.set(path, error);
|
|
1091
|
+
else this.sourceErrors.delete(path);
|
|
1092
|
+
}
|
|
1093
|
+
// Incomplete raw writes retain their verified namespace, not partial JSON.
|
|
1094
|
+
// New/unknown records and mixed failures cannot be narrowed this way.
|
|
1095
|
+
if (globallyUnverified) this.sourceRace = undefined;
|
|
1096
|
+
if (!globallyUnverified && failedPaths.size && failedPaths.size === malformedPaths.size
|
|
1097
|
+
&& (previousState === "ready" || this.sourceRace && previousReason === this.sourceRace.reason)
|
|
1098
|
+
&& [...this.sourceErrors.keys()].every(path => malformedPaths.has(path))) {
|
|
1099
|
+
this.sourceRace = { reason: failedPaths.values().next().value!, paths: malformedPaths,
|
|
1100
|
+
rows: [...malformedPaths].map(path => this.projected.get(this.files.get(path)!.meta.id)) };
|
|
1101
|
+
}
|
|
1102
|
+
if (!this.sourceErrors.size) this.sourceRace = undefined;
|
|
1103
|
+
this.state = this.sourceErrors.size || healthConfig.reason ? "degraded" : !this.imported ? "rebuilding" : rows.some(row => !row.assignment.verified) ? "degraded" : "ready";
|
|
1104
|
+
this.reason = this.sourceErrors.values().next().value ?? healthConfig.reason ?? (this.state === "rebuilding" ? "Initial source inventory is rebuilding." : this.state === "degraded" ? "Some assignment sources could not be verified." : undefined);
|
|
1105
|
+
if ((this.imported || paths.length === 128) && (semanticChange || previousState !== this.state || previousReason !== this.reason)) {
|
|
1106
|
+
this.changedRows = changedRows;
|
|
1107
|
+
this.publish();
|
|
1108
|
+
}
|
|
418
1109
|
} catch (error) {
|
|
1110
|
+
releaseCoordinator?.(); releaseCoordinator = undefined;
|
|
1111
|
+
this.parseStates = parseBefore; this.healthStates = healthBefore;
|
|
419
1112
|
if (this.closed) return;
|
|
420
|
-
|
|
1113
|
+
if (sourceConflict) this.sourceConflicts++;
|
|
1114
|
+
const reason = String(error).slice(0, 512);
|
|
1115
|
+
this.sourceRace = sourceRace;
|
|
1116
|
+
if (this.dirty) for (const path of paths) if (!this.hints.has(path)) this.hints.set(path, Date.now());
|
|
1117
|
+
for (const path of paths) this.sourceErrors.set(path, reason);
|
|
1118
|
+
const changed = this.state !== "degraded" || this.reason !== reason;
|
|
1119
|
+
this.state = "degraded"; this.reason = reason;
|
|
1120
|
+
if (changed) this.publish();
|
|
421
1121
|
} finally { releaseCoordinator?.(); }
|
|
422
1122
|
}
|
|
423
1123
|
|
|
@@ -426,6 +1126,11 @@ export class WorkReadModel {
|
|
|
426
1126
|
return this.db.prepare("SELECT id, revision FROM terminal_log_folds WHERE pending=1 ORDER BY queue_position, id LIMIT 128").all();
|
|
427
1127
|
}
|
|
428
1128
|
acknowledgeTerminalLogs(batch: Array<{id: string; revision: string}>) {
|
|
1129
|
+
if (this.closed) return;
|
|
1130
|
+
if (this.reader?.snapshotActive && this.pending) {
|
|
1131
|
+
void this.pending.then(() => this.acknowledgeTerminalLogs(batch));
|
|
1132
|
+
return;
|
|
1133
|
+
}
|
|
429
1134
|
const acknowledge = this.db.prepare("UPDATE terminal_log_folds SET pending=CASE WHEN revision=? THEN 0 ELSE 1 END, queue_position=? WHERE id=?");
|
|
430
1135
|
// A newer revision remains owed, but rejoins behind existing obligations.
|
|
431
1136
|
// Continuously changing low IDs cannot monopolize every subsequent batch.
|
|
@@ -433,8 +1138,18 @@ export class WorkReadModel {
|
|
|
433
1138
|
}
|
|
434
1139
|
|
|
435
1140
|
snapshot(scope: WorkScope = {}): WorkSnapshot {
|
|
1141
|
+
if (!this.observationInitialized && !this.closed) return { instanceId: this.instanceId, runtimeEpoch: this.instanceId, scopeRevision: hash([scope, this.state, this.reason]), seq: this.revision,
|
|
1142
|
+
observedRevisionVector: { inventory: this.inventory, coordinator: this.coordinator, healthConfig: this.healthRevision }, status: this.state, reason: this.reason,
|
|
1143
|
+
rows: [], totalMatching: 0, activity: { active: 0 }, nextDeadline: null };
|
|
436
1144
|
if (scope.background) {
|
|
437
|
-
if (
|
|
1145
|
+
if (!this.observationInitialized) {
|
|
1146
|
+
const status = this.state === "ready" ? "degraded" : this.state;
|
|
1147
|
+
const reason = this.reason ?? "Derived observation inputs are unavailable.";
|
|
1148
|
+
return { instanceId: this.instanceId, runtimeEpoch: this.instanceId, scopeRevision: hash([scope, status, reason]), seq: this.revision,
|
|
1149
|
+
observedRevisionVector: { inventory: this.inventory, coordinator: this.coordinator, healthConfig: this.healthRevision },
|
|
1150
|
+
status, reason, rows: [], totalMatching: 0, activity: { active: 0 }, nextDeadline: null };
|
|
1151
|
+
}
|
|
1152
|
+
if (scope.backgroundHistory && this.background.refresh()) this.publish(true);
|
|
438
1153
|
const index = scope.backgroundHistory ? this.background.historyIndex(scope) : undefined;
|
|
439
1154
|
const tasks = this.background.read(scope, index);
|
|
440
1155
|
const status = this.background.status === "degraded" ? "degraded" : index ? this.background.historyStatus : this.background.status;
|
|
@@ -445,7 +1160,7 @@ export class WorkReadModel {
|
|
|
445
1160
|
rows: tasks.map(meta => ({ meta, assignment: null, sourceRevision: hash(meta) })), totalMatching: index?.page.total ?? tasks.length,
|
|
446
1161
|
...(index?.page.nextCursor ? { nextCursor: index.page.nextCursor } : {}),
|
|
447
1162
|
...(index ? { backgroundIndex: index } : {}),
|
|
448
|
-
activity: { active }, nextDeadline: null };
|
|
1163
|
+
activity: { active }, nextDeadline: scope.backgroundHistory ? null : this.background.nextDeadline(scope) };
|
|
449
1164
|
}
|
|
450
1165
|
const clauses: string[] = [], args: any[] = [];
|
|
451
1166
|
if (scope.id) { clauses.push("id = ?"); args.push(scope.id); }
|
|
@@ -460,22 +1175,31 @@ export class WorkReadModel {
|
|
|
460
1175
|
if (scope.active !== undefined) { clauses.push("active = ?"); args.push(scope.active ? 1 : 0); }
|
|
461
1176
|
if (scope.endedAfter !== undefined) { clauses.push("(ended IS NULL OR ended >= ?)"); args.push(scope.endedAfter); }
|
|
462
1177
|
if (scope.statuses?.length) { clauses.push(`state IN (${scope.statuses.map(() => "?").join(",")})`); args.push(...scope.statuses); }
|
|
463
|
-
const key =
|
|
1178
|
+
const key = this.scopeKey(scope);
|
|
1179
|
+
const entry = this.scopeEntry(scope);
|
|
464
1180
|
const totalMatching = Number(this.db.prepare(`SELECT count(*) AS n FROM rows ${clauses.length ? "WHERE " + clauses.join(" AND ") : ""}`).get(...args).n);
|
|
465
1181
|
if (scope.cursor) {
|
|
466
1182
|
let cursor;
|
|
467
1183
|
try { cursor = JSON.parse(Buffer.from(scope.cursor, "base64url").toString()); } catch { throw new Error("Invalid runtime cursor"); }
|
|
468
|
-
if (!Array.isArray(cursor) || cursor[0] !== key || cursor[1] !== this.instanceId || cursor[2] !==
|
|
1184
|
+
if (!Array.isArray(cursor) || cursor[0] !== key || cursor[1] !== this.instanceId || cursor[2] !== `${entry.token}:${entry.revision}`) throw new Error("resync_required: cursor snapshot changed");
|
|
469
1185
|
clauses.push("(started < ? OR (started = ? AND id < ?))"); args.push(cursor[3], cursor[3], cursor[4]);
|
|
470
1186
|
}
|
|
471
1187
|
const limit = Math.max(1, Math.min(200, Number.isSafeInteger(scope.limit) ? scope.limit! : 50));
|
|
472
1188
|
const records = this.db.prepare(`SELECT payload, started, id FROM rows ${clauses.length ? "WHERE " + clauses.join(" AND ") : ""} ORDER BY started DESC, id DESC LIMIT ?`).all(...args, limit + 1);
|
|
473
1189
|
const page = records.slice(0, limit), last = page.at(-1);
|
|
474
|
-
|
|
475
|
-
|
|
1190
|
+
const now = Date.now();
|
|
1191
|
+
const rows = page.map((record: any) => {
|
|
1192
|
+
const row = JSON.parse(record.payload);
|
|
1193
|
+
if (this.unsupportedAssignmentRevision) row.assignment = { ...row.assignment, verified: false, reason: this.reason };
|
|
1194
|
+
if (row.health) row.health.nextDeadline = nextHealthDeadline(row.health, row.meta, now);
|
|
1195
|
+
return row;
|
|
1196
|
+
});
|
|
1197
|
+
const deadlines = rows.map((row: any) => row.health?.nextDeadline).filter((deadline: any) => typeof deadline === "number");
|
|
1198
|
+
return { instanceId: this.instanceId, runtimeEpoch: this.instanceId, scopeRevision: hash([key, entry.token, entry.revision]), seq: this.revision,
|
|
1199
|
+
observedRevisionVector: { inventory: this.inventory, coordinator: this.coordinator, healthConfig: this.healthRevision }, ...this.scopeStatus(scope),
|
|
476
1200
|
totalMatching,
|
|
477
|
-
rows: page.map((record: any) => {
|
|
478
|
-
const row =
|
|
1201
|
+
rows: page.map((record: any, index: number) => {
|
|
1202
|
+
const row = rows[index];
|
|
479
1203
|
if (scope.detail && scope.id) {
|
|
480
1204
|
let cached = this.details.get(row.meta.id);
|
|
481
1205
|
if (!cached || cached.revision !== row.sourceRevision) {
|
|
@@ -494,16 +1218,20 @@ export class WorkReadModel {
|
|
|
494
1218
|
}
|
|
495
1219
|
row.detail = cached.value;
|
|
496
1220
|
}
|
|
497
|
-
return { ...row, cursor: Buffer.from(JSON.stringify([key, this.instanceId,
|
|
1221
|
+
return { ...row, cursor: Buffer.from(JSON.stringify([key, this.instanceId, `${entry.token}:${entry.revision}`, record.started, record.id])).toString("base64url") };
|
|
498
1222
|
}),
|
|
499
|
-
...(records.length > limit ? { nextCursor: Buffer.from(JSON.stringify([key, this.instanceId,
|
|
500
|
-
activity: { active }, nextDeadline: null };
|
|
1223
|
+
...(records.length > limit ? { nextCursor: Buffer.from(JSON.stringify([key, this.instanceId, `${entry.token}:${entry.revision}`, last.started, last.id])).toString("base64url") } : {}),
|
|
1224
|
+
activity: { active }, nextDeadline: deadlines.length ? Math.min(...deadlines) : null };
|
|
501
1225
|
}
|
|
502
1226
|
|
|
503
1227
|
async close() {
|
|
504
1228
|
this.closed = true; if (this.timer) clearInterval(this.timer);
|
|
1229
|
+
if (this.conflictRetry) clearTimeout(this.conflictRetry);
|
|
505
1230
|
for (const watcher of this.watchers.values()) watcher.close();
|
|
1231
|
+
for (const { watcher } of this.rootParents.values()) watcher.close();
|
|
1232
|
+
this.rootParents.clear();
|
|
506
1233
|
this.watchers.clear(); this.rootWatchIdentities.clear();
|
|
507
|
-
await this.pending; this.listeners.clear(); await this.background.close(); this.reader.close(); this.db.close();
|
|
1234
|
+
await this.pending; await this.repairWrite; this.listeners.clear(); await this.background.close(); this.reader?.close(); this.checkpoints.close(); this.db.close();
|
|
1235
|
+
await this.repair?.return(undefined);
|
|
508
1236
|
}
|
|
509
1237
|
}
|