fapony 0.3.0 → 0.3.4
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 +87 -65
- package/fapony.ts +3 -116
- package/package.json +6 -5
- package/skill/move-to-done/SKILL.md +22 -32
- package/skill/review-pony/SKILL.md +27 -58
- package/src/adapters/cli.ts +123 -0
- package/src/adapters/hooks/compute-hint-impact.ts +107 -0
- package/src/adapters/hooks/context-data.ts +102 -0
- package/src/adapters/hooks/edit-hint.ts +195 -0
- package/src/adapters/hooks/git-autonomy.ts +178 -0
- package/src/adapters/hooks/index.ts +79 -0
- package/src/adapters/hooks/mv-guard.ts +52 -0
- package/src/adapters/hooks/read-hint.ts +383 -0
- package/src/adapters/hooks/session-start.ts +101 -0
- package/src/adapters/hooks/stop.ts +302 -0
- package/src/{mcp → adapters/mcp}/evidence.ts +2 -2
- package/src/{mcp → adapters/mcp}/primitives.ts +3 -3
- package/src/{mcp → adapters/mcp}/tools/check.ts +1 -1
- package/src/{mcp → adapters/mcp}/tools/collect.ts +1 -1
- package/src/{mcp → adapters/mcp}/tools/index.ts +0 -74
- package/src/{mcp → adapters/mcp}/tools/mem.ts +3 -3
- package/src/{mcp → adapters/mcp}/tools/report.ts +4 -4
- package/src/{mcp → adapters/mcp}/transport.ts +4 -39
- package/src/adapters/mcp/types.ts +18 -0
- package/src/{mcp → adapters/mcp}/worktree.ts +2 -2
- package/src/analyze.ts +2 -2
- package/src/conventions-seed.ts +1 -1
- package/src/core/config.ts +199 -0
- package/src/core/debt-format.ts +107 -0
- package/src/core/debt-types.ts +79 -0
- package/src/core/defaults.ts +8 -0
- package/src/core/enums.ts +34 -0
- package/src/core/format.ts +33 -0
- package/src/core/hint-log.ts +68 -0
- package/src/core/hook-helpers.ts +31 -0
- package/src/core/mem-log.ts +357 -0
- package/src/core/parse.ts +71 -0
- package/src/core/pricing.ts +217 -0
- package/src/core/safety.ts +18 -0
- package/src/core/types.ts +142 -0
- package/src/core/util.ts +105 -0
- package/src/db/store.ts +2 -2
- package/src/debt/cli.ts +1 -1
- package/src/debt/format.ts +2 -107
- package/src/debt/load.ts +1 -1
- package/src/debt/promotion.ts +1 -1
- package/src/debt/types.ts +14 -79
- package/src/digest/collect.ts +4 -3
- package/src/gate.ts +5 -5
- package/src/gates.ts +1 -1
- package/src/hook.ts +69 -1337
- package/src/init-mem.ts +58 -72
- package/src/init.ts +13 -17
- package/src/install/antigravity.ts +112 -0
- package/src/install/claude.ts +19 -123
- package/src/install/detect.ts +17 -7
- package/src/install/opencode.ts +167 -26
- package/src/install.ts +23 -7
- package/src/lint-baseline.ts +1 -2
- package/src/map.ts +29 -8
- package/src/mem/commands/plan.ts +70 -42
- package/src/mem/commands/read.ts +219 -146
- package/src/mem/index.ts +4 -13
- package/src/mem/store.ts +5 -1
- package/src/memory.ts +24 -387
- package/src/parse.ts +9 -71
- package/src/price/fetch.ts +4 -16
- package/src/price/resolve.ts +12 -213
- package/src/report/cli.ts +3 -3
- package/src/safety.ts +2 -18
- package/src/{plan-seed.ts → seed/plan-seed.ts} +18 -32
- package/src/seed/primitives.ts +60 -0
- package/src/{review-seed.ts → seed/review-seed.ts} +7 -54
- package/src/session/types.ts +14 -128
- package/src/setup.ts +1 -1
- package/src/stats/data.ts +4 -4
- package/src/telemetry.ts +3 -3
- package/src/usage/cache.ts +1 -2
- package/src/usage/cli.ts +1 -1
- package/src/usage/scan.ts +2 -1
- package/src/util.ts +10 -32
- package/src/web/html.ts +2 -33
- package/templates/SPEC.md +8 -1
- package/images/logo.png +0 -0
- package/images/logo.webp +0 -0
- package/images/logo@400.webp +0 -0
- package/images/sample.webp +0 -0
- package/images/summary.webp +0 -0
- package/src/db/defaults.ts +0 -34
- package/src/db/getters.ts +0 -35
- package/src/db/index.ts +0 -7
- package/src/db/load.ts +0 -57
- package/src/db/types.ts +0 -77
- package/src/math.ts +0 -13
- package/src/mcp/tools/verdict.ts +0 -161
- package/src/mcp/types.ts +0 -54
package/src/hook.ts
CHANGED
|
@@ -1,1337 +1,69 @@
|
|
|
1
|
-
// src/hook.ts —
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
ids?: string[];
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/**
|
|
74
|
-
* Append a hint-fire log row. Best-effort: never throws, never blocks.
|
|
75
|
-
* Uses $FAPONY_STATE_DIR when set (tests, CI), otherwise ~/.config/fapony.
|
|
76
|
-
*/
|
|
77
|
-
export function recordHintFire(row: HintFireRow): void {
|
|
78
|
-
try {
|
|
79
|
-
const dir = hintLogDir();
|
|
80
|
-
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
81
|
-
appendFileSync(
|
|
82
|
-
hintLogPath(row.worktree),
|
|
83
|
-
`${JSON.stringify(row)}\n`,
|
|
84
|
-
"utf-8",
|
|
85
|
-
);
|
|
86
|
-
} catch {
|
|
87
|
-
// best-effort — swallow
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
// --- Debt precision (PLAN-feedback-surface chunk 2) ---
|
|
92
|
-
//
|
|
93
|
-
// Reads the hint-fire log, re-runs debtForFile at HEAD for each file that
|
|
94
|
-
// received debt hints, and counts which ids are no longer flagged. This is
|
|
95
|
-
// deterministic (no proxy, no join with events) and answers: of the debt
|
|
96
|
-
// lines fapony showed, how many is the repo now clean of?
|
|
97
|
-
|
|
98
|
-
export interface HintImpact {
|
|
99
|
-
fired: number;
|
|
100
|
-
by_surface: {
|
|
101
|
-
read: number;
|
|
102
|
-
debt: number;
|
|
103
|
-
mem: number;
|
|
104
|
-
commit: number;
|
|
105
|
-
edit: number;
|
|
106
|
-
};
|
|
107
|
-
debt: { shown: number; resolved: number; unknown: number };
|
|
108
|
-
window: string | null;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
/**
|
|
112
|
-
* Compute hint-fire impact from the log. `since` is an ISO date string;
|
|
113
|
-
* omit to scan all rows. `worktree` scopes to one project's log file (the
|
|
114
|
-
* `<key>.jsonl` naming makes this a filename comparison) — omit to merge
|
|
115
|
-
* every worktree. Returns zeroed counts (not null) when there are no rows —
|
|
116
|
-
* the caller decides how to present "no data" vs "zero".
|
|
117
|
-
*/
|
|
118
|
-
export function computeHintImpact(
|
|
119
|
-
since?: string,
|
|
120
|
-
worktree?: string,
|
|
121
|
-
): HintImpact {
|
|
122
|
-
const dir = hintLogDir();
|
|
123
|
-
const impact: HintImpact = {
|
|
124
|
-
fired: 0,
|
|
125
|
-
by_surface: { read: 0, debt: 0, mem: 0, commit: 0, edit: 0 },
|
|
126
|
-
debt: { shown: 0, resolved: 0, unknown: 0 },
|
|
127
|
-
window: since ?? null,
|
|
128
|
-
};
|
|
129
|
-
|
|
130
|
-
if (!existsSync(dir)) return impact;
|
|
131
|
-
|
|
132
|
-
// Read the worktree's .jsonl when scoped, else every file in the dir.
|
|
133
|
-
let files: string[];
|
|
134
|
-
try {
|
|
135
|
-
const all = readdirSync(dir).filter((f) => f.endsWith(".jsonl"));
|
|
136
|
-
files = worktree
|
|
137
|
-
? all.filter((f) => f === `${worktreeKey(worktree)}.jsonl`)
|
|
138
|
-
: all;
|
|
139
|
-
} catch {
|
|
140
|
-
return impact;
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
// debtShown: Map<"worktree\tfile\tid", true> — unique debt ids per file.
|
|
144
|
-
const debtShown = new Map<string, true>();
|
|
145
|
-
// debtByFile: Map<"worktree\tfile", string[]> — all ids shown per file.
|
|
146
|
-
const debtByFile = new Map<string, string[]>();
|
|
147
|
-
|
|
148
|
-
for (const file of files) {
|
|
149
|
-
let content: string;
|
|
150
|
-
try {
|
|
151
|
-
content = readFileSync(join(dir, file), "utf-8");
|
|
152
|
-
} catch {
|
|
153
|
-
continue;
|
|
154
|
-
}
|
|
155
|
-
for (const line of content.split("\n")) {
|
|
156
|
-
if (!line) continue;
|
|
157
|
-
let row: HintFireRow;
|
|
158
|
-
try {
|
|
159
|
-
row = JSON.parse(line) as HintFireRow;
|
|
160
|
-
} catch {
|
|
161
|
-
continue;
|
|
162
|
-
}
|
|
163
|
-
if (since && row.ts < since) continue;
|
|
164
|
-
impact.fired++;
|
|
165
|
-
impact.by_surface[row.surface]++;
|
|
166
|
-
|
|
167
|
-
if (row.surface === "debt" && row.ids && row.file) {
|
|
168
|
-
const key = `${row.worktree}\t${row.file}`;
|
|
169
|
-
const existing = debtByFile.get(key) ?? [];
|
|
170
|
-
for (const id of row.ids) {
|
|
171
|
-
const dk = `${row.worktree}\t${row.file}\t${id}`;
|
|
172
|
-
if (!debtShown.has(dk)) {
|
|
173
|
-
debtShown.set(dk, true);
|
|
174
|
-
existing.push(id);
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
debtByFile.set(key, existing);
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
// Re-run debtForFile at HEAD for each file that had debt hints.
|
|
183
|
-
for (const [key, ids] of debtByFile) {
|
|
184
|
-
const [worktree, file] = key.split("\t");
|
|
185
|
-
const absFile = join(worktree, file);
|
|
186
|
-
let currentIds: Set<string>;
|
|
187
|
-
try {
|
|
188
|
-
if (!statSync(absFile).isFile()) {
|
|
189
|
-
// File deleted — all its debt ids are unknown.
|
|
190
|
-
impact.debt.unknown += ids.length;
|
|
191
|
-
continue;
|
|
192
|
-
}
|
|
193
|
-
const convs = debtForFile(worktree, absFile, loadConventions(worktree));
|
|
194
|
-
currentIds = new Set(convs.map((c) => c.id));
|
|
195
|
-
} catch {
|
|
196
|
-
impact.debt.unknown += ids.length;
|
|
197
|
-
continue;
|
|
198
|
-
}
|
|
199
|
-
for (const id of ids) {
|
|
200
|
-
impact.debt.shown++;
|
|
201
|
-
if (currentIds.has(id)) {
|
|
202
|
-
// still present — not resolved
|
|
203
|
-
} else {
|
|
204
|
-
impact.debt.resolved++;
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
return impact;
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
export interface RawStopPayload {
|
|
213
|
-
// Claude Code
|
|
214
|
-
cwd?: string;
|
|
215
|
-
transcript_path?: string | null;
|
|
216
|
-
stop_hook_active?: boolean;
|
|
217
|
-
// Cursor — common schema (https://cursor.com/docs/agent/hooks)
|
|
218
|
-
workspace_roots?: string[];
|
|
219
|
-
conversation_id?: string;
|
|
220
|
-
loop_count?: number;
|
|
221
|
-
status?: string;
|
|
222
|
-
// Codex — hooks contract (https://learn.chatgpt.com/docs/hooks)
|
|
223
|
-
session_id?: string;
|
|
224
|
-
model?: string;
|
|
225
|
-
permission_mode?: string;
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
export type StopClient = "claude" | "cursor" | "codex";
|
|
229
|
-
|
|
230
|
-
export interface NormalizedStopInput {
|
|
231
|
-
client: StopClient;
|
|
232
|
-
cwd: string;
|
|
233
|
-
transcriptPath: string | null;
|
|
234
|
-
stopHookActive: boolean;
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
/** UTC 'YYYY-MM-DD HH:MM:SS' — the format events.ts is written in. */
|
|
238
|
-
export function utcStamp(d: Date): string {
|
|
239
|
-
return d.toISOString().slice(0, 19).replace("T", " ");
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
/**
|
|
243
|
-
* Pure decision: block only when this session produced commits and none of
|
|
244
|
-
* them got graded. Every unknown (no git, no transcript, hook already fired)
|
|
245
|
-
* resolves to "allow" — a hook that guesses wrong must never trap the agent.
|
|
246
|
-
*
|
|
247
|
-
* PLAN-mem-mcp chunk 3: the block message now carries the commit list and the
|
|
248
|
-
* mem-log status (last row date). Both are *information*, never conditions —
|
|
249
|
-
* the block condition stays verdict-only (rule 7: the hook does not judge, it
|
|
250
|
-
* reports what is pending so the agent decides what deserves recording).
|
|
251
|
-
*/
|
|
252
|
-
export function decideStop(opts: {
|
|
253
|
-
stopHookActive: boolean;
|
|
254
|
-
worktree: string | null;
|
|
255
|
-
commits: number;
|
|
256
|
-
verdicts: number;
|
|
257
|
-
commitList?: string[];
|
|
258
|
-
memLastTs?: string | null;
|
|
259
|
-
/** Logs that exist in the repo but are out of scope from this worktree. */
|
|
260
|
-
memCandidates?: string[];
|
|
261
|
-
}): string | null {
|
|
262
|
-
if (opts.stopHookActive) return null; // already blocked once — let it end
|
|
263
|
-
if (!opts.worktree) return null;
|
|
264
|
-
if (opts.commits < 1) return null;
|
|
265
|
-
if (opts.verdicts > 0) return null;
|
|
266
|
-
|
|
267
|
-
const lines: string[] = [
|
|
268
|
-
`${opts.commits} commit(s) landed in ${opts.worktree} this session with no verdict filed.`,
|
|
269
|
-
];
|
|
270
|
-
// ≤ 5 commits listed, rest folded into "… +N more" (spec §6: ≤ 12 lines).
|
|
271
|
-
const list = opts.commitList ?? [];
|
|
272
|
-
for (const c of list.slice(0, 5)) lines.push(` ${c}`);
|
|
273
|
-
if (list.length > 5) lines.push(` … +${list.length - 5} more`);
|
|
274
|
-
if (opts.memLastTs) {
|
|
275
|
-
lines.push(
|
|
276
|
-
`mem: last row ${opts.memLastTs.slice(0, 10)} — nothing newer this session`,
|
|
277
|
-
);
|
|
278
|
-
} else if (opts.memCandidates?.length) {
|
|
279
|
-
// "nothing recorded" would be a lie: the log exists, it is just not in
|
|
280
|
-
// scope from here (monorepo — the log lives in the app dir). Say where.
|
|
281
|
-
lines.push(
|
|
282
|
-
`mem: no log in scope from ${opts.worktree} — found ` +
|
|
283
|
-
`${opts.memCandidates.join(", ")} (run mem commands from there, or --mem-dir)`,
|
|
284
|
-
);
|
|
285
|
-
} else {
|
|
286
|
-
lines.push("mem: no rows at all — nothing recorded in this project yet");
|
|
287
|
-
}
|
|
288
|
-
const runner = detectTestRunner(opts.worktree);
|
|
289
|
-
const verifyLine = runner
|
|
290
|
-
? `If you did not run \`${runner.typecheckCmd ? `${runner.typecheckCmd} and ` : ""}${runner.testCmd}\` to a real exit code, ` +
|
|
291
|
-
`the honest verdict is uncertain, not pass. `
|
|
292
|
-
: `If you did not run this repo's typecheck and test suite to a real exit code, ` +
|
|
293
|
-
`the honest verdict is uncertain, not pass. `;
|
|
294
|
-
|
|
295
|
-
lines.push(
|
|
296
|
-
`Call verdict_submit before ending: worktree must be the absolute path above, ` +
|
|
297
|
-
`regime is one of code|fix|review|plan|inquiry|test, and the note must stand alone ` +
|
|
298
|
-
`(it is read months from now with no access to this conversation). ` +
|
|
299
|
-
`Grade what actually happened — pass-family when it held up, fail if the first ` +
|
|
300
|
-
`attempt was wrong, uncertain when you could not verify it. ${verifyLine}` +
|
|
301
|
-
`What deserves a mem row (decision/bug/note) is your call — not every unit needs one.`,
|
|
302
|
-
);
|
|
303
|
-
return lines.join("\n");
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
function git(args: string[], cwd: string): string | null {
|
|
307
|
-
try {
|
|
308
|
-
const p = Bun.spawnSync(["git", ...args], {
|
|
309
|
-
cwd,
|
|
310
|
-
stdout: "pipe",
|
|
311
|
-
stderr: "pipe",
|
|
312
|
-
});
|
|
313
|
-
return p.exitCode === 0 ? p.stdout.toString().trim() : null;
|
|
314
|
-
} catch {
|
|
315
|
-
return null;
|
|
316
|
-
}
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
/**
|
|
320
|
-
* Cursor transcript location derived from the conversation id —
|
|
321
|
-
* ~/.cursor/projects/<slug>/agent-transcripts/<id>/<id>.jsonl where slug is
|
|
322
|
-
* the workspace path minus its leading "/", "/" → "-" (Claude Code's slug
|
|
323
|
-
* convention). Fallback only: a real transcript_path in the payload wins.
|
|
324
|
-
*/
|
|
325
|
-
export function cursorTranscriptPath(
|
|
326
|
-
home: string,
|
|
327
|
-
cwd: string,
|
|
328
|
-
conversationId: string,
|
|
329
|
-
): string {
|
|
330
|
-
const slug = cwd.replace(/^\//, "").replace(/\//g, "-");
|
|
331
|
-
return join(
|
|
332
|
-
home,
|
|
333
|
-
".cursor",
|
|
334
|
-
"projects",
|
|
335
|
-
slug,
|
|
336
|
-
"agent-transcripts",
|
|
337
|
-
conversationId,
|
|
338
|
-
`${conversationId}.jsonl`,
|
|
339
|
-
);
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
export function isCursorPayload(raw: RawStopPayload): boolean {
|
|
343
|
-
return (
|
|
344
|
-
Array.isArray(raw.workspace_roots) ||
|
|
345
|
-
typeof raw.conversation_id === "string"
|
|
346
|
-
);
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
/** Codex sends permission_mode and/or model — fields neither Claude nor Cursor include in Stop. */
|
|
350
|
-
export function isCodexPayload(raw: RawStopPayload): boolean {
|
|
351
|
-
return (
|
|
352
|
-
typeof raw.permission_mode === "string" ||
|
|
353
|
-
(typeof raw.model === "string" && !isCursorPayload(raw))
|
|
354
|
-
);
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
/** Field-mapping only — all three clients feed the same decideStop below. */
|
|
358
|
-
export function normalizeStopInput(
|
|
359
|
-
raw: RawStopPayload,
|
|
360
|
-
home: string,
|
|
361
|
-
): NormalizedStopInput {
|
|
362
|
-
if (isCodexPayload(raw)) {
|
|
363
|
-
// Codex: cwd is the session working directory; stop_hook_active means
|
|
364
|
-
// the hook already fired once (same semantics as Claude).
|
|
365
|
-
return {
|
|
366
|
-
client: "codex",
|
|
367
|
-
cwd: raw.cwd ?? process.cwd(),
|
|
368
|
-
transcriptPath:
|
|
369
|
-
typeof raw.transcript_path === "string" && raw.transcript_path
|
|
370
|
-
? raw.transcript_path
|
|
371
|
-
: null,
|
|
372
|
-
stopHookActive: raw.stop_hook_active === true,
|
|
373
|
-
};
|
|
374
|
-
}
|
|
375
|
-
if (isCursorPayload(raw)) {
|
|
376
|
-
const cwd = raw.workspace_roots?.[0] ?? raw.cwd ?? process.cwd();
|
|
377
|
-
let transcriptPath =
|
|
378
|
-
typeof raw.transcript_path === "string" && raw.transcript_path
|
|
379
|
-
? raw.transcript_path
|
|
380
|
-
: null;
|
|
381
|
-
if (!transcriptPath && raw.conversation_id) {
|
|
382
|
-
transcriptPath = cursorTranscriptPath(home, cwd, raw.conversation_id);
|
|
383
|
-
}
|
|
384
|
-
return {
|
|
385
|
-
client: "cursor",
|
|
386
|
-
cwd,
|
|
387
|
-
transcriptPath,
|
|
388
|
-
// loop_count counts follow-ups this hook already triggered — ≥ 1 means
|
|
389
|
-
// we already blocked once (Cursor's stop_hook_active).
|
|
390
|
-
stopHookActive: (raw.loop_count ?? 0) > 0,
|
|
391
|
-
};
|
|
392
|
-
}
|
|
393
|
-
return {
|
|
394
|
-
client: "claude",
|
|
395
|
-
cwd: raw.cwd ?? process.cwd(),
|
|
396
|
-
transcriptPath: raw.transcript_path ?? null,
|
|
397
|
-
stopHookActive: raw.stop_hook_active === true,
|
|
398
|
-
};
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
/** Claude blocks with decision:block; Cursor auto-submits as followup_message;
|
|
402
|
-
* Codex continues with decision:block + reason (continue:false would take
|
|
403
|
-
* precedence and end the turn instead — Codex Hooks, Stop section). */
|
|
404
|
-
export function stopOutput(client: StopClient, reason: string): string {
|
|
405
|
-
if (client === "cursor") return JSON.stringify({ followup_message: reason });
|
|
406
|
-
if (client === "codex") return JSON.stringify({ decision: "block", reason });
|
|
407
|
-
return JSON.stringify({ decision: "block", reason });
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
// --- Block dedupe (one block per session + worktree) ---
|
|
411
|
-
//
|
|
412
|
-
// stop_hook_active only suppresses the block that fires *immediately* after
|
|
413
|
-
// one. Every later turn that still carries ungraded commits blocks again, so
|
|
414
|
-
// a session that keeps committing gets the same paragraph 4-5 times. The
|
|
415
|
-
// first block already delivered it; the repeats add noise, not force (rule 9
|
|
416
|
-
// — the forcing happens once, and the agent that ignored it once is not
|
|
417
|
-
// persuaded by the fifth copy).
|
|
418
|
-
//
|
|
419
|
-
// Keyed by the transcript path, which is already the session identity the
|
|
420
|
-
// commit window is measured from — no session field to thread through.
|
|
421
|
-
|
|
422
|
-
const STOP_BLOCK_DIR = "stop-block";
|
|
423
|
-
|
|
424
|
-
interface StopBlockRow {
|
|
425
|
-
ts: string;
|
|
426
|
-
worktree: string;
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
/** Absolute path of a session's block log — may not exist. */
|
|
430
|
-
export function stopBlockPath(session: string): string {
|
|
431
|
-
const base =
|
|
432
|
-
process.env.FAPONY_STATE_DIR || join(homedir(), ".config", "fapony");
|
|
433
|
-
return join(base, STOP_BLOCK_DIR, `${sessionKey(session)}.jsonl`);
|
|
434
|
-
}
|
|
435
|
-
|
|
436
|
-
/**
|
|
437
|
-
* True when this session already blocked for this worktree — the caller then
|
|
438
|
-
* lets the turn end. Records the block when it has not. Every unknown (no
|
|
439
|
-
* session identity, unwritable state dir) resolves to false: a dedupe that
|
|
440
|
-
* guesses must fail towards blocking, never towards silence.
|
|
441
|
-
*/
|
|
442
|
-
export function stopBlockedBefore(
|
|
443
|
-
session: string | null,
|
|
444
|
-
worktree: string,
|
|
445
|
-
): boolean {
|
|
446
|
-
if (!session) return false;
|
|
447
|
-
const path = stopBlockPath(session);
|
|
448
|
-
try {
|
|
449
|
-
if (existsSync(path)) {
|
|
450
|
-
for (const line of readFileSync(path, "utf-8").split("\n")) {
|
|
451
|
-
if (!line) continue;
|
|
452
|
-
try {
|
|
453
|
-
if ((JSON.parse(line) as StopBlockRow).worktree === worktree) {
|
|
454
|
-
return true;
|
|
455
|
-
}
|
|
456
|
-
} catch {
|
|
457
|
-
// a torn line must not lose the rest of the log
|
|
458
|
-
}
|
|
459
|
-
}
|
|
460
|
-
}
|
|
461
|
-
const dir = join(path, "..");
|
|
462
|
-
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
463
|
-
const row: StopBlockRow = { ts: new Date().toISOString(), worktree };
|
|
464
|
-
appendFileSync(path, `${JSON.stringify(row)}\n`, "utf-8");
|
|
465
|
-
} catch {
|
|
466
|
-
return false;
|
|
467
|
-
}
|
|
468
|
-
return false;
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
/** Reads the Stop-hook JSON on stdin, prints a block decision or nothing. */
|
|
472
|
-
export async function cmdHookStop(): Promise<void> {
|
|
473
|
-
let reason: string | null = null;
|
|
474
|
-
let client: StopClient = "claude";
|
|
475
|
-
try {
|
|
476
|
-
const raw = JSON.parse(await Bun.stdin.text()) as RawStopPayload;
|
|
477
|
-
const norm = normalizeStopInput(raw, homedir());
|
|
478
|
-
client = norm.client;
|
|
479
|
-
// Cursor aborted/errored turns pass: the user said stop, or the loop
|
|
480
|
-
// died — commits from those turns are still caught at the next completed
|
|
481
|
-
// stop (the window is the conversation transcript's birthtime).
|
|
482
|
-
if (client === "cursor" && raw.status !== "completed") return;
|
|
483
|
-
// Codex: no status guard needed — Stop fires at turn end unconditionally.
|
|
484
|
-
|
|
485
|
-
const worktree = git(["rev-parse", "--show-toplevel"], norm.cwd);
|
|
486
|
-
|
|
487
|
-
// Session start = when the transcript file was created. No transcript,
|
|
488
|
-
// no window to measure — allow.
|
|
489
|
-
let since: string | null = null;
|
|
490
|
-
if (norm.transcriptPath) {
|
|
491
|
-
try {
|
|
492
|
-
since = utcStamp(statSync(norm.transcriptPath).birthtime);
|
|
493
|
-
} catch {
|
|
494
|
-
since = null;
|
|
495
|
-
}
|
|
496
|
-
}
|
|
497
|
-
|
|
498
|
-
let commits = 0;
|
|
499
|
-
let commitList: string[] = [];
|
|
500
|
-
let verdicts = 0;
|
|
501
|
-
let memLastTs: string | null = null;
|
|
502
|
-
let memCandidates: string[] = [];
|
|
503
|
-
if (worktree && since) {
|
|
504
|
-
const log = git(
|
|
505
|
-
["log", "--since", `${since} +0000`, "--format=%h %s"],
|
|
506
|
-
norm.cwd,
|
|
507
|
-
);
|
|
508
|
-
commitList = log ? log.split("\n").filter(Boolean) : [];
|
|
509
|
-
commits = commitList.length;
|
|
510
|
-
if (commits > 0) {
|
|
511
|
-
const db = openDb();
|
|
512
|
-
const row = db
|
|
513
|
-
.query(
|
|
514
|
-
`SELECT COUNT(*) AS n FROM events e JOIN runs r ON r.id = e.run_id
|
|
515
|
-
WHERE e.kind = 'gate' AND r.worktree = ? AND e.ts >= ?`,
|
|
516
|
-
)
|
|
517
|
-
.get(worktree, since) as { n: number } | null;
|
|
518
|
-
verdicts = row?.n ?? 0;
|
|
519
|
-
// Informational only — read-only, degrade silently (mem status never
|
|
520
|
-
// becomes a block condition, rule 7).
|
|
521
|
-
try {
|
|
522
|
-
const mem = readMemLog(worktree);
|
|
523
|
-
memLastTs = mem.rows[0]?.ts ?? null;
|
|
524
|
-
if (!memLastTs)
|
|
525
|
-
memCandidates = whereMemDir(worktree).candidates ?? [];
|
|
526
|
-
} catch {
|
|
527
|
-
memLastTs = null;
|
|
528
|
-
}
|
|
529
|
-
}
|
|
530
|
-
}
|
|
531
|
-
|
|
532
|
-
reason = decideStop({
|
|
533
|
-
stopHookActive: norm.stopHookActive,
|
|
534
|
-
worktree: since ? worktree : null,
|
|
535
|
-
commits,
|
|
536
|
-
verdicts,
|
|
537
|
-
commitList,
|
|
538
|
-
memLastTs,
|
|
539
|
-
memCandidates,
|
|
540
|
-
});
|
|
541
|
-
// Already blocked for this worktree in this session — say it once.
|
|
542
|
-
if (
|
|
543
|
-
reason &&
|
|
544
|
-
worktree &&
|
|
545
|
-
stopBlockedBefore(norm.transcriptPath, worktree)
|
|
546
|
-
) {
|
|
547
|
-
reason = null;
|
|
548
|
-
}
|
|
549
|
-
} catch {
|
|
550
|
-
reason = null; // any failure = allow the turn to end
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
if (reason) console.log(stopOutput(client, reason));
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
// --- Session start (kickoff as context, not as a thing to remember) ---
|
|
557
|
-
//
|
|
558
|
-
// `fapony mem kickoff` is the one command that pays for itself at session
|
|
559
|
-
// open — what is open, what is stale, what the last rows touched. Asking the
|
|
560
|
-
// agent to run it measured as not enough (rule 9), and an MCP tool would pay
|
|
561
|
-
// schema rent in every session of every client to save one bash round
|
|
562
|
-
// (rule 13). A SessionStart hook is neither: zero rent, and it fires whether
|
|
563
|
-
// or not anyone remembers.
|
|
564
|
-
//
|
|
565
|
-
// Runs the CLI in a subprocess rather than calling cmdKickoff: kickoff prints
|
|
566
|
-
// to stdout and exits on bad input, both of which would be this hook's stdout.
|
|
567
|
-
|
|
568
|
-
/** Cap on injected context — kickoff is short, a broken repo's output is not. */
|
|
569
|
-
export const SESSION_START_MAX_CHARS = 4_000;
|
|
570
|
-
|
|
571
|
-
const TRUNCATED = "… truncated — run `fapony mem kickoff` for the rest";
|
|
572
|
-
|
|
573
|
-
/** Trim to whole lines, keeping the marker's line boundary intact. */
|
|
574
|
-
function headLines(text: string, max: number): string {
|
|
575
|
-
const cut = text.slice(0, max);
|
|
576
|
-
const lastNl = cut.lastIndexOf("\n");
|
|
577
|
-
return (lastNl > 0 ? cut.slice(0, lastNl) : cut).trimEnd();
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
/**
|
|
581
|
-
* Trim to whole lines within the cap, with an honest truncation marker.
|
|
582
|
-
*
|
|
583
|
-
* "## next up" is kickoff's last section and its most actionable one, so a
|
|
584
|
-
* plain head-cut drops exactly the part worth injecting in a repo with a long
|
|
585
|
-
* open list (measured here: 92 rows, the cut landed mid-history). Keep it and
|
|
586
|
-
* spend the rest of the budget on the head.
|
|
587
|
-
*/
|
|
588
|
-
export function capContext(
|
|
589
|
-
text: string,
|
|
590
|
-
max = SESSION_START_MAX_CHARS,
|
|
591
|
-
): string {
|
|
592
|
-
if (text.length <= max) return text;
|
|
593
|
-
const at = text.lastIndexOf("\n## next up");
|
|
594
|
-
const tail = at > 0 ? text.slice(at).trimEnd() : "";
|
|
595
|
-
if (tail && tail.length < max / 2) {
|
|
596
|
-
return `${headLines(text, max - tail.length)}\n${TRUNCATED}\n${tail}`;
|
|
597
|
-
}
|
|
598
|
-
return `${headLines(text, max)}\n${TRUNCATED}`;
|
|
599
|
-
}
|
|
600
|
-
|
|
601
|
-
/** SessionStart hook: inject `fapony mem kickoff` output as context. */
|
|
602
|
-
export async function cmdHookSessionStart(): Promise<void> {
|
|
603
|
-
try {
|
|
604
|
-
const raw = JSON.parse(await Bun.stdin.text()) as { cwd?: string };
|
|
605
|
-
const cwd = raw.cwd ?? process.cwd();
|
|
606
|
-
// No mem log in scope = nothing to say. Silence beats "no rows yet".
|
|
607
|
-
if (!whereMemDir(cwd).dir) return;
|
|
608
|
-
const p = Bun.spawnSync([process.execPath, Bun.main, "mem", "kickoff"], {
|
|
609
|
-
cwd,
|
|
610
|
-
stdout: "pipe",
|
|
611
|
-
stderr: "pipe",
|
|
612
|
-
});
|
|
613
|
-
const out = p.stdout.toString().trim();
|
|
614
|
-
if (p.exitCode !== 0 || !out) return;
|
|
615
|
-
console.log(
|
|
616
|
-
JSON.stringify({
|
|
617
|
-
hookSpecificOutput: {
|
|
618
|
-
hookEventName: "SessionStart",
|
|
619
|
-
additionalContext: capContext(out),
|
|
620
|
-
},
|
|
621
|
-
}),
|
|
622
|
-
);
|
|
623
|
-
} catch {
|
|
624
|
-
// any failure = no context, never a broken session start
|
|
625
|
-
}
|
|
626
|
-
}
|
|
627
|
-
|
|
628
|
-
// --- Read hint (PreToolUse annotate — never block, never dedupe) ---
|
|
629
|
-
//
|
|
630
|
-
// Reading a large file in full is where an agent spends tokens without
|
|
631
|
-
// noticing — warnings in a skill were never enough (same principle as the
|
|
632
|
-
// Stop hook: speak while it is spending). But this hook **annotates only**:
|
|
633
|
-
// no permissionDecision, no "already read" dedupe — context compaction makes
|
|
634
|
-
// "already read" false, and a hook that guesses wrong and traps the agent is
|
|
635
|
-
// worse than no hook (the rule from the original hook.ts) — annotate cannot
|
|
636
|
-
// trap by construction, the worst cost of a miss is one unnecessary line
|
|
637
|
-
//
|
|
638
|
-
// The text is facts only (line count + command + a one-time measurement), not
|
|
639
|
-
// a per-file estimate — guessing tokens is dressing up as data, against
|
|
640
|
-
// "facts only"
|
|
641
|
-
|
|
642
|
-
/** Below this size a full read is already cheap — stay silent. */
|
|
643
|
-
export const READ_HINT_MIN_BYTES = 24_000;
|
|
644
|
-
/** A caller-chosen limit below this is a bounded read — already cheap. */
|
|
645
|
-
export const READ_HINT_MIN_LIMIT = 300;
|
|
646
|
-
/** One-time measurement (2026-09-17, this repo): 5 files / 2,146 lines ≈ 3.7KB out. */
|
|
647
|
-
const READ_HINT_MEASURED = "measured ~3.7KB output on a 2,146-line file";
|
|
648
|
-
|
|
649
|
-
export interface ReadHintInput {
|
|
650
|
-
filePath: unknown;
|
|
651
|
-
offset?: unknown;
|
|
652
|
-
limit?: unknown;
|
|
653
|
-
cwd: string;
|
|
654
|
-
}
|
|
655
|
-
|
|
656
|
-
/**
|
|
657
|
-
* Factual one-liner for a full-file read of a large source file, or null.
|
|
658
|
-
* Every unknown (no path, non-source ext, small file, bounded read, no git
|
|
659
|
-
* repo, stat/read failure) resolves to null — a hint must never fire on a
|
|
660
|
-
* guess. Fast path is statSync only; the file is read just to count lines,
|
|
661
|
-
* and only after the size threshold passed.
|
|
662
|
-
*/
|
|
663
|
-
export function readHintFor(opts: ReadHintInput): string | null {
|
|
664
|
-
try {
|
|
665
|
-
if (typeof opts.filePath !== "string" || opts.filePath === "") return null;
|
|
666
|
-
const dot = opts.filePath.lastIndexOf(".");
|
|
667
|
-
// SCAN_EXTS keys carry the dot (".ts") — slice from the dot itself.
|
|
668
|
-
if (dot < 0 || !SCAN_EXTS.has(opts.filePath.slice(dot))) return null;
|
|
669
|
-
const limit = typeof opts.limit === "number" ? opts.limit : null;
|
|
670
|
-
if (limit !== null && limit < READ_HINT_MIN_LIMIT) return null;
|
|
671
|
-
const st = statSync(opts.filePath);
|
|
672
|
-
if (!st.isFile() || st.size < READ_HINT_MIN_BYTES) return null;
|
|
673
|
-
// review-seed is a git command — outside a repo the hint would lie.
|
|
674
|
-
const git = Bun.spawnSync(["git", "rev-parse", "--show-toplevel"], {
|
|
675
|
-
cwd: opts.cwd,
|
|
676
|
-
stdout: "pipe",
|
|
677
|
-
stderr: "pipe",
|
|
678
|
-
});
|
|
679
|
-
if (git.exitCode !== 0) return null;
|
|
680
|
-
const lines = readFileSync(opts.filePath, "utf-8").split("\n").length;
|
|
681
|
-
// The hint feeds a command line — inside the worktree show the clean
|
|
682
|
-
// relative path, outside it relative() climbs dots, show absolute.
|
|
683
|
-
const rel = relative(opts.cwd, opts.filePath);
|
|
684
|
-
const shown = rel.startsWith("..") ? opts.filePath : rel;
|
|
685
|
-
return (
|
|
686
|
-
`fapony: ${shown} is ${lines} lines — review-seed --files ${shown} ` +
|
|
687
|
-
`returns exports with line numbers, importers, and signatures first ` +
|
|
688
|
-
`(${READ_HINT_MEASURED}; skill /lookup-before-edit has the routine)`
|
|
689
|
-
);
|
|
690
|
-
} catch {
|
|
691
|
-
return null;
|
|
692
|
-
}
|
|
693
|
-
}
|
|
694
|
-
|
|
695
|
-
// --- Re-read tracking (mtime heuristic — annotate only) ---
|
|
696
|
-
//
|
|
697
|
-
// The size hint above fires on almost nothing real: measured 2026-09-20 over
|
|
698
|
-
// 28,151 read parts across every project, only 2.3% had fileSize>=24KB with a
|
|
699
|
-
// full bound, while 55.5% of read context came from files under 24KB and 19.5%
|
|
700
|
-
// from re-reading a path already read this session (39.2% of context sits in
|
|
701
|
-
// (session,path) pairs read >=2x). The cost is repetition, not one big file —
|
|
702
|
-
// so the gate here is not size, it is "same file, unchanged, again".
|
|
703
|
-
//
|
|
704
|
-
// mtime is the whole mechanism: unchanged mtime since the previous read in
|
|
705
|
-
// this session = the same bytes = annotate; mtime moved = someone edited it =
|
|
706
|
-
// new content = silent. No Edit/Grep tracking — mtime already answers "did it
|
|
707
|
-
// change", so no tool-sequence tagging is needed.
|
|
708
|
-
//
|
|
709
|
-
// Log lives beside hint-log but is separate — hint-log counts fires, this
|
|
710
|
-
// records reads keyed by session (one file per session, so a hint never leaks
|
|
711
|
-
// into the next session / rule 11). Same contract as the size hint: annotate
|
|
712
|
-
// only, never block, every unknown → silent, best-effort. Called at the caller
|
|
713
|
-
// only, never inside a pure function (test pollution — same reason
|
|
714
|
-
// recordHintFire is caller-side).
|
|
715
|
-
|
|
716
|
-
const READ_TRACK_DIR = "read-track";
|
|
717
|
-
|
|
718
|
-
export interface ReadTrackRow {
|
|
719
|
-
ts: string;
|
|
720
|
-
path: string;
|
|
721
|
-
mtime: number;
|
|
722
|
-
}
|
|
723
|
-
|
|
724
|
-
/** Filename key for a session — basename of a transcript path or a raw id. */
|
|
725
|
-
export function sessionKey(session: string): string {
|
|
726
|
-
const base = basename(session).replace(/\.[^.]+$/, "");
|
|
727
|
-
return base.replace(/[^A-Za-z0-9_-]/g, "-") || "unknown";
|
|
728
|
-
}
|
|
729
|
-
|
|
730
|
-
/** Directory holding one read log per session. */
|
|
731
|
-
function readTrackDir(): string {
|
|
732
|
-
const base =
|
|
733
|
-
process.env.FAPONY_STATE_DIR || join(homedir(), ".config", "fapony");
|
|
734
|
-
return join(base, READ_TRACK_DIR);
|
|
735
|
-
}
|
|
736
|
-
|
|
737
|
-
/** Absolute path of a session's read log — may not exist. */
|
|
738
|
-
export function readTrackPath(session: string): string {
|
|
739
|
-
return join(readTrackDir(), `${sessionKey(session)}.jsonl`);
|
|
740
|
-
}
|
|
741
|
-
|
|
742
|
-
function readTrackRows(session: string): ReadTrackRow[] {
|
|
743
|
-
const p = readTrackPath(session);
|
|
744
|
-
if (!existsSync(p)) return [];
|
|
745
|
-
const rows: ReadTrackRow[] = [];
|
|
746
|
-
for (const line of readFileSync(p, "utf-8").split("\n")) {
|
|
747
|
-
if (!line) continue;
|
|
748
|
-
try {
|
|
749
|
-
const r = JSON.parse(line) as ReadTrackRow;
|
|
750
|
-
if (typeof r.path === "string" && typeof r.mtime === "number") {
|
|
751
|
-
rows.push(r);
|
|
752
|
-
}
|
|
753
|
-
} catch {
|
|
754
|
-
// a torn line must not lose the rest of the log
|
|
755
|
-
}
|
|
756
|
-
}
|
|
757
|
-
return rows;
|
|
758
|
-
}
|
|
759
|
-
|
|
760
|
-
function appendReadTrackRow(session: string, row: ReadTrackRow): void {
|
|
761
|
-
const dir = readTrackDir();
|
|
762
|
-
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
763
|
-
appendFileSync(readTrackPath(session), `${JSON.stringify(row)}\n`, "utf-8");
|
|
764
|
-
}
|
|
765
|
-
|
|
766
|
-
export interface RereadHintInput {
|
|
767
|
-
filePath: unknown;
|
|
768
|
-
offset?: unknown;
|
|
769
|
-
limit?: unknown;
|
|
770
|
-
cwd: string;
|
|
771
|
-
/** Session identity — transcript path (Claude) or session id (OpenCode). */
|
|
772
|
-
session?: unknown;
|
|
773
|
-
}
|
|
774
|
-
|
|
775
|
-
/**
|
|
776
|
-
* Annotate a full-file read of a path already read this session whose mtime
|
|
777
|
-
* has not moved, or null. Records every full read, so the returned count is
|
|
778
|
-
* the number of prior reads. Every unknown (kill switch on, no session, no
|
|
779
|
-
* path, bounded read, partial offset, missing file, read/write failure)
|
|
780
|
-
* resolves to null — a hint must never fire on a guess.
|
|
781
|
-
*/
|
|
782
|
-
export function rereadHintFor(opts: RereadHintInput): string | null {
|
|
783
|
-
try {
|
|
784
|
-
if (process.env.FAPONY_NO_REREAD_HINT === "1") return null;
|
|
785
|
-
if (typeof opts.session !== "string" || opts.session === "") return null;
|
|
786
|
-
if (typeof opts.filePath !== "string" || opts.filePath === "") return null;
|
|
787
|
-
// A bounded/partial read is already cheap — same line the size hint draws.
|
|
788
|
-
const offset = typeof opts.offset === "number" ? opts.offset : null;
|
|
789
|
-
if (offset !== null && offset !== 0) return null;
|
|
790
|
-
const limit = typeof opts.limit === "number" ? opts.limit : null;
|
|
791
|
-
if (limit !== null && limit < READ_HINT_MIN_LIMIT) return null;
|
|
792
|
-
|
|
793
|
-
const abs = (() => {
|
|
794
|
-
const p = opts.filePath.startsWith("/")
|
|
795
|
-
? opts.filePath
|
|
796
|
-
: join(opts.cwd, opts.filePath);
|
|
797
|
-
try {
|
|
798
|
-
return realpathSync(p);
|
|
799
|
-
} catch {
|
|
800
|
-
return resolve(p);
|
|
801
|
-
}
|
|
802
|
-
})();
|
|
803
|
-
const st = statSync(abs);
|
|
804
|
-
if (!st.isFile()) return null;
|
|
805
|
-
const mtime = Math.round(st.mtimeMs);
|
|
806
|
-
|
|
807
|
-
const prior = readTrackRows(opts.session).filter((r) => r.path === abs);
|
|
808
|
-
const last = prior.at(-1);
|
|
809
|
-
appendReadTrackRow(opts.session, {
|
|
810
|
-
ts: new Date().toISOString(),
|
|
811
|
-
path: abs,
|
|
812
|
-
mtime,
|
|
813
|
-
});
|
|
814
|
-
if (!last || last.mtime !== mtime) return null;
|
|
815
|
-
|
|
816
|
-
// The hint feeds the agent's context — show the path *it* passed, relative
|
|
817
|
-
// to its own cwd, so a symlinked cwd (macOS /var → /private/var) does not
|
|
818
|
-
// turn a clean relative path into a resolved absolute one.
|
|
819
|
-
const rel = relative(opts.cwd, opts.filePath);
|
|
820
|
-
const shown = rel.startsWith("..") ? opts.filePath : rel;
|
|
821
|
-
return (
|
|
822
|
-
`fapony: already read ${shown} ${prior.length}\u00d7 this session — ` +
|
|
823
|
-
`content unchanged since the last read (mtime), grep the line range ` +
|
|
824
|
-
`you need instead of re-reading it`
|
|
825
|
-
);
|
|
826
|
-
} catch {
|
|
827
|
-
return null;
|
|
828
|
-
}
|
|
829
|
-
}
|
|
830
|
-
|
|
831
|
-
// --- Edit hint (PreToolUse annotate — importer count + once-per-session dedupe) ---
|
|
832
|
-
//
|
|
833
|
-
// Editing a file that has importers can silently break its consumers (measured:
|
|
834
|
-
// 17.9% of changed nodes over 30 commits had a 1-hop blast radius; ~12-16% of
|
|
835
|
-
// all-time fail rows were producer/consumer mismatches). The hint is a fact —
|
|
836
|
-
// the importer count plus the review-seed command that lists them — never a
|
|
837
|
-
// judgment about whether the edit is safe, and never a block.
|
|
838
|
-
//
|
|
839
|
-
// Dedupe is per (session, file): the first edit to a file fires, repeats stay
|
|
840
|
-
// silent. The track log reuses the read-track session mechanism (sessionKey,
|
|
841
|
-
// one jsonl per session) but lives in its own dir — sharing read-track's file
|
|
842
|
-
// would make an Edit look like a Read and falsely trip the re-read hint. Like
|
|
843
|
-
// rereadHintFor the track write happens inside this function (the caller-side
|
|
844
|
-
// rule covers recordHintFire, not dedupe state); unlike it there is no mtime
|
|
845
|
-
// comparison — an edit that moves mtime is still the same file in the same
|
|
846
|
-
// session, and repeating the count buys nothing.
|
|
847
|
-
|
|
848
|
-
const EDIT_TRACK_DIR = "edit-track";
|
|
849
|
-
|
|
850
|
-
export interface EditTrackRow {
|
|
851
|
-
ts: string;
|
|
852
|
-
path: string;
|
|
853
|
-
}
|
|
854
|
-
|
|
855
|
-
/** Directory holding one edit log per session. */
|
|
856
|
-
function editTrackDir(): string {
|
|
857
|
-
const base =
|
|
858
|
-
process.env.FAPONY_STATE_DIR || join(homedir(), ".config", "fapony");
|
|
859
|
-
return join(base, EDIT_TRACK_DIR);
|
|
860
|
-
}
|
|
861
|
-
|
|
862
|
-
/** Absolute path of a session's edit log — may not exist. */
|
|
863
|
-
export function editTrackPath(session: string): string {
|
|
864
|
-
return join(editTrackDir(), `${sessionKey(session)}.jsonl`);
|
|
865
|
-
}
|
|
866
|
-
|
|
867
|
-
function editTrackPaths(session: string): Set<string> {
|
|
868
|
-
const p = editTrackPath(session);
|
|
869
|
-
if (!existsSync(p)) return new Set();
|
|
870
|
-
const out = new Set<string>();
|
|
871
|
-
for (const line of readFileSync(p, "utf-8").split("\n")) {
|
|
872
|
-
if (!line) continue;
|
|
873
|
-
try {
|
|
874
|
-
const r = JSON.parse(line) as EditTrackRow;
|
|
875
|
-
if (typeof r.path === "string") out.add(r.path);
|
|
876
|
-
} catch {
|
|
877
|
-
// a torn line must not lose the rest of the log
|
|
878
|
-
}
|
|
879
|
-
}
|
|
880
|
-
return out;
|
|
881
|
-
}
|
|
882
|
-
|
|
883
|
-
function appendEditTrackRow(session: string, row: EditTrackRow): void {
|
|
884
|
-
const dir = editTrackDir();
|
|
885
|
-
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
886
|
-
appendFileSync(editTrackPath(session), `${JSON.stringify(row)}\n`, "utf-8");
|
|
887
|
-
}
|
|
888
|
-
|
|
889
|
-
export interface EditHintInput {
|
|
890
|
-
filePath: unknown;
|
|
891
|
-
cwd: string;
|
|
892
|
-
/**
|
|
893
|
-
* Session identity — transcript path (Claude) or session id. Without it the
|
|
894
|
-
* hint still fires (the importer fact holds) but cannot dedupe.
|
|
895
|
-
*/
|
|
896
|
-
session?: unknown;
|
|
897
|
-
}
|
|
898
|
-
|
|
899
|
-
/**
|
|
900
|
-
* Factual one-liner for editing a source file that has importers, or null.
|
|
901
|
-
* Every unknown (no path, non-source ext, new/unsaved file, outside the
|
|
902
|
-
* worktree, no git repo, graph failure) resolves to null — a hint must never
|
|
903
|
-
* fire on a guess. Files with importers are checked before the dedupe log is
|
|
904
|
-
* touched, so a file nobody imports never writes a track row.
|
|
905
|
-
*/
|
|
906
|
-
export function editHintFor(opts: EditHintInput): string | null {
|
|
907
|
-
try {
|
|
908
|
-
if (typeof opts.filePath !== "string" || opts.filePath === "") return null;
|
|
909
|
-
const dot = opts.filePath.lastIndexOf(".");
|
|
910
|
-
// SCAN_EXTS keys carry the dot (".ts") — slice from the dot itself.
|
|
911
|
-
if (dot < 0 || !SCAN_EXTS.has(opts.filePath.slice(dot))) return null;
|
|
912
|
-
// review-seed is a git command — outside a repo the hint would lie.
|
|
913
|
-
const git = Bun.spawnSync(["git", "rev-parse", "--show-toplevel"], {
|
|
914
|
-
cwd: opts.cwd,
|
|
915
|
-
stdout: "pipe",
|
|
916
|
-
stderr: "pipe",
|
|
917
|
-
});
|
|
918
|
-
if (git.exitCode !== 0) return null;
|
|
919
|
-
// macOS /var → /private/var: normalize both sides before comparing.
|
|
920
|
-
const worktree = realpathSync(git.stdout.toString().trim());
|
|
921
|
-
const abs = (() => {
|
|
922
|
-
const p = opts.filePath.startsWith("/")
|
|
923
|
-
? opts.filePath
|
|
924
|
-
: join(opts.cwd, opts.filePath);
|
|
925
|
-
try {
|
|
926
|
-
return realpathSync(p);
|
|
927
|
-
} catch {
|
|
928
|
-
return null; // new file — nothing imports it yet
|
|
929
|
-
}
|
|
930
|
-
})();
|
|
931
|
-
if (!abs) return null;
|
|
932
|
-
const rel = relative(worktree, abs).split(sep).join("/");
|
|
933
|
-
if (rel.startsWith("..") || rel === "") return null;
|
|
934
|
-
|
|
935
|
-
const importers = buildGraphCached(worktree).dependents.get(rel);
|
|
936
|
-
if (!importers || importers.size === 0) return null;
|
|
937
|
-
|
|
938
|
-
if (typeof opts.session === "string" && opts.session !== "") {
|
|
939
|
-
if (editTrackPaths(opts.session).has(abs)) return null;
|
|
940
|
-
appendEditTrackRow(opts.session, {
|
|
941
|
-
ts: new Date().toISOString(),
|
|
942
|
-
path: abs,
|
|
943
|
-
});
|
|
944
|
-
}
|
|
945
|
-
|
|
946
|
-
const n = importers.size;
|
|
947
|
-
return (
|
|
948
|
-
`fapony: ${rel} has ${n} importer${n === 1 ? "" : "s"} — ` +
|
|
949
|
-
`review-seed --files ${rel} lists them (add --callers <export> for one ` +
|
|
950
|
-
`export's callers); check before changing its shape (skill /lookup-before-edit)`
|
|
951
|
-
);
|
|
952
|
-
} catch {
|
|
953
|
-
return null;
|
|
954
|
-
}
|
|
955
|
-
}
|
|
956
|
-
|
|
957
|
-
// --- Commit hint (tool.execute.after — annotate only, never block) ---
|
|
958
|
-
//
|
|
959
|
-
// OpenCode has no Stop hook (Cursor does — see cursor.ts hook-stop wiring)
|
|
960
|
-
// so it cannot block a turn; instead it appends an annotate to the bash tool
|
|
961
|
-
// output whenever there is a git commit with no verdict pending. It is the
|
|
962
|
-
// same kind of nudge as the read hint: no block, no dedupe, every unknown →
|
|
963
|
-
// silent · called from the opencode plugin by direct import (like
|
|
964
|
-
// readHintFor), no CLI subcommand because no client needs it as a subprocess
|
|
965
|
-
// (Cursor uses its own hook-stop instead)
|
|
966
|
-
//
|
|
967
|
-
// The text is facts only (commit list + verdict status), not an estimate
|
|
968
|
-
|
|
969
|
-
/** Below this number of commits, the hint is unnecessary noise. */
|
|
970
|
-
export const COMMIT_HINT_MIN_COMMITS = 1;
|
|
971
|
-
/** Cap commits shown in the hint message. */
|
|
972
|
-
const COMMIT_HINT_MAX_LIST = 5;
|
|
973
|
-
|
|
974
|
-
export interface CommitHintInput {
|
|
975
|
-
command: unknown;
|
|
976
|
-
cwd: string;
|
|
977
|
-
}
|
|
978
|
-
|
|
979
|
-
/**
|
|
980
|
-
* Nudge for bash commands containing `git commit` that produced
|
|
981
|
-
* ungraded commits. Returns a one-to-two line hint string, or null
|
|
982
|
-
* when there is nothing to nudge about (already graded, no commits,
|
|
983
|
-
* not a git commit command, not a git repo, any failure).
|
|
984
|
-
*
|
|
985
|
-
* Every unknown resolves to null — a hint must never fire on a
|
|
986
|
-
* guess. The work is cheap: one git rev-parse + one git log + one
|
|
987
|
-
* SQLite count.
|
|
988
|
-
*/
|
|
989
|
-
export function commitHintFor(opts: CommitHintInput): string | null {
|
|
990
|
-
try {
|
|
991
|
-
if (typeof opts.command !== "string" || opts.command === "") return null;
|
|
992
|
-
// Only fire on git commit commands — not `git push`, `git pull`, etc.
|
|
993
|
-
if (!/\bgit\s+commit\b/.test(opts.command)) return null;
|
|
994
|
-
|
|
995
|
-
const worktree = git(["rev-parse", "--show-toplevel"], opts.cwd);
|
|
996
|
-
if (!worktree) return null;
|
|
997
|
-
|
|
998
|
-
// Window = commits since the worktree's last verdict, not "does a
|
|
999
|
-
// verdict exist anywhere in its history" — a worktree that earned one
|
|
1000
|
-
// verdict months ago must still nudge on every commit made since, the
|
|
1001
|
-
// same way cmdHookStop windows on `e.ts >= since` (session start) rather
|
|
1002
|
-
// than "any verdict this worktree has ever had".
|
|
1003
|
-
const db = openDb();
|
|
1004
|
-
const lastVerdict = db
|
|
1005
|
-
.query(
|
|
1006
|
-
`SELECT MAX(e.ts) AS ts FROM events e JOIN runs r ON r.id = e.run_id
|
|
1007
|
-
WHERE e.kind = 'gate' AND r.worktree = ?`,
|
|
1008
|
-
)
|
|
1009
|
-
.get(worktree) as { ts: string | null } | null;
|
|
1010
|
-
// git's --since is inclusive to the second, and the commit a verdict
|
|
1011
|
-
// just graded often lands in the same UTC second as the verdict itself
|
|
1012
|
-
// (verdict_submit runs right after the commit) — bump by 1s so that
|
|
1013
|
-
// commit isn't re-flagged as ungraded because of its own grade.
|
|
1014
|
-
const since = lastVerdict?.ts
|
|
1015
|
-
? utcStamp(
|
|
1016
|
-
new Date(
|
|
1017
|
-
new Date(`${lastVerdict.ts.replace(" ", "T")}Z`).getTime() + 1000,
|
|
1018
|
-
),
|
|
1019
|
-
)
|
|
1020
|
-
: null;
|
|
1021
|
-
|
|
1022
|
-
const log = since
|
|
1023
|
-
? git(["log", "--since", `${since} +0000`, "--format=%h %s"], worktree)
|
|
1024
|
-
: git(["log", "--format=%h %s"], worktree);
|
|
1025
|
-
const commitList = log ? log.split("\n").filter(Boolean) : [];
|
|
1026
|
-
if (commitList.length < COMMIT_HINT_MIN_COMMITS) return null;
|
|
1027
|
-
|
|
1028
|
-
const reason = decideStop({
|
|
1029
|
-
stopHookActive: false, // annotate-only: never "already blocked"
|
|
1030
|
-
worktree,
|
|
1031
|
-
commits: commitList.length,
|
|
1032
|
-
verdicts: 0, // every commit left in the window is, by construction, ungraded
|
|
1033
|
-
commitList: commitList.slice(0, COMMIT_HINT_MAX_LIST),
|
|
1034
|
-
});
|
|
1035
|
-
if (!reason) return null;
|
|
1036
|
-
|
|
1037
|
-
// Prefix each line with "fapony:" so it's visually distinct
|
|
1038
|
-
// from normal bash output in the agent's context.
|
|
1039
|
-
const prefixed = reason
|
|
1040
|
-
.split("\n")
|
|
1041
|
-
.map((l) => `fapony: ${l}`)
|
|
1042
|
-
.join("\n");
|
|
1043
|
-
return prefixed;
|
|
1044
|
-
} catch {
|
|
1045
|
-
return null; // any failure = no hint
|
|
1046
|
-
}
|
|
1047
|
-
}
|
|
1048
|
-
|
|
1049
|
-
/** Claude Code PreToolUse (matcher Read): stdin JSON in, additionalContext out.
|
|
1050
|
-
* No permissionDecision ever — the tool call always proceeds. */
|
|
1051
|
-
export async function cmdHookReadHint(): Promise<void> {
|
|
1052
|
-
try {
|
|
1053
|
-
const raw = JSON.parse(await Bun.stdin.text()) as {
|
|
1054
|
-
cwd?: string;
|
|
1055
|
-
transcript_path?: string;
|
|
1056
|
-
session_id?: string;
|
|
1057
|
-
tool_input?: {
|
|
1058
|
-
file_path?: unknown;
|
|
1059
|
-
offset?: unknown;
|
|
1060
|
-
limit?: unknown;
|
|
1061
|
-
};
|
|
1062
|
-
};
|
|
1063
|
-
const cwd = raw.cwd ?? process.cwd();
|
|
1064
|
-
const filePath = raw.tool_input?.file_path;
|
|
1065
|
-
// One read log per session — transcript_path is the Claude session file,
|
|
1066
|
-
// session_id the fallback when a client omits it.
|
|
1067
|
-
const session = raw.transcript_path ?? raw.session_id;
|
|
1068
|
-
const parts: string[] = [];
|
|
1069
|
-
const hint = readHintFor({
|
|
1070
|
-
filePath,
|
|
1071
|
-
offset: raw.tool_input?.offset,
|
|
1072
|
-
limit: raw.tool_input?.limit,
|
|
1073
|
-
cwd,
|
|
1074
|
-
});
|
|
1075
|
-
if (hint) parts.push(hint);
|
|
1076
|
-
const reread = rereadHintFor({
|
|
1077
|
-
filePath,
|
|
1078
|
-
offset: raw.tool_input?.offset,
|
|
1079
|
-
limit: raw.tool_input?.limit,
|
|
1080
|
-
cwd,
|
|
1081
|
-
session,
|
|
1082
|
-
});
|
|
1083
|
-
if (reread) parts.push(reread);
|
|
1084
|
-
const ctx = readContextData(filePath, cwd);
|
|
1085
|
-
if (ctx) {
|
|
1086
|
-
for (const line of [...ctx.debtLines, ...ctx.memLines]) {
|
|
1087
|
-
parts.push(line);
|
|
1088
|
-
}
|
|
1089
|
-
}
|
|
1090
|
-
if (parts.length > 0) {
|
|
1091
|
-
console.log(
|
|
1092
|
-
JSON.stringify({
|
|
1093
|
-
hookSpecificOutput: {
|
|
1094
|
-
hookEventName: "PreToolUse",
|
|
1095
|
-
additionalContext: parts.join("\n"),
|
|
1096
|
-
},
|
|
1097
|
-
}),
|
|
1098
|
-
);
|
|
1099
|
-
}
|
|
1100
|
-
|
|
1101
|
-
// --- hint-fire log (PLAN-feedback-surface chunk 1) ---
|
|
1102
|
-
// After output — best-effort, never block the hint.
|
|
1103
|
-
const rel =
|
|
1104
|
-
typeof filePath === "string"
|
|
1105
|
-
? (() => {
|
|
1106
|
-
try {
|
|
1107
|
-
const git = Bun.spawnSync(
|
|
1108
|
-
["git", "rev-parse", "--show-toplevel"],
|
|
1109
|
-
{ cwd, stdout: "pipe", stderr: "pipe" },
|
|
1110
|
-
);
|
|
1111
|
-
if (git.exitCode !== 0) return null;
|
|
1112
|
-
const wt = realpathSync(git.stdout.toString().trim());
|
|
1113
|
-
const abs = realpathSync(
|
|
1114
|
-
filePath.startsWith("/") ? filePath : join(wt, filePath),
|
|
1115
|
-
);
|
|
1116
|
-
const r = relative(wt, abs).split("\\").join("/");
|
|
1117
|
-
return r.startsWith("..") ? null : r;
|
|
1118
|
-
} catch {
|
|
1119
|
-
return null;
|
|
1120
|
-
}
|
|
1121
|
-
})()
|
|
1122
|
-
: null;
|
|
1123
|
-
const worktree = ctx?.worktree ?? null;
|
|
1124
|
-
if (worktree) {
|
|
1125
|
-
if (hint) {
|
|
1126
|
-
recordHintFire({
|
|
1127
|
-
ts: new Date().toISOString(),
|
|
1128
|
-
worktree,
|
|
1129
|
-
surface: "read",
|
|
1130
|
-
file: rel,
|
|
1131
|
-
count: 1,
|
|
1132
|
-
});
|
|
1133
|
-
}
|
|
1134
|
-
if (ctx && ctx.debtIds.length > 0) {
|
|
1135
|
-
recordHintFire({
|
|
1136
|
-
ts: new Date().toISOString(),
|
|
1137
|
-
worktree,
|
|
1138
|
-
surface: "debt",
|
|
1139
|
-
file: rel,
|
|
1140
|
-
count: ctx.debtIds.length,
|
|
1141
|
-
ids: ctx.debtIds,
|
|
1142
|
-
});
|
|
1143
|
-
}
|
|
1144
|
-
if (ctx && ctx.memLines.length > 0) {
|
|
1145
|
-
recordHintFire({
|
|
1146
|
-
ts: new Date().toISOString(),
|
|
1147
|
-
worktree,
|
|
1148
|
-
surface: "mem",
|
|
1149
|
-
file: rel,
|
|
1150
|
-
count: ctx.memLines.length,
|
|
1151
|
-
});
|
|
1152
|
-
}
|
|
1153
|
-
}
|
|
1154
|
-
} catch {
|
|
1155
|
-
// any failure = no hint; a hook must never block a read over a hint
|
|
1156
|
-
}
|
|
1157
|
-
}
|
|
1158
|
-
|
|
1159
|
-
/** Claude Code PreToolUse (matcher Edit): stdin JSON in, additionalContext out.
|
|
1160
|
-
* No permissionDecision ever — the edit always proceeds. Fires once per
|
|
1161
|
-
* (session, file); the dedupe lives inside editHintFor. */
|
|
1162
|
-
export async function cmdHookEditHint(): Promise<void> {
|
|
1163
|
-
try {
|
|
1164
|
-
const raw = JSON.parse(await Bun.stdin.text()) as {
|
|
1165
|
-
cwd?: string;
|
|
1166
|
-
transcript_path?: string;
|
|
1167
|
-
session_id?: string;
|
|
1168
|
-
tool_input?: {
|
|
1169
|
-
file_path?: unknown;
|
|
1170
|
-
};
|
|
1171
|
-
};
|
|
1172
|
-
const cwd = raw.cwd ?? process.cwd();
|
|
1173
|
-
const filePath = raw.tool_input?.file_path;
|
|
1174
|
-
// One edit log per session — same identity as the read hint.
|
|
1175
|
-
const session = raw.transcript_path ?? raw.session_id;
|
|
1176
|
-
const hint = editHintFor({ filePath, cwd, session });
|
|
1177
|
-
if (hint) {
|
|
1178
|
-
console.log(
|
|
1179
|
-
JSON.stringify({
|
|
1180
|
-
hookSpecificOutput: {
|
|
1181
|
-
hookEventName: "PreToolUse",
|
|
1182
|
-
additionalContext: hint,
|
|
1183
|
-
},
|
|
1184
|
-
}),
|
|
1185
|
-
);
|
|
1186
|
-
}
|
|
1187
|
-
|
|
1188
|
-
// --- hint-fire log (PLAN-edit-importer-hint chunk 3) ---
|
|
1189
|
-
// After output — best-effort, never block the hint.
|
|
1190
|
-
if (hint) {
|
|
1191
|
-
try {
|
|
1192
|
-
const g = Bun.spawnSync(["git", "rev-parse", "--show-toplevel"], {
|
|
1193
|
-
cwd,
|
|
1194
|
-
stdout: "pipe",
|
|
1195
|
-
stderr: "pipe",
|
|
1196
|
-
});
|
|
1197
|
-
if (g.exitCode === 0) {
|
|
1198
|
-
const worktree = realpathSync(g.stdout.toString().trim());
|
|
1199
|
-
const abs =
|
|
1200
|
-
typeof filePath === "string"
|
|
1201
|
-
? (() => {
|
|
1202
|
-
try {
|
|
1203
|
-
return realpathSync(
|
|
1204
|
-
filePath.startsWith("/")
|
|
1205
|
-
? filePath
|
|
1206
|
-
: join(worktree, filePath),
|
|
1207
|
-
);
|
|
1208
|
-
} catch {
|
|
1209
|
-
return null;
|
|
1210
|
-
}
|
|
1211
|
-
})()
|
|
1212
|
-
: null;
|
|
1213
|
-
const rel = abs
|
|
1214
|
-
? relative(worktree, abs).split("\\").join("/")
|
|
1215
|
-
: null;
|
|
1216
|
-
recordHintFire({
|
|
1217
|
-
ts: new Date().toISOString(),
|
|
1218
|
-
worktree,
|
|
1219
|
-
surface: "edit",
|
|
1220
|
-
file: rel && !rel.startsWith("..") ? rel : null,
|
|
1221
|
-
count: 1,
|
|
1222
|
-
});
|
|
1223
|
-
}
|
|
1224
|
-
} catch {
|
|
1225
|
-
// best-effort — swallow
|
|
1226
|
-
}
|
|
1227
|
-
}
|
|
1228
|
-
} catch {
|
|
1229
|
-
// any failure = no hint; a hook must never block an edit over a hint
|
|
1230
|
-
}
|
|
1231
|
-
}
|
|
1232
|
-
|
|
1233
|
-
// --- Debt + mem context (PLAN-convention-debt chunk 4) ---
|
|
1234
|
-
//
|
|
1235
|
-
// The one moment paying down debt is worth tokens is when the file is already
|
|
1236
|
-
// open — so hook-read-hint appends two things after the size hint: conventions
|
|
1237
|
-
// the file still violates (debt detector, computed live) and mem rows that
|
|
1238
|
-
// mention the file (across sessions) · **annotate only**, as before — no
|
|
1239
|
-
// block, no dedupe, every unknown → silent · combined cap 5 lines (debt 3 · mem 2)
|
|
1240
|
-
|
|
1241
|
-
const DEBT_HINT_MAX = 3;
|
|
1242
|
-
const MEM_HINT_MAX = 2;
|
|
1243
|
-
const MEM_TEXT_MAX = 120;
|
|
1244
|
-
|
|
1245
|
-
export interface ContextLineData {
|
|
1246
|
-
worktree: string;
|
|
1247
|
-
debtIds: string[];
|
|
1248
|
-
debtLines: string[];
|
|
1249
|
-
memLines: string[];
|
|
1250
|
-
}
|
|
1251
|
-
|
|
1252
|
-
/** Structured data behind readContextLines — used by cmdHookReadHint for logging. */
|
|
1253
|
-
export function readContextData(
|
|
1254
|
-
filePath: unknown,
|
|
1255
|
-
cwd: string,
|
|
1256
|
-
): ContextLineData | null {
|
|
1257
|
-
try {
|
|
1258
|
-
if (typeof filePath !== "string" || filePath === "") return null;
|
|
1259
|
-
const git = Bun.spawnSync(["git", "rev-parse", "--show-toplevel"], {
|
|
1260
|
-
cwd,
|
|
1261
|
-
stdout: "pipe",
|
|
1262
|
-
stderr: "pipe",
|
|
1263
|
-
});
|
|
1264
|
-
if (git.exitCode !== 0) return null;
|
|
1265
|
-
// macOS /var → /private/var: git reports the resolved root while callers
|
|
1266
|
-
// pass unresolved tmp paths — normalize both sides before comparing.
|
|
1267
|
-
const worktree = realpathSync(git.stdout.toString().trim());
|
|
1268
|
-
const abs = realpathSync(
|
|
1269
|
-
filePath.startsWith("/") ? filePath : join(worktree, filePath),
|
|
1270
|
-
);
|
|
1271
|
-
const rel = relative(worktree, abs).split("\\").join("/");
|
|
1272
|
-
if (rel.startsWith("..") || rel === "") return null;
|
|
1273
|
-
|
|
1274
|
-
const debtIds: string[] = [];
|
|
1275
|
-
const debtLines: string[] = [];
|
|
1276
|
-
const memLines: string[] = [];
|
|
1277
|
-
|
|
1278
|
-
// convention debt — source files only, fresh from the repo
|
|
1279
|
-
const dot = rel.lastIndexOf(".");
|
|
1280
|
-
if (dot >= 0 && SCAN_EXTS.has(rel.slice(dot))) {
|
|
1281
|
-
for (const c of debtForFile(
|
|
1282
|
-
worktree,
|
|
1283
|
-
abs,
|
|
1284
|
-
loadConventions(worktree),
|
|
1285
|
-
).slice(0, DEBT_HINT_MAX)) {
|
|
1286
|
-
debtIds.push(c.id);
|
|
1287
|
-
debtLines.push(`fapony debt: [${c.id}] ${c.rule}`);
|
|
1288
|
-
}
|
|
1289
|
-
}
|
|
1290
|
-
|
|
1291
|
-
// mem rows that are about this file
|
|
1292
|
-
const mem = readMemLog(worktree);
|
|
1293
|
-
if (mem.rows.length > 0) {
|
|
1294
|
-
const base = basename(rel);
|
|
1295
|
-
const direct: typeof mem.rows = [];
|
|
1296
|
-
const baseOnly: typeof mem.rows = [];
|
|
1297
|
-
for (const r of mem.rows) {
|
|
1298
|
-
if (r.kind === "claim" || r.kind === "release") continue;
|
|
1299
|
-
const hay = `${r.text}\n${r.spec ?? ""}\n${(r.files ?? []).join(",")}`;
|
|
1300
|
-
if ((r.files ?? []).includes(rel) || hay.includes(rel)) {
|
|
1301
|
-
direct.push(r);
|
|
1302
|
-
continue;
|
|
1303
|
-
}
|
|
1304
|
-
if (base && hay.includes(base)) baseOnly.push(r);
|
|
1305
|
-
}
|
|
1306
|
-
// A bare-basename hit is only usable when that name is unique in the
|
|
1307
|
-
// repo (24% of files share a basename — guessing would attach a row
|
|
1308
|
-
// about a DIFFERENT index.ts). The walk is paid only when a hit exists.
|
|
1309
|
-
let usableBase = baseOnly;
|
|
1310
|
-
if (baseOnly.length > 0) {
|
|
1311
|
-
const sameName = collectSourceFiles(worktree).filter(
|
|
1312
|
-
(f) => basename(f) === base,
|
|
1313
|
-
).length;
|
|
1314
|
-
if (sameName !== 1) usableBase = [];
|
|
1315
|
-
}
|
|
1316
|
-
// direct hits (files[] / full path) outrank bare-basename hits
|
|
1317
|
-
const memHits = [...direct, ...usableBase].slice(0, MEM_HINT_MAX);
|
|
1318
|
-
for (const r of memHits) {
|
|
1319
|
-
memLines.push(
|
|
1320
|
-
`fapony mem: ${r.ts.slice(0, 10)} ${r.kind} — ${r.text.slice(0, MEM_TEXT_MAX)}`,
|
|
1321
|
-
);
|
|
1322
|
-
}
|
|
1323
|
-
}
|
|
1324
|
-
return { worktree, debtIds, debtLines, memLines };
|
|
1325
|
-
} catch {
|
|
1326
|
-
return null;
|
|
1327
|
-
}
|
|
1328
|
-
}
|
|
1329
|
-
|
|
1330
|
-
export function readContextLines(filePath: unknown, cwd: string): string[] {
|
|
1331
|
-
const data = readContextData(filePath, cwd);
|
|
1332
|
-
if (!data) return [];
|
|
1333
|
-
return [...data.debtLines, ...data.memLines].slice(
|
|
1334
|
-
0,
|
|
1335
|
-
DEBT_HINT_MAX + MEM_HINT_MAX,
|
|
1336
|
-
);
|
|
1337
|
-
}
|
|
1
|
+
// src/hook.ts — re-export shim (PLAN-lib-layer chunk 3)
|
|
2
|
+
//
|
|
3
|
+
// All hook logic now lives in src/adapters/hooks/. This file re-exports
|
|
4
|
+
// everything for backwards compatibility: test/hook.test.ts,
|
|
5
|
+
// src/digest/collect.ts, and the generated OpenCode plugin all import
|
|
6
|
+
// from this path.
|
|
7
|
+
|
|
8
|
+
export {
|
|
9
|
+
COMMIT_HINT_MIN_COMMITS,
|
|
10
|
+
type CommitHintInput,
|
|
11
|
+
type ContextLineData,
|
|
12
|
+
capContext,
|
|
13
|
+
cmdHookEditHint,
|
|
14
|
+
cmdHookMvGuard,
|
|
15
|
+
cmdHookReadHint,
|
|
16
|
+
cmdHookSessionStart,
|
|
17
|
+
cmdHookStop,
|
|
18
|
+
commitHintFor,
|
|
19
|
+
computeHintImpact,
|
|
20
|
+
cursorTranscriptPath,
|
|
21
|
+
decideStop,
|
|
22
|
+
type EditHintInput,
|
|
23
|
+
type EditTrackRow,
|
|
24
|
+
editHintFor,
|
|
25
|
+
editTrackPath,
|
|
26
|
+
GIT_AUTONOMY_COMMIT_POLICY,
|
|
27
|
+
GIT_AUTONOMY_PLUGIN_FILE,
|
|
28
|
+
GIT_AUTONOMY_PLUGIN_NAME,
|
|
29
|
+
GIT_AUTONOMY_SYSTEM_REWRITES,
|
|
30
|
+
GIT_AUTONOMY_TOOL_POLICY,
|
|
31
|
+
GIT_AUTONOMY_TOOL_REWRITES,
|
|
32
|
+
type GitAutonomyRewrite,
|
|
33
|
+
type GitAutonomyStatus,
|
|
34
|
+
type GitAutonomyToolRewrite,
|
|
35
|
+
gitAutonomyStatus,
|
|
36
|
+
type HintFireRow,
|
|
37
|
+
type HintImpact,
|
|
38
|
+
hintLogDir,
|
|
39
|
+
hintLogPath,
|
|
40
|
+
hookTsMs,
|
|
41
|
+
isCodexPayload,
|
|
42
|
+
isCursorPayload,
|
|
43
|
+
mvGuardDecision,
|
|
44
|
+
type NormalizedStopInput,
|
|
45
|
+
normalizeStopInput,
|
|
46
|
+
type RawStopPayload,
|
|
47
|
+
READ_HINT_MIN_BYTES,
|
|
48
|
+
READ_HINT_MIN_LIMIT,
|
|
49
|
+
type ReadHintInput,
|
|
50
|
+
type ReadTrackRow,
|
|
51
|
+
type RereadHintInput,
|
|
52
|
+
readContextData,
|
|
53
|
+
readContextLines,
|
|
54
|
+
readHintFor,
|
|
55
|
+
readTrackPath,
|
|
56
|
+
recordHintFire,
|
|
57
|
+
rereadHintFor,
|
|
58
|
+
rewriteGitAutonomySystem,
|
|
59
|
+
rewriteGitAutonomyTool,
|
|
60
|
+
SESSION_START_MAX_CHARS,
|
|
61
|
+
type StopClient,
|
|
62
|
+
sessionKey,
|
|
63
|
+
sessionStartContext,
|
|
64
|
+
stopBlockedBefore,
|
|
65
|
+
stopBlockPath,
|
|
66
|
+
stopOutput,
|
|
67
|
+
utcStamp,
|
|
68
|
+
worktreeKey,
|
|
69
|
+
} from "./adapters/hooks/index.js";
|