pi-suite 0.3.6 → 0.3.8

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 (43) hide show
  1. package/package.json +1 -1
  2. package/src/agents/child.ts +9 -3
  3. package/src/agents/history.ts +3 -3
  4. package/src/agents/index.ts +22 -21
  5. package/src/agents/manager.ts +40 -12
  6. package/src/agents/records.ts +4 -2
  7. package/src/agents/runner.ts +12 -3
  8. package/src/agents/runtime.ts +1 -1
  9. package/src/agents/schedules/menu.ts +1 -1
  10. package/src/agents/types.ts +2 -1
  11. package/src/agents/ui/runs.ts +34 -14
  12. package/src/agents/viewer.ts +69 -43
  13. package/src/agents/workflow/index.ts +32 -9
  14. package/src/agents/workflow/manager.ts +18 -6
  15. package/src/agents/workflow/ui/menu.ts +2 -2
  16. package/src/jobs/index.ts +49 -36
  17. package/src/jobs/manager-record.ts +2 -2
  18. package/src/jobs/manager.ts +30 -12
  19. package/src/jobs/monitors/runtime.ts +41 -27
  20. package/src/jobs/store.ts +49 -10
  21. package/src/jobs/tools.ts +2 -2
  22. package/src/jobs/types.ts +2 -0
  23. package/src/jobs/viewer/metadata.ts +6 -0
  24. package/src/jobs/viewer.ts +30 -25
  25. package/src/runtime/branch.ts +14 -0
  26. package/src/runtime/cleanup/command.ts +116 -0
  27. package/src/runtime/cleanup/locations.ts +91 -0
  28. package/src/runtime/cleanup/occupancy.ts +117 -0
  29. package/src/runtime/cleanup/paths.ts +44 -0
  30. package/src/runtime/cleanup/quarantine.ts +162 -0
  31. package/src/runtime/cleanup/scan.ts +297 -0
  32. package/src/runtime/cleanup/session-use.ts +62 -0
  33. package/src/runtime/cleanup/sessions.ts +119 -0
  34. package/src/runtime/json-store.ts +6 -0
  35. package/src/runtime/owner.ts +1 -1
  36. package/src/runtime/settings/index.ts +9 -1
  37. package/src/runtime/suite.ts +43 -1
  38. package/src/tasks/store.ts +18 -1
  39. package/src/tasks/viewer.ts +14 -12
  40. package/src/ui/actions.ts +1 -1
  41. package/src/ui/browser.ts +95 -43
  42. package/src/ui/scroll.ts +5 -1
  43. package/src/ui/ticker.ts +2 -2
@@ -35,6 +35,7 @@ export class JobManager {
35
35
  readonly runtimeId: string;
36
36
  private store: JobStore;
37
37
  private jobs = new Map<string, Owned>();
38
+ private admissions = new Set<Pick<StartRequest, 'ownerSessionId' | 'cleanupOwner'>>();
38
39
  private listeners = new Set<() => void>();
39
40
  private stoppingCreators = new Set<string>();
40
41
  /** Jobs whose automatic wake was paused by Esc; their results arrive with the next user turn. */
@@ -73,7 +74,7 @@ export class JobManager {
73
74
  if (item.deleting) return item.saveQueue;
74
75
  item.saveQueue = item.saveQueue.then(async () => {
75
76
  if (!item.dirty) return;
76
- item.dirty = false;
77
+ item.dirty = false; item.saving = true;
77
78
  try {
78
79
  await this.store.save(item.job);
79
80
  item.persistenceError = undefined; item.saveAttempts = 0; item.retryAt = undefined;
@@ -81,7 +82,7 @@ export class JobManager {
81
82
  item.dirty = true; item.persistenceError = String(error);
82
83
  item.saveAttempts = (item.saveAttempts ?? 0) + 1;
83
84
  item.retryAt = Date.now() + Math.min(30000, 1000 * 2 ** Math.min(item.saveAttempts - 1, 5));
84
- }
85
+ } finally { item.saving = false; }
85
86
  }).finally(() => this.changed());
86
87
  return item.saveQueue;
87
88
  }
@@ -98,10 +99,15 @@ export class JobManager {
98
99
  throw new ToolError('INVALID_ARGS', 'command must be 1-32768 characters, name at most 80, timeoutMs 1-86400000');
99
100
  }
100
101
  this.admit(signal);
101
- const workspace = await resolveWorkspace(request.cwd);
102
- if (await this.store.workspaceBytes(workspace) >= LIMITS.workspaceBytes) {
103
- throw new ToolError('WORKSPACE_CAPACITY', 'Workspace job history reached 1 GiB; ask the user to delete finished jobs in /jobs');
104
- }
102
+ const admission = {ownerSessionId: request.ownerSessionId, cleanupOwner: request.cleanupOwner};
103
+ this.admissions.add(admission);
104
+ let workspace;
105
+ try {
106
+ workspace = await resolveWorkspace(request.cwd);
107
+ if (await this.store.workspaceBytes(workspace) >= LIMITS.workspaceBytes) {
108
+ throw new ToolError('WORKSPACE_CAPACITY', 'Workspace job history reached 1 GiB; ask the user to delete finished jobs in /jobs');
109
+ }
110
+ } finally { this.admissions.delete(admission); }
105
111
  this.admit(signal);
106
112
  const id = this.store.allocate(workspace);
107
113
  const job: JobSummary = {
@@ -116,7 +122,7 @@ export class JobManager {
116
122
  ...(request.timeoutMs ? { timeoutMs: request.timeoutMs } : {}), exitCode: null,
117
123
  cleanup: { state: 'not_required', scope: [], rootExited: false },
118
124
  };
119
- const item: Owned = { job, launched: false, ready: Promise.withResolvers(), saveQueue: Promise.resolve(), inputQueue: Promise.resolve(), pendingEvents: [] };
125
+ const item: Owned = { job, cleanupOwner: request.cleanupOwner, launched: false, ready: Promise.withResolvers(), saveQueue: Promise.resolve(), inputQueue: Promise.resolve(), pendingEvents: [] };
120
126
  // Registered before any await so a concurrent creator stop or quit includes this job.
121
127
  this.jobs.set(id, item);
122
128
  if (this.creatorStopping(request.creator)) job.stopReason = 'agent';
@@ -296,10 +302,14 @@ export class JobManager {
296
302
  [job.creator.runId, ...job.creator.ancestors].some(runId => roots.has(runId)));
297
303
  }
298
304
  /** Complete creation scope across workspaces and notification owners, without pagination. */
299
- createdBy(runIds: string[]): JobSummary[] { return this.createdItems(runIds).map(item => this.view(item)); }
305
+ createdBy(runIds: string[], matches?: (job: JobSummary) => boolean): JobSummary[] {
306
+ return this.createdItems(runIds).flatMap(item => !matches || matches(item.job) ? [this.view(item)] : []);
307
+ }
300
308
  /** Session ownership spans working directories; branch visibility belongs to JobsModule. */
301
- sessionJobs(sessionId: string): JobSummary[] {
302
- return [...this.jobs.values()].filter(item => item.job.ownerSessionId === sessionId).map(item => this.view(item));
309
+ sessionJobs(sessionId: string, matches?: (job: JobSummary) => boolean): JobSummary[] {
310
+ const jobs: JobSummary[] = [];
311
+ for (const item of this.jobs.values()) if (item.job.ownerSessionId === sessionId && (!matches || matches(item.job))) jobs.push(this.view(item));
312
+ return jobs;
303
313
  }
304
314
  /** Stop every job created by these agent runs or their descendants, including detached ones. */
305
315
  async stopCreatedBy(runIds: string[]): Promise<StopResult[]> {
@@ -490,7 +500,15 @@ export class JobManager {
490
500
  try { this.store.saveSync(job); } catch {}
491
501
  }
492
502
  }
493
- hasOccupancy(): boolean {
494
- return [...this.jobs.values()].some(item => item.deleting || !item.launched || item.dirty || isActive(item.job));
503
+ *cleanupOwners(): IterableIterator<string> {
504
+ for (const admission of this.admissions) {
505
+ yield admission.ownerSessionId;
506
+ if (admission.cleanupOwner) yield admission.cleanupOwner;
507
+ }
508
+ for (const item of this.jobs.values()) if (item.deleting || !item.launched || item.dirty || item.saving || isActive(item.job)) {
509
+ yield item.job.ownerSessionId;
510
+ if (item.cleanupOwner) yield item.cleanupOwner;
511
+ }
495
512
  }
513
+ hasOccupancy(): boolean { return !this.cleanupOwners().next().done; }
496
514
  }
@@ -5,6 +5,7 @@
5
5
  import { spawn } from 'node:child_process';
6
6
  import { open } from 'node:fs/promises';
7
7
  import { StringDecoder } from 'node:string_decoder';
8
+ import { setImmediate as yieldToLoop } from 'node:timers/promises';
8
9
  import { normalizeVisibleText } from '../terminal/visible-text.ts';
9
10
  import { sanitizeText } from '../../runtime/text.ts';
10
11
  import type { ResolvedShellConfig } from '../terminal/shell.ts';
@@ -17,8 +18,9 @@ export type MonitorEvent = {
17
18
  detectorError?: string;
18
19
  };
19
20
  type Candidate = Omit<MonitorEvent, 'eventId' | 'at'>;
20
- type Source = { path: string; stream: MonitorEvent['stream']; pty: boolean; offset: number; decoder: StringDecoder; partial: string };
21
+ type Source = { path: string; stream: MonitorEvent['stream']; pty: boolean; offset: number; decoder: StringDecoder; partial: string[]; tail: string };
21
22
  const TAIL_MS = 250;
23
+ const READ_BYTES = 128 * 1024;
22
24
 
23
25
  function summarizeDiff(previous: string, current: string): string {
24
26
  if (!previous) return `Output changed: now has content (${current.length} chars)`;
@@ -79,7 +81,7 @@ export class JobMonitor {
79
81
  this.timer.unref();
80
82
  }
81
83
  static sources(entries: { path: string; stream: MonitorEvent['stream'] }[], pty: boolean): Source[] {
82
- return entries.map(entry => ({ ...entry, pty, offset: 0, decoder: new StringDecoder('utf8'), partial: '' }));
84
+ return entries.map(entry => ({ ...entry, pty, offset: 0, decoder: new StringDecoder('utf8'), partial: [], tail: '' }));
83
85
  }
84
86
 
85
87
  private tick(final = false): Promise<void> {
@@ -89,41 +91,53 @@ export class JobMonitor {
89
91
  private async readNew(final: boolean): Promise<void> {
90
92
  for (const source of this.sources) {
91
93
  const file = await open(source.path, 'r');
92
- let text = '';
93
94
  try {
95
+ // Drain only the size observed at the start of this tick; a busy writer
96
+ // cannot monopolize it. Each read bounds the synchronous framing/matching work.
94
97
  const { size } = await file.stat();
95
- if (size > source.offset) {
96
- const buffer = Buffer.alloc(size - source.offset);
97
- const { bytesRead } = await file.read(buffer, 0, buffer.length, source.offset);
98
+ const buffer = Buffer.allocUnsafe(Math.min(READ_BYTES, Math.max(0, size - source.offset)));
99
+ while (source.offset < size) {
100
+ const { bytesRead } = await file.read(buffer, 0, Math.min(buffer.length, size - source.offset), source.offset);
101
+ if (!bytesRead) break;
98
102
  source.offset += bytesRead;
99
- text = source.decoder.write(buffer.subarray(0, bytesRead));
103
+ this.accept(source, source.decoder.write(buffer.subarray(0, bytesRead)), false);
104
+ if (source.offset < size) await yieldToLoop();
100
105
  }
101
106
  } finally { await file.close(); }
102
- if (final) text += source.decoder.end();
103
- this.accept(source, text, final);
107
+ if (final) this.accept(source, source.decoder.end(), true);
104
108
  }
105
109
  }
106
110
  private accept(source: Source, text: string, final: boolean): void {
107
- if (this.config.strategy === 'poll-diff') {
108
- // Keep incomplete markers/output across disk reads. A stop in the middle of an iteration
109
- // must not turn its partial output into a spurious final change.
110
- const samples = (source.partial + text).split(POLL_BOUNDARY);
111
- source.partial = final ? '' : samples.pop()!;
112
- if (final) samples.pop();
113
- for (const raw of samples) {
114
- const sample = raw.split(/\r?\n/).map(line =>
115
- (source.pty ? normalizeVisibleText(line) : sanitizeText(line)).trimEnd()).filter(Boolean).join('\n');
116
- this.pollSample(sample, source.stream);
117
- }
111
+ const polling = this.config.strategy === 'poll-diff';
112
+ const separator = polling ? POLL_BOUNDARY : '\n';
113
+ const input = source.tail + text;
114
+ let start = 0;
115
+ for (let end = input.indexOf(separator); end >= 0; end = input.indexOf(separator, start)) {
116
+ if (source.partial.length) source.partial.push(input.slice(start, end));
117
+ const frame = source.partial.length ? source.partial.join('') : input.slice(start, end);
118
+ source.partial.length = 0;
119
+ this.frame(source, !polling && frame.endsWith('\r') ? frame.slice(0, -1) : frame, polling);
120
+ start = end + separator.length;
121
+ }
122
+ const remaining = input.slice(start);
123
+ if (final) {
124
+ // A partial poll iteration is not a sample. A non-terminated stream line is.
125
+ if (!polling) this.frame(source, source.partial.join('') + remaining, false);
126
+ source.partial.length = 0; source.tail = '';
118
127
  return;
119
128
  }
120
- const lines = (source.partial + text).split(/\r?\n/);
121
- source.partial = final ? '' : lines.pop()!;
122
- for (const raw of lines) {
123
- // PTY lines replay CR overwrites to the final visible text; pipe lines drop control bytes.
124
- const line = (source.pty ? normalizeVisibleText(raw) : sanitizeText(raw)).trimEnd();
125
- if (!line) continue;
126
- this.match(line, line, source.stream);
129
+ // Only the suffix that could contain half a delimiter is searched again.
130
+ // Store the remaining fragments rather than repeatedly joining a long line/sample.
131
+ const tailLength = Math.min(remaining.length, separator.length - 1);
132
+ if (remaining.length > tailLength) source.partial.push(remaining.slice(0, remaining.length - tailLength));
133
+ source.tail = tailLength ? remaining.slice(-tailLength) : '';
134
+ }
135
+ private frame(source: Source, raw: string, polling: boolean): void {
136
+ const visible = (line: string) => (source.pty ? normalizeVisibleText(line) : sanitizeText(line)).trimEnd();
137
+ if (polling) this.pollSample(raw.split(/\r?\n/).map(visible).filter(Boolean).join('\n'), source.stream);
138
+ else {
139
+ const line = visible(raw);
140
+ if (line) this.match(line, line, source.stream);
127
141
  }
128
142
  }
129
143
  private pollSample(sample: string, stream: MonitorEvent['stream']): void {
package/src/jobs/store.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  import { lstatSync, realpathSync, mkdirSync, writeFileSync, renameSync, unlinkSync, existsSync } from 'node:fs';
6
6
  import { readdir, readFile, writeFile, rename, rm, stat, unlink, appendFile } from 'node:fs/promises';
7
7
  import { join, relative, sep, isAbsolute } from 'node:path';
8
- import { randomBytes, randomUUID } from 'node:crypto';
8
+ import { createHash, randomBytes, randomUUID } from 'node:crypto';
9
9
  import { isTerminal } from './state.ts';
10
10
  import { ToolError } from '../runtime/errors.ts';
11
11
  import { SNAPSHOT_BYTES, SNAPSHOT_SCROLLBACK, type TerminalSnapshot } from './terminal/snapshot.ts';
@@ -43,9 +43,12 @@ export class JobStore {
43
43
  }
44
44
  }
45
45
  }
46
- directory(job: Pick<JobSummary, 'id' | 'workspace'>): string {
46
+ private jobDirectory(job: Pick<JobSummary, 'id' | 'workspace'>): string {
47
47
  if (!JOB_ID.test(job.id) || !HASH.test(job.workspace.hash)) throw new ToolError('UNSAFE_PATH', 'Invalid internal job identity');
48
- const dir = join(this.root, job.workspace.hash, job.id);
48
+ return join(this.root, job.workspace.hash, job.id);
49
+ }
50
+ directory(job: Pick<JobSummary, 'id' | 'workspace'>): string {
51
+ const dir = this.jobDirectory(job);
49
52
  this.secure(dir);
50
53
  return dir;
51
54
  }
@@ -145,24 +148,60 @@ export class JobStore {
145
148
  let ids: string[];
146
149
  try { ids = await readdir(root); }
147
150
  catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') errors.push(String(error)); return { jobs, errors }; }
148
- for (const id of ids) {
149
- try { jobs.push(await this.load(workspace, id)); }
150
- catch (error) { errors.push(`${id}: ${String(error)}`.slice(0, 512)); }
151
+ // Bound IO fan-out without changing the order of history or per-record diagnostics.
152
+ const batchSize = 16;
153
+ for (let offset = 0; offset < ids.length; offset += batchSize) {
154
+ const batch = await Promise.all(ids.slice(offset, offset + batchSize).map(async id => {
155
+ try { return await this.load(workspace, id); }
156
+ catch (error) { return `${id}: ${String(error)}`.slice(0, 512); }
157
+ }));
158
+ for (const result of batch) typeof result === 'string' ? errors.push(result) : jobs.push(result);
151
159
  }
152
160
  return { jobs, errors };
153
161
  }
154
162
  async load(workspace: Workspace, id: string): Promise<JobSummary> {
155
- const path = join(this.directory({ id, workspace }), 'job.json'); this.secure(path);
163
+ const path = join(this.jobDirectory({ id, workspace }), 'job.json'); this.secure(path);
164
+ const job = await this.readRecord(path, id, workspace.hash);
165
+ if (job.workspace.key !== workspace.key) throw new ToolError('CORRUPT_HISTORY', 'Mismatched job workspace', id);
166
+ return job;
167
+ }
168
+ private async readRecord(path: string, id: string, hash: string): Promise<JobSummary> {
156
169
  const job = JSON.parse(await readFile(path, 'utf8')) as JobSummary;
157
- if (job?.schemaVersion !== 1 || job.id !== id || job.workspace?.hash !== workspace.hash || job.workspace.key !== workspace.key ||
170
+ if (job?.schemaVersion !== 1 || job.id !== id || job.workspace?.hash !== hash || typeof job.workspace.key !== 'string' ||
158
171
  !STATES.includes(job.state) || !['pipe', 'pty'].includes(job.mode) || typeof job.command !== 'string' ||
159
172
  typeof job.ownerSessionId !== 'string' || !CLEANUP.includes(job.cleanup?.state)) throw new ToolError('CORRUPT_HISTORY', 'Unsupported or mismatched job record', id);
160
173
  return job;
161
174
  }
175
+ async *maintenanceHistory(onRecordError: (path: string, error: unknown) => void): AsyncGenerator<JobSummary> {
176
+ this.secure(this.root);
177
+ const dirs = async (path: string) => readdir(path, {withFileTypes: true}).catch((error: NodeJS.ErrnoException) => {
178
+ if (error.code === 'ENOENT' && path === this.root) return []; throw error;
179
+ });
180
+ // Workspace queries cannot find every job owned by a session: cwd may differ.
181
+ for (const workspace of await dirs(this.root)) {
182
+ if (!HASH.test(workspace.name)) continue;
183
+ const root = join(this.root, workspace.name); this.secure(root);
184
+ if (!workspace.isDirectory()) throw new Error(`Invalid job workspace: ${root}`);
185
+ for (const entry of await dirs(root)) {
186
+ if (!JOB_ID.test(entry.name)) continue;
187
+ const path = join(root, entry.name, 'job.json');
188
+ let job: JobSummary;
189
+ try {
190
+ this.secure(path);
191
+ if (!entry.isDirectory()) throw new Error(`Invalid job directory: ${path}`);
192
+ job = await this.readRecord(path, entry.name, workspace.name);
193
+ if (createHash('sha256').update(job.workspace.key).digest('hex') !== workspace.name) throw new Error(`Invalid job workspace hash: ${path}`);
194
+ } catch (error) { onRecordError(path, error); continue; }
195
+ yield job;
196
+ }
197
+ }
198
+ }
199
+ assertRemovable(job: JobSummary): void {
200
+ if (!isTerminal(job.state) || ['pending', 'unconfirmed'].includes(job.cleanup.state)) throw new ToolError('JOB_OCCUPIED', 'Cannot delete an active or unconfirmed job', job.id);
201
+ }
162
202
  async remove(job: JobSummary): Promise<void> {
163
203
  // Check disk state again; the caller's snapshot cannot authorize deleting live history.
164
- const stored = await this.load(job.workspace, job.id);
165
- if (!isTerminal(stored.state) || ['pending', 'unconfirmed'].includes(stored.cleanup.state)) throw new ToolError('JOB_OCCUPIED', 'Cannot delete an active or unconfirmed job', job.id);
204
+ this.assertRemovable(await this.load(job.workspace, job.id));
166
205
  await rm(this.directory(job), { recursive: true });
167
206
  }
168
207
  }
package/src/jobs/tools.ts CHANGED
@@ -27,7 +27,7 @@ const listSchema = Type.Object(listFields(['active', 'finished', 'all'] as const
27
27
  const getSchema = Type.Object({ id, detail: Type.Optional(Type.Boolean()) }, { additionalProperties: false });
28
28
  const queryHint = 'List: job_list({"state":"all"}); one job: job_get({"id":"job_3fa1c2d0"}).';
29
29
 
30
- export function registerJobTools(pi: ExtensionAPI, jobs: JobsModule, viewer: ViewerDeps, launch: { config: () => SuiteConfig; tasks?: TasksModule; creator?: Creator }): void {
30
+ export function registerJobTools(pi: ExtensionAPI, jobs: JobsModule, viewer: ViewerDeps, launch: { config: () => SuiteConfig; tasks?: TasksModule; creator?: Creator; cleanupOwner?: string }): void {
31
31
  registerBoundTool(pi, {
32
32
  name: 'job_start', ...startRenderers, label: 'Start Job',
33
33
  description: 'Start a command as a background job and return at once. mode=pipe (default) records stdout/stderr for builds, tests and batch work; mode=pty runs it in a terminal for REPLs and interactive programs. ' +
@@ -67,7 +67,7 @@ export function registerJobTools(pi: ExtensionAPI, jobs: JobsModule, viewer: Vie
67
67
  }
68
68
  const taskStore = params.taskId ? await launch.tasks!.executionTask(ctx, params.taskId, params.taskGeneration!) : undefined;
69
69
  // Pi waits for piped stdin EOF before its initial prompt; PTY keeps interactive input.
70
- const job = await manager.start({ ...request, command, cwd, ...owner, creator: launch.creator,
70
+ const job = await manager.start({ ...request, command, cwd, ...owner, creator: launch.creator, cleanupOwner: launch.cleanupOwner,
71
71
  closeInput: agent?.preset === 'pi' && params.mode !== 'pty' }, shell, signal);
72
72
  if (taskStore && params.taskId) {
73
73
  try { await taskStore.link(params.taskId, { jobId: job.id }, params.taskGeneration!); }
package/src/jobs/types.ts CHANGED
@@ -40,6 +40,8 @@ export type StartRequest = {
40
40
  /** Omitted only for a file-watch monitor, which generates its own command. */
41
41
  command?: string; name?: string; cwd: string; mode?: JobMode; timeoutMs?: number; taskId?: string; taskGeneration?: string;
42
42
  ownerSessionId: string; anchorEntryId: string | null; creator?: Creator; cols?: number; rows?: number;
43
+ /** Root attribution for an active job owned by a child SDK session. */
44
+ cleanupOwner?: string;
43
45
  monitor?: MonitorInput; handsFree?: HandsFreeInput;
44
46
  /** Noninteractive pipe callers close stdin during launch, before a short command can exit. */
45
47
  closeInput?: boolean;
@@ -3,6 +3,12 @@ import { executionRow } from '../../ui/dock/line.ts';
3
3
  import { displayName, jobStatus, jobCompactStatus } from '../index.ts';
4
4
  import type { JobSummary } from '../types.ts';
5
5
 
6
+ /** A paint tick advances elapsed time only; lifecycle data arrives via the owner subscription. */
7
+ export function timedJob(job: JobSummary, measuredAt: number): JobSummary {
8
+ return job.endedAt === undefined && job.elapsedMs !== undefined
9
+ ? {...job, elapsedMs: job.elapsedMs + Math.round(performance.now() - measuredAt)} : job;
10
+ }
11
+
6
12
  /** Lists and viewers protect the same domain-ordered state/time/cleanup metrics. */
7
13
  export function jobRow(job: JobSummary, width: number, theme?: Theme): string {
8
14
  return executionRow(displayName(job), jobStatus(job), jobCompactStatus(job), width, theme);
@@ -4,18 +4,19 @@ import type { Dock } from '../ui/dock.ts';
4
4
  import { showDetails } from '../ui/details.ts';
5
5
  import { TerminalView, type TerminalExit, type TerminalKeys } from '../ui/terminal.ts';
6
6
  import { ToolError } from '../runtime/errors.ts';
7
- import { isActive } from './state.ts';
7
+ import { bucket, isActive } from './state.ts';
8
+ import { newestFirst } from '../runtime/tools.ts';
8
9
  import { JOB_SCREEN, type JobScreenDetails } from './render.ts';
9
10
  import { resolveWorkspace } from './workspace.ts';
10
- import { JobsModule, displayName, summaryLine, jobLabel } from './index.ts';
11
- import { jobViewerDetails, type ListScope } from './query.ts';
11
+ import { JobsModule, displayName, summaryLine } from './index.ts';
12
+ import { jobViewerDetails, type ListRow, type ListScope } from './query.ts';
12
13
  import type { JobSummary } from './types.ts';
13
14
  import { browse, browseState, compareActivity } from '../ui/browser.ts';
14
15
  import { openReading } from '../ui/reading.ts';
15
16
  import { ViewerNavigation } from '../ui/viewer/navigation.ts';
16
17
  import { TerminalScreen } from './terminal/screen.ts';
17
18
  import { JobView } from './viewer/component.ts';
18
- import { jobRow } from './viewer/metadata.ts';
19
+ import { jobRow, timedJob } from './viewer/metadata.ts';
19
20
 
20
21
  export interface ViewerDeps { jobs: JobsModule; dock: Dock; notifications: Notifications; keys: () => TerminalKeys }
21
22
 
@@ -66,41 +67,45 @@ async function pickJob(pi: ExtensionAPI, ctx: ExtensionCommandContext, deps: Vie
66
67
  const workspace = await resolveWorkspace(ctx.cwd);
67
68
  const viewState = browseState(), navigation = new ViewerNavigation();
68
69
  while (!navigation.closed) {
69
- const { rows, errors } = await deps.jobs.list(workspace, { state: 'all', scope, limit: Number.MAX_SAFE_INTEGER }, ctx);
70
+ const control = deps.jobs.control();
71
+ const { jobs, errors } = await control.list(workspace);
70
72
  for (const error of errors) ctx.ui.notify(`history error: ${error}`, 'warning');
71
- const current = () => deps.jobs.browseRows(rows, { state, scope }, ctx).sort((a, b) => compareActivity(a.job, b.job, isActive));
72
- let changed = false;
73
- // Native row layout runs once per visible row; index the current item snapshot instead
74
- // of sorting/scanning the complete history again for each rendered name or suffix.
75
- let displayed = new Map<string, JobSummary>();
73
+ let changed = false, ticking = false, total = 0, finished = 0;
74
+ let displayed = new Map<string, ListRow>(), measuredAt = 0;
75
+ const liveView = ({job, live}: ListRow) => live ? timedJob(job, measuredAt) : job;
76
76
  const choice = await browse(ctx, deps.dock, { title: 'Jobs', state: viewState, navigation,
77
- layout: {truncatePrimary: context => {
78
- const job = displayed.get(context.item.value)!;
79
- return jobRow(job, context.maxWidth, context.theme);
80
- }},
77
+ layout: {truncatePrimary: context => jobRow(liveView(displayed.get(context.item.value)!), context.maxWidth, context.theme)},
81
78
  controls: [
82
79
  {key: 'w', label: 'Scope', selected: () => scope, items: () => [{value: 'session', label: 'This session'}, {value: 'workspace', label: 'Workspace'}],
83
80
  select: (value, done) => {scope = value as ListScope; changed = true; done();}},
84
81
  {key: 's', label: 'State', selected: () => state, items: () => STATES.map(value => ({value, label: value[0].toUpperCase() + value.slice(1),
85
- description: String(deps.jobs.browseRows(rows, {state: value, scope}, ctx).length)})),
82
+ description: String(value === 'all' ? total : finished)})),
86
83
  select: value => {state = value as BrowseJobState;}},
87
84
  ],
88
- total: () => deps.jobs.browseRows(rows, {state: 'all', scope}, ctx).length,
89
- selection: item => ({name: displayName(displayed.get(item.value)!)}),
90
- subscribe: refresh => deps.jobs.control().subscribe(refresh), ticking: () => current().some(row => isActive(row.job)),
85
+ total: () => total, selection: item => ({name: displayName(displayed.get(item.value)!.job)}),
86
+ subscribe: refresh => control.subscribe(refresh), ticking: () => ticking,
91
87
  items: () => {
92
- const items = current(); displayed = new Map(items.map(({job}) => [job.id, job]));
93
- return items.map(({ job, live }) => ({ value: job.id, status: job.state,
94
- label: displayName(job), display: jobLabel(job),
95
- search: `${job.id} ${displayName(job)} ${job.state} ${job.command} ${job.cwd}`,
96
- details: () => jobViewerDetails(job, live),
97
- }));
88
+ const rows = deps.jobs.browseRows(jobs, scope, ctx);
89
+ measuredAt = performance.now();
90
+ total = rows.length;
91
+ const settled = rows.filter(({job, live}) => bucket(job, live) === 'finished');
92
+ finished = settled.length;
93
+ const items = (state === 'finished' ? settled : rows)
94
+ .sort((a, b) => compareActivity(a.job, b.job, isActive) || newestFirst(a.job, b.job));
95
+ ticking = items.some(({job, live}) => live && isActive(job));
96
+ displayed = new Map(items.map(row => [row.job.id, row]));
97
+ return items.map(row => {
98
+ const {job} = row, label = displayName(job);
99
+ return { value: job.id, label,
100
+ search: `${job.id} ${label} ${job.state} ${job.command} ${job.cwd}`,
101
+ details: () => jobViewerDetails(liveView(row), row.live) };
102
+ });
98
103
  },
99
104
  });
100
105
  if (navigation.closed) return;
101
106
  if (changed) continue;
102
107
  if (choice === undefined) return;
103
- const job = current().find(row => row.job.id === choice)?.job;
108
+ const job = displayed.get(choice)?.job;
104
109
  if (job) await jobActions(pi, ctx, deps, job.id, false, job.cwd, navigation);
105
110
  }
106
111
  }
@@ -0,0 +1,14 @@
1
+ import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
2
+
3
+ type SessionManager = ExtensionContext['sessionManager'];
4
+
5
+ const branches = new WeakMap<SessionManager, { sessionId: string; leaf: string | null; ids: ReadonlySet<string> }>();
6
+
7
+ /** Pi rebuilds a branch on every getBranch() call. Share membership across consumers of the same leaf. */
8
+ export function branchIds(session: SessionManager): ReadonlySet<string> {
9
+ const leaf = session.getLeafId(), sessionId = session.getSessionId(), cached = branches.get(session);
10
+ if (cached?.leaf === leaf && cached.sessionId === sessionId) return cached.ids;
11
+ const ids = new Set(session.getBranch().map(entry => entry.id));
12
+ branches.set(session, { sessionId, leaf, ids });
13
+ return ids;
14
+ }
@@ -0,0 +1,116 @@
1
+ import { realpath } from 'node:fs/promises';
2
+ import { join, resolve } from 'node:path';
3
+ import { formatSize, getAgentDir, SettingsManager, type ExtensionCommandContext } from '@earendil-works/pi-coding-agent';
4
+ import { AGENT_OWNER, WORKFLOW_OWNER } from '../../agents/registry.ts';
5
+ import { globals, key } from '../../jobs/registry.ts';
6
+ import { withJsonFileLock } from '../json-store.ts';
7
+ import { existingOwner, ownerBusy } from '../owner.ts';
8
+ import { sanitizeText } from '../text.ts';
9
+ import { maintenanceDir, rememberVerifiedHome } from './locations.ts';
10
+ import { inspect, matches, pathKey } from './paths.ts';
11
+ import { orphanCandidates } from './scan.ts';
12
+ import { batches, quarantine, quarantinedBytes, restore } from './quarantine.ts';
13
+ import { coordinated, enableCoordination, readOccupancy, withCoordination } from './occupancy.ts';
14
+
15
+ export async function cleanupCommand(args: string, ctx: ExtensionCommandContext): Promise<void> {
16
+ const [action, id, extra] = args.trim().split(/\s+/);
17
+ if (extra || action && !['restore', 'list', 'coordinate'].includes(action) || (action === 'restore') !== Boolean(id)) {
18
+ throw new Error('Usage: /suite cleanup [list | restore <batch-id> | coordinate]');
19
+ }
20
+ const configuredAgentDir = getAgentDir();
21
+ const agentDir = await realpath(configuredAgentDir);
22
+ if (action !== 'list' && (ctx.mode !== 'tui' || !ctx.isIdle())) {
23
+ throw new Error('Run this command from an idle Pi terminal.');
24
+ }
25
+ const occupied = (includeCurrent = true) => {
26
+ const ids = new Set<string>();
27
+ if (includeCurrent) ids.add(ctx.sessionManager.getSessionId());
28
+ for (const dir of new Set([configuredAgentDir, agentDir])) {
29
+ for (const key of [AGENT_OWNER, WORKFLOW_OWNER]) {
30
+ const owner = existingOwner(key, dir);
31
+ if (owner?.cleanupOwners) for (const id of owner.cleanupOwners()) ids.add(id);
32
+ else if (ownerBusy(key, dir)) throw new Error('An older execution runtime cannot identify its active sessions. Restart Pi before cleanup.');
33
+ }
34
+ }
35
+ const jobs = globals[key];
36
+ if (jobs && (jobs.agentDir === agentDir || jobs.requestedAgentDir === configuredAgentDir)) {
37
+ if (jobs.manager.cleanupOwners) for (const id of jobs.manager.cleanupOwners()) ids.add(id);
38
+ else if (jobs.manager.hasOccupancy?.() !== false) throw new Error('An older Job runtime cannot identify its active sessions. Restart Pi before cleanup.');
39
+ }
40
+ return ids;
41
+ };
42
+ if (action === 'list') {
43
+ const ids = await batches(agentDir);
44
+ ctx.ui.notify(ids.length ? `Cleanup batches:\n${ids.join('\n')}` : 'No recoverable cleanup batches.', 'info');
45
+ return;
46
+ }
47
+ const root = maintenanceDir(agentDir);
48
+ await inspect(agentDir, root);
49
+ if (action === 'coordinate') {
50
+ if (occupied(false).size) throw new Error('Let background executions settle before enabling cleanup coordination.');
51
+ await withJsonFileLock(join(root, 'operation.lock'), 'CLEANUP', () => enableCoordination(agentDir));
52
+ ctx.ui.notify('Local cleanup coordination enabled. Reload Pi to register this session.', 'info');
53
+ return;
54
+ }
55
+ if (!action) ctx.ui.notify('Starting cleanup: scanning for orphaned session data…', 'info');
56
+ const online = await coordinated(agentDir);
57
+ const custom = action === 'restore' ? undefined : process.env.PI_CODING_AGENT_SESSION_DIR || SettingsManager.create(ctx.cwd, agentDir,
58
+ {projectTrusted: ctx.isProjectTrusted()}).getSessionDir();
59
+ const scope = custom ? resolve(ctx.cwd, custom) : undefined;
60
+ // Discovery does not block session admission or reference publication. Only the
61
+ // authoritative rescan and filesystem moves share the coordination transaction.
62
+ const discovery = action === 'restore' ? undefined : await orphanCandidates(agentDir, scope, occupied());
63
+ const apply = async (remote?: ReturnType<typeof readOccupancy>) => {
64
+ if (remote && !remote.local.has(ctx.sessionManager.getSessionId())) throw new Error('This session is not registered for coordinated cleanup. Reload Pi and retry.');
65
+ const protectedIds = () => new Set([...occupied(), ...remote?.held ?? []]);
66
+ if (action === 'restore') {
67
+ const result = await restore(agentDir, id!, protectedIds);
68
+ report(ctx, `Restored ${result.restored} item(s)`, result.errors);
69
+ } else {
70
+ if (!discovery!.groups.length) return {ids: [], moved: [], errors: [], warnings: discovery!.warnings};
71
+ const verified = await orphanCandidates(agentDir, scope, protectedIds(), remote?.sources);
72
+ const candidates = new Map(discovery!.groups.map(group => [group.home.id, group]));
73
+ const ready = [];
74
+ const members = new Map<string, Set<string>>();
75
+ for (const group of verified.groups) {
76
+ const owner = group.home.id, first = candidates.get(owner);
77
+ if (!first) continue;
78
+ const prior = new Map(first.items.map(item => [pathKey(item.path), item]));
79
+ if (group.items.length !== prior.size || group.items.some(item => {
80
+ const expected = prior.get(pathKey(item.path));
81
+ return !expected || !matches(item.stamp, expected.stamp);
82
+ })) continue;
83
+ await rememberVerifiedHome(agentDir, group.home);
84
+ // Session files supply child ownership and creator proof for a later retry.
85
+ members.set(owner, group.sessionIds);
86
+ ready.push(...group.items.toSorted((a, b) => Number(a.kind === 'subagents') - Number(b.kind === 'subagents')));
87
+ }
88
+ const result = await quarantine(agentDir, ready, owner => {
89
+ const ids = protectedIds();
90
+ return [...members.get(owner)!].some(id => ids.has(id));
91
+ });
92
+ return {...result, warnings: verified.warnings};
93
+ }
94
+ };
95
+ const result = online ? await withCoordination(agentDir, db => apply(readOccupancy(db)))
96
+ : await withJsonFileLock(join(root, 'operation.lock'), 'CLEANUP', async () => {
97
+ if (await coordinated(agentDir)) throw new Error('Cleanup coordination was enabled. Reload Pi and retry.');
98
+ return apply();
99
+ });
100
+ if (!result) return;
101
+ // Size is for display only: don't hold the coordination lock while walking moved directories.
102
+ let size: string;
103
+ try { size = formatSize(await quarantinedBytes(result.moved)); }
104
+ catch (error) {
105
+ size = 'size unavailable';
106
+ result.warnings.push(`Could not measure quarantined data: ${String(error)}`);
107
+ }
108
+ const batch = result.ids.length ? ` · batch ${result.ids.join(', ')}` : '';
109
+ report(ctx, `Cleanup complete: Quarantined ${result.moved.length} item(s) · ${size}${batch}`, result.errors, result.warnings);
110
+ }
111
+
112
+ function report(ctx: ExtensionCommandContext, headline: string, errors: string[], warnings: string[] = []): void {
113
+ ctx.ui.notify(`${headline}.`, errors.length ? 'error' : 'info');
114
+ for (const warning of warnings) ctx.ui.notify(sanitizeText(warning), 'warning');
115
+ for (const error of errors) ctx.ui.notify(sanitizeText(error), 'error');
116
+ }