pi-better-server 0.7.3 → 0.8.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.
Files changed (82) hide show
  1. package/package.json +1 -1
  2. package/src/runtime/background-tools.ts +146 -6
  3. package/src/runtime/background.ts +2 -2
  4. package/src/runtime/catalog.ts +30 -1
  5. package/src/runtime/ci-recovery.ts +172 -0
  6. package/src/runtime/domain/assignment-inbox.mjs +4 -0
  7. package/src/runtime/domain/assignment-observation.d.mts +1 -1
  8. package/src/runtime/domain/assignment-observation.mjs +1 -0
  9. package/src/runtime/domain/background/supervisor/identity.mjs +5 -0
  10. package/src/runtime/domain/background/supervisor/supervisor.mjs +3 -4
  11. package/src/runtime/domain/background-service/ci-observation.domain.mjs +134 -0
  12. package/src/runtime/domain/background-service/ci-observation.ts +118 -0
  13. package/src/runtime/domain/background-service/managed-client.domain.mjs +6 -2
  14. package/src/runtime/domain/background-service/managed-client.ts +6 -2
  15. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +47 -7
  16. package/src/runtime/domain/background-service/managed-frontend.ts +36 -6
  17. package/src/runtime/domain/background-service/observed-waits.domain.mjs +36 -7
  18. package/src/runtime/domain/background-service/observed-waits.ts +33 -6
  19. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +3 -0
  20. package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +1 -0
  21. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +0 -2
  22. package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +0 -2
  23. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +6 -4
  24. package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +7 -4
  25. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +5 -12
  26. package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +5 -11
  27. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +53 -1
  28. package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +54 -1
  29. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +3 -3
  30. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +5 -5
  31. package/src/runtime/domain/background-service/supervisor/generated/identity.mjs +5 -0
  32. package/src/runtime/domain/background-service/supervisor/identity.domain.mjs +5 -0
  33. package/src/runtime/domain/background-service/supervisor/identity.ts +6 -0
  34. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +3 -4
  35. package/src/runtime/domain/background-service/supervisor/supervisor.ts +3 -4
  36. package/src/runtime/domain/catalog/catalog-schema.d.mts +6 -0
  37. package/src/runtime/domain/catalog/catalog-schema.mjs +1 -0
  38. package/src/runtime/domain/catalog/roles/role.supervisor.md +16 -0
  39. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +0 -2
  40. package/src/runtime/domain/coordinator/src/discovery.mjs +6 -4
  41. package/src/runtime/domain/coordinator/src/operations.mjs +5 -12
  42. package/src/runtime/domain/coordinator/src/schema.mjs +53 -1
  43. package/src/runtime/domain/coordinator/src/store.mjs +3 -3
  44. package/src/runtime/domain/subagents/catalog-schema.domain.mjs +1 -0
  45. package/src/runtime/domain/subagents/catalog-schema.ts +1 -0
  46. package/src/runtime/domain/subagents/cleanup.domain.mjs +7 -10
  47. package/src/runtime/domain/subagents/cleanup.ts +6 -8
  48. package/src/runtime/domain/subagents/package.json +1 -1
  49. package/src/runtime/domain/subagents/registry.domain.mjs +9 -7
  50. package/src/runtime/domain/subagents/registry.ts +11 -6
  51. package/src/runtime/domain/subagents/retained-result.domain.mjs +3 -3
  52. package/src/runtime/domain/subagents/retained-result.ts +2 -3
  53. package/src/runtime/domain/subagents/roles/role.supervisor.md +16 -0
  54. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +14 -2
  55. package/src/runtime/domain/subagents/shared-catalog.ts +14 -2
  56. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +3 -0
  57. package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +1 -0
  58. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +0 -2
  59. package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +0 -2
  60. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +6 -4
  61. package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +7 -4
  62. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +5 -12
  63. package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +5 -11
  64. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +53 -1
  65. package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +54 -1
  66. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +3 -3
  67. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +5 -5
  68. package/src/runtime/domain/subagents/supervisor-client.mjs +36 -0
  69. package/src/runtime/domain/subagents/worker-waits.domain.mjs +3 -4
  70. package/src/runtime/domain/subagents/worker-waits.ts +3 -3
  71. package/src/runtime/domain/subagents/workspace-files.domain.mjs +19 -5
  72. package/src/runtime/domain/subagents/workspace-files.ts +27 -5
  73. package/src/runtime/queries.ts +17 -3
  74. package/src/runtime/query-executor.ts +46 -3
  75. package/src/runtime/query-worker.mjs +6 -1
  76. package/src/runtime/read-model.ts +14 -5
  77. package/src/runtime/result-supervision.ts +16 -5
  78. package/src/runtime/shared-read-diagnosis.ts +29 -0
  79. package/src/runtime/supervisor-admission.ts +42 -0
  80. package/src/runtime/supervisor-decisions.ts +60 -0
  81. package/src/server.ts +9 -8
  82. package/src/version.ts +1 -1
@@ -0,0 +1,134 @@
1
+ // Generated fixed launch domain from packages/pi-better-background-tasks/src/ci-observation.ts. Do not edit directly.
2
+ import { readHarnessSetting } from "./shared-harness-settings.domain.mjs";
3
+ export const supervisorConsultTool = 'supervisor_consult';
4
+ export const supervisorRecoveryType = 'background-ci-observation-recovery';
5
+ /** Ask the existing Goal gate, including workflow holds, before waking an idle owner. */
6
+ export function requestCiRecoveryWake(pi, ctx, branchId, validUntil) {
7
+ let goalId = null;
8
+ for (const entry of ctx.sessionManager.getBranch()) {
9
+ if (entry.type !== 'custom' || !['pi-better-goal', 'pi-codex-goal'].includes(entry.customType))
10
+ continue;
11
+ const data = entry.data;
12
+ if (data?.kind === 'clear')
13
+ goalId = null;
14
+ if (data?.kind === 'set' && typeof data.goal?.goalId === 'string')
15
+ goalId = data.goal.goalId;
16
+ }
17
+ return new Promise(resolve => {
18
+ let timer;
19
+ let settled = false;
20
+ const finish = (current) => {
21
+ if (settled)
22
+ return;
23
+ settled = true;
24
+ clearTimeout(timer);
25
+ resolve(current);
26
+ };
27
+ timer = setTimeout(() => finish(() => goalId === null), 50);
28
+ try {
29
+ pi.events.emit('pi-better-goal:operation-resume-admission', {
30
+ version: 1,
31
+ owner: { sessionId: ctx.sessionManager.getSessionId(), workspace: ctx.cwd, branchId, goalId },
32
+ pending() {
33
+ if (settled)
34
+ return;
35
+ clearTimeout(timer);
36
+ timer = setTimeout(() => finish(() => false), Math.max(1, validUntil - Date.now()));
37
+ },
38
+ reply(gate) {
39
+ finish(() => gate?.allowed === true && gate.isCurrent?.() !== false);
40
+ },
41
+ });
42
+ }
43
+ catch {
44
+ finish(() => false);
45
+ }
46
+ });
47
+ }
48
+ export function ciObservationRevision(seams) {
49
+ try {
50
+ const setting = readHarnessSetting('supervisorMode', seams);
51
+ if (setting?.enabled === true && Array.isArray(setting.scenarios)
52
+ && setting.scenarios.every(id => typeof id === 'string') && setting.scenarios.includes('ci-observation'))
53
+ return typeof setting.revision === 'string' ? setting.revision : 'initial';
54
+ }
55
+ catch { /* An unreadable setting cannot enable a recovery. */ }
56
+ }
57
+ // Only the current Outcome entry and bounded criteria cross the native grant.
58
+ // Never send the branch transcript or infer an Outcome from tool output.
59
+ export function supervisorOutcome(branch) {
60
+ let entry;
61
+ for (let index = branch.length - 1; index >= 0; index--) {
62
+ const item = branch[index];
63
+ if (item?.type === 'custom' && item.customType === 'pi-better-harness:outcome') {
64
+ entry = item;
65
+ break;
66
+ }
67
+ }
68
+ const data = entry?.data;
69
+ if (!entry || data?.version !== 1 || data.outcome?.status !== 'active'
70
+ || typeof data.outcome.objective !== 'string' || !data.outcome.objective.trim())
71
+ return;
72
+ const lines = (value) => Array.isArray(value) ? value.filter(item => typeof item === 'string').slice(0, 8).map(item => item.slice(0, 400)) : [];
73
+ return { id: entry.id, objective: data.outcome.objective.slice(0, 2000), doneWhen: lines(data.outcome.doneWhen), boundaries: lines(data.outcome.boundaries) };
74
+ }
75
+ export function validCiRun(run) {
76
+ return /^[\w-]+\/[\w.-]+$/.test(run.repo) && !run.repo.endsWith('/.') && !run.repo.endsWith('/..')
77
+ && /^[1-9]\d{0,14}$/.test(run.runId) && Number.isSafeInteger(run.attempt) && run.attempt > 0;
78
+ }
79
+ // Accept a single invocation containing only literal, space-separated words.
80
+ // No shell parsing or execution is needed to identify the run.
81
+ export function ciObserverArgv(spec) {
82
+ if (spec.shell === false)
83
+ return spec.argv;
84
+ const command = spec.command;
85
+ if (typeof command !== 'string' || command.length > 4096 || /[^a-zA-Z0-9/@_., -]/.test(command))
86
+ return;
87
+ return command.trim().split(/ +/);
88
+ }
89
+ /** Recognize known observer invocations, never their stdout or a caller-supplied URL. */
90
+ export function ciRunFromArgv(kind, argv) {
91
+ const script = argv?.[1] ?? '';
92
+ const repositoryWatcher = /^(?:\.\/)?scripts\/watch-github-run\.mjs$/.test(script);
93
+ const installedWatcher = script.startsWith('/') && !script.split('/').includes('..')
94
+ && script.endsWith('/node_modules/@1aboveio/skills/skills/cicd/github-actions/scripts/watch-run.mjs');
95
+ if (kind === 'process' && argv?.[0] === 'node' && (repositoryWatcher || installedWatcher)) {
96
+ const options = new Map();
97
+ for (let i = 2; i < argv.length; i += 2) {
98
+ const flag = argv[i], value = argv[i + 1];
99
+ if (!flag || !value || !['--repo', '--run', '--interval-seconds'].includes(flag) || options.has(flag))
100
+ return;
101
+ options.set(flag, value);
102
+ }
103
+ const run = { repo: options.get('--repo')?.toLowerCase() ?? '', runId: options.get('--run') ?? '', attempt: 1 };
104
+ return validCiRun(run) ? run : undefined;
105
+ }
106
+ if (!argv || argv[0] !== 'gh' || argv[1] !== 'run'
107
+ || !(kind === 'watch' && argv[2] === 'view' || kind === 'process' && argv[2] === 'watch'))
108
+ return;
109
+ const runId = argv[3];
110
+ if (!/^[1-9]\d{0,14}$/.test(runId ?? ''))
111
+ return;
112
+ let repo, attempt = 1, pinned = false, json = false;
113
+ for (let i = 4; i < argv.length; i++) {
114
+ const flag = argv[i];
115
+ if (flag === '--exit-status' && kind === 'process')
116
+ continue;
117
+ const value = argv[++i];
118
+ if ((flag === '--repo' || flag === '-R') && !repo && /^(?:github\.com\/)?[\w-]+\/[\w.-]+$/.test(value ?? '')) {
119
+ repo = value.replace(/^github\.com\//, '').toLowerCase();
120
+ }
121
+ else if (kind === 'watch' && flag === '--attempt' && !pinned && /^[1-9]\d{0,4}$/.test(value ?? '')) {
122
+ attempt = Number(value);
123
+ pinned = true;
124
+ }
125
+ else if (kind === 'watch' && flag === '--json' && !json && /^[A-Za-z,]+$/.test(value ?? '')) {
126
+ json = true;
127
+ }
128
+ else
129
+ return;
130
+ }
131
+ const run = { repo: repo ?? '', runId: runId, attempt };
132
+ if (validCiRun(run) && (kind !== 'watch' || json))
133
+ return run;
134
+ }
@@ -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
+ }
@@ -7,6 +7,7 @@ import { backgroundDigest, backgroundParametersDigest } from "./managed-authorit
7
7
  import { readAdmissionStartToken, readProcessStartTokenFresh } from "./process-identity.domain.mjs";
8
8
  import { currentForegroundSandboxPolicy, FOREGROUND_SANDBOX_POLICY_CHANNEL } from "./sandbox.domain.mjs";
9
9
  import { backgroundListNeedsHistory, backgroundObservation } from "./work-observation.domain.mjs";
10
+ import { supervisorConsultTool, supervisorOutcome } from "./ci-observation.domain.mjs";
10
11
  /** Native host proof carries scope and captured policy, never a transcript or module path. */
11
12
  export async function requestBackgroundTool(pi, ctx, key, tool, params, parameters, signal) {
12
13
  if (signal?.aborted)
@@ -42,7 +43,8 @@ export async function requestBackgroundTool(pi, ctx, key, tool, params, paramete
42
43
  try {
43
44
  const hello = await client.ready;
44
45
  const policy = currentForegroundSandboxPolicy(pi);
45
- const branchIds = ctx.sessionManager.getBranch().map(entry => entry.id).filter((value) => typeof value === 'string');
46
+ const branch = ctx.sessionManager.getBranch();
47
+ const branchIds = branch.map(entry => entry.id).filter((value) => typeof value === 'string');
46
48
  const sessionId = ctx.sessionManager.getSessionId();
47
49
  if (!sessionId)
48
50
  throw new Error('Background tools require a native session identity');
@@ -50,7 +52,9 @@ export async function requestBackgroundTool(pi, ctx, key, tool, params, paramete
50
52
  const start = version === 2 ? readAdmissionStartToken(process.pid) : readProcessStartTokenFresh(process.pid);
51
53
  const record = { version, id, secretHash: createHash('sha256').update(secret).digest('hex'), instanceId: hello.instanceId,
52
54
  owner: { kind: 'parent-session', sessionId, workspace: realpathSync(ctx.cwd) }, branchIds, projectTrusted: ctx.isProjectTrusted(),
53
- pid: process.pid, start, key, tool, params, parametersDigest: parameters === undefined ? undefined : backgroundParametersDigest(parameters), policy };
55
+ pid: process.pid, start, key, tool, params, parametersDigest: parameters === undefined ? undefined : backgroundParametersDigest(parameters), policy,
56
+ supervisorOutcome: ['bg_task_spawn', 'bg_task_watch', 'bg_task', '__background_poll', '__background_receipt', supervisorConsultTool].includes(tool)
57
+ ? supervisorOutcome(branch) : undefined };
54
58
  const staged = `${path}.tmp`;
55
59
  writeFileSync(staged, JSON.stringify(record), { flag: 'wx', mode: 0o600 });
56
60
  renameSync(staged, path);
@@ -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 branchIds = ctx.sessionManager.getBranch().map(entry => entry.id).filter((value): value is string => typeof value === 'string');
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);
@@ -1,10 +1,12 @@
1
1
  // Generated fixed launch domain from packages/pi-better-background-tasks/src/managed-frontend.ts. Do not edit directly.
2
2
  import { randomUUID } from 'node:crypto';
3
+ import { Type } from 'typebox';
3
4
  import { requestBackgroundTool } from "./managed-client.domain.mjs";
4
5
  import { onBackgroundObservation } from "./work-observation.domain.mjs";
5
6
  import { getCallbackBatcher } from "./shared-callback-batcher.domain.mjs";
6
7
  import { registerObservedWaitClient } from "./observed-wait-client.domain.mjs";
7
8
  import { observeNavigatorLaunch } from "./shared-navigator.domain.mjs";
9
+ import { ciObservationRevision, requestCiRecoveryWake, supervisorConsultTool, supervisorOutcome, supervisorRecoveryType } from "./ci-observation.domain.mjs";
8
10
  /** Native transcript delivery and cached UI projections; no coordinator or supervisor. */
9
11
  export function createManagedBackgroundFrontend(pi) {
10
12
  let ctx, generation = 0, refresh, dirty = false;
@@ -139,7 +141,12 @@ export function createManagedBackgroundFrontend(pi) {
139
141
  continue;
140
142
  const n = item.notification;
141
143
  const type = n.event?.customType;
142
- if ((type === 'background-task-stall' || type === 'background-wait-review')
144
+ const recovery = type === supervisorRecoveryType;
145
+ const recoveryProof = () => captured.sessionManager.getBranch().some((entry) => {
146
+ const message = entry.type === 'custom_message' ? entry : entry.message;
147
+ return message?.customType === type && message.details?.urgentEventId === item.receiptId;
148
+ });
149
+ if (!(recovery && recoveryProof()) && (type === 'background-task-stall' || type === 'background-wait-review' || recovery)
143
150
  && (!rechecking?.has(item.receiptId) || !captured.isIdle())) {
144
151
  // Keep the candidate here while busy. Pi's followUp queue cannot
145
152
  // revalidate it when the current turn eventually ends.
@@ -155,7 +162,7 @@ export function createManagedBackgroundFrontend(pi) {
155
162
  .finally(() => { queued.delete(item.token); if (ctx === captured)
156
163
  void reconcile().catch(() => undefined); });
157
164
  };
158
- const proof = captured.sessionManager.getBranch().some((entry) => {
165
+ const proof = recovery ? recoveryProof() : captured.sessionManager.getBranch().some((entry) => {
159
166
  const message = entry.type === 'custom_message' ? entry : entry.message;
160
167
  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);
161
168
  });
@@ -165,13 +172,35 @@ export function createManagedBackgroundFrontend(pi) {
165
172
  }
166
173
  trace('queue', { ...facts, urgent: n.urgent === true, recipientActive: active(n.origin, n.branchId) });
167
174
  if (n.urgent) {
168
- const handoff = getCallbackBatcher(pi).deliverUrgent({ ...n.event, receiptId: item.receiptId,
169
- getSuppressionReason: () => active(n.origin, n.branchId) ? undefined : 'The originating session or branch is no longer active',
170
- onDelivered: () => receipt(true), onSuppressed: reason => receipt(false, reason) });
171
175
  const retry = () => { queued.delete(item.token); if (version === generation)
172
176
  scheduleHandoffPoll(1000); };
173
- void Promise.resolve(handoff).then(ok => { if (!ok)
174
- retry(); }, retry);
177
+ const deliver = (wake) => {
178
+ if (recovery && (version !== generation || !wake?.())) {
179
+ retry();
180
+ return;
181
+ }
182
+ const handoff = getCallbackBatcher(pi).deliverUrgent({ ...n.event, receiptId: item.receiptId,
183
+ getSuppressionReason: () => {
184
+ if (!active(n.origin, n.branchId))
185
+ return 'The originating session or branch is no longer active';
186
+ if (recovery && (typeof n.settingRevision !== 'string' || ciObservationRevision() !== n.settingRevision || supervisorOutcome(captured.sessionManager.getBranch())?.id !== n.outcomeId
187
+ || !captured.isIdle() || Date.now() >= n.validUntil || !wake?.()))
188
+ return 'CI recovery needs fresh settings, Outcome, or remote evidence';
189
+ },
190
+ onDelivered: () => { if (!recovery || recoveryProof())
191
+ receipt(true);
192
+ else
193
+ retry(); },
194
+ onSuppressed: reason => receipt(false, reason) });
195
+ void Promise.resolve(handoff).then(ok => { if (!ok)
196
+ retry(); }, retry);
197
+ };
198
+ // A workflow can asynchronously check its gate. Ordinary
199
+ // completions and the foreground refresh must not wait on it.
200
+ if (recovery)
201
+ void requestCiRecoveryWake(pi, captured, n.branchId, n.validUntil).then(deliver).catch(retry);
202
+ else
203
+ deliver();
175
204
  continue;
176
205
  }
177
206
  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,
@@ -260,6 +289,17 @@ export function createManagedBackgroundFrontend(pi) {
260
289
  },
261
290
  };
262
291
  registerObservedWaitClient(pi, host);
292
+ pi.registerTool({
293
+ name: supervisorConsultTool, label: 'Consult Supervisor',
294
+ 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.',
295
+ parameters: Type.Object({ id: Type.String({ description: 'Background watcher task ID' }) }),
296
+ async execute(id, params, signal, _update, context) {
297
+ adoptContext(context);
298
+ const result = await requestBackgroundTool(pi, context, id, supervisorConsultTool, params, undefined, signal);
299
+ await host.reconcileNow().catch(() => undefined);
300
+ return result;
301
+ },
302
+ });
263
303
  pi.events?.on?.('pi-better-background-tasks:managed-capability', (request) => { if (ctx && typeof request?.accept === 'function')
264
304
  request.accept({ version: 1, assignmentContinuation: 1 }); });
265
305
  onBackgroundObservation(pi, () => { details.clear(); logs.clear(); void reconcile().catch(() => undefined); });
@@ -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
- if ((type === 'background-task-stall' || type === 'background-wait-review')
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
- void Promise.resolve(handoff).then(ok => { if (!ok) retry(); }, retry);
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) {
@@ -35,8 +35,9 @@ import { currentProcessStartToken, readProcessStartToken } from "./process-ident
35
35
  import { assertBackgroundExecutionAllowed, backgroundExecutionLimits, confineCommandSpec, resolveForegroundSandboxPlan, currentForegroundSandboxPolicy, resolveWorkerSandboxPlan, sandboxProvenance, } from "./sandbox.domain.mjs";
36
36
  import { openStore, cancellationCredential, } from "./shared-operation-coordinator/index.domain.mjs";
37
37
  import { createLocalSupervisor, defaultSupervisorDirectory, supervisorPaths, supervisorTaskIdForToken, } from "./supervisor/index.domain.mjs";
38
- import { processGroupAlive } from "./supervisor/identity.domain.mjs";
38
+ import { processGroupExitVerified } from "./supervisor/identity.domain.mjs";
39
39
  import { readStopRequest, writeTextAtomic } from "./supervisor/store.domain.mjs";
40
+ import { ciObserverArgv, ciRunFromArgv, validCiRun } from "./ci-observation.domain.mjs";
40
41
  export const OBSERVED_WAITS_SERVICE_VERSION = 2;
41
42
  export const OBSERVED_WAITS_SERVICE_CHANNEL = "pi-better-background-tasks:observed-waits-service";
42
43
  export const OBSERVED_WAITS_SERVICE_REQUEST_CHANNEL = "pi-better-background-tasks:observed-waits-service-request";
@@ -787,11 +788,14 @@ export class ObservedWaitHost {
787
788
  return;
788
789
  this.authorityPassCache = new Map();
789
790
  try {
790
- const discovery = this.options.serverOwnedResults ? undefined : this.store.readDiscoveryState(this.discoveryScope);
791
+ const discovery = this.options.serverOwnedResults ? undefined : this.store.readDiscoveryState(this.discoveryScope, this.hostId);
791
792
  if (this.options.serverOwnedResults || discovery?.managed) {
792
793
  this.releaseDiscoveryAuthority();
793
- if (!this.options.serverOwnedResults)
794
+ if (!this.options.serverOwnedResults) {
794
795
  this.reconcileFollowerRunning();
796
+ if (discovery?.cleanupPending)
797
+ await this.reconcileAssignmentCleanup();
798
+ }
795
799
  this.reconcileOwnerChanges();
796
800
  this.retryPendingTerminalCallbacks();
797
801
  await this.dispatchOutbox();
@@ -802,13 +806,13 @@ export class ObservedWaitHost {
802
806
  if (role === "holder") {
803
807
  this.discoverObservedTasks();
804
808
  this.reconcileGlobalRunning();
805
- if (discovery.hasAssignmentTasks)
806
- await this.reconcileAssignmentCleanup();
807
809
  }
808
810
  else {
809
811
  this.reconcileFollowerRunning();
810
812
  this.reconcileOwnerChanges();
811
813
  }
814
+ if (discovery?.cleanupPending)
815
+ await this.reconcileAssignmentCleanup();
812
816
  this.retryPendingTerminalCallbacks();
813
817
  await this.dispatchOutbox();
814
818
  }
@@ -818,7 +822,7 @@ export class ObservedWaitHost {
818
822
  }
819
823
  async reconcileAssignmentCleanup() {
820
824
  const store = this.requireStore();
821
- const [candidate] = store.listAssignmentCleanupOperations(1, this.assignmentCleanupCursor);
825
+ const [candidate] = store.listAssignmentCleanupOperations(1, this.assignmentCleanupCursor, this.hostId);
822
826
  this.assignmentCleanupCursor = candidate?.operationId;
823
827
  if (!candidate || candidate.resultManaged || this.supervisionAuthority(candidate) !== "self")
824
828
  return;
@@ -832,7 +836,7 @@ export class ObservedWaitHost {
832
836
  if (inspection.status !== "lost" && inspection.result?.groupCleanup !== "unproven")
833
837
  return;
834
838
  const pgid = inspection.command?.pgid ?? inspection.command?.pid;
835
- if (inspection.cleanup?.groupEmpty === true || (pgid && !processGroupAlive(pgid))) {
839
+ if (processGroupExitVerified(pgid, inspection.cleanup?.groupEmpty)) {
836
840
  store.verifyAssignmentCleanup(candidate.operationId, launchToken, candidate.terminalRevision);
837
841
  return;
838
842
  }
@@ -1030,6 +1034,9 @@ export class ObservedWaitHost {
1030
1034
  authorityRef: this.parentAuthority(owner, prepared.plan),
1031
1035
  intentRef: typeof input.params.operation_id === "string" ? input.params.operation_id : null,
1032
1036
  });
1037
+ const outcomeId = this.options.currentOutcomeId?.();
1038
+ const ciRun = outcomeId && !prepared.spec.env && prepared.cwd === owner.workspace
1039
+ ? ciRunFromArgv(input.kind, ciObserverArgv(prepared.spec)) : undefined;
1033
1040
  const launchContext = {
1034
1041
  kind: input.kind,
1035
1042
  parentOrigin: this.parentOrigin,
@@ -1042,6 +1049,7 @@ export class ObservedWaitHost {
1042
1049
  sandbox: prepared.provenance,
1043
1050
  supervisionPolicy: prepared.plan,
1044
1051
  branchId: owner.branchId ?? null,
1052
+ ...(ciRun && outcomeId ? { ciObservation: { ...ciRun, outcomeId } } : {}),
1045
1053
  };
1046
1054
  // Persist supervision metadata outside the task execution record so a
1047
1055
  // replacement host can still notify the right parent and never re-route a
@@ -1313,6 +1321,25 @@ export class ObservedWaitHost {
1313
1321
  this.projectionMetrics.projectionsBuilt += 1;
1314
1322
  return this.projectDurable(operation, now);
1315
1323
  }
1324
+ /** Resolve exact owner and immutable launch/terminal evidence, not a display projection. */
1325
+ ciObservation(origin, taskId, outcomeId, branchIds) {
1326
+ if (!LOCAL_DURABLE_ID.test(taskId))
1327
+ return;
1328
+ const operation = this.operationForTask(taskId);
1329
+ if (!operation || !this.belongsToParentOrigin(operation, origin)
1330
+ || !operation.owner.branchId || !branchIds.includes(operation.owner.branchId))
1331
+ return;
1332
+ const directory = this.observationDirectory(operation);
1333
+ if (!directory)
1334
+ return;
1335
+ const context = this.readLaunchContext(taskId, directory);
1336
+ if (!context?.ciObservation || context.ciObservation.outcomeId !== outcomeId || context.dismissedAt !== undefined)
1337
+ return;
1338
+ const inspection = this.passiveSnapshot(taskId, directory);
1339
+ if (!inspection || inspection.token !== operation.launchToken)
1340
+ return;
1341
+ return { run: context.ciObservation, operation, inspection, policy: context.supervisionPolicy, callback: context.callback };
1342
+ }
1316
1343
  /** Rebuild a live incident from the runner checkpoint. Only the native handoff writes its receipt. */
1317
1344
  pendingStallAlert(origin, taskId, waits) {
1318
1345
  const operation = this.operationForTask(taskId);
@@ -4078,6 +4105,8 @@ export class ObservedWaitHost {
4078
4105
  ...(value.supervisionPolicy && typeof value.supervisionPolicy === "object"
4079
4106
  ? { supervisionPolicy: value.supervisionPolicy } : {}),
4080
4107
  ...(typeof value.branchId === "string" || value.branchId === null ? { branchId: value.branchId } : {}),
4108
+ ...(value.ciObservation && typeof value.ciObservation.outcomeId === "string" && validCiRun(value.ciObservation)
4109
+ ? { ciObservation: value.ciObservation } : {}),
4081
4110
  ...(typeof value.callbackPendingAt === "number" ? { callbackPendingAt: value.callbackPendingAt } : {}),
4082
4111
  ...(typeof value.callbackDeliveredAt === "number" ? { callbackDeliveredAt: value.callbackDeliveredAt }
4083
4112
  : typeof value.callbackNotifiedAt === "number"