codehere 2.0.4 → 2.1.0-rc.2

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/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, gitDiff, isGitRepo, me, slug, today, isApproved, readApprovals, printable, commitId, statusFiles, gitHashes, noTick,
11
- removedAt,
10
+ listDocs, git, gitDiff, isGitRepo, me, isApproved, readApprovals, printable, commitId, statusFiles, gitHashes, noTick,
11
+ removedAt, expireDrafts, draftFile, saveRecord, readPlain, ownPath, teamSnapshot, teamMark, keepSaved, isMap,
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
- const quiet = () => process.exit(0);
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(fs.readFileSync(path.join(root, '.github/hooks/codehere.json'), 'utf8')).hooks;
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;
@@ -103,25 +119,38 @@ function sessionStart(root, input, agent) {
103
119
  s.startHead = git(root, 'rev-parse HEAD') || null;
104
120
  s.baseline = dirtySnapshot(root);
105
121
  s.settings = settingsSnapshot(root);
122
+ s.team = teamSnapshot(root);
123
+ s.teamHead = s.startHead;
106
124
  } else if (input.source === 'resume') {
107
125
  // While the session was closed only the developer or a pull could change settings.
108
126
  s.settings = settingsSnapshot(root);
127
+ s.team = teamSnapshot(root);
128
+ s.teamHead = git(root, 'rev-parse HEAD') || null;
109
129
  }
110
130
 
111
131
  const out = [];
112
132
  const rules = readRules(root);
113
133
  if (rules.length) {
114
- out.push('Team rules from Codehere (written by your teammates, follow them):');
134
+ out.push("Team rules from your team's rules file (follow them):");
115
135
  rules.slice(0, 20).forEach((r) => out.push(`- ${r}`));
116
136
  }
137
+ out.push(...(out.length ? [''] : []), CHORES_NOTE);
117
138
 
118
- // Only a brief in .codehere/briefs/: state.json can arrive through git and point anywhere.
119
- const brief = briefFile(root, state.pendingBrief);
120
- if (brief) {
121
- out.push('', 'Restart brief from the previous session. Treat it as the full, current spec:');
122
- out.push(fs.readFileSync(brief, 'utf8').slice(0, 4000));
139
+ // A brief is for a fresh session. A resume or a compaction fires session start too, and would
140
+ // use up a brief the agent wrote earlier in this same session.
141
+ if (!input.source || ['startup', 'clear', 'new'].includes(input.source)) {
142
+ // Only a brief in .codehere/briefs/: state.json can arrive through git and point anywhere.
143
+ const brief = briefFile(root, state.pendingBrief);
144
+ let briefText = null;
145
+ try {
146
+ briefText = brief && readPlain(brief); // briefs/ itself can be a committed link to /dev
147
+ } catch {}
148
+ if (briefText) {
149
+ out.push('', 'Restart brief from the previous session. Treat it as the full, current spec:');
150
+ out.push(briefText.slice(0, 4000));
151
+ }
152
+ state.pendingBrief = null;
123
153
  }
124
- state.pendingBrief = null;
125
154
 
126
155
  const mine = me(root);
127
156
  const open = listDocs(paths(root).help).filter((d) => d.meta.status === 'open' && d.meta.author !== mine);
@@ -131,7 +160,7 @@ function sessionStart(root, input, agent) {
131
160
  `Note for the user: ${open.length} teammate help request(s) are open (${open
132
161
  .slice(0, 3)
133
162
  .map((d) => d.meta.author)
134
- .join(', ')}). Mention this once, briefly: they can run \`codehere inbox\`.`
163
+ .join(', ')}). Mention this once, briefly, and offer to show them.`
135
164
  );
136
165
  }
137
166
 
@@ -153,13 +182,14 @@ function sessionStart(root, input, agent) {
153
182
  quiet();
154
183
  }
155
184
 
185
+ // Only a brief directly in this repo's .codehere/briefs/, with no link on the way. state.json and
186
+ // briefs/ can both arrive through git: a resolved path would follow a committed briefs/ link out
187
+ // of the repo. The final name is refused if it is a link when it is read (readPlain).
156
188
  function briefFile(root, file) {
157
- try {
158
- const real = fs.realpathSync(path.resolve(root, file));
159
- return real.startsWith(fs.realpathSync(paths(root).briefs) + path.sep) ? real : null;
160
- } catch {
161
- return null;
162
- }
189
+ const name = typeof file === 'string' ? path.basename(file) : '';
190
+ if (!/^[\w-]+\.md$/.test(name)) return null;
191
+ const brief = path.join(paths(root).briefs, name);
192
+ return ownPath(root, brief) ? brief : null;
163
193
  }
164
194
 
165
195
  // ---------- what changed in THIS session ----------
@@ -201,11 +231,16 @@ const PROTECTED = [
201
231
  '.github/hooks/', '.github/copilot/settings.json', '.github/copilot/settings.local.json',
202
232
  ];
203
233
 
234
+ // A symlink is not followed (one to /dev/zero would hang the hook); its target stands for it, so a
235
+ // change is still seen.
236
+ function readProtectedFile(file) {
237
+ return fs.lstatSync(file).isSymbolicLink() ? `link:${fs.readlinkSync(file)}` : readPlain(file);
238
+ }
204
239
  function readProtected(root, f) {
205
- if (!f.endsWith('/')) return fs.readFileSync(path.join(root, f), 'utf8');
240
+ if (!f.endsWith('/')) return readProtectedFile(path.join(root, f));
206
241
  const files = fs.readdirSync(path.join(root, f)).filter((n) => n.endsWith('.json')).sort();
207
242
  if (!files.length) return null;
208
- return files.map((n) => `${n}\0${fs.readFileSync(path.join(root, f, n), 'utf8')}`).join('\0');
243
+ return files.map((n) => `${n}\0${readProtectedFile(path.join(root, f, n))}`).join('\0');
209
244
  }
210
245
 
211
246
  function settingsSnapshot(root) {
@@ -231,6 +266,35 @@ function settingsSnapshot(root) {
231
266
  return snap;
232
267
  }
233
268
 
269
+ // Lessons and help cards changed since the snapshot. A file with an uncommitted change is listed.
270
+ // Otherwise it is listed only if no commit since the snapshot touched it: a pull, or the person's
271
+ // own commit, changes files through commits, while an uncommitted save undone by `git stash` or
272
+ // `git checkout`, or an untracked file deleted, leaves no commit. What Codehere saved was moved
273
+ // into the snapshot (keepSaved).
274
+ function teamChanged(root, s) {
275
+ if (!isMap(s.team)) return [];
276
+ const now = teamSnapshot(root);
277
+ const diff = [...new Set([...Object.keys(now), ...Object.keys(s.team)])].filter((f) => now[f] !== s.team[f]);
278
+ if (!diff.length) return [];
279
+ const nfc = (f) => f.normalize('NFC');
280
+ const dirty = new Set(statusFiles(root).map(nfc));
281
+ let byCommit = null;
282
+ const committed = (f) => {
283
+ if (!byCommit) {
284
+ // the commits since the snapshot, and the trees' difference (a reset or a branch switch); a
285
+ // rename counts as a removal and an addition
286
+ const from = commitId(s.teamHead === undefined ? s.startHead : s.teamHead);
287
+ const paths = ['--', '.codehere/lessons', '.codehere/help'];
288
+ const names = (out) => out.split('\0').map((x) => nfc(x.replace(/^\n+/, ''))).filter(Boolean);
289
+ const log = names(git(root, ['log', '--name-only', '--no-renames', '--relative', '-z', '--format=', from ? `${from}..HEAD` : 'HEAD', ...paths], true));
290
+ const trees = from ? names(git(root, ['diff', '--name-only', '--no-renames', '--relative', '-z', from, 'HEAD', ...paths], true)) : [];
291
+ byCommit = new Set([...log, ...trees]);
292
+ }
293
+ return byCommit.has(nfc(f));
294
+ };
295
+ return diff.filter((f) => dirty.has(nfc(f)) || !committed(f)).sort();
296
+ }
297
+
234
298
  function settingsChanged(root, s) {
235
299
  if (!s.settings) return []; // no snapshot from session start: cannot tell
236
300
  const now = settingsSnapshot(root);
@@ -245,14 +309,162 @@ function settingsChanged(root, s) {
245
309
  // `cd x && cat a; ls b` is read-only only if every part is. Quoted text is
246
310
  // emptied first so `grep "error|fail"` stays one part, and a part that runs
247
311
  // another command ($(...), backticks, <(...)) is never read-only.
248
- 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))\b/;
312
+ 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|$)/;
313
+ // Read-only commands that can still run another: awk's system(), a pipe or a file of awk code;
314
+ // find's -exec; git grep -O; rg --pre; GNU sed's e command. Read on the part with its quote marks
315
+ // removed, so quoting cannot hide them, and only on read-only parts, so a codehere argument that
316
+ // mentions system() is still Codehere's own output.
317
+ function runsInside(plain) {
318
+ if (/^\s*awk(\s|$)/.test(plain)) return /system\s*\(|\||\s-[fEil]|\s--(file|exec|include|load)|@include|@load/.test(plain);
319
+ if (/^\s*find(\s|$)/.test(plain)) return /\s-(exec|execdir|ok|okdir|delete)(\s|$)/.test(plain);
320
+ if (/^\s*git\s+grep(\s|$)/.test(plain)) return /\s(-O|--open-files-in-pager)/.test(plain);
321
+ if (/^\s*rg(\s|$)/.test(plain)) return /\s--pre(\s|=|$)/.test(plain);
322
+ // GNU sed's e command, or e among the flags after s/.../.../
323
+ 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/, ''));
324
+ return false;
325
+ }
326
+ const readOnlyPart = (p) => READ_ONLY.test(p.bare) && !runsInside(p.plain);
327
+
328
+ // The parts of a shell command, each as { bare, plain }: bare has quoted text emptied (to see the
329
+ // command), plain has only the quote marks removed (to see what it runs). Quotes and backslashes are
330
+ // read as the shell reads them: nothing quoted or escaped separates parts, and single quotes hold
331
+ // plain text. null when a part runs another command or the command cannot be split for sure: $( and
332
+ // backticks (also inside double quotes); <( >( $'...' ( ) a comment or a here-doc outside quotes;
333
+ // an unclosed quote. A lone & separates parts, but not in 2>&1 or &>file.
334
+ function commandParts(command) {
335
+ const parts = [];
336
+ let bare = '';
337
+ let plain = '';
338
+ let quote = null;
339
+ const cut = () => {
340
+ if (bare.trim()) parts.push({ bare, plain });
341
+ bare = plain = '';
342
+ };
343
+ for (let i = 0; i < command.length; i++) {
344
+ const c = command[i];
345
+ const next = command[i + 1];
346
+ const prev = command[i - 1];
347
+ if (quote === "'") {
348
+ if (c === "'") (quote = null), (bare += "''");
349
+ else plain += c;
350
+ continue;
351
+ }
352
+ if (c === '\\') {
353
+ i++; // the next character is literal; a backslash-newline is removed, as the shell does
354
+ if (next !== '\n' && next !== undefined) (bare += quote ? '' : '_'), (plain += next);
355
+ continue;
356
+ }
357
+ if (c === '`' || (c === '$' && (next === '(' || next === '['))) return null; // $[ ] arithmetic expands its text again
358
+ if (quote === '"') {
359
+ if (c === '"') (quote = null), (bare += "''");
360
+ else plain += c;
361
+ continue;
362
+ }
363
+ if (c === '(' || c === ')' || (c === '$' && next === "'") || (c === '<' && next === '<')) return null;
364
+ if (c === '#' && (i === 0 || /[\s;&|]/.test(prev))) return null;
365
+ if (c === "'" || c === '"') {
366
+ quote = c;
367
+ continue;
368
+ }
369
+ if (c === ';' || c === '\n') {
370
+ cut();
371
+ continue;
372
+ }
373
+ if (c === '|') {
374
+ if (next === '|' || next === '&') i++;
375
+ cut();
376
+ continue;
377
+ }
378
+ if (c === '&' && next === '&') {
379
+ i++;
380
+ cut();
381
+ continue;
382
+ }
383
+ if (c === '&' && prev !== '<' && prev !== '>' && next !== '>') {
384
+ cut();
385
+ continue;
386
+ }
387
+ bare += c;
388
+ plain += c;
389
+ }
390
+ if (quote) return null;
391
+ cut();
392
+ return parts;
393
+ }
249
394
  export function readOnly(command) {
250
- const runsSomething = /\$\(|`|<\(/;
251
- if (runsSomething.test(command)) return false;
252
- const bare = command.replace(/(["'])(?:\\.|(?!\1)[^\\])*\1/g, "''");
253
- return bare.split(/&&|\|\||\|&|[;|\n]/).every((part) => !part.trim() || READ_ONLY.test(part));
395
+ return !!commandParts(command)?.every(readOnlyPart);
254
396
  }
255
397
 
398
+ // Codehere's own commands print error text by design (status, help cards, briefs), so their output
399
+ // is not read for errors. A chain that also runs something else still is.
400
+ // codehere on the PATH, through npx (with -y and a version), or the project's own copy, with flags
401
+ // before the subcommand (only the CLI's on/off flags: a flag that takes a value would swallow the
402
+ // subcommand). Not any program named codehere, and no VAR=value in front: PATH= could
403
+ // point to another codehere.
404
+ const CALL = String.raw`^\s*(npx\s+((-y|--yes)\s+)*codehere(@[\w.^~-]+)?|((\.\/)?node_modules\/\.bin\/)?codehere)(\s+--(gemma|all|solved))*`;
405
+ const CODEHERE = new RegExp(`${CALL}(\\s|$)`);
406
+ const ownOrReadOnly = (command) => !!commandParts(command)?.every((p) => CODEHERE.test(p.bare) || readOnlyPart(p));
407
+
408
+ // ---------- drafts: tie the draft a writing command printed to this session ----------
409
+
410
+ const WRITING = new RegExp(`${CALL}\\s+(rules?|lessons?|help|reply)(\\s|$)`);
411
+ const MARKER = /^Codehere draft id: ([0-9a-f]{8})$/;
412
+
413
+ // 'bound', 'refused' (a draft was printed but cannot be tied to the session), or null (no draft).
414
+ // Only the writing call itself may print the last line: it must come last, after nothing but cd.
415
+ // A draft git tracks came through git (a teammate force-added it), so it is never bound.
416
+ function bindDraft(root, input, command, text) {
417
+ const lines = text.split('\n').map((l) => l.trim()).filter(Boolean);
418
+ if (/^<shellId: .*>$/.test(lines.at(-1) || '')) lines.pop(); // Copilot's own last line
419
+ const m = MARKER.exec(lines.at(-1) || '');
420
+ if (!m) return null;
421
+ const parts = commandParts(command);
422
+ // only a writing call makes a draft: other output that ends in a marker is not Codehere's to explain
423
+ const wrote = parts ? parts.some((p) => WRITING.test(p.bare)) : /(^|[\s;&|])codehere\s+(rules?|lessons?|help|reply)(\s|$)/.test(command);
424
+ if (!wrote) return null;
425
+ const file = draftFile(root, m[1]);
426
+ const callOk = !!parts?.length && WRITING.test(parts.at(-1).bare) && parts.slice(0, -1).every((p) => /^\s*cd(\s|$)/.test(p.bare));
427
+ // by exact name, and git's list compared without case: on macOS ABCDEF12.json opens as abcdef12.json
428
+ const exact = !!file && fs.existsSync(path.dirname(file)) && fs.readdirSync(path.dirname(file)).includes(`${m[1]}.json`);
429
+ const rel = path.relative(root, file || '').toLowerCase();
430
+ const tracked = git(root, ['ls-files', '-z']).split('\0').some((x) => x.toLowerCase() === rel); // .CODEHERE/... too
431
+ if (!callOk || !exact || tracked) return 'refused';
432
+ const content = readPlain(file, null);
433
+ let rec = null;
434
+ try {
435
+ rec = JSON.parse(content);
436
+ } catch {}
437
+ // the file must still say what the person was shown: every line of it was in the output
438
+ if (!rec || !shownIn(rec, text)) return 'refused';
439
+ const kind = rec.kind;
440
+ const state = readState(root);
441
+ if (!input.session_id) return 'refused';
442
+ const s = session(state, input.session_id);
443
+ const entry = { id: m[1], kind, hash: crypto.createHash('sha256').update(content).digest('hex') };
444
+ // the lesson the agent drafts after the finish check's offer takes the proof kept for it
445
+ if (kind === 'lesson' && s.pendingLesson && typeof s.pendingLesson === 'object') {
446
+ entry.proof = s.pendingLesson;
447
+ delete s.pendingLesson;
448
+ }
449
+ s.drafts = [...(Array.isArray(s.drafts) ? s.drafts : []), entry];
450
+ delete s.lastSendBack; // any send-back came before this draft, so it cannot be the answer to it
451
+ return writeState(root, state) ? { proof: entry.proof || null } : 'refused'; // a binding that was not kept is not one
452
+ }
453
+
454
+ // The lines the CLI printed for this record (commands.js draft()), each indented by two spaces.
455
+ function shownIn(rec, text) {
456
+ const doc = (x) => (x && typeof x === 'object' ? renderDoc(x.meta || {}, String(x.body ?? x.text ?? '')).split('\n') : []);
457
+ 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)] : [];
458
+ const shown = lines.map((l) => String(l ?? '')).filter((l) => l.trim());
459
+ // whole printed lines, and for a reply the card it is for
460
+ const out = new Set(text.split('\n').map((l) => l.replace(/\r$/, '')));
461
+ const card = rec.kind !== 'reply' || out.has(printable(`Not saved yet. Draft of a reply to help card ${rec.card}:`));
462
+ return card && shown.length > 0 && shown.every((l) => out.has(` ${printable(l)}`));
463
+ }
464
+
465
+ 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.';
466
+ const noteFor = (agent, event, message) => (agent === 'copilot' ? { additionalContext: message } : { hookSpecificOutput: { hookEventName: event, additionalContext: message } });
467
+
256
468
  function matchLesson(root, sig, shown, test) {
257
469
  let best = null;
258
470
  for (const doc of listDocs(paths(root).lessons)) {
@@ -331,33 +543,42 @@ function lessonLine(doc) {
331
543
  return printable(`codehere › ${who}'s lesson given to the agent · ${lessonProof(doc) ? `verified on ${who}'s machine` : 'not verified'}${date}`);
332
544
  }
333
545
 
334
- // Codehere writes the proof fields itself; the agent fills in the title, cause and fix.
335
- function writeLesson(root, sig, proofCommand, changed, test) {
336
- const dir = paths(root).lessons;
337
- fs.mkdirSync(dir, { recursive: true });
338
- const name = `${today()}-${slug(sig, 30)}`;
339
- let file = path.join(dir, `${name}.md`);
340
- for (let i = 2; fs.existsSync(file); i++) file = path.join(dir, `${name}-${i}.md`);
341
- const meta = { title: PLACEHOLDERS[0], signature: sig, ...(test ? { test: redact(test).slice(0, 120) } : {}), author: me(root), date: today(), state: proofCommand ? 'verified' : 'unverified' };
546
+ // The proof the finish check keeps for a solved repeated error. Nothing is written: the agent offers
547
+ // the lesson, its draft takes this proof at binding, and the person's yes saves both. Only Codehere
548
+ // writes these fields; the signature is redacted like the test name, since it goes to the team.
549
+ function lessonProofFor(root, sig, proofCommand, changed, test) {
550
+ const proof = { signature: redact(sig), ...(test ? { test: redact(test).slice(0, 120) } : {}), state: proofCommand ? 'verified' : 'unverified' };
342
551
  if (proofCommand) {
343
- Object.assign(meta, {
552
+ Object.assign(proof, {
344
553
  proof_command: proofCommand,
345
554
  proof_exit: 0,
346
555
  proof_commit: git(root, ['rev-parse', '--short', 'HEAD']),
347
556
  proof_dirty: statusFiles(root).some((f) => !IGNORE(f)),
348
557
  });
349
558
  }
350
- meta.files = JSON.stringify(changed);
351
- meta.file_hashes = JSON.stringify(gitHashes(root, changed));
352
- fs.writeFileSync(file, renderDoc(meta, `## Fix\n- Cause: ${PLACEHOLDERS[1]}\n- Fix: ${PLACEHOLDERS[1]}\n`));
353
- return path.relative(root, file);
559
+ proof.files = JSON.stringify(changed);
560
+ proof.file_hashes = JSON.stringify(gitHashes(root, changed));
561
+ return proof;
562
+ }
563
+
564
+ // What the agent and the person are shown when an offered lesson's draft takes its proof. The
565
+ // person's line names the error, so a yes after a declined offer cannot attach it to another lesson unseen.
566
+ function proofNote(agent, event, proof) {
567
+ 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';
568
+ const context = `Codehere will add this to the lesson: the error "${noTick(proof.signature)}" and ${line}. Show the user this line with the draft.`;
569
+ if (agent === 'copilot') return { additionalContext: printable(context) };
570
+ return { systemMessage: printable(`codehere › lesson draft for "${short(noTick(String(proof.signature)))}" · ${line}`), hookSpecificOutput: { hookEventName: event, additionalContext: printable(context) } };
354
571
  }
355
572
 
356
573
  function postTool(root, input, agent) {
357
574
  if (input.tool_name && input.tool_name !== 'Bash') quiet();
358
575
  const command = (input.tool_input && input.tool_input.command) || '';
359
- if (readOnly(command)) quiet();
360
576
  const text = responseText(input.tool_response) + '\n' + (input.error || '');
577
+ // a refused draft never stops the error count: the note waits for a hook that has nothing else to say
578
+ const bind = bindDraft(root, input, command, text);
579
+ if (bind === 'refused') quietNote = noteFor(agent, input.hook_event_name || 'PostToolUse', NOT_BOUND);
580
+ else if (bind?.proof) quietNote = proofNote(agent, input.hook_event_name || 'PostToolUse', bind.proof);
581
+ if (ownOrReadOnly(command)) quiet();
361
582
  const sig = signature(text);
362
583
  if (!sig) {
363
584
  // the command that failed last now runs clean: that failure is over
@@ -402,9 +623,7 @@ function postTool(root, input, agent) {
402
623
  if (count > threshold) {
403
624
  msg.push(
404
625
  '',
405
- 'You are still stuck. Stop now. Tell the user in one short line that they can run',
406
- '`codehere help "<what you are stuck on>"` to send a ready-made help card to a teammate,',
407
- 'or `codehere brief` to restart in a fresh session. Then wait for the user.'
626
+ '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.'
408
627
  );
409
628
  }
410
629
  // Codex replaces the command's output with a block's text (or exit 2's), so the agent
@@ -438,6 +657,104 @@ function postTool(root, input, agent) {
438
657
  // ---------- UserPromptSubmit: restore what a short prompt leaves out ----------
439
658
  // One message at most, only about this session, under 300 tokens. Silent on normal turns.
440
659
 
660
+ // ---------- the person's answer to a draft ----------
661
+ // A draft is decided by the person's very next message: a plain yes saves it, anything else
662
+ // discards it. Notes go to the agent, lines to the person.
663
+ const RULES = '.codehere/rules.md';
664
+ function gist(rec) {
665
+ if (rec.kind === 'rule') return String(rec.line).replace(/^- /, '').replace(/ \([^()]*\)$/, '');
666
+ if (rec.kind === 'lesson') return String(rec.meta?.title ?? '');
667
+ if (rec.kind === 'help') return (/## Question\n(.+)/.exec(String(rec.text)) || [])[1] || '';
668
+ return String(rec.line).replace(/^- [^:]*\): /, '');
669
+ }
670
+ const short = (t) => (t.length > 60 ? `${t.slice(0, 60)}…` : t);
671
+
672
+ function decideDrafts(root, state, s, prompt) {
673
+ const notes = [];
674
+ const lines = [];
675
+ // Copilot passes a send-back to this hook as if the person typed it: that is not their answer
676
+ // used once: a later message that happens to start the same way is the person's
677
+ const skip = s.lastSendBack && prompt.startsWith(s.lastSendBack);
678
+ delete s.lastSendBack;
679
+ if (skip) return { notes, lines };
680
+ // since this session's previous prompt, or its start: an older draft is not this answer's
681
+ const since = Date.parse(s.lastPromptAt || s.startedAt || '') || Date.now();
682
+ s.lastPromptAt = new Date().toISOString();
683
+ const bound = (Array.isArray(s.drafts) ? s.drafts : []).filter((d) => d && typeof d === 'object' && /^[0-9a-f]{8}$/.test(String(d.id)));
684
+ const yes = plainYes(prompt);
685
+ let proofBack = null;
686
+ for (const d of bound) {
687
+ const file = draftFile(root, d.id);
688
+ // Taken by a rename, which only one of two hooks running at the same moment can win (two unlinks
689
+ // of one file both succeeded in a test on macOS); the other finds it gone and saves nothing.
690
+ let content = null;
691
+ try {
692
+ const taken = `${file}.${crypto.randomBytes(4).toString('hex')}.taken`;
693
+ fs.renameSync(file, taken);
694
+ content = readPlain(taken, null);
695
+ fs.rmSync(taken, { force: true });
696
+ } catch {
697
+ continue;
698
+ }
699
+ if (!yes) {
700
+ proofBack = d.proof || proofBack; // "change the title": the redraft keeps the proof
701
+ continue;
702
+ }
703
+ if (!content || crypto.createHash('sha256').update(content).digest('hex') !== d.hash) {
704
+ notes.push('Codehere did not save a draft: its file changed after it was shown to the user.');
705
+ lines.push('codehere ✕ not saved · the draft changed after it was shown');
706
+ continue;
707
+ }
708
+ let rec = null;
709
+ try {
710
+ rec = JSON.parse(content);
711
+ } catch {}
712
+ const before = settingsSnapshot(root)[RULES];
713
+ const teamBefore = teamMark(root);
714
+ const saved = saveRecord(root, rec, d.proof || null);
715
+ if (saved.error) {
716
+ notes.push(`Codehere could not save the draft: ${saved.error}`);
717
+ lines.push(`codehere ✕ not saved · ${noTick(saved.error)}`);
718
+ continue;
719
+ }
720
+ // a saved rule is not a settings change, unless rules.md had already changed this session
721
+ if (rec.kind === 'rule' && s.settings && s.settings[RULES] === before) s.settings[RULES] = settingsSnapshot(root)[RULES];
722
+ const teamAfter = teamSnapshot(root);
723
+ for (const x of Object.values(state.sessions)) keepSaved(x, teamBefore, teamAfter); // every open session: the save is not its agent's either
724
+ 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.`);
725
+ // the agent's own words: never a tick in a codehere line (DESIGN.md §1)
726
+ lines.push(`codehere › saved after your yes · ${rec.kind} · ${short(noTick(gist(rec)))}`);
727
+ }
728
+ if (bound.length && !yes) {
729
+ notes.push("Codehere discarded the draft because the user's reply was not a plain yes. If they still want it, draft it again.");
730
+ 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
731
+ }
732
+ // a yes that a draft made this turn did not reach (for example a binding lost to a parallel call)
733
+ if (yes && draftMadeSince(root, state, since)) {
734
+ 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.`);
735
+ 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');
736
+ }
737
+ s.drafts = [];
738
+ if (proofBack) s.pendingLesson = proofBack;
739
+ else delete s.pendingLesson;
740
+ return { notes, lines };
741
+ }
742
+
743
+ // An unbound draft made since then: one bound in any session is that session's to decide.
744
+ function draftMadeSince(root, state, since) {
745
+ try {
746
+ const dir = path.dirname(draftFile(root, '00000000'));
747
+ const bound = new Set(Object.values(state.sessions).flatMap((x) => (Array.isArray(x.drafts) ? x.drafts.map((d) => `${d.id}.json`) : [])));
748
+ 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);
749
+ if (!fresh.length) return false;
750
+ // a draft git tracks came through git (a pull), not from a command this session ran
751
+ const tracked = new Set(git(root, ['ls-files', '-z']).split('\0').map((x) => path.basename(x).toLowerCase()));
752
+ return fresh.some((f) => !tracked.has(f));
753
+ } catch {
754
+ return false;
755
+ }
756
+ }
757
+
441
758
  function promptSubmit(root, input) {
442
759
  if (!input.session_id) quiet(); // without it, sessions cannot be told apart
443
760
  const prompt = String(input.prompt || '');
@@ -447,6 +764,11 @@ function promptSubmit(root, input) {
447
764
  s.transcript = input.transcript_path || s.transcript;
448
765
  s.prompts = (s.prompts || 0) + 1;
449
766
  if (!s.settings) s.settings = settingsSnapshot(root); // session start did not run for this session
767
+ if (!isMap(s.team)) {
768
+ s.team = teamSnapshot(root);
769
+ s.teamHead = git(root, 'rev-parse HEAD') || null;
770
+ }
771
+ const decided = decideDrafts(root, state, s, prompt);
450
772
 
451
773
  // Only a failure from the agent's last turn counts: an older one may be fixed or forgotten.
452
774
  const f = s.lastFailure && (s.lastFailure.prompt || 0) === s.prompts - 1 ? s.lastFailure : null;
@@ -471,7 +793,7 @@ function promptSubmit(root, input) {
471
793
  msg = [
472
794
  `Codehere: this session is long (about ${Math.round(transcriptTokens(s) / 1000)}k tokens) and the same error came back ${repeats} times.`,
473
795
  'Fresh sessions with one clear spec fix bugs better than long ones.',
474
- 'In one line, suggest the user run `codehere brief` and start a new session (it loads the brief). Then continue with their request.',
796
+ 'In one line, offer to write a restart brief for a fresh session. Then continue with their request.',
475
797
  ].join('\n');
476
798
  } else if (!f && !s.askedHowToCheck && vagueFeature(prompt)) {
477
799
  s.askedHowToCheck = true;
@@ -484,8 +806,12 @@ function promptSubmit(root, input) {
484
806
  }
485
807
 
486
808
  writeState(root, state);
487
- if (msg) {
488
- emitJson({ hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: msg.slice(0, 1100) } });
809
+ const context = [...decided.notes, ...(msg ? [msg.slice(0, 1100)] : [])].join('\n\n');
810
+ if (context || decided.lines.length) {
811
+ emitJson({
812
+ ...(decided.lines.length ? { systemMessage: decided.lines.map(printable).join('\n') } : {}),
813
+ ...(context ? { hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: context } } : {}),
814
+ });
489
815
  }
490
816
  quiet();
491
817
  }
@@ -576,13 +902,28 @@ function stop(root, input) {
576
902
  const state = readState(root);
577
903
  const s = session(state, input.session_id);
578
904
  const mayBlock = (s.stopBlocks || 0) < 3; // never trap the agent: after 3 blocks, only observe
905
+ // The first line of each reason is kept: Copilot passes a send-back to the prompt hook as if the
906
+ // person typed it, and the prompt hook must not take it as their answer to a draft.
907
+ // A send-back that cannot be counted is not sent: without the count the 3-block cap would never
908
+ // stop the agent. The developer still gets what was found and why the agent was not sent back.
909
+ // carryOn: a finding that comes before the test run goes in the report and the check goes on, so
910
+ // the test result is not hidden behind it.
911
+ const sendAgentBack = (reason, message, carryOn = false) => {
912
+ s.lastSendBack = reason.split('\n')[0];
913
+ if (writeState(root, state)) block(reason, message);
914
+ const found = reason.split('\n').filter((l) => l.startsWith('- ')).map((l) => l.slice(2));
915
+ const why = `codehere ✕ ${noTick([s.lastSendBack, ...found].join(' ')).slice(0, 160)} · not sent back · Codehere could not save its state in .codehere/local`;
916
+ if (carryOn) return void lines.push(why);
917
+ emitJson({ systemMessage: [String(message || '').replace(/ · agent sent back · \d+ of 3/, ''), printable(why)].filter(Boolean).join('\n') });
918
+ };
579
919
 
580
920
  if (!isGitRepo(root)) quiet();
581
921
  const base = commitId(s.startHead) || 'HEAD';
582
922
  const changed = changedThisSession(root, s);
583
923
  const settings = settingsChanged(root, s);
584
924
  const removed = removedAt(root);
585
- if (!changed.length && !settings.length && !removed) quiet(); // the agent changed nothing this session: stay silent
925
+ const team = teamChanged(root, s);
926
+ if (!changed.length && !settings.length && !removed && !team.length) quiet(); // the agent changed nothing this session: stay silent
586
927
 
587
928
  // Lines for the developer. Each is escaped as a whole, so text from the repo cannot fake a
588
929
  // line, and text from the repo never carries a tick (noTick).
@@ -593,6 +934,7 @@ function stop(root, input) {
593
934
  if (a.at > (s.startedAt || '')) all.push(`codehere › approved on this machine during this session: ${noTick(a.command)}`);
594
935
  }
595
936
  if (settings.length) all.push(`codehere ✕ settings changed during this session · ${settings.join(' · ')}`);
937
+ if (team.length) all.push(`codehere ✕ team files changed during this session, not saved by Codehere · ${noTick(team.slice(0, 5).join(' · '))}${team.length > 5 ? ` · and ${team.length - 5} more` : ''}`);
596
938
  if (removed) all.push(removedLine(removed));
597
939
  return all.map(printable).join('\n');
598
940
  }
@@ -601,6 +943,8 @@ function stop(root, input) {
601
943
  if (m) emitJson({ systemMessage: m });
602
944
  quiet();
603
945
  }
946
+ // only lessons or help cards changed: the person gets the line, and the tests are not run
947
+ if (!changed.length && !settings.length && !removed) report();
604
948
 
605
949
  // 1. tampering with tests or checks (only in files changed this session)
606
950
  let findings = [];
@@ -616,13 +960,15 @@ function stop(root, input) {
616
960
  s.tamperReported = key;
617
961
  s.stopBlocks++;
618
962
  writeState(root, state);
619
- block(
963
+ sendAgentBack(
620
964
  [
621
965
  'Codehere found changes that weaken tests or checks:',
622
966
  ...findings.map((f) => `- ${f}`),
623
967
  'Restore them and fix the code instead.',
624
968
  'If the change is truly intended, tell the user in one line why, then finish.',
625
- ].join('\n')
969
+ ].join('\n'),
970
+ null,
971
+ true
626
972
  );
627
973
  }
628
974
 
@@ -635,13 +981,15 @@ function stop(root, input) {
635
981
  s.settingsReported = settingsKey;
636
982
  s.stopBlocks++;
637
983
  writeState(root, state);
638
- block(
984
+ sendAgentBack(
639
985
  [
640
986
  'Codehere settings or hook settings changed during this session:',
641
987
  ...settings.map((f) => `- ${f}`),
642
988
  'If you changed them and the user did not ask for it, undo your change.',
643
989
  'Then tell the user in one line what changed and why, and finish.',
644
- ].join('\n')
990
+ ].join('\n'),
991
+ null,
992
+ true
645
993
  );
646
994
  }
647
995
 
@@ -661,6 +1009,9 @@ function stop(root, input) {
661
1009
  let proven = false; // passed here, now, with intact tests and an unchanged config
662
1010
  if (cfg.verifyOnStop && approved) {
663
1011
  const t = runTests(root, cfg);
1012
+ // saves made while the tests ran moved snapshots on disk, and this hook writes the whole state back
1013
+ const disk = readState(root).sessions || {};
1014
+ for (const [k, x] of Object.entries(state.sessions)) if (isMap(disk[k]?.team)) Object.assign(x, { team: disk[k].team, teamHead: disk[k].teamHead });
664
1015
  if (!t.ok && !mayBlock) {
665
1016
  lines.push(`codehere ✕ ${cmd} · ${runResult(t)} · not sent back, limit of 3 reached`);
666
1017
  writeState(root, state);
@@ -670,7 +1021,7 @@ function stop(root, input) {
670
1021
  s.stopBlocks++;
671
1022
  writeState(root, state);
672
1023
  const tail = t.output.split('\n').slice(-25).join('\n');
673
- block(
1024
+ sendAgentBack(
674
1025
  [
675
1026
  `Codehere ran \`${cmd}\` and it ${t.timedOut ? 'timed out' : 'failed'}. The task is not done yet.`,
676
1027
  ...(t.code === 0 && !t.timedOut ? ['Its own summary counts failed tests, though the command exited 0.'] : []),
@@ -695,28 +1046,30 @@ function stop(root, input) {
695
1046
  lines.unshift(passLine);
696
1047
  }
697
1048
 
698
- // 4. turn a solved repeated error into a team lesson (once per session). After the 3-block
699
- // cap the agent is not asked to fill it in; the developer is told instead.
1049
+ // 4. a solved repeated error: the agent offers it to the team as a lesson (once per session).
1050
+ // Nothing is written here; the proof waits in the session for the lesson draft, and the person's
1051
+ // yes saves it. After the 3-block cap there is no offer, and the developer is told.
700
1052
  const solved = Object.entries(s.errors).filter(([, n]) => n >= 2);
701
1053
  if (solved.length && !s.lessonAsked) {
702
1054
  s.lessonAsked = true;
703
1055
  const [sig] = solved.sort((a, b) => b[1] - a[1])[0];
704
1056
  const named = s.tests && s.tests[sig];
705
- const file = writeLesson(root, sig, proven ? cfg.testCommand : null, changed, typeof named === 'string' ? named : '');
706
1057
  if (mayBlock) {
1058
+ s.pendingLesson = lessonProofFor(root, sig, proven ? cfg.testCommand : null, changed, typeof named === 'string' ? named : '');
707
1059
  s.stopBlocks++;
708
- writeState(root, state);
709
- block(
1060
+ sendAgentBack(
710
1061
  [
711
- `Before you finish: you hit and solved a repeated error ("${sig}").`,
712
- `Codehere saved it for the team in ${file}${proven ? ', with this test run as proof' : ''}.`,
713
- 'In that file, replace the three <...> placeholders (title, Cause, Fix) with one line each.',
714
- 'Do not change the other fields. Then finish your reply as normal. Do not mention this step unless asked.',
1062
+ // the first line is fixed text: Copilot sends the reason back as a prompt, and the skip
1063
+ // compares this line, so the error's own text must not be in it
1064
+ 'Before you finish: you hit and solved a repeated error.',
1065
+ `The error: ${printable(noTick(sig))}`,
1066
+ '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.',
1067
+ `Codehere adds ${proven ? 'this test run as proof' : 'the error and the changed files'}; it saves the lesson only if the user says yes.`,
715
1068
  ].join('\n'),
716
- message()
1069
+ message(),
1070
+ true
717
1071
  );
718
- }
719
- lines.push(`codehere › lesson saved: ${file} · fill in its title, cause and fix`);
1072
+ } else lines.push('codehere › repeated error solved · not offered as a lesson · limit of 3 reached');
720
1073
  }
721
1074
 
722
1075
  writeState(root, state);