@abelxiaoxing/cadence 2.0.38 → 2.0.41

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.
@@ -1,429 +1,55 @@
1
- /** Model-facing observation tools and their worker-local resource lifetime.
2
- * A cursor is one-use navigation, never execution authority or a durable snapshot. */
3
- import { randomUUID } from "node:crypto";
4
- import { Type } from "typebox";
5
- import { RESEARCH_LIMITS as L, ResearchScan } from "./research-scan.mjs";
1
+ /** Pi's standard readonly file tools, at the admitted investigation location.
2
+ * No second file protocol, scanner, cursor registry or model-managed cleanup. */
3
+ import { readFile, stat } from "node:fs/promises";
4
+ import {
5
+ createFindToolDefinition,
6
+ createGrepToolDefinition,
7
+ createLsToolDefinition,
8
+ createReadToolDefinition,
9
+ detectSupportedImageMimeTypeFromFile,
10
+ } from "@earendil-works/pi-coding-agent";
6
11
 
7
- const object = (value, keys) => {
8
- if (
9
- !value ||
10
- typeof value !== "object" ||
11
- Array.isArray(value) ||
12
- Object.keys(value).some((key) => !keys.includes(key))
13
- )
14
- throw new Error("Invalid investigation arguments");
15
- return value;
16
- };
17
- const integer = (value, maximum = Number.MAX_SAFE_INTEGER, minimum = 1) => {
18
- if (!Number.isSafeInteger(value) || value < minimum || value > maximum)
19
- throw new Error("Invalid investigation range or limit");
20
- return value;
21
- };
22
- const string = (value, maximum = 4096) => {
23
- if (
24
- typeof value !== "string" ||
25
- !value ||
26
- value.length > maximum ||
27
- value.includes("\0")
28
- )
29
- throw new Error("Invalid investigation path or pattern");
30
- return value;
31
- };
32
- const array = (value, maximum) => {
33
- if (!Array.isArray(value) || !value.length || value.length > maximum)
34
- throw new Error("Invalid investigation batch");
35
- return value;
36
- };
37
- const glob = (value) => {
38
- string(value, 256);
39
- if (/[{}()]/u.test(value))
40
- throw new Error("Use a simple glob without braces or extglobs");
41
- return value;
42
- };
43
- function query(kind, args) {
44
- const common = ["pageSize", "path"];
45
- object(args, [
46
- ...common,
47
- ...(kind === "read"
48
- ? ["files", "offset", "limit"]
49
- : kind === "grep"
50
- ? ["pattern", "patterns", "glob", "depth", "ignoreCase", "literal"]
51
- : kind === "find"
52
- ? ["pattern", "depth"]
53
- : []),
54
- ]);
55
- const result = {
56
- kind,
57
- pageSize: integer(args.pageSize ?? L.results, L.results),
58
- };
59
- if (kind === "read") {
60
- if (
61
- args.files !== undefined &&
62
- ["path", "offset", "limit"].some((key) => args[key] !== undefined)
63
- )
64
- throw new Error("Select either one file or a file batch");
65
- const offset = integer(args.offset ?? 1);
66
- const end =
67
- args.limit === undefined
68
- ? Number.MAX_SAFE_INTEGER
69
- : integer(offset + integer(args.limit) - 1);
70
- const files =
71
- args.files === undefined
72
- ? [{ path: string(args.path), ranges: [{ start: offset, end }] }]
73
- : array(args.files, L.files);
74
- let count = 0;
75
- result.files = files.map((entry) => {
76
- object(entry, ["path", "ranges"]);
77
- const ranges = entry.ranges ?? [
78
- { start: 1, end: Number.MAX_SAFE_INTEGER },
79
- ];
80
- return {
81
- path: string(entry.path),
82
- ranges: array(ranges, L.ranges).map((range) => {
83
- object(range, ["start", "end"]);
84
- if (++count > L.ranges)
85
- throw new Error("Too many requested line ranges");
86
- const start = integer(range.start);
87
- return {
88
- start,
89
- end: integer(range.end, Number.MAX_SAFE_INTEGER, start),
90
- };
91
- }),
92
- };
93
- });
94
- } else {
95
- result.path = args.path === undefined ? undefined : string(args.path);
96
- result.depth = integer(args.depth ?? L.depth, L.depth, 0);
97
- if (kind === "find") result.glob = glob(args.pattern);
98
- if (kind === "grep") {
99
- if (args.literal !== undefined && args.literal !== true)
100
- throw new Error("Research grep supports literal text only, not regex");
101
- if (args.ignoreCase !== undefined && typeof args.ignoreCase !== "boolean")
102
- throw new Error("Invalid case selection");
103
- if ((args.pattern === undefined) === (args.patterns === undefined))
104
- throw new Error("Supply one pattern or a patterns array");
105
- result.ignoreCase = args.ignoreCase === true;
106
- result.patterns = array(args.patterns ?? [args.pattern], L.patterns).map(
107
- (pattern) => {
108
- const text = string(pattern, 256);
109
- return result.ignoreCase ? text.toLowerCase() : text;
110
- },
111
- );
112
- if (args.glob !== undefined) result.glob = glob(args.glob);
113
- }
114
- }
115
- return result;
116
- }
12
+ export const RESEARCH_INSTRUCTIONS =
13
+ "Use Pi's read, grep, find and ls tools directly. read accepts one path with optional offset/limit; follow its next-offset notice for more text. grep accepts one pattern, find accepts a glob, and ls lists a directory. Searches respect .gitignore; use explicit paths and directory listings when investigating ignored dependencies or backups. Explicit absolute paths outside the checkout remain readable. Relative paths use the first investigation root. These are live filesystem reads, not a snapshot: report truncation and unresolved coverage honestly. There is no bash, write or edit tool in this readonly role; shell work belongs to an authorized implementation. Keep credentials and private session content out of reports.";
117
14
 
118
- const path = Type.Optional(
119
- Type.String({
120
- minLength: 1,
121
- maxLength: 4096,
122
- description:
123
- "Within the admitted roots; relative paths use the first root.",
124
- }),
125
- );
126
- const pageSize = Type.Optional(
127
- Type.Integer({ minimum: 1, maximum: L.results }),
128
- );
129
- const depth = Type.Optional(Type.Integer({ minimum: 0, maximum: L.depth }));
130
- const pattern = Type.String({ minLength: 1, maxLength: 256 });
131
- // Provider function schemas require an object root, not a union of objects.
132
- // Initial-query versus continuation exclusivity is checked before admission;
133
- // every field is optional here because a continuation carries no query fields.
134
- const parameters = (shape) =>
135
- Type.Partial(
136
- Type.Object({
137
- ...shape,
138
- cursor: Type.String({ minLength: 1, maxLength: 128 }),
139
- close: Type.Literal(true),
140
- }),
141
- { additionalProperties: false },
142
- );
143
- const definitions = [
144
- {
145
- name: "read",
146
- description:
147
- "Read UTF-8 text or a batch of file/line ranges. Use path with optional 1-based offset/limit, or files with ranges {start,end}. Overlapping ranges are merged. pageSize bounds one response, not the requested range. Resume a returned cursor instead of rereading a prefix; {cursor,close:true} releases it. Long/binary/invalid text omissions are explicit.",
148
- parameters: parameters({
149
- path,
150
- offset: Type.Optional(Type.Integer({ minimum: 1 })),
151
- limit: Type.Optional(Type.Integer({ minimum: 1 })),
152
- files: Type.Optional(
153
- Type.Array(
154
- Type.Object(
155
- {
156
- path: Type.String(),
157
- ranges: Type.Optional(
158
- Type.Array(
159
- Type.Object({
160
- start: Type.Integer({ minimum: 1 }),
161
- end: Type.Integer({ minimum: 1 }),
162
- }),
163
- { minItems: 1, maxItems: L.ranges },
164
- ),
165
- ),
166
- },
167
- { additionalProperties: false },
168
- ),
169
- { minItems: 1, maxItems: L.files },
170
- ),
171
- ),
172
- pageSize,
173
- }),
174
- },
175
- {
176
- name: "grep",
177
- description:
178
- "Search literal text, not regex, in one file or a tree. Supply pattern or patterns (OR; matchedPatterns are zero-based input indexes). Each file is scanned once per query. Optional simple glob, ignoreCase and depth. No symlink traversal, .gitignore interpretation, or .git/node_modules scan. Empty pages with a cursor are progress, NOT absence. Resume with {cursor}, or release with {cursor,close:true}.",
179
- parameters: parameters({
180
- path,
181
- pattern: Type.Optional(pattern),
182
- patterns: Type.Optional(
183
- Type.Array(pattern, { minItems: 1, maxItems: L.patterns }),
184
- ),
185
- glob: Type.Optional(pattern),
186
- literal: Type.Optional(Type.Literal(true)),
187
- ignoreCase: Type.Optional(Type.Boolean()),
188
- depth,
189
- pageSize,
15
+ export function createResearchTools(workspace) {
16
+ const cwd = workspace.roots[0];
17
+ const definitions = [
18
+ createReadToolDefinition(cwd, {
19
+ operations: {
20
+ readFile,
21
+ detectImageMimeType: detectSupportedImageMimeTypeFromFile,
22
+ async access(path) {
23
+ // Pi resolves paths first. Follow regular-file aliases, but never
24
+ // intentionally open a device, socket, pipe or directory for reading.
25
+ if (!(await stat(path)).isFile())
26
+ throw new Error("Only regular files can be read");
27
+ },
28
+ },
190
29
  }),
191
- },
192
- {
193
- name: "find",
194
- description:
195
- "Find file paths with a simple glob (*, **, ?, brackets; no braces/extglobs). Bounded traversal in filesystem order, skipping tree symlinks and .git/node_modules, not backup trees; .gitignore is not interpreted. Resume actual directory positions with {cursor}; {cursor,close:true} releases them. Coverage/omissions are explicit.",
196
- parameters: parameters({ path, pattern, depth, pageSize }),
197
- },
198
- {
199
- name: "ls",
200
- description:
201
- "List one directory in filesystem order, including entry kinds. Does not follow symlinks or recurse. Continue with the returned {cursor}, not a repeated initial request; {cursor,close:true} releases it.",
202
- parameters: parameters({ path, pageSize }),
203
- },
204
- ];
205
-
206
- function render(scan, items, state, nextCursor, pausedBy, elapsedMs) {
207
- const omissions = [...scan.omissions].map(([reason, count]) => ({
208
- reason,
209
- count,
210
- }));
211
- const details = {
212
- state,
213
- nextCursor,
214
- pausedBy,
215
- coverage: {
216
- complete: state === "done" && !omissions.length,
217
- consistency: "live-filesystem",
218
- omissions,
219
- },
220
- progress: { ...scan.page, total: { ...scan.total } },
221
- elapsedMs,
222
- ...(state === "more" || omissions.length
223
- ? {
224
- truncation: {
225
- reason: [
226
- ...(pausedBy ? [pausedBy] : []),
227
- ...omissions.map((o) => o.reason),
228
- ],
229
- },
230
- }
231
- : {}),
232
- };
233
- return {
234
- content: [{ type: "text", text: JSON.stringify({ items, ...details }) }],
235
- details,
236
- };
237
- }
238
- const size = (result) => Buffer.byteLength(JSON.stringify(result));
239
-
240
- export function createResearchTools(workspace, now = () => performance.now()) {
241
- const scans = new Set();
242
- const cursors = new Map();
243
- let closing = false,
244
- closingOriginal,
245
- failure;
246
- const finish = (scan) => {
247
- scan.finishing ??= (async () => {
248
- try {
249
- await scan.close();
250
- scans.delete(scan);
251
- } catch {
252
- failure = new Error("Investigation resource closure failed");
253
- throw failure;
254
- }
255
- })();
256
- return scan.finishing;
257
- };
258
- const stop = async (scan) => {
259
- scan.stopping = true;
260
- await scan.active?.catch(() => {});
261
- await finish(scan);
262
- };
263
- const execute = (kind, args, signal) => {
264
- if (closing || failure)
265
- return Promise.reject(failure ?? new Error("Investigation tools closed"));
266
- if (signal?.aborted)
267
- return Promise.reject(new Error("Investigation canceled"));
268
- let scan,
269
- close = false;
270
- try {
271
- if (args?.cursor !== undefined) {
272
- object(args, ["cursor", "close"]);
273
- if (args.close !== undefined && args.close !== true)
274
- throw new Error("Invalid cursor operation");
275
- const token = string(args.cursor, 128);
276
- scan = cursors.get(token);
277
- if (scan && scan.query.kind === kind && now() >= scan.expiresAt) {
278
- cursors.delete(token);
279
- clearTimeout(scan.timer);
280
- void stop(scan).catch(() => {
281
- /* finish retains the closure failure. */
282
- });
283
- throw new Error(
284
- "Investigation cursor expired; start a fresh query explicitly",
285
- );
286
- }
287
- if (!scan || scan.query.kind !== kind)
288
- throw new Error(
289
- "Investigation cursor consumed or foreign; start a fresh query explicitly",
290
- );
291
- cursors.delete(token);
292
- clearTimeout(scan.timer);
293
- close = args.close === true;
294
- } else {
295
- const request = query(kind, args);
296
- if (scans.size >= L.scans)
297
- throw new Error(
298
- "Investigation cursor capacity reached; close an unused cursor",
299
- );
300
- scan = new ResearchScan(workspace, request);
301
- scans.add(scan); // Reserve before the first asynchronous filesystem operation.
302
- }
303
- } catch (error) {
304
- return Promise.reject(error);
305
- }
306
- const original = (async () => {
307
- const startedAt = now();
308
- scan.begin(signal);
309
- const items = [];
310
- const token = randomUUID();
311
- let done = false,
312
- pausedBy = null;
313
- try {
314
- if (close) {
315
- await finish(scan);
316
- return render(
317
- scan,
318
- [],
319
- "closed",
320
- null,
321
- null,
322
- Math.max(0, now() - startedAt),
323
- );
324
- }
325
- await scan.validate();
326
- for (;;) {
327
- scan.check();
328
- if (now() - startedAt >= L.toolMs) {
329
- pausedBy = "cooperative time quantum";
330
- break;
331
- }
332
- const next = scan.pending ?? (await scan.iterator.next());
333
- scan.pending = undefined;
334
- scan.check();
335
- if (next.done) {
336
- done = true;
337
- break;
338
- }
339
- if (!next.value) continue;
340
- if (next.value.pause) {
341
- pausedBy = next.value.pause;
342
- break;
343
- }
344
- const item = next.value.item;
345
- const candidate = render(
346
- scan,
347
- [...items, item],
348
- "more",
349
- token,
350
- "output quantum",
351
- 0,
352
- );
353
- // Reserve bounded metadata growth (counters/omissions/elapsed) while
354
- // charging the entire encoded envelope, not just unescaped line text.
355
- if (size(candidate) > L.outputBytes - 4096) {
356
- if (!items.length) {
357
- scan.omit("oversized result omitted");
358
- continue;
359
- }
360
- scan.pending = next;
361
- pausedBy = "output quantum";
362
- break;
363
- }
364
- if (items.length >= scan.query.pageSize) {
365
- scan.pending = next;
366
- pausedBy = "result quantum";
367
- break;
368
- }
369
- items.push(item);
370
- }
371
- await scan.validate();
372
- scan.check();
373
- if (done) await finish(scan);
374
- const result = render(
375
- scan,
376
- items,
377
- done ? "done" : "more",
378
- done ? null : token,
379
- pausedBy,
380
- Math.max(0, now() - startedAt),
381
- );
382
- if (size(result) > L.outputBytes)
383
- throw new Error("Investigation reply exceeds bound");
384
- if (!done) {
385
- scan.expiresAt = now() + L.idleMs;
386
- cursors.set(token, scan);
387
- scan.timer = setTimeout(() => {
388
- cursors.delete(token);
389
- void stop(scan).catch(() => {
390
- /* finish retains the failure and reservation. */
391
- });
392
- }, L.idleMs);
393
- scan.timer.unref();
394
- }
395
- return result;
396
- } catch (error) {
397
- await finish(scan);
398
- throw error;
399
- }
400
- })();
401
- scan.active = original;
402
- // Return the tracked original. No detached rejecting finally promise.
403
- return original.finally(() => {
404
- if (scan.active === original) scan.active = undefined;
405
- });
406
- };
30
+ createGrepToolDefinition(cwd),
31
+ createFindToolDefinition(cwd),
32
+ createLsToolDefinition(cwd),
33
+ ];
407
34
  return {
408
35
  tools: definitions.map((tool) => ({
409
36
  ...tool,
410
- label: tool.name,
411
- execute: (_id, args, signal) => execute(tool.name, args, signal),
412
- })),
413
- close() {
414
- if (closingOriginal) return closingOriginal;
415
- closing = true;
416
- for (const scan of cursors.values()) clearTimeout(scan.timer);
417
- cursors.clear();
418
- closingOriginal = (async () => {
419
- const outcomes = await Promise.allSettled([...scans].map(stop));
37
+ async execute(id, args, signal, update, context) {
38
+ if (signal?.aborted) throw new Error("Investigation canceled");
39
+ // The worker already enforces offline mode before creating its session.
40
+ // Keep direct uses equally noninstalling without changing ambient env.
420
41
  if (
421
- failure ||
422
- outcomes.some((outcome) => outcome.status === "rejected")
42
+ ["grep", "find"].includes(tool.name) &&
43
+ process.env.PI_OFFLINE !== "1"
423
44
  )
424
- throw failure ?? new Error("Investigation resource closure failed");
425
- })();
426
- return closingOriginal;
427
- },
45
+ throw new Error(
46
+ "Readonly search requires PI_OFFLINE=1; no tools were downloaded",
47
+ );
48
+ const selected = { ...context, cwd };
49
+ // Original-operation accounting and cancellation belong to the toolkit,
50
+ // just as they do for the standard file tools of an editing worker.
51
+ return tool.execute(id, args, signal, update, selected);
52
+ },
53
+ })),
428
54
  };
429
55
  }
@@ -429,7 +429,10 @@ try {
429
429
  getPrompts: () => ({ prompts: [], diagnostics: [] }),
430
430
  getThemes: () => ({ themes: [], diagnostics: [] }),
431
431
  getAgentsFiles: () => ({ agentsFiles: [] }),
432
- getSystemPrompt: () => instructions,
432
+ getSystemPrompt: () =>
433
+ toolkit?.instructions
434
+ ? `${instructions}\n\n${toolkit.instructions}`
435
+ : instructions,
433
436
  getSystemPromptSource: () => undefined,
434
437
  getAppendSystemPrompt: () => [],
435
438
  getAppendSystemPromptSources: () => [],
@@ -685,7 +688,7 @@ try {
685
688
  publicRequest.context,
686
689
  ...(!conversation && kind !== "code"
687
690
  ? [
688
- `Investigation roots: ${JSON.stringify(workspace.roots)}. Start at these specific paths, not / or their parents. Observation tools support file/range batches, literal multi-pattern searches and one-use continuation cursors; no shell is available. Read their schemas. Continue a cursor to advance actual I/O, including empty progress pages; do not repeat the initial query to paginate. Close unused cursors. Source-changed/expired cursors require an explicit fresh query, never an assumed continuation. Coverage names omissions and live-filesystem observation, not a snapshot. Search filenames and shallow directories before content; do not silently exclude backup trees. Total worker deadline: ${investigation?.timeoutMs ?? LIMITS.workerMs}ms, including model and tool time; activity never extends it. There is no cumulative tool-call quota or early tool cutoff. Use nextCursor when available; for terminal omissions, narrow the scope as needed. Never claim exhaustive absence from a progress page or incomplete coverage. Report retained evidence and unresolved questions honestly.`,
691
+ `Investigation roots: ${JSON.stringify(workspace.roots)}. Relative file-tool paths use the first root; select other roots explicitly. Start with these paths rather than broad parent trees. Total worker deadline: ${investigation?.timeoutMs ?? LIMITS.workerMs}ms, including model and tool time; activity never extends it. Report observed evidence, truncation and unresolved questions honestly.`,
689
692
  ]
690
693
  : []),
691
694
  ...publicRequest.handoff.inputs.map(
@@ -0,0 +1,190 @@
1
+ /** Short-lived, single-writer Pi activity metadata. Readers never repair or delete. */
2
+ import { randomUUID } from "node:crypto";
3
+ import { opendirSync, renameSync } from "node:fs";
4
+ import { hostname } from "node:os";
5
+ import { join } from "node:path";
6
+ import { canonicalAmbientRoot, defaultStateHome } from "../workspace.ts";
7
+ import {
8
+ closed,
9
+ decodeHash,
10
+ decodeId,
11
+ integer,
12
+ literal,
13
+ text,
14
+ } from "./contracts/core.ts";
15
+ import { decodeSessionId } from "./contracts/models.ts";
16
+ import { holderState, type ProcessMark } from "./liveness.ts";
17
+ import {
18
+ encoded,
19
+ type FileSnapshot,
20
+ hash,
21
+ json,
22
+ PrivateFiles,
23
+ } from "./private-files.ts";
24
+
25
+ export const ACTIVITY_RENEW_MS = 5000;
26
+ export const ACTIVITY_FRESH_MS = 15000;
27
+ /** Lost observations leave the activity area after two minutes, never as success. */
28
+ export const ACTIVITY_RETAIN_MS = 120000;
29
+ /** Per configuration/host scan and response bound; overflow is explicitly partial. */
30
+ export const ACTIVITY_FILES = 256;
31
+ export interface NativeActivity {
32
+ schema: "cadence-pi-activity/1";
33
+ instance: string;
34
+ activity: string;
35
+ scope: string;
36
+ sessionScope: string;
37
+ process: ProcessMark;
38
+ cwd: string;
39
+ sessionId: string;
40
+ leaf: string | null;
41
+ startedAt: number;
42
+ renewedAt: number;
43
+ }
44
+ export function decodeNativeActivity(value: unknown): NativeActivity {
45
+ const o = closed(value, [
46
+ "schema",
47
+ "instance",
48
+ "activity",
49
+ "scope",
50
+ "sessionScope",
51
+ "process",
52
+ "cwd",
53
+ "sessionId",
54
+ "leaf",
55
+ "startedAt",
56
+ "renewedAt",
57
+ ]);
58
+ const p = closed(o.process, ["pid", "host", "boot", "started"]);
59
+ return {
60
+ schema: literal(o.schema, "cadence-pi-activity/1"),
61
+ instance: decodeId(o.instance),
62
+ activity: decodeId(o.activity),
63
+ scope: decodeHash(o.scope),
64
+ sessionScope: decodeHash(o.sessionScope),
65
+ process: {
66
+ pid: integer(p.pid, 1, 2147483647),
67
+ host: text(p.host, 255, true),
68
+ boot: p.boot === null ? null : text(p.boot, 128, true),
69
+ started: p.started === null ? null : text(p.started, 128, true),
70
+ },
71
+ cwd: text(o.cwd, 4096, true),
72
+ sessionId: decodeSessionId(o.sessionId),
73
+ leaf: o.leaf === null ? null : text(o.leaf, 128, true),
74
+ startedAt: integer(o.startedAt, 0),
75
+ renewedAt: integer(o.renewedAt, 0),
76
+ };
77
+ }
78
+ export const activityScope = (agentDir: string) =>
79
+ hash(canonicalAmbientRoot(agentDir));
80
+ /** Bind the existing reader's configuration without exposing any source path. */
81
+ export const activityReaderScope = (agentDir: string, sessionDir?: string) =>
82
+ hash(
83
+ encoded([
84
+ canonicalAmbientRoot(agentDir),
85
+ process.env.PI_CODING_AGENT_SESSION_DIR ?? null,
86
+ sessionDir ?? null,
87
+ ]),
88
+ );
89
+ export class ActivityFiles {
90
+ readonly files: PrivateFiles;
91
+ readonly directory: string;
92
+ readonly scope: string;
93
+ constructor(agentDir: string, stateHome = defaultStateHome()) {
94
+ this.files = new PrivateFiles(
95
+ join(canonicalAmbientRoot(stateHome), "cadence-assistant-v1"),
96
+ );
97
+ this.scope = activityScope(agentDir);
98
+ this.directory = join(
99
+ this.files.namespace,
100
+ "pi-activity-v1",
101
+ this.scope,
102
+ hash(hostname()),
103
+ );
104
+ }
105
+ scan(): { records: NativeActivity[]; unavailable: number } {
106
+ const records: NativeActivity[] = [];
107
+ let unavailable = 0;
108
+ if (!this.files.directory(this.directory)) return { records, unavailable };
109
+ const dir = opendirSync(this.directory);
110
+ try {
111
+ let count = 0;
112
+ for (let e = dir.readSync(); e; e = dir.readSync()) {
113
+ if (++count > ACTIVITY_FILES) {
114
+ unavailable++;
115
+ break;
116
+ }
117
+ try {
118
+ if (!e.isFile() || !/^[0-9a-f-]{36}\.json$/.test(e.name))
119
+ throw new Error();
120
+ const file = this.files.read(join(this.directory, e.name));
121
+ if (!file) continue; // A publisher settled between directory and file reads.
122
+ const record = decodeNativeActivity(json(file));
123
+ if (
124
+ `${record.instance}.json` !== e.name ||
125
+ record.scope !== this.scope ||
126
+ record.process.host !== hostname()
127
+ )
128
+ throw new Error();
129
+ records.push(record);
130
+ } catch {
131
+ unavailable++;
132
+ }
133
+ }
134
+ } finally {
135
+ dir.closeSync();
136
+ }
137
+ return { records, unavailable };
138
+ }
139
+ /** Only a writer starting real work retires provably dead reports. Unknown
140
+ * and corrupt bytes stay untouched. Archived metadata expires with the existing
141
+ * 30-day recovery archive; a readonly discovery never cleans consumer data. */
142
+ retireDead(now: number): void {
143
+ const { records } = this.scan();
144
+ for (const record of records) {
145
+ if (
146
+ now - record.renewedAt <= ACTIVITY_RETAIN_MS ||
147
+ holderState(record.process).state !== "dead"
148
+ )
149
+ continue;
150
+ const path = join(this.directory, `${record.instance}.json`);
151
+ const before = this.files.read(path);
152
+ if (
153
+ !before ||
154
+ encoded(decodeNativeActivity(json(before))) !== encoded(record)
155
+ )
156
+ continue;
157
+ const archive = join(
158
+ this.files.namespace,
159
+ "recovery-archive-v1",
160
+ `${Date.now()}-${randomUUID()}`,
161
+ );
162
+ this.files.directory(archive, true);
163
+ this.files.assert(path, before);
164
+ renameSync(path, join(archive, "pi-activity.json"));
165
+ }
166
+ }
167
+ publish(record: NativeActivity, previous?: FileSnapshot): FileSnapshot {
168
+ if (!previous) {
169
+ const scanned = this.scan();
170
+ if (scanned.records.length + scanned.unavailable >= ACTIVITY_FILES)
171
+ throw new Error("activity-capacity");
172
+ }
173
+ const path = join(this.directory, `${record.instance}.json`);
174
+ const bytes = encoded(decodeNativeActivity(record));
175
+ if (previous) return this.files.replace(path, previous, bytes);
176
+ // Publish the first report atomically too. A failed temporary is preserved,
177
+ // not interpreted as an idle terminal or silently deleted by a reader.
178
+ this.files.directory(this.directory, true);
179
+ const temporary = join(this.directory, `pending-${record.instance}.json`);
180
+ this.files.create(temporary, bytes);
181
+ this.files.assert(path, undefined);
182
+ renameSync(temporary, path);
183
+ const saved = this.files.read(path);
184
+ if (!saved) throw new Error("activity-unavailable");
185
+ return saved;
186
+ }
187
+ withdraw(instance: string, previous: FileSnapshot): void {
188
+ this.files.remove(join(this.directory, `${instance}.json`), previous);
189
+ }
190
+ }