pi-better-server 0.5.0 → 0.6.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 +4 -1
- 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/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-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 +131 -23
- package/src/runtime/background.ts +351 -68
- 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 +3 -3
- package/src/runtime/domain/background/registry.mjs +61 -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 +6 -9
- package/src/runtime/domain/background-service/index.ts +6 -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 +75 -17
- package/src/runtime/domain/background-service/managed-frontend.ts +62 -17
- package/src/runtime/domain/background-service/navigator-provider.domain.mjs +16 -5
- package/src/runtime/domain/background-service/navigator-provider.ts +15 -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 +170 -27
- package/src/runtime/domain/background-service/observed-waits.ts +154 -30
- 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 +3 -3
- package/src/runtime/domain/background-service/process.ts +3 -3
- 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/runtime.domain.mjs +32 -16
- package/src/runtime/domain/background-service/runtime.ts +19 -9
- 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 +218 -13
- package/src/runtime/domain/background-service/shared-navigator.ts +197 -14
- 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/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 +21 -3
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +34 -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/supervisor/generated/process-identity.mjs +20 -2
- package/src/runtime/domain/background-service/supervisor/generated/process.mjs +3 -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 +31 -24
- package/src/runtime/domain/background-service/tools.ts +41 -38
- package/src/runtime/domain/background-service/types.domain.mjs +1 -0
- package/src/runtime/domain/background-service/types.ts +3 -1
- 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/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 +21 -3
- 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/parse.d.mts +4 -1
- package/src/runtime/domain/parse.mjs +50 -5
- package/src/runtime/domain/sandbox-policy/README.md +61 -63
- 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/subagents/README.md +1 -1
- package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +12 -6
- package/src/runtime/domain/subagents/assignment-outcomes.ts +11 -5
- package/src/runtime/domain/subagents/assignment-report.domain.mjs +87 -24
- package/src/runtime/domain/subagents/assignment-report.ts +83 -19
- 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/config.domain.mjs +49 -2
- package/src/runtime/domain/subagents/config.ts +46 -2
- 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/extensions.mjs +11 -13
- package/src/runtime/domain/subagents/finalization.domain.mjs +12 -0
- package/src/runtime/domain/subagents/finalization.ts +15 -0
- 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 +296 -123
- package/src/runtime/domain/subagents/index.ts +257 -98
- 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/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 +6 -3
- package/src/runtime/domain/subagents/managed-launch-client.ts +6 -3
- 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/owned-exit.domain.mjs +12 -0
- package/src/runtime/domain/subagents/owned-exit.ts +12 -0
- package/src/runtime/domain/subagents/package.json +1 -1
- package/src/runtime/domain/subagents/parse.domain.mjs +50 -5
- package/src/runtime/domain/subagents/parse.ts +48 -6
- 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 +47 -33
- package/src/runtime/domain/subagents/registry.ts +54 -33
- 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 +6 -23
- package/src/runtime/domain/subagents/shared-catalog.ts +6 -14
- 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 +218 -13
- package/src/runtime/domain/subagents/shared-navigator.ts +197 -14
- 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/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 +21 -3
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +34 -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-policy.domain.mjs +1 -1
- package/src/runtime/domain/subagents/task-policy.ts +3 -1
- package/src/runtime/domain/subagents/timing.domain.mjs +10 -1
- package/src/runtime/domain/subagents/timing.ts +10 -1
- package/src/runtime/domain/subagents/work-observation.domain.mjs +77 -16
- package/src/runtime/domain/subagents/work-observation.ts +71 -16
- 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/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 +846 -120
- package/src/runtime/read-watchdog-probe.ts +4 -0
- package/src/runtime/result-supervision.ts +188 -16
- 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
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// Fixed labels only: the watchdog log must not include request or source data.
|
|
2
|
+
export const executionPhases = ["starting", "idle", "snapshot", "request", "publish"] as const;
|
|
3
|
+
export const inventoryPhases = ["idle", "background", "metadata", "coordinator", "log-stats", "projection", "verify", "commit"] as const;
|
|
4
|
+
export type InventoryPhase = typeof inventoryPhases[number];
|
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
import { join } from "node:path";
|
|
2
|
-
import { existsSync } from "node:fs";
|
|
2
|
+
import { existsSync, watch, type FSWatcher } from "node:fs";
|
|
3
3
|
import { createRequire } from "node:module";
|
|
4
4
|
import { acquireMutationStore } from "./mutation-store.ts";
|
|
5
|
+
import { ENTITY_BUDGET } from "./work-budget.ts";
|
|
5
6
|
// @ts-expect-error Generated canonical supervisor.
|
|
6
7
|
import { createLocalSupervisor } from "./domain/background/supervisor/supervisor.mjs";
|
|
8
|
+
// @ts-expect-error Generated canonical durable stop records.
|
|
9
|
+
import { readStopRequest } from "./domain/background/supervisor/store.mjs";
|
|
10
|
+
// @ts-expect-error Generated canonical process identity checks.
|
|
11
|
+
import { processGroupAlive } from "./domain/background/supervisor/identity.mjs";
|
|
7
12
|
// @ts-expect-error Generated canonical terminal evidence rules.
|
|
8
13
|
import { supervisorTerminalPublication } from "./domain/background/terminal-publication.mjs";
|
|
9
14
|
|
|
@@ -16,48 +21,215 @@ export function hasResultSupervision(root: string): boolean {
|
|
|
16
21
|
finally { db.close(); }
|
|
17
22
|
}
|
|
18
23
|
|
|
19
|
-
/**
|
|
24
|
+
/** Observes managed task results and stops exact tasks of terminal assignments. */
|
|
20
25
|
export class RuntimeResultSupervision {
|
|
21
26
|
private store: any;
|
|
27
|
+
private budget: ReturnType<typeof acquireMutationStore>["budget"];
|
|
22
28
|
private releaseStore: () => void;
|
|
23
|
-
private timer
|
|
29
|
+
private timer?: NodeJS.Timeout;
|
|
30
|
+
private watcher?: FSWatcher;
|
|
31
|
+
private taskWatchers = new Map<string, FSWatcher>();
|
|
32
|
+
private active = new Map<string, { grant: any; due: number; reason?: any; failure?: string; uncertainSince?: number }>();
|
|
33
|
+
private dirty = new Set<string>();
|
|
34
|
+
private position?: { generation: string; seq: number };
|
|
35
|
+
private scheduled = false;
|
|
36
|
+
private closed = false;
|
|
37
|
+
readonly metrics = { restores: 0, feedPages: 0, inspections: 0, publications: 0, deadlineLatenessMs: 0, passes: 0 };
|
|
24
38
|
readonly hostId: string;
|
|
25
39
|
readonly epoch: string;
|
|
26
|
-
|
|
27
|
-
|
|
40
|
+
private observationReason?: string;
|
|
41
|
+
private assignmentCleanup?: Promise<void>;
|
|
42
|
+
private assignmentCleanupCursor?: string;
|
|
43
|
+
private assignmentCleanupReason?: string;
|
|
44
|
+
get reason() { return this.assignmentCleanupReason ?? this.observationReason; }
|
|
45
|
+
private verificationMs: number;
|
|
46
|
+
constructor(root: string, epoch: string, verificationMs = 30_000) {
|
|
47
|
+
this.verificationMs = verificationMs;
|
|
28
48
|
this.epoch = epoch;
|
|
29
49
|
this.hostId = `server:${epoch}`;
|
|
30
50
|
const lease = acquireMutationStore(root);
|
|
31
51
|
this.store = lease.store;
|
|
52
|
+
this.budget = lease.budget;
|
|
32
53
|
this.releaseStore = lease.release;
|
|
54
|
+
this.watcher = watch(root, (_event, file) => {
|
|
55
|
+
if (!file || String(file).startsWith("operation-coordinator.sqlite")) this.schedule();
|
|
56
|
+
});
|
|
57
|
+
this.watcher.on("error", () => { this.watcher?.close(); this.watcher = undefined; });
|
|
33
58
|
this.reconcile();
|
|
34
|
-
this.timer = setInterval(() => this.reconcile(), 250);
|
|
35
|
-
this.timer.unref();
|
|
36
59
|
}
|
|
60
|
+
private schedule() {
|
|
61
|
+
if (this.closed || this.scheduled) return;
|
|
62
|
+
this.scheduled = true;
|
|
63
|
+
setImmediate(() => { this.scheduled = false; if (!this.closed) this.reconcile(); });
|
|
64
|
+
}
|
|
65
|
+
private retain(grant: any) {
|
|
66
|
+
const previous = this.active.get(grant.operationId);
|
|
67
|
+
if (previous && JSON.stringify(previous.grant) === JSON.stringify(grant)) return;
|
|
68
|
+
const now = Date.now();
|
|
69
|
+
this.active.set(grant.operationId, { grant, due: now, reason: { kind: "verification", id: grant.operationId,
|
|
70
|
+
operationId: grant.operationId, owner: grant.owner, lastProgressAt: now, nextDeadline: now + this.verificationMs,
|
|
71
|
+
recovery: "restore-captured-result-authority" } });
|
|
72
|
+
this.dirty.add(grant.operationId);
|
|
73
|
+
this.taskWatchers.get(grant.operationId)?.close();
|
|
74
|
+
this.taskWatchers.delete(grant.operationId);
|
|
75
|
+
try {
|
|
76
|
+
const watcher = watch(join(grant.directory, "tasks", this.store.getOperation(grant.operationId).taskId), () => {
|
|
77
|
+
if (this.active.has(grant.operationId)) { this.dirty.add(grant.operationId); this.schedule(); }
|
|
78
|
+
});
|
|
79
|
+
watcher.on("error", () => { watcher.close(); this.taskWatchers.delete(grant.operationId); });
|
|
80
|
+
this.taskWatchers.set(grant.operationId, watcher);
|
|
81
|
+
} catch { /* Missing task evidence is checked at its bounded deadline. */ }
|
|
82
|
+
}
|
|
83
|
+
private forget(id: string) {
|
|
84
|
+
this.active.delete(id); this.dirty.delete(id);
|
|
85
|
+
this.taskWatchers.get(id)?.close(); this.taskWatchers.delete(id);
|
|
86
|
+
}
|
|
87
|
+
livenessReasons() { return [...this.active.values()].flatMap(entry => entry.reason ? [entry.reason] : []); }
|
|
88
|
+
manages(operationId: string) { return this.active.has(operationId); }
|
|
37
89
|
reconcile() {
|
|
90
|
+
if (this.closed) return;
|
|
91
|
+
const release = this.budget.enter("control");
|
|
92
|
+
if (!release) {
|
|
93
|
+
if (this.timer) clearTimeout(this.timer);
|
|
94
|
+
this.timer = setTimeout(() => this.reconcile(), 1000); this.timer.unref(); return;
|
|
95
|
+
}
|
|
96
|
+
this.metrics.passes++;
|
|
38
97
|
try {
|
|
39
|
-
this.
|
|
40
|
-
|
|
98
|
+
this.observationReason = undefined;
|
|
99
|
+
try {
|
|
100
|
+
const page = this.store.resultSupervisionChanges(this.position);
|
|
101
|
+
this.metrics.feedPages++;
|
|
102
|
+
if (page.reset) {
|
|
103
|
+
this.metrics.restores++;
|
|
104
|
+
const grants = this.store.resultSupervisions(true);
|
|
105
|
+
const ids = new Set(grants.map((grant: any) => grant.operationId));
|
|
106
|
+
for (const id of this.active.keys()) if (!ids.has(id)) this.forget(id);
|
|
107
|
+
for (const grant of grants) this.retain(grant);
|
|
108
|
+
} else for (const id of page.operationIds) {
|
|
109
|
+
const grant = this.store.resultSupervision(id);
|
|
110
|
+
const operation = this.store.getOperation(id);
|
|
111
|
+
if (grant && operation?.phase === "running" && !operation.terminalRevision) { this.retain(grant); this.dirty.add(id); }
|
|
112
|
+
else this.forget(id);
|
|
113
|
+
}
|
|
114
|
+
// Restart always restores authority; this in-memory position never authorizes work.
|
|
115
|
+
this.position = { generation: page.generation, seq: page.seq };
|
|
116
|
+
if (page.more) this.schedule();
|
|
117
|
+
} catch (error) {
|
|
118
|
+
// Feed recovery must not suppress deadlines for already captured work.
|
|
119
|
+
this.observationReason = String(error);
|
|
120
|
+
}
|
|
121
|
+
const now = Date.now();
|
|
122
|
+
for (const [id, entry] of this.active) if (entry.due <= now) this.dirty.add(id);
|
|
123
|
+
for (const id of [...this.dirty].slice(0, ENTITY_BUDGET)) {
|
|
124
|
+
this.dirty.delete(id);
|
|
125
|
+
const entry = this.active.get(id)!;
|
|
126
|
+
let grant = entry.grant;
|
|
127
|
+
this.metrics.deadlineLatenessMs = Math.max(this.metrics.deadlineLatenessMs, Math.max(0, now - entry.due));
|
|
128
|
+
entry.due = now + 1000;
|
|
41
129
|
const operation = this.store.getOperation(grant.operationId);
|
|
42
|
-
if (!operation || operation.terminalRevision > 0) continue;
|
|
130
|
+
if (!operation || operation.terminalRevision > 0) { this.forget(id); continue; }
|
|
131
|
+
entry.reason = undefined;
|
|
132
|
+
const uncertain = (reason: string) => {
|
|
133
|
+
this.observationReason = reason;
|
|
134
|
+
entry.failure = reason;
|
|
135
|
+
entry.uncertainSince ??= now;
|
|
136
|
+
if (now < entry.uncertainSince + this.verificationMs) entry.reason = {
|
|
137
|
+
kind: "verification", id: operation.taskId, operationId: operation.operationId,
|
|
138
|
+
owner: operation.owner, lastProgressAt: entry.uncertainSince,
|
|
139
|
+
nextDeadline: entry.uncertainSince + this.verificationMs, recovery: reason,
|
|
140
|
+
};
|
|
141
|
+
else entry.due = Infinity;
|
|
142
|
+
if (entry.reason) entry.due = Math.min(entry.due, entry.uncertainSince + this.verificationMs);
|
|
143
|
+
};
|
|
144
|
+
try {
|
|
43
145
|
if (grant.capability?.adapter !== "background-results-v1" || !grant.capability.captured || !grant.capability.current) {
|
|
44
|
-
|
|
146
|
+
uncertain("permission-unavailable: captured Background adapter or permission source unavailable");
|
|
45
147
|
continue;
|
|
46
148
|
}
|
|
47
149
|
if (grant.epoch !== this.epoch) {
|
|
48
150
|
// Daemon startup has already proved the preceding root owner exited.
|
|
49
151
|
grant = { ...grant, hostId: this.hostId, epoch: this.epoch };
|
|
50
152
|
this.store.recoverResultSupervision(grant);
|
|
153
|
+
entry.grant = grant;
|
|
51
154
|
}
|
|
155
|
+
this.metrics.inspections++;
|
|
52
156
|
const inspection = createLocalSupervisor({ directory: grant.directory }).inspect(operation.taskId);
|
|
53
157
|
if (!inspection || inspection.token !== grant.launchToken) {
|
|
54
|
-
|
|
158
|
+
uncertain("reconciling: exact runner evidence unavailable; no replacement command is permitted");
|
|
55
159
|
continue;
|
|
56
160
|
}
|
|
57
|
-
if (inspection.terminal
|
|
58
|
-
|
|
161
|
+
if (!inspection.terminal && (inspection.fenceBusy || !inspection.claim?.pidStartTime)) {
|
|
162
|
+
uncertain("reconciling: runner start identity or state fence is unverified; no takeover is permitted");
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
if (inspection.terminal) {
|
|
166
|
+
this.store.publishSupervisedResult({ operationId: operation.operationId,
|
|
167
|
+
epoch: this.epoch, publication: supervisorTerminalPublication(operation, inspection) });
|
|
168
|
+
this.metrics.publications++; this.forget(id);
|
|
169
|
+
} else {
|
|
170
|
+
entry.failure = undefined;
|
|
171
|
+
entry.uncertainSince = undefined;
|
|
172
|
+
entry.reason = { kind: "runner", id: operation.taskId, operationId: operation.operationId,
|
|
173
|
+
launchToken: grant.launchToken, owner: operation.owner, directory: grant.directory,
|
|
174
|
+
lastProgressAt: inspection.command?.startedAt ?? inspection.claim?.claimedAt ?? inspection.launch.createdAt,
|
|
175
|
+
nextDeadline: entry.due, recovery: "observe-existing-runner" };
|
|
176
|
+
}
|
|
177
|
+
} catch (error) { uncertain(String(error)); }
|
|
59
178
|
}
|
|
60
|
-
|
|
179
|
+
this.observationReason ??= [...this.active.values()].find(entry => entry.failure)?.failure;
|
|
180
|
+
try { this.reconcileAssignmentCleanup(); }
|
|
181
|
+
catch (error) { this.assignmentCleanupReason = `Assignment cleanup: ${String(error)}`; }
|
|
182
|
+
} catch (error) { this.observationReason = String(error); }
|
|
183
|
+
finally {
|
|
184
|
+
release();
|
|
185
|
+
if (this.timer) clearTimeout(this.timer);
|
|
186
|
+
if (this.dirty.size) this.schedule();
|
|
187
|
+
// A cheap journal page repairs missed database hints; task inspections are
|
|
188
|
+
// charged only to exact dirty identities or their liveness deadline.
|
|
189
|
+
const next = [...this.active.values()].reduce((deadline, entry) => Math.min(deadline, entry.due), Date.now() + 1000);
|
|
190
|
+
this.timer = setTimeout(() => this.reconcile(), Math.max(1, next - Date.now()));
|
|
191
|
+
this.timer.unref();
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
private reconcileAssignmentCleanup() {
|
|
195
|
+
if (this.assignmentCleanup) return;
|
|
196
|
+
const [operation] = this.store.listAssignmentCleanupOperations(1, this.assignmentCleanupCursor);
|
|
197
|
+
this.assignmentCleanupCursor = operation?.operationId;
|
|
198
|
+
if (!operation) {
|
|
199
|
+
if (!this.store.listAssignmentCleanupOperations(1).length) this.assignmentCleanupReason = undefined;
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
const grant = this.store.resultSupervision(operation.operationId);
|
|
203
|
+
if (!grant || (operation.terminalRevision === 0 && grant.epoch !== this.epoch) || grant.launchToken !== operation.launchToken || grant.hostId !== operation.supervision?.hostId ||
|
|
204
|
+
grant.capability?.adapter !== "background-results-v1" || !grant.capability.captured || !grant.capability.current) {
|
|
205
|
+
this.assignmentCleanupReason = `Assignment cleanup for ${operation.taskId}: exact supervision authority unavailable`;
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
const supervisor = createLocalSupervisor({ directory: grant.directory });
|
|
209
|
+
const inspection = supervisor.snapshot(operation.taskId);
|
|
210
|
+
const stop = readStopRequest(grant.directory, operation.taskId);
|
|
211
|
+
if (inspection?.token !== operation.launchToken || (stop && stop.token !== operation.launchToken)) {
|
|
212
|
+
this.assignmentCleanupReason = `Assignment cleanup for ${operation.taskId}: exact launch evidence unavailable`;
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
this.assignmentCleanupReason = `Assignment cleanup for ${operation.taskId}: waiting for supervisor evidence`;
|
|
216
|
+
if (inspection.terminal) {
|
|
217
|
+
if (inspection.status !== "lost" && inspection.result?.groupCleanup !== "unproven") return;
|
|
218
|
+
const pgid = inspection.command?.pgid ?? inspection.command?.pid;
|
|
219
|
+
if (inspection.cleanup?.groupEmpty === true || (pgid && !processGroupAlive(pgid))) {
|
|
220
|
+
this.store.verifyAssignmentCleanup(operation.operationId, operation.launchToken, operation.terminalRevision);
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
this.assignmentCleanupReason = `Assignment cleanup for ${operation.taskId}: process group exit unverified`;
|
|
224
|
+
if (!pgid) return;
|
|
225
|
+
}
|
|
226
|
+
this.assignmentCleanup = supervisor.stop(operation.taskId, { token: operation.launchToken, reason: "owning assignment ended" })
|
|
227
|
+
.catch((error: unknown) => { this.assignmentCleanupReason = `Assignment cleanup for ${operation.taskId}: ${String(error)}`; })
|
|
228
|
+
.finally(() => { this.assignmentCleanup = undefined; });
|
|
229
|
+
}
|
|
230
|
+
close() {
|
|
231
|
+
this.closed = true; if (this.timer) clearTimeout(this.timer); this.watcher?.close();
|
|
232
|
+
for (const watcher of this.taskWatchers.values()) watcher.close();
|
|
233
|
+
this.taskWatchers.clear(); this.releaseStore();
|
|
61
234
|
}
|
|
62
|
-
close() { clearInterval(this.timer); this.releaseStore(); }
|
|
63
235
|
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { EventEmitter } from "node:events";
|
|
2
|
+
import { realpathSync, statSync, watch } from "node:fs";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { basename, dirname, relative, sep } from "node:path";
|
|
5
|
+
import { isMainThread, type MessagePort } from "node:worker_threads";
|
|
6
|
+
|
|
7
|
+
export interface SourceWatcher extends EventEmitter { ready: Promise<void>; close(): void }
|
|
8
|
+
export type SourceWatch = (path: string, listener: (event: string, name?: string) => void, shareParent?: boolean) => SourceWatcher;
|
|
9
|
+
export type WatchBackend = (path: string, changed: (name?: string) => void, failed: (error: Error) => void, shareParent?: boolean) => () => Promise<void>;
|
|
10
|
+
|
|
11
|
+
type ChangeListener = (name?: string) => void;
|
|
12
|
+
interface DarwinRunStream {
|
|
13
|
+
listeners: Map<string, Set<ChangeListener>>;
|
|
14
|
+
stop: () => Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
const runStreams = new Map<string, DarwinRunStream>();
|
|
17
|
+
|
|
18
|
+
// FSEvents is recursive. Share a stream across sibling run directories while
|
|
19
|
+
// keeping individual subscriptions, event routing and generation cleanup.
|
|
20
|
+
function watchDarwinRun(parent: string, root: string, changed: ChangeListener): () => Promise<void> {
|
|
21
|
+
const stat = statSync(parent, { bigint: true });
|
|
22
|
+
const key = JSON.stringify([parent, String(stat.dev), String(stat.ino)]);
|
|
23
|
+
let stream = runStreams.get(key);
|
|
24
|
+
if (!stream) {
|
|
25
|
+
const listeners = new Map<string, Set<ChangeListener>>();
|
|
26
|
+
const native = createRequire(import.meta.url)("fsevents");
|
|
27
|
+
const stop = native.watch(parent, (entry: string, flags: number) => {
|
|
28
|
+
if ((flags & 7) || entry === parent) {
|
|
29
|
+
for (const group of listeners.values()) for (const notify of group) notify();
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
for (const notify of listeners.get(dirname(entry)) ?? []) notify(basename(entry));
|
|
33
|
+
// A directory itself was renamed or removed.
|
|
34
|
+
for (const notify of listeners.get(entry) ?? []) notify();
|
|
35
|
+
});
|
|
36
|
+
stream = { listeners, stop };
|
|
37
|
+
runStreams.set(key, stream);
|
|
38
|
+
}
|
|
39
|
+
const group = stream.listeners.get(root) ?? new Set<ChangeListener>();
|
|
40
|
+
const notify: ChangeListener = name => changed(name);
|
|
41
|
+
group.add(notify);
|
|
42
|
+
stream.listeners.set(root, group);
|
|
43
|
+
return async () => {
|
|
44
|
+
if (!group.delete(notify)) return;
|
|
45
|
+
if (!group.size) stream.listeners.delete(root);
|
|
46
|
+
if (!stream.listeners.size) {
|
|
47
|
+
runStreams.delete(key);
|
|
48
|
+
await stream.stop();
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export const nativeWatch: WatchBackend = (path, changed, failed, shareParent) => {
|
|
54
|
+
const root = realpathSync(path);
|
|
55
|
+
if (process.platform !== "darwin") {
|
|
56
|
+
const watcher = watch(root, (_event, name) => changed(name ?? undefined));
|
|
57
|
+
watcher.on("error", failed);
|
|
58
|
+
return () => new Promise(resolve => { watcher.once("close", resolve); watcher.close(); });
|
|
59
|
+
}
|
|
60
|
+
// Loaded only by the owner, never by an executor worker.
|
|
61
|
+
if (!isMainThread) throw new Error("Darwin native source watches require the host transport");
|
|
62
|
+
if (shareParent && dirname(root) === realpathSync(dirname(path))) return watchDarwinRun(dirname(root), root, changed);
|
|
63
|
+
const native = createRequire(import.meta.url)("fsevents");
|
|
64
|
+
return native.watch(root, (entry: string, flags: number) => {
|
|
65
|
+
const name = relative(root, entry);
|
|
66
|
+
if (name === ".." || name.includes(sep)) return;
|
|
67
|
+
changed(flags & 7 ? undefined : name || basename(root));
|
|
68
|
+
});
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
export const watchSource: SourceWatch = (path, listener, shareParent) => {
|
|
72
|
+
const watcher = new EventEmitter() as SourceWatcher;
|
|
73
|
+
let closed = false;
|
|
74
|
+
watcher.on("change", listener);
|
|
75
|
+
const stop = nativeWatch(path, name => { if (!closed) watcher.emit("change", "rename", name); }, error => { if (!closed) watcher.emit("error", error); }, shareParent);
|
|
76
|
+
watcher.ready = Promise.resolve();
|
|
77
|
+
watcher.close = () => { if (!closed) { closed = true; void stop().then(() => watcher.emit("close"), error => watcher.emit("error", error)); } };
|
|
78
|
+
return watcher;
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
interface Subscription { live: boolean; busy: boolean; names: Set<string | undefined>; overflow: boolean; stop: () => Promise<void>; retiring?: Promise<void> }
|
|
82
|
+
/** One executor owns native lifetimes even when its worker cannot run cleanup. */
|
|
83
|
+
export class HostSourceWatches {
|
|
84
|
+
private entries = new Map<string, Subscription>();
|
|
85
|
+
private revoked = new Set<number>();
|
|
86
|
+
private stopFailures = 0;
|
|
87
|
+
private backend: WatchBackend;
|
|
88
|
+
private limit: number;
|
|
89
|
+
constructor(backend: WatchBackend = nativeWatch, limit = 16384) { this.backend = backend; this.limit = limit; }
|
|
90
|
+
metrics() { return { allocated: this.entries.size, retiring: [...this.entries.values()].filter(value => !value.live).length, stopFailures: this.stopFailures }; }
|
|
91
|
+
handle(generation: number, message: any, send: (value: any) => void) {
|
|
92
|
+
if (!String(message.type).startsWith("source-watch-")) return false;
|
|
93
|
+
const id = message.id, key = `${generation}:${id}`;
|
|
94
|
+
if (!Number.isSafeInteger(id) || id < 1) return true;
|
|
95
|
+
const entry = this.entries.get(key);
|
|
96
|
+
if (message.type === "source-watch-subscribe") {
|
|
97
|
+
if (this.revoked.has(generation)) return true;
|
|
98
|
+
try {
|
|
99
|
+
if (entry || this.entries.size >= this.limit) throw new Error("Source watch capacity exhausted (including retiring subscriptions)");
|
|
100
|
+
const value: Subscription = { live: true, busy: false, names: new Set(), overflow: false, stop: async () => {} };
|
|
101
|
+
this.entries.set(key, value);
|
|
102
|
+
const changed = (name?: string) => {
|
|
103
|
+
if (!value.live) return;
|
|
104
|
+
if (value.busy) {
|
|
105
|
+
if (value.names.size < 128) value.names.add(name); else value.overflow = true;
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
value.busy = true;
|
|
109
|
+
send({ type: "source-watch-event", id, names: [name] });
|
|
110
|
+
};
|
|
111
|
+
try { value.stop = this.backend(message.path, changed, error => {
|
|
112
|
+
if (!value.live) return;
|
|
113
|
+
send({ type: "source-watch-error", id, error: String(error).slice(0, 512) });
|
|
114
|
+
void this.retire(key, value).catch(() => {});
|
|
115
|
+
}, message.shareParent === true); }
|
|
116
|
+
catch (error) { this.entries.delete(key); throw error; }
|
|
117
|
+
send({ type: "source-watch-subscribed", id });
|
|
118
|
+
} catch (error) { send({ type: "source-watch-subscribed", id, error: String(error).slice(0, 512) }); }
|
|
119
|
+
} else if (message.type === "source-watch-consumed" && entry?.live) {
|
|
120
|
+
entry.busy = false;
|
|
121
|
+
if (entry.names.size || entry.overflow) {
|
|
122
|
+
const names = [...entry.names];
|
|
123
|
+
if (entry.overflow) names.push(undefined);
|
|
124
|
+
entry.names.clear(); entry.overflow = false; entry.busy = true;
|
|
125
|
+
send({ type: "source-watch-event", id, names });
|
|
126
|
+
}
|
|
127
|
+
} else if (message.type === "source-watch-unsubscribe") {
|
|
128
|
+
void (entry ? this.retire(key, entry) : Promise.resolve()).then(() => send({ type: "source-watch-unsubscribed", id }),
|
|
129
|
+
error => send({ type: "source-watch-unsubscribed", id, error: String(error).slice(0, 512) }));
|
|
130
|
+
}
|
|
131
|
+
return true;
|
|
132
|
+
}
|
|
133
|
+
private retire(key: string, entry: Subscription) {
|
|
134
|
+
entry.live = false;
|
|
135
|
+
return entry.retiring ??= Promise.resolve().then(entry.stop).then(() => { this.entries.delete(key); }, error => { this.stopFailures++; throw error; });
|
|
136
|
+
}
|
|
137
|
+
revoke(generation: number) {
|
|
138
|
+
this.revoked.add(generation);
|
|
139
|
+
return Promise.all([...this.entries].filter(([key]) => key.startsWith(`${generation}:`)).map(([key, entry]) => this.retire(key, entry)));
|
|
140
|
+
}
|
|
141
|
+
close() { return Promise.all([...this.entries].map(([key, entry]) => this.retire(key, entry))); }
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function workerSourceWatch(port: MessagePort): SourceWatch {
|
|
145
|
+
let counter = 0;
|
|
146
|
+
const entries = new Map<number, { watcher: SourceWatcher; resolve(): void; reject(error: Error): void; closed: boolean }>();
|
|
147
|
+
port.on("message", message => {
|
|
148
|
+
const entry = entries.get(message.id);
|
|
149
|
+
if (!entry || !String(message.type).startsWith("source-watch-")) return;
|
|
150
|
+
if (message.type === "source-watch-subscribed") {
|
|
151
|
+
if (message.error) entry.reject(new Error(message.error)); else entry.resolve();
|
|
152
|
+
} else if (message.type === "source-watch-error") {
|
|
153
|
+
if (!entry.closed) entry.watcher.emit("error", new Error(message.error));
|
|
154
|
+
} else if (message.type === "source-watch-event") {
|
|
155
|
+
if (!entry.closed) for (const name of message.names) entry.watcher.emit("change", "rename", name);
|
|
156
|
+
port.postMessage({ type: "source-watch-consumed", id: message.id });
|
|
157
|
+
} else if (message.type === "source-watch-unsubscribed") {
|
|
158
|
+
entries.delete(message.id);
|
|
159
|
+
if (message.error) entry.watcher.emit("error", new Error(message.error)); else entry.watcher.emit("close");
|
|
160
|
+
}
|
|
161
|
+
});
|
|
162
|
+
return (path, listener, shareParent) => {
|
|
163
|
+
// Preserve synchronous missing-path semantics; the model owns ancestor selection.
|
|
164
|
+
realpathSync(path);
|
|
165
|
+
const id = ++counter, watcher = new EventEmitter() as SourceWatcher;
|
|
166
|
+
let resolve!: () => void, reject!: (error: Error) => void;
|
|
167
|
+
watcher.ready = new Promise<void>((yes, no) => { resolve = yes; reject = no; });
|
|
168
|
+
void watcher.ready.catch(() => {});
|
|
169
|
+
const entry = { watcher, resolve, reject, closed: false };
|
|
170
|
+
entries.set(id, entry); watcher.on("change", listener);
|
|
171
|
+
watcher.close = () => { if (!entry.closed) { entry.closed = true; port.postMessage({ type: "source-watch-unsubscribe", id }); } };
|
|
172
|
+
port.postMessage({ type: "source-watch-subscribe", id, path, shareParent });
|
|
173
|
+
return watcher;
|
|
174
|
+
};
|
|
175
|
+
}
|
|
@@ -14,7 +14,7 @@ export function hasSubagentManagement(root: string): boolean {
|
|
|
14
14
|
}
|
|
15
15
|
|
|
16
16
|
/** Fixed bundled domain adapter. No client module paths reach this boundary. */
|
|
17
|
-
export async function createSubagentLaunch(root: string, instance: string, catalog: unknown) {
|
|
17
|
+
export async function createSubagentLaunch(root: string, instance: string, catalog: unknown, verificationMs = 30000) {
|
|
18
18
|
if (Number(process.versions.node.split(".")[0]) < 24) throw new Error("Managed subagents require Node 24 or newer");
|
|
19
19
|
const path = "./domain/subagents/managed-launch-host.domain.mjs";
|
|
20
20
|
const { ManagedSubagentHost } = await import(path);
|
|
@@ -29,10 +29,13 @@ export async function createSubagentLaunch(root: string, instance: string, catal
|
|
|
29
29
|
const runtimePath = "./domain/background-service/runtime.domain.mjs";
|
|
30
30
|
const { registerTools } = await import(toolsPath);
|
|
31
31
|
const { createBackgroundTaskRuntime } = await import(runtimePath);
|
|
32
|
+
const registryPath = './domain/background-service/registry.domain.mjs';
|
|
33
|
+
const { readMeta } = await import(registryPath);
|
|
32
34
|
const sandboxPath="./domain/background-service/sandbox.domain.mjs";
|
|
33
35
|
const sandbox=await import(sandboxPath);
|
|
34
36
|
host = new ManagedSubagentHost(root, instance, catalog, lease.store, (pi: any) => {
|
|
35
|
-
const service = createObservedWaitHost(pi, { sharedStore: lease.store, storePath: join(root, "operation-coordinator.sqlite"), serverOwnedResults: true,
|
|
37
|
+
const service = createObservedWaitHost(pi, { sharedStore: lease.store, storePath: join(root, "operation-coordinator.sqlite"), serverOwnedResults: true, pollMs: 0,
|
|
38
|
+
enterControl: () => lease.budget.enter("control"), verificationMs,
|
|
36
39
|
prepareWorkerPolicy(run:any){
|
|
37
40
|
const resolve=()=>{
|
|
38
41
|
const attempt=lease.store.subagentLaunchJournal().attempt(run.runId);
|
|
@@ -47,12 +50,16 @@ export async function createSubagentLaunch(root: string, instance: string, catal
|
|
|
47
50
|
return ()=>{if(JSON.stringify(resolve())!==expected)throw new Error('permission-unavailable: Background policy changed before worker dispatch');};
|
|
48
51
|
}
|
|
49
52
|
});
|
|
50
|
-
const runtime = createBackgroundTaskRuntime(
|
|
53
|
+
const runtime = createBackgroundTaskRuntime(undefined, undefined, undefined,
|
|
54
|
+
(kind: string, id: string, work: () => unknown, dueAt?: number) => {
|
|
55
|
+
const origin = readMeta(id)?.callbackOrigin;
|
|
56
|
+
return lease.budget.scheduleSource(`legacy-${kind}`, id, work, JSON.stringify([origin?.cwd ?? root, origin?.sessionId ?? null]), dueAt);
|
|
57
|
+
});
|
|
51
58
|
registerTools(pi, runtime, () => undefined);
|
|
52
59
|
const close = service.close.bind(service);
|
|
53
60
|
service.close = () => { try { close(); } finally { runtime.suspendScheduledWork(); } };
|
|
54
61
|
return service;
|
|
55
|
-
}, () => readPermissionSettings({ agentDir: () => root }));
|
|
62
|
+
}, () => readPermissionSettings({ agentDir: () => root }), verificationMs, () => lease.budget.enter("control"));
|
|
56
63
|
await host.recover();
|
|
57
64
|
const close = host.close.bind(host);
|
|
58
65
|
host.close = async () => {
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// Source hints coalesce by entity. Receipt/application remains owned by each
|
|
2
|
+
// domain; both domains take the same bounded foreground allowance before repair.
|
|
3
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
4
|
+
export const ENTITY_BUDGET = 32;
|
|
5
|
+
export type WorkLane = "control" | "query" | "repair";
|
|
6
|
+
const lanes: WorkLane[] = ["control", "query", "repair"];
|
|
7
|
+
const limits = [16, 8, 8];
|
|
8
|
+
const sourceKinds = ['legacy-watch', 'legacy-remote-poll', 'legacy-handoff', 'legacy-process-deadline', 'legacy-log-retention'];
|
|
9
|
+
const wakeIndex = 10 + sourceKinds.length * 5;
|
|
10
|
+
export function notifyWorkBudget(buffer: SharedArrayBuffer) {
|
|
11
|
+
const counters = new Int32Array(buffer);
|
|
12
|
+
if (counters.length > wakeIndex) { Atomics.add(counters, wakeIndex, 1); Atomics.notify(counters, wakeIndex); }
|
|
13
|
+
}
|
|
14
|
+
/** Root-wide outstanding source work. Reserved lanes cannot be consumed by a wedged reader. */
|
|
15
|
+
export function createWorkBudget(buffer = new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT * (wakeIndex + 7 + sourceKinds.length))) {
|
|
16
|
+
const counters = new Int32Array(buffer);
|
|
17
|
+
const legacyIndex = 9 + sourceKinds.length * 5;
|
|
18
|
+
const reservation = new AsyncLocalStorage<{ active: boolean }>();
|
|
19
|
+
const pending = new Map<string, Promise<unknown>>();
|
|
20
|
+
const ownerObservations = new Map<string, number>();
|
|
21
|
+
const queue: Array<() => boolean> = [];
|
|
22
|
+
let waiting = false, pumping = false;
|
|
23
|
+
const pump = () => {
|
|
24
|
+
if (pumping) return;
|
|
25
|
+
pumping = true;
|
|
26
|
+
const version = Atomics.load(counters, wakeIndex);
|
|
27
|
+
for (let i = 0; i < queue.length;) { if (queue[i]!()) queue.splice(i, 1); else i++; }
|
|
28
|
+
pumping = false;
|
|
29
|
+
if (queue.length && !waiting) {
|
|
30
|
+
const wait = (Atomics as typeof Atomics & { waitAsync(array: Int32Array, index: number, value: number): { async: boolean; value: string | Promise<string> } }).waitAsync(counters, wakeIndex, version);
|
|
31
|
+
if (wait.async) { waiting = true; void (wait.value as Promise<string>).then(() => { waiting = false; pump(); }); }
|
|
32
|
+
else queueMicrotask(pump);
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
const sourceWork = new Map<string, { started: number; completed: number; failed: number; elapsedMs: number; active: number }>();
|
|
36
|
+
return { buffer,
|
|
37
|
+
// Timers and accepted recovery use deferred dispatch. Synchronous callers
|
|
38
|
+
// retain their return/throw contract; nested source measurement never waits.
|
|
39
|
+
scheduleSource<T>(kind: string, id: string, work: () => T, owner = 'runtime', dueAt?: number): Promise<Awaited<T>> {
|
|
40
|
+
if (reservation.getStore()?.active) return Promise.resolve().then(() => this.source(kind, work)) as Promise<Awaited<T>>;
|
|
41
|
+
const key = JSON.stringify([owner, kind, id]);
|
|
42
|
+
const prior = pending.get(key);
|
|
43
|
+
if (prior) return prior as Promise<Awaited<T>>;
|
|
44
|
+
let resolve!: (value: Awaited<T>) => void, reject!: (error: unknown) => void;
|
|
45
|
+
const result = new Promise<Awaited<T>>((yes, no) => { resolve = yes; reject = no; });
|
|
46
|
+
pending.set(key, result);
|
|
47
|
+
queue.push(() => {
|
|
48
|
+
// Outstanding observations cannot consume the slots needed by deadlines.
|
|
49
|
+
const observation = !['legacy-process-deadline', 'legacy-handoff', 'cancellation'].includes(kind);
|
|
50
|
+
if (observation && owner !== 'runtime' && (ownerObservations.get(owner) ?? 0) >= 2) return false;
|
|
51
|
+
if (observation && counters.length > legacyIndex) {
|
|
52
|
+
for (;;) {
|
|
53
|
+
const active = Atomics.load(counters, legacyIndex);
|
|
54
|
+
if (active >= 8) return false;
|
|
55
|
+
if (Atomics.compareExchange(counters, legacyIndex, active, active + 1) === active) break;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const release = this.enter('control');
|
|
59
|
+
if (!release) { if (observation && counters.length > legacyIndex) Atomics.sub(counters, legacyIndex, 1); return false; }
|
|
60
|
+
const scope = { active: true };
|
|
61
|
+
const sourceIndex = sourceKinds.indexOf(kind);
|
|
62
|
+
if (sourceIndex >= 0 && dueAt !== undefined) Atomics.add(counters, wakeIndex + 7 + sourceIndex, Math.max(0, Date.now() - dueAt));
|
|
63
|
+
if (observation) ownerObservations.set(owner, (ownerObservations.get(owner) ?? 0) + 1);
|
|
64
|
+
const finish = () => {
|
|
65
|
+
scope.active = false;
|
|
66
|
+
if (observation) { const left = ownerObservations.get(owner)! - 1; if (left) ownerObservations.set(owner, left); else ownerObservations.delete(owner); }
|
|
67
|
+
if (observation && counters.length > legacyIndex) Atomics.sub(counters, legacyIndex, 1); pending.delete(key); release();
|
|
68
|
+
};
|
|
69
|
+
try {
|
|
70
|
+
Promise.resolve(reservation.run(scope, () => this.source(kind, work))).then(value => { finish(); resolve(value); }, error => { finish(); reject(error); });
|
|
71
|
+
} catch (error) { finish(); reject(error); }
|
|
72
|
+
return true;
|
|
73
|
+
});
|
|
74
|
+
pump();
|
|
75
|
+
return result;
|
|
76
|
+
},
|
|
77
|
+
// Measure at the owner that performs the work, including asynchronous completion.
|
|
78
|
+
source<T>(kind: string, work: () => T): T {
|
|
79
|
+
const index = sourceKinds.indexOf(kind), base = 9 + index * 5;
|
|
80
|
+
const shared = index >= 0 && counters.length >= base + 5;
|
|
81
|
+
let metric = sourceWork.get(kind);
|
|
82
|
+
if (!metric) { metric = { started: 0, completed: 0, failed: 0, elapsedMs: 0, active: 0 }; sourceWork.set(kind, metric); }
|
|
83
|
+
metric.started++; metric.active++;
|
|
84
|
+
if (shared) { Atomics.add(counters, base, 1); Atomics.add(counters, base + 4, 1); }
|
|
85
|
+
const started = performance.now();
|
|
86
|
+
const finish = (failed: boolean) => {
|
|
87
|
+
const elapsed = performance.now() - started;
|
|
88
|
+
metric.active--; metric.completed++; metric.failed += Number(failed); metric.elapsedMs += elapsed;
|
|
89
|
+
if (shared) { Atomics.add(counters, base + 1, 1); Atomics.add(counters, base + 2, Number(failed)); Atomics.add(counters, base + 3, Math.round(elapsed)); Atomics.sub(counters, base + 4, 1); }
|
|
90
|
+
};
|
|
91
|
+
try {
|
|
92
|
+
const value = work();
|
|
93
|
+
if (value instanceof Promise) return value.then(result => { finish(false); return result; }, error => { finish(true); throw error; }) as T;
|
|
94
|
+
finish(false);
|
|
95
|
+
return value;
|
|
96
|
+
} catch (error) { finish(true); throw error; }
|
|
97
|
+
},
|
|
98
|
+
enter(lane: WorkLane) {
|
|
99
|
+
const index = lanes.indexOf(lane);
|
|
100
|
+
for (;;) {
|
|
101
|
+
const used = Atomics.load(counters, index);
|
|
102
|
+
if (used >= limits[index]!) { Atomics.add(counters, index + 6, 1); return undefined; }
|
|
103
|
+
if (Atomics.compareExchange(counters, index, used, used + 1) === used) break;
|
|
104
|
+
}
|
|
105
|
+
Atomics.add(counters, index + 3, 1);
|
|
106
|
+
const started = performance.now();
|
|
107
|
+
let released = false;
|
|
108
|
+
return () => { if (!released) {
|
|
109
|
+
released = true; Atomics.sub(counters, index, 1);
|
|
110
|
+
Atomics.add(counters, wakeIndex + 1 + index, 1);
|
|
111
|
+
Atomics.add(counters, wakeIndex + 4 + index, Math.round(performance.now() - started));
|
|
112
|
+
notifyWorkBudget(buffer);
|
|
113
|
+
} };
|
|
114
|
+
},
|
|
115
|
+
metrics() { return { queuedSources: queue.length, pendingSources: pending.size, sources: { ...Object.fromEntries([...sourceWork].map(([kind, metric]) => [kind, { ...metric, deadlineLatenessMs: 0 }])),
|
|
116
|
+
...Object.fromEntries(sourceKinds.flatMap((kind, i) => {
|
|
117
|
+
const base = 9 + i * 5;
|
|
118
|
+
return counters.length < base + 5 ? [] : [[kind, { started: Atomics.load(counters, base), completed: Atomics.load(counters, base + 1),
|
|
119
|
+
failed: Atomics.load(counters, base + 2), elapsedMs: Atomics.load(counters, base + 3), active: Atomics.load(counters, base + 4),
|
|
120
|
+
deadlineLatenessMs: Atomics.load(counters, wakeIndex + 7 + i) }]];
|
|
121
|
+
})) }, capacity: ENTITY_BUDGET, lanes: Object.fromEntries(lanes.map((lane, i) => [lane,
|
|
122
|
+
{ capacity: limits[i], active: Atomics.load(counters, i), admitted: Atomics.load(counters, i + 3), deferred: Atomics.load(counters, i + 6),
|
|
123
|
+
completed: Atomics.load(counters, wakeIndex + 1 + i), elapsedMs: Atomics.load(counters, wakeIndex + 4 + i) }])) }; },
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
export function workPage<T>(items: Iterable<T>, limit = ENTITY_BUDGET): T[] {
|
|
127
|
+
const page: T[] = [];
|
|
128
|
+
for (const item of items) { if (page.length === limit) break; page.push(item); }
|
|
129
|
+
return page;
|
|
130
|
+
}
|
|
@@ -12,3 +12,11 @@ export class WorkClient {
|
|
|
12
12
|
onCatalog(listener: (snapshot: any) => void): () => void;
|
|
13
13
|
close(): void;
|
|
14
14
|
}
|
|
15
|
+
|
|
16
|
+
export interface ConnectionOptions {
|
|
17
|
+
timeoutMs?: number;
|
|
18
|
+
signal?: AbortSignal;
|
|
19
|
+
recover?: (options: { timeoutMs: number; signal: AbortSignal }) => Promise<unknown>;
|
|
20
|
+
}
|
|
21
|
+
/** Establishes a connection; never replays application requests. */
|
|
22
|
+
export function connectWorkClient(socketPath: string, agentDir: string, capabilities?: string[], options?: ConnectionOptions): Promise<WorkClient>;
|