codehere 2.0.2 → 2.1.0-rc.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 +46 -18
- package/bin/codehere.js +4 -1
- package/package.json +1 -1
- package/src/brain.js +245 -14
- package/src/commands.js +188 -71
- package/src/gemma.js +17 -3
- package/src/hooks.js +380 -69
- package/src/signals.js +59 -11
package/src/hooks.js
CHANGED
|
@@ -7,11 +7,11 @@ import crypto from 'node:crypto';
|
|
|
7
7
|
import { spawnSync } from 'node:child_process';
|
|
8
8
|
import {
|
|
9
9
|
findRoot, paths, readConfig, readState, writeState, session, readRules, renderDoc,
|
|
10
|
-
listDocs, git, isGitRepo, me,
|
|
11
|
-
removedAt,
|
|
10
|
+
listDocs, git, isGitRepo, me, isApproved, readApprovals, printable, commitId, statusFiles, gitHashes, noTick,
|
|
11
|
+
removedAt, expireDrafts, draftFile, saveRecord, readPlain, ownPath,
|
|
12
12
|
} from './brain.js';
|
|
13
13
|
import {
|
|
14
|
-
responseText, signature, errorLines, similarity, tamperFindings, failingTest, lowInfoPrompt, vagueFeature, testCounts, redact,
|
|
14
|
+
responseText, signature, errorLines, similarity, tamperFindings, failingTest, lowInfoPrompt, vagueFeature, testCounts, redact, plainYes,
|
|
15
15
|
} from './signals.js';
|
|
16
16
|
|
|
17
17
|
function readStdin() {
|
|
@@ -34,7 +34,9 @@ function toAgent(message) {
|
|
|
34
34
|
process.exit(2);
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
-
|
|
37
|
+
// A note for the agent that goes out only when the hook has nothing else to say.
|
|
38
|
+
let quietNote = null;
|
|
39
|
+
const quiet = () => (quietNote ? emitJson(quietNote) : process.exit(0));
|
|
38
40
|
|
|
39
41
|
// Copilot's inputs: camelCase from its own hook file, snake_case from .claude/settings.json.
|
|
40
42
|
// Map them to the names the handlers read. A failed command arrives as a successful tool
|
|
@@ -55,7 +57,7 @@ const COPILOT_EVENT = { 'session-start': 'sessionStart', prompt: 'userPromptSubm
|
|
|
55
57
|
// Whether Copilot's own hook file runs Codehere for this event.
|
|
56
58
|
function copilotFileRuns(root, event) {
|
|
57
59
|
try {
|
|
58
|
-
const hooks = JSON.parse(
|
|
60
|
+
const hooks = JSON.parse(readPlain(path.join(root, '.github/hooks/codehere.json'))).hooks;
|
|
59
61
|
return (hooks?.[COPILOT_EVENT[event]] || []).some((h) => h?.command === `codehere hook ${event} --agent copilot`);
|
|
60
62
|
} catch {
|
|
61
63
|
return false;
|
|
@@ -93,7 +95,21 @@ export async function runHook(event, agent) {
|
|
|
93
95
|
|
|
94
96
|
// ---------- SessionStart: load only human-confirmed context ----------
|
|
95
97
|
|
|
98
|
+
// How the agent learns the chores (spec 3.2). It comes after the team rules at every session start.
|
|
99
|
+
const CHORES_NOTE = [
|
|
100
|
+
'Codehere is set up in this repo. When the user asks for one of these, or Codehere asks you to offer one, run the command:',
|
|
101
|
+
'- add a team rule: codehere rule "<rule>"',
|
|
102
|
+
'- save a fix for the team: codehere lesson "<problem>" --cause "<cause>" --fix "<fix>"',
|
|
103
|
+
'- ask the team for help: codehere help "<question>"',
|
|
104
|
+
"- see teammates' help cards: codehere inbox, then codehere show <card-id>",
|
|
105
|
+
'- answer a card: codehere reply <card-id> "<answer>" (add --solved to also save it as a lesson)',
|
|
106
|
+
'- restart in a fresh session: codehere brief',
|
|
107
|
+
'rule, lesson, help and reply only print a draft. Show the user the draft exactly as printed and ask only about it. Codehere saves it if their next message is a plain yes, such as "yes" or "save it"; any other reply discards it. You never save it yourself.',
|
|
108
|
+
'Never edit files in .codehere/ yourself, and do not commit or push them; the user does that.',
|
|
109
|
+
].join('\n');
|
|
110
|
+
|
|
96
111
|
function sessionStart(root, input, agent) {
|
|
112
|
+
expireDrafts(root);
|
|
97
113
|
const state = readState(root);
|
|
98
114
|
const s = session(state, input.session_id);
|
|
99
115
|
s.transcript = input.transcript_path || s.transcript;
|
|
@@ -111,17 +127,26 @@ function sessionStart(root, input, agent) {
|
|
|
111
127
|
const out = [];
|
|
112
128
|
const rules = readRules(root);
|
|
113
129
|
if (rules.length) {
|
|
114
|
-
out.push(
|
|
130
|
+
out.push("Team rules from your team's rules file (follow them):");
|
|
115
131
|
rules.slice(0, 20).forEach((r) => out.push(`- ${r}`));
|
|
116
132
|
}
|
|
133
|
+
out.push(...(out.length ? [''] : []), CHORES_NOTE);
|
|
117
134
|
|
|
118
|
-
//
|
|
119
|
-
|
|
120
|
-
if (
|
|
121
|
-
|
|
122
|
-
|
|
135
|
+
// A brief is for a fresh session. A resume or a compaction fires session start too, and would
|
|
136
|
+
// use up a brief the agent wrote earlier in this same session.
|
|
137
|
+
if (!input.source || ['startup', 'clear', 'new'].includes(input.source)) {
|
|
138
|
+
// Only a brief in .codehere/briefs/: state.json can arrive through git and point anywhere.
|
|
139
|
+
const brief = briefFile(root, state.pendingBrief);
|
|
140
|
+
let briefText = null;
|
|
141
|
+
try {
|
|
142
|
+
briefText = brief && readPlain(brief); // briefs/ itself can be a committed link to /dev
|
|
143
|
+
} catch {}
|
|
144
|
+
if (briefText) {
|
|
145
|
+
out.push('', 'Restart brief from the previous session. Treat it as the full, current spec:');
|
|
146
|
+
out.push(briefText.slice(0, 4000));
|
|
147
|
+
}
|
|
148
|
+
state.pendingBrief = null;
|
|
123
149
|
}
|
|
124
|
-
state.pendingBrief = null;
|
|
125
150
|
|
|
126
151
|
const mine = me(root);
|
|
127
152
|
const open = listDocs(paths(root).help).filter((d) => d.meta.status === 'open' && d.meta.author !== mine);
|
|
@@ -131,7 +156,7 @@ function sessionStart(root, input, agent) {
|
|
|
131
156
|
`Note for the user: ${open.length} teammate help request(s) are open (${open
|
|
132
157
|
.slice(0, 3)
|
|
133
158
|
.map((d) => d.meta.author)
|
|
134
|
-
.join(', ')}). Mention this once, briefly
|
|
159
|
+
.join(', ')}). Mention this once, briefly, and offer to show them.`
|
|
135
160
|
);
|
|
136
161
|
}
|
|
137
162
|
|
|
@@ -145,19 +170,22 @@ function sessionStart(root, input, agent) {
|
|
|
145
170
|
}
|
|
146
171
|
|
|
147
172
|
writeState(root, state);
|
|
173
|
+
// Rules, briefs and help cards come from the repo: none of it may show the agent Codehere's tick.
|
|
174
|
+
const text = noTick(out.join('\n'), '[tick]'); // "[tick]" keeps the meaning of a spec that asks for one
|
|
148
175
|
// Copilot reads only JSON here; Claude Code and Codex take the plain text
|
|
149
|
-
if (out.length && agent === 'copilot') emitJson({ additionalContext:
|
|
150
|
-
if (out.length) process.stdout.write(
|
|
176
|
+
if (out.length && agent === 'copilot') emitJson({ additionalContext: text });
|
|
177
|
+
if (out.length) process.stdout.write(text + '\n');
|
|
151
178
|
quiet();
|
|
152
179
|
}
|
|
153
180
|
|
|
181
|
+
// Only a brief directly in this repo's .codehere/briefs/, with no link on the way. state.json and
|
|
182
|
+
// briefs/ can both arrive through git: a resolved path would follow a committed briefs/ link out
|
|
183
|
+
// of the repo. The final name is refused if it is a link when it is read (readPlain).
|
|
154
184
|
function briefFile(root, file) {
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
return null;
|
|
160
|
-
}
|
|
185
|
+
const name = typeof file === 'string' ? path.basename(file) : '';
|
|
186
|
+
if (!/^[\w-]+\.md$/.test(name)) return null;
|
|
187
|
+
const brief = path.join(paths(root).briefs, name);
|
|
188
|
+
return ownPath(root, brief) ? brief : null;
|
|
161
189
|
}
|
|
162
190
|
|
|
163
191
|
// ---------- what changed in THIS session ----------
|
|
@@ -199,11 +227,16 @@ const PROTECTED = [
|
|
|
199
227
|
'.github/hooks/', '.github/copilot/settings.json', '.github/copilot/settings.local.json',
|
|
200
228
|
];
|
|
201
229
|
|
|
230
|
+
// A symlink is not followed (one to /dev/zero would hang the hook); its target stands for it, so a
|
|
231
|
+
// change is still seen.
|
|
232
|
+
function readProtectedFile(file) {
|
|
233
|
+
return fs.lstatSync(file).isSymbolicLink() ? `link:${fs.readlinkSync(file)}` : readPlain(file);
|
|
234
|
+
}
|
|
202
235
|
function readProtected(root, f) {
|
|
203
|
-
if (!f.endsWith('/')) return
|
|
236
|
+
if (!f.endsWith('/')) return readProtectedFile(path.join(root, f));
|
|
204
237
|
const files = fs.readdirSync(path.join(root, f)).filter((n) => n.endsWith('.json')).sort();
|
|
205
238
|
if (!files.length) return null;
|
|
206
|
-
return files.map((n) => `${n}\0${
|
|
239
|
+
return files.map((n) => `${n}\0${readProtectedFile(path.join(root, f, n))}`).join('\0');
|
|
207
240
|
}
|
|
208
241
|
|
|
209
242
|
function settingsSnapshot(root) {
|
|
@@ -243,14 +276,162 @@ function settingsChanged(root, s) {
|
|
|
243
276
|
// `cd x && cat a; ls b` is read-only only if every part is. Quoted text is
|
|
244
277
|
// emptied first so `grep "error|fail"` stays one part, and a part that runs
|
|
245
278
|
// another command ($(...), backticks, <(...)) is never read-only.
|
|
246
|
-
const READ_ONLY = /^\s*(cd|pwd|echo|cat|head|tail|less|more|grep|rg|ag|sed\s+-n|awk|ls|find|tree|wc|git\s+(diff|show|log|blame|grep|status))\
|
|
279
|
+
const READ_ONLY = /^\s*(cd|pwd|echo|cat|head|tail|less|more|grep|rg|ag|sed\s+-n|awk|ls|find|tree|wc|git\s+(diff|show|log|blame|grep|status))(\s|$)/;
|
|
280
|
+
// Read-only commands that can still run another: awk's system(), a pipe or a file of awk code;
|
|
281
|
+
// find's -exec; git grep -O; rg --pre; GNU sed's e command. Read on the part with its quote marks
|
|
282
|
+
// removed, so quoting cannot hide them, and only on read-only parts, so a codehere argument that
|
|
283
|
+
// mentions system() is still Codehere's own output.
|
|
284
|
+
function runsInside(plain) {
|
|
285
|
+
if (/^\s*awk(\s|$)/.test(plain)) return /system\s*\(|\||\s-[fEil]|\s--(file|exec|include|load)|@include|@load/.test(plain);
|
|
286
|
+
if (/^\s*find(\s|$)/.test(plain)) return /\s-(exec|execdir|ok|okdir|delete)(\s|$)/.test(plain);
|
|
287
|
+
if (/^\s*git\s+grep(\s|$)/.test(plain)) return /\s(-O|--open-files-in-pager)/.test(plain);
|
|
288
|
+
if (/^\s*rg(\s|$)/.test(plain)) return /\s--pre(\s|=|$)/.test(plain);
|
|
289
|
+
// GNU sed's e command, or e among the flags after s/.../.../
|
|
290
|
+
if (/^\s*sed(\s|$)/.test(plain)) return /(^|[\s;{}0-9/$])e(\s|;|$)|\/[a-zA-Z0-9]*e[a-zA-Z0-9]*(\s|;|$)/.test(plain.replace(/^\s*sed\s+-n/, ''));
|
|
291
|
+
return false;
|
|
292
|
+
}
|
|
293
|
+
const readOnlyPart = (p) => READ_ONLY.test(p.bare) && !runsInside(p.plain);
|
|
294
|
+
|
|
295
|
+
// The parts of a shell command, each as { bare, plain }: bare has quoted text emptied (to see the
|
|
296
|
+
// command), plain has only the quote marks removed (to see what it runs). Quotes and backslashes are
|
|
297
|
+
// read as the shell reads them: nothing quoted or escaped separates parts, and single quotes hold
|
|
298
|
+
// plain text. null when a part runs another command or the command cannot be split for sure: $( and
|
|
299
|
+
// backticks (also inside double quotes); <( >( $'...' ( ) a comment or a here-doc outside quotes;
|
|
300
|
+
// an unclosed quote. A lone & separates parts, but not in 2>&1 or &>file.
|
|
301
|
+
function commandParts(command) {
|
|
302
|
+
const parts = [];
|
|
303
|
+
let bare = '';
|
|
304
|
+
let plain = '';
|
|
305
|
+
let quote = null;
|
|
306
|
+
const cut = () => {
|
|
307
|
+
if (bare.trim()) parts.push({ bare, plain });
|
|
308
|
+
bare = plain = '';
|
|
309
|
+
};
|
|
310
|
+
for (let i = 0; i < command.length; i++) {
|
|
311
|
+
const c = command[i];
|
|
312
|
+
const next = command[i + 1];
|
|
313
|
+
const prev = command[i - 1];
|
|
314
|
+
if (quote === "'") {
|
|
315
|
+
if (c === "'") (quote = null), (bare += "''");
|
|
316
|
+
else plain += c;
|
|
317
|
+
continue;
|
|
318
|
+
}
|
|
319
|
+
if (c === '\\') {
|
|
320
|
+
i++; // the next character is literal; a backslash-newline is removed, as the shell does
|
|
321
|
+
if (next !== '\n' && next !== undefined) (bare += quote ? '' : '_'), (plain += next);
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
if (c === '`' || (c === '$' && (next === '(' || next === '['))) return null; // $[ ] arithmetic expands its text again
|
|
325
|
+
if (quote === '"') {
|
|
326
|
+
if (c === '"') (quote = null), (bare += "''");
|
|
327
|
+
else plain += c;
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
if (c === '(' || c === ')' || (c === '$' && next === "'") || (c === '<' && next === '<')) return null;
|
|
331
|
+
if (c === '#' && (i === 0 || /[\s;&|]/.test(prev))) return null;
|
|
332
|
+
if (c === "'" || c === '"') {
|
|
333
|
+
quote = c;
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
if (c === ';' || c === '\n') {
|
|
337
|
+
cut();
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
if (c === '|') {
|
|
341
|
+
if (next === '|' || next === '&') i++;
|
|
342
|
+
cut();
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
if (c === '&' && next === '&') {
|
|
346
|
+
i++;
|
|
347
|
+
cut();
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
350
|
+
if (c === '&' && prev !== '<' && prev !== '>' && next !== '>') {
|
|
351
|
+
cut();
|
|
352
|
+
continue;
|
|
353
|
+
}
|
|
354
|
+
bare += c;
|
|
355
|
+
plain += c;
|
|
356
|
+
}
|
|
357
|
+
if (quote) return null;
|
|
358
|
+
cut();
|
|
359
|
+
return parts;
|
|
360
|
+
}
|
|
247
361
|
export function readOnly(command) {
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
362
|
+
return !!commandParts(command)?.every(readOnlyPart);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// Codehere's own commands print error text by design (status, help cards, briefs), so their output
|
|
366
|
+
// is not read for errors. A chain that also runs something else still is.
|
|
367
|
+
// codehere on the PATH, through npx (with -y and a version), or the project's own copy, with flags
|
|
368
|
+
// before the subcommand (only the CLI's on/off flags: a flag that takes a value would swallow the
|
|
369
|
+
// subcommand). Not any program named codehere, and no VAR=value in front: PATH= could
|
|
370
|
+
// point to another codehere.
|
|
371
|
+
const CALL = String.raw`^\s*(npx\s+((-y|--yes)\s+)*codehere(@[\w.^~-]+)?|((\.\/)?node_modules\/\.bin\/)?codehere)(\s+--(gemma|all|solved))*`;
|
|
372
|
+
const CODEHERE = new RegExp(`${CALL}(\\s|$)`);
|
|
373
|
+
const ownOrReadOnly = (command) => !!commandParts(command)?.every((p) => CODEHERE.test(p.bare) || readOnlyPart(p));
|
|
374
|
+
|
|
375
|
+
// ---------- drafts: tie the draft a writing command printed to this session ----------
|
|
376
|
+
|
|
377
|
+
const WRITING = new RegExp(`${CALL}\\s+(rules?|lessons?|help|reply)(\\s|$)`);
|
|
378
|
+
const MARKER = /^Codehere draft id: ([0-9a-f]{8})$/;
|
|
379
|
+
|
|
380
|
+
// 'bound', 'refused' (a draft was printed but cannot be tied to the session), or null (no draft).
|
|
381
|
+
// Only the writing call itself may print the last line: it must come last, after nothing but cd.
|
|
382
|
+
// A draft git tracks came through git (a teammate force-added it), so it is never bound.
|
|
383
|
+
function bindDraft(root, input, command, text) {
|
|
384
|
+
const lines = text.split('\n').map((l) => l.trim()).filter(Boolean);
|
|
385
|
+
if (/^<shellId: .*>$/.test(lines.at(-1) || '')) lines.pop(); // Copilot's own last line
|
|
386
|
+
const m = MARKER.exec(lines.at(-1) || '');
|
|
387
|
+
if (!m) return null;
|
|
388
|
+
const parts = commandParts(command);
|
|
389
|
+
// only a writing call makes a draft: other output that ends in a marker is not Codehere's to explain
|
|
390
|
+
const wrote = parts ? parts.some((p) => WRITING.test(p.bare)) : /(^|[\s;&|])codehere\s+(rules?|lessons?|help|reply)(\s|$)/.test(command);
|
|
391
|
+
if (!wrote) return null;
|
|
392
|
+
const file = draftFile(root, m[1]);
|
|
393
|
+
const callOk = !!parts?.length && WRITING.test(parts.at(-1).bare) && parts.slice(0, -1).every((p) => /^\s*cd(\s|$)/.test(p.bare));
|
|
394
|
+
// by exact name, and git's list compared without case: on macOS ABCDEF12.json opens as abcdef12.json
|
|
395
|
+
const exact = !!file && fs.existsSync(path.dirname(file)) && fs.readdirSync(path.dirname(file)).includes(`${m[1]}.json`);
|
|
396
|
+
const rel = path.relative(root, file || '').toLowerCase();
|
|
397
|
+
const tracked = git(root, ['ls-files', '-z']).split('\0').some((x) => x.toLowerCase() === rel); // .CODEHERE/... too
|
|
398
|
+
if (!callOk || !exact || tracked) return 'refused';
|
|
399
|
+
const content = readPlain(file, null);
|
|
400
|
+
let rec = null;
|
|
401
|
+
try {
|
|
402
|
+
rec = JSON.parse(content);
|
|
403
|
+
} catch {}
|
|
404
|
+
// the file must still say what the person was shown: every line of it was in the output
|
|
405
|
+
if (!rec || !shownIn(rec, text)) return 'refused';
|
|
406
|
+
const kind = rec.kind;
|
|
407
|
+
const state = readState(root);
|
|
408
|
+
if (!input.session_id) return 'refused';
|
|
409
|
+
const s = session(state, input.session_id);
|
|
410
|
+
const entry = { id: m[1], kind, hash: crypto.createHash('sha256').update(content).digest('hex') };
|
|
411
|
+
// the lesson the agent drafts after the finish check's offer takes the proof kept for it
|
|
412
|
+
if (kind === 'lesson' && s.pendingLesson && typeof s.pendingLesson === 'object') {
|
|
413
|
+
entry.proof = s.pendingLesson;
|
|
414
|
+
delete s.pendingLesson;
|
|
415
|
+
}
|
|
416
|
+
s.drafts = [...(Array.isArray(s.drafts) ? s.drafts : []), entry];
|
|
417
|
+
delete s.lastSendBack; // any send-back came before this draft, so it cannot be the answer to it
|
|
418
|
+
return writeState(root, state) ? { proof: entry.proof || null } : 'refused'; // a binding that was not kept is not one
|
|
252
419
|
}
|
|
253
420
|
|
|
421
|
+
// The lines the CLI printed for this record (commands.js draft()), each indented by two spaces.
|
|
422
|
+
function shownIn(rec, text) {
|
|
423
|
+
const doc = (x) => (x && typeof x === 'object' ? renderDoc(x.meta || {}, String(x.body ?? x.text ?? '')).split('\n') : []);
|
|
424
|
+
const lines = rec.kind === 'rule' ? [rec.line] : rec.kind === 'lesson' ? doc(rec) : rec.kind === 'help' ? doc({ meta: rec.meta, text: rec.text }) : rec.kind === 'reply' ? [rec.line, ...doc(rec.lesson)] : [];
|
|
425
|
+
const shown = lines.map((l) => String(l ?? '')).filter((l) => l.trim());
|
|
426
|
+
// whole printed lines, and for a reply the card it is for
|
|
427
|
+
const out = new Set(text.split('\n').map((l) => l.replace(/\r$/, '')));
|
|
428
|
+
const card = rec.kind !== 'reply' || out.has(printable(`Not saved yet. Draft of a reply to help card ${rec.card}:`));
|
|
429
|
+
return card && shown.length > 0 && shown.every((l) => out.has(` ${printable(l)}`));
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
const NOT_BOUND = 'Codehere could not tie this draft to the session, so a yes will not save it. Run the codehere command again on its own, with nothing before it but cd and nothing after it.';
|
|
433
|
+
const noteFor = (agent, event, message) => (agent === 'copilot' ? { additionalContext: message } : { hookSpecificOutput: { hookEventName: event, additionalContext: message } });
|
|
434
|
+
|
|
254
435
|
function matchLesson(root, sig, shown, test) {
|
|
255
436
|
let best = null;
|
|
256
437
|
for (const doc of listDocs(paths(root).lessons)) {
|
|
@@ -320,7 +501,7 @@ function lessonText(root, doc) {
|
|
|
320
501
|
: 'Proof none recorded.'
|
|
321
502
|
);
|
|
322
503
|
out.push('Check whether it fits before trying something new.');
|
|
323
|
-
return out.join('\n');
|
|
504
|
+
return noTick(out.join('\n'), '[tick]'); // a teammate's text cannot show the agent Codehere's tick
|
|
324
505
|
}
|
|
325
506
|
|
|
326
507
|
function lessonLine(doc) {
|
|
@@ -329,33 +510,42 @@ function lessonLine(doc) {
|
|
|
329
510
|
return printable(`codehere › ${who}'s lesson given to the agent · ${lessonProof(doc) ? `verified on ${who}'s machine` : 'not verified'}${date}`);
|
|
330
511
|
}
|
|
331
512
|
|
|
332
|
-
//
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
const
|
|
337
|
-
let file = path.join(dir, `${name}.md`);
|
|
338
|
-
for (let i = 2; fs.existsSync(file); i++) file = path.join(dir, `${name}-${i}.md`);
|
|
339
|
-
const meta = { title: PLACEHOLDERS[0], signature: sig, ...(test ? { test: redact(test).slice(0, 120) } : {}), author: me(root), date: today(), state: proofCommand ? 'verified' : 'unverified' };
|
|
513
|
+
// The proof the finish check keeps for a solved repeated error. Nothing is written: the agent offers
|
|
514
|
+
// the lesson, its draft takes this proof at binding, and the person's yes saves both. Only Codehere
|
|
515
|
+
// writes these fields; the signature is redacted like the test name, since it goes to the team.
|
|
516
|
+
function lessonProofFor(root, sig, proofCommand, changed, test) {
|
|
517
|
+
const proof = { signature: redact(sig), ...(test ? { test: redact(test).slice(0, 120) } : {}), state: proofCommand ? 'verified' : 'unverified' };
|
|
340
518
|
if (proofCommand) {
|
|
341
|
-
Object.assign(
|
|
519
|
+
Object.assign(proof, {
|
|
342
520
|
proof_command: proofCommand,
|
|
343
521
|
proof_exit: 0,
|
|
344
522
|
proof_commit: git(root, ['rev-parse', '--short', 'HEAD']),
|
|
345
523
|
proof_dirty: statusFiles(root).some((f) => !IGNORE(f)),
|
|
346
524
|
});
|
|
347
525
|
}
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
526
|
+
proof.files = JSON.stringify(changed);
|
|
527
|
+
proof.file_hashes = JSON.stringify(gitHashes(root, changed));
|
|
528
|
+
return proof;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// What the agent and the person are shown when an offered lesson's draft takes its proof. The
|
|
532
|
+
// person's line names the error, so a yes after a declined offer cannot attach it to another lesson unseen.
|
|
533
|
+
function proofNote(agent, event, proof) {
|
|
534
|
+
const line = proof.state === 'verified' ? `proof: ${noTick(proof.proof_command)} passed here at ${noTick(proof.proof_commit)}` : 'not verified: no passing test run here this session';
|
|
535
|
+
const context = `Codehere will add this to the lesson: the error "${noTick(proof.signature)}" and ${line}. Show the user this line with the draft.`;
|
|
536
|
+
if (agent === 'copilot') return { additionalContext: printable(context) };
|
|
537
|
+
return { systemMessage: printable(`codehere › lesson draft for "${short(noTick(String(proof.signature)))}" · ${line}`), hookSpecificOutput: { hookEventName: event, additionalContext: printable(context) } };
|
|
352
538
|
}
|
|
353
539
|
|
|
354
540
|
function postTool(root, input, agent) {
|
|
355
541
|
if (input.tool_name && input.tool_name !== 'Bash') quiet();
|
|
356
542
|
const command = (input.tool_input && input.tool_input.command) || '';
|
|
357
|
-
if (readOnly(command)) quiet();
|
|
358
543
|
const text = responseText(input.tool_response) + '\n' + (input.error || '');
|
|
544
|
+
// a refused draft never stops the error count: the note waits for a hook that has nothing else to say
|
|
545
|
+
const bind = bindDraft(root, input, command, text);
|
|
546
|
+
if (bind === 'refused') quietNote = noteFor(agent, input.hook_event_name || 'PostToolUse', NOT_BOUND);
|
|
547
|
+
else if (bind?.proof) quietNote = proofNote(agent, input.hook_event_name || 'PostToolUse', bind.proof);
|
|
548
|
+
if (ownOrReadOnly(command)) quiet();
|
|
359
549
|
const sig = signature(text);
|
|
360
550
|
if (!sig) {
|
|
361
551
|
// the command that failed last now runs clean: that failure is over
|
|
@@ -400,9 +590,7 @@ function postTool(root, input, agent) {
|
|
|
400
590
|
if (count > threshold) {
|
|
401
591
|
msg.push(
|
|
402
592
|
'',
|
|
403
|
-
'You are still stuck. Stop now.
|
|
404
|
-
'`codehere help "<what you are stuck on>"` to send a ready-made help card to a teammate,',
|
|
405
|
-
'or `codehere brief` to restart in a fresh session. Then wait for the user.'
|
|
593
|
+
'You are still stuck. Stop now. In one short line, offer to write a help card for the team or a restart brief for a fresh session. Then wait for the user.'
|
|
406
594
|
);
|
|
407
595
|
}
|
|
408
596
|
// Codex replaces the command's output with a block's text (or exit 2's), so the agent
|
|
@@ -436,6 +624,101 @@ function postTool(root, input, agent) {
|
|
|
436
624
|
// ---------- UserPromptSubmit: restore what a short prompt leaves out ----------
|
|
437
625
|
// One message at most, only about this session, under 300 tokens. Silent on normal turns.
|
|
438
626
|
|
|
627
|
+
// ---------- the person's answer to a draft ----------
|
|
628
|
+
// A draft is decided by the person's very next message: a plain yes saves it, anything else
|
|
629
|
+
// discards it. Notes go to the agent, lines to the person.
|
|
630
|
+
const RULES = '.codehere/rules.md';
|
|
631
|
+
function gist(rec) {
|
|
632
|
+
if (rec.kind === 'rule') return String(rec.line).replace(/^- /, '').replace(/ \([^()]*\)$/, '');
|
|
633
|
+
if (rec.kind === 'lesson') return String(rec.meta?.title ?? '');
|
|
634
|
+
if (rec.kind === 'help') return (/## Question\n(.+)/.exec(String(rec.text)) || [])[1] || '';
|
|
635
|
+
return String(rec.line).replace(/^- [^:]*\): /, '');
|
|
636
|
+
}
|
|
637
|
+
const short = (t) => (t.length > 60 ? `${t.slice(0, 60)}…` : t);
|
|
638
|
+
|
|
639
|
+
function decideDrafts(root, state, s, prompt) {
|
|
640
|
+
const notes = [];
|
|
641
|
+
const lines = [];
|
|
642
|
+
// Copilot passes a send-back to this hook as if the person typed it: that is not their answer
|
|
643
|
+
// used once: a later message that happens to start the same way is the person's
|
|
644
|
+
const skip = s.lastSendBack && prompt.startsWith(s.lastSendBack);
|
|
645
|
+
delete s.lastSendBack;
|
|
646
|
+
if (skip) return { notes, lines };
|
|
647
|
+
// since this session's previous prompt, or its start: an older draft is not this answer's
|
|
648
|
+
const since = Date.parse(s.lastPromptAt || s.startedAt || '') || Date.now();
|
|
649
|
+
s.lastPromptAt = new Date().toISOString();
|
|
650
|
+
const bound = (Array.isArray(s.drafts) ? s.drafts : []).filter((d) => d && typeof d === 'object' && /^[0-9a-f]{8}$/.test(String(d.id)));
|
|
651
|
+
const yes = plainYes(prompt);
|
|
652
|
+
let proofBack = null;
|
|
653
|
+
for (const d of bound) {
|
|
654
|
+
const file = draftFile(root, d.id);
|
|
655
|
+
// Taken by a rename, which only one of two hooks running at the same moment can win (two unlinks
|
|
656
|
+
// of one file both succeeded in a test on macOS); the other finds it gone and saves nothing.
|
|
657
|
+
let content = null;
|
|
658
|
+
try {
|
|
659
|
+
const taken = `${file}.${crypto.randomBytes(4).toString('hex')}.taken`;
|
|
660
|
+
fs.renameSync(file, taken);
|
|
661
|
+
content = readPlain(taken, null);
|
|
662
|
+
fs.rmSync(taken, { force: true });
|
|
663
|
+
} catch {
|
|
664
|
+
continue;
|
|
665
|
+
}
|
|
666
|
+
if (!yes) {
|
|
667
|
+
proofBack = d.proof || proofBack; // "change the title": the redraft keeps the proof
|
|
668
|
+
continue;
|
|
669
|
+
}
|
|
670
|
+
if (!content || crypto.createHash('sha256').update(content).digest('hex') !== d.hash) {
|
|
671
|
+
notes.push('Codehere did not save a draft: its file changed after it was shown to the user.');
|
|
672
|
+
lines.push('codehere ✕ not saved · the draft changed after it was shown');
|
|
673
|
+
continue;
|
|
674
|
+
}
|
|
675
|
+
let rec = null;
|
|
676
|
+
try {
|
|
677
|
+
rec = JSON.parse(content);
|
|
678
|
+
} catch {}
|
|
679
|
+
const before = settingsSnapshot(root)[RULES];
|
|
680
|
+
const saved = saveRecord(root, rec, d.proof || null);
|
|
681
|
+
if (saved.error) {
|
|
682
|
+
notes.push(`Codehere could not save the draft: ${saved.error}`);
|
|
683
|
+
lines.push(`codehere ✕ not saved · ${noTick(saved.error)}`);
|
|
684
|
+
continue;
|
|
685
|
+
}
|
|
686
|
+
// a saved rule is not a settings change, unless rules.md had already changed this session
|
|
687
|
+
if (rec.kind === 'rule' && s.settings && s.settings[RULES] === before) s.settings[RULES] = settingsSnapshot(root)[RULES];
|
|
688
|
+
notes.push(`Codehere saved the draft after the user's yes: ${saved.file}${saved.lesson ? `, and the team lesson ${saved.lesson}` : ''}. Tell them it is saved. Teammates get it once the user commits and pushes it.`);
|
|
689
|
+
// the agent's own words: never a tick in a codehere line (DESIGN.md §1)
|
|
690
|
+
lines.push(`codehere › saved after your yes · ${rec.kind} · ${short(noTick(gist(rec)))}`);
|
|
691
|
+
}
|
|
692
|
+
if (bound.length && !yes) {
|
|
693
|
+
notes.push("Codehere discarded the draft because the user's reply was not a plain yes. If they still want it, draft it again.");
|
|
694
|
+
lines.push('codehere › draft not saved · your reply was not a plain yes'); // so a near-yes such as "yes, save it" is not lost unseen
|
|
695
|
+
}
|
|
696
|
+
// a yes that a draft made this turn did not reach (for example a binding lost to a parallel call)
|
|
697
|
+
if (yes && draftMadeSince(root, state, since)) {
|
|
698
|
+
notes.push(`Codehere saved ${bound.length ? 'not all of it' : 'nothing'}: a draft was not tied to this session. Run that codehere command again on its own.`);
|
|
699
|
+
lines.push(bound.length ? 'codehere ✕ not saved · a draft was not tied to this session' : 'codehere ✕ nothing saved · the draft was not tied to this session');
|
|
700
|
+
}
|
|
701
|
+
s.drafts = [];
|
|
702
|
+
if (proofBack) s.pendingLesson = proofBack;
|
|
703
|
+
else delete s.pendingLesson;
|
|
704
|
+
return { notes, lines };
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
// An unbound draft made since then: one bound in any session is that session's to decide.
|
|
708
|
+
function draftMadeSince(root, state, since) {
|
|
709
|
+
try {
|
|
710
|
+
const dir = path.dirname(draftFile(root, '00000000'));
|
|
711
|
+
const bound = new Set(Object.values(state.sessions).flatMap((x) => (Array.isArray(x.drafts) ? x.drafts.map((d) => `${d.id}.json`) : [])));
|
|
712
|
+
const fresh = fs.readdirSync(dir).filter((f) => /^[0-9a-f]{8}\.json$/.test(f) && !bound.has(f) && fs.lstatSync(path.join(dir, f)).mtimeMs > since);
|
|
713
|
+
if (!fresh.length) return false;
|
|
714
|
+
// a draft git tracks came through git (a pull), not from a command this session ran
|
|
715
|
+
const tracked = new Set(git(root, ['ls-files', '-z']).split('\0').map((x) => path.basename(x).toLowerCase()));
|
|
716
|
+
return fresh.some((f) => !tracked.has(f));
|
|
717
|
+
} catch {
|
|
718
|
+
return false;
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
|
|
439
722
|
function promptSubmit(root, input) {
|
|
440
723
|
if (!input.session_id) quiet(); // without it, sessions cannot be told apart
|
|
441
724
|
const prompt = String(input.prompt || '');
|
|
@@ -445,6 +728,7 @@ function promptSubmit(root, input) {
|
|
|
445
728
|
s.transcript = input.transcript_path || s.transcript;
|
|
446
729
|
s.prompts = (s.prompts || 0) + 1;
|
|
447
730
|
if (!s.settings) s.settings = settingsSnapshot(root); // session start did not run for this session
|
|
731
|
+
const decided = decideDrafts(root, state, s, prompt);
|
|
448
732
|
|
|
449
733
|
// Only a failure from the agent's last turn counts: an older one may be fixed or forgotten.
|
|
450
734
|
const f = s.lastFailure && (s.lastFailure.prompt || 0) === s.prompts - 1 ? s.lastFailure : null;
|
|
@@ -469,7 +753,7 @@ function promptSubmit(root, input) {
|
|
|
469
753
|
msg = [
|
|
470
754
|
`Codehere: this session is long (about ${Math.round(transcriptTokens(s) / 1000)}k tokens) and the same error came back ${repeats} times.`,
|
|
471
755
|
'Fresh sessions with one clear spec fix bugs better than long ones.',
|
|
472
|
-
'In one line,
|
|
756
|
+
'In one line, offer to write a restart brief for a fresh session. Then continue with their request.',
|
|
473
757
|
].join('\n');
|
|
474
758
|
} else if (!f && !s.askedHowToCheck && vagueFeature(prompt)) {
|
|
475
759
|
s.askedHowToCheck = true;
|
|
@@ -482,8 +766,12 @@ function promptSubmit(root, input) {
|
|
|
482
766
|
}
|
|
483
767
|
|
|
484
768
|
writeState(root, state);
|
|
485
|
-
|
|
486
|
-
|
|
769
|
+
const context = [...decided.notes, ...(msg ? [msg.slice(0, 1100)] : [])].join('\n\n');
|
|
770
|
+
if (context || decided.lines.length) {
|
|
771
|
+
emitJson({
|
|
772
|
+
...(decided.lines.length ? { systemMessage: decided.lines.map(printable).join('\n') } : {}),
|
|
773
|
+
...(context ? { hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: context } } : {}),
|
|
774
|
+
});
|
|
487
775
|
}
|
|
488
776
|
quiet();
|
|
489
777
|
}
|
|
@@ -549,15 +837,17 @@ function runTests(root, cfg) {
|
|
|
549
837
|
});
|
|
550
838
|
const output = `${r.stdout || ''}\n${r.stderr || ''}`.trim();
|
|
551
839
|
const timedOut = r.error && r.error.code === 'ETIMEDOUT';
|
|
552
|
-
|
|
840
|
+
// The runner's own count of failures wins over exit 0: `|| true` on a test script is one edit.
|
|
841
|
+
const c = testCounts(output);
|
|
842
|
+
return { ok: r.status === 0 && !timedOut && !(c && c.failed), output, timedOut, code: r.status, seconds: (Date.now() - started) / 1000 };
|
|
553
843
|
}
|
|
554
844
|
|
|
555
845
|
// "48 passed" or "2 failed" when the runner's summary can be read, else the exit code
|
|
556
846
|
export function runResult(t) {
|
|
557
847
|
if (t.timedOut) return 'timed out';
|
|
558
848
|
const c = testCounts(t.output);
|
|
559
|
-
if (t.ok) return c && !c.failed ? `${c.passed} passed` : 'exit 0'; //
|
|
560
|
-
return c && c.failed ? `${c.failed} failed` : `exit ${t.code}`;
|
|
849
|
+
if (t.ok) return c && !c.failed ? `${c.passed} passed` : 'exit 0'; // no summary to read: say only the exit code
|
|
850
|
+
return c && c.failed ? `${c.failed} failed${t.code === 0 ? ' · exit 0' : ''}` : `exit ${t.code}`;
|
|
561
851
|
}
|
|
562
852
|
|
|
563
853
|
const removedLine = (at) => `codehere ✕ codehere uninstall ran at ${new Date(at).toTimeString().slice(0, 5)} · this repo's checks are removed`;
|
|
@@ -572,6 +862,20 @@ function stop(root, input) {
|
|
|
572
862
|
const state = readState(root);
|
|
573
863
|
const s = session(state, input.session_id);
|
|
574
864
|
const mayBlock = (s.stopBlocks || 0) < 3; // never trap the agent: after 3 blocks, only observe
|
|
865
|
+
// The first line of each reason is kept: Copilot passes a send-back to the prompt hook as if the
|
|
866
|
+
// person typed it, and the prompt hook must not take it as their answer to a draft.
|
|
867
|
+
// A send-back that cannot be counted is not sent: without the count the 3-block cap would never
|
|
868
|
+
// stop the agent. The developer still gets what was found and why the agent was not sent back.
|
|
869
|
+
// carryOn: a finding that comes before the test run goes in the report and the check goes on, so
|
|
870
|
+
// the test result is not hidden behind it.
|
|
871
|
+
const sendAgentBack = (reason, message, carryOn = false) => {
|
|
872
|
+
s.lastSendBack = reason.split('\n')[0];
|
|
873
|
+
if (writeState(root, state)) block(reason, message);
|
|
874
|
+
const found = reason.split('\n').filter((l) => l.startsWith('- ')).map((l) => l.slice(2));
|
|
875
|
+
const why = `codehere ✕ ${noTick([s.lastSendBack, ...found].join(' ')).slice(0, 160)} · not sent back · Codehere could not save its state in .codehere/local`;
|
|
876
|
+
if (carryOn) return void lines.push(why);
|
|
877
|
+
emitJson({ systemMessage: [String(message || '').replace(/ · agent sent back · \d+ of 3/, ''), printable(why)].filter(Boolean).join('\n') });
|
|
878
|
+
};
|
|
575
879
|
|
|
576
880
|
if (!isGitRepo(root)) quiet();
|
|
577
881
|
const base = commitId(s.startHead) || 'HEAD';
|
|
@@ -609,13 +913,15 @@ function stop(root, input) {
|
|
|
609
913
|
s.tamperReported = key;
|
|
610
914
|
s.stopBlocks++;
|
|
611
915
|
writeState(root, state);
|
|
612
|
-
|
|
916
|
+
sendAgentBack(
|
|
613
917
|
[
|
|
614
918
|
'Codehere found changes that weaken tests or checks:',
|
|
615
919
|
...findings.map((f) => `- ${f}`),
|
|
616
920
|
'Restore them and fix the code instead.',
|
|
617
921
|
'If the change is truly intended, tell the user in one line why, then finish.',
|
|
618
|
-
].join('\n')
|
|
922
|
+
].join('\n'),
|
|
923
|
+
null,
|
|
924
|
+
true
|
|
619
925
|
);
|
|
620
926
|
}
|
|
621
927
|
|
|
@@ -628,13 +934,15 @@ function stop(root, input) {
|
|
|
628
934
|
s.settingsReported = settingsKey;
|
|
629
935
|
s.stopBlocks++;
|
|
630
936
|
writeState(root, state);
|
|
631
|
-
|
|
937
|
+
sendAgentBack(
|
|
632
938
|
[
|
|
633
939
|
'Codehere settings or hook settings changed during this session:',
|
|
634
940
|
...settings.map((f) => `- ${f}`),
|
|
635
941
|
'If you changed them and the user did not ask for it, undo your change.',
|
|
636
942
|
'Then tell the user in one line what changed and why, and finish.',
|
|
637
|
-
].join('\n')
|
|
943
|
+
].join('\n'),
|
|
944
|
+
null,
|
|
945
|
+
true
|
|
638
946
|
);
|
|
639
947
|
}
|
|
640
948
|
|
|
@@ -662,9 +970,10 @@ function stop(root, input) {
|
|
|
662
970
|
s.stopBlocks++;
|
|
663
971
|
writeState(root, state);
|
|
664
972
|
const tail = t.output.split('\n').slice(-25).join('\n');
|
|
665
|
-
|
|
973
|
+
sendAgentBack(
|
|
666
974
|
[
|
|
667
975
|
`Codehere ran \`${cmd}\` and it ${t.timedOut ? 'timed out' : 'failed'}. The task is not done yet.`,
|
|
976
|
+
...(t.code === 0 && !t.timedOut ? ['Its own summary counts failed tests, though the command exited 0.'] : []),
|
|
668
977
|
'Last lines of output:',
|
|
669
978
|
tail,
|
|
670
979
|
'Fix the cause, then finish. Do not change or skip tests to make them pass.',
|
|
@@ -685,28 +994,30 @@ function stop(root, input) {
|
|
|
685
994
|
lines.unshift(passLine);
|
|
686
995
|
}
|
|
687
996
|
|
|
688
|
-
// 4.
|
|
689
|
-
//
|
|
997
|
+
// 4. a solved repeated error: the agent offers it to the team as a lesson (once per session).
|
|
998
|
+
// Nothing is written here; the proof waits in the session for the lesson draft, and the person's
|
|
999
|
+
// yes saves it. After the 3-block cap there is no offer, and the developer is told.
|
|
690
1000
|
const solved = Object.entries(s.errors).filter(([, n]) => n >= 2);
|
|
691
1001
|
if (solved.length && !s.lessonAsked) {
|
|
692
1002
|
s.lessonAsked = true;
|
|
693
1003
|
const [sig] = solved.sort((a, b) => b[1] - a[1])[0];
|
|
694
1004
|
const named = s.tests && s.tests[sig];
|
|
695
|
-
const file = writeLesson(root, sig, proven ? cfg.testCommand : null, changed, typeof named === 'string' ? named : '');
|
|
696
1005
|
if (mayBlock) {
|
|
1006
|
+
s.pendingLesson = lessonProofFor(root, sig, proven ? cfg.testCommand : null, changed, typeof named === 'string' ? named : '');
|
|
697
1007
|
s.stopBlocks++;
|
|
698
|
-
|
|
699
|
-
block(
|
|
1008
|
+
sendAgentBack(
|
|
700
1009
|
[
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
'
|
|
704
|
-
|
|
1010
|
+
// the first line is fixed text: Copilot sends the reason back as a prompt, and the skip
|
|
1011
|
+
// compares this line, so the error's own text must not be in it
|
|
1012
|
+
'Before you finish: you hit and solved a repeated error.',
|
|
1013
|
+
`The error: ${printable(noTick(sig))}`,
|
|
1014
|
+
'Offer it to your team as a lesson: run `codehere lesson "<short title>" --cause "<one line>" --fix "<one line>"` and show the user the draft in one short message.',
|
|
1015
|
+
`Codehere adds ${proven ? 'this test run as proof' : 'the error and the changed files'}; it saves the lesson only if the user says yes.`,
|
|
705
1016
|
].join('\n'),
|
|
706
|
-
message()
|
|
1017
|
+
message(),
|
|
1018
|
+
true
|
|
707
1019
|
);
|
|
708
|
-
}
|
|
709
|
-
lines.push(`codehere › lesson saved: ${file} · fill in its title, cause and fix`);
|
|
1020
|
+
} else lines.push('codehere › repeated error solved · not offered as a lesson · limit of 3 reached');
|
|
710
1021
|
}
|
|
711
1022
|
|
|
712
1023
|
writeState(root, state);
|