pi-better-background-tasks 0.20.3 → 0.21.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/runtime-client/artifacts/darwin-arm64.gz +0 -0
- package/runtime-client/artifacts/darwin-arm64.json +1 -1
- package/runtime-client/artifacts/darwin-x64.gz +0 -0
- package/runtime-client/artifacts/darwin-x64.json +1 -1
- package/runtime-client/artifacts/linux-arm64.gz +0 -0
- package/runtime-client/artifacts/linux-arm64.json +1 -1
- package/runtime-client/artifacts/linux-x64.gz +0 -0
- package/runtime-client/artifacts/linux-x64.json +1 -1
- package/src/ci-observation.ts +118 -0
- package/src/managed-client.ts +6 -2
- package/src/managed-frontend.ts +36 -6
- package/src/observed-waits.ts +33 -6
- package/src/shared-operation-coordinator/assignment-observation.mjs +1 -0
- package/src/shared-operation-coordinator/src/assignment-outcomes.ts +0 -2
- package/src/shared-operation-coordinator/src/discovery.ts +7 -4
- package/src/shared-operation-coordinator/src/operations.ts +5 -11
- package/src/shared-operation-coordinator/src/schema.ts +54 -1
- package/src/shared-operation-coordinator/src/store.ts +5 -5
- package/src/supervisor/generated/identity.mjs +5 -0
- package/src/supervisor/identity.ts +6 -0
- package/src/supervisor/supervisor.ts +3 -4
package/package.json
CHANGED
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"build":{"format":1,"sourceDigest":"
|
|
1
|
+
{"build":{"format":1,"sourceDigest":"50cb9496e6037883197cc2f748546323d1ca69e95f8a5a9677a4bb309687e733","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.1","contentId":"0fd591f51ac98c9d1d4f9611a46d08da13c86851382d2109a909fc004b567943"},"sha256":"6a47351f9c0eec3516ba566c7a885ff3cc762bba05e33f5305db7a56fabf1982"}
|
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"build":{"format":1,"sourceDigest":"
|
|
1
|
+
{"build":{"format":1,"sourceDigest":"50cb9496e6037883197cc2f748546323d1ca69e95f8a5a9677a4bb309687e733","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"darwin-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.1","contentId":"a12968284314d7c54f2656ec7d1b1289e85535aea95b0203d92b5c0a2687347f"},"sha256":"4315671ab6da4d3ab3398143388c6ea5041e496ea9a757ee08021bf29e9f725c"}
|
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"build":{"format":1,"sourceDigest":"
|
|
1
|
+
{"build":{"format":1,"sourceDigest":"50cb9496e6037883197cc2f748546323d1ca69e95f8a5a9677a4bb309687e733","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-arm64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.1","contentId":"9f474bd45ac5315217d6f20898e6b845c707172cc6a849e96c8e38bdc69803f2"},"sha256":"40ddd825229477fc75a2f8fdb6153d8a064b32c825e88897b74545b80e9d05a8"}
|
|
Binary file
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"build":{"format":1,"sourceDigest":"
|
|
1
|
+
{"build":{"format":1,"sourceDigest":"50cb9496e6037883197cc2f748546323d1ca69e95f8a5a9677a4bb309687e733","piSdkVersion":"1.4.0","nodeVersion":"24.14.1","platform":"linux-x64","dependencyLockDigest":"300f19071b0e3f4e68220f42d7976b92dc6a629dd2719325fb7fad41781164c8","protocolVersion":1,"serverVersion":"0.8.1","contentId":"3623fb69d87cbdcf92f946d5b34d89265136f9619a0f713d9aba52883ec882a5"},"sha256":"9729edc6beff7b4b5c547811d1a5142d765a04524538aef519faabc3330d9641"}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { readHarnessSetting, type HarnessSettingsSeams } from './shared-harness-settings.js';
|
|
2
|
+
import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
3
|
+
|
|
4
|
+
export const supervisorConsultTool = 'supervisor_consult';
|
|
5
|
+
export const supervisorRecoveryType = 'background-ci-observation-recovery';
|
|
6
|
+
|
|
7
|
+
/** Ask the existing Goal gate, including workflow holds, before waking an idle owner. */
|
|
8
|
+
export function requestCiRecoveryWake(pi: ExtensionAPI, ctx: ExtensionContext, branchId: string, validUntil: number): Promise<() => boolean> {
|
|
9
|
+
let goalId: string | null = null;
|
|
10
|
+
for (const entry of ctx.sessionManager.getBranch()) {
|
|
11
|
+
if (entry.type !== 'custom' || !['pi-better-goal', 'pi-codex-goal'].includes(entry.customType)) continue;
|
|
12
|
+
const data = entry.data as { kind?: string; goal?: { goalId?: string } } | undefined;
|
|
13
|
+
if (data?.kind === 'clear') goalId = null;
|
|
14
|
+
if (data?.kind === 'set' && typeof data.goal?.goalId === 'string') goalId = data.goal.goalId;
|
|
15
|
+
}
|
|
16
|
+
return new Promise(resolve => {
|
|
17
|
+
let timer: ReturnType<typeof setTimeout>;
|
|
18
|
+
let settled = false;
|
|
19
|
+
const finish = (current: () => boolean) => {
|
|
20
|
+
if (settled) return;
|
|
21
|
+
settled = true;
|
|
22
|
+
clearTimeout(timer);
|
|
23
|
+
resolve(current);
|
|
24
|
+
};
|
|
25
|
+
timer = setTimeout(() => finish(() => goalId === null), 50);
|
|
26
|
+
try {
|
|
27
|
+
pi.events.emit('pi-better-goal:operation-resume-admission', {
|
|
28
|
+
version: 1,
|
|
29
|
+
owner: { sessionId: ctx.sessionManager.getSessionId(), workspace: ctx.cwd, branchId, goalId },
|
|
30
|
+
pending() {
|
|
31
|
+
if (settled) return;
|
|
32
|
+
clearTimeout(timer);
|
|
33
|
+
timer = setTimeout(() => finish(() => false), Math.max(1, validUntil - Date.now()));
|
|
34
|
+
},
|
|
35
|
+
reply(gate: { allowed: boolean; isCurrent?: () => boolean }) {
|
|
36
|
+
finish(() => gate?.allowed === true && gate.isCurrent?.() !== false);
|
|
37
|
+
},
|
|
38
|
+
});
|
|
39
|
+
} catch { finish(() => false); }
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function ciObservationRevision(seams?: HarnessSettingsSeams): string | undefined {
|
|
44
|
+
try {
|
|
45
|
+
const setting = readHarnessSetting<{ enabled?: unknown; scenarios?: unknown; revision?: unknown }>('supervisorMode', seams);
|
|
46
|
+
if (setting?.enabled === true && Array.isArray(setting.scenarios)
|
|
47
|
+
&& setting.scenarios.every(id => typeof id === 'string') && setting.scenarios.includes('ci-observation'))
|
|
48
|
+
return typeof setting.revision === 'string' ? setting.revision : 'initial';
|
|
49
|
+
} catch { /* An unreadable setting cannot enable a recovery. */ }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Only the current Outcome entry and bounded criteria cross the native grant.
|
|
53
|
+
// Never send the branch transcript or infer an Outcome from tool output.
|
|
54
|
+
export function supervisorOutcome(branch: readonly { id: string; type: string; customType?: string; data?: unknown }[]) {
|
|
55
|
+
let entry: typeof branch[number] | undefined;
|
|
56
|
+
for (let index = branch.length - 1; index >= 0; index--) {
|
|
57
|
+
const item = branch[index];
|
|
58
|
+
if (item?.type === 'custom' && item.customType === 'pi-better-harness:outcome') { entry = item; break; }
|
|
59
|
+
}
|
|
60
|
+
const data = entry?.data as { version?: number; outcome?: { status?: string; objective?: string; doneWhen?: string[]; boundaries?: string[] } } | undefined;
|
|
61
|
+
if (!entry || data?.version !== 1 || data.outcome?.status !== 'active'
|
|
62
|
+
|| typeof data.outcome.objective !== 'string' || !data.outcome.objective.trim()) return;
|
|
63
|
+
const lines = (value: unknown) => Array.isArray(value) ? value.filter(item => typeof item === 'string').slice(0, 8).map(item => item.slice(0, 400)) : [];
|
|
64
|
+
return { id: entry.id, objective: data.outcome.objective.slice(0, 2000), doneWhen: lines(data.outcome.doneWhen), boundaries: lines(data.outcome.boundaries) };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface CiRun { repo: string; runId: string; attempt: number }
|
|
68
|
+
|
|
69
|
+
export function validCiRun(run: CiRun): boolean {
|
|
70
|
+
return /^[\w-]+\/[\w.-]+$/.test(run.repo) && !run.repo.endsWith('/.') && !run.repo.endsWith('/..')
|
|
71
|
+
&& /^[1-9]\d{0,14}$/.test(run.runId) && Number.isSafeInteger(run.attempt) && run.attempt > 0;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Accept a single invocation containing only literal, space-separated words.
|
|
75
|
+
// No shell parsing or execution is needed to identify the run.
|
|
76
|
+
export function ciObserverArgv(spec: { shell?: boolean; argv?: string[]; command?: string }) {
|
|
77
|
+
if (spec.shell === false) return spec.argv;
|
|
78
|
+
const command = spec.command;
|
|
79
|
+
if (typeof command !== 'string' || command.length > 4096 || /[^a-zA-Z0-9/@_., -]/.test(command)) return;
|
|
80
|
+
return command.trim().split(/ +/);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Recognize known observer invocations, never their stdout or a caller-supplied URL. */
|
|
84
|
+
export function ciRunFromArgv(kind: string, argv: readonly string[] | undefined): CiRun | undefined {
|
|
85
|
+
const script = argv?.[1] ?? '';
|
|
86
|
+
const repositoryWatcher = /^(?:\.\/)?scripts\/watch-github-run\.mjs$/.test(script);
|
|
87
|
+
const installedWatcher = script.startsWith('/') && !script.split('/').includes('..')
|
|
88
|
+
&& script.endsWith('/node_modules/@1aboveio/skills/skills/cicd/github-actions/scripts/watch-run.mjs');
|
|
89
|
+
if (kind === 'process' && argv?.[0] === 'node' && (repositoryWatcher || installedWatcher)) {
|
|
90
|
+
const options = new Map<string, string>();
|
|
91
|
+
for (let i = 2; i < argv.length; i += 2) {
|
|
92
|
+
const flag = argv[i], value = argv[i + 1];
|
|
93
|
+
if (!flag || !value || !['--repo', '--run', '--interval-seconds'].includes(flag) || options.has(flag)) return;
|
|
94
|
+
options.set(flag, value);
|
|
95
|
+
}
|
|
96
|
+
const run = { repo: options.get('--repo')?.toLowerCase() ?? '', runId: options.get('--run') ?? '', attempt: 1 };
|
|
97
|
+
return validCiRun(run) ? run : undefined;
|
|
98
|
+
}
|
|
99
|
+
if (!argv || argv[0] !== 'gh' || argv[1] !== 'run'
|
|
100
|
+
|| !(kind === 'watch' && argv[2] === 'view' || kind === 'process' && argv[2] === 'watch')) return;
|
|
101
|
+
const runId = argv[3];
|
|
102
|
+
if (!/^[1-9]\d{0,14}$/.test(runId ?? '')) return;
|
|
103
|
+
let repo: string | undefined, attempt = 1, pinned = false, json = false;
|
|
104
|
+
for (let i = 4; i < argv.length; i++) {
|
|
105
|
+
const flag = argv[i];
|
|
106
|
+
if (flag === '--exit-status' && kind === 'process') continue;
|
|
107
|
+
const value = argv[++i];
|
|
108
|
+
if ((flag === '--repo' || flag === '-R') && !repo && /^(?:github\.com\/)?[\w-]+\/[\w.-]+$/.test(value ?? '')) {
|
|
109
|
+
repo = value!.replace(/^github\.com\//, '').toLowerCase();
|
|
110
|
+
} else if (kind === 'watch' && flag === '--attempt' && !pinned && /^[1-9]\d{0,4}$/.test(value ?? '')) {
|
|
111
|
+
attempt = Number(value); pinned = true;
|
|
112
|
+
} else if (kind === 'watch' && flag === '--json' && !json && /^[A-Za-z,]+$/.test(value ?? '')) {
|
|
113
|
+
json = true;
|
|
114
|
+
} else return;
|
|
115
|
+
}
|
|
116
|
+
const run = { repo: repo ?? '', runId: runId!, attempt };
|
|
117
|
+
if (validCiRun(run) && (kind !== 'watch' || json)) return run;
|
|
118
|
+
}
|
package/src/managed-client.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { backgroundDigest, backgroundParametersDigest } from './managed-authorit
|
|
|
6
6
|
import { readAdmissionStartToken, readProcessStartTokenFresh } from './process-identity.js';
|
|
7
7
|
import { currentForegroundSandboxPolicy, FOREGROUND_SANDBOX_POLICY_CHANNEL } from './sandbox.js';
|
|
8
8
|
import { backgroundListNeedsHistory, backgroundObservation } from './work-observation.js';
|
|
9
|
+
import { supervisorConsultTool, supervisorOutcome } from './ci-observation.js';
|
|
9
10
|
/** Native host proof carries scope and captured policy, never a transcript or module path. */
|
|
10
11
|
export async function requestBackgroundTool(pi: ExtensionAPI, ctx: ExtensionContext, key: string, tool: string, params: unknown, parameters?: unknown, signal?: AbortSignal): Promise<any> {
|
|
11
12
|
if (signal?.aborted)
|
|
@@ -40,7 +41,8 @@ export async function requestBackgroundTool(pi: ExtensionAPI, ctx: ExtensionCont
|
|
|
40
41
|
try {
|
|
41
42
|
const hello = await client.ready;
|
|
42
43
|
const policy = currentForegroundSandboxPolicy(pi);
|
|
43
|
-
const
|
|
44
|
+
const branch = ctx.sessionManager.getBranch();
|
|
45
|
+
const branchIds = branch.map(entry => entry.id).filter((value): value is string => typeof value === 'string');
|
|
44
46
|
const sessionId = ctx.sessionManager.getSessionId();
|
|
45
47
|
if (!sessionId)
|
|
46
48
|
throw new Error('Background tools require a native session identity');
|
|
@@ -48,7 +50,9 @@ export async function requestBackgroundTool(pi: ExtensionAPI, ctx: ExtensionCont
|
|
|
48
50
|
const start = version === 2 ? readAdmissionStartToken(process.pid) : readProcessStartTokenFresh(process.pid);
|
|
49
51
|
const record = { version, id, secretHash: createHash('sha256').update(secret).digest('hex'), instanceId: hello.instanceId,
|
|
50
52
|
owner: { kind: 'parent-session', sessionId, workspace: realpathSync(ctx.cwd) }, branchIds, projectTrusted: ctx.isProjectTrusted(),
|
|
51
|
-
pid: process.pid, start, key, tool, params, parametersDigest: parameters === undefined ? undefined : backgroundParametersDigest(parameters), policy
|
|
53
|
+
pid: process.pid, start, key, tool, params, parametersDigest: parameters === undefined ? undefined : backgroundParametersDigest(parameters), policy,
|
|
54
|
+
supervisorOutcome: ['bg_task_spawn', 'bg_task_watch', 'bg_task', '__background_poll', '__background_receipt', supervisorConsultTool].includes(tool)
|
|
55
|
+
? supervisorOutcome(branch) : undefined };
|
|
52
56
|
const staged = `${path}.tmp`;
|
|
53
57
|
writeFileSync(staged, JSON.stringify(record), { flag: 'wx', mode: 0o600 });
|
|
54
58
|
renameSync(staged, path);
|
package/src/managed-frontend.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { ManagedBackgroundNavigator } from './navigator-provider.js';
|
|
2
2
|
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { Type } from 'typebox';
|
|
3
4
|
import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
4
5
|
import { requestBackgroundTool } from './managed-client.js';
|
|
5
6
|
import { onBackgroundObservation } from './work-observation.js';
|
|
@@ -7,6 +8,7 @@ import { getCallbackBatcher } from './shared-callback-batcher.js';
|
|
|
7
8
|
import { registerObservedWaitClient } from "./observed-wait-client.js";
|
|
8
9
|
import type { ObservedWaitHost } from "./observed-waits.js";
|
|
9
10
|
import { observeNavigatorLaunch } from './shared-navigator.ts';
|
|
11
|
+
import { ciObservationRevision, requestCiRecoveryWake, supervisorConsultTool, supervisorOutcome, supervisorRecoveryType } from './ci-observation.js';
|
|
10
12
|
/** Native transcript delivery and cached UI projections; no coordinator or supervisor. */
|
|
11
13
|
export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
12
14
|
let ctx: ExtensionContext | undefined, generation = 0, refresh: Promise<void> | undefined, dirty=false;
|
|
@@ -109,7 +111,12 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
|
109
111
|
continue;
|
|
110
112
|
const n = item.notification;
|
|
111
113
|
const type = n.event?.customType;
|
|
112
|
-
|
|
114
|
+
const recovery = type === supervisorRecoveryType;
|
|
115
|
+
const recoveryProof = () => captured.sessionManager.getBranch().some((entry: any) => {
|
|
116
|
+
const message = entry.type === 'custom_message' ? entry : entry.message;
|
|
117
|
+
return message?.customType === type && message.details?.urgentEventId === item.receiptId;
|
|
118
|
+
});
|
|
119
|
+
if (!(recovery && recoveryProof()) && (type === 'background-task-stall' || type === 'background-wait-review' || recovery)
|
|
113
120
|
&& (!rechecking?.has(item.receiptId) || !captured.isIdle())) {
|
|
114
121
|
// Keep the candidate here while busy. Pi's followUp queue cannot
|
|
115
122
|
// revalidate it when the current turn eventually ends.
|
|
@@ -124,7 +131,7 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
|
124
131
|
.then(() => trace('receipt-return', facts), error => trace('receipt-error', { ...facts, error: String(error).slice(0, 256) }))
|
|
125
132
|
.finally(() => {queued.delete(item.token);if(ctx===captured)void reconcile().catch(()=>undefined);});
|
|
126
133
|
};
|
|
127
|
-
const proof = captured.sessionManager.getBranch().some((entry: any) => {
|
|
134
|
+
const proof = recovery ? recoveryProof() : captured.sessionManager.getBranch().some((entry: any) => {
|
|
128
135
|
const message = entry.type === 'custom_message' ? entry : entry.message;
|
|
129
136
|
return item.notification.urgent ? message?.customType===item.notification.event.customType&&message.details?.urgentEventId===item.receiptId : message?.customType === 'background-completion-batch' && message.details?.completionEventIds?.includes(item.receiptId);
|
|
130
137
|
});
|
|
@@ -134,11 +141,23 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
|
134
141
|
}
|
|
135
142
|
trace('queue', { ...facts, urgent: n.urgent === true, recipientActive: active(n.origin, n.branchId) });
|
|
136
143
|
if (n.urgent) {
|
|
137
|
-
const handoff = getCallbackBatcher(pi).deliverUrgent({ ...n.event, receiptId: item.receiptId,
|
|
138
|
-
getSuppressionReason: () => active(n.origin, n.branchId) ? undefined : 'The originating session or branch is no longer active',
|
|
139
|
-
onDelivered: () => receipt(true), onSuppressed: reason => receipt(false, reason) });
|
|
140
144
|
const retry = () => { queued.delete(item.token); if (version === generation) scheduleHandoffPoll(1000); };
|
|
141
|
-
|
|
145
|
+
const deliver = (wake?: () => boolean) => {
|
|
146
|
+
if (recovery && (version !== generation || !wake?.())) { retry(); return; }
|
|
147
|
+
const handoff = getCallbackBatcher(pi).deliverUrgent({ ...n.event, receiptId: item.receiptId,
|
|
148
|
+
getSuppressionReason: () => {
|
|
149
|
+
if (!active(n.origin, n.branchId)) return 'The originating session or branch is no longer active';
|
|
150
|
+
if (recovery && (typeof n.settingRevision !== 'string' || ciObservationRevision() !== n.settingRevision || supervisorOutcome(captured.sessionManager.getBranch())?.id !== n.outcomeId
|
|
151
|
+
|| !captured.isIdle() || Date.now() >= n.validUntil || !wake?.())) return 'CI recovery needs fresh settings, Outcome, or remote evidence';
|
|
152
|
+
},
|
|
153
|
+
onDelivered: () => { if (!recovery || recoveryProof()) receipt(true); else retry(); },
|
|
154
|
+
onSuppressed: reason => receipt(false, reason) });
|
|
155
|
+
void Promise.resolve(handoff).then(ok => { if (!ok) retry(); }, retry);
|
|
156
|
+
};
|
|
157
|
+
// A workflow can asynchronously check its gate. Ordinary
|
|
158
|
+
// completions and the foreground refresh must not wait on it.
|
|
159
|
+
if (recovery) void requestCiRecoveryWake(pi, captured, n.branchId, n.validUntil).then(deliver).catch(retry);
|
|
160
|
+
else deliver();
|
|
142
161
|
continue;
|
|
143
162
|
}
|
|
144
163
|
getCallbackBatcher(pi).enqueue({ ...n.event, source: 'background-task', id: n.taskId, label: n.taskId, status: n.waitId ? `${n.status}; wait ${n.waitId} ready` : n.status,
|
|
@@ -207,6 +226,17 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
|
207
226
|
return false; void request('__background_dismiss', { id }).then(() => reconcile()).catch(() => undefined); return false; },
|
|
208
227
|
};
|
|
209
228
|
registerObservedWaitClient(pi, host as unknown as ObservedWaitHost);
|
|
229
|
+
pi.registerTool({
|
|
230
|
+
name: supervisorConsultTool, label: 'Consult Supervisor',
|
|
231
|
+
description: 'Ask the daemon to diagnose an interrupted CI watcher owned by this session and Outcome. Shares automatic recovery and never launches or restarts a remote run. Any recommendation arrives once through the normal Background callback.',
|
|
232
|
+
parameters: Type.Object({ id: Type.String({ description: 'Background watcher task ID' }) }),
|
|
233
|
+
async execute(id, params, signal, _update, context) {
|
|
234
|
+
adoptContext(context);
|
|
235
|
+
const result = await requestBackgroundTool(pi, context, id, supervisorConsultTool, params, undefined, signal);
|
|
236
|
+
await host.reconcileNow().catch(() => undefined);
|
|
237
|
+
return result;
|
|
238
|
+
},
|
|
239
|
+
});
|
|
210
240
|
pi.events?.on?.('pi-better-background-tasks:managed-capability',(request:any)=>{if(ctx&&typeof request?.accept==='function')request.accept({version:1,assignmentContinuation:1});});
|
|
211
241
|
onBackgroundObservation(pi, () => { details.clear(); logs.clear(); void reconcile().catch(() => undefined); });
|
|
212
242
|
const proxy = new Proxy(pi, { get(target, key) {
|
package/src/observed-waits.ts
CHANGED
|
@@ -77,8 +77,9 @@ import {
|
|
|
77
77
|
type SupervisorStartOptions,
|
|
78
78
|
type SupervisorTaskStatus,
|
|
79
79
|
} from "./supervisor/index.js";
|
|
80
|
-
import {
|
|
80
|
+
import { processGroupExitVerified } from "./supervisor/identity.js";
|
|
81
81
|
import { readStopRequest, writeTextAtomic } from "./supervisor/store.js";
|
|
82
|
+
import { ciObserverArgv, ciRunFromArgv, validCiRun } from "./ci-observation.js";
|
|
82
83
|
import type { BackgroundTaskCallbackOrigin, CommandSpec, Condition, TaskSandboxProvenance } from "./types.js";
|
|
83
84
|
import type { SpawnTaskParams, WatchTaskParams } from "./runtime.js";
|
|
84
85
|
|
|
@@ -575,6 +576,7 @@ function rpcCode(error: unknown): string {
|
|
|
575
576
|
}
|
|
576
577
|
|
|
577
578
|
export interface ObservedWaitHostOptions {
|
|
579
|
+
currentOutcomeId?: () => string | undefined;
|
|
578
580
|
/** Fixed server admission guard, checked immediately before external dispatch. */
|
|
579
581
|
assertAdmission?: () => void;
|
|
580
582
|
/** Fixed native adapter alone may authorize an explicit cross-owner stop. */
|
|
@@ -687,6 +689,7 @@ interface LaunchContext {
|
|
|
687
689
|
readonly supervisionPolicy?: ForegroundSandboxPlan;
|
|
688
690
|
/** Owner branch anchor captured at launch (undefined when unavailable). */
|
|
689
691
|
readonly branchId?: string | null;
|
|
692
|
+
readonly ciObservation?: { repo: string; runId: string; attempt: number; outcomeId: string };
|
|
690
693
|
callbackPendingAt?: number;
|
|
691
694
|
callbackDeliveredAt?: number;
|
|
692
695
|
callbackDeferredReason?: string;
|
|
@@ -1296,10 +1299,13 @@ export class ObservedWaitHost {
|
|
|
1296
1299
|
if (!this.store || this.closed) return;
|
|
1297
1300
|
this.authorityPassCache = new Map();
|
|
1298
1301
|
try {
|
|
1299
|
-
const discovery = this.options.serverOwnedResults ? undefined : this.store.readDiscoveryState(this.discoveryScope);
|
|
1302
|
+
const discovery = this.options.serverOwnedResults ? undefined : this.store.readDiscoveryState(this.discoveryScope, this.hostId);
|
|
1300
1303
|
if (this.options.serverOwnedResults || discovery?.managed) {
|
|
1301
1304
|
this.releaseDiscoveryAuthority();
|
|
1302
|
-
if (!this.options.serverOwnedResults)
|
|
1305
|
+
if (!this.options.serverOwnedResults) {
|
|
1306
|
+
this.reconcileFollowerRunning();
|
|
1307
|
+
if (discovery?.cleanupPending) await this.reconcileAssignmentCleanup();
|
|
1308
|
+
}
|
|
1303
1309
|
this.reconcileOwnerChanges();
|
|
1304
1310
|
this.retryPendingTerminalCallbacks();
|
|
1305
1311
|
await this.dispatchOutbox();
|
|
@@ -1310,11 +1316,11 @@ export class ObservedWaitHost {
|
|
|
1310
1316
|
if (role === "holder") {
|
|
1311
1317
|
this.discoverObservedTasks();
|
|
1312
1318
|
this.reconcileGlobalRunning();
|
|
1313
|
-
if (discovery!.hasAssignmentTasks) await this.reconcileAssignmentCleanup();
|
|
1314
1319
|
} else {
|
|
1315
1320
|
this.reconcileFollowerRunning();
|
|
1316
1321
|
this.reconcileOwnerChanges();
|
|
1317
1322
|
}
|
|
1323
|
+
if (discovery?.cleanupPending) await this.reconcileAssignmentCleanup();
|
|
1318
1324
|
this.retryPendingTerminalCallbacks();
|
|
1319
1325
|
await this.dispatchOutbox();
|
|
1320
1326
|
} finally {
|
|
@@ -1324,7 +1330,7 @@ export class ObservedWaitHost {
|
|
|
1324
1330
|
|
|
1325
1331
|
private async reconcileAssignmentCleanup(): Promise<void> {
|
|
1326
1332
|
const store = this.requireStore();
|
|
1327
|
-
const [candidate] = store.listAssignmentCleanupOperations(1, this.assignmentCleanupCursor);
|
|
1333
|
+
const [candidate] = store.listAssignmentCleanupOperations(1, this.assignmentCleanupCursor, this.hostId);
|
|
1328
1334
|
this.assignmentCleanupCursor = candidate?.operationId;
|
|
1329
1335
|
if (!candidate || candidate.resultManaged || this.supervisionAuthority(candidate) !== "self") return;
|
|
1330
1336
|
const { taskId, launchToken } = candidate;
|
|
@@ -1335,7 +1341,7 @@ export class ObservedWaitHost {
|
|
|
1335
1341
|
if (inspection.terminal) {
|
|
1336
1342
|
if (inspection.status !== "lost" && inspection.result?.groupCleanup !== "unproven") return;
|
|
1337
1343
|
const pgid = inspection.command?.pgid ?? inspection.command?.pid;
|
|
1338
|
-
if (inspection.cleanup?.groupEmpty
|
|
1344
|
+
if (processGroupExitVerified(pgid, inspection.cleanup?.groupEmpty)) {
|
|
1339
1345
|
store.verifyAssignmentCleanup(candidate.operationId, launchToken, candidate.terminalRevision);
|
|
1340
1346
|
return;
|
|
1341
1347
|
}
|
|
@@ -1534,6 +1540,9 @@ export class ObservedWaitHost {
|
|
|
1534
1540
|
authorityRef: this.parentAuthority(owner, prepared.plan),
|
|
1535
1541
|
intentRef: typeof input.params.operation_id === "string" ? input.params.operation_id : null,
|
|
1536
1542
|
});
|
|
1543
|
+
const outcomeId = this.options.currentOutcomeId?.();
|
|
1544
|
+
const ciRun = outcomeId && !prepared.spec.env && prepared.cwd === owner.workspace
|
|
1545
|
+
? ciRunFromArgv(input.kind, ciObserverArgv(prepared.spec)) : undefined;
|
|
1537
1546
|
const launchContext: LaunchContext = {
|
|
1538
1547
|
kind: input.kind,
|
|
1539
1548
|
parentOrigin: this.parentOrigin,
|
|
@@ -1546,6 +1555,7 @@ export class ObservedWaitHost {
|
|
|
1546
1555
|
sandbox: prepared.provenance,
|
|
1547
1556
|
supervisionPolicy: prepared.plan,
|
|
1548
1557
|
branchId: owner.branchId ?? null,
|
|
1558
|
+
...(ciRun && outcomeId ? { ciObservation: { ...ciRun, outcomeId } } : {}),
|
|
1549
1559
|
};
|
|
1550
1560
|
// Persist supervision metadata outside the task execution record so a
|
|
1551
1561
|
// replacement host can still notify the right parent and never re-route a
|
|
@@ -1799,6 +1809,21 @@ export class ObservedWaitHost {
|
|
|
1799
1809
|
return this.projectDurable(operation, now);
|
|
1800
1810
|
}
|
|
1801
1811
|
|
|
1812
|
+
/** Resolve exact owner and immutable launch/terminal evidence, not a display projection. */
|
|
1813
|
+
ciObservation(origin: BackgroundTaskCallbackOrigin, taskId: string, outcomeId: string, branchIds: readonly string[]) {
|
|
1814
|
+
if (!LOCAL_DURABLE_ID.test(taskId)) return;
|
|
1815
|
+
const operation = this.operationForTask(taskId);
|
|
1816
|
+
if (!operation || !this.belongsToParentOrigin(operation, origin)
|
|
1817
|
+
|| !operation.owner.branchId || !branchIds.includes(operation.owner.branchId)) return;
|
|
1818
|
+
const directory = this.observationDirectory(operation);
|
|
1819
|
+
if (!directory) return;
|
|
1820
|
+
const context = this.readLaunchContext(taskId, directory);
|
|
1821
|
+
if (!context?.ciObservation || context.ciObservation.outcomeId !== outcomeId || context.dismissedAt !== undefined) return;
|
|
1822
|
+
const inspection = this.passiveSnapshot(taskId, directory);
|
|
1823
|
+
if (!inspection || inspection.token !== operation.launchToken) return;
|
|
1824
|
+
return { run: context.ciObservation, operation, inspection, policy: context.supervisionPolicy, callback: context.callback };
|
|
1825
|
+
}
|
|
1826
|
+
|
|
1802
1827
|
/** Rebuild a live incident from the runner checkpoint. Only the native handoff writes its receipt. */
|
|
1803
1828
|
pendingStallAlert(origin: BackgroundTaskCallbackOrigin, taskId: string, waits: readonly { waitId: string; generation: number }[]) {
|
|
1804
1829
|
const operation = this.operationForTask(taskId);
|
|
@@ -4484,6 +4509,8 @@ export class ObservedWaitHost {
|
|
|
4484
4509
|
...(value.supervisionPolicy && typeof value.supervisionPolicy === "object"
|
|
4485
4510
|
? { supervisionPolicy: value.supervisionPolicy } : {}),
|
|
4486
4511
|
...(typeof value.branchId === "string" || value.branchId === null ? { branchId: value.branchId } : {}),
|
|
4512
|
+
...(value.ciObservation && typeof value.ciObservation.outcomeId === "string" && validCiRun(value.ciObservation)
|
|
4513
|
+
? { ciObservation: value.ciObservation } : {}),
|
|
4487
4514
|
...(typeof value.callbackPendingAt === "number" ? { callbackPendingAt: value.callbackPendingAt } : {}),
|
|
4488
4515
|
...(typeof value.callbackDeliveredAt === "number" ? { callbackDeliveredAt: value.callbackDeliveredAt }
|
|
4489
4516
|
: typeof (value as { callbackNotifiedAt?: unknown }).callbackNotifiedAt === "number"
|
|
@@ -90,6 +90,7 @@ export function createAssignmentReader(path, inboxPath = ":memory:", derivedConn
|
|
|
90
90
|
connection(refresh = true) { if (refresh) this.revision(); return db; },
|
|
91
91
|
changes() { this.revision(); return inbox.receive(db, identity); },
|
|
92
92
|
acknowledgeChanges(batch, complete) { inbox.acknowledge(batch, complete); },
|
|
93
|
+
get hasPendingChanges() { return inbox.hasPendingChanges; },
|
|
93
94
|
get changeMetrics() { return inbox.metrics; },
|
|
94
95
|
get snapshotActive() { return snapshot; },
|
|
95
96
|
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
// Generated from packages/operation-coordinator/src/assignment-outcomes.ts. Do not edit directly.
|
|
2
2
|
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
-
import { bumpChangeRevision } from "./discovery.ts";
|
|
4
3
|
import { StoreError } from "./errors.ts";
|
|
5
4
|
import { columnText, getRow, getRows, run, type StoreContext } from "./sqlite.ts";
|
|
6
5
|
import { requireWait, readPins } from "./rows.ts";
|
|
@@ -121,7 +120,6 @@ export function recordAssignmentOutcome(ctx: StoreContext, input: AssignmentOutc
|
|
|
121
120
|
}
|
|
122
121
|
for (const e of retained) run(ctx, `INSERT OR IGNORE INTO evidence_pins (pin_id, wait_id, generation, operation_id, terminal_revision, kind, ref, summary, detail_lost, bytes, pinned_at) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)`, `pin_${randomUUID()}`, eventId, e.operationId, e.terminalRevision, e.kind, e.ref, e.summary ?? null, e.detailLost ? 1 : 0, e.bytes ?? null, at);
|
|
123
122
|
run(ctx, `INSERT INTO outbox_events (event_id, event_type, operation_id, terminal_revision, wait_id, generation, recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id, state, created_at) VALUES (?, 'assignment-outcome', ?, ?, ?, 1, ?, ?, ?, ?, ?, 'pending', ?)`, eventId, assignmentId, revision, eventId, recipient.kind, recipient.sessionId, recipient.workspace, recipient.branchId ?? null, recipient.goalId ?? null, at);
|
|
124
|
-
bumpChangeRevision(ctx);
|
|
125
123
|
return record;
|
|
126
124
|
});
|
|
127
125
|
}
|
|
@@ -49,13 +49,16 @@ export function readDiscoveryClaim(ctx: StoreContext, scope: unknown): Discovery
|
|
|
49
49
|
}
|
|
50
50
|
|
|
51
51
|
/** Read scope transfer and its discovery claim from one SQLite snapshot. */
|
|
52
|
-
export function readDiscoveryState(ctx: StoreContext, scope: string): { managed: boolean; claim: DiscoveryClaimRecord | null; hasAssignmentTasks: boolean } {
|
|
52
|
+
export function readDiscoveryState(ctx: StoreContext, scope: string, hostId?: string): { managed: boolean; claim: DiscoveryClaimRecord | null; hasAssignmentTasks: boolean; cleanupPending?: boolean } {
|
|
53
53
|
scope = requireId("scope", scope);
|
|
54
54
|
const row = getRow(ctx, `SELECT d.*, EXISTS(SELECT 1 FROM coordinator_state WHERE key = ?) AS managed,
|
|
55
55
|
EXISTS(SELECT 1 FROM operations INDEXED BY operations_assignment_cleanup
|
|
56
|
-
WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks
|
|
57
|
-
|
|
58
|
-
|
|
56
|
+
WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks,
|
|
57
|
+
EXISTS(SELECT 1 FROM assignment_cleanup_pending WHERE supervision_host_id = ?) AS cleanup_pending
|
|
58
|
+
FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope,
|
|
59
|
+
hostId === undefined ? null : requireId("hostId", hostId), scope)!;
|
|
60
|
+
return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row), hasAssignmentTasks: Number(row.has_assignment_tasks) === 1,
|
|
61
|
+
...(hostId === undefined ? {} : { cleanupPending: Number(row.cleanup_pending) === 1 }) };
|
|
59
62
|
}
|
|
60
63
|
|
|
61
64
|
export function tryClaimDiscovery(
|
|
@@ -467,23 +467,17 @@ export function listAssignmentCleanupOperations(
|
|
|
467
467
|
ctx: StoreContext,
|
|
468
468
|
limit: number,
|
|
469
469
|
afterOperationId?: string,
|
|
470
|
+
hostId?: string,
|
|
470
471
|
): OperationRecord[] {
|
|
471
472
|
const requested = requireCounter("limit", limit);
|
|
472
473
|
if (requested === 0) throw new StoreError("validation", "Invalid limit: must be at least 1");
|
|
473
474
|
const cursor = afterOperationId === undefined ? "" : requireId("afterOperationId", afterOperationId);
|
|
474
|
-
|
|
475
|
+
const params = hostId === undefined ? [] : [requireId("hostId", hostId)];
|
|
475
476
|
return getRows(ctx, `SELECT op.*, EXISTS(SELECT 1 FROM coordinator_state s
|
|
476
477
|
WHERE s.key = 'result-supervision-v1:' || op.operation_id) AS result_managed
|
|
477
|
-
FROM operations op
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
WHERE op.assignment_attempt_id IS NOT NULL AND op.operation_id > ?
|
|
481
|
-
AND (op.terminal_revision = 0 OR op.terminal_outcome = 'lost'
|
|
482
|
-
OR EXISTS (SELECT 1 FROM operation_evidence e WHERE e.operation_id = op.operation_id
|
|
483
|
-
AND e.terminal_revision = op.terminal_revision AND e.kind = 'terminal-record'
|
|
484
|
-
AND e.summary LIKE '%groupCleanup=unproven%'))
|
|
485
|
-
AND NOT EXISTS (SELECT 1 FROM coordinator_state s WHERE s.key = 'assignment-cleanup-verified:' || op.operation_id)
|
|
486
|
-
ORDER BY op.operation_id LIMIT ?`, cursor, Math.min(requested, ASSIGNMENT_CLEANUP_PAGE_MAX))
|
|
478
|
+
FROM assignment_cleanup_pending p CROSS JOIN operations op ON op.operation_id = p.operation_id
|
|
479
|
+
WHERE ${hostId === undefined ? "" : "p.supervision_host_id = ? AND "}p.operation_id > ?
|
|
480
|
+
ORDER BY p.operation_id LIMIT ?`, ...params, cursor, Math.min(requested, ASSIGNMENT_CLEANUP_PAGE_MAX))
|
|
487
481
|
.map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
|
|
488
482
|
}
|
|
489
483
|
|
|
@@ -72,6 +72,45 @@ const ASSIGNMENT_CLEANUP_INDEX = `CREATE INDEX IF NOT EXISTS operations_assignme
|
|
|
72
72
|
ON operations (operation_id, assignment_attempt_id)
|
|
73
73
|
WHERE assignment_attempt_id IS NOT NULL`;
|
|
74
74
|
|
|
75
|
+
// Terminal evidence is written before the operation's terminal revision in the same transaction.
|
|
76
|
+
function needsAssignmentCleanup(row: "op" | "NEW"): string {
|
|
77
|
+
return `(${row}.terminal_revision = 0 OR ${row}.terminal_outcome = 'lost' OR EXISTS (
|
|
78
|
+
SELECT 1 FROM operation_evidence e WHERE e.operation_id = ${row}.operation_id
|
|
79
|
+
AND e.terminal_revision = ${row}.terminal_revision AND e.kind = 'terminal-record'
|
|
80
|
+
AND e.summary LIKE '%groupCleanup=unproven%'))`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const CLEANUP_FOR_ASSIGNMENT = `SELECT op.operation_id, op.supervision_host_id
|
|
84
|
+
FROM assignment_attempts a JOIN operations op ON op.assignment_attempt_id = a.attempt_id
|
|
85
|
+
WHERE a.assignment_id = NEW.assignment_id AND ${needsAssignmentCleanup("op")}`;
|
|
86
|
+
|
|
87
|
+
// Triggers also cover older processes that still have an open coordinator connection.
|
|
88
|
+
const PENDING_CLEANUP_DDL = [
|
|
89
|
+
`CREATE TABLE IF NOT EXISTS assignment_cleanup_pending (
|
|
90
|
+
operation_id TEXT PRIMARY KEY REFERENCES operations(operation_id),
|
|
91
|
+
supervision_host_id TEXT
|
|
92
|
+
) WITHOUT ROWID`,
|
|
93
|
+
`CREATE INDEX assignment_cleanup_host ON assignment_cleanup_pending(supervision_host_id, operation_id)`,
|
|
94
|
+
`CREATE INDEX assignment_attempts_by_assignment ON assignment_attempts(assignment_id, attempt_id)`,
|
|
95
|
+
`CREATE INDEX operations_by_assignment_attempt ON operations(assignment_attempt_id)
|
|
96
|
+
WHERE assignment_attempt_id IS NOT NULL`,
|
|
97
|
+
`CREATE TRIGGER assignment_cleanup_enqueue AFTER INSERT ON assignment_outcomes BEGIN
|
|
98
|
+
INSERT INTO assignment_cleanup_pending ${CLEANUP_FOR_ASSIGNMENT};
|
|
99
|
+
END`,
|
|
100
|
+
`CREATE TRIGGER assignment_cleanup_terminal AFTER UPDATE OF terminal_revision ON operations
|
|
101
|
+
WHEN NEW.assignment_attempt_id IS NOT NULL AND NEW.terminal_revision > 0 AND NOT ${needsAssignmentCleanup("NEW")} BEGIN
|
|
102
|
+
DELETE FROM assignment_cleanup_pending WHERE operation_id = NEW.operation_id;
|
|
103
|
+
END`,
|
|
104
|
+
`CREATE TRIGGER assignment_cleanup_transfer AFTER UPDATE OF supervision_host_id ON operations
|
|
105
|
+
WHEN NEW.assignment_attempt_id IS NOT NULL AND NEW.supervision_host_id IS NOT OLD.supervision_host_id BEGIN
|
|
106
|
+
UPDATE assignment_cleanup_pending SET supervision_host_id = NEW.supervision_host_id WHERE operation_id = NEW.operation_id;
|
|
107
|
+
END`,
|
|
108
|
+
`CREATE TRIGGER assignment_cleanup_verified AFTER INSERT ON coordinator_state
|
|
109
|
+
WHEN NEW.key GLOB 'assignment-cleanup-verified:*' BEGIN
|
|
110
|
+
DELETE FROM assignment_cleanup_pending WHERE operation_id = substr(NEW.key, length('assignment-cleanup-verified:') + 1);
|
|
111
|
+
END`,
|
|
112
|
+
];
|
|
113
|
+
|
|
75
114
|
const DDL: readonly string[] = [
|
|
76
115
|
`CREATE TABLE task_cancellation_authorities (
|
|
77
116
|
credential_hash TEXT PRIMARY KEY,
|
|
@@ -293,6 +332,7 @@ const DDL: readonly string[] = [
|
|
|
293
332
|
PRIMARY KEY (wait_id, generation)
|
|
294
333
|
)`,
|
|
295
334
|
RESULT_ADMISSION_FENCE,
|
|
335
|
+
...PENDING_CLEANUP_DDL,
|
|
296
336
|
];
|
|
297
337
|
|
|
298
338
|
const SCHEMA_VERSION_KEY = "schema_version";
|
|
@@ -377,12 +417,25 @@ export function ensureSchema(ctx: StoreContext): void {
|
|
|
377
417
|
function ensureAssignmentCleanupSchema(ctx: StoreContext): void {
|
|
378
418
|
for (const statement of EXPIRY_INDEXES) ctx.db.exec(statement);
|
|
379
419
|
const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
|
|
380
|
-
|
|
420
|
+
const hasPending = () => !!getRow(ctx, "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'assignment_cleanup_pending'");
|
|
421
|
+
if (hasPending()) return;
|
|
381
422
|
ctx.transaction(() => {
|
|
423
|
+
if (hasPending()) return;
|
|
382
424
|
ctx.db.exec(ASSIGNMENT_ATTEMPTS_DDL);
|
|
383
425
|
// Legacy writers leave the nullable provenance unset.
|
|
384
426
|
if (!hasColumn()) ctx.db.exec(`ALTER TABLE operations ADD COLUMN ${ASSIGNMENT_ATTEMPT_COLUMN}`);
|
|
385
427
|
ctx.db.exec(ASSIGNMENT_CLEANUP_INDEX);
|
|
428
|
+
for (const statement of PENDING_CLEANUP_DDL) ctx.db.exec(statement);
|
|
429
|
+
if (process.platform === "win32") {
|
|
430
|
+
// Earlier Windows writers mistook an unsupported group probe for proof of exit.
|
|
431
|
+
ctx.db.exec("DELETE FROM coordinator_state WHERE key GLOB 'assignment-cleanup-verified:*'");
|
|
432
|
+
}
|
|
433
|
+
ctx.db.exec(`INSERT INTO assignment_cleanup_pending
|
|
434
|
+
SELECT op.operation_id, op.supervision_host_id FROM operations op
|
|
435
|
+
JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
|
|
436
|
+
JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
|
|
437
|
+
WHERE ${needsAssignmentCleanup("op")} AND NOT EXISTS (SELECT 1 FROM coordinator_state
|
|
438
|
+
WHERE key = 'assignment-cleanup-verified:' || op.operation_id)`);
|
|
386
439
|
});
|
|
387
440
|
}
|
|
388
441
|
|
|
@@ -207,7 +207,7 @@ export interface Store {
|
|
|
207
207
|
* Read up to 256 unfinished cleanup obligations in operation id order.
|
|
208
208
|
* The cursor is exclusive. Start each new sweep without a cursor.
|
|
209
209
|
*/
|
|
210
|
-
listAssignmentCleanupOperations(limit: number, afterOperationId?: string): OperationRecord[];
|
|
210
|
+
listAssignmentCleanupOperations(limit: number, afterOperationId?: string, hostId?: string): OperationRecord[];
|
|
211
211
|
verifyAssignmentCleanup(operationId: string, launchToken: string, terminalRevision: number): boolean;
|
|
212
212
|
/** Running operations currently assigned to this supervising host. */
|
|
213
213
|
listRunningSupervisedBy(hostId: string): OperationRecord[];
|
|
@@ -217,7 +217,7 @@ export interface Store {
|
|
|
217
217
|
|
|
218
218
|
/** The shared discovery leader for this store/supervisor scope, if recorded. */
|
|
219
219
|
readDiscoveryClaim(scope: string): DiscoveryClaimRecord | null;
|
|
220
|
-
readDiscoveryState(scope: string): ReturnType<typeof readDiscoveryState>;
|
|
220
|
+
readDiscoveryState(scope: string, hostId?: string): ReturnType<typeof readDiscoveryState>;
|
|
221
221
|
/**
|
|
222
222
|
* Compare-and-swap a discovery claim. The caller must name the exact claim it
|
|
223
223
|
* observed, or null for none; a stale contender receives null and must not
|
|
@@ -427,9 +427,9 @@ export function openStore(options: StoreOptions): Store {
|
|
|
427
427
|
alive();
|
|
428
428
|
return readOperationRecords(ctx, filter);
|
|
429
429
|
},
|
|
430
|
-
listAssignmentCleanupOperations(limit, afterOperationId) {
|
|
430
|
+
listAssignmentCleanupOperations(limit, afterOperationId, hostId) {
|
|
431
431
|
alive();
|
|
432
|
-
return readAssignmentCleanupOperations(ctx, limit, afterOperationId);
|
|
432
|
+
return readAssignmentCleanupOperations(ctx, limit, afterOperationId, hostId);
|
|
433
433
|
},
|
|
434
434
|
verifyAssignmentCleanup(operationId, launchToken, terminalRevision) {
|
|
435
435
|
alive();
|
|
@@ -453,7 +453,7 @@ export function openStore(options: StoreOptions): Store {
|
|
|
453
453
|
terminalRevision === undefined ? undefined : requireCounter("terminalRevision", terminalRevision),
|
|
454
454
|
);
|
|
455
455
|
},
|
|
456
|
-
readDiscoveryState(scope) { alive(); return readDiscoveryState(ctx, scope); },
|
|
456
|
+
readDiscoveryState(scope, hostId) { alive(); return readDiscoveryState(ctx, scope, hostId); },
|
|
457
457
|
readDiscoveryClaim(scope) {
|
|
458
458
|
alive();
|
|
459
459
|
return readClaim(ctx, scope);
|
|
@@ -93,3 +93,8 @@ export function processGroupAlive(pgid) {
|
|
|
93
93
|
return error.code !== "ESRCH";
|
|
94
94
|
}
|
|
95
95
|
}
|
|
96
|
+
/** Windows has no POSIX group probe. Older cleanup records used that probe there too. */
|
|
97
|
+
export function processGroupExitVerified(pgid, recordedEmpty = false) {
|
|
98
|
+
return process.platform !== "win32" && (recordedEmpty ||
|
|
99
|
+
(pgid !== undefined && Number.isSafeInteger(pgid) && pgid > 0 && !processGroupAlive(pgid)));
|
|
100
|
+
}
|
|
@@ -97,3 +97,9 @@ export function processGroupAlive(pgid: number | undefined): boolean {
|
|
|
97
97
|
return (error as NodeJS.ErrnoException).code !== "ESRCH";
|
|
98
98
|
}
|
|
99
99
|
}
|
|
100
|
+
|
|
101
|
+
/** Windows has no POSIX group probe. Older cleanup records used that probe there too. */
|
|
102
|
+
export function processGroupExitVerified(pgid: number | undefined, recordedEmpty = false): boolean {
|
|
103
|
+
return process.platform !== "win32" && (recordedEmpty ||
|
|
104
|
+
(pgid !== undefined && Number.isSafeInteger(pgid) && pgid > 0 && !processGroupAlive(pgid)));
|
|
105
|
+
}
|
|
@@ -25,7 +25,7 @@ import { join, resolve } from "node:path";
|
|
|
25
25
|
import { setTimeout as delay } from "node:timers/promises";
|
|
26
26
|
import { validateCondition } from "../conditions.ts";
|
|
27
27
|
import { stopProcessGroup } from "../process.ts";
|
|
28
|
-
import { identityAlive, identityAllowsSignals, processGroupAlive, readStartToken, verifyProcessIdentity } from "./identity.ts";
|
|
28
|
+
import { identityAlive, identityAllowsSignals, processGroupAlive, processGroupExitVerified, readStartToken, verifyProcessIdentity } from "./identity.ts";
|
|
29
29
|
import type { ProcessIdentityVerdict } from "./identity.ts";
|
|
30
30
|
import { supervisorRunnerInvocation } from "./invocation.ts";
|
|
31
31
|
import {
|
|
@@ -685,8 +685,7 @@ class Supervisor implements LocalSupervisor {
|
|
|
685
685
|
// Unknown identity cannot authorize an external signal. A recorded process
|
|
686
686
|
// that is gone is only "already gone" when its group is gone too; survivors
|
|
687
687
|
// in a group whose leader died cannot be verified, so they are refused.
|
|
688
|
-
|
|
689
|
-
outcome = (verdict === "dead" || verdict === "absent") && !groupStillAlive ? "already-gone" : "refused-unknown-identity";
|
|
688
|
+
outcome = (verdict === "dead" || verdict === "absent") && processGroupExitVerified(pgid) ? "already-gone" : "refused-unknown-identity";
|
|
690
689
|
groupEmpty = outcome === "already-gone" ? true : false;
|
|
691
690
|
} else {
|
|
692
691
|
/**
|
|
@@ -717,7 +716,7 @@ class Supervisor implements LocalSupervisor {
|
|
|
717
716
|
while (Date.now() < killDeadline && processGroupAlive(pgid)) {
|
|
718
717
|
await delay(25);
|
|
719
718
|
}
|
|
720
|
-
groupEmpty =
|
|
719
|
+
groupEmpty = processGroupExitVerified(pgid);
|
|
721
720
|
outcome = !groupEmpty ? "unproven" : signalledWhileVerified ? "killed" : "already-gone";
|
|
722
721
|
}
|
|
723
722
|
|