@leonardo-marziali/ad-lfl-kit 2.15.0 → 2.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +98 -10
- package/base.js +82 -0
- package/changes.js +2 -0
- package/guard.js +115 -0
- package/index.js +2 -0
- package/package.json +3 -1
- package/scope.js +23 -4
- package/track.js +43 -9
package/README.md
CHANGED
|
@@ -68,7 +68,12 @@ calls too, with the parent's `session_id` and their own `agent_id`.
|
|
|
68
68
|
'use strict';
|
|
69
69
|
|
|
70
70
|
const path = require('node:path');
|
|
71
|
-
const {
|
|
71
|
+
const {
|
|
72
|
+
readHookInput,
|
|
73
|
+
stateDir,
|
|
74
|
+
guardCommit,
|
|
75
|
+
trackSessionChanges,
|
|
76
|
+
} = require('@leonardo-marziali/ad-lfl-kit');
|
|
72
77
|
|
|
73
78
|
const input = readHookInput();
|
|
74
79
|
if (input) {
|
|
@@ -76,11 +81,12 @@ if (input) {
|
|
|
76
81
|
sessionId: input.session_id,
|
|
77
82
|
namespace: 'my-plugin-session-scope',
|
|
78
83
|
});
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
+
const listFile = path.join(dir, 'touched-files.txt');
|
|
85
|
+
const matches = (absPath) => /\.md$/i.test(absPath);
|
|
86
|
+
// No commits while touched files are still waiting on the Stop hook.
|
|
87
|
+
if (!guardCommit({ input, listFile, matches, label: 'my-plugin' }).denied) {
|
|
88
|
+
trackSessionChanges({ input, listFile, matches });
|
|
89
|
+
}
|
|
84
90
|
}
|
|
85
91
|
```
|
|
86
92
|
|
|
@@ -174,6 +180,38 @@ context compaction and session restarts, and it sees every write —
|
|
|
174
180
|
including the ones no `PostToolUse` hook ever hears about, like a `sed -i`,
|
|
175
181
|
a formatter run from another hook, or the user's own editor.
|
|
176
182
|
|
|
183
|
+
**Commits made mid-session.** `HEAD` is only the last known-clean state
|
|
184
|
+
while the session hasn't committed its own work. A session that commits
|
|
185
|
+
before its `Stop` hook runs moves `HEAD` past its own edits, `git diff HEAD`
|
|
186
|
+
comes back empty, and every finding on those lines reads as pre-existing —
|
|
187
|
+
the check passes having checked nothing. Two pieces close that gap, and a
|
|
188
|
+
consumer should use both:
|
|
189
|
+
|
|
190
|
+
- **A session base.** `trackSessionChanges` records, per repository, the
|
|
191
|
+
`HEAD` the session's first tracked file there was edited on top of (for a
|
|
192
|
+
shell call, the `HEAD` from its `PreToolUse` snapshot, so
|
|
193
|
+
`edit && git commit` in one command is covered). Pass it to `scopesFor`:
|
|
194
|
+
|
|
195
|
+
```js
|
|
196
|
+
const { readSessionBases, SESSION_BASE_FILE } = require('@leonardo-marziali/ad-lfl-kit');
|
|
197
|
+
|
|
198
|
+
const scopes = scopesFor(files, { bases: readSessionBases(sessionDir) });
|
|
199
|
+
// …and list SESSION_BASE_FILE among the main Stop hook's stateFiles.
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
Each repo with a base is then diffed against it, so committed and
|
|
203
|
+
uncommitted session lines are both in scope. `sessionDir` is the session's
|
|
204
|
+
directory, not `loopStateDir`'s — a subagent's lines are diffed against
|
|
205
|
+
the same base. Cleaning `SESSION_BASE_FILE` up when the loop passes means
|
|
206
|
+
the next turn starts a fresh base from whatever `HEAD` is then. A pull or
|
|
207
|
+
rebase mid-session widens the scope to whatever it brought into the
|
|
208
|
+
touched files — the fail-open direction.
|
|
209
|
+
|
|
210
|
+
- **A commit guard.** `guardCommit`, called from the `PreToolUse` hook,
|
|
211
|
+
denies a `git commit` while the session's list still holds files no check
|
|
212
|
+
has passed yet, so commits only happen after the `Stop` hook has run. See
|
|
213
|
+
[Commit guard](#commit-guard-guardjs).
|
|
214
|
+
|
|
177
215
|
**Ordering.** Because `fixableFiles` needs to know what's out of scope, an
|
|
178
216
|
auto-fixing consumer runs check → fix → re-check rather than fix → check:
|
|
179
217
|
lint once to get the findings, partition them, fix only the files with
|
|
@@ -291,11 +329,58 @@ How `toolChangedFiles` answers for tools that don't name their files.
|
|
|
291
329
|
it decides which files a session becomes answerable for.
|
|
292
330
|
- **`MTIME_SLACK_MS`** / **`PRUNED_DIR_NAMES`** — the mtime tolerance for
|
|
293
331
|
coarse filesystems, and the directories skipped.
|
|
332
|
+
- **`repoRoot(dir)`** / **`headOf(root)`** — the git root containing `dir`
|
|
333
|
+
and the `HEAD` commit of a repo, or `null`.
|
|
294
334
|
|
|
295
335
|
What it can't see: writes outside both the snapshot's and the current
|
|
296
336
|
cwd's repository, and a background command's writes more than
|
|
297
337
|
`BACKGROUND_WINDOW_MS` after it started.
|
|
298
338
|
|
|
339
|
+
### Session base (`base.js`)
|
|
340
|
+
|
|
341
|
+
- **`SESSION_BASE_FILE`** — `'session-base.json'`, written beside the
|
|
342
|
+
tracked-file list.
|
|
343
|
+
- **`readSessionBases(dir)`** — `{ [repoRoot]: sha }` for a session state
|
|
344
|
+
directory, `{}` when nothing was recorded or the file is unreadable.
|
|
345
|
+
- **`recordSessionBase(dir, root, head)`** — records `head` as `root`'s base
|
|
346
|
+
unless one is already recorded (first sighting wins). Returns whether it
|
|
347
|
+
wrote anything. `trackSessionChanges` and `trackTouchedFile` call it for
|
|
348
|
+
you.
|
|
349
|
+
- **`knownRootFor(bases, absPath)`** — the deepest recorded root containing
|
|
350
|
+
`absPath`, or `null`.
|
|
351
|
+
|
|
352
|
+
### Commit guard (`guard.js`)
|
|
353
|
+
|
|
354
|
+
- **`guardCommit({ input, listFile, matches, label, buildReason, write })`**
|
|
355
|
+
— on a `PreToolUse` event for a commit call, while `listFile` still holds
|
|
356
|
+
files (filtered by `matches`, if given), prints a `permissionDecision:
|
|
357
|
+
"deny"` payload and returns `{ denied: true, files }`; otherwise prints
|
|
358
|
+
nothing and returns `{ denied: false }`. `label` names the plugin in the
|
|
359
|
+
message, and `buildReason({ label, files })` replaces it. Call it before
|
|
360
|
+
`trackSessionChanges` in the `PreToolUse` hook and skip tracking when it
|
|
361
|
+
denies — a denied call never runs, so no `Post*` event would consume its
|
|
362
|
+
snapshot:
|
|
363
|
+
|
|
364
|
+
```js
|
|
365
|
+
if (guardCommit({ input, listFile, matches, label: 'my-plugin' }).denied) return;
|
|
366
|
+
trackSessionChanges({ input, listFile, matches });
|
|
367
|
+
```
|
|
368
|
+
|
|
369
|
+
The list is cleared when `runFixLoop` passes or gives up at the cap, so
|
|
370
|
+
"edit and commit" becomes two turns: the edit ends the turn and the
|
|
371
|
+
checks run, then a commit asked for afterwards goes through. While a
|
|
372
|
+
`check` keeps throwing (`reason: 'error'`) the list stays and so does the
|
|
373
|
+
block; the deny message tells Claude to say so, and the user can still
|
|
374
|
+
commit from their own terminal — only Claude's tool calls reach a hook.
|
|
375
|
+
|
|
376
|
+
- **`isCommitCall(input)`** — whether a call creates a commit: a `Bash` or
|
|
377
|
+
`PowerShell` command running `git [global options] commit` (not
|
|
378
|
+
`commit-tree` or `commit-graph`), or an MCP tool named `…__commit` or
|
|
379
|
+
`…__git_commit`. It matches command text, so it catches accidents, not a
|
|
380
|
+
determined workaround (`sh -c`, a git alias, a script that commits).
|
|
381
|
+
- **`commitDenyPayload(reason)`** — the deny payload, for hooks that gate a
|
|
382
|
+
call outside `guardCommit`.
|
|
383
|
+
|
|
299
384
|
### Execution (`exec.js`)
|
|
300
385
|
|
|
301
386
|
- **`resolveBin(name, { extraDirs })`** — finds a CLI binary across
|
|
@@ -318,14 +403,17 @@ a git ref_, so a one-line edit to a long, already-messy document doesn't hand
|
|
|
318
403
|
Claude every pre-existing violation in it. See
|
|
319
404
|
[Scoping to changes against HEAD](#scoping-to-changes-against-head).
|
|
320
405
|
|
|
321
|
-
- **`scopesFor(files, { ref, context })`** — the entry point: a `Map`
|
|
322
|
-
absolute path → scope, with the context margin already applied. `ref`
|
|
323
|
-
defaults to `HEAD`, `context` to `DEFAULT_CONTEXT_LINES` (2).
|
|
406
|
+
- **`scopesFor(files, { ref, bases, context })`** — the entry point: a `Map`
|
|
407
|
+
of absolute path → scope, with the context margin already applied. `ref`
|
|
408
|
+
defaults to `HEAD`, `context` to `DEFAULT_CONTEXT_LINES` (2). `bases` (an
|
|
409
|
+
object or `Map` of repo root → commit, normally `readSessionBases()`)
|
|
410
|
+
overrides `ref` per repository; a base that no longer names a commit falls
|
|
411
|
+
back to `ref`. A scope is
|
|
324
412
|
`{ file, all, ranges, includes(line) }`, where `all` means the whole file
|
|
325
413
|
is in scope and `ranges` are inclusive, 1-based `[start, end]` pairs in
|
|
326
414
|
current-file coordinates. `includes()` called without a line number
|
|
327
415
|
returns `all`.
|
|
328
|
-
- **`changedRangesByFile(files, { ref })`** — the same answer before the
|
|
416
|
+
- **`changedRangesByFile(files, { ref, bases })`** — the same answer before the
|
|
329
417
|
margin is applied, as `{ all, ranges }`. Exposed for callers that want to
|
|
330
418
|
do their own widening.
|
|
331
419
|
- **`partitionByScope(items, { scopes, getFile, getLine })`** — splits a
|
package/base.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* The session base: per repository, the HEAD a session started from — the
|
|
5
|
+
* commit its first tracked file in that repo was edited on top of.
|
|
6
|
+
*
|
|
7
|
+
* scope.js narrows a check to the lines that differ from HEAD, on the
|
|
8
|
+
* assumption that nothing the session wrote has been committed yet. A
|
|
9
|
+
* session that commits before its Stop hook runs breaks that assumption:
|
|
10
|
+
* HEAD moves past its own edits, `git diff HEAD` comes back empty, and every
|
|
11
|
+
* finding on those lines reads as pre-existing. Diffing against the session
|
|
12
|
+
* base instead keeps the session's own commits in scope.
|
|
13
|
+
*
|
|
14
|
+
* The base is recorded beside the tracked-file list when a repo's first file
|
|
15
|
+
* is tracked, and read back with readSessionBases() for scopesFor's `bases`
|
|
16
|
+
* option. A Stop hook should list SESSION_BASE_FILE among the state files it
|
|
17
|
+
* cleans up, so that once a check passes, the next turn starts a fresh base
|
|
18
|
+
* from whatever HEAD is then: committed work that passed is no longer the
|
|
19
|
+
* session's to answer for.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
const fs = require('node:fs');
|
|
23
|
+
const path = require('node:path');
|
|
24
|
+
|
|
25
|
+
const SESSION_BASE_FILE = 'session-base.json';
|
|
26
|
+
|
|
27
|
+
function baseFile(dir) {
|
|
28
|
+
return path.join(dir, SESSION_BASE_FILE);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/*
|
|
32
|
+
* `{ [repoRoot]: sha }` for the session state dir `dir`; `{}` when nothing
|
|
33
|
+
* was recorded or the file is unreadable — callers then fall back to HEAD.
|
|
34
|
+
*/
|
|
35
|
+
function readSessionBases(dir) {
|
|
36
|
+
try {
|
|
37
|
+
const parsed = JSON.parse(fs.readFileSync(baseFile(dir), 'utf8'));
|
|
38
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
|
|
39
|
+
const bases = {};
|
|
40
|
+
for (const [root, sha] of Object.entries(parsed)) {
|
|
41
|
+
if (typeof sha === 'string' && /^[0-9a-f]{7,64}$/i.test(sha)) bases[root] = sha;
|
|
42
|
+
}
|
|
43
|
+
return bases;
|
|
44
|
+
} catch {
|
|
45
|
+
return {};
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/*
|
|
50
|
+
* Records `head` as `root`'s base unless one is already recorded: the first
|
|
51
|
+
* sighting wins, since every later one may already sit on top of the
|
|
52
|
+
* session's own commits. Returns whether anything was written.
|
|
53
|
+
*/
|
|
54
|
+
function recordSessionBase(dir, root, head) {
|
|
55
|
+
if (!root || !head) return false;
|
|
56
|
+
const bases = readSessionBases(dir);
|
|
57
|
+
if (bases[root]) return false;
|
|
58
|
+
|
|
59
|
+
bases[root] = head;
|
|
60
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
61
|
+
const tmp = `${baseFile(dir)}.${process.pid}.tmp`;
|
|
62
|
+
fs.writeFileSync(tmp, JSON.stringify(bases));
|
|
63
|
+
fs.renameSync(tmp, baseFile(dir));
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/*
|
|
68
|
+
* The recorded repo root that contains `absPath`, deepest first, or null.
|
|
69
|
+
* Lets tracking skip a git call for files in a repo that already has a base.
|
|
70
|
+
*/
|
|
71
|
+
function knownRootFor(bases, absPath) {
|
|
72
|
+
let best = null;
|
|
73
|
+
for (const root of Object.keys(bases)) {
|
|
74
|
+
const rel = path.relative(root, absPath);
|
|
75
|
+
if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) {
|
|
76
|
+
if (!best || root.length > best.length) best = root;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return best;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
module.exports = { SESSION_BASE_FILE, readSessionBases, recordSessionBase, knownRootFor };
|
package/changes.js
CHANGED
package/guard.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* The commit guard: a PreToolUse check that keeps Claude from committing
|
|
5
|
+
* files its session touched before the Stop hook has checked them.
|
|
6
|
+
*
|
|
7
|
+
* A tracked file stays on the session's list until a Stop hook's runFixLoop
|
|
8
|
+
* either passes it or gives up at the attempt cap, and cleans the list up.
|
|
9
|
+
* So "the list is non-empty" means exactly "this session has edits that no
|
|
10
|
+
* check has signed off on yet", and a commit then would put unchecked work
|
|
11
|
+
* into history and — for scope.js callers without a session base — move
|
|
12
|
+
* HEAD past the very lines the check is meant to look at.
|
|
13
|
+
*
|
|
14
|
+
* Denying the commit turns "edit and commit" into two turns: the edit ends
|
|
15
|
+
* the turn, the Stop hook runs, and a commit asked for afterwards finds the
|
|
16
|
+
* list empty and goes through. Commits only happen once checks have run,
|
|
17
|
+
* which in practice means once the user has seen the result and asked.
|
|
18
|
+
*
|
|
19
|
+
* Recognising a commit is a match on the command text, so this guards
|
|
20
|
+
* against accidents, not against a determined workaround (`sh -c`, a git
|
|
21
|
+
* alias, a script that commits). Only Claude's tool calls are gated: the
|
|
22
|
+
* user's own terminal and `!` commands never reach a PreToolUse hook.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
const { readTrackedFiles } = require('./state');
|
|
26
|
+
|
|
27
|
+
const SHELL_TOOLS = new Set(['Bash', 'PowerShell']);
|
|
28
|
+
|
|
29
|
+
/*
|
|
30
|
+
* `git`, then any global options — `-C <dir>` and `-c <key=value>` take a
|
|
31
|
+
* value, possibly quoted — then the `commit` subcommand, not `commit-tree`
|
|
32
|
+
* or `commit-graph`. Anchored to a command boundary so `echo legit commit`
|
|
33
|
+
* and `git log --grep commit` don't match.
|
|
34
|
+
*/
|
|
35
|
+
const ARG = String.raw`(?:"[^"]*"|'[^']*'|[^\s;&|()]+)`;
|
|
36
|
+
const GIT_COMMIT = new RegExp(
|
|
37
|
+
String.raw`(?:^|[\s;&|()\x60{])git(?:\.exe)?` +
|
|
38
|
+
String.raw`(?:\s+(?:-[Cc]\s+${ARG}|--?[\w-]+(?:=${ARG})?))*` +
|
|
39
|
+
String.raw`\s+commit(?![\w-])`,
|
|
40
|
+
);
|
|
41
|
+
|
|
42
|
+
// A git MCP server's commit tool: `mcp__git__git_commit`, `mcp__x__commit`.
|
|
43
|
+
const MCP_COMMIT = /^mcp__.+__(?:git_)?commit$/;
|
|
44
|
+
|
|
45
|
+
const MAX_LISTED_FILES = 10;
|
|
46
|
+
|
|
47
|
+
/*
|
|
48
|
+
* Whether this tool call creates a git commit, as far as can be told from
|
|
49
|
+
* its input.
|
|
50
|
+
*/
|
|
51
|
+
function isCommitCall(input) {
|
|
52
|
+
const tool = input?.tool_name || '';
|
|
53
|
+
if (MCP_COMMIT.test(tool)) return true;
|
|
54
|
+
if (!SHELL_TOOLS.has(tool)) return false;
|
|
55
|
+
const command = input.tool_input?.command;
|
|
56
|
+
return typeof command === 'string' && GIT_COMMIT.test(command);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function denyPayload(reason) {
|
|
60
|
+
return {
|
|
61
|
+
hookSpecificOutput: {
|
|
62
|
+
hookEventName: 'PreToolUse',
|
|
63
|
+
permissionDecision: 'deny',
|
|
64
|
+
permissionDecisionReason: reason,
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function defaultReason({ label, files }) {
|
|
70
|
+
const shown = files.slice(0, MAX_LISTED_FILES).map((file) => ` ${file}`);
|
|
71
|
+
if (files.length > MAX_LISTED_FILES)
|
|
72
|
+
shown.push(` … and ${files.length - MAX_LISTED_FILES} more`);
|
|
73
|
+
return (
|
|
74
|
+
`${label}: commit blocked. ${files.length} file(s) touched in this session have not ` +
|
|
75
|
+
`passed the end-of-turn checks yet:\n${shown.join('\n')}\n\n` +
|
|
76
|
+
'Commits wait until those checks have run, so nothing unchecked reaches history. ' +
|
|
77
|
+
'Do not try another way to commit. Finish the work and end your turn so the Stop ' +
|
|
78
|
+
'hook can check these files. If the user asked for this commit, tell them it is ' +
|
|
79
|
+
'waiting on the checks and that they can ask for it again once the turn has ended ' +
|
|
80
|
+
'cleanly. If the checks cannot run at all, say so: the user can still commit ' +
|
|
81
|
+
'from their own terminal.'
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/*
|
|
86
|
+
* The PreToolUse half: for a commit call while `listFile` still holds files
|
|
87
|
+
* — filtered by `matches`, when given — prints a deny decision and returns
|
|
88
|
+
* `{ denied: true, files }`; otherwise prints nothing and returns
|
|
89
|
+
* `{ denied: false }`. Call it before trackSessionChanges, and skip tracking
|
|
90
|
+
* when it denies: a denied call never runs, so it gets no Post event to
|
|
91
|
+
* consume the snapshot.
|
|
92
|
+
*
|
|
93
|
+
* `label` names the plugin in the message; `buildReason({ label, files })`
|
|
94
|
+
* replaces the default message entirely.
|
|
95
|
+
*/
|
|
96
|
+
function guardCommit({
|
|
97
|
+
input,
|
|
98
|
+
listFile,
|
|
99
|
+
matches,
|
|
100
|
+
label = 'ad-lfl-kit',
|
|
101
|
+
buildReason = defaultReason,
|
|
102
|
+
write = (text) => process.stdout.write(text),
|
|
103
|
+
}) {
|
|
104
|
+
if (!input || input.hook_event_name !== 'PreToolUse') return { denied: false };
|
|
105
|
+
if (!isCommitCall(input)) return { denied: false };
|
|
106
|
+
|
|
107
|
+
let files = readTrackedFiles(listFile);
|
|
108
|
+
if (typeof matches === 'function') files = files.filter((file) => matches(file));
|
|
109
|
+
if (files.length === 0) return { denied: false };
|
|
110
|
+
|
|
111
|
+
write(JSON.stringify(denyPayload(buildReason({ label, files }))));
|
|
112
|
+
return { denied: true, files };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
module.exports = { isCommitCall, guardCommit, commitDenyPayload: denyPayload };
|
package/index.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@leonardo-marziali/ad-lfl-kit",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.16.0",
|
|
4
4
|
"description": "Agentic development lint-fix-loop kit: session-scoped file tracking and a capped Stop-hook fix loop for Claude Code plugins.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"claude-code",
|
|
@@ -29,7 +29,9 @@
|
|
|
29
29
|
"state.js",
|
|
30
30
|
"changes.js",
|
|
31
31
|
"track.js",
|
|
32
|
+
"base.js",
|
|
32
33
|
"scope.js",
|
|
34
|
+
"guard.js",
|
|
33
35
|
"loop.js"
|
|
34
36
|
],
|
|
35
37
|
"engines": {
|
package/scope.js
CHANGED
|
@@ -15,6 +15,11 @@
|
|
|
15
15
|
* including the ones no PostToolUse hook ever hears about, like a `sed -i`,
|
|
16
16
|
* a formatter run from another hook, or the user's own editor.
|
|
17
17
|
*
|
|
18
|
+
* One exception: a session that commits its own work before its Stop hook
|
|
19
|
+
* runs would move HEAD past those lines and hide them. Callers that record
|
|
20
|
+
* a session base (base.js) pass it as `bases`, and each repo with a base is
|
|
21
|
+
* diffed against that commit instead of `ref`.
|
|
22
|
+
*
|
|
18
23
|
* Everything here fails OPEN. No repo, no git, an untracked path, a diff we
|
|
19
24
|
* can't parse — each resolves to "the whole file is in scope", which is
|
|
20
25
|
* exactly the behaviour callers had before this module existed. A scope we
|
|
@@ -149,6 +154,18 @@ function scopeWholeFile() {
|
|
|
149
154
|
* exotically quoted path, a binary file) is caught and scoped whole rather
|
|
150
155
|
* than mistaken for unchanged.
|
|
151
156
|
*/
|
|
157
|
+
/*
|
|
158
|
+
* The ref to diff `root` against: its session base when one was recorded
|
|
159
|
+
* and still names a commit, `ref` otherwise. A base that no longer resolves
|
|
160
|
+
* (the repo was re-created, the commit garbage-collected) falls back to
|
|
161
|
+
* `ref`, which is the behaviour from before bases existed.
|
|
162
|
+
*/
|
|
163
|
+
function refFor(root, ref, bases) {
|
|
164
|
+
const base = bases instanceof Map ? bases.get(root) : bases?.[root];
|
|
165
|
+
if (typeof base !== 'string' || !base) return ref;
|
|
166
|
+
return ok(git(['cat-file', '-e', `${base}^{commit}`], root)) ? base : ref;
|
|
167
|
+
}
|
|
168
|
+
|
|
152
169
|
function resolveRepoGroup(root, files, ref, into) {
|
|
153
170
|
const tracked = readPathSet(git(['ls-files', '-z', '--', ...files], root), root);
|
|
154
171
|
const trackedFiles = [];
|
|
@@ -202,13 +219,15 @@ function resolveRepoGroup(root, files, ref, into) {
|
|
|
202
219
|
* is in scope.
|
|
203
220
|
*/
|
|
204
221
|
function changedRangesByFile(files, options = {}) {
|
|
205
|
-
const { ref = 'HEAD' } = options;
|
|
222
|
+
const { ref = 'HEAD', bases } = options;
|
|
206
223
|
const result = new Map();
|
|
207
224
|
if (!files || files.length === 0) return result;
|
|
208
225
|
|
|
209
226
|
const { groups, outsideRepo } = groupByRepo(files);
|
|
210
227
|
for (const file of outsideRepo) result.set(file, scopeWholeFile());
|
|
211
|
-
for (const [root, group] of groups)
|
|
228
|
+
for (const [root, group] of groups) {
|
|
229
|
+
resolveRepoGroup(root, group, refFor(root, ref, bases), result);
|
|
230
|
+
}
|
|
212
231
|
|
|
213
232
|
return result;
|
|
214
233
|
}
|
|
@@ -270,10 +289,10 @@ function makeScope(file, changed, context) {
|
|
|
270
289
|
* already applied.
|
|
271
290
|
*/
|
|
272
291
|
function scopesFor(files, options = {}) {
|
|
273
|
-
const { ref = 'HEAD', context = DEFAULT_CONTEXT_LINES } = options;
|
|
292
|
+
const { ref = 'HEAD', bases, context = DEFAULT_CONTEXT_LINES } = options;
|
|
274
293
|
const scopes = new Map();
|
|
275
294
|
|
|
276
|
-
for (const [file, changed] of changedRangesByFile(files, { ref })) {
|
|
295
|
+
for (const [file, changed] of changedRangesByFile(files, { ref, bases })) {
|
|
277
296
|
scopes.set(file, makeScope(file, changed, context));
|
|
278
297
|
}
|
|
279
298
|
|
package/track.js
CHANGED
|
@@ -3,7 +3,14 @@
|
|
|
3
3
|
const fs = require('node:fs');
|
|
4
4
|
const path = require('node:path');
|
|
5
5
|
const { appendTrackedFile, agentStateDir } = require('./state');
|
|
6
|
-
const {
|
|
6
|
+
const {
|
|
7
|
+
snapshotWorkspace,
|
|
8
|
+
advanceSnapshot,
|
|
9
|
+
filesChangedSince,
|
|
10
|
+
repoRoot,
|
|
11
|
+
headOf,
|
|
12
|
+
} = require('./changes');
|
|
13
|
+
const { readSessionBases, recordSessionBase, knownRootFor } = require('./base');
|
|
7
14
|
|
|
8
15
|
/*
|
|
9
16
|
* The PostToolUse half of the loop: records the files a tool just wrote, so
|
|
@@ -84,6 +91,7 @@ function trackTouchedFile({ input, listFile, matches }) {
|
|
|
84
91
|
if (typeof matches === 'function' && !matches(absPath)) return null;
|
|
85
92
|
|
|
86
93
|
record(listFile, absPath, input.agent_id);
|
|
94
|
+
noteSessionBase(path.dirname(listFile), absPath);
|
|
87
95
|
return absPath;
|
|
88
96
|
}
|
|
89
97
|
|
|
@@ -162,7 +170,7 @@ function sweepBackgroundWindows(stateDir, now) {
|
|
|
162
170
|
const expired = now - window.openedAt >= BACKGROUND_WINDOW_MS;
|
|
163
171
|
const next = expired ? null : advanceSnapshot(window.snapshot, { now });
|
|
164
172
|
for (const changed of filesChangedSince(window.snapshot, { cwd: window.cwd })) {
|
|
165
|
-
changes.push({ file: changed, agentId: window.agentId });
|
|
173
|
+
changes.push({ file: changed, agentId: window.agentId, snapshot: window.snapshot });
|
|
166
174
|
}
|
|
167
175
|
try {
|
|
168
176
|
if (expired) fs.rmSync(file, { force: true });
|
|
@@ -237,7 +245,8 @@ function takeMarker(file) {
|
|
|
237
245
|
function toolChangedEntries({ input, stateDir, now }) {
|
|
238
246
|
const tool = input.tool_name || '';
|
|
239
247
|
const event = input.hook_event_name || 'PostToolUse';
|
|
240
|
-
const own = (files
|
|
248
|
+
const own = (files, snapshot) =>
|
|
249
|
+
files.map((file) => ({ file, agentId: input.agent_id, snapshot }));
|
|
241
250
|
|
|
242
251
|
if (event === 'PreToolUse') {
|
|
243
252
|
if (SHELL_TOOL.test(tool) && input.tool_use_id) {
|
|
@@ -262,7 +271,7 @@ function toolChangedEntries({ input, stateDir, now }) {
|
|
|
262
271
|
if (!snapshot) return changes;
|
|
263
272
|
|
|
264
273
|
const next = isBackgrounded(input) ? advanceSnapshot(snapshot, { now }) : null;
|
|
265
|
-
changes.push(...own(filesChangedSince(snapshot, { cwd: input.cwd })));
|
|
274
|
+
changes.push(...own(filesChangedSince(snapshot, { cwd: input.cwd }), snapshot));
|
|
266
275
|
if (next) openBackgroundWindow(stateDir, input, next, now);
|
|
267
276
|
return changes;
|
|
268
277
|
}
|
|
@@ -272,6 +281,30 @@ function toolChangedFiles({ input, stateDir, now = Date.now() }) {
|
|
|
272
281
|
return [...new Set(toolChangedEntries({ input, stateDir, now }).map(({ file }) => file))];
|
|
273
282
|
}
|
|
274
283
|
|
|
284
|
+
/*
|
|
285
|
+
* Records the session base (see base.js) for the repo holding `file`, if it
|
|
286
|
+
* has none yet. A shell call's own snapshot knows the HEAD from before the
|
|
287
|
+
* call ran, which matters for `edit && git commit` in one command: by the
|
|
288
|
+
* time its Post event fires HEAD already includes the edit. Anything else —
|
|
289
|
+
* an Edit-family call, which never commits, or a file in a repo the call
|
|
290
|
+
* only cd'd into — takes that repo's HEAD as it is now.
|
|
291
|
+
*/
|
|
292
|
+
function noteSessionBase(dir, file, snapshot) {
|
|
293
|
+
try {
|
|
294
|
+
const bases = readSessionBases(dir);
|
|
295
|
+
if (knownRootFor(bases, file)) return;
|
|
296
|
+
|
|
297
|
+
if (snapshot?.root && snapshot.head && knownRootFor({ [snapshot.root]: true }, file)) {
|
|
298
|
+
recordSessionBase(dir, snapshot.root, snapshot.head);
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
const root = repoRoot(path.dirname(file));
|
|
302
|
+
if (root) recordSessionBase(dir, root, headOf(root));
|
|
303
|
+
} catch {
|
|
304
|
+
// No base means scoping falls back to HEAD, as before bases existed.
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
275
308
|
/*
|
|
276
309
|
* toolChangedFiles + trackTouchedFile's bookkeeping: tracks every file the
|
|
277
310
|
* call wrote that `matches` accepts, in the session's list and (inside a
|
|
@@ -283,17 +316,18 @@ function toolChangedFiles({ input, stateDir, now = Date.now() }) {
|
|
|
283
316
|
* background command's file goes in its subagent's list only when that
|
|
284
317
|
* subagent is the one sweeping: one that has already stopped has no loop
|
|
285
318
|
* left to read it, and the session's list still gets it.
|
|
319
|
+
*
|
|
320
|
+
* It also records, beside `listFile`, the session base of each repo a
|
|
321
|
+
* tracked file sits in (see base.js), for scopesFor's `bases` option.
|
|
286
322
|
*/
|
|
287
323
|
function trackSessionChanges({ input, listFile, matches, now = Date.now() }) {
|
|
288
324
|
if (!input) return [];
|
|
289
325
|
const tracked = [];
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
stateDir: path.dirname(listFile),
|
|
293
|
-
now,
|
|
294
|
-
})) {
|
|
326
|
+
const dir = path.dirname(listFile);
|
|
327
|
+
for (const { file, agentId, snapshot } of toolChangedEntries({ input, stateDir: dir, now })) {
|
|
295
328
|
if (typeof matches === 'function' && !matches(file)) continue;
|
|
296
329
|
record(listFile, file, agentId && agentId === input.agent_id ? agentId : undefined);
|
|
330
|
+
noteSessionBase(dir, file, snapshot);
|
|
297
331
|
if (!tracked.includes(file)) tracked.push(file);
|
|
298
332
|
}
|
|
299
333
|
return tracked;
|