codehere 2.0.3 → 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 +42 -14
- package/bin/codehere.js +4 -1
- package/package.json +1 -1
- package/src/brain.js +244 -13
- package/src/commands.js +182 -65
- package/src/hooks.js +369 -63
- package/src/signals.js +9 -0
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
|
|
|
@@ -153,13 +178,14 @@ function sessionStart(root, input, agent) {
|
|
|
153
178
|
quiet();
|
|
154
179
|
}
|
|
155
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).
|
|
156
184
|
function briefFile(root, file) {
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
return null;
|
|
162
|
-
}
|
|
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;
|
|
163
189
|
}
|
|
164
190
|
|
|
165
191
|
// ---------- what changed in THIS session ----------
|
|
@@ -201,11 +227,16 @@ const PROTECTED = [
|
|
|
201
227
|
'.github/hooks/', '.github/copilot/settings.json', '.github/copilot/settings.local.json',
|
|
202
228
|
];
|
|
203
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
|
+
}
|
|
204
235
|
function readProtected(root, f) {
|
|
205
|
-
if (!f.endsWith('/')) return
|
|
236
|
+
if (!f.endsWith('/')) return readProtectedFile(path.join(root, f));
|
|
206
237
|
const files = fs.readdirSync(path.join(root, f)).filter((n) => n.endsWith('.json')).sort();
|
|
207
238
|
if (!files.length) return null;
|
|
208
|
-
return files.map((n) => `${n}\0${
|
|
239
|
+
return files.map((n) => `${n}\0${readProtectedFile(path.join(root, f, n))}`).join('\0');
|
|
209
240
|
}
|
|
210
241
|
|
|
211
242
|
function settingsSnapshot(root) {
|
|
@@ -245,14 +276,162 @@ function settingsChanged(root, s) {
|
|
|
245
276
|
// `cd x && cat a; ls b` is read-only only if every part is. Quoted text is
|
|
246
277
|
// emptied first so `grep "error|fail"` stays one part, and a part that runs
|
|
247
278
|
// 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))\
|
|
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
|
+
}
|
|
249
361
|
export function readOnly(command) {
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
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
|
|
254
419
|
}
|
|
255
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
|
+
|
|
256
435
|
function matchLesson(root, sig, shown, test) {
|
|
257
436
|
let best = null;
|
|
258
437
|
for (const doc of listDocs(paths(root).lessons)) {
|
|
@@ -331,33 +510,42 @@ function lessonLine(doc) {
|
|
|
331
510
|
return printable(`codehere › ${who}'s lesson given to the agent · ${lessonProof(doc) ? `verified on ${who}'s machine` : 'not verified'}${date}`);
|
|
332
511
|
}
|
|
333
512
|
|
|
334
|
-
//
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
const
|
|
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' };
|
|
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' };
|
|
342
518
|
if (proofCommand) {
|
|
343
|
-
Object.assign(
|
|
519
|
+
Object.assign(proof, {
|
|
344
520
|
proof_command: proofCommand,
|
|
345
521
|
proof_exit: 0,
|
|
346
522
|
proof_commit: git(root, ['rev-parse', '--short', 'HEAD']),
|
|
347
523
|
proof_dirty: statusFiles(root).some((f) => !IGNORE(f)),
|
|
348
524
|
});
|
|
349
525
|
}
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
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) } };
|
|
354
538
|
}
|
|
355
539
|
|
|
356
540
|
function postTool(root, input, agent) {
|
|
357
541
|
if (input.tool_name && input.tool_name !== 'Bash') quiet();
|
|
358
542
|
const command = (input.tool_input && input.tool_input.command) || '';
|
|
359
|
-
if (readOnly(command)) quiet();
|
|
360
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();
|
|
361
549
|
const sig = signature(text);
|
|
362
550
|
if (!sig) {
|
|
363
551
|
// the command that failed last now runs clean: that failure is over
|
|
@@ -402,9 +590,7 @@ function postTool(root, input, agent) {
|
|
|
402
590
|
if (count > threshold) {
|
|
403
591
|
msg.push(
|
|
404
592
|
'',
|
|
405
|
-
'You are still stuck. Stop now.
|
|
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.'
|
|
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.'
|
|
408
594
|
);
|
|
409
595
|
}
|
|
410
596
|
// Codex replaces the command's output with a block's text (or exit 2's), so the agent
|
|
@@ -438,6 +624,101 @@ function postTool(root, input, agent) {
|
|
|
438
624
|
// ---------- UserPromptSubmit: restore what a short prompt leaves out ----------
|
|
439
625
|
// One message at most, only about this session, under 300 tokens. Silent on normal turns.
|
|
440
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
|
+
|
|
441
722
|
function promptSubmit(root, input) {
|
|
442
723
|
if (!input.session_id) quiet(); // without it, sessions cannot be told apart
|
|
443
724
|
const prompt = String(input.prompt || '');
|
|
@@ -447,6 +728,7 @@ function promptSubmit(root, input) {
|
|
|
447
728
|
s.transcript = input.transcript_path || s.transcript;
|
|
448
729
|
s.prompts = (s.prompts || 0) + 1;
|
|
449
730
|
if (!s.settings) s.settings = settingsSnapshot(root); // session start did not run for this session
|
|
731
|
+
const decided = decideDrafts(root, state, s, prompt);
|
|
450
732
|
|
|
451
733
|
// Only a failure from the agent's last turn counts: an older one may be fixed or forgotten.
|
|
452
734
|
const f = s.lastFailure && (s.lastFailure.prompt || 0) === s.prompts - 1 ? s.lastFailure : null;
|
|
@@ -471,7 +753,7 @@ function promptSubmit(root, input) {
|
|
|
471
753
|
msg = [
|
|
472
754
|
`Codehere: this session is long (about ${Math.round(transcriptTokens(s) / 1000)}k tokens) and the same error came back ${repeats} times.`,
|
|
473
755
|
'Fresh sessions with one clear spec fix bugs better than long ones.',
|
|
474
|
-
'In one line,
|
|
756
|
+
'In one line, offer to write a restart brief for a fresh session. Then continue with their request.',
|
|
475
757
|
].join('\n');
|
|
476
758
|
} else if (!f && !s.askedHowToCheck && vagueFeature(prompt)) {
|
|
477
759
|
s.askedHowToCheck = true;
|
|
@@ -484,8 +766,12 @@ function promptSubmit(root, input) {
|
|
|
484
766
|
}
|
|
485
767
|
|
|
486
768
|
writeState(root, state);
|
|
487
|
-
|
|
488
|
-
|
|
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
|
+
});
|
|
489
775
|
}
|
|
490
776
|
quiet();
|
|
491
777
|
}
|
|
@@ -576,6 +862,20 @@ function stop(root, input) {
|
|
|
576
862
|
const state = readState(root);
|
|
577
863
|
const s = session(state, input.session_id);
|
|
578
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
|
+
};
|
|
579
879
|
|
|
580
880
|
if (!isGitRepo(root)) quiet();
|
|
581
881
|
const base = commitId(s.startHead) || 'HEAD';
|
|
@@ -613,13 +913,15 @@ function stop(root, input) {
|
|
|
613
913
|
s.tamperReported = key;
|
|
614
914
|
s.stopBlocks++;
|
|
615
915
|
writeState(root, state);
|
|
616
|
-
|
|
916
|
+
sendAgentBack(
|
|
617
917
|
[
|
|
618
918
|
'Codehere found changes that weaken tests or checks:',
|
|
619
919
|
...findings.map((f) => `- ${f}`),
|
|
620
920
|
'Restore them and fix the code instead.',
|
|
621
921
|
'If the change is truly intended, tell the user in one line why, then finish.',
|
|
622
|
-
].join('\n')
|
|
922
|
+
].join('\n'),
|
|
923
|
+
null,
|
|
924
|
+
true
|
|
623
925
|
);
|
|
624
926
|
}
|
|
625
927
|
|
|
@@ -632,13 +934,15 @@ function stop(root, input) {
|
|
|
632
934
|
s.settingsReported = settingsKey;
|
|
633
935
|
s.stopBlocks++;
|
|
634
936
|
writeState(root, state);
|
|
635
|
-
|
|
937
|
+
sendAgentBack(
|
|
636
938
|
[
|
|
637
939
|
'Codehere settings or hook settings changed during this session:',
|
|
638
940
|
...settings.map((f) => `- ${f}`),
|
|
639
941
|
'If you changed them and the user did not ask for it, undo your change.',
|
|
640
942
|
'Then tell the user in one line what changed and why, and finish.',
|
|
641
|
-
].join('\n')
|
|
943
|
+
].join('\n'),
|
|
944
|
+
null,
|
|
945
|
+
true
|
|
642
946
|
);
|
|
643
947
|
}
|
|
644
948
|
|
|
@@ -666,7 +970,7 @@ function stop(root, input) {
|
|
|
666
970
|
s.stopBlocks++;
|
|
667
971
|
writeState(root, state);
|
|
668
972
|
const tail = t.output.split('\n').slice(-25).join('\n');
|
|
669
|
-
|
|
973
|
+
sendAgentBack(
|
|
670
974
|
[
|
|
671
975
|
`Codehere ran \`${cmd}\` and it ${t.timedOut ? 'timed out' : 'failed'}. The task is not done yet.`,
|
|
672
976
|
...(t.code === 0 && !t.timedOut ? ['Its own summary counts failed tests, though the command exited 0.'] : []),
|
|
@@ -690,28 +994,30 @@ function stop(root, input) {
|
|
|
690
994
|
lines.unshift(passLine);
|
|
691
995
|
}
|
|
692
996
|
|
|
693
|
-
// 4.
|
|
694
|
-
//
|
|
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.
|
|
695
1000
|
const solved = Object.entries(s.errors).filter(([, n]) => n >= 2);
|
|
696
1001
|
if (solved.length && !s.lessonAsked) {
|
|
697
1002
|
s.lessonAsked = true;
|
|
698
1003
|
const [sig] = solved.sort((a, b) => b[1] - a[1])[0];
|
|
699
1004
|
const named = s.tests && s.tests[sig];
|
|
700
|
-
const file = writeLesson(root, sig, proven ? cfg.testCommand : null, changed, typeof named === 'string' ? named : '');
|
|
701
1005
|
if (mayBlock) {
|
|
1006
|
+
s.pendingLesson = lessonProofFor(root, sig, proven ? cfg.testCommand : null, changed, typeof named === 'string' ? named : '');
|
|
702
1007
|
s.stopBlocks++;
|
|
703
|
-
|
|
704
|
-
block(
|
|
1008
|
+
sendAgentBack(
|
|
705
1009
|
[
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
'
|
|
709
|
-
|
|
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.`,
|
|
710
1016
|
].join('\n'),
|
|
711
|
-
message()
|
|
1017
|
+
message(),
|
|
1018
|
+
true
|
|
712
1019
|
);
|
|
713
|
-
}
|
|
714
|
-
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');
|
|
715
1021
|
}
|
|
716
1022
|
|
|
717
1023
|
writeState(root, state);
|
package/src/signals.js
CHANGED
|
@@ -75,6 +75,15 @@ const REPAIR =
|
|
|
75
75
|
const POSITIVE = /\b(thanks|thank you|thx|works now|working now|great|nice|good|perfect|awesome|mantap|makasih|terima kasih|sip|berhasil|sudah bisa|udah bisa)\b/i;
|
|
76
76
|
|
|
77
77
|
// "still broken", "fix it", "masih error": short, no specifics, asks for a repair.
|
|
78
|
+
// The person's answer to a draft: a yes word, optionally with one polite word. A fixed list, in the
|
|
79
|
+
// style of askApproval(), so no model decides what is saved for the team.
|
|
80
|
+
const YES = new Set(['yes', 'y', 'yep', 'yeah', 'ok', 'okay', 'sure', 'save', 'save it', 'go ahead', 'do it', 'ya', 'iya', 'oke', 'boleh', 'simpan']);
|
|
81
|
+
export function plainYes(p) {
|
|
82
|
+
const t = String(p || '').trim().toLowerCase().replace(/[.!]+$/, '').trim();
|
|
83
|
+
const m = /^(.+?)(?:[\s,]+(?:please|thanks|thank you|makasih|dong))?$/.exec(t);
|
|
84
|
+
return !!m && YES.has(m[1].trim());
|
|
85
|
+
}
|
|
86
|
+
|
|
78
87
|
export function lowInfoPrompt(p) {
|
|
79
88
|
const w = words(p);
|
|
80
89
|
if (!w.length || w.length > 8 || SPECIFIC.test(p) || POSITIVE.test(p)) return false;
|