@zhuxixi/pi-agent-board 0.12.0 → 0.13.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/CHANGELOG.md +36 -0
- package/README.md +7 -7
- package/docs/superpowers/plans/2026-10-19-issue-213-reply-guard-csi-key.md +257 -0
- package/docs/superpowers/plans/2026-10-19-issue-214-attach-forward-alt-modifier.md +202 -0
- package/docs/superpowers/plans/2026-10-21-issue-221-ask-user-question.md +198 -0
- package/docs/superpowers/plans/2026-10-23-issue-225-monotonic-foreground-state.md +450 -0
- package/docs/superpowers/plans/2026-10-23-issue-229-vim-jkl.md +449 -0
- package/docs/superpowers/plans/2026-10-23-issue-232-attach-bg-only-cells.md +153 -0
- package/docs/superpowers/plans/2026-10-23-lease-heartbeat-staleness.md +537 -0
- package/docs/superpowers/plans/2026-10-23-selected-row-highlight.md +405 -0
- package/docs/superpowers/plans/2026-10-24-issue-217-windows-pid-reuse-stopping.md +367 -0
- package/docs/superpowers/plans/2026-10-24-issue-230-warm-host-background-runs.md +806 -0
- package/docs/superpowers/plans/2026-10-24-issue-238-windows-process-identity-token.md +490 -0
- package/docs/superpowers/plans/2026-10-24-issue-241-coordinator-root-exit.md +461 -0
- package/docs/superpowers/plans/2026-10-25-issue-239-coordinator-replacement-identity.md +504 -0
- package/docs/superpowers/specs/2026-10-14-issue-170-attach-reply-guard-design.md +5 -0
- package/docs/superpowers/specs/2026-10-19-issue-213-reply-guard-csi-key-design.md +165 -0
- package/docs/superpowers/specs/2026-10-19-issue-214-attach-forward-alt-modifier-design.md +131 -0
- package/docs/superpowers/specs/2026-10-20-issue-221-ask-user-question-design.md +270 -0
- package/docs/superpowers/specs/2026-10-22-issue-225-monotonic-foreground-state-design.md +225 -0
- package/docs/superpowers/specs/2026-10-23-issue-229-vim-jkl-design.md +90 -0
- package/docs/superpowers/specs/2026-10-23-issue-232-attach-bg-only-cells-design.md +146 -0
- package/docs/superpowers/specs/2026-10-23-lease-heartbeat-staleness-design.md +271 -0
- package/docs/superpowers/specs/2026-10-23-selected-row-highlight-design.md +191 -0
- package/docs/superpowers/specs/2026-10-24-issue-217-windows-pid-reuse-stopping-design.md +334 -0
- package/docs/superpowers/specs/2026-10-24-issue-230-warm-host-background-runs-design.md +283 -0
- package/docs/superpowers/specs/2026-10-24-issue-238-windows-process-identity-token-design.md +286 -0
- package/docs/superpowers/specs/2026-10-24-issue-241-coordinator-root-exit-design.md +381 -0
- package/docs/superpowers/specs/2026-10-25-issue-239-coordinator-replacement-identity-design.md +331 -0
- package/package.json +3 -3
- package/runner/pty-runner.mjs +18 -22
- package/runner/state-coordinator.mjs +213 -26
- package/scripts/release_helper.mjs +39 -7
- package/scripts/run-tests.mjs +375 -0
- package/src/core/background-runs.mjs +273 -0
- package/src/core/coordinator-client.mjs +346 -26
- package/src/core/diagnostics.mjs +24 -0
- package/src/core/events.mjs +16 -3
- package/src/core/foreground-projection-cache.mjs +99 -0
- package/src/core/host-coordination.mjs +69 -1
- package/src/core/launch.mjs +21 -1
- package/src/core/locks.mjs +176 -31
- package/src/core/pid.mjs +4 -2
- package/src/core/process-identity-probe.mjs +228 -0
- package/src/core/pty-scroll.mjs +21 -14
- package/src/core/state-commands.mjs +5 -1
- package/src/core/terminal-reply-guard.mjs +26 -4
- package/src/core/types.mjs +1 -0
- package/src/core/warm-host-sweeper.mjs +7 -2
- package/src/runtime/service.mjs +385 -73
- package/src/ui/dashboard.ts +48 -25
- package/src/ui/pty-attach.ts +18 -7
package/src/runtime/service.mjs
CHANGED
|
@@ -4,19 +4,21 @@
|
|
|
4
4
|
* safety rule. Pure node + core modules; the Pi-coupled bits (attach, dialogs) live in
|
|
5
5
|
* the command handler. The pi invocation + runner path are injected (resolved in index.ts).
|
|
6
6
|
*/
|
|
7
|
-
import { existsSync
|
|
7
|
+
import { existsSync } from "node:fs";
|
|
8
8
|
import { randomBytes } from "node:crypto";
|
|
9
9
|
import { createRequire } from "node:module";
|
|
10
10
|
import { createConnection } from "node:net";
|
|
11
11
|
import { resolve } from "node:path";
|
|
12
12
|
import { applyAutoStateToStatus, autoStateEnabled, heuristicAutoState, isManualVerdict } from "../core/auto-state.mjs";
|
|
13
|
+
import { CLOCK_EPSILON_MS, classifyRunsForRow, probeBackgroundRun, resolveWorkflowHome, scanBackgroundRuns } from "../core/background-runs.mjs";
|
|
13
14
|
import { appendLine, atomicWriteJson, removeFile } from "../core/atomic.mjs";
|
|
14
15
|
import { finalizeRun, projectViewState, reduceEvent } from "../core/events.mjs";
|
|
15
|
-
import { clearDiagnostics, appendDiagnostic, tailDiagnostics } from "../core/diagnostics.mjs";
|
|
16
|
+
import { clearDiagnostics, appendDiagnostic, appendDiagnosticOnce, tailDiagnostics } from "../core/diagnostics.mjs";
|
|
16
17
|
import { emptyEvidenceSnapshot, finalizeEvidence, readEvidence, reduceEvidence, summarizeEvidence, writeEvidence } from "../core/evidence.mjs";
|
|
17
18
|
import { updateCodeRefsFromEvidence } from "../core/code-refs-store.mjs";
|
|
18
19
|
import { claimNextFollowUp, completeFollowUp, enqueueFollowUp, failFollowUp, readFollowUpQueue, releaseFollowUp, summarizeFollowUpQueue, clearQueuedFollowUps, removeLastFollowUp } from "../core/follow-up-queue.mjs";
|
|
19
20
|
import { foregroundPreviewCache } from "../core/foreground-preview-cache.mjs";
|
|
21
|
+
import { foregroundProjectionCache } from "../core/foreground-projection-cache.mjs";
|
|
20
22
|
import { approvePlan as approvePlanState, markExecutingApprovedPlan, readSteering, recordPlanReady, requestPlan as requestPlanState, requestPlanChanges as requestPlanChangesState, summarizeSteering } from "../core/steering.mjs";
|
|
21
23
|
import { buildApprovePlanPrompt, buildPlanChangesPrompt, buildPlanRequestPrompt } from "../core/steering-prompts.mjs";
|
|
22
24
|
import { isGenericStatusText } from "../core/derive.mjs";
|
|
@@ -24,9 +26,10 @@ import { firstSentence, truncate } from "../core/heuristics.mjs";
|
|
|
24
26
|
import { newRunId, newViewId, slugifyTask } from "../core/ids.mjs";
|
|
25
27
|
import { launchAutoState as launchAutoStateProcess, launchHost as launchHostProcess, launchRun, launchTitle as launchTitleProcess } from "../core/launch.mjs";
|
|
26
28
|
import { gitRepoRoot } from "../core/repo.mjs";
|
|
27
|
-
import { isAlive, killProcess } from "../core/pid.mjs";
|
|
29
|
+
import { captureStartToken, isAlive, killProcess } from "../core/pid.mjs";
|
|
28
30
|
import { acquireOwnedViewLock, tryAcquireOwnedViewLock } from "../core/locks.mjs";
|
|
29
|
-
import { canFinalizeLegacyHost, canReplaceHost } from "../core/host-coordination.mjs";
|
|
31
|
+
import { canFinalizeLegacyHost, canReplaceHost, classifyUnverifiableProcess, processIdentityState } from "../core/host-coordination.mjs";
|
|
32
|
+
import { readProcessIdentityProbe, readProcessStartToken } from "../core/process-identity-probe.mjs";
|
|
30
33
|
import { modelRefAvailable } from "../core/launch-options.mjs";
|
|
31
34
|
import { ensureCoordinator, sendStateCommand, coordinatorDisabled } from "../core/coordinator-client.mjs";
|
|
32
35
|
import { createDesyncEpisodeThrottle, rereadPair, statusRevisionDesynced } from "../core/status-consistency.mjs";
|
|
@@ -66,8 +69,20 @@ export const HOST_START_LOCK_WAIT_MS = 500;
|
|
|
66
69
|
export const HOST_RECOVERY_GRACE_MS = 5_000;
|
|
67
70
|
/** Poll cadence while waiting out a host recovery window. */
|
|
68
71
|
const HOST_RECOVERY_POLL_MS = 150;
|
|
72
|
+
/** Creation-time tolerance when a host role can only be corroborated by process creation time (issue #217). */
|
|
73
|
+
export const HOST_IDENTITY_CREATION_TOLERANCE_MS = 5_000;
|
|
69
74
|
/** Default wall-clock budget for one attach resolution (issue #70 Task 12). */
|
|
70
75
|
const ATTACH_RESOLVE_TIMEOUT_MS = 120_000;
|
|
76
|
+
/**
|
|
77
|
+
* How long after a finalized host to keep re-probing a still-`running` run
|
|
78
|
+
* before treating it as a hard-kill artifact (issue #230). Finalization waits
|
|
79
|
+
* for the runner and child pids to die, not for the workflow engine's last
|
|
80
|
+
* write, so the `paused` head the engine writes while settling in-flight step
|
|
81
|
+
* children during SIGTERM shutdown can land after `host.state = exited`. A
|
|
82
|
+
* probe in that window reports `running` and, without this grace period, the
|
|
83
|
+
* interruption notice would be swallowed for that host incarnation.
|
|
84
|
+
*/
|
|
85
|
+
export const NOTICE_FLIP_GRACE_MS = 60_000;
|
|
71
86
|
|
|
72
87
|
/**
|
|
73
88
|
* Dynamic readers for the ladder constants above (issue #95 F4). Module-load-time
|
|
@@ -90,6 +105,11 @@ export function resolveHostRecoveryPollMs(env = process.env) {
|
|
|
90
105
|
return resolveTestMs(env, "AGENT_BOARD_TEST_HOST_RECOVERY_POLL_MS", HOST_RECOVERY_POLL_MS);
|
|
91
106
|
}
|
|
92
107
|
|
|
108
|
+
/** @param {NodeJS.ProcessEnv} [env] @returns {number} */
|
|
109
|
+
export function resolveIdentityCreationToleranceMs(env = process.env) {
|
|
110
|
+
return resolveTestMs(env, "AGENT_BOARD_TEST_IDENTITY_CREATION_TOLERANCE_MS", HOST_IDENTITY_CREATION_TOLERANCE_MS);
|
|
111
|
+
}
|
|
112
|
+
|
|
93
113
|
/** @param {NodeJS.ProcessEnv} [env] @returns {number} */
|
|
94
114
|
export function resolveAttachResolveTimeoutMs(env = process.env) {
|
|
95
115
|
return resolveTestMs(env, "AGENT_BOARD_TEST_ATTACH_RESOLVE_TIMEOUT_MS", ATTACH_RESOLVE_TIMEOUT_MS);
|
|
@@ -115,12 +135,20 @@ export function resolveAttachResolveTimeoutMs(env = process.env) {
|
|
|
115
135
|
* now?: () => number,
|
|
116
136
|
* acquireLock?: typeof acquireOwnedViewLock,
|
|
117
137
|
* tryAcquireLock?: typeof tryAcquireOwnedViewLock,
|
|
118
|
-
* observeProcess?: (identity: {pid: number, startToken: string|null}|null) => "not_started"|"dead"|"owned"|"foreign"|"unknown"
|
|
138
|
+
* observeProcess?: (identity: {pid: number, startToken: string|null}|null, observation: {spawnedAt: number|null, pid: number|null, tokenMemo: Map<number, Promise<string|null>>}) => "not_started"|"dead"|"owned"|"foreign"|"unknown"|Promise<"not_started"|"dead"|"owned"|"foreign"|"unknown">,
|
|
139
|
+
* isAlive?: (pid: number) => boolean,
|
|
140
|
+
* readStartToken?: (pid: number) => Promise<string|null>,
|
|
141
|
+
* probeProcessIdentity?: (pid: number) => Promise<{creationTimeMs: number|null, commandLine: string|null}|null>,
|
|
119
142
|
* signalOwnedProcess?: (identity: {pid: number, startToken: string|null}, signal: string) => void,
|
|
120
143
|
* probeHostFn?: typeof probeHost,
|
|
121
144
|
* sleepFn?: (ms: number) => Promise<void>,
|
|
122
145
|
* sendStateCommand?: typeof sendStateCommand,
|
|
123
146
|
* availableModels?: () => Array<{ provider: string, id: string }> | undefined,
|
|
147
|
+
* workflowHome?: string,
|
|
148
|
+
* backgroundRuns?: {
|
|
149
|
+
* scanBackgroundRuns: typeof scanBackgroundRuns,
|
|
150
|
+
* probeBackgroundRun: typeof probeBackgroundRun,
|
|
151
|
+
* },
|
|
124
152
|
* }} opts
|
|
125
153
|
*/
|
|
126
154
|
export function createService(opts) {
|
|
@@ -143,8 +171,21 @@ export function createService(opts) {
|
|
|
143
171
|
const desyncThrottle = createDesyncEpisodeThrottle();
|
|
144
172
|
// Identity-aware observation/signalling for host recovery (issue #70). Callers must
|
|
145
173
|
// only signal after observeProcess returned "owned" for that exact identity.
|
|
146
|
-
|
|
174
|
+
// The default assembles the observation snapshot (issue #238 D4) and hands the
|
|
175
|
+
// judgment to the pure `processIdentityState`.
|
|
176
|
+
// Injected observers are also called when the role has no identity (the default
|
|
177
|
+
// handles that and falls through to the probe path), so an injection must not
|
|
178
|
+
// assume `identity.pid` is present.
|
|
179
|
+
const observeProcessImpl = opts.observeProcess ?? observeProcessIdentity;
|
|
147
180
|
const signalOwnedProcessImpl = opts.signalOwnedProcess ?? defaultSignalOwnedProcess;
|
|
181
|
+
// Process liveness and cross-platform start-token reads (issue #238). Both are
|
|
182
|
+
// injectable so token-path judgment is unit-testable without real processes.
|
|
183
|
+
const isAliveImpl = opts.isAlive ?? isAlive;
|
|
184
|
+
const readStartTokenImpl = opts.readStartToken ?? readProcessStartToken;
|
|
185
|
+
// Corroborating process identity probe for platforms without a start token
|
|
186
|
+
// (issue #217). Callers inject it in tests; the default reads platform-
|
|
187
|
+
// specific creation time + command line for one pid.
|
|
188
|
+
const probeProcessIdentityImpl = opts.probeProcessIdentity ?? readProcessIdentityProbe;
|
|
148
189
|
// Attach-resolver dependencies (issue #70 Task 12): a real socket probe and an
|
|
149
190
|
// awaitable sleep. The resolver runs on the UI thread, so its waits MUST go
|
|
150
191
|
// through sleepFn (never a blocking acquire / Atomics.wait).
|
|
@@ -154,6 +195,17 @@ export function createService(opts) {
|
|
|
154
195
|
// at validation time (never cached at startup) and wrapped defensively by the
|
|
155
196
|
// caller; undefined/absent skips validation entirely.
|
|
156
197
|
const availableModelsImpl = opts.availableModels ?? null;
|
|
198
|
+
// Background-run protection (issue #230): the scan/probe pair and the workflow
|
|
199
|
+
// home are injectable for tests; the env guard flag is read at call time.
|
|
200
|
+
const backgroundRunsImpl = opts.backgroundRuns ?? { scanBackgroundRuns, probeBackgroundRun };
|
|
201
|
+
const workflowHomeImpl = opts.workflowHome ?? resolveWorkflowHome();
|
|
202
|
+
// Notice memo (issue #230): remember (viewId, host.endedAt) after a successful
|
|
203
|
+
// probe, except while it still reports any `running` run inside the flip grace
|
|
204
|
+
// window — the engine's last `paused` write can land after finalization, so
|
|
205
|
+
// that window stays un-memoized and re-probes next tick to catch the flip
|
|
206
|
+
// even when an older `paused` run coexists with the running one. `!probe.ok`
|
|
207
|
+
// stays un-memoized to retry transient read failures.
|
|
208
|
+
const noticeProbeMemo = new Set();
|
|
157
209
|
// In-flight attach resolutions, keyed by viewId: concurrent resolver calls for
|
|
158
210
|
// the same view share one promise (issue #70 Task 12).
|
|
159
211
|
const inflightAttachResolvers = new Map();
|
|
@@ -773,6 +825,7 @@ export function createService(opts) {
|
|
|
773
825
|
if (result.reason === "coordinator_disabled") archiveStateDirect(row);
|
|
774
826
|
}
|
|
775
827
|
foregroundPreviewCache.forget(viewId);
|
|
828
|
+
foregroundProjectionCache.forget(viewId);
|
|
776
829
|
row.meta.archived = true;
|
|
777
830
|
writeMeta(root, row.meta);
|
|
778
831
|
return { ok: true };
|
|
@@ -829,6 +882,8 @@ export function createService(opts) {
|
|
|
829
882
|
processState: s.processState,
|
|
830
883
|
summary: s.summary,
|
|
831
884
|
lastActivityAt: s.lastActivityAt,
|
|
885
|
+
// Issue #225: freshness signal for the projection cache. Absent on legacy rows.
|
|
886
|
+
updatedAt: typeof s.updatedAt === "number" ? s.updatedAt : 0,
|
|
832
887
|
currentTool: s.latestTool ? { name: s.latestTool.name, path: s.latestTool.path, summary: s.summary } : null,
|
|
833
888
|
latestAssistantPreview: s.latestAssistantPreview,
|
|
834
889
|
question: s.question,
|
|
@@ -852,7 +907,11 @@ export function createService(opts) {
|
|
|
852
907
|
* @returns {Promise<void>}
|
|
853
908
|
*/
|
|
854
909
|
async function writeForegroundState(row, status, opts = {}) {
|
|
855
|
-
|
|
910
|
+
// Issue #225: a strictly increasing stamp lets the next disk rebuild tell a stale
|
|
911
|
+
// snapshot from this write, even when both land in the same millisecond.
|
|
912
|
+
const stamp = foregroundProjectionCache.nextStamp(row.meta.id);
|
|
913
|
+
const projected = projectViewState(status, stamp, readState(root, row.meta.id) ?? row.state ?? null);
|
|
914
|
+
foregroundProjectionCache.remember(row.meta.id, status, stamp);
|
|
856
915
|
// Foreground turns are driven by the interactive Pi process, not a detached
|
|
857
916
|
// runner, so keep currentRunId null. This prevents reconcile()/stop() from
|
|
858
917
|
// treating a foreground turn as a managed background runner pid. (The
|
|
@@ -896,14 +955,42 @@ export function createService(opts) {
|
|
|
896
955
|
const ttlMs = envInt("AGENT_BOARD_WARM_HOST_TTL_MS", 10 * 60 * 1000, 0, 24 * 60 * 60 * 1000, "AGENT_VIEW_WARM_HOST_TTL_MS");
|
|
897
956
|
if (maxWarm === 0 && ttlMs === 0) return;
|
|
898
957
|
const graceMs = envInt("AGENT_BOARD_WARM_HOST_GRACE_MS", 30 * 1000, 0, 24 * 60 * 60 * 1000, "AGENT_VIEW_WARM_HOST_GRACE_MS");
|
|
899
|
-
const
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
958
|
+
const keepViewId = pruneOpts.keepViewId ?? null;
|
|
959
|
+
const now = Date.now();
|
|
960
|
+
const rows = listRows(root);
|
|
961
|
+
const guardDisabled = process.env.AGENT_BOARD_NO_BACKGROUND_RUN_GUARD === "1";
|
|
962
|
+
|
|
963
|
+
// Phase 1 (dry): select without background-run protection. No candidates
|
|
964
|
+
// means no IO at all, preserving today's fast path for a full warm pool.
|
|
965
|
+
const dry = selectIdleHostsToEvict(rows, { now, maxWarm, ttlMs, graceMs, keepViewId });
|
|
966
|
+
const candidates = [...dry.ttlEvicted, ...dry.excessEvicted];
|
|
967
|
+
if (candidates.length === 0) return;
|
|
968
|
+
|
|
969
|
+
// One scan for the whole pass; the protection predicate stays pure
|
|
970
|
+
// in-memory (spec D5). minMtimeMs prefilters to heads that could belong
|
|
971
|
+
// to a live candidate host (spec D4); a candidate without startedAt
|
|
972
|
+
// falls back to 0, which disables the prefilter.
|
|
973
|
+
let scan = { ok: true, heads: [], error: null };
|
|
974
|
+
if (!guardDisabled) {
|
|
975
|
+
const candidateStartedAts = candidates.map((viewId) => rows.find((r) => r.meta.id === viewId)?.host?.startedAt ?? null);
|
|
976
|
+
const minStartedAt = candidateStartedAts.some((v) => v == null) ? 0 : Math.min(...candidateStartedAts);
|
|
977
|
+
scan = backgroundRunsImpl.scanBackgroundRuns({
|
|
978
|
+
workflowHome: workflowHomeImpl,
|
|
979
|
+
minMtimeMs: minStartedAt - CLOCK_EPSILON_MS,
|
|
980
|
+
});
|
|
981
|
+
}
|
|
982
|
+
const isProtected = (row) => {
|
|
983
|
+
if (guardDisabled) return false;
|
|
984
|
+
return classifyRunsForRow(scan.heads, {
|
|
985
|
+
sessionFile: row.meta.sessionFile,
|
|
986
|
+
hostStartedAt: row.host?.startedAt,
|
|
987
|
+
}).state === "protecting";
|
|
988
|
+
};
|
|
989
|
+
|
|
990
|
+
// Phase 2: re-select with the protection predicate so both eviction
|
|
991
|
+
// branches (TTL and maxWarm) exempt hosts running a background workflow.
|
|
992
|
+
const selected = selectIdleHostsToEvict(rows, { now, maxWarm, ttlMs, graceMs, keepViewId, isProtected });
|
|
993
|
+
for (const viewId of [...selected.ttlEvicted, ...selected.excessEvicted]) {
|
|
907
994
|
// Re-verify against fresh state before terminating: the selection ran
|
|
908
995
|
// on a listRows snapshot, and the host may have been dispatched (busy)
|
|
909
996
|
// or attached (attachedClients > 0) since. Never kill a busy/attached
|
|
@@ -913,6 +1000,42 @@ export function createService(opts) {
|
|
|
913
1000
|
if (isAgentBusy(row)) continue;
|
|
914
1001
|
if ((row.host?.attachedClients ?? 0) !== 0) continue;
|
|
915
1002
|
if (graceMs > 0 && row.host?.startedAt != null && Date.now() - row.host.startedAt < graceMs) continue;
|
|
1003
|
+
if (isProtected(row)) continue;
|
|
1004
|
+
|
|
1005
|
+
if (guardDisabled) {
|
|
1006
|
+
stopHostRow(row, "warm_prune");
|
|
1007
|
+
continue;
|
|
1008
|
+
}
|
|
1009
|
+
// Fresh protection probe (A9): a run started between the snapshot and
|
|
1010
|
+
// this stop decision still blocks the eviction. Fail-open: a probe
|
|
1011
|
+
// error logs a deduped warning and proceeds without protection (D6).
|
|
1012
|
+
const fresh = backgroundRunsImpl.probeBackgroundRun({
|
|
1013
|
+
sessionFile: row.meta.sessionFile ?? null,
|
|
1014
|
+
hostStartedAt: row.host?.startedAt ?? null,
|
|
1015
|
+
workflowHome: workflowHomeImpl,
|
|
1016
|
+
});
|
|
1017
|
+
if (fresh.running) {
|
|
1018
|
+
const runId = fresh.running.runId;
|
|
1019
|
+
appendDiagnosticOnce(root, viewId, {
|
|
1020
|
+
source: "service",
|
|
1021
|
+
level: "warn",
|
|
1022
|
+
code: "warm_prune_during_background_run",
|
|
1023
|
+
message: `Skipped warm-host eviction: background workflow ${runId} started after selection`,
|
|
1024
|
+
details: { runId, hostStartedAt: row.host?.startedAt ?? null },
|
|
1025
|
+
}, { match: ["runId"] });
|
|
1026
|
+
continue;
|
|
1027
|
+
}
|
|
1028
|
+
if (!fresh.ok) {
|
|
1029
|
+
appendDiagnosticOnce(root, viewId, {
|
|
1030
|
+
source: "service",
|
|
1031
|
+
level: "warn",
|
|
1032
|
+
code: "warm_prune_probe_failed",
|
|
1033
|
+
message: "Could not read the workflow run store; warm-host eviction proceeded without background-run protection",
|
|
1034
|
+
details: { error: String(fresh.error ?? "unknown") },
|
|
1035
|
+
}, { match: ["error"] });
|
|
1036
|
+
stopHostRow(row, "warm_prune");
|
|
1037
|
+
continue;
|
|
1038
|
+
}
|
|
916
1039
|
stopHostRow(row, "warm_prune");
|
|
917
1040
|
}
|
|
918
1041
|
}
|
|
@@ -947,13 +1070,127 @@ export function createService(opts) {
|
|
|
947
1070
|
return { ok: true, requested: wasRequested };
|
|
948
1071
|
}
|
|
949
1072
|
|
|
950
|
-
/**
|
|
951
|
-
*
|
|
952
|
-
*
|
|
953
|
-
|
|
1073
|
+
/**
|
|
1074
|
+
* Assemble one host-role observation snapshot and let the pure state machine
|
|
1075
|
+
* judge it (issue #238 D4). The recorded start token is only read when the
|
|
1076
|
+
* record carries one, so legacy records (token `null`, or platforms without a
|
|
1077
|
+
* token) keep the zero-token-read path. `tokenMemo` deduplicates the (async,
|
|
1078
|
+
* expensive on win32) token read per pid, so one recovery pass reads each
|
|
1079
|
+
* process at most once.
|
|
1080
|
+
* @param {{pid:number,startToken:string|null}|null} identity recorded identity
|
|
1081
|
+
* @param {{spawnedAt:number|null, pid:number|null, tokenMemo:Map<number, Promise<string|null>>}} observation
|
|
1082
|
+
* @returns {Promise<"not_started"|"dead"|"owned"|"foreign"|"unknown">}
|
|
1083
|
+
*/
|
|
1084
|
+
async function observeProcessIdentity(identity, { spawnedAt, pid, tokenMemo }) {
|
|
1085
|
+
if (identity == null && spawnedAt == null) return "not_started";
|
|
1086
|
+
if (pid == null) return "unknown";
|
|
1087
|
+
const alive = isAliveImpl(pid);
|
|
1088
|
+
const observed = { alive, startToken: null };
|
|
1089
|
+
if (alive && identity != null && identity.startToken != null) {
|
|
1090
|
+
if (!tokenMemo.has(pid)) tokenMemo.set(pid, readStartTokenImpl(pid));
|
|
1091
|
+
observed.startToken = await tokenMemo.get(pid);
|
|
1092
|
+
}
|
|
1093
|
+
return processIdentityState(identity, observed, spawnedAt);
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
/**
|
|
1097
|
+
* Observe one host role: a recorded identity goes through identity-aware
|
|
1098
|
+
* observation (token comparison first); a missing identity means `not_started`
|
|
1099
|
+
* (never spawned). An `unknown` observation (no stable token, or the token
|
|
1100
|
+
* path unavailable) is then corroborated by the process identity probe before
|
|
1101
|
+
* recovery decides (issue #217). The caller's `memo` deduplicates probes per
|
|
1102
|
+
* pid and `tokenMemo` deduplicates token reads per pid so one recovery pass
|
|
1103
|
+
* never observes the same process twice.
|
|
1104
|
+
* @param {any} host host record holding this role's identity/pid/spawn fields
|
|
1105
|
+
* @param {"runner"|"child"} role which host process to observe
|
|
1106
|
+
* @param {{ sessionFile: string|null, memo: Map<number, any>, tokenMemo: Map<number, Promise<string|null>> }} opts
|
|
1107
|
+
* session file used as the child command fragment, and the per-call
|
|
1108
|
+
* probe/token memos (kept separate: probe values are objects, token values
|
|
1109
|
+
* are strings or null)
|
|
1110
|
+
*/
|
|
1111
|
+
async function observeHostRole(host, role, { sessionFile, memo, tokenMemo }) {
|
|
1112
|
+
const identity = host?.[`${role}Identity`] ?? null;
|
|
1113
|
+
const spawnedAt = host?.[`${role}SpawnedAt`] ?? null;
|
|
1114
|
+
if (identity == null && spawnedAt == null) return "not_started";
|
|
1115
|
+
const pid = identity?.pid ?? host?.[`${role}Pid`] ?? null;
|
|
1116
|
+
if (pid == null) return "unknown";
|
|
1117
|
+
const observation = await observeProcessImpl(identity, { spawnedAt, pid, tokenMemo });
|
|
1118
|
+
if (observation !== "unknown") return observation;
|
|
1119
|
+
if (!memo.has(pid)) memo.set(pid, await probeProcessIdentityImpl(pid));
|
|
1120
|
+
return classifyUnverifiableProcess({
|
|
1121
|
+
spawnedAt,
|
|
1122
|
+
probe: memo.get(pid),
|
|
1123
|
+
expectedCommandFragment: role === "child" ? sessionFile : host?.configPath ?? null,
|
|
1124
|
+
toleranceMs: resolveIdentityCreationToleranceMs(),
|
|
1125
|
+
});
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
/** Re-validate an "owned" identity immediately before signalling: a pid reused
|
|
1129
|
+
* mid-recovery must never receive an escalation signal (#240 CR). A recorded
|
|
1130
|
+
* start token is re-read live, bypassing the observation memo — on win32 the
|
|
1131
|
+
* observed token may be ~400 ms old, leaving a pid-reuse window — and any
|
|
1132
|
+
* mismatch or unreadable token refuses the signal, which leaves the recovery
|
|
1133
|
+
* pending (safe: never foreign, never signalled). Records without a token keep
|
|
1134
|
+
* the probe-derived re-validation. */
|
|
1135
|
+
async function revalidateProbeOwned(host, role, sessionFile, memo) {
|
|
954
1136
|
const identity = host?.[`${role}Identity`] ?? null;
|
|
955
|
-
|
|
956
|
-
|
|
1137
|
+
const pid = identity?.pid ?? host?.[`${role}Pid`] ?? null;
|
|
1138
|
+
if (pid == null) return false;
|
|
1139
|
+
if (identity?.startToken != null) {
|
|
1140
|
+
const token = await readStartTokenImpl(pid);
|
|
1141
|
+
return token != null && token === identity.startToken;
|
|
1142
|
+
}
|
|
1143
|
+
const probe = await probeProcessIdentityImpl(pid);
|
|
1144
|
+
memo.set(pid, probe);
|
|
1145
|
+
return classifyUnverifiableProcess({
|
|
1146
|
+
spawnedAt: host?.[`${role}SpawnedAt`] ?? null,
|
|
1147
|
+
probe,
|
|
1148
|
+
expectedCommandFragment: role === "child" ? sessionFile : host?.configPath ?? null,
|
|
1149
|
+
toleranceMs: resolveIdentityCreationToleranceMs(),
|
|
1150
|
+
}) === "owned";
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
/** A host role observation is "ended" when it is provably not running:
|
|
1154
|
+
* never-spawned, confirmed dead, or a reused PID (foreign). */
|
|
1155
|
+
const hostRoleEnded = (o) => o === "not_started" || o === "dead" || o === "foreign";
|
|
1156
|
+
|
|
1157
|
+
/**
|
|
1158
|
+
* Record the host roles that stranded a recovery (issue #217 D4).
|
|
1159
|
+
* Only roles whose identity is unverifiable (`"unknown"`) are recorded: an
|
|
1160
|
+
* `"owned"` role is alive and verified, so flagging it as unverifiable would
|
|
1161
|
+
* contradict the observation that stranded recovery. Only the producing side
|
|
1162
|
+
* writes: one event per instance+role, so repeated attach clicks on the same
|
|
1163
|
+
* stranded host never flood the diagnostics tail.
|
|
1164
|
+
* @param {string} viewId
|
|
1165
|
+
* @param {any} host host record the observations came from
|
|
1166
|
+
* @param {{ runner: string, child?: string|null }} observations `null` = not observed
|
|
1167
|
+
* @param {Map<number, any>} memo probe memo of the pass that produced `observations`
|
|
1168
|
+
* @param {"recover"|"attach"} path which call site stranded
|
|
1169
|
+
*/
|
|
1170
|
+
function noteRecoveryPending(viewId, host, observations, memo, path) {
|
|
1171
|
+
for (const role of ["runner", "child"]) {
|
|
1172
|
+
const observation = observations[role];
|
|
1173
|
+
if (observation !== "unknown") continue;
|
|
1174
|
+
const pid = host?.[`${role}Identity`]?.pid ?? host?.[`${role}Pid`] ?? null;
|
|
1175
|
+
appendDiagnosticOnce(
|
|
1176
|
+
root,
|
|
1177
|
+
viewId,
|
|
1178
|
+
{
|
|
1179
|
+
source: "service",
|
|
1180
|
+
level: "warn",
|
|
1181
|
+
code: "host_recovery_pending",
|
|
1182
|
+
message: "Host recovery is pending: process identity unverifiable",
|
|
1183
|
+
details: {
|
|
1184
|
+
instanceId: host?.instanceId ?? null,
|
|
1185
|
+
role,
|
|
1186
|
+
observation,
|
|
1187
|
+
probe: (pid == null ? null : memo.get(pid)) ? "available" : "unavailable",
|
|
1188
|
+
path,
|
|
1189
|
+
},
|
|
1190
|
+
},
|
|
1191
|
+
{ match: ["instanceId", "role"] },
|
|
1192
|
+
);
|
|
1193
|
+
}
|
|
957
1194
|
}
|
|
958
1195
|
|
|
959
1196
|
/**
|
|
@@ -965,14 +1202,16 @@ export function createService(opts) {
|
|
|
965
1202
|
* after runner and child are both confirmed ended.
|
|
966
1203
|
* @param {string} viewId
|
|
967
1204
|
* @param {string} expectedInstanceId
|
|
1205
|
+
* @param {string|null} [sessionFile] session whose file identifies the child
|
|
1206
|
+
* process; defaults to the row's meta session file
|
|
968
1207
|
* @returns {Promise<{ ok: boolean, recovered?: boolean, instanceId?: string, socketPath?: string|null, error?: string }>}
|
|
969
1208
|
*/
|
|
970
|
-
|
|
971
|
-
* never-spawned, confirmed dead, or a reused PID (foreign). */
|
|
972
|
-
const hostRoleEnded = (o) => o === "not_started" || o === "dead" || o === "foreign";
|
|
973
|
-
|
|
974
|
-
async function recoverHost(viewId, expectedInstanceId) {
|
|
1209
|
+
async function recoverHost(viewId, expectedInstanceId, sessionFile = loadRow(root, viewId)?.meta.sessionFile ?? null) {
|
|
975
1210
|
const ended = hostRoleEnded;
|
|
1211
|
+
const probeMemo = new Map();
|
|
1212
|
+
// Token reads are memoized separately from probes: probe values are objects,
|
|
1213
|
+
// token values are strings/null. One recovery pass reads each pid once.
|
|
1214
|
+
const tokenMemo = new Map();
|
|
976
1215
|
const instanceStillExpected = () => {
|
|
977
1216
|
const h = readHost(root, viewId);
|
|
978
1217
|
return h != null && h.instanceId === expectedInstanceId;
|
|
@@ -1003,31 +1242,42 @@ export function createService(opts) {
|
|
|
1003
1242
|
while (nowImpl() - startedAt < resolveHostRecoveryGraceMs()) {
|
|
1004
1243
|
const host = readHost(root, viewId);
|
|
1005
1244
|
if (!host || host.instanceId !== expectedInstanceId) return { ok: false, error: "already_recovered" };
|
|
1006
|
-
const runnerObservation = observeHostRole(host, "runner");
|
|
1007
|
-
const childObservation = observeHostRole(host, "child");
|
|
1245
|
+
const runnerObservation = await observeHostRole(host, "runner", { sessionFile, memo: probeMemo, tokenMemo });
|
|
1246
|
+
const childObservation = await observeHostRole(host, "child", { sessionFile, memo: probeMemo, tokenMemo });
|
|
1008
1247
|
if (ended(runnerObservation) && ended(childObservation)) break;
|
|
1009
1248
|
// Alive-but-unverifiable: never signal, never claim — stay pending.
|
|
1010
|
-
if (runnerObservation === "unknown" || childObservation === "unknown")
|
|
1249
|
+
if (runnerObservation === "unknown" || childObservation === "unknown") {
|
|
1250
|
+
noteRecoveryPending(viewId, host, { runner: runnerObservation, child: childObservation }, probeMemo, "recover");
|
|
1251
|
+
return { ok: false, error: "recovery_pending" };
|
|
1252
|
+
}
|
|
1011
1253
|
if (!instanceStillExpected()) return { ok: false, error: "already_recovered" };
|
|
1012
1254
|
const elapsed = nowImpl() - startedAt;
|
|
1013
1255
|
if (runnerObservation === "owned") {
|
|
1014
1256
|
if (!runnerTermSent) {
|
|
1015
|
-
|
|
1016
|
-
|
|
1257
|
+
if (await revalidateProbeOwned(host, "runner", sessionFile, probeMemo)) {
|
|
1258
|
+
signalOwnedProcessImpl(host.runnerIdentity, "SIGTERM");
|
|
1259
|
+
runnerTermSent = true;
|
|
1260
|
+
}
|
|
1017
1261
|
} else if (elapsed >= resolveHostRecoveryGraceMs() / 2 && !runnerKillSent) {
|
|
1018
|
-
|
|
1019
|
-
|
|
1262
|
+
if (await revalidateProbeOwned(host, "runner", sessionFile, probeMemo)) {
|
|
1263
|
+
signalOwnedProcessImpl(host.runnerIdentity, "SIGKILL");
|
|
1264
|
+
runnerKillSent = true;
|
|
1265
|
+
}
|
|
1020
1266
|
}
|
|
1021
1267
|
}
|
|
1022
1268
|
// The child is only escalated once its runner is confirmed gone.
|
|
1023
1269
|
if (childObservation === "owned" && runnerObservation !== "owned") {
|
|
1024
1270
|
if (!childTermSent) {
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1271
|
+
if (await revalidateProbeOwned(host, "child", sessionFile, probeMemo)) {
|
|
1272
|
+
signalOwnedProcessImpl(host.childIdentity, "SIGTERM");
|
|
1273
|
+
childTermSent = true;
|
|
1274
|
+
childTermAt = elapsed;
|
|
1275
|
+
}
|
|
1028
1276
|
} else if (elapsed - childTermAt >= 1_000 && !childKillSent) {
|
|
1029
|
-
|
|
1030
|
-
|
|
1277
|
+
if (await revalidateProbeOwned(host, "child", sessionFile, probeMemo)) {
|
|
1278
|
+
signalOwnedProcessImpl(host.childIdentity, "SIGKILL");
|
|
1279
|
+
childKillSent = true;
|
|
1280
|
+
}
|
|
1031
1281
|
}
|
|
1032
1282
|
}
|
|
1033
1283
|
await sleepFnImpl(resolveHostRecoveryPollMs());
|
|
@@ -1035,7 +1285,12 @@ export function createService(opts) {
|
|
|
1035
1285
|
// Grace exhausted or loop broke — verify both roles are confirmed ended before claiming.
|
|
1036
1286
|
const finalHost = readHost(root, viewId);
|
|
1037
1287
|
if (!finalHost || finalHost.instanceId !== expectedInstanceId) return { ok: false, error: "already_recovered" };
|
|
1038
|
-
|
|
1288
|
+
const finalRunnerObservation = await observeHostRole(finalHost, "runner", { sessionFile, memo: probeMemo, tokenMemo });
|
|
1289
|
+
// Decision order preserved: the child is observed only once the runner is ended,
|
|
1290
|
+
// and `null` means "not observed" so no diagnostic claims an unlooked-at role.
|
|
1291
|
+
const finalChildObservation = ended(finalRunnerObservation) ? await observeHostRole(finalHost, "child", { sessionFile, memo: probeMemo, tokenMemo }) : null;
|
|
1292
|
+
if (!ended(finalRunnerObservation) || !ended(finalChildObservation)) {
|
|
1293
|
+
noteRecoveryPending(viewId, finalHost, { runner: finalRunnerObservation, child: finalChildObservation }, probeMemo, "recover");
|
|
1039
1294
|
return { ok: false, error: "recovery_pending" };
|
|
1040
1295
|
}
|
|
1041
1296
|
|
|
@@ -1293,16 +1548,20 @@ export function createService(opts) {
|
|
|
1293
1548
|
if (host.state === "stopping") {
|
|
1294
1549
|
const staleStop = host.instanceId != null && nowImpl() - (host.stopRequestedAt ?? host.claimAt ?? 0) >= resolveHostRecoveryGraceMs();
|
|
1295
1550
|
if (staleStop && !recovered) {
|
|
1296
|
-
const
|
|
1297
|
-
|
|
1551
|
+
const probeMemo = new Map();
|
|
1552
|
+
// Fresh token memo per branch entry; never shared with probeMemo.
|
|
1553
|
+
const tokenMemo = new Map();
|
|
1554
|
+
const runnerObs = await observeHostRole(host, "runner", { sessionFile, memo: probeMemo, tokenMemo });
|
|
1555
|
+
const childObs = await observeHostRole(host, "child", { sessionFile, memo: probeMemo, tokenMemo });
|
|
1298
1556
|
if (runnerObs === "unknown" || childObs === "unknown") {
|
|
1299
1557
|
// Unverifiable processes on a stranded record — never force.
|
|
1558
|
+
noteRecoveryPending(viewId, host, { runner: runnerObs, child: childObs }, probeMemo, "attach");
|
|
1300
1559
|
return pending(sessionFile, "recovery_pending: host identity unverifiable");
|
|
1301
1560
|
}
|
|
1302
1561
|
if (hostRoleEnded(runnerObs) && hostRoleEnded(childObs)) {
|
|
1303
1562
|
recovered = true;
|
|
1304
1563
|
try {
|
|
1305
|
-
const rec = await recoverHost(viewId, /** @type {string} */ (host.instanceId));
|
|
1564
|
+
const rec = await recoverHost(viewId, /** @type {string} */ (host.instanceId), sessionFile);
|
|
1306
1565
|
if (!rec.ok && rec.error === "recovery_pending") {
|
|
1307
1566
|
return pending(sessionFile, "recovery_pending: host identity unverifiable");
|
|
1308
1567
|
}
|
|
@@ -1370,7 +1629,7 @@ export function createService(opts) {
|
|
|
1370
1629
|
if (!recovered) {
|
|
1371
1630
|
recovered = true;
|
|
1372
1631
|
try {
|
|
1373
|
-
const rec = await recoverHost(viewId, /** @type {string} */ (host.instanceId));
|
|
1632
|
+
const rec = await recoverHost(viewId, /** @type {string} */ (host.instanceId), sessionFile);
|
|
1374
1633
|
if (!rec.ok && rec.error === "recovery_pending") {
|
|
1375
1634
|
return pending(sessionFile, "recovery_pending: host identity unverifiable");
|
|
1376
1635
|
}
|
|
@@ -1538,6 +1797,8 @@ export function createService(opts) {
|
|
|
1538
1797
|
// can lag the freshest known preview/activity. Restore read-your-writes
|
|
1539
1798
|
// before any event branch touches the status.
|
|
1540
1799
|
foregroundPreviewCache.backfill(row.meta.id, status);
|
|
1800
|
+
// Issue #225: correct a stale disk rebuild before the new event is reduced.
|
|
1801
|
+
foregroundProjectionCache.adopt(row.meta.id, status);
|
|
1541
1802
|
let evidence = readEvidence(root, row.meta.id);
|
|
1542
1803
|
if (!evidence.viewId) evidence = emptyEvidenceSnapshot({ viewId: row.meta.id, source: "hosted" });
|
|
1543
1804
|
try {
|
|
@@ -1633,6 +1894,84 @@ export function createService(opts) {
|
|
|
1633
1894
|
return false;
|
|
1634
1895
|
}
|
|
1635
1896
|
|
|
1897
|
+
/**
|
|
1898
|
+
* Reconcile pre-pass (issue #230): when a warm host has died (state
|
|
1899
|
+
* `exited`/`failed` and no longer alive) while its session owns a paused
|
|
1900
|
+
* background workflow run, the row otherwise stays silent. Announce the
|
|
1901
|
+
* interruption by patching `summary` (through patch_fields so the manual
|
|
1902
|
+
* fence still governs) and record one diagnostic per run.
|
|
1903
|
+
*
|
|
1904
|
+
* The memo key is `(viewId, host.endedAt)`. A successful probe is memoized
|
|
1905
|
+
* except for the grace window right after the host ended: the workflow
|
|
1906
|
+
* engine writes the `paused` head while settling in-flight step children
|
|
1907
|
+
* during SIGTERM shutdown, and that write can land after the board finalizes
|
|
1908
|
+
* `host.state = exited` (finalization waits for the runner and child pids to
|
|
1909
|
+
* die, not for the engine's last write). A probe in that window reports
|
|
1910
|
+
* `running`, so any still-`running` result inside `NOTICE_FLIP_GRACE_MS`
|
|
1911
|
+
* stays un-memoized and re-probes next tick to catch the flip — including
|
|
1912
|
+
* when it coexists with an older `paused` run, which stays idempotent to
|
|
1913
|
+
* announce. Re-probing stops after `NOTICE_FLIP_GRACE_MS`; a `running` record
|
|
1914
|
+
* that survives the grace window is treated as a hard-kill artifact with no
|
|
1915
|
+
* notice (issue #230 follow-up). `!probe.ok` stays un-memoized so a transient
|
|
1916
|
+
* read failure retries next tick. Notice fires only for `paused`.
|
|
1917
|
+
*
|
|
1918
|
+
* An already-announced row still costs one probe per reconcile so a later
|
|
1919
|
+
* host incarnation can surface a new interrupted run; the summary write is
|
|
1920
|
+
* skipped only when it already names this same runId, and diagnostics stay
|
|
1921
|
+
* deduped per runId.
|
|
1922
|
+
*
|
|
1923
|
+
* This pre-pass deliberately sits outside the looksActive-gated loop below:
|
|
1924
|
+
* the target rows are already at `processState: "exited"`.
|
|
1925
|
+
* @param {number} now
|
|
1926
|
+
*/
|
|
1927
|
+
async function noticeInterruptedBackgroundRuns(now) {
|
|
1928
|
+
for (const row of listRows(root)) {
|
|
1929
|
+
const host = row.host;
|
|
1930
|
+
if (!host || (host.state !== "exited" && host.state !== "failed") || row.hostAlive) continue;
|
|
1931
|
+
const viewId = row.meta.id;
|
|
1932
|
+
const key = `${viewId}:${host.endedAt ?? 0}`;
|
|
1933
|
+
if (noticeProbeMemo.has(key)) continue;
|
|
1934
|
+
const probe = backgroundRunsImpl.probeBackgroundRun({
|
|
1935
|
+
sessionFile: row.meta.sessionFile ?? null,
|
|
1936
|
+
hostStartedAt: host.startedAt ?? null,
|
|
1937
|
+
workflowHome: workflowHomeImpl,
|
|
1938
|
+
});
|
|
1939
|
+
if (!probe.ok) continue; // incomplete scan: retry next tick, memo not written
|
|
1940
|
+
const runningWithinGrace = probe.running != null && now - (host.endedAt ?? 0) < NOTICE_FLIP_GRACE_MS;
|
|
1941
|
+
if (!runningWithinGrace) {
|
|
1942
|
+
noticeProbeMemo.add(key);
|
|
1943
|
+
}
|
|
1944
|
+
if (!probe.paused) continue;
|
|
1945
|
+
const runId = probe.paused.runId;
|
|
1946
|
+
const summary = `Background workflow ${runId} was interrupted — resume it from this session`;
|
|
1947
|
+
const alreadyAnnounced = typeof row.state?.summary === "string" && row.state.summary.startsWith(`Background workflow ${runId} `);
|
|
1948
|
+
if (!alreadyAnnounced) {
|
|
1949
|
+
const result = await sendLifecycleCommand({
|
|
1950
|
+
type: "state_command",
|
|
1951
|
+
viewId,
|
|
1952
|
+
runId: null,
|
|
1953
|
+
source: "service",
|
|
1954
|
+
kind: "patch_fields",
|
|
1955
|
+
expectedRevision: null,
|
|
1956
|
+
payload: { state: { summary } },
|
|
1957
|
+
}, viewId);
|
|
1958
|
+
if (result.reason === "coordinator_disabled") {
|
|
1959
|
+
const fresh = readState(root, viewId) ?? blankState(viewId);
|
|
1960
|
+
fresh.summary = summary;
|
|
1961
|
+
fresh.updatedAt = now;
|
|
1962
|
+
writeState(root, fresh);
|
|
1963
|
+
}
|
|
1964
|
+
}
|
|
1965
|
+
appendDiagnosticOnce(root, viewId, {
|
|
1966
|
+
source: "service",
|
|
1967
|
+
level: "warn",
|
|
1968
|
+
code: "background_run_interrupted",
|
|
1969
|
+
message: `Background workflow ${runId} was interrupted when its host died`,
|
|
1970
|
+
details: { runId, hostState: host.state, exitCode: host.exitCode ?? null },
|
|
1971
|
+
}, { match: ["runId"] });
|
|
1972
|
+
}
|
|
1973
|
+
}
|
|
1974
|
+
|
|
1636
1975
|
return {
|
|
1637
1976
|
root,
|
|
1638
1977
|
/**
|
|
@@ -2129,6 +2468,7 @@ export function createService(opts) {
|
|
|
2129
2468
|
if (row.host?.instanceId) stopHostRow(row, "archive");
|
|
2130
2469
|
else if (row.hostAlive) sendHostMessage(row, { type: "terminate" });
|
|
2131
2470
|
foregroundPreviewCache.forget(row.meta.id);
|
|
2471
|
+
foregroundProjectionCache.forget(row.meta.id);
|
|
2132
2472
|
row.meta.archived = true;
|
|
2133
2473
|
writeMeta(root, row.meta);
|
|
2134
2474
|
archived += 1;
|
|
@@ -2144,6 +2484,7 @@ export function createService(opts) {
|
|
|
2144
2484
|
*/
|
|
2145
2485
|
async reconcile() {
|
|
2146
2486
|
const now = Date.now();
|
|
2487
|
+
await noticeInterruptedBackgroundRuns(now);
|
|
2147
2488
|
let fixed = 0;
|
|
2148
2489
|
for (const row of listRows(root)) {
|
|
2149
2490
|
const s = row.state;
|
|
@@ -2415,26 +2756,9 @@ function compactSummary(text) {
|
|
|
2415
2756
|
return truncate(first.length >= 12 ? first : cleaned, 80);
|
|
2416
2757
|
}
|
|
2417
2758
|
|
|
2418
|
-
/** POSIX process start token — /proc/<pid>/stat field 22 (starttime). Mirrors the
|
|
2419
|
-
* runner's captureStartToken (issue #70) so both sides publish comparable
|
|
2420
|
-
* identities; null on failure or non-Linux platforms. Task 11 may promote this
|
|
2421
|
-
* to a shared module when identity-aware observation lands. */
|
|
2422
|
-
function readProcStartToken(pid) {
|
|
2423
|
-
if (process.platform !== "linux" || !pid) return null;
|
|
2424
|
-
try {
|
|
2425
|
-
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
2426
|
-
// comm (field 2) may contain spaces and parens — fields resume AFTER the
|
|
2427
|
-
// last ')'. fields[0] is state (field 3) → starttime (field 22) is [19].
|
|
2428
|
-
const afterComm = stat.slice(stat.lastIndexOf(")") + 1).trimStart();
|
|
2429
|
-
return afterComm.split(/\s+/)[19] ?? null;
|
|
2430
|
-
} catch {
|
|
2431
|
-
return null;
|
|
2432
|
-
}
|
|
2433
|
-
}
|
|
2434
|
-
|
|
2435
2759
|
/** Launch-time identity this service process stamps on leases and claims. */
|
|
2436
2760
|
function serviceIdentity() {
|
|
2437
|
-
return { pid: process.pid, startToken:
|
|
2761
|
+
return { pid: process.pid, startToken: captureStartToken(process.pid) };
|
|
2438
2762
|
}
|
|
2439
2763
|
|
|
2440
2764
|
/**
|
|
@@ -2493,18 +2817,6 @@ function conservativeObservation(pid) {
|
|
|
2493
2817
|
return isAlive(pid) ? "unknown" : "dead";
|
|
2494
2818
|
}
|
|
2495
2819
|
|
|
2496
|
-
/** Identity-aware process observation (issue #70): a live pid whose /proc start
|
|
2497
|
-
* token matches the recorded identity is `owned` (safe to signal); a mismatch is
|
|
2498
|
-
* `foreign` (pid reused — the original is gone); alive-but-unverifiable is
|
|
2499
|
-
* `unknown` (recovery must stay pending, never signal). */
|
|
2500
|
-
function defaultObserveProcess(identity) {
|
|
2501
|
-
if (!identity || identity.pid == null) return "unknown";
|
|
2502
|
-
if (!isAlive(identity.pid)) return "dead";
|
|
2503
|
-
const token = readProcStartToken(identity.pid);
|
|
2504
|
-
if (identity.startToken == null || token == null) return "unknown";
|
|
2505
|
-
return token === identity.startToken ? "owned" : "foreign";
|
|
2506
|
-
}
|
|
2507
|
-
|
|
2508
2820
|
/** Signal an identity previously observed as "owned". ESRCH is tolerated (the
|
|
2509
2821
|
* process may exit between observation and signal); anything else rethrows. */
|
|
2510
2822
|
function defaultSignalOwnedProcess(identity, signal) {
|