@agimon-ai/po-file-edit 0.0.0-alpha.21 → 0.0.0-alpha.211

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.
@@ -24,281 +24,409 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
24
24
  enumerable: true
25
25
  }) : target, mod));
26
26
  //#endregion
27
+ const require_package = require("../package-ZnJMUINx.cjs");
27
28
  let _agimon_ai_po_core_serverPlugin = require("@agimon-ai/po-core/serverPlugin");
28
29
  let _agimon_ai_po_core_extensionFile = require("@agimon-ai/po-core/extensionFile");
30
+ let _agimon_ai_po_core_platform = require("@agimon-ai/po-core/platform");
29
31
  let _agimon_ai_po_core_childSession = require("@agimon-ai/po-core/childSession");
30
32
  let _agimon_ai_po_core_hubChannel = require("@agimon-ai/po-core/hubChannel");
31
- let node_fs_promises = require("node:fs/promises");
32
- node_fs_promises = __toESM(node_fs_promises, 1);
33
+ let _agimon_ai_po_core_packageApi = require("@agimon-ai/po-core/packageApi");
33
34
  let node_path = require("node:path");
34
35
  node_path = __toESM(node_path, 1);
35
36
  let _agimon_ai_po_hashline = require("@agimon-ai/po-hashline");
36
37
  let _agimon_ai_po_hashline_files = require("@agimon-ai/po-hashline/files");
37
- let node_fs = require("node:fs");
38
- node_fs = __toESM(node_fs, 1);
39
- let _agimon_ai_po_core_childProcess = require("@agimon-ai/po-core/childProcess");
40
- let _agimon_ai_po_telemetry = require("@agimon-ai/po-telemetry");
38
+ let node_fs_promises = require("node:fs/promises");
39
+ node_fs_promises = __toESM(node_fs_promises, 1);
40
+ let node_os = require("node:os");
41
+ node_os = __toESM(node_os, 1);
42
+ let _agimon_ai_po_config = require("@agimon-ai/po-config");
43
+ let _agimon_ai_po_core_nodePlatform = require("@agimon-ai/po-core/nodePlatform");
41
44
  let node_crypto = require("node:crypto");
45
+ let _agimon_ai_po_core_childProcess = require("@agimon-ai/po-core/childProcess");
42
46
  let _agimon_ai_po_core_piSettings = require("@agimon-ai/po-core/piSettings");
43
47
  let node_child_process = require("node:child_process");
44
48
  let node_util = require("node:util");
45
49
  let ignore = require("ignore");
46
50
  ignore = __toESM(ignore, 1);
47
- let node_os = require("node:os");
48
- node_os = __toESM(node_os, 1);
49
- let _agimon_ai_po_config = require("@agimon-ai/po-config");
51
+ let _agimon_ai_po_core_telemetry = require("@agimon-ai/po-core/telemetry");
50
52
  let hono = require("hono");
51
53
  //#region src/constants/editPresence.ts
52
54
  const PRESENCE_NOTE_TITLE = "[Po: other active agents edited files in this result]";
53
55
  const PRESENCE_NOTE_GUIDANCE = "Preserve unrelated edits. If coordination would help, you can use intercom to send to the session id, or ask the subagent by name if it is on your team. Contact is optional; this notice does not block editing.";
54
56
  //#endregion
55
- //#region src/services/editPresence/index.ts
56
- const PATH_TOOLS = /* @__PURE__ */ new Set([
57
- "read",
58
- "edit",
59
- "write"
60
- ]);
61
- const EDIT_TOOLS = /* @__PURE__ */ new Set(["edit", "write"]);
62
- const MAX_GREP_FILES = 50;
63
- const MAX_NOTE_LINES = 10;
64
- const MINUTE_MS = 6e4;
65
- const SHORT_ID_LENGTH = 8;
66
- /** Pi's built-in grep prints match rows as `relative/path:line: text`. */
67
- const PI_GREP_ROW = /^(.+?):(\d+): /u;
68
- function forgetPresence(ledger, agentKey) {
69
- for (const [file, entries] of ledger) {
70
- entries.delete(agentKey);
71
- if (entries.size === 0) ledger.delete(file);
72
- }
73
- }
74
- function stringArg(args, key) {
75
- if (typeof args !== "object" || args === null) return void 0;
76
- const value = args[key];
77
- return typeof value === "string" && value.length > 0 ? value : void 0;
78
- }
79
- function textOf(content) {
80
- return content.map((part) => part.type === "text" && "text" in part && typeof part.text === "string" ? part.text : "").join("\n");
81
- }
82
- async function grepFiles(call) {
83
- const lines = textOf(call.content).split("\n");
84
- const headers = lines.flatMap((line) => {
85
- const header = (0, _agimon_ai_po_hashline.parseFileHeader)(line);
86
- return header === void 0 ? [] : [(0, _agimon_ai_po_hashline_files.resolveInputPath)(header.path, call.cwd)];
87
- });
88
- if (headers.length > 0) return [...new Set(headers)].slice(0, MAX_GREP_FILES);
89
- const rows = lines.flatMap((line) => {
90
- const match = PI_GREP_ROW.exec(line)?.[1];
91
- return match === void 0 ? [] : [match];
92
- });
93
- if (rows.length === 0) return [];
94
- const searchPath = (0, _agimon_ai_po_hashline_files.resolveInputPath)(stringArg(call.args, "path") ?? ".", call.cwd);
95
- if ((await node_fs_promises.default.stat(searchPath).catch(() => void 0))?.isFile()) return [searchPath];
96
- return [...new Set(rows.map((row) => node_path.default.resolve(searchPath, row)))].slice(0, MAX_GREP_FILES);
57
+ //#region src/services/editPathNames/index.ts
58
+ /** The directory this package owns, under whichever root holds agent state. */
59
+ const STATE_DIRECTORY = "po-file-edit";
60
+ /** A stable short name for a path or session key, so state files are found from those two alone. */
61
+ function pathHash(value) {
62
+ return (0, node_crypto.createHash)("sha256").update(value).digest("hex").slice(0, 16);
97
63
  }
98
- async function touchedFiles(call) {
99
- if (PATH_TOOLS.has(call.toolName)) {
100
- const input = stringArg(call.args, "path");
101
- return input === void 0 ? [] : [await (0, _agimon_ai_po_hashline_files.resolveReadInputPath)(input, call.cwd)];
64
+ /** A subagent child writes to its parent's timeline, so the two stay one session to every reader. */
65
+ function sessionKeyFor(sessionId, environment) {
66
+ if (environment[_agimon_ai_po_core_childProcess.SUBAGENT_CHILD_ENV]) {
67
+ const parent = environment[_agimon_ai_po_core_childProcess.SUBAGENT_PARENT_SESSION_ENV];
68
+ if (parent) return parent;
102
69
  }
103
- return call.toolName === "grep" ? grepFiles(call) : [];
104
- }
105
- function ago(elapsed) {
106
- const minutes = Math.floor(elapsed / MINUTE_MS);
107
- return minutes < 1 ? "under 1m ago" : `${minutes}m ago`;
70
+ return sessionId;
108
71
  }
109
- function liveOthers(ledger, file, self) {
110
- const entries = ledger.get(file);
111
- if (entries === void 0) return [];
112
- const live = [];
113
- for (const [key, entry] of entries) {
114
- if (key === self) continue;
115
- if (entry.agent.isLive()) live.push(entry);
116
- else entries.delete(key);
117
- }
118
- return live.sort((left, right) => right.at - left.at);
119
- }
120
- function record(ledger, file, agent, tag, at) {
121
- const entries = ledger.get(file) ?? /* @__PURE__ */ new Map();
122
- entries.set(agent.key, {
123
- agent,
124
- tag,
125
- at
126
- });
127
- ledger.set(file, entries);
72
+ /** Where every session's state lives: beside the other Po packages' agent state, never in the working tree. */
73
+ function stateDirectoryFor(environment) {
74
+ return node_path.default.join((0, _agimon_ai_po_core_piSettings.piAgentDirectory)(environment, environment.HOME), STATE_DIRECTORY);
128
75
  }
129
- function renderNote(lines) {
130
- const shown = lines.slice(0, MAX_NOTE_LINES);
131
- const more = lines.length - shown.length;
132
- return [
133
- PRESENCE_NOTE_TITLE,
134
- ...shown,
135
- ...more > 0 ? [`- and ${more} more`] : [],
136
- PRESENCE_NOTE_GUIDANCE
137
- ].join("\n");
76
+ /** Snapshots sit beside their timeline and take its name, so the two are found and cleared together. */
77
+ function snapshotsPathOf(timelinePath) {
78
+ return `${timelinePath.replace(/\.jsonl$/u, "")}.blobs`;
138
79
  }
139
- /**
140
- * Notes live editors of the files a tool call touched, then records the caller's own successful edit.
141
- * Returns the content with one note appended, or undefined when there is nothing to add, so callers
142
- * never rewrite a result needlessly.
143
- */
144
- async function observePresence(ledger, agent, call, now = Date.now()) {
145
- const recording = EDIT_TOOLS.has(call.toolName) && !call.isError;
146
- if (!recording && ledger.size === 0) return void 0;
147
- const lines = [];
148
- for (const file of await touchedFiles(call)) {
149
- const real = await node_fs_promises.default.realpath(file).catch(() => void 0);
150
- if (real === void 0) continue;
151
- const others = liveOthers(ledger, real, agent.key);
152
- let bytes;
153
- if (others.length > 0) {
154
- bytes = await node_fs_promises.default.readFile(real).catch(() => void 0);
155
- const current = bytes === void 0 ? void 0 : (0, _agimon_ai_po_hashline_files.computeFileTag)(bytes);
156
- const shown = (0, _agimon_ai_po_hashline_files.displayPath)(file, call.cwd);
157
- for (const entry of others) {
158
- const state = entry.tag === current ? "unchanged" : "changed";
159
- lines.push(`- ${shown}: ${entry.agent.label()}, ${ago(now - entry.at)}, file ${state} since their edit.`);
160
- }
161
- }
162
- if (recording) {
163
- bytes ??= await node_fs_promises.default.readFile(real).catch(() => void 0);
164
- if (bytes !== void 0) record(ledger, real, agent, (0, _agimon_ai_po_hashline_files.computeFileTag)(bytes), now);
165
- }
80
+ //#endregion
81
+ //#region src/services/fileEditPaths/index.ts
82
+ var FileEditPaths = class {
83
+ environment;
84
+ constructor(environment = process.env) {
85
+ this.environment = environment;
166
86
  }
167
- if (lines.length === 0) return void 0;
168
- return [...call.content, {
169
- type: "text",
170
- text: renderNote(lines)
171
- }];
172
- }
173
- /** Edit presence for one hub session and the in-process children it spawns. */
174
- function createSessionPresence(options) {
175
- const { sessionId, ledger } = options;
176
- const sessionAgent = {
177
- key: `session:${sessionId}`,
178
- label: () => `session ${sessionId}${options.workflowStep ? " (workflow step)" : ""}`,
179
- contact: sessionId,
180
- isLive: options.isLive
181
- };
182
- const safely = async (work) => {
183
- try {
184
- return await work();
185
- } catch (error) {
186
- options.onError?.(error);
187
- return;
188
- }
189
- };
190
- return {
191
- toolResult: {
192
- event: "tool_result",
193
- async handle(event, execution) {
194
- const toolName = event.toolName;
195
- if (execution.sessionId !== sessionId || typeof toolName !== "string" || !Array.isArray(event.content)) return;
196
- const content = event.content;
197
- const next = await safely(() => observePresence(ledger, sessionAgent, {
198
- toolName,
199
- args: event.args,
200
- content,
201
- isError: event.isError === true,
202
- cwd: execution.cwd
203
- }));
204
- return next === void 0 ? void 0 : { content: next };
205
- }
206
- },
207
- childHooks: { bind(scope) {
208
- const { runId, parentSessionId, agent } = scope.request;
209
- const child = {
210
- key: `run:${runId}`,
211
- label: () => `${options.labelFor(runId) ?? `${agent} (run ${runId.slice(0, SHORT_ID_LENGTH)})`} (subagent of session ${parentSessionId})`,
212
- contact: parentSessionId,
213
- isLive: () => !scope.signal.aborted
214
- };
215
- return {
216
- beforeTool: () => void 0,
217
- async afterTool(event) {
218
- const next = await safely(() => observePresence(ledger, child, {
219
- toolName: event.toolName,
220
- args: event.args,
221
- content: event.content,
222
- isError: event.isError,
223
- cwd: scope.request.cwd || options.cwd
224
- }));
225
- return next === void 0 ? void 0 : { content: next };
226
- },
227
- dispose: async () => forgetPresence(ledger, child.key)
228
- };
229
- } },
230
- dispose: () => forgetPresence(ledger, sessionAgent.key)
231
- };
232
- }
87
+ sessionKey(sessionId, env = this.environment) {
88
+ return sessionKeyFor(sessionId, env);
89
+ }
90
+ /**
91
+ * Where every session's state lives: the Pi agent directory, the same root
92
+ * every other Po package writes to, and never inside the working tree.
93
+ *
94
+ * An earlier layout put this in the repository's git common directory. That
95
+ * is git's own storage: nothing in git's lifecycle prunes a directory we add
96
+ * to it, a linked worktree writes into the main checkout rather than its own,
97
+ * a submodule writes inside `.git/modules`, and `PI_CODING_AGENT_DIR` was
98
+ * ignored outright. The snapshots are verbatim copies of files the session
99
+ * touched, so where they land is a question about handling content, not a
100
+ * question about convenience.
101
+ */
102
+ stateDirectory() {
103
+ return stateDirectoryFor(this.environment);
104
+ }
105
+ /**
106
+ * One session's timeline, named from its working directory and its session so
107
+ * the hub and the session API can find it from another process knowing only
108
+ * those two things.
109
+ */
110
+ async timelinePath(cwd, sessionKey) {
111
+ const directory = this.stateDirectory();
112
+ await node_fs_promises.default.mkdir(directory, { recursive: true });
113
+ return node_path.default.join(directory, `${pathHash(await node_fs_promises.default.realpath(cwd))}-${pathHash(sessionKey)}.jsonl`);
114
+ }
115
+ /**
116
+ * Where this session's content snapshots live: beside its timeline and named
117
+ * after it, so the two are found together and cleared together.
118
+ */
119
+ async snapshotsPath(cwd, sessionKey) {
120
+ return snapshotsPathOf(await this.timelinePath(cwd, sessionKey));
121
+ }
122
+ };
233
123
  //#endregion
234
- //#region src/services/lineDiff/index.ts
124
+ //#region src/services/gitStatus/index.ts
235
125
  /**
236
- * The line difference between two versions of a file, as bounded hunks.
126
+ * Answers the unchanged question with git, in two batched calls per chunk.
237
127
  *
238
- * This is deliberately the package's own rather than Pi's `generateDiffString`:
239
- * that helper reaches the session process through an optional peer dependency,
240
- * and these routes run in a host that imports only the built entry, so its
241
- * presence is an assumption rather than a fact. A line diff is small enough to
242
- * own outright, and owning it means the wire carries structured rows instead of
243
- * a formatted string the browser has to parse back apart.
128
+ * One technology per adapter. This is where git enters the scan path; the
129
+ * tracker that depends on the capability keeps importing the port.
244
130
  *
245
- * Bounded twice over. Common prefix and suffix are trimmed first, which is what
246
- * makes a one-line change in a large file cheap. What remains is matched with a
247
- * longest-common-subsequence table, and only while that table stays under
248
- * MAX_MATRIX_CELLS: past it the changed region is reported as one replacement
249
- * rather than growing a matrix that would outweigh the file.
131
+ * `ls-files` names which of the given paths git tracks at all, and `status`
132
+ * names which of those moved. Everything else, an ignored build artefact, a
133
+ * temporary file, a tree with no repository, falls out of both answers and is
134
+ * therefore never reported as unchanged: the caller must keep recording it,
135
+ * because git has nothing to say about a file it never saw.
250
136
  */
251
- /** Lines of unchanged context kept either side of a change. */
252
- const CONTEXT_LINES = 3;
253
- /** The largest LCS table worth building; past it the changed region is one replacement. */
254
- const MAX_MATRIX_CELLS = 1e6;
255
- function splitLines(text) {
256
- const normalized = text.replaceAll("\r\n", "\n").replaceAll("\r", "\n");
257
- return normalized === "" ? [] : normalized.split("\n");
258
- }
259
- /** How many leading lines the two sides share. */
260
- function commonPrefix(before, after) {
261
- const limit = Math.min(before.length, after.length);
262
- let count = 0;
263
- while (count < limit && before[count] === after[count]) count += 1;
264
- return count;
137
+ /** Paths per git invocation, so a large scan cannot overflow the argument list. */
138
+ const CHUNK = 200;
139
+ const MAX_BUFFER = 4194304;
140
+ const run = (0, node_util.promisify)(node_child_process.execFile);
141
+ function chunked(values, size) {
142
+ const groups = [];
143
+ for (let index = 0; index < values.length; index += size) groups.push(values.slice(index, index + size));
144
+ return groups;
265
145
  }
266
- /** How many trailing lines the two sides share, never overlapping the prefix. */
267
- function commonSuffix(before, after, prefix) {
268
- const limit = Math.min(before.length, after.length) - prefix;
269
- let count = 0;
270
- while (count < limit && before[before.length - 1 - count] === after[after.length - 1 - count]) count += 1;
271
- return count;
146
+ function splitRecords(output) {
147
+ return output.split("\0").filter((entry) => entry !== "");
272
148
  }
273
149
  /**
274
- * The classic LCS length table. Only ever called once the caller has checked
275
- * the region against MAX_MATRIX_CELLS, so the allocation is bounded.
150
+ * The paths named by `status --porcelain -z`, whose records carry a two-letter
151
+ * code and a space. A rename adds a bare second record; keeping it is harmless,
152
+ * because every path in this set is one the caller records anyway.
276
153
  */
277
- function lcsTable(before, after) {
278
- const rows = before.length + 1;
279
- const columns = after.length + 1;
280
- const table = new Uint32Array(rows * columns);
281
- for (let row = before.length - 1; row >= 0; row -= 1) for (let column = after.length - 1; column >= 0; column -= 1) {
282
- const index = row * columns + column;
283
- table[index] = before[row] === after[column] ? (table[index + columns + 1] ?? 0) + 1 : Math.max(table[index + columns] ?? 0, table[index + 1] ?? 0);
284
- }
285
- return table;
154
+ function statusPaths(output) {
155
+ return splitRecords(output).map((record) => record.length > 3 && record[2] === " " ? record.slice(3) : record);
286
156
  }
287
- /** Walks the table to turn it back into an ordered run of keeps, removals and additions. */
288
- function backtrack(before, after, beforeStart, afterStart) {
289
- const table = lcsTable(before, after);
290
- const columns = after.length + 1;
291
- const steps = [];
292
- let row = 0;
293
- let column = 0;
294
- while (row < before.length && column < after.length) {
295
- if (before[row] === after[column]) {
296
- steps.push({
297
- marker: " ",
298
- content: after[column] ?? "",
299
- line: afterStart + column
300
- });
301
- row += 1;
157
+ function isInside$1(root, filePath) {
158
+ const relative = node_path.default.relative(root, filePath);
159
+ return relative !== "" && !relative.startsWith("..") && !node_path.default.isAbsolute(relative);
160
+ }
161
+ var NodeGitStatusAdapter = class {
162
+ /** Repository roots already found, so a call per bash command costs one git process, not two. */
163
+ roots = /* @__PURE__ */ new Map();
164
+ async dirty(cwd) {
165
+ const root = await this.topLevel(cwd);
166
+ if (root === void 0) return void 0;
167
+ const output = await this.git(cwd, [
168
+ "status",
169
+ "--porcelain",
170
+ "-z",
171
+ "--untracked-files=all",
172
+ "--",
173
+ "."
174
+ ]);
175
+ return output === void 0 ? void 0 : statusPaths(output).map((entry) => node_path.default.resolve(root, entry));
176
+ }
177
+ async unchanged(cwd, filePaths) {
178
+ const clean = /* @__PURE__ */ new Set();
179
+ if (filePaths.length === 0) return clean;
180
+ const root = await this.topLevel(cwd);
181
+ if (root === void 0) return clean;
182
+ for (const group of chunked(filePaths.filter((filePath) => isInside$1(root, filePath)), CHUNK)) {
183
+ const relative = group.map((filePath) => node_path.default.relative(root, filePath));
184
+ const tracked = await this.git(root, [
185
+ "ls-files",
186
+ "-z",
187
+ "--",
188
+ ...relative
189
+ ]);
190
+ if (tracked === void 0) continue;
191
+ const dirty = await this.git(root, [
192
+ "status",
193
+ "--porcelain",
194
+ "-z",
195
+ "--untracked-files=no",
196
+ "--",
197
+ ...relative
198
+ ]);
199
+ if (dirty === void 0) continue;
200
+ const moved = new Set(statusPaths(dirty));
201
+ for (const entry of splitRecords(tracked)) if (!moved.has(entry)) clean.add(node_path.default.resolve(root, entry));
202
+ }
203
+ return clean;
204
+ }
205
+ /** The repository root, or undefined when this tree is not one. */
206
+ async topLevel(cwd) {
207
+ const known = this.roots.get(cwd);
208
+ if (known !== void 0) return known;
209
+ const root = (await this.git(cwd, ["rev-parse", "--show-toplevel"]))?.trim();
210
+ if (root === void 0 || root === "") return void 0;
211
+ this.roots.set(cwd, node_path.default.resolve(root));
212
+ return node_path.default.resolve(root);
213
+ }
214
+ /** Git's stdout, or undefined when the call failed for any reason at all. */
215
+ async git(cwd, args) {
216
+ try {
217
+ const { stdout } = await run("git", [...args], {
218
+ cwd,
219
+ encoding: "utf8",
220
+ maxBuffer: MAX_BUFFER
221
+ });
222
+ return stdout;
223
+ } catch {
224
+ return;
225
+ }
226
+ }
227
+ };
228
+ //#endregion
229
+ //#region src/services/fileChanges/index.ts
230
+ const TOOLS = /* @__PURE__ */ new Set([
231
+ "edit",
232
+ "write",
233
+ "bash",
234
+ "user"
235
+ ]);
236
+ function isRecord(value) {
237
+ return typeof value === "object" && value !== null && !Array.isArray(value);
238
+ }
239
+ function optionalString(value) {
240
+ return typeof value === "string" && value !== "" ? value : void 0;
241
+ }
242
+ function optionalCount(value) {
243
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
244
+ }
245
+ /** Narrows one parsed line, or answers null so a malformed line can be skipped. */
246
+ function parseTimelineEvent(value) {
247
+ if (!isRecord(value)) return null;
248
+ const { version, path: filePath, tool, at } = value;
249
+ if (typeof filePath !== "string" || filePath === "") return null;
250
+ if (typeof at !== "number" || !Number.isFinite(at)) return null;
251
+ if (typeof tool !== "string" || !TOOLS.has(tool)) return null;
252
+ if (version === 1) {
253
+ if (tool === "user") return null;
254
+ return {
255
+ version: 1,
256
+ path: filePath,
257
+ tool,
258
+ at
259
+ };
260
+ }
261
+ if (version !== 2) return null;
262
+ return {
263
+ version: 2,
264
+ path: filePath,
265
+ tool,
266
+ at,
267
+ origin: value.origin === "scan" ? "scan" : "tool",
268
+ ...optionalString(value.before) === void 0 ? {} : { before: value.before },
269
+ ...optionalString(value.after) === void 0 ? {} : { after: value.after },
270
+ ...optionalCount(value.additions) === void 0 ? {} : { additions: value.additions },
271
+ ...optionalCount(value.removals) === void 0 ? {} : { removals: value.removals },
272
+ ...value.verified === true ? { verified: true } : {},
273
+ ...value.created === true ? { created: true } : {}
274
+ };
275
+ }
276
+ /** Every recorded line of the timeline, malformed ones dropped, in file order. */
277
+ function parseTimeline(content, onMalformed) {
278
+ const events = [];
279
+ for (const line of content.split("\n")) {
280
+ if (line === "") continue;
281
+ let parsed;
282
+ try {
283
+ parsed = JSON.parse(line);
284
+ } catch {
285
+ onMalformed?.(line);
286
+ continue;
287
+ }
288
+ const event = parseTimelineEvent(parsed);
289
+ if (event === null) onMalformed?.(line);
290
+ else events.push(event);
291
+ }
292
+ return events;
293
+ }
294
+ /**
295
+ * Whether a recorded change is evidence that the file's content actually moved.
296
+ *
297
+ * A tool change names its file and reads both sides, so it always is. A scan
298
+ * change is a tree comparison of size and modification time, which a checkout,
299
+ * an install, or a command that merely touched a file moves as readily as an
300
+ * edit does; only a scan the tracker confirmed carries `verified`. Version 1
301
+ * lines predate the distinction entirely, so a bash one cannot be trusted.
302
+ */
303
+ function isConfirmedChange(event) {
304
+ if (event.version !== 2) return event.tool !== "bash";
305
+ return event.origin !== "scan" || event.verified === true;
306
+ }
307
+ /** The recorded changes worth listing, which is every change but an unconfirmed touch. */
308
+ function confirmedChanges(events) {
309
+ return events.filter(isConfirmedChange);
310
+ }
311
+ /** One row per file, newest change first, which is the order both docks list in. */
312
+ function foldEntries(events) {
313
+ const folded = /* @__PURE__ */ new Map();
314
+ for (const event of events) {
315
+ const current = folded.get(event.path);
316
+ folded.set(event.path, {
317
+ path: event.path,
318
+ tool: event.at >= (current?.at ?? 0) ? event.tool : current?.tool ?? event.tool,
319
+ at: Math.max(event.at, current?.at ?? 0),
320
+ count: (current?.count ?? 0) + 1
321
+ });
322
+ }
323
+ return [...folded.values()].sort((left, right) => right.at - left.at);
324
+ }
325
+ /** One file's history, oldest first, numbered so a reader can name a version. */
326
+ function foldVersions(events, filePath) {
327
+ return events.filter((event) => event.path === filePath).sort((left, right) => left.at - right.at).map((event, offset) => {
328
+ const version = {
329
+ index: offset + 1,
330
+ tool: event.tool,
331
+ at: event.at,
332
+ origin: event.version === 2 ? event.origin : "scan"
333
+ };
334
+ if (event.version !== 2) return version;
335
+ return {
336
+ ...version,
337
+ ...event.before === void 0 ? {} : { before: event.before },
338
+ ...event.after === void 0 ? {} : { after: event.after },
339
+ ...event.additions === void 0 ? {} : { additions: event.additions },
340
+ ...event.removals === void 0 ? {} : { removals: event.removals },
341
+ ...event.verified === true ? { verified: true } : {},
342
+ ...event.created === true ? { created: true } : {}
343
+ };
344
+ });
345
+ }
346
+ /**
347
+ * Whether a file can be diffed at all: some version has to give the diff a
348
+ * starting point. A captured baseline is one. So is a version that created the
349
+ * file, whose starting point is nothing at all.
350
+ *
351
+ * A file only ever seen after the fact, which is every file a bash script
352
+ * wrote, still cannot be.
353
+ */
354
+ function isDiffable(versions) {
355
+ return versions.some((version) => version.before !== void 0 || version.created === true);
356
+ }
357
+ /** The oldest captured baseline for a file, which is what the whole-session diff starts from. */
358
+ function baselineOf(versions) {
359
+ return versions.find((version) => version.before !== void 0)?.before;
360
+ }
361
+ //#endregion
362
+ //#region src/services/lineDiff/index.ts
363
+ /**
364
+ * The line difference between two versions of a file, as bounded hunks.
365
+ *
366
+ * This is deliberately the package's own rather than Pi's `generateDiffString`:
367
+ * that helper reaches the session process through an optional peer dependency,
368
+ * and these routes run in a host that imports only the built entry, so its
369
+ * presence is an assumption rather than a fact. A line diff is small enough to
370
+ * own outright, and owning it means the wire carries structured rows instead of
371
+ * a formatted string the browser has to parse back apart.
372
+ *
373
+ * Bounded twice over. Common prefix and suffix are trimmed first, which is what
374
+ * makes a one-line change in a large file cheap. What remains is matched with a
375
+ * longest-common-subsequence table, and only while that table stays under
376
+ * MAX_MATRIX_CELLS: past it the changed region is reported as one replacement
377
+ * rather than growing a matrix that would outweigh the file.
378
+ */
379
+ /** Lines of unchanged context kept either side of a change. */
380
+ const CONTEXT_LINES = 3;
381
+ /** The largest LCS table worth building; past it the changed region is one replacement. */
382
+ const MAX_MATRIX_CELLS = 1e6;
383
+ function splitLines(text) {
384
+ const normalized = text.replaceAll("\r\n", "\n").replaceAll("\r", "\n");
385
+ return normalized === "" ? [] : normalized.split("\n");
386
+ }
387
+ /** How many leading lines the two sides share. */
388
+ function commonPrefix(before, after) {
389
+ const limit = Math.min(before.length, after.length);
390
+ let count = 0;
391
+ while (count < limit && before[count] === after[count]) count += 1;
392
+ return count;
393
+ }
394
+ /** How many trailing lines the two sides share, never overlapping the prefix. */
395
+ function commonSuffix(before, after, prefix) {
396
+ const limit = Math.min(before.length, after.length) - prefix;
397
+ let count = 0;
398
+ while (count < limit && before[before.length - 1 - count] === after[after.length - 1 - count]) count += 1;
399
+ return count;
400
+ }
401
+ /**
402
+ * The classic LCS length table. Only ever called once the caller has checked
403
+ * the region against MAX_MATRIX_CELLS, so the allocation is bounded.
404
+ */
405
+ function lcsTable(before, after) {
406
+ const rows = before.length + 1;
407
+ const columns = after.length + 1;
408
+ const table = new Uint32Array(rows * columns);
409
+ for (let row = before.length - 1; row >= 0; row -= 1) for (let column = after.length - 1; column >= 0; column -= 1) {
410
+ const index = row * columns + column;
411
+ table[index] = before[row] === after[column] ? (table[index + columns + 1] ?? 0) + 1 : Math.max(table[index + columns] ?? 0, table[index + 1] ?? 0);
412
+ }
413
+ return table;
414
+ }
415
+ /** Walks the table to turn it back into an ordered run of keeps, removals and additions. */
416
+ function backtrack(before, after, beforeStart, afterStart) {
417
+ const table = lcsTable(before, after);
418
+ const columns = after.length + 1;
419
+ const steps = [];
420
+ let row = 0;
421
+ let column = 0;
422
+ while (row < before.length && column < after.length) {
423
+ if (before[row] === after[column]) {
424
+ steps.push({
425
+ marker: " ",
426
+ content: after[column] ?? "",
427
+ line: afterStart + column
428
+ });
429
+ row += 1;
302
430
  column += 1;
303
431
  continue;
304
432
  }
@@ -433,387 +561,679 @@ function lineDiff(before, after) {
433
561
  };
434
562
  }
435
563
  //#endregion
436
- //#region src/services/editTracker/index.ts
437
- const EDIT_TOOL = "edit";
438
- const WRITE_TOOL = "write";
439
- const BASH_TOOL = "bash";
440
- function objectValue(value, key) {
441
- if (!value || typeof value !== "object") return void 0;
442
- const found = value[key];
443
- return typeof found === "string" ? found : void 0;
564
+ //#region src/services/fileEditsViews/index.ts
565
+ /** Past this, the working view reports the file rather than carrying it. */
566
+ const MAX_WORKING_BYTES = 1048576;
567
+ const NO_BASELINE_NOTE = "changed by a command, so no baseline was captured; showing the file as it stands";
568
+ /**
569
+ * A change the tool layer named but never captured content for. That is what
570
+ * every record written before this package learned to snapshot looks like, and
571
+ * calling those "changed by a command" would be wrong: the tool is right there
572
+ * in the record.
573
+ */
574
+ const NO_SNAPSHOT_NOTE = "recorded before this session began capturing content, so there is no diff for it";
575
+ const NO_AFTER_NOTE = "the new content could not be captured: the file is binary or past the size cap";
576
+ const NO_BEFORE_NOTE = "the previous content could not be captured: it was binary or past the size cap";
577
+ const APPROXIMATE_NOTE = "the changed region was too large to match line by line";
578
+ /** Like Node's utf8 read, a byte-order mark stays in the text. */
579
+ const decoder = new TextDecoder("utf-8", {
580
+ fatal: false,
581
+ ignoreBOM: true
582
+ });
583
+ function hashOf(content) {
584
+ return (0, node_crypto.createHash)("sha256").update(content, "utf8").digest("hex");
585
+ }
586
+ function isInside(root, candidate) {
587
+ return candidate === root || candidate.startsWith(`${root}${node_path.default.sep}`);
588
+ }
589
+ /** A file the source view cannot show, with the reason it says instead. */
590
+ function unavailable(reason) {
591
+ return {
592
+ content: "",
593
+ hash: "",
594
+ unavailable: true,
595
+ reason
596
+ };
597
+ }
598
+ /** The source view of a file's bytes: refused when oversized or binary, otherwise its text and hash. */
599
+ function workingViewOf(raw) {
600
+ if (raw.byteLength > 1048576) return unavailable(`the file is larger than ${MAX_WORKING_BYTES} bytes`);
601
+ if (raw.subarray(0, 8192).includes(0)) return unavailable("the file is binary");
602
+ const content = decoder.decode(raw);
603
+ return {
604
+ content,
605
+ hash: hashOf(content),
606
+ unavailable: false
607
+ };
444
608
  }
445
609
  /**
446
- * How far before a call started a write may claim to have happened and still be
447
- * attributed to it. A working tree can sit on a filesystem that stores whole
448
- * seconds, which floors a write made just after the call began to a stamp just
449
- * before it, and the cost of being generous here is one second of the staleness
450
- * this check exists to remove.
610
+ * One recorded change as the page renders it. A change with both sides captured
611
+ * carries its own diff; one without says why, rather than showing nothing.
612
+ *
613
+ * A file this session created counts as captured on both sides. Its baseline is
614
+ * empty rather than missing, so the whole file reads as arriving at once, which
615
+ * is exactly what happened.
451
616
  */
452
- const MODIFIED_TOLERANCE_MS = 1e3;
453
- var EditTracker = class {
454
- timeline;
455
- snapshots;
456
- manifests;
457
- pending = /* @__PURE__ */ new Map();
458
- /** Start time per in-flight bash call, so its end knows what it may claim. */
459
- bracketed = /* @__PURE__ */ new Map();
460
- /**
461
- * The tree as this tracker last saw it. A bash call compares against it and
462
- * then replaces it, so each call costs one walk rather than two, and a change
463
- * made between calls is still noticed on the next one.
464
- */
465
- manifest;
466
- /**
467
- * This package's own storage, which the walk must never report. The timeline
468
- * and its snapshots can land inside the tree being watched, and recording
469
- * them would make every change cause another one.
470
- */
471
- excluded = [];
472
- /**
473
- * The project's own ignore rules. A path the project disowns is not worth a
474
- * git call, a read, or a stored copy of its content, so it is dropped before
475
- * it costs any of them.
476
- */
477
- isIgnored;
478
- /**
479
- * The last content hash this session saw per path, from either mechanism.
480
- * A candidate whose hash has not moved was touched, not edited.
481
- */
482
- contents = /* @__PURE__ */ new Map();
483
- now;
484
- git;
485
- /**
486
- * The scan deferred by the last bash call. Every bracket joins this chain, so
487
- * at most one walk runs at a time and each one sees the baseline the previous
488
- * one left behind.
489
- */
490
- scanning = Promise.resolve();
491
- constructor(timeline, snapshots, manifests, options = {}) {
492
- this.timeline = timeline;
493
- this.snapshots = snapshots;
494
- this.manifests = manifests;
495
- this.now = options.now ?? Date.now;
496
- this.git = options.git;
617
+ async function toVersionView(version, snapshots) {
618
+ const view = {
619
+ index: version.index,
620
+ tool: version.tool,
621
+ at: version.at,
622
+ origin: version.origin,
623
+ additions: version.additions ?? 0,
624
+ removals: version.removals ?? 0
625
+ };
626
+ const createdHere = version.before === void 0 && version.created === true;
627
+ if (version.after === void 0 || version.before === void 0 && !createdHere) {
628
+ if (version.origin === "tool") return {
629
+ ...view,
630
+ note: version.after === void 0 ? NO_AFTER_NOTE : NO_BEFORE_NOTE
631
+ };
632
+ return {
633
+ ...view,
634
+ note: version.tool === "bash" ? NO_BASELINE_NOTE : NO_SNAPSHOT_NOTE
635
+ };
497
636
  }
498
- /**
499
- * Forgets the previous session's tree so a new one does not inherit its
500
- * baseline, and takes the paths this session's own bookkeeping occupies.
501
- */
502
- reset(options = {}) {
503
- this.pending.clear();
504
- this.bracketed.clear();
505
- this.contents.clear();
506
- this.manifest = void 0;
507
- this.scanning = Promise.resolve();
508
- this.excluded = options.exclude ?? [];
509
- this.isIgnored = options.isIgnored;
637
+ const after = await snapshots.read(version.after);
638
+ if (after === void 0) return {
639
+ ...view,
640
+ note: "the content behind this change is no longer held"
641
+ };
642
+ if (version.before === void 0) {
643
+ const fresh = lineDiffFromEmpty(after);
644
+ return {
645
+ ...view,
646
+ additions: fresh.additions,
647
+ removals: fresh.removals,
648
+ hunks: fresh.hunks,
649
+ ...fresh.approximate ? { note: APPROXIMATE_NOTE } : {}
650
+ };
510
651
  }
511
- /**
512
- * Awaits a scan still running in the background. A caller that is about to
513
- * clear the timeline needs this, or the scan appends after the clear.
514
- */
515
- async flush() {
516
- await this.scanning;
652
+ const before = await snapshots.read(version.before);
653
+ if (before === void 0) return {
654
+ ...view,
655
+ note: "the content behind this change is no longer held"
656
+ };
657
+ const diff = lineDiff(before, after);
658
+ return {
659
+ ...view,
660
+ additions: diff.additions,
661
+ removals: diff.removals,
662
+ hunks: diff.hunks,
663
+ ...diff.approximate ? { note: APPROXIMATE_NOTE } : {}
664
+ };
665
+ }
666
+ /** Everything the session did to the file: its oldest baseline against what is on disk now. */
667
+ async function toCumulativeView(versions, working, snapshots) {
668
+ const createdHere = versions[0]?.created === true;
669
+ const baseline = baselineOf(versions);
670
+ if (!createdHere && baseline === void 0) return {
671
+ additions: 0,
672
+ removals: 0,
673
+ note: versions[0]?.origin === "tool" ? NO_BEFORE_NOTE : NO_BASELINE_NOTE
674
+ };
675
+ if (working.unavailable) return {
676
+ additions: 0,
677
+ removals: 0,
678
+ note: working.reason ?? "the file cannot be read"
679
+ };
680
+ if (createdHere || baseline === void 0) {
681
+ const fresh = lineDiffFromEmpty(working.content);
682
+ return {
683
+ additions: fresh.additions,
684
+ removals: fresh.removals,
685
+ hunks: fresh.hunks,
686
+ ...fresh.approximate ? { note: APPROXIMATE_NOTE } : {}
687
+ };
517
688
  }
518
- async start(id, tool, args, cwd) {
519
- await this.scanning;
520
- if (tool === EDIT_TOOL || tool === WRITE_TOOL) {
521
- const supplied = objectValue(args, "path");
522
- if (!supplied) return;
523
- const filePath = node_path.default.resolve(cwd, supplied);
524
- const [before, fingerprint] = await Promise.all([this.snapshots.capture(filePath), this.manifests.fingerprint(filePath)]);
525
- this.pending.set(id, {
526
- tool,
527
- filePath,
528
- before,
529
- existed: fingerprint !== void 0
530
- });
531
- return;
532
- }
533
- if (tool !== BASH_TOOL) return;
534
- this.bracketed.set(id, this.now());
535
- this.manifest ??= await this.manifests.take(cwd, this.excluded);
689
+ const before = await snapshots.read(baseline);
690
+ if (before === void 0) return {
691
+ additions: 0,
692
+ removals: 0,
693
+ note: "the content this session started from is no longer held"
694
+ };
695
+ const diff = lineDiff(before, working.content);
696
+ return {
697
+ additions: diff.additions,
698
+ removals: diff.removals,
699
+ hunks: diff.hunks,
700
+ ...diff.approximate ? { note: APPROXIMATE_NOTE } : {}
701
+ };
702
+ }
703
+ //#endregion
704
+ //#region src/services/nodeWorkingFiles/index.ts
705
+ /**
706
+ * The routes' file operations over Node's real files.
707
+ *
708
+ * One technology per adapter. This is where node enters the API: a link or a
709
+ * rename can swap what a path names between two checks, so every read and write
710
+ * pins the file it checked by its open descriptor instead of by its name.
711
+ */
712
+ function hasCode$2(error, code) {
713
+ return error instanceof Error && "code" in error && error.code === code;
714
+ }
715
+ function describe(error) {
716
+ return error instanceof Error ? error.message : String(error);
717
+ }
718
+ /**
719
+ * The same containment check after symlinks are followed. A path that does not
720
+ * exist yet resolves to nothing, and there is nothing to hand out, so it
721
+ * passes and the read below reports it missing.
722
+ */
723
+ async function isRealPathInside(root, candidate) {
724
+ let realRoot;
725
+ let real;
726
+ try {
727
+ realRoot = await node_fs_promises.default.realpath(root);
728
+ real = await node_fs_promises.default.realpath(candidate);
729
+ } catch (error) {
730
+ return hasCode$2(error, "ENOENT");
536
731
  }
537
- async end(id, isError, cwd) {
538
- const pending = this.pending.get(id);
539
- this.pending.delete(id);
540
- const startedAt = this.bracketed.get(id);
541
- this.bracketed.delete(id);
542
- if (pending) {
543
- if (!isError) await this.recordTool(pending);
544
- return;
732
+ return isInside(realRoot, real);
733
+ }
734
+ /** Reads the file as the source view will show it, or says why it cannot. */
735
+ async function readWorking(filePath, opened, allowedRoot) {
736
+ let handle = opened;
737
+ let raw;
738
+ try {
739
+ handle ??= await (0, _agimon_ai_po_core_platform.openGuardedFile)(filePath, { root: allowedRoot });
740
+ const stats = await handle.stat();
741
+ if (!stats.isFile()) return unavailable("the file is not a regular file");
742
+ const named = await node_fs_promises.default.lstat(filePath);
743
+ if (!named.isFile() || stats.dev !== named.dev || stats.ino !== named.ino || allowedRoot !== void 0 && !await isRealPathInside(allowedRoot, filePath)) return unavailable("the file path changed or leaves its readable directory");
744
+ raw = Buffer.alloc(1048577);
745
+ if (stats.size <= 1048576) {
746
+ let offset = 0;
747
+ while (offset < raw.length) {
748
+ const { bytesRead } = await handle.read(raw, offset, raw.length - offset, offset);
749
+ if (bytesRead === 0) break;
750
+ offset += bytesRead;
751
+ }
752
+ raw = raw.subarray(0, offset);
545
753
  }
546
- if (startedAt === void 0) return;
547
- this.scanning = this.scanning.then(async () => {
548
- try {
549
- await this.recordScan(cwd, startedAt);
550
- } catch {}
551
- });
754
+ } catch {
755
+ return unavailable("the file no longer exists or cannot be safely read");
756
+ } finally {
757
+ if (opened === void 0) await handle?.close();
552
758
  }
553
- /** An `edit` or `write` whose file was read on both sides of the call. */
554
- async recordTool(pending) {
555
- const after = await this.snapshots.capture(pending.filePath);
556
- const created = !pending.existed;
557
- const counts = await this.countChanges(pending.before, after, created);
558
- if (after !== void 0) this.contents.set(pending.filePath, after);
559
- await this.append({
560
- version: 2,
561
- path: pending.filePath,
562
- tool: pending.tool,
563
- at: this.now(),
564
- origin: "tool",
565
- ...pending.before === void 0 ? {} : { before: pending.before },
566
- ...after === void 0 ? {} : { after },
567
- ...created ? { created: true } : {},
568
- ...counts
759
+ return workingViewOf(raw);
760
+ }
761
+ async function isInsideRoot(root, filePath) {
762
+ return isInside(root, filePath) && await isRealPathInside(root, filePath);
763
+ }
764
+ var NodeWorkingFiles = class {
765
+ readWorking(filePath, allowedRoot) {
766
+ return readWorking(filePath, void 0, allowedRoot);
767
+ }
768
+ isRealPathInside(root, candidate) {
769
+ return isRealPathInside(root, candidate);
770
+ }
771
+ async save({ filePath, root, content, expectedHash }) {
772
+ const canonical = await node_fs_promises.default.realpath(filePath);
773
+ return _agimon_ai_po_core_platform.fileMutationRunner.forKey(canonical)(async () => {
774
+ const handle = await (0, _agimon_ai_po_core_platform.openGuardedFile)(filePath, {
775
+ write: true,
776
+ root
777
+ });
778
+ try {
779
+ if (await node_fs_promises.default.realpath(filePath) !== canonical) return { status: "moved" };
780
+ const current = await readWorking(filePath, handle, root);
781
+ if (current.unavailable) return {
782
+ status: "unreadable",
783
+ reason: current.reason ?? "The file cannot be read."
784
+ };
785
+ if (current.hash !== expectedHash) return {
786
+ status: "stale",
787
+ hash: current.hash
788
+ };
789
+ const opened = await handle.stat();
790
+ const named = await node_fs_promises.default.lstat(filePath);
791
+ if (!opened.isFile() || opened.nlink !== 1 || !named.isFile() || named.nlink !== 1 || opened.dev !== named.dev || opened.ino !== named.ino || await node_fs_promises.default.realpath(filePath) !== canonical || !await isInsideRoot(root, filePath)) return { status: "moved" };
792
+ await handle.writeFile(content, "utf8");
793
+ await handle.truncate(Buffer.byteLength(content, "utf8"));
794
+ return {
795
+ status: "saved",
796
+ hash: hashOf(content)
797
+ };
798
+ } finally {
799
+ await handle.close();
800
+ }
569
801
  });
570
- await this.remember(pending.filePath);
571
802
  }
572
- /** Whatever a bash call actually edited, however the command wrote it. */
573
- async recordScan(cwd, startedAt) {
574
- const before = this.manifest;
575
- if (before === void 0) return;
576
- const after = await this.manifests.take(cwd, this.excluded);
577
- this.manifest = after;
578
- const disowned = this.isIgnored;
579
- const named = this.manifests.changed(before, after).filter((filePath) => disowned === void 0 || !disowned(filePath));
580
- const candidates = await this.writtenDuring(named, startedAt);
581
- if (candidates.length === 0) return;
582
- const unchanged = await this.unchangedInGit(cwd, candidates);
583
- for (const filePath of candidates) {
584
- const known = this.contents.get(filePath);
585
- if (known === void 0 && unchanged.has(filePath)) continue;
586
- const beforePrint = before.entries.get(filePath);
587
- const afterPrint = after.entries.get(filePath);
588
- const captured = afterPrint === void 0 ? void 0 : await this.snapshots.capture(filePath);
589
- if (captured !== void 0) this.contents.set(filePath, captured);
590
- if (captured !== void 0 && captured === known) continue;
591
- const proven = beforePrint === void 0 || afterPrint === void 0 || this.manifests.sizeChanged(beforePrint, afterPrint) || known !== void 0 && captured !== void 0 && captured !== known;
592
- await this.append({
593
- version: 2,
594
- path: filePath,
595
- tool: BASH_TOOL,
596
- at: this.now(),
597
- origin: "scan",
598
- ...proven ? { verified: true } : {},
599
- ...captured === void 0 ? {} : { after: captured }
803
+ async remove(filePath, root) {
804
+ try {
805
+ const canonical = await node_fs_promises.default.realpath(filePath).catch((error) => {
806
+ if (hasCode$2(error, "ENOENT")) return filePath;
807
+ throw error;
808
+ });
809
+ return await _agimon_ai_po_core_platform.fileMutationRunner.forKey(canonical)(async () => {
810
+ if (!await isInsideRoot(root, filePath)) return { status: "outside" };
811
+ await node_fs_promises.default.unlink(filePath);
812
+ return { status: "removed" };
600
813
  });
814
+ } catch (error) {
815
+ if (hasCode$2(error, "ENOENT")) return { status: "removed" };
816
+ return {
817
+ status: "failed",
818
+ reason: describe(error)
819
+ };
601
820
  }
602
821
  }
603
- /**
604
- * Narrows candidates to the ones that could have been written by the call
605
- * being closed.
606
- *
607
- * This is what keeps a working tree that was already dirty out of the list. A
608
- * file whose bytes were last written before the call began was differed by
609
- * something else, whatever moved its fingerprint. A file that is no longer
610
- * there has no time to read and a delete is a change the call may well have
611
- * made, so it stays a candidate.
612
- */
613
- async writtenDuring(candidates, startedAt) {
614
- const floor = startedAt - MODIFIED_TOLERANCE_MS;
615
- const written = [];
616
- for (const filePath of candidates) {
617
- const modifiedAt = await this.manifests.modifiedAt(filePath);
618
- if (modifiedAt === void 0 || modifiedAt >= floor) written.push(filePath);
822
+ };
823
+ //#endregion
824
+ //#region src/services/sessionStateSweep/index.ts
825
+ /**
826
+ * Remove the state sessions left behind when they never got to clean up.
827
+ *
828
+ * A session clears its own timeline and snapshots on shutdown, which covers the
829
+ * ordinary case and nothing else: a killed process, a crash, or a machine that
830
+ * lost power leaves both behind, and nothing ever looked at the directory
831
+ * again. One week of that filled a real checkout with hundreds of megabytes.
832
+ *
833
+ * Age is the only signal used, because it is the only one that is true from
834
+ * another process. A running session appends as it works, so its timeline is
835
+ * recent; a dead one stops moving at the moment it died.
836
+ */
837
+ /**
838
+ * How long state may sit untouched before a later session removes it.
839
+ *
840
+ * Generous on purpose. The cost of waiting is disk, and the cost of being wrong
841
+ * is deleting a live session's history, so this is set far beyond any plausible
842
+ * gap between two appends rather than close to it.
843
+ */
844
+ const STATE_MAX_AGE_MS = 6048e5;
845
+ const TIMELINE_SUFFIX = ".jsonl";
846
+ const SNAPSHOTS_SUFFIX = ".blobs";
847
+ async function remove(target) {
848
+ await node_fs_promises.default.rm(target, {
849
+ recursive: true,
850
+ force: true
851
+ });
852
+ }
853
+ /** The most recent time anything under this session's state moved. */
854
+ async function lastTouched(paths) {
855
+ let newest;
856
+ for (const target of paths) try {
857
+ const stat = await node_fs_promises.default.stat(target);
858
+ if (newest === void 0 || stat.mtimeMs > newest) newest = stat.mtimeMs;
859
+ } catch {}
860
+ return newest;
861
+ }
862
+ /** How many sessions' worth of state was removed. */
863
+ async function sweepSessionState(options) {
864
+ const { directory, keep, removeDirectory = false, now = Date.now(), maxAgeMs = STATE_MAX_AGE_MS } = options;
865
+ let entries;
866
+ try {
867
+ entries = await node_fs_promises.default.readdir(directory);
868
+ } catch {
869
+ return 0;
870
+ }
871
+ const floor = now - maxAgeMs;
872
+ const timelines = new Set(entries.filter((entry) => entry.endsWith(TIMELINE_SUFFIX)));
873
+ let removed = 0;
874
+ for (const entry of timelines) {
875
+ const timelinePath = node_path.default.join(directory, entry);
876
+ if (keep !== void 0 && timelinePath === keep) continue;
877
+ const snapshotsPath = `${timelinePath.slice(0, -6)}${SNAPSHOTS_SUFFIX}`;
878
+ const lockPath = `${timelinePath}.lock`;
879
+ const touched = await lastTouched([
880
+ timelinePath,
881
+ snapshotsPath,
882
+ lockPath
883
+ ]);
884
+ if (touched === void 0 || touched >= floor) continue;
885
+ await remove(snapshotsPath);
886
+ await remove(timelinePath);
887
+ await remove(lockPath);
888
+ removed += 1;
889
+ }
890
+ for (const entry of entries) {
891
+ if (!entry.endsWith(SNAPSHOTS_SUFFIX)) continue;
892
+ if (timelines.has(`${entry.slice(0, -6)}${TIMELINE_SUFFIX}`)) continue;
893
+ const orphan = node_path.default.join(directory, entry);
894
+ const touched = await lastTouched([orphan]);
895
+ if (touched === void 0 || touched >= floor) continue;
896
+ await remove(orphan);
897
+ }
898
+ if (removeDirectory) try {
899
+ await node_fs_promises.default.rmdir(directory);
900
+ } catch {}
901
+ return removed;
902
+ }
903
+ //#endregion
904
+ //#region src/services/snapshotStore/index.ts
905
+ /**
906
+ * Store and read the file content this session's diffs are built from.
907
+ *
908
+ * One technology per adapter. This is where node enters the package; the
909
+ * services that depend on the capability keep importing the port.
910
+ *
911
+ * Snapshots are content-addressed, so a file written twice with the same bytes
912
+ * occupies one blob and the second capture is a hash and an exists check. The
913
+ * whole directory goes when the session's timeline does, which is what keeps
914
+ * this from growing without bound across a machine's lifetime.
915
+ */
916
+ const MISSING_CODES = /* @__PURE__ */ new Set([
917
+ "ENOENT",
918
+ "ENOTDIR",
919
+ "EISDIR",
920
+ "ENAMETOOLONG"
921
+ ]);
922
+ function hasCode$1(error, codes) {
923
+ return error instanceof Error && "code" in error && typeof error.code === "string" && codes.has(error.code);
924
+ }
925
+ var NodeSnapshotStoreAdapter = class {
926
+ directory;
927
+ initialize(directory) {
928
+ this.directory = directory;
929
+ }
930
+ async capture(filePath) {
931
+ let raw;
932
+ try {
933
+ if ((await node_fs_promises.default.stat(filePath)).size > 1048576) return void 0;
934
+ raw = await node_fs_promises.default.readFile(filePath);
935
+ } catch (error) {
936
+ if (hasCode$1(error, MISSING_CODES)) return void 0;
937
+ throw error;
619
938
  }
620
- return written;
939
+ if (raw.byteLength > 1048576) return void 0;
940
+ if (raw.subarray(0, 8192).includes(0)) return void 0;
941
+ return this.put(raw.toString("utf8"));
621
942
  }
622
- /** Which candidates git tracks and reports as untouched; empty when it cannot say. */
623
- async unchangedInGit(cwd, candidates) {
624
- const unseen = candidates.filter((filePath) => !this.contents.has(filePath));
625
- if (this.git === void 0 || unseen.length === 0) return /* @__PURE__ */ new Set();
626
- return this.git.unchanged(cwd, unseen);
943
+ async put(content) {
944
+ const hash = (0, node_crypto.createHash)("sha256").update(content, "utf8").digest("hex");
945
+ const blobPath = node_path.default.join(this.requireDirectory(), hash);
946
+ try {
947
+ await node_fs_promises.default.access(blobPath);
948
+ return hash;
949
+ } catch (error) {
950
+ if (!hasCode$1(error, MISSING_CODES)) throw error;
951
+ }
952
+ await node_fs_promises.default.mkdir(this.requireDirectory(), { recursive: true });
953
+ await node_fs_promises.default.writeFile(blobPath, content, "utf8");
954
+ return hash;
627
955
  }
628
- /** How many lines moved, when there is enough captured content to say. */
629
- async countChanges(before, after, created) {
630
- if (after === void 0) return {};
631
- if (before === void 0) {
632
- if (!created) return {};
633
- const createdText = await this.snapshots.read(after);
634
- if (createdText === void 0) return {};
635
- const fresh = lineDiffFromEmpty(createdText);
636
- return {
637
- additions: fresh.additions,
638
- removals: fresh.removals
639
- };
956
+ async read(hash) {
957
+ if (!/^[0-9a-f]{64}$/u.test(hash)) return void 0;
958
+ try {
959
+ return await node_fs_promises.default.readFile(node_path.default.join(this.requireDirectory(), hash), "utf8");
960
+ } catch (error) {
961
+ if (hasCode$1(error, MISSING_CODES)) return void 0;
962
+ throw error;
640
963
  }
641
- if (before === after) return {
642
- additions: 0,
643
- removals: 0
644
- };
645
- const [beforeText, afterText] = await Promise.all([this.snapshots.read(before), this.snapshots.read(after)]);
646
- if (beforeText === void 0 || afterText === void 0) return {};
647
- const diff = lineDiff(beforeText, afterText);
648
- return {
649
- additions: diff.additions,
650
- removals: diff.removals
651
- };
652
964
  }
653
- /** Records the change unless it turned out to be no change at all. */
654
- async append(event) {
655
- if (event.before !== void 0 && event.before === event.after) return;
656
- await this.timeline.append(event);
965
+ async clear() {
966
+ if (this.directory === void 0) return;
967
+ await node_fs_promises.default.rm(this.directory, {
968
+ recursive: true,
969
+ force: true
970
+ });
657
971
  }
658
- /**
659
- * Folds a path the tool layer just handled into the tracked manifest, so the
660
- * next bash comparison sees it as already accounted for.
661
- *
662
- * The fingerprint has to be the one a walk would read, not a stand-in, or the
663
- * next comparison reports the file again under bash and every tool edit is
664
- * recorded twice.
665
- */
666
- async remember(filePath) {
667
- if (this.manifest === void 0) return;
668
- const entries = new Map(this.manifest.entries);
669
- const fingerprint = await this.manifests.fingerprint(filePath);
670
- if (fingerprint === void 0) entries.delete(filePath);
671
- else entries.set(filePath, fingerprint);
672
- this.manifest = {
673
- entries,
674
- truncated: this.manifest.truncated
675
- };
972
+ requireDirectory() {
973
+ if (this.directory === void 0) throw new Error("Snapshot store is not initialized");
974
+ return this.directory;
676
975
  }
677
976
  };
678
977
  //#endregion
679
- //#region src/services/fileEditPaths/index.ts
680
- /** The directory this package owns, under whichever root holds agent state. */
681
- const STATE_DIRECTORY = "po-file-edit";
682
- function hash(value) {
683
- return (0, node_crypto.createHash)("sha256").update(value).digest("hex").slice(0, 16);
978
+ //#region src/services/timelineStore/index.ts
979
+ const LOCK_RETRY_MS = 25;
980
+ const LOCK_RETRIES = 400;
981
+ /**
982
+ * How long a lock file may sit untouched before a waiter treats it as abandoned.
983
+ *
984
+ * An append writes one line, so a holder that has been there for half a minute
985
+ * is a process that died without unlinking. Without this, that one file would
986
+ * block every later append to the same timeline permanently.
987
+ */
988
+ const LOCK_STALE_MS = 3e4;
989
+ function hasCode(error, code) {
990
+ return error instanceof Error && "code" in error && error.code === code;
684
991
  }
685
- var FileEditPaths = class {
686
- environment;
687
- constructor(environment = process.env) {
688
- this.environment = environment;
992
+ var TimelineStore = class {
993
+ filePath;
994
+ initialize(filePath) {
995
+ this.filePath = filePath;
689
996
  }
690
- sessionKey(sessionId, env = this.environment) {
691
- if (env[_agimon_ai_po_core_childProcess.SUBAGENT_CHILD_ENV]) {
692
- const parent = env[_agimon_ai_po_core_childProcess.SUBAGENT_PARENT_SESSION_ENV];
693
- if (parent) return parent;
997
+ async append(event) {
998
+ await this.withLock(async () => node_fs_promises.default.appendFile(this.requirePath(), `${JSON.stringify(event)}\n`, "utf8"));
999
+ }
1000
+ async list() {
1001
+ return foldEntries(confirmedChanges(await this.events()));
1002
+ }
1003
+ async versions(filePath) {
1004
+ return foldVersions(confirmedChanges(await this.events()), filePath);
1005
+ }
1006
+ async clear() {
1007
+ try {
1008
+ await node_fs_promises.default.unlink(this.requirePath());
1009
+ } catch (error) {
1010
+ if (!hasCode(error, "ENOENT")) throw error;
694
1011
  }
695
- return sessionId;
696
1012
  }
697
- /**
698
- * Where every session's state lives: the Pi agent directory, the same root
699
- * every other Po package writes to, and never inside the working tree.
700
- *
701
- * An earlier layout put this in the repository's git common directory. That
702
- * is git's own storage: nothing in git's lifecycle prunes a directory we add
703
- * to it, a linked worktree writes into the main checkout rather than its own,
704
- * a submodule writes inside `.git/modules`, and `PI_CODING_AGENT_DIR` was
705
- * ignored outright. The snapshots are verbatim copies of files the session
706
- * touched, so where they land is a question about handling content, not a
707
- * question about convenience.
708
- */
709
- stateDirectory() {
710
- return node_path.default.join((0, _agimon_ai_po_core_piSettings.piAgentDirectory)(this.environment, this.environment.HOME), STATE_DIRECTORY);
1013
+ /** Every recorded change, or none at all when the session has not written yet. */
1014
+ async events() {
1015
+ let content;
1016
+ try {
1017
+ content = await node_fs_promises.default.readFile(this.requirePath(), "utf8");
1018
+ } catch (error) {
1019
+ if (hasCode(error, "ENOENT")) return [];
1020
+ throw error;
1021
+ }
1022
+ return parseTimeline(content, (line) => console.warn(`Ignoring malformed file edit timeline line: ${line.slice(0, 200)}`));
711
1023
  }
712
- /**
713
- * One session's timeline, named from its working directory and its session so
714
- * the hub and the session API can find it from another process knowing only
715
- * those two things.
716
- */
717
- timelinePath(cwd, sessionKey) {
718
- const directory = this.stateDirectory();
719
- node_fs.default.mkdirSync(directory, { recursive: true });
720
- return node_path.default.join(directory, `${hash(node_fs.default.realpathSync(cwd))}-${hash(sessionKey)}.jsonl`);
1024
+ requirePath() {
1025
+ if (!this.filePath) throw new Error("Timeline store is not initialized");
1026
+ return this.filePath;
721
1027
  }
722
- /**
723
- * Where this session's content snapshots live: beside its timeline and named
724
- * after it, so the two are found together and cleared together.
725
- */
726
- snapshotsPath(cwd, sessionKey) {
727
- return `${this.timelinePath(cwd, sessionKey).replace(/\.jsonl$/u, "")}.blobs`;
1028
+ async withLock(operation) {
1029
+ const lockPath = `${this.requirePath()}.lock`;
1030
+ const lock = await this.acquire(lockPath);
1031
+ try {
1032
+ return await operation();
1033
+ } finally {
1034
+ await lock.close();
1035
+ await this.release(lockPath);
1036
+ }
1037
+ }
1038
+ /** Waits for the lock file, breaking one an earlier process left behind. */
1039
+ async acquire(lockPath) {
1040
+ for (let attempt = 0; attempt < LOCK_RETRIES; attempt += 1) try {
1041
+ return await node_fs_promises.default.open(lockPath, "wx");
1042
+ } catch (error) {
1043
+ if (!hasCode(error, "EEXIST")) throw error;
1044
+ if (await this.breakStale(lockPath)) continue;
1045
+ await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
1046
+ }
1047
+ throw new Error(`Timed out acquiring timeline lock ${lockPath}`);
1048
+ }
1049
+ /** Whether the lock is now free to take, having removed it when its holder is gone. */
1050
+ async breakStale(lockPath) {
1051
+ try {
1052
+ const stats = await node_fs_promises.default.stat(lockPath);
1053
+ if (Date.now() - stats.mtimeMs < LOCK_STALE_MS) return false;
1054
+ await node_fs_promises.default.unlink(lockPath);
1055
+ return true;
1056
+ } catch (error) {
1057
+ if (hasCode(error, "ENOENT")) return true;
1058
+ throw error;
1059
+ }
1060
+ }
1061
+ async release(lockPath) {
1062
+ try {
1063
+ await node_fs_promises.default.unlink(lockPath);
1064
+ } catch (error) {
1065
+ if (!hasCode(error, "ENOENT")) console.warn(`Could not remove timeline lock: ${String(error)}`);
1066
+ }
728
1067
  }
729
1068
  };
730
1069
  //#endregion
731
- //#region src/services/gitStatus/index.ts
1070
+ //#region src/services/manifestComparison/index.ts
732
1071
  /**
733
- * Answers the unchanged question with git, in two batched calls per chunk.
734
- *
735
- * One technology per adapter. This is where git enters the scan path; the
736
- * tracker that depends on the capability keeps importing the port.
1072
+ * Directories a working tree fills with output nobody wants listed as an edit.
737
1073
  *
738
- * `ls-files` names which of the given paths git tracks at all, and `status`
739
- * names which of those moved. Everything else, an ignored build artefact, a
740
- * temporary file, a tree with no repository, falls out of both answers and is
741
- * therefore never reported as unchanged: the caller must keep recording it,
742
- * because git has nothing to say about a file it never saw.
1074
+ * Two kinds live here. Most are the build and dependency trees every checkout
1075
+ * grows. The rest are where tooling, including this agent's own, writes while a
1076
+ * session runs: a telemetry log under `logs`, a test run's artifacts under
1077
+ * `test-results` and `playwright-report`, scratch space under `tmp`, and agent
1078
+ * state under `.pi`. A changed path under any of them is dropped by construction
1079
+ * rather than judged file by file, because recording it reports the session
1080
+ * watching itself.
743
1081
  */
744
- /** Paths per git invocation, so a large scan cannot overflow the argument list. */
745
- const CHUNK = 200;
746
- const MAX_BUFFER = 4194304;
747
- const run = (0, node_util.promisify)(node_child_process.execFile);
748
- function chunked(values, size) {
749
- const groups = [];
750
- for (let index = 0; index < values.length; index += size) groups.push(values.slice(index, index + size));
751
- return groups;
1082
+ const IGNORED_DIRECTORIES = /* @__PURE__ */ new Set([
1083
+ ".git",
1084
+ ".hg",
1085
+ ".svn",
1086
+ ".cache",
1087
+ ".gradle",
1088
+ ".next",
1089
+ ".nuxt",
1090
+ ".nx",
1091
+ ".pi",
1092
+ ".pnpm-store",
1093
+ ".turbo",
1094
+ ".venv",
1095
+ "__pycache__",
1096
+ "build",
1097
+ "coverage",
1098
+ "dist",
1099
+ "logs",
1100
+ "node_modules",
1101
+ "out",
1102
+ "playwright-report",
1103
+ "target",
1104
+ "test-results",
1105
+ "tmp",
1106
+ "vendor",
1107
+ "venv"
1108
+ ]);
1109
+ /**
1110
+ * How a file is summarised. Size and modification time are one stat away;
1111
+ * hashing every candidate would turn each comparison into a read of each file.
1112
+ */
1113
+ function fingerprintOf(size, modifiedMs) {
1114
+ return `${size}:${modifiedMs}`;
1115
+ }
1116
+ /** The size half of a fingerprint, which only the adapter that wrote it can read. */
1117
+ function sizeOf(fingerprint) {
1118
+ const separator = fingerprint.indexOf(":");
1119
+ return separator === -1 ? fingerprint : fingerprint.slice(0, separator);
752
1120
  }
753
- function splitRecords(output) {
754
- return output.split("\0").filter((entry) => entry !== "");
1121
+ /** Every path added, removed, or modified between two manifests, sorted. */
1122
+ function changedBetween(before, after) {
1123
+ const moved = /* @__PURE__ */ new Set();
1124
+ for (const [filePath, fingerprint] of after.entries) if (before.entries.get(filePath) !== fingerprint) moved.add(filePath);
1125
+ for (const filePath of before.entries.keys()) if (!after.entries.has(filePath)) moved.add(filePath);
1126
+ return [...moved].sort();
755
1127
  }
1128
+ /** Whether two fingerprints disagree about size; false when either side is absent. */
1129
+ function sizesDiffer(before, after) {
1130
+ if (before === void 0 || after === void 0) return false;
1131
+ return sizeOf(before) !== sizeOf(after);
1132
+ }
1133
+ //#endregion
1134
+ //#region src/services/treeManifest/index.ts
756
1135
  /**
757
- * The paths named by `status --porcelain -z`, whose records carry a two-letter
758
- * code and a space. A rename adds a bare second record; keeping it is harmless,
759
- * because every path in this set is one the caller records anyway.
1136
+ * Fingerprints single files with node's fs.
1137
+ *
1138
+ * One technology per adapter. This is where node enters the package; the
1139
+ * services that depend on the capability keep importing the port.
760
1140
  */
761
- function statusPaths(output) {
762
- return splitRecords(output).map((record) => record.length > 3 && record[2] === " " ? record.slice(3) : record);
763
- }
764
- function isInside$1(root, filePath) {
765
- const relative = node_path.default.relative(root, filePath);
766
- return relative !== "" && !relative.startsWith("..") && !node_path.default.isAbsolute(relative);
767
- }
768
- var NodeGitStatusAdapter = class {
769
- async unchanged(cwd, filePaths) {
770
- const clean = /* @__PURE__ */ new Set();
771
- if (filePaths.length === 0) return clean;
772
- const root = await this.topLevel(cwd);
773
- if (root === void 0) return clean;
774
- for (const group of chunked(filePaths.filter((filePath) => isInside$1(root, filePath)), CHUNK)) {
775
- const relative = group.map((filePath) => node_path.default.relative(root, filePath));
776
- const tracked = await this.git(root, [
777
- "ls-files",
778
- "-z",
779
- "--",
780
- ...relative
781
- ]);
782
- if (tracked === void 0) continue;
783
- const dirty = await this.git(root, [
784
- "status",
785
- "--porcelain",
786
- "-z",
787
- "--untracked-files=no",
788
- "--",
789
- ...relative
790
- ]);
791
- if (dirty === void 0) continue;
792
- const moved = new Set(statusPaths(dirty));
793
- for (const entry of splitRecords(tracked)) if (!moved.has(entry)) clean.add(node_path.default.resolve(root, entry));
1141
+ var NodeTreeManifestAdapter = class {
1142
+ async fingerprint(filePath) {
1143
+ try {
1144
+ const stat = await node_fs_promises.default.stat(filePath);
1145
+ return stat.isFile() ? fingerprintOf(stat.size, stat.mtimeMs) : void 0;
1146
+ } catch {
1147
+ return;
794
1148
  }
795
- return clean;
796
- }
797
- /** The repository root, or undefined when this tree is not one. */
798
- async topLevel(cwd) {
799
- const root = (await this.git(cwd, ["rev-parse", "--show-toplevel"]))?.trim();
800
- return root === void 0 || root === "" ? void 0 : node_path.default.resolve(root);
801
1149
  }
802
- /** Git's stdout, or undefined when the call failed for any reason at all. */
803
- async git(cwd, args) {
1150
+ async modifiedAt(filePath) {
804
1151
  try {
805
- const { stdout } = await run("git", [...args], {
806
- cwd,
807
- encoding: "utf8",
808
- maxBuffer: MAX_BUFFER
809
- });
810
- return stdout;
1152
+ const stat = await node_fs_promises.default.stat(filePath);
1153
+ return stat.isFile() ? stat.mtimeMs : void 0;
811
1154
  } catch {
812
1155
  return;
813
1156
  }
814
1157
  }
1158
+ changed(before, after) {
1159
+ return changedBetween(before, after);
1160
+ }
1161
+ sizeChanged(before, after) {
1162
+ return sizesDiffer(before, after);
1163
+ }
815
1164
  };
816
1165
  //#endregion
1166
+ //#region src/types/webFiles.ts
1167
+ /** The frame type the hub publishes and the web plugin claims; declared in the poWeb block too. */
1168
+ const filesChannelType = "file_edits";
1169
+ /** Footer status key whose presence shows the activity group; the extension publishes it. */
1170
+ const filesStatusKey = "po-file-edit-files";
1171
+ //#endregion
1172
+ //#region src/services/filesChannel/index.ts
1173
+ /**
1174
+ * The changed-files channel consumes snapshots emitted by the owning session's
1175
+ * server plugin. Durable timeline reads seed a channel that starts after session
1176
+ * startup.
1177
+ */
1178
+ function filesPayload(value) {
1179
+ return typeof value === "object" && value !== null && Array.isArray(value.items);
1180
+ }
1181
+ /**
1182
+ * The files data channel: one direct-event subscription per managed session,
1183
+ * published as { items } payloads under the 'file_edits' frame type.
1184
+ */
1185
+ function createFilesChannel(storage) {
1186
+ return {
1187
+ frameType: filesChannelType,
1188
+ start(host) {
1189
+ const latest = /* @__PURE__ */ new Map();
1190
+ const subscriptions = /* @__PURE__ */ new Map();
1191
+ return {
1192
+ payloadFor(scope) {
1193
+ const items = latest.get(scope.sessionId);
1194
+ return items === void 0 ? void 0 : { items };
1195
+ },
1196
+ sessionAdded(scope) {
1197
+ subscriptions.get(scope.sessionId)?.();
1198
+ const paths = storage.paths(scope.environment);
1199
+ let current = true;
1200
+ let receivedDirect = false;
1201
+ const unsubscribe = host.directEvents.subscribe(filesChannelType, scope.sessionId, (payload) => {
1202
+ if (!filesPayload(payload)) return;
1203
+ receivedDirect = true;
1204
+ latest.set(scope.sessionId, payload.items);
1205
+ host.publish(scope.sessionId, payload);
1206
+ }, { replayLatest: true });
1207
+ subscriptions.set(scope.sessionId, () => {
1208
+ current = false;
1209
+ unsubscribe();
1210
+ });
1211
+ (async () => {
1212
+ let items = [];
1213
+ try {
1214
+ const timelinePath = await paths.timelinePath(scope.cwd, paths.sessionKey(scope.sessionId));
1215
+ items = await storage.sessionFiles(timelinePath, scope.cwd);
1216
+ } catch {}
1217
+ if (!current || receivedDirect) return;
1218
+ latest.set(scope.sessionId, items);
1219
+ host.publish(scope.sessionId, { items });
1220
+ })().catch((error) => host.onNotice(`File-edit channel seed failed: ${String(error)}`));
1221
+ },
1222
+ sessionRemoved(sessionId) {
1223
+ subscriptions.get(sessionId)?.();
1224
+ subscriptions.delete(sessionId);
1225
+ latest.delete(sessionId);
1226
+ },
1227
+ close() {
1228
+ for (const unsubscribe of subscriptions.values()) unsubscribe();
1229
+ subscriptions.clear();
1230
+ latest.clear();
1231
+ }
1232
+ };
1233
+ }
1234
+ };
1235
+ }
1236
+ //#endregion
817
1237
  //#region src/services/poIgnore/index.ts
818
1238
  function matchablePath(relPath) {
819
1239
  const normalized = relPath.replace(/\\/gu, "/");
@@ -848,437 +1268,704 @@ function filterPoIgnoredFiles(items, content) {
848
1268
  if (ignored === void 0) return items;
849
1269
  return items.filter((item) => !ignored(item.relPath));
850
1270
  }
851
- /** How much of a file is read before deciding it is binary. */
852
- const BINARY_SAMPLE_BYTES$1 = 8192;
853
- const MISSING_CODES = /* @__PURE__ */ new Set([
854
- "ENOENT",
855
- "ENOTDIR",
856
- "EISDIR",
857
- "ENAMETOOLONG"
858
- ]);
859
- function hasCode$2(error, codes) {
860
- return error instanceof Error && "code" in error && typeof error.code === "string" && codes.has(error.code);
861
- }
862
- var NodeSnapshotStoreAdapter = class {
863
- directory;
864
- initialize(directory) {
865
- this.directory = directory;
866
- }
867
- async capture(filePath) {
868
- let raw;
869
- try {
870
- raw = await node_fs_promises.default.readFile(filePath);
871
- } catch (error) {
872
- if (hasCode$2(error, MISSING_CODES)) return void 0;
873
- throw error;
874
- }
875
- if (raw.byteLength > 1048576) return void 0;
876
- if (raw.subarray(0, BINARY_SAMPLE_BYTES$1).includes(0)) return void 0;
877
- return this.put(raw.toString("utf8"));
878
- }
879
- async put(content) {
880
- const hash = (0, node_crypto.createHash)("sha256").update(content, "utf8").digest("hex");
881
- const blobPath = node_path.default.join(this.requireDirectory(), hash);
882
- try {
883
- await node_fs_promises.default.access(blobPath);
884
- return hash;
885
- } catch (error) {
886
- if (!hasCode$2(error, MISSING_CODES)) throw error;
887
- }
888
- await node_fs_promises.default.mkdir(this.requireDirectory(), { recursive: true });
889
- await node_fs_promises.default.writeFile(blobPath, content, "utf8");
890
- return hash;
891
- }
892
- async read(hash) {
893
- if (!/^[0-9a-f]{64}$/u.test(hash)) return void 0;
894
- try {
895
- return await node_fs_promises.default.readFile(node_path.default.join(this.requireDirectory(), hash), "utf8");
896
- } catch (error) {
897
- if (hasCode$2(error, MISSING_CODES)) return void 0;
898
- throw error;
899
- }
900
- }
901
- async clear() {
902
- if (this.directory === void 0) return;
903
- await node_fs_promises.default.rm(this.directory, {
904
- recursive: true,
905
- force: true
906
- });
907
- }
908
- requireDirectory() {
909
- if (this.directory === void 0) throw new Error("Snapshot store is not initialized");
910
- return this.directory;
911
- }
912
- };
913
1271
  //#endregion
914
- //#region src/services/fileChanges/index.ts
915
- const TOOLS = /* @__PURE__ */ new Set([
916
- "edit",
917
- "write",
918
- "bash",
919
- "user"
920
- ]);
921
- function isRecord(value) {
922
- return typeof value === "object" && value !== null && !Array.isArray(value);
923
- }
924
- function optionalString(value) {
925
- return typeof value === "string" && value !== "" ? value : void 0;
926
- }
927
- function optionalCount(value) {
928
- return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
929
- }
930
- /** Narrows one parsed line, or answers null so a malformed line can be skipped. */
931
- function parseTimelineEvent(value) {
932
- if (!isRecord(value)) return null;
933
- const { version, path: filePath, tool, at } = value;
934
- if (typeof filePath !== "string" || filePath === "") return null;
935
- if (typeof at !== "number" || !Number.isFinite(at)) return null;
936
- if (typeof tool !== "string" || !TOOLS.has(tool)) return null;
937
- if (version === 1) {
938
- if (tool === "user") return null;
939
- return {
940
- version: 1,
941
- path: filePath,
942
- tool,
943
- at
944
- };
945
- }
946
- if (version !== 2) return null;
947
- return {
948
- version: 2,
949
- path: filePath,
950
- tool,
951
- at,
952
- origin: value.origin === "scan" ? "scan" : "tool",
953
- ...optionalString(value.before) === void 0 ? {} : { before: value.before },
954
- ...optionalString(value.after) === void 0 ? {} : { after: value.after },
955
- ...optionalCount(value.additions) === void 0 ? {} : { additions: value.additions },
956
- ...optionalCount(value.removals) === void 0 ? {} : { removals: value.removals },
957
- ...value.verified === true ? { verified: true } : {},
958
- ...value.created === true ? { created: true } : {}
959
- };
960
- }
961
- /** Every recorded line of the timeline, malformed ones dropped, in file order. */
962
- function parseTimeline(content, onMalformed) {
963
- const events = [];
964
- for (const line of content.split("\n")) {
965
- if (line === "") continue;
966
- let parsed;
967
- try {
968
- parsed = JSON.parse(line);
969
- } catch {
970
- onMalformed?.(line);
971
- continue;
972
- }
973
- const event = parseTimelineEvent(parsed);
974
- if (event === null) onMalformed?.(line);
975
- else events.push(event);
1272
+ //#region src/services/sessionFileRows/index.ts
1273
+ /**
1274
+ * Presents a session's timeline as the rows the dock lists.
1275
+ *
1276
+ * A file the session changed and then removed is left out, and so is a path a
1277
+ * bash call only touched: a command that moves a modification time without
1278
+ * changing a byte is not an edit, and listing it buries the ones that are. The
1279
+ * dock is a list of things to open, and a row that can only ever answer "this
1280
+ * is gone" is a dead end; the timeline still holds the change, so a tab already
1281
+ * open on the file keeps working and says so.
1282
+ */
1283
+ async function sessionFileRows({ content, cwd, exists, readPoIgnore }) {
1284
+ const events = confirmedChanges(parseTimeline(content));
1285
+ const entries = foldEntries(events);
1286
+ const present = await Promise.all(entries.map((entry) => exists(entry.path)));
1287
+ const items = entries.filter((_entry, index) => present[index]).map((entry) => ({
1288
+ path: entry.path,
1289
+ relPath: node_path.default.relative(cwd, entry.path) || entry.path,
1290
+ tool: entry.tool,
1291
+ at: entry.at,
1292
+ count: entry.count,
1293
+ diffable: isDiffable(foldVersions(events, entry.path))
1294
+ }));
1295
+ try {
1296
+ return filterPoIgnoredFiles(items, await readPoIgnore());
1297
+ } catch {
1298
+ return items;
976
1299
  }
977
- return events;
978
1300
  }
1301
+ //#endregion
1302
+ //#region src/services/webFilesChannel/index.ts
1303
+ /** Whether the file is still there to be opened. */
1304
+ async function stillExists(filePath) {
1305
+ try {
1306
+ return (await node_fs_promises.default.stat(filePath)).isFile();
1307
+ } catch {
1308
+ return false;
1309
+ }
1310
+ }
1311
+ /** Reads one session's timeline from Node's files and presents it as the rows the dock lists. */
1312
+ async function readSessionFiles(timelinePath, cwd) {
1313
+ let content;
1314
+ try {
1315
+ content = await node_fs_promises.default.readFile(timelinePath, "utf8");
1316
+ } catch {
1317
+ return [];
1318
+ }
1319
+ return sessionFileRows({
1320
+ content,
1321
+ cwd,
1322
+ exists: stillExists,
1323
+ readPoIgnore: () => node_fs_promises.default.readFile(node_path.default.join(cwd, ".poignore"), "utf8")
1324
+ });
1325
+ }
1326
+ //#endregion
1327
+ //#region src/services/fileEditStorage/index.ts
979
1328
  /**
980
- * Whether a recorded change is evidence that the file's content actually moved.
1329
+ * The storage a session's file history uses on Node: the real file system,
1330
+ * read directly, with the cross-process lock a subagent child's appends need.
981
1331
  *
982
- * A tool change names its file and reads both sides, so it always is. A scan
983
- * change is a tree comparison of size and modification time, which a checkout,
984
- * an install, or a command that merely touched a file moves as readily as an
985
- * edit does; only a scan the tracker confirmed carries `verified`. Version 1
986
- * lines predate the distinction entirely, so a bash one cannot be trusted.
1332
+ * The edge build replaces this module with `index.edge.ts`, which reads the
1333
+ * file system the host injects. On Node, an injected file system is used for
1334
+ * config reads when provided, falling back to `createNodePlatform().env(cwd)`.
987
1335
  */
988
- function isConfirmedChange(event) {
989
- if (event.version !== 2) return event.tool !== "bash";
990
- return event.origin !== "scan" || event.verified === true;
991
- }
992
- /** The recorded changes worth listing, which is every change but an unconfirmed touch. */
993
- function confirmedChanges(events) {
994
- return events.filter(isConfirmedChange);
995
- }
996
- /** One row per file, newest change first, which is the order both docks list in. */
997
- function foldEntries(events) {
998
- const folded = /* @__PURE__ */ new Map();
999
- for (const event of events) {
1000
- const current = folded.get(event.path);
1001
- folded.set(event.path, {
1002
- path: event.path,
1003
- tool: event.at >= (current?.at ?? 0) ? event.tool : current?.tool ?? event.tool,
1004
- at: Math.max(event.at, current?.at ?? 0),
1005
- count: (current?.count ?? 0) + 1
1336
+ const nodePresenceFiles = {
1337
+ isFile: async (filePath) => (await node_fs_promises.default.stat(filePath).catch(() => void 0))?.isFile() === true,
1338
+ realpath: (filePath) => node_fs_promises.default.realpath(filePath).catch(() => void 0),
1339
+ read: (filePath) => node_fs_promises.default.readFile(filePath).catch(() => void 0)
1340
+ };
1341
+ /**
1342
+ * The plans directory Plan mode writes to, resolved the way Plan resolves it, so
1343
+ * a plan link in the transcript opens in the file view. A config that cannot be
1344
+ * read admits nothing extra rather than failing the preview.
1345
+ */
1346
+ async function plansRoots(files, cwd, environment, homeDirectory) {
1347
+ const home = homeDirectory ?? environment.HOME ?? node_os.default.homedir();
1348
+ const fs = files ?? (0, _agimon_ai_po_core_nodePlatform.createNodePlatform)().env(cwd);
1349
+ try {
1350
+ const config = await (0, _agimon_ai_po_config.readPoConfig)(fs, cwd, _agimon_ai_po_core_platform.BACKGROUND_CONTEXT, {
1351
+ environment,
1352
+ homeDirectory: home
1006
1353
  });
1354
+ return [(0, _agimon_ai_po_config.resolvePlanningPlansDirectory)(config.modes?.planning?.plansDirectory, cwd, home)];
1355
+ } catch {
1356
+ return [];
1007
1357
  }
1008
- return [...folded.values()].sort((left, right) => right.at - left.at);
1009
1358
  }
1010
- /** One file's history, oldest first, numbered so a reader can name a version. */
1011
- function foldVersions(events, filePath) {
1012
- return events.filter((event) => event.path === filePath).sort((left, right) => left.at - right.at).map((event, offset) => {
1013
- const version = {
1014
- index: offset + 1,
1015
- tool: event.tool,
1016
- at: event.at,
1017
- origin: event.version === 2 ? event.origin : "scan"
1018
- };
1019
- if (event.version !== 2) return version;
1020
- return {
1021
- ...version,
1022
- ...event.before === void 0 ? {} : { before: event.before },
1023
- ...event.after === void 0 ? {} : { after: event.after },
1024
- ...event.additions === void 0 ? {} : { additions: event.additions },
1025
- ...event.removals === void 0 ? {} : { removals: event.removals },
1026
- ...event.verified === true ? { verified: true } : {},
1027
- ...event.created === true ? { created: true } : {}
1028
- };
1359
+ function createFileEditStorage(fileSystem) {
1360
+ return {
1361
+ paths: (environment) => new FileEditPaths(environment),
1362
+ timeline: () => new TimelineStore(),
1363
+ snapshots: () => new NodeSnapshotStoreAdapter(),
1364
+ manifests: () => new NodeTreeManifestAdapter(),
1365
+ git: () => new NodeGitStatusAdapter(),
1366
+ workingFiles: () => new NodeWorkingFiles(),
1367
+ presenceFiles: () => nodePresenceFiles,
1368
+ sessionFiles: readSessionFiles,
1369
+ readableRoots: ({ cwd, environment, homeDirectory }) => () => plansRoots(fileSystem, cwd, environment, homeDirectory),
1370
+ sweepAbandoned: (directory, keep) => sweepSessionState({
1371
+ directory,
1372
+ keep
1373
+ }),
1374
+ clearOnClose: true
1375
+ };
1376
+ }
1377
+ //#endregion
1378
+ //#region src/services/editPresence/index.ts
1379
+ const PATH_TOOLS = /* @__PURE__ */ new Set([
1380
+ "read",
1381
+ "edit",
1382
+ "write"
1383
+ ]);
1384
+ const EDIT_TOOLS = /* @__PURE__ */ new Set(["edit", "write"]);
1385
+ const MAX_GREP_FILES = 50;
1386
+ const MAX_NOTE_LINES = 10;
1387
+ const MINUTE_MS = 6e4;
1388
+ const SHORT_ID_LENGTH = 8;
1389
+ /** Pi's built-in grep prints match rows as `relative/path:line: text`. */
1390
+ const PI_GREP_ROW = /^(.+?):(\d+): /u;
1391
+ function stringArg(args, key) {
1392
+ if (typeof args !== "object" || args === null) return void 0;
1393
+ const value = args[key];
1394
+ return typeof value === "string" && value.length > 0 ? value : void 0;
1395
+ }
1396
+ function textOf(content) {
1397
+ return content.map((part) => part.type === "text" && "text" in part && typeof part.text === "string" ? part.text : "").join("\n");
1398
+ }
1399
+ async function grepFiles(call, files) {
1400
+ const lines = textOf(call.content).split("\n");
1401
+ const headers = lines.flatMap((line) => {
1402
+ const header = (0, _agimon_ai_po_hashline.parseFileHeader)(line);
1403
+ return header === void 0 ? [] : [(0, _agimon_ai_po_hashline_files.resolveInputPath)(header.path, call.cwd)];
1029
1404
  });
1405
+ if (headers.length > 0) return [...new Set(headers)].slice(0, MAX_GREP_FILES);
1406
+ const rows = lines.flatMap((line) => {
1407
+ const match = PI_GREP_ROW.exec(line)?.[1];
1408
+ return match === void 0 ? [] : [match];
1409
+ });
1410
+ if (rows.length === 0) return [];
1411
+ const searchPath = (0, _agimon_ai_po_hashline_files.resolveInputPath)(stringArg(call.args, "path") ?? ".", call.cwd);
1412
+ if (await files.isFile(searchPath)) return [searchPath];
1413
+ return [...new Set(rows.map((row) => node_path.default.resolve(searchPath, row)))].slice(0, MAX_GREP_FILES);
1414
+ }
1415
+ async function touchedFiles(call, files) {
1416
+ if (PATH_TOOLS.has(call.toolName)) {
1417
+ const input = stringArg(call.args, "path");
1418
+ return input === void 0 ? [] : [await (0, _agimon_ai_po_hashline_files.resolveReadInputPath)(input, call.cwd)];
1419
+ }
1420
+ return call.toolName === "grep" ? grepFiles(call, files) : [];
1421
+ }
1422
+ function ago(elapsed) {
1423
+ const minutes = Math.floor(elapsed / MINUTE_MS);
1424
+ return minutes < 1 ? "under 1m ago" : `${minutes}m ago`;
1425
+ }
1426
+ function renderNote(lines) {
1427
+ const shown = lines.slice(0, MAX_NOTE_LINES);
1428
+ const more = lines.length - shown.length;
1429
+ return [
1430
+ PRESENCE_NOTE_TITLE,
1431
+ ...shown,
1432
+ ...more > 0 ? [`- and ${more} more`] : [],
1433
+ PRESENCE_NOTE_GUIDANCE
1434
+ ].join("\n");
1030
1435
  }
1031
1436
  /**
1032
- * Whether a file can be diffed at all: some version has to give the diff a
1033
- * starting point. A captured baseline is one. So is a version that created the
1034
- * file, whose starting point is nothing at all.
1035
- *
1036
- * A file only ever seen after the fact, which is every file a bash script
1037
- * wrote, still cannot be.
1437
+ * Notes live editors of the files a tool call touched, then records the caller's own successful edit.
1438
+ * Returns the content with one note appended, or undefined when there is nothing to add, so callers
1439
+ * never rewrite a result needlessly.
1038
1440
  */
1039
- function isDiffable(versions) {
1040
- return versions.some((version) => version.before !== void 0 || version.created === true);
1441
+ async function observePresence(presence, agent, call, now = Date.now(), files = createFileEditStorage().presenceFiles()) {
1442
+ const recording = EDIT_TOOLS.has(call.toolName) && !call.isError;
1443
+ const lines = [];
1444
+ for (const file of await touchedFiles(call, files)) {
1445
+ const real = await files.realpath(file);
1446
+ if (real === void 0) continue;
1447
+ const others = presence.touch(real, agent);
1448
+ let bytes;
1449
+ if (others.length > 0) {
1450
+ bytes = await files.read(real);
1451
+ const current = bytes === void 0 ? void 0 : (0, _agimon_ai_po_hashline_files.computeFileTag)(bytes);
1452
+ const shown = (0, _agimon_ai_po_hashline_files.displayPath)(file, call.cwd);
1453
+ for (const entry of others) {
1454
+ const state = entry.tag === current ? "unchanged" : "changed";
1455
+ lines.push(`- ${shown}: ${entry.agent.label()}, ${ago(now - entry.at)}, file ${state} since their edit.`);
1456
+ }
1457
+ }
1458
+ if (recording) {
1459
+ bytes ??= await files.read(real);
1460
+ if (bytes !== void 0) presence.record(real, {
1461
+ agent,
1462
+ tag: (0, _agimon_ai_po_hashline_files.computeFileTag)(bytes),
1463
+ at: now
1464
+ });
1465
+ }
1466
+ }
1467
+ if (lines.length === 0) return void 0;
1468
+ return [...call.content, {
1469
+ type: "text",
1470
+ text: renderNote(lines)
1471
+ }];
1041
1472
  }
1042
- /** The oldest captured baseline for a file, which is what the whole-session diff starts from. */
1043
- function baselineOf(versions) {
1044
- return versions.find((version) => version.before !== void 0)?.before;
1473
+ /** Edit presence for one hub session and the in-process children it spawns. */
1474
+ function createSessionPresence(options) {
1475
+ const { sessionId, presence } = options;
1476
+ const sessionAgent = {
1477
+ key: `session:${sessionId}`,
1478
+ label: () => `session ${sessionId}${options.workflowStep ? " (workflow step)" : ""}`,
1479
+ contact: sessionId,
1480
+ isLive: options.isLive
1481
+ };
1482
+ const safely = async (work) => {
1483
+ try {
1484
+ return await work();
1485
+ } catch (error) {
1486
+ options.onError?.(error);
1487
+ return;
1488
+ }
1489
+ };
1490
+ return {
1491
+ operationAfter: {
1492
+ event: "operation_after",
1493
+ async handle(event, execution) {
1494
+ if (execution.sessionId !== sessionId || event.outcome !== "executed") return;
1495
+ const direct = event.operation.kind === "tool";
1496
+ const name = event.operation.name;
1497
+ const fsWrite = event.operation.kind === "codemode" && [
1498
+ "fs.writeFile",
1499
+ "fs.appendFile",
1500
+ "fs.copyFile",
1501
+ "fs.rename"
1502
+ ].includes(name);
1503
+ const result = event.result;
1504
+ if (!direct && !fsWrite) return;
1505
+ const content = result && typeof result === "object" && "content" in result && Array.isArray(result.content) ? result.content : [];
1506
+ const toolName = fsWrite ? "write" : name;
1507
+ const args = fsWrite ? { path: event.args[["fs.copyFile", "fs.rename"].includes(name) ? 1 : 0] } : event.args[0];
1508
+ const next = await safely(() => observePresence(presence, sessionAgent, {
1509
+ toolName,
1510
+ args,
1511
+ content,
1512
+ isError: !!(result && typeof result === "object" && "isError" in result && result.isError),
1513
+ cwd: execution.cwd
1514
+ }, void 0, options.files));
1515
+ if (next === void 0) return void 0;
1516
+ return direct && result && typeof result === "object" ? { result: {
1517
+ ...result,
1518
+ content: next
1519
+ } } : { notes: next.slice(content.length).flatMap((part) => "text" in part && typeof part.text === "string" ? [part.text] : []) };
1520
+ }
1521
+ },
1522
+ childHooks: { bind(scope) {
1523
+ const { runId, parentSessionId, agent } = scope.request;
1524
+ const child = {
1525
+ key: `run:${runId}`,
1526
+ label: () => `${options.labelFor(runId) ?? `${agent} (run ${runId.slice(0, SHORT_ID_LENGTH)})`} (subagent of session ${parentSessionId})`,
1527
+ contact: parentSessionId,
1528
+ isLive: () => !scope.signal.aborted
1529
+ };
1530
+ return {
1531
+ beforeTool: () => void 0,
1532
+ async afterTool(event) {
1533
+ const next = await safely(() => observePresence(presence, child, {
1534
+ toolName: event.toolName,
1535
+ args: event.args,
1536
+ content: event.content,
1537
+ isError: event.isError,
1538
+ cwd: scope.request.cwd || options.cwd
1539
+ }, void 0, options.files));
1540
+ return next === void 0 ? void 0 : { content: next };
1541
+ },
1542
+ dispose: async () => presence.forget(child.key)
1543
+ };
1544
+ } },
1545
+ dispose: () => presence.forget(sessionAgent.key)
1546
+ };
1045
1547
  }
1046
1548
  //#endregion
1047
- //#region src/services/timelineStore/index.ts
1048
- const LOCK_RETRY_MS = 25;
1049
- const LOCK_RETRIES = 400;
1549
+ //#region src/services/bashTargets/index.ts
1550
+ const SEPARATOR = ";";
1551
+ /** `>&2` and `2>&1` duplicate a descriptor and name no file. */
1552
+ const DUPLICATE = ">&";
1553
+ /** Words a shell would expand: what they name is unknowable from the text. */
1554
+ const EXPANDS = /[$`*?{}()<>]/u;
1555
+ const WRITE_ARGUMENTS = /* @__PURE__ */ new Set([
1556
+ "tee",
1557
+ "touch",
1558
+ "rm",
1559
+ "truncate"
1560
+ ]);
1561
+ const WRITE_DESTINATION = /* @__PURE__ */ new Set([
1562
+ "cp",
1563
+ "mv",
1564
+ "install"
1565
+ ]);
1566
+ function tokens(command) {
1567
+ const out = [];
1568
+ let word = "";
1569
+ let started = false;
1570
+ let quote;
1571
+ const flush = () => {
1572
+ if (started) out.push({
1573
+ op: false,
1574
+ value: word
1575
+ });
1576
+ word = "";
1577
+ started = false;
1578
+ };
1579
+ for (let index = 0; index < command.length; index += 1) {
1580
+ const character = command[index];
1581
+ const next = command[index + 1];
1582
+ if (quote !== void 0) {
1583
+ if (character === quote) quote = void 0;
1584
+ else if (character === "\\" && quote === "\"" && next !== void 0) word += command[++index];
1585
+ else word += character;
1586
+ } else if (character === "'" || character === "\"") {
1587
+ quote = character;
1588
+ started = true;
1589
+ } else if (character === "\\" && next !== void 0) {
1590
+ word += command[++index];
1591
+ started = true;
1592
+ } else if (character === "&" && next === ">") {
1593
+ flush();
1594
+ word = "&";
1595
+ started = true;
1596
+ } else if (character === ">") {
1597
+ const prefix = started && /^(?:\d|&)$/u.test(word) ? word : "";
1598
+ if (prefix) {
1599
+ word = "";
1600
+ started = false;
1601
+ } else flush();
1602
+ let operator = `${prefix}>`;
1603
+ if (command[index + 1] === ">") operator += command[++index];
1604
+ if (command[index + 1] === "&") {
1605
+ while (/[&\d-]/u.test(command[index + 1] ?? "")) index += 1;
1606
+ operator = DUPLICATE;
1607
+ }
1608
+ out.push({
1609
+ op: true,
1610
+ value: operator
1611
+ });
1612
+ } else if (character === ";" || character === "|" || character === "&" || character === "\n") {
1613
+ flush();
1614
+ if ((character === "&" || character === "|") && (next === character || next === "&")) index += 1;
1615
+ out.push({
1616
+ op: true,
1617
+ value: SEPARATOR
1618
+ });
1619
+ } else if (/\s/u.test(character)) flush();
1620
+ else {
1621
+ word += character;
1622
+ started = true;
1623
+ }
1624
+ }
1625
+ flush();
1626
+ return out;
1627
+ }
1628
+ /** The targets one simple command writes through its arguments. */
1629
+ function argumentTargets(words) {
1630
+ const start = words.findIndex((word) => !/^\w+=/u.test(word));
1631
+ if (start === -1) return [];
1632
+ const program = node_path.default.basename(words[start]);
1633
+ const rest = words.slice(start + 1);
1634
+ const operands = rest.filter((word) => word !== "" && !word.startsWith("-"));
1635
+ if (WRITE_ARGUMENTS.has(program)) return operands;
1636
+ if (WRITE_DESTINATION.has(program)) return operands.length >= 2 ? [operands.at(-1)] : [];
1637
+ if (program === "sed" && rest.some((word) => word.startsWith("-i") || word === "--in-place")) {
1638
+ if (!rest.some((word) => word === "-e" || word === "-f")) return operands.slice(1);
1639
+ return rest.filter((word, index) => word !== "" && !word.startsWith("-") && rest[index - 1] !== "-e" && rest[index - 1] !== "-f");
1640
+ }
1641
+ if (program === "git" && (operands[0] === "checkout" || operands[0] === "restore")) {
1642
+ const separator = rest.indexOf("--");
1643
+ if (separator !== -1) return rest.slice(separator + 1);
1644
+ return operands[0] === "restore" ? operands.slice(1) : [];
1645
+ }
1646
+ return [];
1647
+ }
1648
+ /** Absolute paths of the files `command`, run in `cwd`, names as outputs. */
1649
+ function bashTargets(command, cwd) {
1650
+ const named = /* @__PURE__ */ new Set();
1651
+ const add = (word) => {
1652
+ if (word === "" || word.startsWith("-") || word.startsWith("~") || EXPANDS.test(word)) return;
1653
+ if (word.startsWith("/dev/")) return;
1654
+ named.add(node_path.default.resolve(cwd, word));
1655
+ };
1656
+ let words = [];
1657
+ const list = tokens(command);
1658
+ for (let index = 0; index < list.length; index += 1) {
1659
+ const token = list[index];
1660
+ if (!token.op) words.push(token.value);
1661
+ else if (token.value === SEPARATOR) {
1662
+ argumentTargets(words).forEach(add);
1663
+ words = [];
1664
+ } else if (token.value !== DUPLICATE && list[index + 1]?.op === false) add(list[++index].value);
1665
+ }
1666
+ argumentTargets(words).forEach(add);
1667
+ return [...named];
1668
+ }
1669
+ //#endregion
1670
+ //#region src/services/editTracker/index.ts
1671
+ const EDIT_TOOL = "edit";
1672
+ const WRITE_TOOL = "write";
1673
+ const BASH_TOOL = "bash";
1674
+ /** Code mode scripts can write files like a shell can, so they get the same git comparison. */
1675
+ const EXEC_TOOL = "exec";
1676
+ function objectValue(value, key) {
1677
+ if (!value || typeof value !== "object") return void 0;
1678
+ const found = value[key];
1679
+ return typeof found === "string" ? found : void 0;
1680
+ }
1050
1681
  /**
1051
- * How long a lock file may sit untouched before a waiter treats it as abandoned.
1052
- *
1053
- * An append writes one line, so a holder that has been there for half a minute
1054
- * is a process that died without unlinking. Without this, that one file would
1055
- * block every later append to the same timeline permanently.
1682
+ * How far before a call started a write may claim to have happened and still be
1683
+ * attributed to it. A working tree can sit on a filesystem that stores whole
1684
+ * seconds, which floors a write made just after the call began to a stamp just
1685
+ * before it, and the cost of being generous here is one second of the staleness
1686
+ * this check exists to remove.
1056
1687
  */
1057
- const LOCK_STALE_MS = 3e4;
1058
- function hasCode$1(error, code) {
1059
- return error instanceof Error && "code" in error && error.code === code;
1060
- }
1061
- var TimelineStore = class {
1062
- filePath;
1063
- initialize(filePath) {
1064
- this.filePath = filePath;
1065
- }
1066
- async append(event) {
1067
- await this.withLock(async () => node_fs_promises.default.appendFile(this.requirePath(), `${JSON.stringify(event)}\n`, "utf8"));
1688
+ const MODIFIED_TOLERANCE_MS = 1e3;
1689
+ var EditTracker = class {
1690
+ timeline;
1691
+ snapshots;
1692
+ manifests;
1693
+ pending = /* @__PURE__ */ new Map();
1694
+ /** The files each in-flight bash call named in its text, read before it ran. */
1695
+ named = /* @__PURE__ */ new Map();
1696
+ /** Start time per in-flight bash call, so its end knows what it may claim. */
1697
+ bracketed = /* @__PURE__ */ new Map();
1698
+ /**
1699
+ * The watched files as this tracker last saw them. A bash call compares
1700
+ * against it and then replaces it, so a change made between calls is still
1701
+ * noticed on the next one.
1702
+ */
1703
+ manifest;
1704
+ /**
1705
+ * This package's own storage, which must never be reported. The timeline and
1706
+ * its snapshots can land inside the tree being watched, and recording them
1707
+ * would make every change cause another one.
1708
+ */
1709
+ excluded = [];
1710
+ /**
1711
+ * The project's own ignore rules. A path the project disowns is not worth a
1712
+ * git call, a read, or a stored copy of its content, so it is dropped before
1713
+ * it costs any of them.
1714
+ */
1715
+ isIgnored;
1716
+ /**
1717
+ * The last content hash this session saw per path, from either mechanism.
1718
+ * A candidate whose hash has not moved was touched, not edited.
1719
+ */
1720
+ contents = /* @__PURE__ */ new Map();
1721
+ onChanged;
1722
+ now;
1723
+ git;
1724
+ onScanFailed;
1725
+ /**
1726
+ * The scan deferred by the last bash call. Every bracket joins this chain, so
1727
+ * at most one comparison runs at a time and each one sees the baseline the
1728
+ * previous one left behind.
1729
+ */
1730
+ scanning = Promise.resolve();
1731
+ constructor(timeline, snapshots, manifests, options) {
1732
+ this.timeline = timeline;
1733
+ this.snapshots = snapshots;
1734
+ this.manifests = manifests;
1735
+ this.onChanged = options.onChanged;
1736
+ this.now = options.now ?? Date.now;
1737
+ this.git = options.git;
1738
+ this.onScanFailed = options.onScanFailed;
1068
1739
  }
1069
- async list() {
1070
- return foldEntries(confirmedChanges(await this.events()));
1740
+ /**
1741
+ * Forgets the previous session's tree so a new one does not inherit its
1742
+ * baseline, and takes the paths this session's own bookkeeping occupies.
1743
+ */
1744
+ reset(options = {}) {
1745
+ this.pending.clear();
1746
+ this.named.clear();
1747
+ this.bracketed.clear();
1748
+ this.contents.clear();
1749
+ this.manifest = void 0;
1750
+ this.scanning = Promise.resolve();
1751
+ this.excluded = options.exclude ?? [];
1752
+ this.isIgnored = options.isIgnored;
1071
1753
  }
1072
- async versions(filePath) {
1073
- return foldVersions(confirmedChanges(await this.events()), filePath);
1754
+ /**
1755
+ * Awaits a scan still running in the background. A caller that is about to
1756
+ * clear the timeline needs this, or the scan appends after the clear.
1757
+ */
1758
+ async flush() {
1759
+ await this.scanning;
1074
1760
  }
1075
- async clear() {
1076
- try {
1077
- await node_fs_promises.default.unlink(this.requirePath());
1078
- } catch (error) {
1079
- if (!hasCode$1(error, "ENOENT")) throw error;
1761
+ async start(id, tool, args, cwd) {
1762
+ await this.scanning;
1763
+ if (tool === EDIT_TOOL || tool === WRITE_TOOL) {
1764
+ const supplied = objectValue(args, "path");
1765
+ if (!supplied) return false;
1766
+ this.pending.set(id, await this.prepare(tool, node_path.default.resolve(cwd, supplied)));
1767
+ return true;
1080
1768
  }
1081
- }
1082
- /** Every recorded change, or none at all when the session has not written yet. */
1083
- async events() {
1084
- let content;
1085
- try {
1086
- content = await node_fs_promises.default.readFile(this.requirePath(), "utf8");
1087
- } catch (error) {
1088
- if (hasCode$1(error, "ENOENT")) return [];
1089
- throw error;
1769
+ if (tool !== BASH_TOOL && tool !== EXEC_TOOL) return false;
1770
+ this.bracketed.set(id, this.now());
1771
+ const command = tool === BASH_TOOL ? objectValue(args, "command") : void 0;
1772
+ if (command !== void 0) {
1773
+ const targets = bashTargets(command, cwd).filter((filePath) => this.watched(cwd, filePath));
1774
+ this.named.set(id, await Promise.all(targets.map((filePath) => this.prepare(BASH_TOOL, filePath))));
1090
1775
  }
1091
- return parseTimeline(content, (line) => console.warn(`Ignoring malformed file edit timeline line: ${line.slice(0, 200)}`));
1092
- }
1093
- requirePath() {
1094
- if (!this.filePath) throw new Error("Timeline store is not initialized");
1095
- return this.filePath;
1776
+ this.manifest ??= await this.takeManifest(cwd);
1777
+ return true;
1096
1778
  }
1097
- async withLock(operation) {
1098
- const lockPath = `${this.requirePath()}.lock`;
1099
- const lock = await this.acquire(lockPath);
1100
- try {
1101
- return await operation();
1102
- } finally {
1103
- await lock.close();
1104
- await this.release(lockPath);
1105
- }
1779
+ /**
1780
+ * Reads a named file before the call that may change it. The fingerprint is
1781
+ * the only thing that tells a file being created from one whose content could
1782
+ * not be captured, because a capture answers undefined for either.
1783
+ */
1784
+ async prepare(tool, filePath) {
1785
+ const [before, fingerprint] = await Promise.all([this.snapshots.capture(filePath), this.manifests.fingerprint(filePath)]);
1786
+ return {
1787
+ tool,
1788
+ filePath,
1789
+ before,
1790
+ existed: fingerprint !== void 0
1791
+ };
1106
1792
  }
1107
- /** Waits for the lock file, breaking one an earlier process left behind. */
1108
- async acquire(lockPath) {
1109
- for (let attempt = 0; attempt < LOCK_RETRIES; attempt += 1) try {
1110
- return await node_fs_promises.default.open(lockPath, "wx");
1111
- } catch (error) {
1112
- if (!hasCode$1(error, "EEXIST")) throw error;
1113
- if (await this.breakStale(lockPath)) continue;
1114
- await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS));
1793
+ async end(id, isError, cwd) {
1794
+ const pending = this.pending.get(id);
1795
+ this.pending.delete(id);
1796
+ const startedAt = this.bracketed.get(id);
1797
+ this.bracketed.delete(id);
1798
+ const named = this.named.get(id) ?? [];
1799
+ this.named.delete(id);
1800
+ if (pending) {
1801
+ if (!isError) await this.recordTool(pending);
1802
+ return;
1115
1803
  }
1116
- throw new Error(`Timed out acquiring timeline lock ${lockPath}`);
1804
+ if (startedAt === void 0) return;
1805
+ this.scanning = this.scanning.then(async () => {
1806
+ try {
1807
+ for (const target of named) if (target.existed ? target.before !== void 0 : await this.manifests.fingerprint(target.filePath) !== void 0) await this.recordTool(target);
1808
+ await this.recordScan(cwd, startedAt);
1809
+ } catch (error) {
1810
+ this.onScanFailed(error);
1811
+ }
1812
+ });
1117
1813
  }
1118
- /** Whether the lock is now free to take, having removed it when its holder is gone. */
1119
- async breakStale(lockPath) {
1120
- try {
1121
- const stats = await node_fs_promises.default.stat(lockPath);
1122
- if (Date.now() - stats.mtimeMs < LOCK_STALE_MS) return false;
1123
- await node_fs_promises.default.unlink(lockPath);
1124
- return true;
1125
- } catch (error) {
1126
- if (hasCode$1(error, "ENOENT")) return true;
1127
- throw error;
1128
- }
1814
+ /** A file named before the call, by `edit`, `write` or a bash command's text, read on both sides of it. */
1815
+ async recordTool(pending) {
1816
+ const after = await this.snapshots.capture(pending.filePath);
1817
+ const created = !pending.existed;
1818
+ const counts = await this.countChanges(pending.before, after, created);
1819
+ if (after !== void 0) this.contents.set(pending.filePath, after);
1820
+ await this.append({
1821
+ version: 2,
1822
+ path: pending.filePath,
1823
+ tool: pending.tool,
1824
+ at: this.now(),
1825
+ origin: "tool",
1826
+ ...pending.before === void 0 ? {} : { before: pending.before },
1827
+ ...after === void 0 ? {} : { after },
1828
+ ...created ? { created: true } : {},
1829
+ ...counts
1830
+ });
1831
+ await this.remember(pending.filePath);
1129
1832
  }
1130
- async release(lockPath) {
1131
- try {
1132
- await node_fs_promises.default.unlink(lockPath);
1133
- } catch (error) {
1134
- if (!hasCode$1(error, "ENOENT")) console.warn(`Could not remove timeline lock: ${String(error)}`);
1135
- }
1833
+ /**
1834
+ * Whether a path is worth watching: inside the session's tree, outside this
1835
+ * package's own storage and the directories builds and tooling fill, and not
1836
+ * disowned by the project.
1837
+ */
1838
+ watched(cwd, filePath) {
1839
+ const relative = node_path.default.relative(cwd, filePath);
1840
+ if (relative === "" || relative.startsWith("..") || node_path.default.isAbsolute(relative)) return false;
1841
+ if (this.excluded.some((entry) => filePath === entry || filePath.startsWith(`${entry}${node_path.default.sep}`))) return false;
1842
+ if (relative.split(node_path.default.sep).some((segment) => IGNORED_DIRECTORIES.has(segment))) return false;
1843
+ return this.isIgnored === void 0 || !this.isIgnored(filePath);
1136
1844
  }
1137
- };
1138
- //#endregion
1139
- //#region src/services/treeManifest/index.ts
1140
- /**
1141
- * Take a bounded manifest of a working tree and report which files moved
1142
- * between two of them.
1143
- *
1144
- * One technology per adapter. This is where node enters the package; the
1145
- * services that depend on the capability keep importing the port.
1146
- *
1147
- * The caps are the whole design. An unbounded walk of a working directory is
1148
- * dominated by dependency and build trees, which change constantly and tell a
1149
- * reader nothing, so those are skipped by name; what remains is capped on both
1150
- * entries and depth so the walk stays a fixed cost rather than a function of
1151
- * how large the checkout grew. Hitting a cap is reported, never hidden.
1152
- */
1153
- /**
1154
- * Directories a working tree fills with output nobody wants listed as an edit.
1155
- *
1156
- * Two kinds live here. Most are the build and dependency trees every checkout
1157
- * grows. The rest are where tooling, including this agent's own, writes while a
1158
- * session runs: a telemetry log under `logs`, a test run's artifacts under
1159
- * `test-results` and `playwright-report`, scratch space under `tmp`, and agent
1160
- * state under `.pi`. Those are skipped by construction rather than judged file
1161
- * by file, because a walk that enters them reports the session watching itself.
1162
- */
1163
- const IGNORED_DIRECTORIES = /* @__PURE__ */ new Set([
1164
- ".git",
1165
- ".hg",
1166
- ".svn",
1167
- ".cache",
1168
- ".gradle",
1169
- ".next",
1170
- ".nuxt",
1171
- ".nx",
1172
- ".pi",
1173
- ".pnpm-store",
1174
- ".turbo",
1175
- ".venv",
1176
- "__pycache__",
1177
- "build",
1178
- "coverage",
1179
- "dist",
1180
- "logs",
1181
- "node_modules",
1182
- "out",
1183
- "playwright-report",
1184
- "target",
1185
- "test-results",
1186
- "tmp",
1187
- "vendor",
1188
- "venv"
1189
- ]);
1190
- /**
1191
- * How a file is summarised. Size and modification time are what a walk can read
1192
- * cheaply for thousands of files; hashing every one of them would turn a scan
1193
- * into a read of the whole tree.
1194
- */
1195
- function fingerprintOf(size, modifiedMs) {
1196
- return `${size}:${modifiedMs}`;
1197
- }
1198
- /** The size half of a fingerprint, which only the adapter that wrote it can read. */
1199
- function sizeOf(fingerprint) {
1200
- const separator = fingerprint.indexOf(":");
1201
- return separator === -1 ? fingerprint : fingerprint.slice(0, separator);
1202
- }
1203
- var NodeTreeManifestAdapter = class {
1204
- maxEntries;
1205
- maxDepth;
1206
- ignored;
1207
- constructor(options = {}) {
1208
- this.maxEntries = options.maxEntries ?? 2e4;
1209
- this.maxDepth = options.maxDepth ?? 12;
1210
- this.ignored = options.ignoredDirectories ?? IGNORED_DIRECTORIES;
1211
- }
1212
- async take(root, exclude = []) {
1845
+ /**
1846
+ * Fingerprints what git calls dirty under `cwd`, plus the paths already being
1847
+ * followed, so a file reverted to clean still shows as moved. Outside a
1848
+ * repository it holds only what it carries.
1849
+ */
1850
+ async takeManifest(cwd, carried = []) {
1851
+ const paths = new Set(carried);
1852
+ for (const filePath of await this.git?.dirty(cwd) ?? []) if (this.watched(cwd, filePath)) paths.add(filePath);
1213
1853
  const entries = /* @__PURE__ */ new Map();
1214
- const skipped = new Set(exclude.map((entry) => node_path.default.resolve(entry)));
1215
- return {
1216
- entries,
1217
- truncated: await this.walk(root, 0, entries, skipped)
1218
- };
1854
+ for (const filePath of paths) {
1855
+ const fingerprint = await this.manifests.fingerprint(filePath);
1856
+ if (fingerprint !== void 0) entries.set(filePath, fingerprint);
1857
+ }
1858
+ return { entries };
1219
1859
  }
1220
- async fingerprint(filePath) {
1221
- try {
1222
- const stat = await node_fs_promises.default.stat(filePath);
1223
- return stat.isFile() ? fingerprintOf(stat.size, stat.mtimeMs) : void 0;
1224
- } catch {
1225
- return;
1860
+ /** Whatever a bash call actually edited, however the command wrote it. */
1861
+ async recordScan(cwd, startedAt) {
1862
+ const before = this.manifest;
1863
+ if (before === void 0) return;
1864
+ const after = await this.takeManifest(cwd, before.entries.keys());
1865
+ this.manifest = after;
1866
+ const disowned = this.isIgnored;
1867
+ const named = this.manifests.changed(before, after).filter((filePath) => disowned === void 0 || !disowned(filePath));
1868
+ const candidates = await this.writtenDuring(named, startedAt);
1869
+ if (candidates.length === 0) return;
1870
+ const unchanged = await this.unchangedInGit(cwd, candidates);
1871
+ for (const filePath of candidates) {
1872
+ const known = this.contents.get(filePath);
1873
+ if (known === void 0 && unchanged.has(filePath)) continue;
1874
+ const beforePrint = before.entries.get(filePath);
1875
+ const afterPrint = after.entries.get(filePath);
1876
+ const captured = afterPrint === void 0 ? void 0 : await this.snapshots.capture(filePath);
1877
+ if (captured !== void 0) this.contents.set(filePath, captured);
1878
+ if (captured !== void 0 && captured === known) continue;
1879
+ const proven = beforePrint === void 0 || afterPrint === void 0 || this.manifests.sizeChanged(beforePrint, afterPrint) || known !== void 0 && captured !== void 0 && captured !== known;
1880
+ await this.append({
1881
+ version: 2,
1882
+ path: filePath,
1883
+ tool: BASH_TOOL,
1884
+ at: this.now(),
1885
+ origin: "scan",
1886
+ ...proven ? { verified: true } : {},
1887
+ ...captured === void 0 ? {} : { after: captured }
1888
+ });
1226
1889
  }
1227
1890
  }
1228
- async modifiedAt(filePath) {
1229
- try {
1230
- const stat = await node_fs_promises.default.stat(filePath);
1231
- return stat.isFile() ? stat.mtimeMs : void 0;
1232
- } catch {
1233
- return;
1891
+ /**
1892
+ * Narrows candidates to the ones that could have been written by the call
1893
+ * being closed.
1894
+ *
1895
+ * This is what keeps a working tree that was already dirty out of the list. A
1896
+ * file whose bytes were last written before the call began was differed by
1897
+ * something else, whatever moved its fingerprint. A file that is no longer
1898
+ * there has no time to read and a delete is a change the call may well have
1899
+ * made, so it stays a candidate.
1900
+ */
1901
+ async writtenDuring(candidates, startedAt) {
1902
+ const floor = startedAt - MODIFIED_TOLERANCE_MS;
1903
+ const written = [];
1904
+ for (const filePath of candidates) {
1905
+ const modifiedAt = await this.manifests.modifiedAt(filePath);
1906
+ if (modifiedAt === void 0 || modifiedAt >= floor) written.push(filePath);
1234
1907
  }
1908
+ return written;
1235
1909
  }
1236
- changed(before, after) {
1237
- const moved = /* @__PURE__ */ new Set();
1238
- for (const [filePath, fingerprint] of after.entries) if (before.entries.get(filePath) !== fingerprint) moved.add(filePath);
1239
- for (const filePath of before.entries.keys()) if (!after.entries.has(filePath)) moved.add(filePath);
1240
- return [...moved].sort();
1241
- }
1242
- sizeChanged(before, after) {
1243
- if (before === void 0 || after === void 0) return false;
1244
- return sizeOf(before) !== sizeOf(after);
1910
+ /** Which candidates git tracks and reports as untouched; empty when it cannot say. */
1911
+ async unchangedInGit(cwd, candidates) {
1912
+ const unseen = candidates.filter((filePath) => !this.contents.has(filePath));
1913
+ if (this.git === void 0 || unseen.length === 0) return /* @__PURE__ */ new Set();
1914
+ return this.git.unchanged(cwd, unseen);
1245
1915
  }
1246
- /** Fills `entries` depth-first and answers whether a cap cut the walk short. */
1247
- async walk(directory, depth, entries, skipped) {
1248
- if (depth > this.maxDepth) return true;
1249
- let listing;
1250
- try {
1251
- listing = await node_fs_promises.default.readdir(directory, { withFileTypes: true });
1252
- } catch {
1253
- return false;
1916
+ /** How many lines moved, when there is enough captured content to say. */
1917
+ async countChanges(before, after, created) {
1918
+ if (after === void 0) return {};
1919
+ if (before === void 0) {
1920
+ if (!created) return {};
1921
+ const createdText = await this.snapshots.read(after);
1922
+ if (createdText === void 0) return {};
1923
+ const fresh = lineDiffFromEmpty(createdText);
1924
+ return {
1925
+ additions: fresh.additions,
1926
+ removals: fresh.removals
1927
+ };
1254
1928
  }
1255
- let truncated = false;
1256
- for (const entry of listing) {
1257
- if (entries.size >= this.maxEntries) return true;
1258
- const entryPath = node_path.default.join(directory, entry.name);
1259
- if (skipped.has(entryPath)) continue;
1260
- if (entry.isSymbolicLink()) continue;
1261
- if (entry.isDirectory()) {
1262
- if (this.ignored.has(entry.name)) continue;
1263
- truncated = await this.walk(entryPath, depth + 1, entries, skipped) || truncated;
1264
- continue;
1265
- }
1266
- if (!entry.isFile()) continue;
1267
- try {
1268
- const stat = await node_fs_promises.default.stat(entryPath);
1269
- entries.set(entryPath, fingerprintOf(stat.size, stat.mtimeMs));
1270
- } catch {}
1929
+ if (before === after) return {
1930
+ additions: 0,
1931
+ removals: 0
1932
+ };
1933
+ const [beforeText, afterText] = await Promise.all([this.snapshots.read(before), this.snapshots.read(after)]);
1934
+ if (beforeText === void 0 || afterText === void 0) return {};
1935
+ const diff = lineDiff(beforeText, afterText);
1936
+ return {
1937
+ additions: diff.additions,
1938
+ removals: diff.removals
1939
+ };
1940
+ }
1941
+ /** Records the change unless it turned out to be no change at all. */
1942
+ async append(event) {
1943
+ if (event.before !== void 0 && event.before === event.after) return;
1944
+ await this.timeline.append(event);
1945
+ if (event.after !== void 0 && (event.origin === "tool" || event.verified)) try {
1946
+ await this.onChanged?.([event.path]);
1947
+ } catch (error) {
1948
+ this.onScanFailed(error);
1271
1949
  }
1272
- return truncated;
1950
+ }
1951
+ /**
1952
+ * Folds a path the tool layer just handled into the tracked manifest, so the
1953
+ * next bash comparison sees it as already accounted for.
1954
+ *
1955
+ * The fingerprint has to be the one a comparison would read, not a stand-in, or the
1956
+ * next comparison reports the file again under bash and every tool edit is
1957
+ * recorded twice.
1958
+ */
1959
+ async remember(filePath) {
1960
+ if (this.manifest === void 0) return;
1961
+ const entries = new Map(this.manifest.entries);
1962
+ const fingerprint = await this.manifests.fingerprint(filePath);
1963
+ if (fingerprint === void 0) entries.delete(filePath);
1964
+ else entries.set(filePath, fingerprint);
1965
+ this.manifest = { entries };
1273
1966
  }
1274
1967
  };
1275
1968
  //#endregion
1276
- //#region src/types/webFiles.ts
1277
- /** The frame type the hub publishes and the web plugin claims; declared in the poWeb block too. */
1278
- const filesChannelType = "file_edits";
1279
- /** Footer status key whose presence shows the activity group; the extension publishes it. */
1280
- const filesStatusKey = "po-file-edit-files";
1281
- //#endregion
1282
1969
  //#region src/types/apiRoutes.ts
1283
1970
  /**
1284
1971
  * This package's routes, as data.
@@ -1328,225 +2015,51 @@ const routes = {
1328
2015
  path: "/file",
1329
2016
  raw: true,
1330
2017
  query: ["path"],
1331
- host: true
1332
- }
1333
- };
1334
- //#endregion
1335
- //#region src/types/fileEditsApi.ts
1336
- /**
1337
- * The wire vocabulary this package's API shares with whatever calls it.
1338
- *
1339
- * It lives under src/types because that is the one server root a browser
1340
- * bundle may read: the cockpit plugin builds its URLs from these and the
1341
- * routes answer them, so neither half can drift from the other.
1342
- *
1343
- * Routes live in `./apiRoutes`, which the contract, the Hono app and the
1344
- * generated client all read. This file holds the shapes that travel over them.
1345
- *
1346
- * Opening a changed file wants its whole history at once, so `detail` answers
1347
- * in one round trip rather than making the page stitch three reads together;
1348
- * `content` takes the manual save back; `preview` reads a file the session
1349
- * never changed, which has no history to answer with.
1350
- */
1351
- /** Where a host mounts this package's API; the segment after /api/plugins/. */
1352
- const API_BASE_PATH = "file-edits";
1353
- /** Query parameter naming the file a request is about. */
1354
- const PATH_QUERY_PARAM = "path";
1355
- //#endregion
1356
- //#region src/services/fileEditsApi/index.ts
1357
- /**
1358
- * This package's HTTP surface: one file's history, and the manual save.
1359
- *
1360
- * Routes are relative to the mount its host gives it, so nothing here repeats
1361
- * where it was mounted. The host is one session's own server, which is what
1362
- * makes the session id and working directory available without the page
1363
- * supplying either: a page names a file, never a session's private paths.
1364
- *
1365
- * The detail route answers everything a reader needs to open a changed file,
1366
- * because splitting it would make the page stitch three responses together for
1367
- * one click. The save route is the only mutation, and it refuses unless the
1368
- * reader proves they were looking at the content that is still on disk. The
1369
- * preview route is the read-only way in to a file the session never changed,
1370
- * bounded by the working directory instead of by the timeline.
1371
- */
1372
- /** Past this, the working view reports the file rather than carrying it. */
1373
- const MAX_WORKING_BYTES = 1048576;
1374
- const BINARY_SAMPLE_BYTES = 8192;
1375
- const NO_BASELINE_NOTE = "changed by a command, so no baseline was captured; showing the file as it stands";
1376
- /**
1377
- * A change the tool layer named but never captured content for. That is what
1378
- * every record written before this package learned to snapshot looks like, and
1379
- * calling those "changed by a command" would be wrong: the tool is right there
1380
- * in the record.
1381
- */
1382
- const NO_SNAPSHOT_NOTE = "recorded before this session began capturing content, so there is no diff for it";
1383
- const NO_AFTER_NOTE = "the new content could not be captured: the file is binary or past the size cap";
1384
- const NO_BEFORE_NOTE = "the previous content could not be captured: it was binary or past the size cap";
1385
- const APPROXIMATE_NOTE = "the changed region was too large to match line by line";
1386
- function hashOf(content) {
1387
- return (0, node_crypto.createHash)("sha256").update(content, "utf8").digest("hex");
1388
- }
1389
- function hasCode(error, code) {
1390
- return error instanceof Error && "code" in error && error.code === code;
1391
- }
1392
- function describe(error) {
1393
- return error instanceof Error ? error.message : String(error);
1394
- }
1395
- /** Reads the file as the source view will show it, or says why it cannot. */
1396
- async function readWorking(filePath) {
1397
- let raw;
1398
- try {
1399
- raw = await node_fs_promises.default.readFile(filePath);
1400
- } catch {
1401
- return {
1402
- content: "",
1403
- hash: "",
1404
- unavailable: true,
1405
- reason: "the file no longer exists"
1406
- };
1407
- }
1408
- if (raw.byteLength > 1048576) return {
1409
- content: "",
1410
- hash: "",
1411
- unavailable: true,
1412
- reason: `the file is larger than ${MAX_WORKING_BYTES} bytes`
1413
- };
1414
- if (raw.subarray(0, BINARY_SAMPLE_BYTES).includes(0)) return {
1415
- content: "",
1416
- hash: "",
1417
- unavailable: true,
1418
- reason: "the file is binary"
1419
- };
1420
- const content = raw.toString("utf8");
1421
- return {
1422
- content,
1423
- hash: hashOf(content),
1424
- unavailable: false
1425
- };
1426
- }
1427
- function isInside(root, candidate) {
1428
- return candidate === root || candidate.startsWith(`${root}${node_path.default.sep}`);
1429
- }
1430
- /**
1431
- * The same containment check after symlinks are followed. A path that does not
1432
- * exist yet resolves to nothing, and there is nothing to hand out, so it
1433
- * passes and the read below reports it missing.
1434
- */
1435
- async function isRealPathInside(root, candidate) {
1436
- let realRoot;
1437
- let real;
1438
- try {
1439
- realRoot = await node_fs_promises.default.realpath(root);
1440
- real = await node_fs_promises.default.realpath(candidate);
1441
- } catch (error) {
1442
- return hasCode(error, "ENOENT");
1443
- }
1444
- return isInside(realRoot, real);
1445
- }
1446
- /**
1447
- * One recorded change as the page renders it. A change with both sides captured
1448
- * carries its own diff; one without says why, rather than showing nothing.
1449
- *
1450
- * A file this session created counts as captured on both sides. Its baseline is
1451
- * empty rather than missing, so the whole file reads as arriving at once, which
1452
- * is exactly what happened.
1453
- */
1454
- async function toVersionView(version, snapshots) {
1455
- const view = {
1456
- index: version.index,
1457
- tool: version.tool,
1458
- at: version.at,
1459
- origin: version.origin,
1460
- additions: version.additions ?? 0,
1461
- removals: version.removals ?? 0
1462
- };
1463
- const createdHere = version.before === void 0 && version.created === true;
1464
- if (version.after === void 0 || version.before === void 0 && !createdHere) {
1465
- if (version.origin === "tool") return {
1466
- ...view,
1467
- note: version.after === void 0 ? NO_AFTER_NOTE : NO_BEFORE_NOTE
1468
- };
1469
- return {
1470
- ...view,
1471
- note: version.tool === "bash" ? NO_BASELINE_NOTE : NO_SNAPSHOT_NOTE
1472
- };
1473
- }
1474
- const after = await snapshots.read(version.after);
1475
- if (after === void 0) return {
1476
- ...view,
1477
- note: "the content behind this change is no longer held"
1478
- };
1479
- if (version.before === void 0) {
1480
- const fresh = lineDiffFromEmpty(after);
1481
- return {
1482
- ...view,
1483
- additions: fresh.additions,
1484
- removals: fresh.removals,
1485
- hunks: fresh.hunks,
1486
- ...fresh.approximate ? { note: APPROXIMATE_NOTE } : {}
1487
- };
1488
- }
1489
- const before = await snapshots.read(version.before);
1490
- if (before === void 0) return {
1491
- ...view,
1492
- note: "the content behind this change is no longer held"
1493
- };
1494
- const diff = lineDiff(before, after);
1495
- return {
1496
- ...view,
1497
- additions: diff.additions,
1498
- removals: diff.removals,
1499
- hunks: diff.hunks,
1500
- ...diff.approximate ? { note: APPROXIMATE_NOTE } : {}
1501
- };
1502
- }
1503
- /** Everything the session did to the file: its oldest baseline against what is on disk now. */
1504
- async function toCumulativeView(versions, working, snapshots) {
1505
- const createdHere = versions[0]?.created === true;
1506
- const baseline = baselineOf(versions);
1507
- if (!createdHere && baseline === void 0) return {
1508
- additions: 0,
1509
- removals: 0,
1510
- note: versions[0]?.origin === "tool" ? NO_BEFORE_NOTE : NO_BASELINE_NOTE
1511
- };
1512
- if (working.unavailable) return {
1513
- additions: 0,
1514
- removals: 0,
1515
- note: working.reason ?? "the file cannot be read"
1516
- };
1517
- if (createdHere || baseline === void 0) {
1518
- const fresh = lineDiffFromEmpty(working.content);
1519
- return {
1520
- additions: fresh.additions,
1521
- removals: fresh.removals,
1522
- hunks: fresh.hunks,
1523
- ...fresh.approximate ? { note: APPROXIMATE_NOTE } : {}
1524
- };
1525
- }
1526
- const before = await snapshots.read(baseline);
1527
- if (before === void 0) return {
1528
- additions: 0,
1529
- removals: 0,
1530
- note: "the content this session started from is no longer held"
1531
- };
1532
- const diff = lineDiff(before, working.content);
1533
- return {
1534
- additions: diff.additions,
1535
- removals: diff.removals,
1536
- hunks: diff.hunks,
1537
- ...diff.approximate ? { note: APPROXIMATE_NOTE } : {}
1538
- };
1539
- }
2018
+ host: true
2019
+ }
2020
+ };
2021
+ //#endregion
2022
+ //#region src/types/fileEditsApi.ts
2023
+ /**
2024
+ * The wire vocabulary this package's API shares with whatever calls it.
2025
+ *
2026
+ * It lives under src/types because that is the one server root a browser
2027
+ * bundle may read: the cockpit plugin builds its URLs from these and the
2028
+ * routes answer them, so neither half can drift from the other.
2029
+ *
2030
+ * Routes live in `./apiRoutes`, which the contract, the Hono app and the
2031
+ * generated client all read. This file holds the shapes that travel over them.
2032
+ *
2033
+ * Opening a changed file wants its whole history at once, so `detail` answers
2034
+ * in one round trip rather than making the page stitch three reads together;
2035
+ * `content` takes the manual save back; `preview` reads a file the session
2036
+ * never changed, which has no history to answer with.
2037
+ */
2038
+ /** Where a host mounts this package's API; the segment after /api/plugins/. */
2039
+ const API_BASE_PATH = "file-edits";
2040
+ /** Query parameter naming the file a request is about. */
2041
+ const PATH_QUERY_PARAM = "path";
2042
+ //#endregion
2043
+ //#region src/services/fileEditsApi/index.ts
1540
2044
  function createFileEditsApi(options = {}) {
1541
- const timeline = options.timeline ?? new TimelineStore();
1542
- const snapshots = options.snapshots ?? new NodeSnapshotStoreAdapter();
1543
- const paths = options.paths ?? new FileEditPaths();
2045
+ const storage = options.storage ?? createFileEditStorage();
2046
+ const timeline = options.timeline ?? storage.timeline();
2047
+ const snapshots = options.snapshots ?? storage.snapshots();
2048
+ const paths = options.paths ?? storage.paths();
2049
+ const files = options.files ?? storage.workingFiles();
1544
2050
  const cwd = options.cwd ?? "";
1545
2051
  const app = new hono.Hono();
1546
2052
  if (options.sessionId !== void 0 && cwd !== "") {
1547
2053
  const sessionKey = paths.sessionKey(options.sessionId);
1548
- if (options.timeline === void 0) timeline.initialize(paths.timelinePath(cwd, sessionKey));
1549
- if (options.snapshots === void 0) snapshots.initialize(paths.snapshotsPath(cwd, sessionKey));
2054
+ let initializing;
2055
+ app.use(async (_context, next) => {
2056
+ initializing ??= (async () => {
2057
+ if (options.timeline === void 0) timeline.initialize(await paths.timelinePath(cwd, sessionKey));
2058
+ if (options.snapshots === void 0) snapshots.initialize(await paths.snapshotsPath(cwd, sessionKey));
2059
+ })();
2060
+ await initializing;
2061
+ await next();
2062
+ });
1550
2063
  }
1551
2064
  /**
1552
2065
  * The file a request names, rejected unless this session actually recorded a
@@ -1562,13 +2075,13 @@ function createFileEditsApi(options = {}) {
1562
2075
  const isInsideSession = async (filePath) => {
1563
2076
  if (cwd === "") return false;
1564
2077
  const root = node_path.default.resolve(cwd);
1565
- return isInside(root, filePath) && await isRealPathInside(root, filePath);
2078
+ return isInside(root, filePath) && await files.isRealPathInside(root, filePath);
1566
2079
  };
1567
2080
  /** The Po-owned folder holding the file, checked the same two ways as the working directory. */
1568
2081
  const readableRootOf = async (filePath) => {
1569
- for (const root of options.readableRoots?.() ?? []) {
2082
+ for (const root of await options.readableRoots?.() ?? []) {
1570
2083
  const resolved = node_path.default.resolve(root);
1571
- if (isInside(resolved, filePath) && await isRealPathInside(resolved, filePath)) return resolved;
2084
+ if (isInside(resolved, filePath) && await files.isRealPathInside(resolved, filePath)) return resolved;
1572
2085
  }
1573
2086
  };
1574
2087
  app.get(routes.detail.path, async (context) => {
@@ -1576,7 +2089,8 @@ function createFileEditsApi(options = {}) {
1576
2089
  const versions = await recordedVersions(requested);
1577
2090
  if (versions === void 0 || requested === void 0) return context.json({ error: "This session recorded no changes to that file." }, 404);
1578
2091
  const filePath = node_path.default.resolve(cwd, requested);
1579
- const working = await readWorking(filePath);
2092
+ const allowedRoot = cwd !== "" && isInside(node_path.default.resolve(cwd), filePath) ? node_path.default.resolve(cwd) : void 0;
2093
+ const working = await files.readWorking(filePath, allowedRoot);
1580
2094
  const body = {
1581
2095
  path: filePath,
1582
2096
  relPath: cwd === "" ? filePath : node_path.default.relative(cwd, filePath),
@@ -1604,11 +2118,12 @@ function createFileEditsApi(options = {}) {
1604
2118
  const root = node_path.default.resolve(cwd);
1605
2119
  const filePath = node_path.default.resolve(root, requested);
1606
2120
  const inSession = await isInsideSession(filePath);
1607
- if (!inSession && await readableRootOf(filePath) === void 0) return context.json({ error: "The path leaves the session directory." }, 403);
2121
+ const allowedRoot = inSession ? root : await readableRootOf(filePath);
2122
+ if (allowedRoot === void 0) return context.json({ error: "The path leaves the session directory." }, 403);
1608
2123
  const body = {
1609
2124
  path: filePath,
1610
2125
  relPath: inSession ? node_path.default.relative(root, filePath) : filePath,
1611
- working: await readWorking(filePath)
2126
+ working: await files.readWorking(filePath, allowedRoot)
1612
2127
  };
1613
2128
  return context.json(body);
1614
2129
  });
@@ -1619,240 +2134,75 @@ function createFileEditsApi(options = {}) {
1619
2134
  } catch {
1620
2135
  return context.json({ error: "The save body is not JSON." }, 400);
1621
2136
  }
1622
- if (typeof request.path !== "string" || typeof request.content !== "string") return context.json({ error: "A save names a path and the content to write." }, 400);
1623
- if (await recordedVersions(request.path) === void 0) return context.json({ error: "This session recorded no changes to that file." }, 404);
1624
- const filePath = node_path.default.resolve(cwd, request.path);
2137
+ if (typeof request !== "object" || request === null || Array.isArray(request) || !("path" in request) || typeof request.path !== "string" || !("content" in request) || typeof request.content !== "string" || !("expectedHash" in request) || typeof request.expectedHash !== "string") return context.json({ error: "A save names a path, the content to write and the hash it was read at." }, 400);
2138
+ const { path: requested, content, expectedHash } = request;
2139
+ if (await recordedVersions(requested) === void 0) return context.json({ error: "This session recorded no changes to that file." }, 404);
2140
+ const filePath = node_path.default.resolve(cwd, requested);
1625
2141
  if (!await isInsideSession(filePath)) return context.json({ error: "Files outside the session directory are read-only." }, 403);
1626
- const current = await readWorking(filePath);
1627
- if (current.unavailable) return context.json({ error: current.reason ?? "The file cannot be read." }, 409);
1628
- if (current.hash !== request.expectedHash) return context.json({
1629
- error: "The file changed since it was opened.",
1630
- hash: current.hash
1631
- }, 409);
1632
- await node_fs_promises.default.writeFile(filePath, request.content, "utf8");
1633
- const body = { hash: hashOf(request.content) };
1634
- return context.json(body);
2142
+ if (new TextEncoder().encode(content).byteLength > 1048576) return context.json({ error: `The file is larger than ${MAX_WORKING_BYTES} bytes.` }, 413);
2143
+ try {
2144
+ const outcome = await files.save({
2145
+ filePath,
2146
+ root: node_path.default.resolve(cwd),
2147
+ content,
2148
+ expectedHash
2149
+ });
2150
+ switch (outcome.status) {
2151
+ case "saved": {
2152
+ const body = { hash: outcome.hash };
2153
+ return context.json(body);
2154
+ }
2155
+ case "stale": return context.json({
2156
+ error: "The file changed since it was opened.",
2157
+ hash: outcome.hash
2158
+ }, 409);
2159
+ case "unreadable": return context.json({ error: outcome.reason }, 409);
2160
+ case "moved": return context.json({ error: "The file changed before it could be written." }, 409);
2161
+ }
2162
+ } catch {
2163
+ return context.json({ error: "The file cannot be safely written." }, 409);
2164
+ }
1635
2165
  });
1636
2166
  app.delete(routes.remove.path, async (context) => {
1637
2167
  const requested = context.req.query(PATH_QUERY_PARAM);
1638
2168
  if (await recordedVersions(requested) === void 0 || requested === void 0) return context.json({ error: "This session recorded no changes to that file." }, 404);
1639
2169
  const filePath = node_path.default.resolve(cwd, requested);
1640
2170
  if (!await isInsideSession(filePath)) return context.json({ error: "Files outside the session directory are read-only." }, 403);
1641
- try {
1642
- await node_fs_promises.default.unlink(filePath);
1643
- } catch (error) {
1644
- if (!hasCode(error, "ENOENT")) return context.json({ error: `The file could not be deleted: ${describe(error)}` }, 409);
2171
+ const outcome = await files.remove(filePath, node_path.default.resolve(cwd));
2172
+ switch (outcome.status) {
2173
+ case "outside": return context.json({ error: "Files outside the session directory are read-only." }, 403);
2174
+ case "failed": return context.json({ error: `The file could not be deleted: ${outcome.reason}` }, 409);
2175
+ case "removed": return context.body(null, 204);
1645
2176
  }
1646
- return context.body(null, 204);
1647
2177
  });
1648
2178
  return app;
1649
2179
  }
1650
- /** The named export a host imports from this package's built entry. */
1651
- const api = {
1652
- basePath: API_BASE_PATH,
1653
- start(context) {
1654
- const environment = context.environment ?? process.env;
1655
- const cwd = context.cwd;
1656
- const app = createFileEditsApi({
1657
- paths: new FileEditPaths(context.environment),
1658
- ...context.sessionId === void 0 ? {} : { sessionId: context.sessionId },
1659
- ...cwd === void 0 ? {} : {
1660
- cwd,
1661
- readableRoots: () => plansRoots(cwd, environment)
1662
- }
1663
- });
1664
- return {
1665
- fetch: (request) => app.fetch(request),
1666
- close: () => void 0
1667
- };
1668
- }
1669
- };
1670
- /**
1671
- * The plans directory Plan mode writes to, resolved the way Plan resolves it, so
1672
- * a plan link in the transcript opens in the file view. A config that cannot be
1673
- * read admits nothing extra rather than failing the preview.
1674
- */
1675
- function plansRoots(cwd, environment) {
1676
- const home = environment.HOME ?? node_os.default.homedir();
1677
- try {
1678
- const configured = (0, _agimon_ai_po_config.loadPoConfig)(cwd, home, environment).modes?.planning?.plansDirectory;
1679
- return [(0, _agimon_ai_po_config.resolvePlanningPlansDirectory)(configured, cwd, home)];
1680
- } catch {
1681
- return [];
1682
- }
1683
- }
1684
- //#endregion
1685
- //#region src/services/sessionStateSweep/index.ts
1686
- /**
1687
- * Remove the state sessions left behind when they never got to clean up.
1688
- *
1689
- * A session clears its own timeline and snapshots on shutdown, which covers the
1690
- * ordinary case and nothing else: a killed process, a crash, or a machine that
1691
- * lost power leaves both behind, and nothing ever looked at the directory
1692
- * again. One week of that filled a real checkout with hundreds of megabytes.
1693
- *
1694
- * Age is the only signal used, because it is the only one that is true from
1695
- * another process. A running session appends as it works, so its timeline is
1696
- * recent; a dead one stops moving at the moment it died.
1697
- */
1698
- /**
1699
- * How long state may sit untouched before a later session removes it.
1700
- *
1701
- * Generous on purpose. The cost of waiting is disk, and the cost of being wrong
1702
- * is deleting a live session's history, so this is set far beyond any plausible
1703
- * gap between two appends rather than close to it.
1704
- */
1705
- const STATE_MAX_AGE_MS = 6048e5;
1706
- const TIMELINE_SUFFIX = ".jsonl";
1707
- const SNAPSHOTS_SUFFIX = ".blobs";
1708
- async function remove(target) {
1709
- await node_fs_promises.default.rm(target, {
1710
- recursive: true,
1711
- force: true
1712
- });
1713
- }
1714
- /** The most recent time anything under this session's state moved. */
1715
- async function lastTouched(paths) {
1716
- let newest;
1717
- for (const target of paths) try {
1718
- const stat = await node_fs_promises.default.stat(target);
1719
- if (newest === void 0 || stat.mtimeMs > newest) newest = stat.mtimeMs;
1720
- } catch {}
1721
- return newest;
1722
- }
1723
- /** How many sessions' worth of state was removed. */
1724
- async function sweepSessionState(options) {
1725
- const { directory, keep, removeDirectory = false, now = Date.now(), maxAgeMs = STATE_MAX_AGE_MS } = options;
1726
- let entries;
1727
- try {
1728
- entries = await node_fs_promises.default.readdir(directory);
1729
- } catch {
1730
- return 0;
1731
- }
1732
- const floor = now - maxAgeMs;
1733
- const timelines = new Set(entries.filter((entry) => entry.endsWith(TIMELINE_SUFFIX)));
1734
- let removed = 0;
1735
- for (const entry of timelines) {
1736
- const timelinePath = node_path.default.join(directory, entry);
1737
- if (keep !== void 0 && timelinePath === keep) continue;
1738
- const snapshotsPath = `${timelinePath.slice(0, -6)}${SNAPSHOTS_SUFFIX}`;
1739
- const lockPath = `${timelinePath}.lock`;
1740
- const touched = await lastTouched([
1741
- timelinePath,
1742
- snapshotsPath,
1743
- lockPath
1744
- ]);
1745
- if (touched === void 0 || touched >= floor) continue;
1746
- await remove(snapshotsPath);
1747
- await remove(timelinePath);
1748
- await remove(lockPath);
1749
- removed += 1;
1750
- }
1751
- for (const entry of entries) {
1752
- if (!entry.endsWith(SNAPSHOTS_SUFFIX)) continue;
1753
- if (timelines.has(`${entry.slice(0, -6)}${TIMELINE_SUFFIX}`)) continue;
1754
- const orphan = node_path.default.join(directory, entry);
1755
- const touched = await lastTouched([orphan]);
1756
- if (touched === void 0 || touched >= floor) continue;
1757
- await remove(orphan);
1758
- }
1759
- if (removeDirectory) try {
1760
- await node_fs_promises.default.rmdir(directory);
1761
- } catch {}
1762
- return removed;
1763
- }
1764
- //#endregion
1765
- //#region src/services/webFilesChannel/index.ts
1766
- /**
1767
- * The changed-files channel consumes snapshots emitted by the owning session's
1768
- * server plugin. Durable timeline reads seed a channel that starts after session
1769
- * startup.
1770
- */
1771
- /** Whether the file is still there to be opened. */
1772
- function stillExists(filePath) {
1773
- try {
1774
- return node_fs.default.statSync(filePath).isFile();
1775
- } catch {
1776
- return false;
1777
- }
1778
- }
1779
- /**
1780
- * Reads one session's timeline and presents it as the rows the dock lists.
1781
- *
1782
- * A file the session changed and then removed is left out, and so is a path a
1783
- * bash call only touched: a command that moves a modification time without
1784
- * changing a byte is not an edit, and listing it buries the ones that are. The
1785
- * dock is a list of things to open, and a row that can only ever answer "this
1786
- * is gone" is a dead end; the timeline still holds the change, so a tab already
1787
- * open on the file keeps working and says so.
1788
- */
1789
- function readSessionFiles(timelinePath, cwd) {
1790
- let content;
1791
- try {
1792
- content = node_fs.default.readFileSync(timelinePath, "utf8");
1793
- } catch {
1794
- return [];
1795
- }
1796
- const events = confirmedChanges(parseTimeline(content));
1797
- const items = foldEntries(events).filter((entry) => stillExists(entry.path)).map((entry) => ({
1798
- path: entry.path,
1799
- relPath: node_path.default.relative(cwd, entry.path) || entry.path,
1800
- tool: entry.tool,
1801
- at: entry.at,
1802
- count: entry.count,
1803
- diffable: isDiffable(foldVersions(events, entry.path))
1804
- }));
1805
- try {
1806
- return filterPoIgnoredFiles(items, node_fs.default.readFileSync(node_path.default.join(cwd, ".poignore"), "utf8"));
1807
- } catch {
1808
- return items;
1809
- }
1810
- }
1811
- function filesPayload(value) {
1812
- return typeof value === "object" && value !== null && Array.isArray(value.items);
1813
- }
1814
- /**
1815
- * The files data channel: one direct-event subscription per managed session,
1816
- * published as { items } payloads under the 'file_edits' frame type.
1817
- */
1818
- function createFilesChannel() {
2180
+ /** The named export a host mounts, built over the storage it runs on. */
2181
+ function createFileEditsPoApi(storage) {
1819
2182
  return {
1820
- frameType: filesChannelType,
1821
- start(host) {
1822
- const latest = /* @__PURE__ */ new Map();
1823
- const subscriptions = /* @__PURE__ */ new Map();
1824
- return {
1825
- payloadFor(scope) {
1826
- const items = latest.get(scope.sessionId);
1827
- return items === void 0 ? void 0 : { items };
1828
- },
1829
- sessionAdded(scope) {
1830
- subscriptions.get(scope.sessionId)?.();
1831
- const paths = new FileEditPaths(scope.environment);
1832
- let timelinePath;
1833
- try {
1834
- timelinePath = paths.timelinePath(scope.cwd, paths.sessionKey(scope.sessionId));
1835
- } catch {}
1836
- const items = timelinePath === void 0 ? [] : readSessionFiles(timelinePath, scope.cwd);
1837
- latest.set(scope.sessionId, items);
1838
- host.publish(scope.sessionId, { items });
1839
- const unsubscribe = host.directEvents.subscribe(filesChannelType, scope.sessionId, (payload) => {
1840
- if (!filesPayload(payload)) return;
1841
- latest.set(scope.sessionId, payload.items);
1842
- host.publish(scope.sessionId, payload);
1843
- }, { replayLatest: true });
1844
- subscriptions.set(scope.sessionId, unsubscribe);
1845
- },
1846
- sessionRemoved(sessionId) {
1847
- subscriptions.get(sessionId)?.();
1848
- subscriptions.delete(sessionId);
1849
- latest.delete(sessionId);
1850
- },
1851
- close() {
1852
- for (const unsubscribe of subscriptions.values()) unsubscribe();
1853
- subscriptions.clear();
1854
- latest.clear();
2183
+ basePath: API_BASE_PATH,
2184
+ start(context) {
2185
+ const environment = context.environment ?? {};
2186
+ const cwd = context.cwd;
2187
+ const app = createFileEditsApi({
2188
+ storage,
2189
+ paths: storage.paths({
2190
+ ...environment,
2191
+ HOME: context.homeDirectory ?? environment.HOME
2192
+ }),
2193
+ ...context.sessionId === void 0 ? {} : { sessionId: context.sessionId },
2194
+ ...cwd === void 0 ? {} : {
2195
+ cwd,
2196
+ readableRoots: storage.readableRoots({
2197
+ cwd,
2198
+ environment,
2199
+ ...context.homeDirectory === void 0 ? {} : { homeDirectory: context.homeDirectory }
2200
+ })
1855
2201
  }
2202
+ });
2203
+ return {
2204
+ fetch: (request) => app.fetch(request),
2205
+ close: () => void 0
1856
2206
  };
1857
2207
  }
1858
2208
  };
@@ -1860,39 +2210,74 @@ function createFilesChannel() {
1860
2210
  //#endregion
1861
2211
  //#region src/services/fileEditSession/index.ts
1862
2212
  const PO_IGNORE_FILE = ".poignore";
1863
- function readPoIgnore(cwd) {
2213
+ async function readPoIgnore(cwd, fs) {
1864
2214
  try {
1865
- const matcher = createPoIgnoreMatcher(node_fs.default.readFileSync(node_path.default.join(cwd, PO_IGNORE_FILE), "utf8"));
2215
+ const content = await (0, _agimon_ai_po_core_platform.readTextIfExists)(fs, node_path.default.join(cwd, PO_IGNORE_FILE), _agimon_ai_po_core_platform.BACKGROUND_CONTEXT);
2216
+ if (content === void 0) return void 0;
2217
+ const matcher = createPoIgnoreMatcher(content);
1866
2218
  return matcher === void 0 ? void 0 : (filePath) => matcher(node_path.default.relative(cwd, filePath));
1867
2219
  } catch {
1868
2220
  return;
1869
2221
  }
1870
2222
  }
2223
+ /** Export only fixed categories from structured tool details, never displayed output. */
2224
+ function failureAttributes(result) {
2225
+ if (!result || typeof result !== "object" || !("details" in result)) return {};
2226
+ const details = result.details;
2227
+ if (!details || typeof details !== "object") return {};
2228
+ const failure = "failure" in details ? details.failure : void 0;
2229
+ const kind = failure && typeof failure === "object" && "kind" in failure ? failure.kind : void 0;
2230
+ return {
2231
+ ...typeof kind === "string" && [
2232
+ "timeout",
2233
+ "exit_code",
2234
+ "not_found",
2235
+ "permission",
2236
+ "validation",
2237
+ "aborted",
2238
+ "unknown"
2239
+ ].includes(kind) ? { "failure.kind": kind } : {},
2240
+ ..."exit_code" in details && typeof details.exit_code === "number" && Number.isFinite(details.exit_code) ? { exit_code: details.exit_code } : {}
2241
+ };
2242
+ }
1871
2243
  function stringValue(value, key) {
1872
2244
  const candidate = value[key];
1873
2245
  return typeof candidate === "string" && candidate.length > 0 ? candidate : void 0;
1874
2246
  }
1875
- function createFileEditSession({ agent, host }) {
1876
- if (!agent) return { api: [api] };
2247
+ function createFileEditSession({ agent, host }, fs, storage = createFileEditStorage(fs)) {
2248
+ const fileEditsApi = createFileEditsPoApi(storage);
2249
+ if (!agent) return { api: [fileEditsApi] };
1877
2250
  const environment = Object.freeze({ ...host.context.environment });
1878
- const paths = new FileEditPaths(environment);
1879
- const timeline = new TimelineStore();
1880
- const snapshots = new NodeSnapshotStoreAdapter();
1881
- const editTracker = new EditTracker(timeline, snapshots, new NodeTreeManifestAdapter(), { git: new NodeGitStatusAdapter() });
1882
- if (host.context.directEvents === void 0) throw new Error("File-edit server plugin requires the session direct event bus.");
1883
- const directEvents = host.context.directEvents;
1884
- const telemetry = (0, _agimon_ai_po_telemetry.createPoTelemetry)({
2251
+ const paths = storage.paths(environment);
2252
+ const timeline = storage.timeline();
2253
+ const snapshots = storage.snapshots();
2254
+ const telemetry = (0, _agimon_ai_po_core_telemetry.createPoTelemetry)({
1885
2255
  serviceName: "po-file-edit",
1886
2256
  packageName: "@agimon-ai/po-file-edit",
1887
2257
  env: environment,
1888
2258
  enableLogs: true,
1889
2259
  enableTraces: true
1890
2260
  });
2261
+ const changeListeners = /* @__PURE__ */ new Set();
2262
+ const editTracker = new EditTracker(timeline, snapshots, storage.manifests(), {
2263
+ git: storage.git(),
2264
+ onChanged: async (paths) => {
2265
+ for (const listener of changeListeners) try {
2266
+ await listener(paths);
2267
+ } catch (error) {
2268
+ await telemetry.recordWarning("po_file_edit.subscriber_failed", error);
2269
+ }
2270
+ },
2271
+ onScanFailed: (error) => void track(() => telemetry.recordWarning("po_file_edit.scan_failed", error))
2272
+ });
2273
+ if (host.context.directEvents === void 0) throw new Error("File-edit server plugin requires the session direct event bus.");
2274
+ const directEvents = host.context.directEvents;
1891
2275
  const toolStartedAt = /* @__PURE__ */ new Map();
1892
2276
  const pending = /* @__PURE__ */ new Set();
1893
2277
  let closed = false;
1894
2278
  let disposal;
1895
2279
  let stopping;
2280
+ let starting;
1896
2281
  let initialized = false;
1897
2282
  const track = (work) => {
1898
2283
  const task = work();
@@ -1910,8 +2295,9 @@ function createFileEditSession({ agent, host }) {
1910
2295
  * string is deliberate: the group declares `hideWhenEmpty`, so a session that
1911
2296
  * has edited nothing publishes a key with no content and stays hidden.
1912
2297
  */
1913
- const publish = (runtime) => {
1914
- const items = readSessionFiles(runtime.timelinePath, runtime.context.cwd);
2298
+ const publish = async (runtime) => {
2299
+ const items = await storage.sessionFiles(runtime.timelinePath, runtime.context.cwd);
2300
+ if (active !== runtime || closed || stopping) return;
1915
2301
  directEvents.publish(filesChannelType, runtime.context.sessionId, { items });
1916
2302
  runtime.context.client.setStatus(filesStatusKey, items.length === 0 ? "" : `${items.length} ${items.length === 1 ? "file" : "files"}`);
1917
2303
  };
@@ -1920,11 +2306,13 @@ function createFileEditSession({ agent, host }) {
1920
2306
  const runtime = active;
1921
2307
  active = void 0;
1922
2308
  stopping = (async () => {
1923
- await Promise.allSettled(pending);
2309
+ while (pending.size > 0) await Promise.allSettled(pending);
2310
+ const startedRuntime = active;
2311
+ active = void 0;
1924
2312
  await editTracker.flush();
1925
2313
  editTracker.reset();
1926
2314
  toolStartedAt.clear();
1927
- runtime?.context.client.setStatus(filesStatusKey, void 0);
2315
+ (runtime ?? startedRuntime)?.context.client.setStatus(filesStatusKey, void 0);
1928
2316
  })();
1929
2317
  return stopping;
1930
2318
  };
@@ -1934,10 +2322,10 @@ function createFileEditSession({ agent, host }) {
1934
2322
  disposal = (0, _agimon_ai_po_core_extensionFile.runCleanups)([
1935
2323
  stopActivity,
1936
2324
  async () => {
1937
- if (lastRuntime && !environment[_agimon_ai_po_core_childProcess.SUBAGENT_CHILD_ENV]) await timeline.clear();
2325
+ if (storage.clearOnClose && lastRuntime && !environment[_agimon_ai_po_core_childProcess.SUBAGENT_CHILD_ENV]) await timeline.clear();
1938
2326
  },
1939
2327
  async () => {
1940
- if (lastRuntime && !environment[_agimon_ai_po_core_childProcess.SUBAGENT_CHILD_ENV]) await snapshots.clear();
2328
+ if (storage.clearOnClose && lastRuntime && !environment[_agimon_ai_po_core_childProcess.SUBAGENT_CHILD_ENV]) await snapshots.clear();
1941
2329
  },
1942
2330
  async () => {
1943
2331
  if (lastRuntime) await telemetry.recordEvent("po_file_edit.timeline_finished", { outcome: "closed" });
@@ -1946,22 +2334,23 @@ function createFileEditSession({ agent, host }) {
1946
2334
  ], "File-edit session cleanup failed.");
1947
2335
  return disposal;
1948
2336
  };
1949
- return {
1950
- api: [api],
1951
- activities: [{
1952
- name: "file-edits",
1953
- start: async (executionContext) => {
1954
- if (closed) throw new Error("File-edit session is closed.");
1955
- if (active) return stopActivity;
1956
- if (stopping) await stopping;
1957
- if (closed) throw new Error("File-edit session is closed.");
1958
- stopping = void 0;
2337
+ const activity = {
2338
+ name: "file-edits",
2339
+ start: async (executionContext) => {
2340
+ if (closed) throw new Error("File-edit session is closed.");
2341
+ if (starting) return starting;
2342
+ if (active) return stopActivity;
2343
+ if (stopping) await stopping;
2344
+ if (closed) throw new Error("File-edit session is closed.");
2345
+ if (starting) return starting;
2346
+ stopping = void 0;
2347
+ starting = track(async () => {
1959
2348
  const sessionKey = paths.sessionKey(executionContext.sessionId);
1960
- const timelinePath = paths.timelinePath(executionContext.cwd, sessionKey);
1961
- const snapshotsPath = paths.snapshotsPath(executionContext.cwd, sessionKey);
2349
+ const timelinePath = await paths.timelinePath(executionContext.cwd, sessionKey);
2350
+ const snapshotsPath = await paths.snapshotsPath(executionContext.cwd, sessionKey);
1962
2351
  timeline.initialize(timelinePath);
1963
2352
  snapshots.initialize(snapshotsPath);
1964
- const isIgnored = readPoIgnore(executionContext.cwd);
2353
+ const isIgnored = await readPoIgnore(executionContext.cwd, fs);
1965
2354
  editTracker.reset({
1966
2355
  exclude: [
1967
2356
  timelinePath,
@@ -1977,112 +2366,158 @@ function createFileEditSession({ agent, host }) {
1977
2366
  };
1978
2367
  active = runtime;
1979
2368
  lastRuntime = runtime;
1980
- publish(runtime);
2369
+ await publish(runtime);
1981
2370
  track(async () => {
1982
2371
  try {
1983
- await sweepSessionState({
1984
- directory: paths.stateDirectory(),
1985
- keep: timelinePath
1986
- });
1987
- } catch {}
2372
+ await storage.sweepAbandoned?.(paths.stateDirectory(), timelinePath);
2373
+ } catch (error) {
2374
+ await telemetry.recordWarning("po_file_edit.sweep_failed", error);
2375
+ }
1988
2376
  });
1989
2377
  if (!initialized) {
1990
2378
  initialized = true;
1991
2379
  await track(() => telemetry.recordEvent("po_file_edit.timeline_started", { outcome: "initialized" }));
1992
2380
  }
1993
2381
  return () => active === runtime ? stopActivity() : Promise.resolve();
2382
+ });
2383
+ try {
2384
+ return await starting;
2385
+ } finally {
2386
+ starting = void 0;
1994
2387
  }
1995
- }],
1996
- hooks: [{
1997
- event: "tool_execution_start",
1998
- handle: (event, executionContext) => {
1999
- const runtime = active;
2000
- const toolCallId = stringValue(event, "toolCallId");
2001
- const toolName = stringValue(event, "toolName");
2002
- if (runtime === void 0 || runtime.context.sessionId !== executionContext.sessionId || !toolCallId || !toolName) return;
2003
- return track(async () => {
2004
- toolStartedAt.set(toolCallId, Date.now());
2005
- const hookStartedAt = Date.now();
2006
- await editTracker.start(toolCallId, toolName, event.args, executionContext.cwd);
2007
- if (active !== runtime) return;
2008
- await telemetry.recordEvent("po_file_edit.edit_started", {
2009
- "tool.name": toolName,
2010
- hook_ms: Date.now() - hookStartedAt
2011
- });
2388
+ }
2389
+ };
2390
+ const startHook = {
2391
+ event: "tool_execution_start",
2392
+ handle: (event, executionContext) => {
2393
+ if (closed || stopping) return;
2394
+ const runtime = active;
2395
+ const toolCallId = stringValue(event, "toolCallId");
2396
+ const toolName = stringValue(event, "toolName");
2397
+ if (runtime === void 0 || runtime.context.sessionId !== executionContext.sessionId || !toolCallId || !toolName) return;
2398
+ return track(async () => {
2399
+ const hookStartedAt = Date.now();
2400
+ if (!await editTracker.start(toolCallId, toolName, event.args, executionContext.cwd) || active !== runtime) return;
2401
+ toolStartedAt.set(toolCallId, hookStartedAt);
2402
+ await telemetry.recordEvent("po_file_edit.edit_started", {
2403
+ "tool.name": toolName,
2404
+ hook_ms: Date.now() - hookStartedAt
2012
2405
  });
2013
- }
2014
- }, {
2015
- event: "tool_execution_end",
2016
- handle: (event, executionContext) => {
2017
- const runtime = active;
2018
- const toolCallId = stringValue(event, "toolCallId");
2019
- const toolName = stringValue(event, "toolName");
2020
- if (runtime === void 0 || runtime.context.sessionId !== executionContext.sessionId || !toolCallId || !toolName) return;
2021
- return track(async () => {
2022
- const startedAt = toolStartedAt.get(toolCallId);
2023
- toolStartedAt.delete(toolCallId);
2024
- const hookStartedAt = Date.now();
2025
- const isError = event.isError === true;
2026
- await editTracker.end(toolCallId, isError, executionContext.cwd);
2027
- if (active !== runtime) return;
2028
- publish(runtime);
2029
- await telemetry.recordEvent("po_file_edit.edit_finished", {
2030
- "tool.name": toolName,
2031
- "tool.result.error": isError,
2032
- ...startedAt === void 0 ? {} : { duration_ms: Date.now() - startedAt },
2033
- hook_ms: Date.now() - hookStartedAt,
2034
- outcome: isError ? "failed" : "completed"
2035
- });
2406
+ });
2407
+ }
2408
+ };
2409
+ const endHook = {
2410
+ event: "tool_execution_end",
2411
+ handle: (event, executionContext) => {
2412
+ if (closed || stopping) return;
2413
+ const runtime = active;
2414
+ const toolCallId = stringValue(event, "toolCallId");
2415
+ const toolName = stringValue(event, "toolName");
2416
+ if (runtime === void 0 || runtime.context.sessionId !== executionContext.sessionId || !toolCallId || !toolName) return;
2417
+ return track(async () => {
2418
+ const startedAt = toolStartedAt.get(toolCallId);
2419
+ if (startedAt === void 0) return;
2420
+ toolStartedAt.delete(toolCallId);
2421
+ const hookStartedAt = Date.now();
2422
+ const isError = event.isError === true;
2423
+ await editTracker.end(toolCallId, isError, executionContext.cwd);
2424
+ if (active !== runtime) return;
2425
+ await publish(runtime);
2426
+ await telemetry.recordEvent("po_file_edit.edit_finished", {
2427
+ "tool.name": toolName,
2428
+ "tool.result.error": isError,
2429
+ ...failureAttributes(event.result),
2430
+ ...startedAt === void 0 ? {} : { duration_ms: Date.now() - startedAt },
2431
+ hook_ms: Date.now() - hookStartedAt,
2432
+ outcome: isError ? "failed" : "completed"
2036
2433
  });
2037
- }
2038
- }],
2434
+ });
2435
+ }
2436
+ };
2437
+ const changes = {
2438
+ sessionId: agent.context.sessionId,
2439
+ subscribe(listener) {
2440
+ changeListeners.add(listener);
2441
+ return () => {
2442
+ changeListeners.delete(listener);
2443
+ };
2444
+ },
2445
+ flush: () => editTracker.flush()
2446
+ };
2447
+ return {
2448
+ services: [(scope) => scope.provide(require_package.PO_FILE_EDIT_CHANGES_SERVICE, changes)],
2449
+ api: [fileEditsApi],
2450
+ activities: [activity],
2451
+ hooks: [startHook, endHook],
2039
2452
  onDispose: dispose
2040
2453
  };
2041
2454
  }
2042
2455
  //#endregion
2043
2456
  //#region src/extensions/workspaces/sessions/(backend)/_lib/serverRoot.ts
2044
- function createPresence({ agent, host, context }) {
2045
- const ledger = host.context.editPresence;
2046
- if (!agent || !ledger) return void 0;
2457
+ function createPresence({ agent, host, context }, presence, files) {
2458
+ if (!agent || !presence) return void 0;
2047
2459
  const execution = agent.context;
2048
2460
  return createSessionPresence({
2049
- ledger,
2461
+ presence,
2050
2462
  sessionId: execution.sessionId,
2051
2463
  cwd: execution.cwd,
2464
+ files,
2052
2465
  workflowStep: execution.sessionContext?.provenance === _agimon_ai_po_core_hubChannel.WORKFLOW_STEP_SESSION_PROVENANCE,
2053
2466
  isLive: () => host.context.sessionService?.isLive(execution.sessionId) ?? true,
2054
2467
  labelFor: (runId) => (0, _agimon_ai_po_core_childSession.readPoChildSessionLabels)(context)?.labelFor(runId),
2055
2468
  onError: (error) => host.context.onNotice(`Edit presence failed: ${error instanceof Error ? error.message : String(error)}`)
2056
2469
  });
2057
2470
  }
2058
- const createFileEditServerRoot = (context) => {
2059
- const runtime = createFileEditSession(context);
2060
- const presence = createPresence(context);
2471
+ const createFileEditServerRoot = (context, fs) => {
2472
+ const storage = createFileEditStorage(fs);
2473
+ const runtime = createFileEditSession(context, fs, storage);
2474
+ let presence;
2475
+ let disposePresence = () => {};
2476
+ let closed = false;
2477
+ let disposal;
2061
2478
  return {
2062
2479
  value: {
2063
2480
  ...runtime,
2064
- ...presence === void 0 ? {} : { presence }
2481
+ get presence() {
2482
+ return presence;
2483
+ }
2065
2484
  },
2066
2485
  activities: runtime.activities,
2067
- ...presence === void 0 ? {} : { services: [(cordis) => {
2068
- cordis.inject([_agimon_ai_po_core_childSession.PO_CHILD_SESSION_HOOK_REGISTRY_SERVICE], (registryContext) => {
2069
- const registration = registryContext.get(_agimon_ai_po_core_childSession.PO_CHILD_SESSION_HOOK_REGISTRY_SERVICE).register(presence.childHooks);
2070
- return () => registration.dispose();
2486
+ services: [...runtime.services ?? [], (cordis) => {
2487
+ cordis.inject([_agimon_ai_po_core_packageApi.PO_EDIT_PRESENCE_SERVICE], (presenceContext) => {
2488
+ if (closed) return;
2489
+ const bound = createPresence(context, presenceContext.get(_agimon_ai_po_core_packageApi.PO_EDIT_PRESENCE_SERVICE), storage.presenceFiles());
2490
+ if (!bound) return;
2491
+ presence = bound;
2492
+ let disposed = false;
2493
+ const cleanup = () => {
2494
+ if (disposed) return;
2495
+ disposed = true;
2496
+ if (presence === bound) presence = void 0;
2497
+ bound.dispose();
2498
+ };
2499
+ disposePresence = cleanup;
2500
+ presenceContext.inject([_agimon_ai_po_core_childSession.PO_CHILD_SESSION_HOOK_REGISTRY_SERVICE], (registryContext) => {
2501
+ const registration = registryContext.get(_agimon_ai_po_core_childSession.PO_CHILD_SESSION_HOOK_REGISTRY_SERVICE).register(bound.childHooks);
2502
+ return () => registration.dispose();
2503
+ });
2504
+ return cleanup;
2071
2505
  });
2072
- }] },
2073
- onDispose: async (pluginContext) => {
2074
- await (0, _agimon_ai_po_core_extensionFile.runCleanups)([() => presence?.dispose(), () => runtime.onDispose?.(pluginContext)], "File-edit root cleanup failed.");
2506
+ }],
2507
+ onDispose: (pluginContext) => {
2508
+ closed = true;
2509
+ return disposal ??= (0, _agimon_ai_po_core_extensionFile.runCleanups)([() => disposePresence(), () => runtime.onDispose?.(pluginContext)], "File-edit root cleanup failed.");
2075
2510
  }
2076
2511
  };
2077
2512
  };
2078
2513
  //#endregion
2079
2514
  //#region src/extensions/workspaces/sessions/(backend)/root.server.ts
2080
- var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)(createFileEditServerRoot);
2515
+ var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)((context) => createFileEditServerRoot(context, (0, _agimon_ai_po_core_platform.requirePoFs)(context.context)));
2081
2516
  //#endregion
2082
2517
  //#region src/extensions/(backend)/channel/fileEdits.server.ts
2083
- var fileEdits_server_default = (0, _agimon_ai_po_core_extensionFile.defineChannel)(function fileEditsChannel() {
2084
- return createFilesChannel();
2085
- });
2518
+ var fileEdits_server_default = (0, _agimon_ai_po_core_extensionFile.defineChannel)(function fileEditsChannel(context) {
2519
+ return createFilesChannel(createFileEditStorage((0, _agimon_ai_po_core_platform.readPoFs)(context.context)));
2520
+ }, { context: true });
2086
2521
  //#endregion
2087
2522
  //#region src/extensions/workspaces/sessions/(backend)/api/file-edits/route.server.ts
2088
2523
  /**
@@ -2092,38 +2527,59 @@ var fileEdits_server_default = (0, _agimon_ai_po_core_extensionFile.defineChanne
2092
2527
  * returns a runtime carrying `api`, but a root's `api` is not folded into the
2093
2528
  * generated entry the way its services and activities are, so the registration
2094
2529
  * was dropped in silence and the cockpit called routes that answered 404.
2530
+ *
2531
+ * The API reads the files of the host it runs on, so it is built from the file
2532
+ * system the session was given.
2095
2533
  */
2096
- var route_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoute)(api);
2534
+ var route_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoute)((context) => createFileEditsPoApi(createFileEditStorage((0, _agimon_ai_po_core_platform.readPoFs)(context.context))));
2535
+ //#endregion
2536
+ //#region src/extensions/workspaces/sessions/(backend)/hook/operation-after.server.ts
2537
+ var operation_after_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)(({ root }) => ({
2538
+ name: "observe-edit-presence",
2539
+ description: "For executed tools or supported filesystem writes in this session, observe file presence and add collaboration notes; leave results unchanged without a ledger.",
2540
+ event: "operation_after",
2541
+ handle: async (event, execution) => root.presence?.operationAfter.handle(event, execution)
2542
+ }));
2097
2543
  //#endregion
2098
2544
  //#region src/extensions/workspaces/sessions/(backend)/hook/tool-execution-end.server.ts
2099
- var tool_execution_end_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)((context) => context.root.hooks[1]);
2545
+ var tool_execution_end_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)((context) => ({
2546
+ ...context.root.hooks[1],
2547
+ name: "track-file-edit-result",
2548
+ description: "For tracked tool calls in the active matching session while not closing or stopping, finalize edits, publish changes, and record outcome telemetry."
2549
+ }));
2100
2550
  //#endregion
2101
2551
  //#region src/extensions/workspaces/sessions/(backend)/hook/tool-execution-start.server.ts
2102
- var tool_execution_start_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)((context) => context.root.hooks[0]);
2103
- //#endregion
2104
- //#region src/extensions/workspaces/sessions/(backend)/hook/tool-result.server.ts
2105
- var tool_result_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)(({ root }) => ({
2106
- event: "tool_result",
2107
- handle: async (event, execution) => root.presence?.toolResult.handle(event, execution)
2552
+ var tool_execution_start_server_default = (0, _agimon_ai_po_core_extensionFile.defineHook)((context) => ({
2553
+ ...context.root.hooks[0],
2554
+ name: "track-file-edit-start",
2555
+ description: "For valid tool calls in the active matching session while not closing or stopping, snapshot admitted edits and record start telemetry."
2108
2556
  }));
2109
2557
  //#endregion
2110
2558
  //#region generated/server.ts
2111
2559
  const at = (value, context) => typeof value === "function" ? value(context) : value;
2112
2560
  /* v8 ignore next -- generated normalization branch */
2113
2561
  const defined = (values) => values.filter((value) => value !== void 0);
2114
- const via = (identity, value) => value === void 0 ? void 0 : {
2115
- ...identity,
2116
- ...value
2562
+ const via = (identity, value) => {
2563
+ if (value === void 0) return void 0;
2564
+ const declaration = value;
2565
+ return {
2566
+ ...identity,
2567
+ ...declaration,
2568
+ ...declaration.relations === void 0 ? {} : { relations: declaration.relations.map((relation) => ({
2569
+ evidence: "declared",
2570
+ ...relation
2571
+ })) }
2572
+ };
2117
2573
  };
2118
2574
  const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
2119
2575
  name: "@agimon-ai/po-file-edit",
2120
2576
  providerOverrides: (0, _agimon_ai_po_core_serverPlugin.composeServerProviderOverrides)(root_server_default),
2121
2577
  injects: (0, _agimon_ai_po_core_extensionFile.composeRootInjects)({ session: [root_server_default] }),
2122
- global: () => ({ get channels() {
2123
- return [() => via({ frameType: "file_edits" }, fileEdits_server_default())];
2578
+ host: (context) => ({ get channels() {
2579
+ return [() => via({ frameType: "file_edits" }, at(fileEdits_server_default, context))];
2124
2580
  } }),
2125
2581
  workspace: (context) => ({ get channels() {
2126
- return defined([context.hosted("global") ? void 0 : () => via({ frameType: "file_edits" }, fileEdits_server_default())]);
2582
+ return defined([context.hosted("host") ? void 0 : () => via({ frameType: "file_edits" }, at(fileEdits_server_default, context))]);
2127
2583
  } }),
2128
2584
  session: async (context) => {
2129
2585
  const scopeSession = await context.scopeRoot("session", root_server_default, context);
@@ -2137,13 +2593,13 @@ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
2137
2593
  return [at(route_server_default, contextSession)];
2138
2594
  },
2139
2595
  get channels() {
2140
- return defined([context.hosted("global") ? void 0 : () => via({ frameType: "file_edits" }, fileEdits_server_default())]);
2596
+ return defined([context.hosted("host") ? void 0 : () => via({ frameType: "file_edits" }, at(fileEdits_server_default, context))]);
2141
2597
  },
2142
2598
  get hooks() {
2143
2599
  return [
2600
+ via({ event: "operation_after" }, at(operation_after_server_default, contextSession)),
2144
2601
  via({ event: "tool_execution_end" }, at(tool_execution_end_server_default, contextSession)),
2145
- via({ event: "tool_execution_start" }, at(tool_execution_start_server_default, contextSession)),
2146
- via({ event: "tool_result" }, at(tool_result_server_default, contextSession))
2602
+ via({ event: "tool_execution_start" }, at(tool_execution_start_server_default, contextSession))
2147
2603
  ];
2148
2604
  },
2149
2605
  services: [...scopeSession.services ?? []],