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