pi-better-background-tasks 0.9.1 → 0.10.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/README.md CHANGED
@@ -17,47 +17,45 @@ Use `pi-better-background-tasks` when a command should keep running while the fo
17
17
  - Keep task metadata and logs available across reloads.
18
18
  - Retain completed task artifacts for seven days, then remove them during rate-limited maintenance.
19
19
  - Show active work in Pi's background-work navigator.
20
- - Flag running tasks with no observable output or completed poll as stalled.
20
+ - Report quiet work and suspected stalls separately from task lifecycle.
21
21
  - Confine local task writes to the project directory when `pi-better-sandbox` is enabled.
22
22
 
23
23
  ## Write Sandbox
24
24
 
25
25
  When [`pi-better-sandbox`](https://github.com/1aboveio/pi-better-harness/tree/main/packages/pi-better-sandbox#readme)
26
- is installed and enabled, every **local** task captures
27
- the effective foreground policy at launch and runs under the platform's write
28
- sandbox: reads and network stay unrestricted, writes are confined to the
29
- canonical project directory, and denied paths stay denied.
30
-
31
- The policy is captured once, when the task starts. The foreground sandbox is
32
- inactive by default, so local tasks ordinarily launch unconfined. A later
33
- `/sandbox on`, `/sandbox off`, `/sandbox default on|off`, or a deny-rule change
34
- reaches tasks launched after it; a task
35
- already running — including a watcher resumed in a later Pi session — keeps the
36
- policy it started with.
37
-
38
- If the foreground sandbox reports `unavailable` or `failed`, a local launch is
39
- refused with an explanation instead of running unconfined. `/sandbox off` is the
40
- deliberate way to run local tasks unsandboxed.
41
-
42
- A task follows Main's permission profile. With Main's Outside project = Write, the
43
- task writes across home and temp but can remove files outside the project only in
44
- temp, hidden home directories, and worktree folders (see
26
+ is installed, local tasks follow the independent **Background tasks** column in
27
+ `/sandbox`. Its Sandbox switch starts Off for fresh settings. When enabled,
28
+ commands run under macOS Seatbelt or Linux Bubblewrap with that column's project,
29
+ outside-project, credential-file, command and network permissions. Protected
30
+ paths remain denied.
31
+
32
+ The policy is captured once at launch. Later settings changes affect only new
33
+ tasks. An existing process, including a watcher resumed in a later Pi session,
34
+ keeps its launch policy. `/sandbox on|off` and `/sandbox default on|off` now
35
+ change Main only; use the Background tasks column to change new task launches.
36
+ Older settings migrate by copying Main's values into Background tasks once.
37
+
38
+ If the Background policy is `unavailable` or `failed`, launch is refused rather
39
+ than retried unconfined. Turning its Sandbox switch Off deliberately permits
40
+ unconfined local launches.
41
+
42
+ With Background tasks' Outside project = Write, the task can write across home
43
+ and temp but can remove files outside the project only in temp, hidden home
44
+ directories, and worktree folders (see
45
45
  [pi-better-sandbox](https://github.com/1aboveio/pi-better-harness/tree/main/packages/pi-better-sandbox#readme)).
46
- On macOS, a task launched with Outside project = Write or Write & delete starts an
47
- APFS local snapshot (`tmutil localsnapshot`) in the background as a recovery aid.
48
- A failed snapshot is noted in the task log and never blocks the task.
49
-
50
- Structured remote SSH tasks are unaffected: the foreground sandbox describes this
51
- machine, and remote work keeps its existing remote semantics. Without
52
- `pi-better-sandbox` installed, local tasks behave exactly as they always have.
53
-
54
- Reads and network access are never restricted; only writes are. Pi's own
55
- process, `pi.exec` calls, and unrelated third-party extension code stay outside
56
- the guarantee, and confinement is per surface: a confined process on another
57
- first-party surface can still write this one's task registry. Installing
58
- [`pi-better-harness`](https://github.com/1aboveio/pi-better-harness/tree/main/packages/pi-better-harness#readme)
59
- installs the sandbox extension, but leaves foreground tools and local background
60
- tasks inactive until a human opts in.
46
+ On macOS, Outside project = Write or Write & delete starts an APFS local snapshot
47
+ (`tmutil localsnapshot`) as a recovery aid. A failed snapshot is noted in the log
48
+ and never blocks execution.
49
+
50
+ Structured SSH cannot apply local file and credential permissions remotely, so
51
+ an enabled permission-aware Background profile refuses those launches. When
52
+ unconfined, SSH retains its documented remote behavior; local policy never
53
+ establishes remote confinement. Without the sandbox extension, local tasks
54
+ retain their historical unconfined behavior.
55
+
56
+ Pi's own process, provider transport, `pi.exec` calls, and unrelated runtime
57
+ extensions remain outside the task boundary. Installing the harness does not
58
+ activate Main or Background confinement by default.
61
59
 
62
60
  ## Remote SSH
63
61
 
@@ -105,6 +103,61 @@ is recorded as finished, and its callback is delivered when its session resumes.
105
103
  If you quit Pi first, nothing records that exit: when the session is resumed in a
106
104
  new Pi process, a task whose process is gone is marked lost.
107
105
 
106
+ ## Progress And Suspected Stalls
107
+
108
+ A task can remain `running` without recent progress evidence. Compact status and
109
+ navigator use the same observation. Process tasks use recorded progress and the
110
+ log's modification time. Watches use recorded progress and completed polls. Before
111
+ any progress, the task's launch time anchors the silence duration. This does not
112
+ measure CPU activity, network waits, or useful application work.
113
+
114
+ At 60 seconds without observed progress, work is `quiet`. At 5 minutes, it has a
115
+ `suspected stall`. Both thresholds are inclusive. Set `PI_BETTER_STALL_QUIET_MS`
116
+ and `PI_BETTER_STALL_MS` to positive millisecond durations to override them.
117
+ Compact status shows the last observed time, silence duration, and a warning:
118
+ silence alone does not prove the task is hung. Terminal tasks are not reported as
119
+ suspected stalls. New output or a completed watch poll refreshes the observation.
120
+
121
+ A status cursor changes when the observation crosses either threshold, even if
122
+ metadata and log bytes have not changed. Within the same observation state,
123
+ unchanged status still shows the current silence duration. A suspected stall
124
+ records an observation, not a process failure. After the existing 60-second
125
+ attention grace, callback-enabled tasks wake the parent once per silent spell.
126
+ New progress closes the observation and a later spell can notify again. Quiet
127
+ work does not alert, `callback:false` suppresses notification, and no silence
128
+ threshold stops a task or changes its lifecycle. The active session's runtime
129
+ checks observations once per second, including an in-flight watch poll. Reload
130
+ restores monitoring and the persisted attention receipts. Log-retention writes
131
+ are excluded from task progress.
132
+
133
+ ## Launch Policy And Diagnostics
134
+
135
+ `/sandbox` has an independent **Background tasks** column. New tasks capture
136
+ that column at launch; subsequent changes do not alter an existing process or
137
+ its future watch polls. Older saved settings copy Main into Background tasks
138
+ once so the migration preserves behavior. Older sandbox publishers without the
139
+ Background field retain their Main-policy behavior.
140
+
141
+ Launch and status show `confined`, `unconfined`, or `unknown`, plus the backend
142
+ when known and the policy source. `verbose:true` includes the persisted policy
143
+ summary. Restored tasks without recorded launch evidence report `unknown`;
144
+ missing profile files or current process-tool denials are not confinement proof.
145
+ Remote execution also reports unknown remote confinement.
146
+
147
+ Use `bg_task_status` with `diagnostics:true` (or either wrapper's `status`
148
+ action) for a bounded, current process snapshot. Both Main and Background tasks
149
+ must currently permit **Process access: Read**, even when sandbox switches are
150
+ Off. The result checks the recorded PID and start identity, then reports process
151
+ state, accumulated CPU time, and available wait evidence. It never reads command
152
+ arguments or environment values and never probes a remote host or descendants.
153
+ A snapshot cannot establish useful work or a hang. Watch poll PIDs are not
154
+ retained, so their activity evidence is explicitly unavailable.
155
+
156
+ The process-activity adapter is unavailable under Main confinement; it never
157
+ retries `ps` unconfined. Unsupported systems, absent launch identities, reused
158
+ PIDs, and blocked diagnostics each receive a separate explanation. Diagnostics
159
+ permissions do not change or describe the task's launch-time confinement.
160
+
108
161
  ## Watch conditions
109
162
 
110
163
  JSON conditions require a root-prefixed path, such as `$.status` or
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-background-tasks",
3
- "version": "0.9.1",
3
+ "version": "0.10.0",
4
4
  "description": "Pi extension for durable background shell tasks, watchers, logs, and status inspection.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -0,0 +1,55 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { inspectMeta } from "./registry.js";
3
+
4
+ /** Optional-peer contract, mirrored by pi-better-sandbox/background-admission.ts. */
5
+ export const BACKGROUND_ADAPTER_REQUEST = "pi-better-background-tasks:adapter-request";
6
+ export const BACKGROUND_ADAPTER_VERSION = 1;
7
+
8
+ type Admission = "local-launch" | "registry";
9
+ type Request = {
10
+ version: number;
11
+ name: string;
12
+ input: unknown;
13
+ reply(value: { version: number; parameters: object; admission: Admission }): void;
14
+ };
15
+
16
+ /** The schemas belong to one registerTools invocation, never to a module singleton. */
17
+ export function advertiseBackgroundAdapter(pi: ExtensionAPI, schemas: ReadonlyMap<string, object>): void {
18
+ const unsubscribe = pi.events?.on(BACKGROUND_ADAPTER_REQUEST, (data: unknown) => {
19
+ const request = data as Partial<Request> | undefined;
20
+ if (request?.version !== BACKGROUND_ADAPTER_VERSION || typeof request.name !== "string" ||
21
+ typeof request.reply !== "function") return;
22
+ const parameters = schemas.get(request.name);
23
+ if (!parameters) return;
24
+ const admission = classify(request.name, request.input);
25
+ if (admission) request.reply({ version: BACKGROUND_ADAPTER_VERSION, parameters, admission });
26
+ });
27
+ pi.on("session_shutdown", () => { if (typeof unsubscribe === "function") unsubscribe(); });
28
+ }
29
+
30
+ function classify(name: string, input: unknown): Admission | undefined {
31
+ if (!input || typeof input !== "object" || Array.isArray(input)) return;
32
+ const params = input as Record<string, unknown>;
33
+ let action: unknown;
34
+ switch (name) {
35
+ case "bg_task_spawn": action = "spawn"; break;
36
+ case "bg_task_watch": action = "watch"; break;
37
+ case "bg_task_list": action = "list"; break;
38
+ case "bg_task_status": action = "status"; break;
39
+ case "bg_task_log": action = "log"; break;
40
+ case "bg_task_stop": action = "stop"; break;
41
+ case "bg_task": action = params.action; break;
42
+ case "bg_status":
43
+ if (params.action === "spawn" || params.action === "watch") return;
44
+ action = params.action;
45
+ break;
46
+ default: return;
47
+ }
48
+ if (action === "spawn" || action === "watch") return params.ssh ? undefined : "local-launch";
49
+ if (action === "list" || action === "status" || action === "log" || action === "clear") return "registry";
50
+ if (action !== "stop" || typeof params.id !== "string" || !params.id) return;
51
+ // Never trust caller flags about locality. Missing/corrupt metadata is not proof
52
+ // of a local stop; a remote stop can execute SSH in the trusted Pi process.
53
+ const meta = inspectMeta(params.id).meta;
54
+ if (meta && !meta.ssh && !meta.remote && (meta.kind === "process" || meta.kind === "command_watch")) return "registry";
55
+ }
@@ -15,7 +15,7 @@ import { failurePath, failureView } from "./failures.js";
15
15
  import { readLog } from "./logs.js";
16
16
  import { listMetasForOrigin, onMetaChanged, readMeta, writeMeta } from "./registry.js";
17
17
  import { stopTask } from "./runtime.js";
18
- import { observeBackgroundTaskStall } from "./stall.js";
18
+ import { formatBackgroundTaskStall, observeBackgroundTaskStall } from "./stall.js";
19
19
  import type { BackgroundTaskCallbackOrigin, BackgroundTaskMeta, BackgroundTaskStatus } from "./types.js";
20
20
 
21
21
  let unregister: (() => void) | undefined;
@@ -152,8 +152,8 @@ function detailFromMeta(meta: BackgroundTaskMeta | undefined, now: number, optio
152
152
  if (meta.deadlineAt) metadata.push({ label: "deadline", value: formatDuration(meta.deadlineAt - now) });
153
153
  if (meta.lastCheckedAt) metadata.push({ label: "checked", value: `${formatDuration(now - meta.lastCheckedAt)} ago` });
154
154
  if (meta.status === "running") {
155
- const stall = observeBackgroundTaskStall(meta, now);
156
- if (stall.state !== "healthy") metadata.push({ label: "activity", value: stall.state });
155
+ const activity = formatBackgroundTaskStall(observeBackgroundTaskStall(meta, now));
156
+ if (activity) metadata.push({ label: "activity", value: activity });
157
157
  }
158
158
  if (meta.lastExitCode !== undefined) metadata.push({ label: "exit", value: String(meta.lastExitCode) });
159
159
  if (meta.error) metadata.push({ label: "error", value: meta.error });
@@ -223,9 +223,8 @@ function factsForMeta(meta: BackgroundTaskMeta, now: number): string[] {
223
223
  const incident = actionableFailures(readFailureState(failurePath(meta.id)))[0];
224
224
  if (incident) facts.push(`${failureLabel(incident)}: ${incident.summary}`);
225
225
  if (meta.status === "running") {
226
- const stall = observeBackgroundTaskStall(meta, now);
227
- if (stall.state === "stalled") facts.push("stalled");
228
- else if (stall.state === "quiet") facts.push("quiet");
226
+ const activity = formatBackgroundTaskStall(observeBackgroundTaskStall(meta, now));
227
+ if (activity) facts.push(activity);
229
228
  }
230
229
  if (meta.kind === "command_watch" && meta.intervalMs) facts.push(`every ${formatDuration(meta.intervalMs)}`);
231
230
  if (meta.deadlineAt && meta.status === "running") facts.push(`${formatDuration(meta.deadlineAt - now)} left`);
package/src/output.ts CHANGED
@@ -10,8 +10,11 @@ import {
10
10
  incidentResource,
11
11
  incidentVerbatimPage,
12
12
  isIncidentCursor,
13
+ pendingAttentionNote,
14
+ pendingFailureAttention,
13
15
  quietFailureLine,
14
16
  readFailureState,
17
+ terminalFailureParts,
15
18
  scopedFailures,
16
19
  type FailureState,
17
20
  type IncidentDetail,
@@ -40,6 +43,9 @@ import {
40
43
  import { failurePath } from "./failures.js";
41
44
  import { captureGapsFor, pageTaskLog, readLog, type LogRead } from "./logs.js";
42
45
  import { belongsToOrigin, inspectMeta, listTaskRecords, originOf, type MetaInspection } from "./registry.js";
46
+ import { formatBackgroundTaskStall, observeBackgroundTaskStall } from "./stall.js";
47
+ import type { TaskProcessDiagnostics } from "./task-diagnostics.js";
48
+ import type { StallObservation } from "./shared-stall-detector.js";
43
49
  import type { BackgroundTaskCallbackOrigin, BackgroundTaskMeta, Condition, FirstWatchCheck } from "./types.js";
44
50
 
45
51
  /** The launch tool stopped waiting while a watch's first check was still running (#359). */
@@ -75,6 +81,7 @@ const LIST_LEAD_PREVIEW_BYTES = 200;
75
81
  export type BackgroundOutputSurface = keyof typeof BACKGROUND_OUTPUT_BUDGET_BYTES;
76
82
 
77
83
  export interface OutputOptions {
84
+ processDiagnostics?: TaskProcessDiagnostics;
78
85
  cursor?: string;
79
86
  maxBytes?: number;
80
87
  verbose?: boolean;
@@ -237,7 +244,9 @@ export function formatCallbackFacts(meta: BackgroundTaskMeta): {
237
244
  incidentCount?: number;
238
245
  } {
239
246
  const state = failureStateFor(meta.id);
240
- const rows = formatFailureLines(state);
247
+ const pending = pendingFailureAttention(state, Date.now(), { terminal: true });
248
+ const incidents = pending?.incidents ?? [];
249
+ const rows = terminalFailureParts(state, incidents).rows;
241
250
  const gapLines = [
242
251
  meta.logDiscardedBytes ? `retention discarded ${meta.logDiscardedBytes} bytes; not recoverable` : undefined,
243
252
  meta.captureDiscardedBytes ? `capture overflow discarded ${meta.captureDiscardedBytes} bytes; not full history` : undefined,
@@ -245,8 +254,8 @@ export function formatCallbackFacts(meta: BackgroundTaskMeta): {
245
254
  // History (expected and closed incidents) is not a row, but the callback still says it exists, so a
246
255
  // declared expected exit is not read as a plain failure. It leads the decision: a tight callback
247
256
  // budget keeps a prefix of the decision, and this short line must survive it (#332).
248
- const history = rows.length ? historyTailLine(state) : quietFailureLine(state);
249
- const decision = [history, formatDecision(meta), ...gapLines].filter(Boolean).join("\n") || undefined;
257
+ const history = actionableFailures(state).length ? historyTailLine(state) : quietFailureLine(state);
258
+ const decision = [history, pendingAttentionNote(state, incidents), formatDecision(meta), ...gapLines].filter(Boolean).join("\n") || undefined;
250
259
  return {
251
260
  outcome: meta.status,
252
261
  ...(rows.length ? { failureRows: rows, incidentCount: rows.length } : {}),
@@ -271,6 +280,28 @@ function formatDiagnostics(meta: BackgroundTaskMeta, extra: string[] = []): stri
271
280
  return lines.length ? lines.join("\n") : undefined;
272
281
  }
273
282
 
283
+ function formatProcessDiagnostics(diagnostics: TaskProcessDiagnostics | undefined): string | undefined {
284
+ if (!diagnostics) return undefined;
285
+ const facts = diagnostics.availability === "available" && diagnostics.identity === "matches"
286
+ ? `identity matches; state=${diagnostics.state}; CPU=${diagnostics.cpuTime}; wait=${diagnostics.waitChannel}`
287
+ : diagnostics.reason ?? diagnostics.availability;
288
+ return `process diagnostics: ${facts}\nA snapshot cannot prove useful work or a hang.`;
289
+ }
290
+
291
+ function formatLaunchSandbox(meta: BackgroundTaskMeta): string | undefined {
292
+ const sandbox = meta.sandbox;
293
+ if (!sandbox) return "sandbox: unknown; launch-time policy was not recorded.";
294
+ const backend = sandbox.backend ? `; ${oneLine(sandbox.backend, 40)}` : "";
295
+ return `sandbox: ${sandbox.confinement}${backend}; source: ${oneLine(sandbox.policySource, 80)}; later changes do not affect this task.`;
296
+ }
297
+
298
+ function formatStaleProgress(stall: StallObservation | undefined): string | undefined {
299
+ if (!stall) return undefined;
300
+ const summary = formatBackgroundTaskStall(stall);
301
+ if (!summary) return undefined;
302
+ return `progress: ${summary}; last observed: ${new Date(stall.observedAt!).toISOString()}.\nSilence alone does not prove the task is hung.`;
303
+ }
304
+
274
305
  function formatProgress(meta: BackgroundTaskMeta): string | undefined {
275
306
  const lines = [`kind: ${meta.kind}`];
276
307
  if (meta.name) lines.push(`name: ${oneLine(meta.name, 80)}`);
@@ -289,8 +320,10 @@ function identityLine(meta: BackgroundTaskMeta): string {
289
320
  }
290
321
 
291
322
  /** Lifecycle, result, and retained-log facts. A deleted or rewritten log is a change. */
292
- function contentRevision(meta: BackgroundTaskMeta): string {
323
+ function contentRevision(meta: BackgroundTaskMeta, stall?: StallObservation): string {
293
324
  return lifecycleContentRevision([
325
+ stall ? [stall.state, stall.observedAt ?? null] : null,
326
+ meta.sandbox ?? null,
294
327
  meta.status,
295
328
  meta.endedAt ?? null,
296
329
  meta.lastCheckedAt ?? null,
@@ -460,7 +493,7 @@ export function formatLaunch(meta: BackgroundTaskMeta, firstCheck?: FirstWatchCh
460
493
  identity: `Started background ${meta.kind} ${label}. Status: ${meta.status}.`,
461
494
  failure: incidentSection(meta.id, {}),
462
495
  decision: formatDecision(meta),
463
- diagnostics: [...remoteLines, ...(checkText ? [checkText] : [])].join("\n") || undefined,
496
+ diagnostics: [formatLaunchSandbox(meta), ...remoteLines, ...(checkText ? [checkText] : [])].filter(Boolean).join("\n") || undefined,
464
497
  progress: withLog ? logLine : undefined,
465
498
  },
466
499
  gaps: taskGaps(meta),
@@ -520,7 +553,11 @@ export function formatFirstWatchCheck(meta: BackgroundTaskMeta, check: FirstWatc
520
553
  ...(keptOut.length ? [`stdout tail:\n${keptOut.map((line) => ` ${line}`).join("\n")}`] : []),
521
554
  ...(keptEmptyStdout ? ["stdout: (empty)"] : []),
522
555
  ].join("\n");
523
- const fits = () => utf8ByteLength(render()) <= maxBytes;
556
+ const omissionNote = () => {
557
+ const omitted = (stderr.length - keptErr.length) + (stdout.length - keptOut.length);
558
+ return omitted > 0 ? `(${omitted} output line${omitted === 1 ? "" : "s"} omitted; see bg_task_log)` : undefined;
559
+ };
560
+ const fits = () => utf8ByteLength([render(), omissionNote()].filter(Boolean).join("\n")) <= maxBytes;
524
561
  // Newest first within each stream; each kept line goes in front to stay in order.
525
562
  for (const line of [...stderr].reverse()) {
526
563
  keptErr.unshift(line);
@@ -534,21 +571,17 @@ export function formatFirstWatchCheck(meta: BackgroundTaskMeta, check: FirstWatc
534
571
  keptEmptyStdout = true;
535
572
  if (!fits()) keptEmptyStdout = false;
536
573
  }
537
- const omitted = (stderr.length - keptErr.length) + (stdout.length - keptOut.length);
538
- if (omitted > 0) {
539
- const note = `(${omitted} output line${omitted === 1 ? "" : "s"} omitted; see bg_task_log)`;
540
- const text = `${render()}\n${note}`;
541
- if (utf8ByteLength(text) <= maxBytes) return text;
542
- }
543
- return render();
574
+ return [render(), omissionNote()].filter(Boolean).join("\n");
544
575
  }
545
576
 
546
- function redactedVerbose(meta: BackgroundTaskMeta): unknown {
577
+ function redactedVerbose(meta: BackgroundTaskMeta, options: OutputOptions): unknown {
547
578
  const { env, ...rest } = meta;
548
579
  const state = failureStateFor(meta.id);
549
580
  const observations = Object.values(state.observations);
550
581
  const body = {
551
582
  ...rest,
583
+ sandbox: meta.sandbox ?? { confinement: "unknown", policySummary: "Launch-time policy was not recorded." },
584
+ ...(options.processDiagnostics ? { processDiagnostics: options.processDiagnostics } : {}),
552
585
  ...(env ? { env: { omitted: true, keyCount: Object.keys(env).length } } : {}),
553
586
  };
554
587
  if (!observations.length) return body;
@@ -569,16 +602,20 @@ function redactedVerbose(meta: BackgroundTaskMeta): unknown {
569
602
  * with a caller cursor like any other retained evidence.
570
603
  */
571
604
  function formatVerbose(meta: BackgroundTaskMeta, options: OutputOptions): string {
572
- const json = JSON.stringify(redactedVerbose(meta), null, 2);
605
+ const json = JSON.stringify(redactedVerbose(meta, options), null, 2);
573
606
  const resource = `verbose:${scopeKey(options)}:${meta.id}`;
574
607
  if (!options.cursor && utf8ByteLength(json) <= backgroundBudget("rawPage", options.maxBytes)) return json;
608
+ // Live process samples are not part of the paged document: CPU/state changes
609
+ // must not invalidate continuation, even when diagnostics is omitted next time.
610
+ const stableJson = JSON.stringify(redactedVerbose(meta, { ...options, processDiagnostics: undefined }), null, 2);
575
611
  return assembleBackgroundContent({
576
612
  surface: "rawPage",
577
613
  maxBytes: options.maxBytes,
578
614
  sections: {
579
615
  identity: `Background task ${meta.id} metadata (environment values omitted).`,
616
+ diagnostics: formatProcessDiagnostics(options.processDiagnostics),
580
617
  },
581
- verbatim: (budget) => pageVerbatimText(json, { cursor: options.cursor, maxBytes: budget, resource }),
618
+ verbatim: (budget) => pageVerbatimText(stableJson, { cursor: options.cursor, maxBytes: budget, resource }),
582
619
  });
583
620
  }
584
621
 
@@ -641,10 +678,13 @@ export function formatStatus(
641
678
  // stale status cursor (#332).
642
679
  const listCursor = pageKind === "l";
643
680
  const state = failureStateFor(meta.id);
681
+ const stall = meta.status === "running" ? observeBackgroundTaskStall(meta) : undefined;
682
+ const staleProgress = formatStaleProgress(stall);
683
+ const sandbox = formatLaunchSandbox(meta);
644
684
  const resource = `status:${scopeKey(options)}:${meta.id}`;
645
685
  const revision = inspectStatusRevision({
646
686
  resource,
647
- contentRevision: contentRevision(meta),
687
+ contentRevision: contentRevision(meta, stall),
648
688
  failureRevision: failureRevision(state),
649
689
  cursor: listCursor ? undefined : options.cursor,
650
690
  });
@@ -657,7 +697,8 @@ export function formatStatus(
657
697
  failure: actionableFailures(state).length
658
698
  ? `${actionableFailures(state).length} active failure observation(s), unchanged.`
659
699
  : undefined,
660
- decision: formatUnchangedEvidence(options.cursor),
700
+ decision: [staleProgress, formatUnchangedEvidence(options.cursor)].filter(Boolean).join("\n"),
701
+ diagnostics: sandbox,
661
702
  },
662
703
  statusCursor: revision.nextCursor,
663
704
  });
@@ -677,8 +718,8 @@ export function formatStatus(
677
718
  sections: {
678
719
  identity: identityLine(meta),
679
720
  failure: incidentSection(meta.id, options, state),
680
- decision: [...changeFacts, formatDecision(meta)].filter(Boolean).join("\n") || undefined,
681
- diagnostics: formatDiagnostics(meta),
721
+ decision: [...changeFacts, formatDecision(meta), staleProgress].filter(Boolean).join("\n") || undefined,
722
+ diagnostics: formatDiagnostics(meta, [formatProcessDiagnostics(options.processDiagnostics), sandbox].filter((line): line is string => !!line)),
682
723
  progress: formatProgress(meta),
683
724
  },
684
725
  verbatim: log.error ? undefined : (budget) => excerptPage(meta, options, log, budget),
package/src/runtime.ts CHANGED
@@ -7,7 +7,7 @@ import { currentProcessStartToken, readProcessStartToken } from "./process-ident
7
7
  import { DEFAULT_TMUX_BOOTSTRAP_TIMEOUT_MS, expandSshRemoteTaskPreset } from "./remote-task-preset.js";
8
8
  import type { RemoteRunner, ResolvedSshRemoteTask } from "./remote-task-preset.js";
9
9
  import { ensureTaskDir, logPathFor, nextTaskId, readMeta, sandboxProfilePathFor, writeMeta } from "./registry.js";
10
- import { confineCommandSpec, resolveForegroundSandboxPlan } from "./sandbox.js";
10
+ import { confineCommandSpec, resolveForegroundSandboxPlan, sandboxProvenance } from "./sandbox.js";
11
11
  import { takeRecoverySnapshot } from "./shared-sandbox-core.js";
12
12
  import { failurePath, readTaskIntent, recordExitFailure, recordFailure, recoverDeclaredOperation, recoverFailure, resumeFailureAttention, scheduleFailureAttention, stopFailureAttention, suspendFailureAttention, terminalFailureAttention } from "./failures.js";
13
13
  import { markFailureAttentionDelivered } from "./shared-failure-observations.js";
@@ -24,6 +24,7 @@ import type {
24
24
  SshConnectionParams,
25
25
  TerminalResult,
26
26
  } from "./types.js";
27
+ import { observeTaskStallAttention } from "./stall-attention.js";
27
28
  import { isTerminalStatus } from "./types.js";
28
29
 
29
30
  const watcherTimers = new Map<string, ReturnType<typeof setTimeout>>();
@@ -262,6 +263,7 @@ export function spawnTask(
262
263
  cwd,
263
264
  env: params.env,
264
265
  launchArgv: launchArgvOf(commandSpec, launchSpec),
266
+ sandbox: sandboxProvenance(sandboxPlan, !!remoteTask),
265
267
  maxLogBytes: resolveMaxLogBytes(params.max_log_bytes),
266
268
  pid: spawned?.child.pid,
267
269
  pidStartTime: spawned?.child.pid ? readProcessStartToken(spawned.child.pid) : undefined,
@@ -273,7 +275,7 @@ export function spawnTask(
273
275
  ...intent,
274
276
  };
275
277
  writeMeta(meta);
276
- scheduleLogRetention(id);
278
+ scheduleLogRetention(pi, id, getActiveSession);
277
279
  if (tmuxBacked && remoteTask) {
278
280
  activeRemoteTasks.set(id, remoteTask);
279
281
  appendLine(logPath, `--- remote tmux bootstrap ${new Date(now).toISOString()} target=${remoteTask.metadata.ssh.target} session=${remoteTask.metadata.remote.sessionName} ---`);
@@ -533,6 +535,7 @@ export function startWatchTask(
533
535
  cwd,
534
536
  env: params.env,
535
537
  launchArgv: launchArgvOf(commandSpec, launchSpec),
538
+ sandbox: sandboxProvenance(sandboxPlan, !!remoteTask),
536
539
  maxLogBytes: resolveMaxLogBytes(params.max_log_bytes),
537
540
  spawnPid: process.pid,
538
541
  spawnPidStartTime: currentProcessStartToken(),
@@ -548,6 +551,7 @@ export function startWatchTask(
548
551
  appendLine(meta.logPath, `--- watch ${new Date(now).toISOString()} interval_ms=${meta.intervalMs} ---`);
549
552
  for (const line of sandboxNotices) appendLine(meta.logPath, `--- ${line} ---`);
550
553
  writeMeta(meta);
554
+ scheduleLogRetention(pi, meta.id, getActiveSession);
551
555
  let resolveFirst!: (check: FirstWatchCheck | "suspended" | undefined) => void;
552
556
  const firstCheck = new Promise<FirstWatchCheck | "suspended" | undefined>((resolve) => { resolveFirst = resolve; });
553
557
  firstCheckWaiters.set(id, { promise: firstCheck, resolve: resolveFirst });
@@ -592,6 +596,7 @@ export function resumeRunningTask(
592
596
  writeMeta(meta);
593
597
  }
594
598
 
599
+ scheduleLogRetention(pi, meta.id, getActiveSession);
595
600
  const remoteTask = resolvePersistedRemoteTask(meta, dependencies.remoteRunner);
596
601
  if (meta.kind === "command_watch") {
597
602
  scheduleWatch(pi, meta.id, 0, getActiveSession, remoteTask
@@ -600,7 +605,6 @@ export function resumeRunningTask(
600
605
  return meta;
601
606
  }
602
607
 
603
- scheduleLogRetention(meta.id);
604
608
  if (meta.remote?.session === "tmux" && meta.remote.sessionStarted !== false && remoteTask) {
605
609
  activeRemoteTasks.set(meta.id, remoteTask);
606
610
  scheduleRemoteSessionPoll(pi, meta.id, 0, getActiveSession);
@@ -1155,6 +1159,7 @@ async function notifyTerminal(
1155
1159
  meta: BackgroundTaskMeta,
1156
1160
  getActiveSession?: ActiveSessionProvider,
1157
1161
  ): Promise<void> {
1162
+ observeTaskStallAttention(readMeta(meta.id) ?? meta);
1158
1163
  // A suspended instance has no active session: delivering or suppressing here would
1159
1164
  // be wrong either way. The instance that resumes the task delivers it (#324).
1160
1165
  if (scheduledWorkSuspended) return;
@@ -1260,16 +1265,17 @@ function launchArgvOf(commandSpec: CommandSpec, launchSpec: CommandSpec): string
1260
1265
  return launchSpec === commandSpec ? undefined : launchSpec.argv;
1261
1266
  }
1262
1267
 
1263
- function scheduleLogRetention(id: string): void {
1268
+ function scheduleLogRetention(pi: ExtensionAPI, id: string, getActiveSession?: ActiveSessionProvider): void {
1264
1269
  stopLogRetention(id);
1265
1270
  if (scheduledWorkSuspended) return;
1266
1271
  const timer = setInterval(() => {
1267
1272
  const meta = readMeta(id);
1268
- if (!meta || meta.status !== "running" || meta.kind !== "process") {
1273
+ if (!meta || meta.status !== "running") {
1269
1274
  stopLogRetention(id);
1270
1275
  return;
1271
1276
  }
1272
- enforceLogRetention(meta);
1277
+ if (meta.kind === "process") enforceLogRetention(meta);
1278
+ if (observeTaskStallAttention(meta)) scheduleFailureAttention(pi, id, getActiveSession);
1273
1279
  }, LOG_RETENTION_CHECK_MS);
1274
1280
  timer.unref();
1275
1281
  logRetentionTimers.set(id, timer);
@@ -1283,8 +1289,10 @@ function stopLogRetention(id: string): void {
1283
1289
 
1284
1290
  function enforceLogRetention(meta: BackgroundTaskMeta): void {
1285
1291
  try {
1286
- const mtimeMs = Math.trunc(statSync(meta.logPath).mtimeMs);
1287
- if (mtimeMs > (meta.lastProgressAt ?? meta.startedAt)) {
1292
+ const log = statSync(meta.logPath);
1293
+ const mtimeMs = Math.trunc(log.mtimeMs);
1294
+ const maintenance = meta.logMaintenance?.mtimeMs === mtimeMs && meta.logMaintenance.size === log.size;
1295
+ if (!maintenance && mtimeMs > (meta.lastProgressAt ?? meta.startedAt)) {
1288
1296
  meta.lastProgressAt = mtimeMs;
1289
1297
  writeMeta(meta);
1290
1298
  }
@@ -1296,6 +1304,10 @@ function enforceLogRetention(meta: BackgroundTaskMeta): void {
1296
1304
  meta.logDiscardedBytes = (meta.logDiscardedBytes ?? 0) + compacted.discardedBytes;
1297
1305
  meta.logRetentionEvents = (meta.logRetentionEvents ?? 0) + 1;
1298
1306
  meta.logGeneration = (meta.logGeneration ?? 0) + 1;
1307
+ try {
1308
+ const log = statSync(meta.logPath);
1309
+ meta.logMaintenance = { mtimeMs: Math.trunc(log.mtimeMs), size: log.size };
1310
+ } catch { /* Missing log remains an evidence gap. */ }
1299
1311
  writeMeta(meta);
1300
1312
  }
1301
1313
 
package/src/sandbox.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  /**
2
- * Foreground write-sandbox policy for locally launched background tasks.
2
+ * Background launch sandbox policy. New publishers provide a separate Background
3
+ * tasks profile; older publishers retain the historical Main-policy behavior.
4
+ * Every task keeps its policy snapshot for its whole lifetime.
3
5
  *
4
6
  * `pi-better-sandbox` owns the foreground policy and publishes an immutable
5
7
  * snapshot of it on `pi.events`. This module is the consumer side of that wire
@@ -39,7 +41,7 @@ type SandboxPermissions = {
39
41
  commands: boolean;
40
42
  network: boolean;
41
43
  };
42
- import type { CommandSpec } from "./types.js";
44
+ import type { CommandSpec, TaskSandboxProvenance } from "./types.js";
43
45
  import { SandboxDiagnostics, diagnosticPackageVersion, type DiagnosticResource } from "./shared-sandbox-diagnostics.js";
44
46
 
45
47
  function backgroundDiagnostics(policy: unknown): SandboxDiagnostics | undefined {
@@ -63,7 +65,7 @@ function backgroundDiagnostics(policy: unknown): SandboxDiagnostics | undefined
63
65
  * is an optional peer.
64
66
  */
65
67
  export const FOREGROUND_SANDBOX_REMEDY =
66
- "Run unconfined on purpose with /sandbox off, or work in a session that has a backend.";
68
+ "Change the controlling Sandbox column in /sandbox, or work in a session that has a backend.";
67
69
 
68
70
  /** Channel `pi-better-sandbox` publishes every effective-policy change on. */
69
71
  export const FOREGROUND_SANDBOX_POLICY_CHANNEL = "pi-better-sandbox:policy";
@@ -92,6 +94,7 @@ export interface ForegroundSandboxPolicy {
92
94
  /** Human-readable evidence for why `state` is what it is. */
93
95
  readonly reason: string;
94
96
  readonly permissions?: Readonly<SandboxPermissions & { enabled: boolean }>;
97
+ readonly policySource?: "background" | "main-legacy";
95
98
  }
96
99
 
97
100
  /** The minimum `pi.events` surface this module uses. */
@@ -106,7 +109,7 @@ export class ForegroundSandboxBlockedError extends Error {
106
109
 
107
110
  constructor(policy: ForegroundSandboxPolicy, detail?: string) {
108
111
  super(
109
- `Foreground sandbox is ${policy.state}; this local background task was blocked rather than launched unconfined. ${detail ?? policy.reason}`,
112
+ `${policy.policySource === "background" ? "Background tasks" : "Foreground"} sandbox is ${policy.state}; this local background task was blocked rather than launched unconfined. ${detail ?? policy.reason}`,
110
113
  );
111
114
  this.name = "ForegroundSandboxBlockedError";
112
115
  this.policy = policy;
@@ -124,6 +127,12 @@ export type ForegroundSandboxPlan =
124
127
  };
125
128
 
126
129
  const UNCONFINED: ForegroundSandboxPlan = { confined: false };
130
+ const launchPolicies = new WeakMap<ForegroundSandboxPlan, ForegroundSandboxPolicy | undefined>();
131
+ function capturePlan(plan: ForegroundSandboxPlan, policy: ForegroundSandboxPolicy | undefined): ForegroundSandboxPlan {
132
+ const snapshot = { ...plan };
133
+ launchPolicies.set(snapshot, policy);
134
+ return snapshot;
135
+ }
127
136
 
128
137
  const VALID_STATES = new Set<string>(["inactive", "enabled", "disabled", "unavailable", "failed"]);
129
138
 
@@ -134,7 +143,8 @@ const VALID_STATES = new Set<string>(["inactive", "enabled", "disabled", "unavai
134
143
  * sessions inside one process (and separate tests) cannot read each other's
135
144
  * policy.
136
145
  */
137
- const mirrors = new WeakMap<PolicyEventBus, { policy: ForegroundSandboxPolicy | undefined; error?: Error }>();
146
+ type PolicyMirror = { policy: ForegroundSandboxPolicy | undefined; error?: Error; processAccess?: "off" | "read"; mainConfined?: boolean };
147
+ const mirrors = new WeakMap<PolicyEventBus, PolicyMirror>();
138
148
 
139
149
  function eventBusOf(pi: unknown): PolicyEventBus | undefined {
140
150
  const events = (pi as { events?: unknown } | undefined)?.events;
@@ -149,7 +159,7 @@ function eventBusOf(pi: unknown): PolicyEventBus | undefined {
149
159
  * understands, so an unrelated extension emitting on the channel cannot clear a
150
160
  * real policy or invent one.
151
161
  */
152
- function readPolicy(data: unknown): ForegroundSandboxPolicy | undefined {
162
+ function readPolicy(data: unknown, profile = "Main"): ForegroundSandboxPolicy | undefined {
153
163
  if (!data || typeof data !== "object") return undefined;
154
164
  const value = data as Record<string, unknown>;
155
165
  if (typeof value.state !== "string" || !VALID_STATES.has(value.state)) return undefined;
@@ -159,7 +169,7 @@ function readPolicy(data: unknown): ForegroundSandboxPolicy | undefined {
159
169
  : [];
160
170
  const permissions = value.permissions === undefined ? undefined : readPermissions(value.permissions);
161
171
  if (value.permissions !== undefined && !permissions) {
162
- throw new Error("Invalid Main sandbox permission profile; update permissions in the sandbox UI.");
172
+ throw new Error(`Invalid ${profile} sandbox permission profile; update permissions in the sandbox UI.`);
163
173
  }
164
174
  return {
165
175
  state: value.state as ForegroundSandboxState,
@@ -177,7 +187,8 @@ function readPermissions(value: unknown): ForegroundSandboxPolicy["permissions"]
177
187
  const access = (v: unknown) => credential(v) || v === "write";
178
188
  if (typeof p.enabled !== "boolean" || typeof p.commands !== "boolean" ||
179
189
  typeof p.network !== "boolean" || !access(p.projectFiles) ||
180
- !access(p.outsideProject) || !credential(p.storedCredentials)) return undefined;
190
+ !access(p.outsideProject) || !credential(p.storedCredentials) ||
191
+ (p.processAccess !== undefined && p.processAccess !== "off" && p.processAccess !== "read")) return undefined;
181
192
  return Object.freeze({
182
193
  enabled: p.enabled, commands: p.commands, network: p.network,
183
194
  projectFiles: p.projectFiles as SandboxPermissions["projectFiles"],
@@ -198,14 +209,25 @@ export function observeForegroundSandboxPolicy(pi: unknown): void {
198
209
  const events = eventBusOf(pi);
199
210
  if (!events || mirrors.has(events)) return;
200
211
 
201
- const mirror: { policy: ForegroundSandboxPolicy | undefined; error?: Error } = { policy: undefined };
212
+ const mirror: PolicyMirror = { policy: undefined };
202
213
  mirrors.set(events, mirror);
203
214
  events.on(FOREGROUND_SANDBOX_POLICY_CHANNEL, (data) => {
204
215
  try {
205
- const policy = readPolicy(data);
216
+ const published = data && typeof data === "object" ? data as Record<string, unknown> : undefined;
217
+ const hasBackground = published && Object.hasOwn(published, "background");
218
+ const policy = readPolicy(hasBackground ? published.background : data, hasBackground ? "Background tasks" : "Main");
219
+ if (hasBackground && !policy) throw new Error("Invalid Background tasks sandbox policy; update permissions in /sandbox.");
220
+ const access = (value: unknown): unknown => {
221
+ if (!value || typeof value !== "object") return undefined;
222
+ return (value as { permissions?: { processAccess?: unknown } }).permissions?.processAccess;
223
+ };
224
+ mirror.mainConfined = published?.state !== "disabled" && published?.state !== "inactive";
225
+ mirror.processAccess = access(data) === "read" && access(hasBackground ? published.background : data) === "read" ? "read" : "off";
226
+ if (policy) Object.assign(policy, { policySource: hasBackground ? "background" : "main-legacy" });
206
227
  if (policy) { mirror.policy = policy; mirror.error = undefined; }
207
228
  } catch (error) {
208
229
  mirror.error = error as Error;
230
+ mirror.processAccess = "off";
209
231
  }
210
232
  });
211
233
  events.emit(FOREGROUND_SANDBOX_POLICY_REQUEST_CHANNEL, undefined);
@@ -230,6 +252,28 @@ export function currentForegroundSandboxPolicy(pi: unknown): ForegroundSandboxPo
230
252
  return mirror?.policy;
231
253
  }
232
254
 
255
+ /** Current diagnostics permissions are independent of the task's launch snapshot. */
256
+ export function backgroundProcessDiagnosticsAccess(pi: unknown): "read" | "off" | "unknown" | "confined" {
257
+ try { currentForegroundSandboxPolicy(pi); } catch { return "off"; }
258
+ const events = eventBusOf(pi);
259
+ const mirror = events ? mirrors.get(events) : undefined;
260
+ const access = mirror?.processAccess ?? "unknown";
261
+ return access === "read" && mirror?.mainConfined ? "confined" : access;
262
+ }
263
+
264
+ export function sandboxProvenance(plan: ForegroundSandboxPlan, remote = false): TaskSandboxProvenance {
265
+ const policy = launchPolicies.get(plan);
266
+ const policySource = remote ? "remote" : policy?.policySource ?? (policy ? "main-legacy" : "no-publisher");
267
+ if (remote) return { confinement: "unknown", policySource, policySummary: "Remote execution; local sandbox does not establish remote confinement.", changesAffectTask: false };
268
+ if (!plan.confined) return { confinement: "unconfined", policySource,
269
+ policySummary: policy ? "Sandbox disabled at launch." : "No sandbox policy publisher at launch.", changesAffectTask: false };
270
+ const support = describeSandboxSupport();
271
+ const p = plan.permissions;
272
+ return { confinement: "confined", policySource, ...(support.supported ? { backend: support.backend } : {}),
273
+ policySummary: p ? `project=${p.projectFiles}; outside=${p.outsideProject}; credentials=${p.storedCredentials}; commands=${p.commands ? "on" : "off"}; network=${p.network ? "on" : "off"}`
274
+ : "Project write confinement with protected paths.", changesAffectTask: false };
275
+ }
276
+
233
277
  /**
234
278
  * Decide how a local launch must be confined, before the task has an id, a
235
279
  * directory, or a log.
@@ -239,15 +283,15 @@ export function currentForegroundSandboxPolicy(pi: unknown): ForegroundSandboxPo
239
283
  */
240
284
  export function resolveForegroundSandboxPlan(pi: unknown, remote = false, operation?: unknown, tool = "bg_task_spawn"): ForegroundSandboxPlan {
241
285
  const policy = currentForegroundSandboxPolicy(pi);
242
- if (remote && !policy?.permissions) return UNCONFINED; // Preserve legacy SSH behavior.
286
+ if (remote && !policy?.permissions) return capturePlan(UNCONFINED, policy); // Preserve legacy SSH behavior.
243
287
  try {
244
288
  const plan = planFor(policy);
245
289
  if (remote && plan.confined) {
246
290
  throw new ForegroundSandboxBlockedError(policy!, !plan.permissions?.network
247
- ? "Main profile disables network. SSH launches are blocked."
248
- : "Structured SSH cannot apply local file and credential permissions yet. Use SSH through confined bash, or change Main permissions in /sandbox.");
291
+ ? `${policy?.policySource === "background" ? "Background tasks" : "Main"} profile disables network. SSH launches are blocked.`
292
+ : `Structured SSH cannot apply local file and credential permissions yet. Use SSH through confined bash, or change ${policy?.policySource === "background" ? "Background tasks" : "Main"} permissions in /sandbox.`);
249
293
  }
250
- return plan;
294
+ return capturePlan(plan, policy);
251
295
  } catch (error) {
252
296
  if (error instanceof ForegroundSandboxBlockedError) {
253
297
  const resource: DiagnosticResource = policy?.permissions?.enabled && !policy.permissions.commands ? "command-execution"
@@ -264,7 +308,7 @@ export function planFor(policy: ForegroundSandboxPolicy | undefined): Foreground
264
308
  // keeps its historical unsandboxed behaviour.
265
309
  if (!policy) return UNCONFINED;
266
310
  if (policy.permissions?.enabled && !policy.permissions.commands) {
267
- throw new ForegroundSandboxBlockedError(policy, "Main profile disables commands. Change permissions in the sandbox UI before launching background tasks.");
311
+ throw new ForegroundSandboxBlockedError(policy, `${policy.policySource === "background" ? "Background tasks" : "Main"} profile disables commands. Change permissions in /sandbox before launching background tasks.`);
268
312
  }
269
313
  if (policy.state === "inactive" || policy.state === "disabled") return UNCONFINED;
270
314
  if (policy.state !== "enabled" || !policy.writableRoot) {
@@ -368,6 +412,7 @@ function blocked(plan: ForegroundSandboxPlan & { confined: true }, detail: strin
368
412
  return new ForegroundSandboxBlockedError(
369
413
  {
370
414
  state: "failed",
415
+ policySource: launchPolicies.get(plan)?.policySource,
371
416
  writableRoot: plan.writableRoot,
372
417
  denyWrite: plan.denyWrite,
373
418
  reason: detail,
@@ -0,0 +1,31 @@
1
+ import { failurePath, recordFailure, recoverFailure } from "./failures.js";
2
+ import { actionableFailures, failureIdentity, readFailureState } from "./shared-failure-observations.js";
3
+ import { formatBackgroundTaskStall, observeBackgroundTaskStall } from "./stall.js";
4
+ import type { BackgroundTaskMeta } from "./types.js";
5
+
6
+ const STALL_OPERATION = "suspected-stall";
7
+
8
+ /** Observe silence without changing lifecycle. The caller schedules existing failure attention on true. */
9
+ export function observeTaskStallAttention(meta: BackgroundTaskMeta, now = Date.now()): boolean {
10
+ if (meta.status !== "running") {
11
+ recoverFailure(meta, STALL_OPERATION, ["terminal", meta.status], now);
12
+ return false;
13
+ }
14
+ const observation = observeBackgroundTaskStall(meta, now);
15
+ if (observation.observedAt === undefined || observation.state === "unknown") return false;
16
+
17
+ const path = failurePath(meta.id);
18
+ const before = readFailureState(path);
19
+ const prior = before.observations[failureIdentity(STALL_OPERATION)];
20
+ const eventKey = observation.observedAt;
21
+ const incidentId = failureIdentity(meta.id, STALL_OPERATION, eventKey);
22
+
23
+ // A new progress anchor ends the previous spell, even if the monitor missed the healthy interval.
24
+ if (prior && prior.id !== incidentId) recoverFailure(meta, STALL_OPERATION, eventKey, now);
25
+ if (observation.state !== "stalled") return false;
26
+
27
+ recordFailure(meta, STALL_OPERATION, formatBackgroundTaskStall(observation)!, eventKey, { category: "stall", at: now });
28
+ const previousActionable = new Set(actionableFailures(before).map((incident) => incident.id));
29
+ return actionableFailures(readFailureState(path))
30
+ .some((incident) => incident.id === incidentId && !previousActionable.has(incident.id));
31
+ }
package/src/stall.ts CHANGED
@@ -25,7 +25,10 @@ export function backgroundTaskProgressAt(meta: BackgroundTaskMeta): number | und
25
25
  const recorded = Math.max(meta.lastProgressAt ?? 0, meta.lastCheckedAt ?? 0, meta.startedAt);
26
26
  if (meta.kind !== "process") return recorded;
27
27
  try {
28
- return Math.max(recorded, Math.trunc(statSync(meta.logPath).mtimeMs));
28
+ const log = statSync(meta.logPath);
29
+ const mtimeMs = Math.trunc(log.mtimeMs);
30
+ if (meta.logMaintenance?.mtimeMs === mtimeMs && meta.logMaintenance.size === log.size) return recorded;
31
+ return Math.max(recorded, mtimeMs);
29
32
  } catch {
30
33
  return recorded;
31
34
  }
@@ -39,4 +42,13 @@ export function observeBackgroundTaskStall(meta: BackgroundTaskMeta, now = Date.
39
42
  exempt: meta.status !== "running",
40
43
  thresholds: backgroundTaskStallThresholds(),
41
44
  });
42
- }
45
+ }
46
+
47
+ /** Silence is an observation, not proof that the process is hung. */
48
+ export function formatBackgroundTaskStall(observation: StallObservation): string | undefined {
49
+ if (observation.state !== "quiet" && observation.state !== "stalled") return undefined;
50
+ const seconds = Math.max(0, Math.round((observation.ageMs ?? 0) / 1000));
51
+ const duration = seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m${(seconds % 60).toString().padStart(2, "0")}s`;
52
+ const label = observation.state === "stalled" ? "suspected stall" : "quiet";
53
+ return `${label}; no observed progress for ${duration}`;
54
+ }
@@ -0,0 +1,71 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import type { BackgroundTaskMeta } from "./types.js";
3
+
4
+ export interface ProcessSample {
5
+ uid: number;
6
+ startTime: string;
7
+ state: string;
8
+ cpuTime: string;
9
+ waitChannel: string;
10
+ }
11
+
12
+ export interface TaskProcessDiagnostics {
13
+ availability: "available" | "blocked" | "unavailable";
14
+ identity?: "matches" | "absent" | "mismatch" | "unverified";
15
+ state?: string;
16
+ cpuTime?: string;
17
+ waitChannel?: string;
18
+ reason?: string;
19
+ limit: string;
20
+ }
21
+
22
+ const LIMIT = "One process snapshot cannot prove useful work or a hang; descendants and network requests are not inspected.";
23
+ const normalized = (value: string) => value.trim().replace(/\s+/g, " ");
24
+
25
+ /** Fixed, bounded probe of one registered task PID. Never reads argv, environment or paths. */
26
+ function sampleProcess(pid: number): ProcessSample | undefined {
27
+ if (process.platform !== "darwin" && process.platform !== "linux") throw new Error("unsupported platform");
28
+ const file = process.platform === "darwin" ? "/bin/ps" : "/usr/bin/ps";
29
+ let output: string;
30
+ try {
31
+ output = execFileSync(file, ["-p", String(pid), "-o", "uid=,lstart=,state=,time=,wchan="], {
32
+ encoding: "utf8", timeout: 2_000, maxBuffer: 4096,
33
+ stdio: ["ignore", "pipe", "pipe"], env: { LC_ALL: "C", PATH: "/usr/bin:/bin" },
34
+ }).trim();
35
+ } catch (error) {
36
+ const failure = error as { status?: number; stdout?: unknown; stderr?: unknown };
37
+ if (failure.status === 1 && !String(failure.stdout ?? "").trim() && !String(failure.stderr ?? "").trim()) return undefined;
38
+ throw new Error("process snapshot unavailable");
39
+ }
40
+ if (!output) return undefined;
41
+ const match = /^(\d+)\s+(\S+\s+\S+\s+\d+\s+[\d:]+\s+\d+)\s+([A-Za-z+<>NsLslWXZRTIDUP?-]+)\s+([\d:.\-]+)\s*(\S*)$/.exec(output);
42
+ if (!match || match[5]!.length > 128) throw new Error("unsupported process snapshot");
43
+ return { uid: Number(match[1]), startTime: normalized(match[2]!), state: match[3]!, cpuTime: match[4]!, waitChannel: match[5] || "unavailable" };
44
+ }
45
+
46
+ export function inspectTaskProcess(
47
+ meta: BackgroundTaskMeta,
48
+ access: "read" | "off" | "unknown" | "confined",
49
+ probe: (pid: number) => ProcessSample | undefined = sampleProcess,
50
+ ): TaskProcessDiagnostics {
51
+ const unavailable = (reason: string, identity?: TaskProcessDiagnostics["identity"]): TaskProcessDiagnostics =>
52
+ ({ availability: "unavailable", reason, ...(identity ? { identity } : {}), limit: LIMIT });
53
+ if (access === "confined") return unavailable("Process activity adapter is unavailable under Main confinement; no unconfined process probe was run. Process access Read does not bypass kernel rules.");
54
+ if (access !== "read") return { availability: "blocked", reason: access === "off"
55
+ ? "Process access is Off in Main or Background tasks. Enable Read in /sandbox; this does not describe task confinement."
56
+ : "Current process-access policy is unavailable; no process probe was run.", limit: LIMIT };
57
+ if (meta.ssh) return unavailable("Remote activity is unavailable; no remote diagnostic command was run.");
58
+ if (meta.kind !== "process") return unavailable("Watch poll PID is not retained; last completed check is progress evidence only.");
59
+ if (!Number.isSafeInteger(meta.pid) || meta.pid! <= 0) return unavailable("Task PID is unavailable.");
60
+ try {
61
+ const sample = probe(meta.pid!);
62
+ if (!sample) return { availability: "available", identity: "absent", reason: "Recorded PID is absent; the execution result may still be unavailable.", limit: LIMIT };
63
+ if (sample.uid !== process.getuid?.()) return unavailable("Recorded PID is not a current-user process.", "mismatch");
64
+ if (!meta.pidStartTime) return unavailable("Launch-time process identity is missing; sampled activity cannot be attributed to this task.", "unverified");
65
+ if (normalized(sample.startTime) !== normalized(meta.pidStartTime)) return unavailable("Recorded PID has been reused; sampled activity is not this task.", "mismatch");
66
+ return { availability: "available", identity: "matches", state: sample.state, cpuTime: sample.cpuTime,
67
+ waitChannel: sample.waitChannel, limit: LIMIT };
68
+ } catch {
69
+ return unavailable("OS process activity/wait evidence is unavailable or unsupported; no command output is disclosed.");
70
+ }
71
+ }
package/src/tools.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Type } from "typebox";
2
2
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import { advertiseBackgroundAdapter } from "./adapter-contract.js";
3
4
  import { refreshBackgroundTasksNavigator } from "./navigator-provider.js";
4
5
  import {
5
6
  classifyOwnership,
@@ -12,12 +13,13 @@ import {
12
13
  formatStopResult,
13
14
  type OutputOptions,
14
15
  } from "./output.js";
15
- import { readOutputControls } from "./shared-log-utils.js";
16
+ import { cursorKind, readOutputControls } from "./shared-log-utils.js";
16
17
  import { cancelCallbackBatch, getCallbackBatcher, setCallbackBatchContext } from "./shared-callback-batcher.js";
17
18
  import { inspectMeta, listMetasForOrigin, readMeta, writeMeta } from "./registry.js";
18
19
  import { awaitFirstWatchCheck, FIRST_WATCH_CHECK_WAIT_MS, resumeRunningTask, spawnTask, startWatchTask, stopTask, type WatchTaskParams } from "./runtime.js";
19
20
  import { runTaskMaintenance } from "./maintenance.js";
20
- import { ForegroundSandboxBlockedError } from "./sandbox.js";
21
+ import { backgroundProcessDiagnosticsAccess, ForegroundSandboxBlockedError } from "./sandbox.js";
22
+ import { inspectTaskProcess } from "./task-diagnostics.js";
21
23
  import type { BackgroundTaskCallbackOrigin, BackgroundTaskMeta } from "./types.js";
22
24
  import { isTerminalStatus } from "./types.js";
23
25
 
@@ -123,6 +125,7 @@ const IdParams = Type.Object({
123
125
  ...CursorFields,
124
126
  });
125
127
  const HistoryField = {
128
+ diagnostics: Type.Optional(Type.Boolean({ description: "For status: sample registered task process identity, CPU time, state and wait evidence. Requires current Process access Read in both Main and Background tasks. No arguments, environment or remote probes; a snapshot cannot prove useful work or a hang." })),
126
129
  history: Type.Optional(Type.Boolean({ description: "If true, return an incident page that also lists failure history: expected failures and recovered or superseded incidents. Default output lists only failures that need action and counts the rest." })),
127
130
  };
128
131
  const StatusParams = Type.Object({
@@ -193,6 +196,14 @@ const BACKGROUND_ORCHESTRATION_GUIDELINES = [
193
196
  export function registerTools(pi: ExtensionAPI): void {
194
197
  let activeSession: BackgroundTaskCallbackOrigin | undefined;
195
198
  const getActiveSession = () => activeSession;
199
+ const schemas = new Map<string, object>();
200
+ const register: ExtensionAPI["registerTool"] = (definition) => {
201
+ // A reload must not share schema identity with the previous registration.
202
+ const parameters = { ...definition.parameters };
203
+ schemas.set(definition.name, parameters);
204
+ pi.registerTool({ ...definition, parameters });
205
+ };
206
+ advertiseBackgroundAdapter(pi, schemas);
196
207
 
197
208
  pi.on("session_start", async (_event, ctx) => {
198
209
  setCallbackBatchContext(pi, ctx);
@@ -225,7 +236,7 @@ export function registerTools(pi: ExtensionAPI): void {
225
236
  cancelCallbackBatch(pi);
226
237
  });
227
238
 
228
- pi.registerTool({
239
+ register({
229
240
  name: "bg_task_spawn",
230
241
  label: "BG Spawn",
231
242
  description: "Start a long-running background process and return immediately with its task id. For remote work, prefer structured ssh: pass ssh:{host,user} and put the remote command in command; spawn defaults to a remote tmux session with durable local logs and real remote stop. For short synchronous remote commands that should return output now, use remote_bash from pi-better-ssh. If tmux is missing, the preset attempts to install tmux non-interactively and fails closed with operator guidance when setup cannot proceed. Explicit remote.session=direct skips tmux, but direct mode has weaker stop semantics and may leave the remote process running. Never wait or poll in the foreground.",
@@ -239,7 +250,7 @@ export function registerTools(pi: ExtensionAPI): void {
239
250
  },
240
251
  });
241
252
 
242
- pi.registerTool({
253
+ register({
243
254
  name: "bg_task_watch",
244
255
  label: "BG Watch",
245
256
  description: `Poll a command in the background until success_when, failure_when, or timeout matches. For remote work, prefer structured ssh: pass ssh:{host,user} and provide the remote command in command; each interval opens a direct one-shot SSH poll without tmux installation. For short synchronous remote commands that should return output now, use remote_bash from pi-better-ssh. Returns its task id once the first check finishes. ${WATCH_CHECK_GUIDANCE} Default timeout 900 seconds; pass timeout_seconds:0 to disable.`,
@@ -253,7 +264,7 @@ export function registerTools(pi: ExtensionAPI): void {
253
264
  },
254
265
  });
255
266
 
256
- pi.registerTool({
267
+ register({
257
268
  name: "bg_task_list",
258
269
  label: "BG List",
259
270
  description: "List durable background tasks as compact rows under a 1 KiB UTF-8 budget (10 entries default), newest first. Current-session only unless all:true. Nonblocking. Pass the returned nextCursor as cursor to page further (every task is reachable), or statusCursor to get a small no-change response or failure-only updates; a higher limit/max_bytes gives a larger explicit page.",
@@ -264,18 +275,18 @@ export function registerTools(pi: ExtensionAPI): void {
264
275
  },
265
276
  });
266
277
 
267
- pi.registerTool({
278
+ register({
268
279
  name: "bg_task_status",
269
280
  label: "BG Status",
270
281
  description: "Inspect one background task. Default output is a compact model-facing summary (1 KiB UTF-8) with matched condition, exit/signal, stop error, and failure counts before progress. Current-session only unless all:true; unknown ownership is a gap, not missing or healthy. Pass verbose:true only when full raw metadata is explicitly needed. Environment values are omitted. A raw log nextCursor passed as cursor continues the raw log page; an incidentCursor pages incidents that need action; history:true lists failure history too. After a terminal callback, call this first and call bg_task_log only if the summary is insufficient.",
271
282
  parameters: StatusParams,
272
283
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
273
284
  activeSession = getCallbackOrigin(ctx);
274
- return text(formatStatus(inspectMeta(params.id), statusOptions(params, activeSession)));
285
+ return text(taskStatus(pi, params.id, params, statusOptions(params, activeSession)));
275
286
  },
276
287
  });
277
288
 
278
- pi.registerTool({
289
+ register({
279
290
  name: "bg_task_log",
280
291
  label: "BG Log",
281
292
  description: "Read a background task log. Default output is a compact 10-line terminal-aware tail for model ingestion (1 KiB UTF-8). Current-session only unless all:true. Pass lines for a bounded tail (tail_lines is a deprecated alias); lines:0 pages the retained raw log from the oldest retained offset (16 KiB pages, 64 KiB hard cap) with a caller-owned cursor. Capture and retention loss are disclosed; this is not a full-history archive. Nonblocking.",
@@ -289,7 +300,7 @@ export function registerTools(pi: ExtensionAPI): void {
289
300
  },
290
301
  });
291
302
 
292
- pi.registerTool({
303
+ register({
293
304
  name: "bg_task_stop",
294
305
  label: "BG Stop",
295
306
  description: "Cancel a watcher or terminate a background task. Only a task owned by the current session stops; a foreign-session or unverifiable task is refused unless all:true. For a tmux-backed SSH task, stop kills its remote tmux session before marking it cancelled. Direct SSH stop only tears down the local client and may leave the remote process running.",
@@ -302,7 +313,7 @@ export function registerTools(pi: ExtensionAPI): void {
302
313
  },
303
314
  });
304
315
 
305
- pi.registerTool({
316
+ register({
306
317
  name: "bg_task",
307
318
  label: "BG Task",
308
319
  description: "Action wrapper for background tasks: spawn, watch, list, status, log, stop, or clear. For remote work, prefer structured ssh: pass ssh:{host,user} and provide the remote command in command. For short synchronous remote commands that should return output now, use remote_bash from pi-better-ssh. SSH spawn defaults to durable tmux; SSH watches use direct one-shot polls without tmux installation; remote.session=direct is a weaker-stop spawn escape hatch. Spawn returns immediately; do not poll in foreground. For action:watch: " + WATCH_CHECK_GUIDANCE + " For action:status, default compact output and use verbose:true only for full metadata. For action:log, default compact tail and use lines:0 to page retained raw bytes. Standalone tools and these wrappers share the same output assembler. List/status/log default to the current session; pass all:true to override. Stop and clear change only current-session tasks: clear dismisses every owned terminal task, or one task with id (all:true allows another session's task by id).",
@@ -317,7 +328,7 @@ export function registerTools(pi: ExtensionAPI): void {
317
328
  },
318
329
  });
319
330
 
320
- pi.registerTool({
331
+ register({
321
332
  name: "bg_status",
322
333
  label: "BG Status",
323
334
  description: "Action wrapper for inspecting background tasks: list, status, log, stop, or clear. Nonblocking. Status is compact by default; log returns a compact tail by default. Use verbose:true or lines:0 only for explicit full-data recovery. Shares the same output assembler as the standalone tools. Current-session default; pass all:true to override. Stop and clear change only current-session tasks (clear with id and all:true for another session's task).",
@@ -353,6 +364,19 @@ function statusOptions(params: Record<string, unknown>, origin?: BackgroundTaskC
353
364
  };
354
365
  }
355
366
 
367
+ function taskStatus(pi: ExtensionAPI, id: string, params: Record<string, unknown>, options: OutputOptions): string {
368
+ const inspection = inspectMeta(id);
369
+ const enriched: OutputOptions = { ...options };
370
+ const kind = cursorKind(options.cursor);
371
+ if (params.diagnostics === true && !options.history && (!kind || kind === "s" || kind === "t") &&
372
+ inspection.meta && classifyOwnership(inspection.meta, options) === "allow") {
373
+ enriched.processDiagnostics = inspectTaskProcess(inspection.meta, backgroundProcessDiagnosticsAccess(pi));
374
+ // Fresh samples bypass status suppression, not raw or incident pagination.
375
+ if (kind === "s") enriched.cursor = undefined;
376
+ }
377
+ return formatStatus(inspection, enriched);
378
+ }
379
+
356
380
  function logOptions(params: Record<string, unknown>, origin?: BackgroundTaskCallbackOrigin): OutputOptions {
357
381
  // Canonical `lines`, else the deprecated `tail_lines` alias (#321).
358
382
  const lines = readOutputControls(params).lines;
@@ -409,7 +433,7 @@ async function runAction(
409
433
  return formatList(listOptions(params, callbackOrigin));
410
434
  case "status":
411
435
  if (!params.id) return "Invalid parameters: status requires id.";
412
- return formatStatus(inspectMeta(String(params.id)), statusOptions(params, callbackOrigin));
436
+ return taskStatus(pi, String(params.id), params, statusOptions(params, callbackOrigin));
413
437
  case "log":
414
438
  if (!params.id) return "Invalid parameters: log requires id.";
415
439
  return formatLog(String(params.id), logOptions(params, callbackOrigin));
package/src/types.ts CHANGED
@@ -82,6 +82,14 @@ export interface BackgroundTaskCallbackOrigin {
82
82
  sessionId?: string;
83
83
  }
84
84
 
85
+ export interface TaskSandboxProvenance {
86
+ confinement: "confined" | "unconfined" | "unknown";
87
+ backend?: string;
88
+ policySource: "background" | "main-legacy" | "no-publisher" | "remote";
89
+ policySummary: string;
90
+ changesAffectTask: false;
91
+ }
92
+
85
93
  export interface BackgroundTaskMeta {
86
94
  id: string;
87
95
  name?: string;
@@ -119,9 +127,13 @@ export interface BackgroundTaskMeta {
119
127
  * own request, so status, navigator, and goal surfaces read unchanged.
120
128
  */
121
129
  launchArgv?: string[];
130
+ /** Launch-time evidence, never inferred from current settings or missing profile files. */
131
+ sandbox?: TaskSandboxProvenance;
122
132
  maxLogBytes?: number;
123
133
  logDiscardedBytes?: number;
124
134
  logRetentionEvents?: number;
135
+ /** Own retention writes are not task output. Both fields must still match to ignore them. */
136
+ logMaintenance?: { mtimeMs: number; size: number };
125
137
  /** Incremented on every same-inode compaction so log-page cursors can detect it. */
126
138
  logGeneration?: number;
127
139
  /** Bytes never captured into watch/command buffers. Distinct from logDiscardedBytes. */