codehere 2.1.0-rc.3 → 2.1.0-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -98,7 +98,7 @@ Don't want to commit help cards? Copy the printed text into WhatsApp, Discord or
98
98
  | Ask the agent for a team chore, saved on your yes | yes: 12 of 12 runs (rule, help card, answer a card, lesson; [result](docs/conformance/2026-11-03-claude-2.1.317-haiku-chores.md)) | partly, with a 9B local model: lesson 2 of 3, rule, help card and answer 0 of 3; the agent wrote the team files itself ([result](docs/conformance/2026-11-03-codex-0.164.0-qwen3.5-9b-q4_K_M-chores.md), [lesson](docs/conformance/2026-11-03-codex-0.164.0-qwen3.5-9b-q4_K_M-chores-L10.md)) | partly, with a 9B local model: rule and answer 3 of 3, help card and lesson 0 of 3 ([result](docs/conformance/2026-11-03-copilot-1.0.105-qwen3.5-9b-q4_K_M-chores.md)) |
99
99
  | Before it works | nothing | each developer trusts the hooks in `/hooks` | each developer trusts the folder when Copilot asks |
100
100
  | MCP tools, instruction file | no | no | no |
101
- | Tested on | 2.1.311 with haiku: [result](docs/conformance/2026-10-27-claude-2.1.311-haiku.md) | 0.164.0 with a local model (Qwen 3.5 9B through Ollama): [result](docs/conformance/2026-10-27-codex-0.164.0-qwen3.5-9b-q4-K-M.md) | 1.0.105 with a local model (Qwen 3.5 9B through Ollama): [result](docs/conformance/2026-10-29-copilot-1.0.105-qwen3.5-9b-q4-K-M.md), with only the Claude Code hooks installed: [result](docs/conformance/2026-10-29-copilot-1.0.105-qwen3.5-9b-q4-K-M-claude-hooks-only.md), and with a GitHub-hosted model (`auto`, which picked gpt-6-luna): [result](docs/conformance/2026-10-29-copilot-1.0.105-auto.md) |
101
+ | Tested on | 2.1.323 with haiku, on 2.1.0-rc.3 from npm, 3 runs: [results](docs/evidence/2026-11-14-live-claude.md) | 0.164.0 with a local model (Qwen 3.5 9B through Ollama), on 2.1.0-rc.3 from npm, 3 runs: [results](docs/evidence/2026-11-14-live-codex.md) | 1.0.105 with a local model (Qwen 3.5 9B through Ollama), on 2.1.0-rc.3 from npm, 3 runs: [results](docs/evidence/2026-11-14-live-copilot.md); on 2.0.x, with only the Claude Code hooks installed: [result](docs/conformance/2026-10-29-copilot-1.0.105-qwen3.5-9b-q4-K-M-claude-hooks-only.md), and with a GitHub-hosted model (`auto`, which picked gpt-6-luna): [result](docs/conformance/2026-10-29-copilot-1.0.105-auto.md) |
102
102
 
103
103
  The rows for rules, lessons and the finish check are checked on the real agent by `node scripts/conformance.mjs`, and the chores row by `node scripts/chores.mjs` (3 runs per chore, each in a fresh repo). The other rows are checked by `npm test` on hook inputs recorded from each agent.
104
104
 
@@ -145,7 +145,7 @@ Everything is plain markdown, so you can read, edit, review and delete it like a
145
145
  - **No AI in the decision path.** Loops, failed tests and tampering are detected with plain rules, so Codehere doesn't inherit the agent's mistakes.
146
146
  - **It talks to the agent, not to you.** If Codehere is wrong, the agent does one extra check. You lose nothing. For team chores, you ask your agent, and it shows you a draft first.
147
147
  - **Silent on normal turns.** Your prompt gets extra context only after a failure, for a feature with no way to check it, or in a long session stuck on one error. Each at most once, under 300 tokens. After you answer a draft, you also get one line saying whether it was saved.
148
- - **It only reacts to this session's work.** Changes you had before the session are ignored. If the agent changed nothing, Codehere does nothing. A draft saved after your yes does not count as a change by the agent.
148
+ - **It only reacts to this session's work.** Changes you had before the session are ignored. If the agent changed nothing, Codehere does nothing. A session Codehere did not see start (set up mid-session) is checked at each finish and says there is no record of its test files. A draft saved after your yes does not count as a change by the agent.
149
149
  - **It never traps the agent.** At most 3 "not done yet" messages per session, then it lets go.
150
150
  - **It fails open.** If anything breaks, the hook exits quietly and the agent carries on.
151
151
  - **Small model, small job.** Gemma 4 (via Ollama) is optional and only writes summaries for briefs and help cards, which you read before using. Turn it on with `--gemma`. The text goes only to a model on this machine: Codehere refuses an `OLLAMA_HOST` on another machine and Ollama cloud models, and uses the plain text instead.
@@ -164,7 +164,8 @@ npm test # end-to-end checks
164
164
  - Claude Code, Codex CLI and Copilot CLI. OpenCode is next. Copilot in VS Code reads the same hook files but has not been checked, and Copilot's cloud agent is not supported. See [Which agents](#which-agents) for what works on each.
165
165
  - Lessons match by error text: at least 0.45 of the words in the two error lines must be shared (words in both, divided by words in either). When both the failure and the lesson name a failing test, the names must be the same, so a lesson for a failed `assert.equal` reaches only a failing test with the same name. Two tests with the same name in different files or suites still share lessons. A generic error outside a test can bring up a lesson that doesn't fit, which is why the agent gets it as reference, not as an instruction.
166
166
  - Redaction catches common keys, tokens and emails. Always read a help card before sharing it.
167
- - The "done" check needs a test command. Without one, only the tampering check runs.
167
+ - The "done" check needs a test command. Without one, only the tampering check runs. A run where the test runner reports 0 passed (every test skipped, or none found) gets no ✓; for runners whose count Codehere cannot read, the ✓ line says "exit 0" instead of a count.
168
+ - The finish check checks the work of an agent doing its task. It is not a sandbox: an agent that sets out to defeat it through git's own machinery (index flags such as assume-unchanged, replace refs, `core.bare`, moving `.git`, a test folder swapped for a link) can hide a change from it. What the ✓ promises, and what is out of scope, is in [docs/finish-check-promise.md](docs/finish-check-promise.md).
168
169
  - Approvals are per folder. Each git worktree or extra clone needs its own `codehere approve`.
169
170
  - In `codex exec`, Codex shows you none of Codehere's lines. The agent still gets every message, and the finish check still sends it back.
170
171
  - Copilot shows you none of Codehere's lines either, so on Copilot you do not see the ✓, the ⊘, or the notes about an approval, an uninstall, a settings change or team files changed during a session. The agent gets every message except what Codehere adds to your prompt (Copilot drops that, so its agent is not told when a draft is saved or discarded), and when the finish check sends it back you see the reason as the next prompt.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codehere",
3
- "version": "2.1.0-rc.3",
3
+ "version": "2.1.0-rc.4",
4
4
  "description": "A git-native team brain for vibe coders. Silent fixes for AI coding agents: breaks doom loops, verifies 'done', blocks test tampering, and shares what your team learned.",
5
5
  "repository": {
6
6
  "type": "git",
package/src/audit.js CHANGED
@@ -2,9 +2,9 @@
2
2
  // Read-only: it runs git on this machine and sends nothing anywhere. The kinds come from the finish
3
3
  // check's own detector. A count found by pattern is a list of candidates, never proof (DESIGN.md §1).
4
4
  import { spawn, execFileSync } from 'node:child_process';
5
- import readline from 'node:readline';
6
- import { printable, hasGit } from './brain.js';
5
+ import { printable, hasGit, gitRead, PLAIN_DIFF, GIT_ENV, GIT_TIMEOUT } from './brain.js';
7
6
  import { tamperEvents, isTestFile, isTestConfig } from './signals.js';
7
+ import { unquotePath, hunkReader } from './gitpath.js';
8
8
 
9
9
  const DAYS = 90;
10
10
  const KINDS = new Set(['test-deleted', 'test-skipped', 'assertion-weakened']);
@@ -31,7 +31,7 @@ export function markersOf(author, body) {
31
31
 
32
32
  function gitLine(root, args) {
33
33
  try {
34
- return execFileSync('git', args, { cwd: root, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim();
34
+ return execFileSync('git', args, { cwd: root, stdio: ['ignore', 'pipe', 'ignore'], env: GIT_ENV, timeout: GIT_TIMEOUT }).toString().trim();
35
35
  } catch {
36
36
  return null;
37
37
  }
@@ -43,6 +43,7 @@ function commitsSince(root, since) {
43
43
  cwd: root,
44
44
  stdio: ['ignore', 'pipe', 'ignore'],
45
45
  maxBuffer: BIG,
46
+ env: GIT_ENV,
46
47
  }).toString();
47
48
  return out
48
49
  .split('\x1e')
@@ -55,7 +56,13 @@ function commitsSince(root, since) {
55
56
  }
56
57
 
57
58
  // The path in `diff --git a/P b/P` when both sides name the same file, as they do for a deletion.
59
+ // Git quotes both sides of a path it escapes: diff --git "a/caf\303\251.js" "b/caf\303\251.js".
58
60
  function samePath(line) {
61
+ const q = /^diff --git ("(?:[^"\\]|\\.)*") ("(?:[^"\\]|\\.)*")$/.exec(line);
62
+ if (q) {
63
+ const [a, b] = [unquotePath(q[1]), unquotePath(q[2])];
64
+ return a.startsWith('a/') && b === `b/${a.slice(2)}` ? a.slice(2) : '';
65
+ }
59
66
  const rest = line.slice('diff --git a/'.length);
60
67
  const half = (rest.length - ' b/'.length) / 2;
61
68
  return Number.isInteger(half) && rest.slice(half, half + 3) === ' b/' ? rest.slice(0, half) : '';
@@ -66,53 +73,79 @@ function samePath(line) {
66
73
  // memory stays small however large a commit is. Each commit's kinds go on its entry in bySha.
67
74
  function scanChanges(root, since, bySha) {
68
75
  return new Promise((resolve, reject) => {
69
- const child = spawn('git', ['log', '--no-merges', `--since=${since}`, '-p', '--no-color', '--format=%x00%H'], {
76
+ const child = spawn('git', ['log', ...PLAIN_DIFF, '--no-merges', `--since=${since}`, '-p', '--format=%x00%H'], {
70
77
  cwd: root,
71
78
  stdio: ['ignore', 'pipe', 'ignore'],
79
+ env: GIT_ENV,
72
80
  });
73
- const lines = readline.createInterface({ input: child.stdout, crlfDelay: Infinity });
74
81
  let commit = null;
82
+ let sha = '';
83
+ let inHunk = hunkReader();
75
84
  let nameStatus = [];
76
85
  let kept = [];
77
86
  let keep = false;
78
87
  let deleted = '';
88
+ let renamedFrom = '';
79
89
  const finish = () => {
80
- if (commit) commit.events = tamperEvents(nameStatus.join('\n'), kept.join('\n')).filter((e) => KINDS.has(e.kind));
90
+ // the repo's test files before that commit, for a test renamed to another code extension
91
+ const at = sha;
92
+ const testFiles = () => (gitRead(root, ['ls-tree', '-r', '-z', '--name-only', `${at}^`]) ?? '').split('\0').filter(isTestFile);
93
+ if (commit) commit.events = tamperEvents(nameStatus.join('\n'), kept.join('\n'), { testFiles }).filter((e) => KINDS.has(e.kind));
81
94
  };
82
- lines.on('line', (line) => {
95
+ const onLine = (line) => {
83
96
  if (line.startsWith('\0')) {
84
97
  finish();
85
- commit = bySha.get(line.slice(1)) || null;
98
+ sha = line.slice(1);
99
+ commit = bySha.get(sha) || null;
100
+ inHunk = hunkReader();
86
101
  nameStatus = [];
87
102
  kept = [];
88
103
  keep = false;
89
104
  return;
90
105
  }
91
106
  if (!commit) return;
107
+ const body = inHunk(line); // in a hunk, "+++ n;" is an added "++ n;", not a file header
92
108
  if (line.startsWith('diff --git ')) {
93
109
  keep = false;
94
110
  deleted = samePath(line);
95
111
  return;
96
112
  }
113
+ if (line.startsWith('rename from ')) {
114
+ renamedFrom = unquotePath(line.slice('rename from '.length));
115
+ return;
116
+ }
117
+ if (line.startsWith('rename to ')) {
118
+ if (isTestFile(renamedFrom)) nameStatus.push(`R\t${renamedFrom}\t${unquotePath(line.slice('rename to '.length))}`);
119
+ renamedFrom = '';
120
+ return;
121
+ }
97
122
  if (line.startsWith('deleted file mode')) {
98
123
  if (deleted && isTestFile(deleted)) nameStatus.push(`D\t${deleted}`);
99
124
  deleted = '';
100
125
  keep = false;
101
126
  return;
102
127
  }
103
- if (line.startsWith('+++ ')) {
104
- const file = line.replace(/^\+\+\+ (b\/)?/, '');
128
+ if (!body && line.startsWith('+++ ')) {
129
+ const file = unquotePath(line.slice(4)).replace(/^b\//, '');
105
130
  keep = file !== '/dev/null' && (isTestFile(file) || isTestConfig(file));
106
131
  if (keep) kept.push(`+++ ${file}`);
107
132
  return;
108
133
  }
109
- if (keep && !line.startsWith('--- ')) kept.push(line);
134
+ if (keep && (body || !line.startsWith('--- '))) kept.push(line);
135
+ };
136
+ // Lines end at \n only, as git writes them: readline also ends one at a lone \r inside a line, which puts
137
+ // the hunk reader out of step (cold review, L13 round 6).
138
+ let rest = '';
139
+ child.stdout.setEncoding('utf8');
140
+ child.stdout.on('data', (chunk) => {
141
+ const parts = (rest + chunk).split('\n');
142
+ rest = parts.pop();
143
+ parts.forEach(onLine);
110
144
  });
111
145
  let failed = null;
112
146
  child.on('error', (e) => (failed = e));
113
- const ended = new Promise((r) => lines.on('close', r));
114
- child.on('close', async (code) => {
115
- await ended;
147
+ child.on('close', (code) => {
148
+ if (rest) onLine(rest);
116
149
  finish();
117
150
  if (failed || code !== 0) reject(failed || new Error(`git log exited ${code}`));
118
151
  else resolve();
package/src/brain.js CHANGED
@@ -57,6 +57,13 @@ const DEFAULT_CONFIG = {
57
57
  // final link and without blocking, checked on the open file, and read up to max bytes: a linked
58
58
  // folder can still reach a file such as /proc/self/pagemap, which says it is plain and never ends.
59
59
  // encoding null gives a Buffer.
60
+ // A teammate can commit .codehere/ or a folder in it as a link to a folder outside the repo (git keeps
61
+ // links), so a brain file is read only when no part of its path below root is a link.
62
+ export function readOwn(root, file, encoding, max) {
63
+ if (!ownPath(root, file)) throw Object.assign(new Error(`linked path: ${file}`), { code: 'ENOTPLAIN' });
64
+ return readPlain(file, encoding, max);
65
+ }
66
+
60
67
  export function readPlain(file, encoding = 'utf8', max = 8 * 1024 * 1024) {
61
68
  const notPlain = () => Object.assign(new Error(`not a plain file: ${file}`), { code: 'ENOTPLAIN' });
62
69
  let fd;
@@ -82,7 +89,7 @@ export function readPlain(file, encoding = 'utf8', max = 8 * 1024 * 1024) {
82
89
  export function readConfig(root) {
83
90
  const p = paths(root);
84
91
  try {
85
- return { ...DEFAULT_CONFIG, ...JSON.parse(readPlain(p.config)) };
92
+ return { ...DEFAULT_CONFIG, ...JSON.parse(readOwn(root, p.config)) };
86
93
  } catch {
87
94
  return { ...DEFAULT_CONFIG };
88
95
  }
@@ -96,7 +103,7 @@ export function writeConfig(root, cfg) {
96
103
 
97
104
  export function readState(root) {
98
105
  try {
99
- const state = JSON.parse(readPlain(paths(root).state));
106
+ const state = JSON.parse(readOwn(root, paths(root).state));
100
107
  // state.json can arrive through git: a file of the wrong shape counts as empty
101
108
  if (state && state.sessions && typeof state.sessions === 'object') return state;
102
109
  } catch {}
@@ -110,12 +117,27 @@ export function readState(root) {
110
117
  // made with exclusive create, so no planted link at that name is followed. Never throws: false when
111
118
  // nothing was saved, and a caller that needs the state kept (the finish check's send-back count)
112
119
  // then holds back, while what it reports still goes out.
113
- export function writeState(root, state) {
120
+ // owned: the sessions this writer changed. Every other session is taken from the file as it is now, under a lock, so
121
+ // hooks running at once (two session starts, a finish check running the tests while another session starts or stops)
122
+ // neither drop each other's sessions nor write them back stale (cold review, L13 rounds 9 and 10). The top-level
123
+ // fields are taken from the file too, except those named in fields, which this writer set (round 11). Without owned,
124
+ // the state is written as given.
125
+ export function writeState(root, state, owned, fields = ['lastSession']) {
114
126
  const p = paths(root);
115
127
  if (!ownPath(root, p.local)) return false;
116
128
  const tmp = `${p.state}.${crypto.randomBytes(6).toString('hex')}.tmp`;
129
+ let lock = null;
117
130
  try {
118
131
  fs.mkdirSync(p.local, { recursive: true });
132
+ if (owned) {
133
+ lock = takeLock(`${p.state}.lock`);
134
+ const mine = new Set(owned);
135
+ const disk = readState(root);
136
+ for (const [k, v] of Object.entries(disk)) if (k !== 'sessions' && !fields.includes(k)) state[k] = v;
137
+ const sessions = { ...disk.sessions };
138
+ for (const k of mine) if (state.sessions[k]) sessions[k] = state.sessions[k];
139
+ state.sessions = keepRecent(sessions, mine);
140
+ }
119
141
  fs.writeFileSync(tmp, JSON.stringify(state, null, 2), { flag: 'wx' });
120
142
  fs.renameSync(tmp, p.state);
121
143
  return true;
@@ -124,9 +146,41 @@ export function writeState(root, state) {
124
146
  fs.rmSync(tmp, { force: true });
125
147
  } catch {} // local/ may be a file: there is no temporary file to remove
126
148
  return false;
149
+ } finally {
150
+ if (lock) fs.rmSync(lock, { force: true });
127
151
  }
128
152
  }
129
153
 
154
+ // A lock taken with an exclusive create, waited for up to 3 s; one older than 10 s is left by a hook that died. null
155
+ // when it cannot be taken: the write goes ahead without it, as a hook must not hang.
156
+ function takeLock(file) {
157
+ const until = Date.now() + 3000;
158
+ for (;;) {
159
+ try {
160
+ fs.writeFileSync(file, String(process.pid), { flag: 'wx' });
161
+ return file;
162
+ } catch (e) {
163
+ if (e.code !== 'EEXIST') return null;
164
+ try {
165
+ if (Date.now() - fs.lstatSync(file).mtimeMs > 10000) fs.rmSync(file, { force: true });
166
+ } catch {}
167
+ if (Date.now() > until) return null;
168
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
169
+ }
170
+ }
171
+ }
172
+
173
+ // keep the state file small: drop all but the 50 sessions active most recently (a long session still in use is kept,
174
+ // though newer ones started after it: rounds 9 and 10), never one in keep
175
+ function keepRecent(sessions, keep = new Set()) {
176
+ const keys = Object.keys(sessions);
177
+ if (keys.length <= 50) return sessions;
178
+ const seen = (k) => sessions[k].lastActive || sessions[k].startedAt || '';
179
+ const drop = keys.filter((k) => !keep.has(k)).sort((a, b) => seen(a).localeCompare(seen(b))).slice(0, keys.length - 50);
180
+ for (const k of drop) delete sessions[k];
181
+ return sessions;
182
+ }
183
+
130
184
  export function session(state, id) {
131
185
  const key = id || 'default';
132
186
  if (!state.sessions[key]) {
@@ -142,14 +196,7 @@ export function session(state, id) {
142
196
  }
143
197
  state.lastSession = key;
144
198
  state.sessions[key].lastActive = new Date().toISOString();
145
- // keep the state file small: drop sessions older than the 20 most recent
146
- const keys = Object.keys(state.sessions);
147
- if (keys.length > 20) {
148
- keys
149
- .sort((a, b) => (state.sessions[a].startedAt || '').localeCompare(state.sessions[b].startedAt || ''))
150
- .slice(0, keys.length - 20)
151
- .forEach((k) => delete state.sessions[k]);
152
- }
199
+ keepRecent(state.sessions, new Set([key]));
153
200
  return state.sessions[key];
154
201
  }
155
202
 
@@ -174,7 +221,7 @@ export function renderDoc(meta, body) {
174
221
  }
175
222
 
176
223
  export function listDocs(dir) {
177
- if (!fs.existsSync(dir)) return [];
224
+ if (!fs.existsSync(dir) || !ownPath(path.dirname(path.dirname(dir)), dir)) return []; // dir is <root>/.codehere/<folder>
178
225
  return fs
179
226
  .readdirSync(dir)
180
227
  .filter((f) => f.endsWith('.md'))
@@ -216,7 +263,7 @@ export function readRules(root) {
216
263
  const file = paths(root).rules;
217
264
  let text = '';
218
265
  try {
219
- text = readPlain(file);
266
+ text = readOwn(root, file);
220
267
  } catch {
221
268
  return [];
222
269
  }
@@ -332,62 +379,126 @@ export function printable(text) {
332
379
 
333
380
  // ---------- git helpers (all fail-safe) ----------
334
381
 
335
- // Pass an array whenever an argument comes from the repo or the state file: it never
336
- // goes through a shell, so a file name such as a$(cmd).js stays a file name.
337
- // raw keeps the output as git wrote it: -z lists, and porcelain lines whose first character is a space.
338
- export function git(root, args, raw = false) {
382
+ const BIG = 512 * 1024 * 1024;
383
+
384
+ // diff and log output as plain text whatever the repo's config or attributes ask for: no color, no external
385
+ // diff program, no textconv, no "Binary files differ", and a/ b/ prefixes. The agent can change all of these
386
+ // in .git/config or .git/info/attributes (cold review, L13 round 5).
387
+ export const PLAIN_DIFF = ['--no-color', '--no-ext-diff', '--no-textconv', '--text', '--src-prefix=a/', '--dst-prefix=b/'];
388
+
389
+ // Every git call runs with these over anything the repo or the user set (cold review, L13 rounds 6 and 7): no
390
+ // fsmonitor program or repo hook, which git would run inside the hook; no replace objects, which can swap the session's
391
+ // start commit for one holding a gutted test; and blank context lines that keep their leading space. A call
392
+ // that takes longer than GIT_TIMEOUT counts as failed, so the finish check says it could not read the diff.
393
+ const extra = Number(process.env.GIT_CONFIG_COUNT) || 0;
394
+ export const GIT_ENV = {
395
+ ...process.env,
396
+ GIT_NO_REPLACE_OBJECTS: '1',
397
+ GIT_OPTIONAL_LOCKS: '0', // git status does not write the index, so no index hook has a reason to run
398
+ GIT_CONFIG_COUNT: String(extra + 4),
399
+ [`GIT_CONFIG_KEY_${extra}`]: 'core.fsmonitor',
400
+ [`GIT_CONFIG_VALUE_${extra}`]: 'false',
401
+ [`GIT_CONFIG_KEY_${extra + 1}`]: 'diff.suppressBlankEmpty',
402
+ [`GIT_CONFIG_VALUE_${extra + 1}`]: 'false',
403
+ // no hook of the repo's runs inside Codehere's git calls, such as post-index-change (round 7, finding 2)
404
+ [`GIT_CONFIG_KEY_${extra + 2}`]: 'core.hooksPath',
405
+ [`GIT_CONFIG_VALUE_${extra + 2}`]: os.devNull,
406
+ // no signature check, which would run the repo's gpg.program inside a `git log` (round 8, m4)
407
+ [`GIT_CONFIG_KEY_${extra + 3}`]: 'log.showSignature',
408
+ [`GIT_CONFIG_VALUE_${extra + 3}`]: 'false',
409
+ };
410
+ export const GIT_TIMEOUT = 30000;
411
+
412
+ // Every git call with arguments from the repo or the state file: an array never goes through a shell, so a
413
+ // file name such as a$(cmd).js stays a file name. The output is read whole, and null when git fails, so an
414
+ // unread answer never looks like an empty one.
415
+ export function gitRead(root, args, input) {
416
+ const [cmd, ...rest] = args;
339
417
  try {
340
- const opts = { cwd: root, stdio: ['ignore', 'pipe', 'ignore'] };
341
- const out = (Array.isArray(args) ? execFileSync('git', ['--literal-pathspecs', ...args], opts) : execSync(`git ${args}`, opts)).toString();
342
- return raw ? out : out.trim();
418
+ // check-ignore takes plain paths and refuses the pathspec flag
419
+ const all = [...(cmd === 'check-ignore' ? [] : ['--literal-pathspecs']), cmd, ...(cmd === 'diff' || cmd === 'log' ? PLAIN_DIFF : []), ...rest];
420
+ return execFileSync('git', all, { cwd: root, input, stdio: [input == null ? 'ignore' : 'pipe', 'pipe', 'ignore'], maxBuffer: BIG, env: GIT_ENV, timeout: GIT_TIMEOUT }).toString();
343
421
  } catch {
344
- return '';
422
+ return null;
345
423
  }
346
424
  }
347
425
 
348
- // A diff can be far larger than execFileSync's 1 MiB default, and an unread diff must never look
349
- // like an empty one: this reads it whole and returns null when git fails.
350
- export function gitDiff(root, args) {
426
+ // gitRead with paths after "--", in batches: one argument list holds about 1 MiB on macOS, and a session can
427
+ // change tens of thousands of files (an npm install into a node_modules that is not ignored). Null when a batch fails.
428
+ export function gitPaths(root, args, paths) {
429
+ let out = '';
430
+ for (let i = 0; i < paths.length; ) {
431
+ let j = i;
432
+ for (let bytes = 0; j < paths.length && (j === i || bytes < 256 * 1024); j++) bytes += Buffer.byteLength(paths[j]) + 1;
433
+ const part = gitRead(root, [...args, '--', ...paths.slice(i, j)]);
434
+ if (part == null) return null;
435
+ out += part;
436
+ i = j;
437
+ }
438
+ return out;
439
+ }
440
+
441
+ // raw keeps the output as git wrote it: -z lists, and porcelain lines whose first character is a space.
442
+ // '' when git fails; a string is for fixed commands only.
443
+ export function git(root, args, raw = false) {
351
444
  try {
352
- return execFileSync('git', ['--literal-pathspecs', ...args], { cwd: root, stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 512 * 1024 * 1024 }).toString();
445
+ const out = Array.isArray(args) ? (gitRead(root, args) ?? '') : execSync(`git ${args}`, { cwd: root, stdio: ['ignore', 'pipe', 'ignore'], env: GIT_ENV, timeout: GIT_TIMEOUT }).toString();
446
+ return raw ? out : out.trim();
353
447
  } catch {
354
- return null;
448
+ return '';
355
449
  }
356
450
  }
357
451
 
358
- // Files with uncommitted changes, relative to root, which may be a subfolder of the repo.
452
+ // Files with uncommitted changes, relative to root, which may be a subfolder of the repo. Null when git fails.
359
453
  export function statusFiles(root) {
360
454
  const prefix = git(root, ['rev-parse', '--show-prefix']);
361
- const entries = git(root, ['status', '--porcelain', '-z', '--untracked-files=all', '--', '.'], true).split('\0');
455
+ const out = gitRead(root, ['status', '--porcelain', '-z', '--untracked-files=all', '--', '.']);
456
+ if (out == null) return null;
457
+ const entries = out.split('\0');
362
458
  const files = [];
363
459
  for (let i = 0; i < entries.length; i++) {
364
460
  const e = entries[i];
365
461
  if (e.length < 4) continue;
366
462
  if (e.slice(3).startsWith(prefix)) files.push(e.slice(3 + prefix.length));
367
- if (e[0] === 'R' || e[0] === 'C') i++; // the old name of a rename or copy
463
+ if (e[0] === 'R' || e[0] === 'C') {
464
+ const old = entries[++i] || ''; // the old name of a rename or copy
465
+ if (e[0] === 'R' && old.startsWith(prefix)) files.push(old.slice(prefix.length)); // a rename changed the old path too
466
+ }
368
467
  }
369
468
  return files;
370
469
  }
371
470
 
372
- // What `git hash-object` gives for each file (git's filters applied), 'deleted' for a missing
373
- // file, null when git cannot say. One git call for all of them; absolute paths, because
471
+ // What `git hash-object` gives for each file (git's filters applied, so a lesson's hash is the same on a teammate's
472
+ // machine; filters: false for a session's own snapshot, so no filter program of the repo's runs), 'deleted' for a missing
473
+ // file, null for one git cannot say; and null for all of them when the git call fails. One git call for all of them; absolute paths, because
374
474
  // --stdin-paths ignores the subfolder git was started in.
375
- export function gitHashes(root, files) {
376
- const present = files.filter((f) => !f.includes('\n') && fs.existsSync(path.join(root, f)));
377
- let out = [];
378
- try {
379
- if (present.length) {
380
- out = execFileSync('git', ['hash-object', '--stdin-paths'], { cwd: root, input: present.map((f) => path.resolve(root, f)).join('\n') + '\n', stdio: ['pipe', 'pipe', 'ignore'] })
381
- .toString()
382
- .trim()
383
- .split('\n');
475
+ export function gitHashes(root, files, { filters = true } = {}) {
476
+ // only regular files: git status lists a dirty submodule or a nested worktree as a folder, and one folder fails
477
+ // the whole call (round 9). A folder or another kind of entry gets its kind, not a hash.
478
+ const kind = (f) => {
479
+ try {
480
+ const st = fs.lstatSync(path.join(root, f)); // a link is not followed: it counts by where it points (round 11)
481
+ return st.isSymbolicLink() ? `link:${fs.readlinkSync(path.join(root, f))}` : st.isFile() ? 'file' : st.isDirectory() ? 'folder' : 'other';
482
+ } catch {
483
+ return 'deleted';
384
484
  }
385
- } catch {}
386
- return files.map((f) => {
387
- const i = present.indexOf(f);
388
- if (i >= 0) return out[i] || null;
389
- return f.includes('\n') ? null : 'deleted';
390
- });
485
+ };
486
+ const kinds = files.map((f) => (f.includes('\n') ? null : kind(f)));
487
+ const present = files.filter((f, i) => kinds[i] === 'file');
488
+ const read = present.length ? gitRead(root, ['hash-object', ...(filters ? [] : ['--no-filters']), '--stdin-paths'], present.map((f) => path.resolve(root, f)).join('\n') + '\n') : '';
489
+ if (read == null) return null;
490
+ const out = read.trim().split('\n');
491
+ const at = new Map(present.map((f, i) => [f, i]));
492
+ // a folder (a submodule, a worktree inside the repo) by its own commit and status, so an edit inside one is seen
493
+ // (round 10); 'folder' when git cannot read it
494
+ const folder = (f) => {
495
+ const dir = path.join(root, f);
496
+ const head = gitRead(dir, ['rev-parse', 'HEAD']);
497
+ const status = gitRead(dir, ['status', '--porcelain', '-z', '--untracked-files=all']);
498
+ const diff = gitRead(dir, ['diff', 'HEAD']); // a second edit to a file already changed keeps its status line
499
+ return head == null || status == null || diff == null ? 'folder' : `folder:${crypto.createHash('sha256').update(`${head}\0${status}\0${diff}`).digest('hex')}`;
500
+ };
501
+ return files.map((f, i) => (kinds[i] === 'file' ? out[at.get(f)] || null : kinds[i] === 'folder' ? folder(f) : kinds[i]));
391
502
  }
392
503
 
393
504
  // A tick is Codehere's mark for a run it made on this machine (DESIGN.md §1). Text from the
@@ -531,7 +642,7 @@ export function teamSnapshot(root) {
531
642
 
532
643
  // Before a save: the team files' hashes, and which files git sees as changed.
533
644
  export function teamMark(root) {
534
- return { hashes: teamSnapshot(root), dirty: new Set(statusFiles(root).map((f) => f.normalize('NFC'))) };
645
+ return { hashes: teamSnapshot(root), dirty: new Set((statusFiles(root) || []).map((f) => f.normalize('NFC'))) };
535
646
  }
536
647
 
537
648
  // A save Codehere made is not the agent's change: what it changed moves into the session's
package/src/commands.js CHANGED
@@ -242,7 +242,8 @@ function saveOrExit(root, rec) {
242
242
  // typed by the person, so not the agent's change in a session that is open now
243
243
  const after = teamSnapshot(root);
244
244
  const state = readState(root);
245
- if (Object.values(state.sessions || {}).filter((x) => keepSaved(x, before, after)).length) writeState(root, state);
245
+ const moved = Object.entries(state.sessions || {}).filter(([, x]) => keepSaved(x, before, after)).map(([k]) => k);
246
+ if (moved.length) writeState(root, state, moved, []);
246
247
  return saved;
247
248
  }
248
249
 
@@ -373,10 +374,26 @@ export async function init(flags) {
373
374
  console.log("Copilot runs a repo's hooks only in a folder you trust. Answer yes when Copilot asks on its first start here.");
374
375
  console.log('');
375
376
  }
377
+ const onPath = hooksCodehere();
378
+ if (onPath) console.log(`${onPath}\n`);
376
379
  console.log(`Next: commit .codehere/ and ${agents.map((a) => a.file).join(' and ')} so your team gets it too.`);
377
380
  console.log(`Then just use ${agents.map((a) => a.name).join(' or ')} as usual. Codehere stays quiet unless it helps.`);
378
381
  }
379
382
 
383
+ // The hooks call `codehere` from PATH. Set up through npx, or beside an older global install, they would fail
384
+ // with "command not found" or run another version, and the finish check would not be this one.
385
+ function hooksCodehere() {
386
+ const own = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
387
+ let found = '';
388
+ try {
389
+ found = execFileSync('codehere', ['--version'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 10000 }).trim().replace(/^codehere /, '');
390
+ } catch {}
391
+ if (found === own) return null;
392
+ return found
393
+ ? `The hooks run the codehere on PATH, which is ${printable(found)}, not this ${own}. To use ${own}: npm install -g codehere@${own}`
394
+ : `The hooks call codehere, which is not on PATH here, so they cannot run. Install it: npm install -g codehere@${own}`;
395
+ }
396
+
380
397
  // ---------- uninstall ----------
381
398
 
382
399
  function removeGitignoreLine(root) {
@@ -620,7 +637,7 @@ export async function brief(flags) {
620
637
  const file = path.join(paths(root).briefs, `${stamp()}.md`);
621
638
  writePlain(root, file, text + '\n'); // briefs/ may be a committed link
622
639
  state.pendingBrief = file;
623
- writeState(root, state);
640
+ writeState(root, state, [], ['pendingBrief']); // no session changed here: every session is kept as it is on disk
624
641
  console.log(text);
625
642
  console.log('');
626
643
  console.log(`Saved to ${path.relative(root, file)}.`);
package/src/gitpath.js ADDED
@@ -0,0 +1,47 @@
1
+ // Git writes a path that holds a tab, newline, quote, backslash or (by default) a non-ASCII character
2
+ // C-quoted and escaped: "test/caf\303\251.test.js". This gives the path back as it is on disk.
3
+ export function unquotePath(p) {
4
+ if (p.length < 2 || p[0] !== '"' || p.at(-1) !== '"') return p;
5
+ const s = p.slice(1, -1);
6
+ const named = { a: 7, b: 8, t: 9, n: 10, v: 11, f: 12, r: 13 };
7
+ const parts = [];
8
+ const re = /\\([0-7]{3}|.)/g;
9
+ let at = 0;
10
+ for (let m; (m = re.exec(s)); at = re.lastIndex) {
11
+ parts.push(Buffer.from(s.slice(at, m.index)));
12
+ const c = m[1];
13
+ parts.push(Buffer.from([c.length === 3 ? parseInt(c, 8) : (named[c] ?? c.charCodeAt(0))]));
14
+ }
15
+ parts.push(Buffer.from(s.slice(at)));
16
+ return Buffer.concat(parts).toString('utf8');
17
+ }
18
+
19
+ // Reads a unified diff one line at a time and says whether the line is in a hunk, counting the lines its
20
+ // header announced (@@ -3,2 +3,0 @@). In a hunk, an added "++ n;" reads "+++ n;" and a removed "-- seed"
21
+ // reads "--- seed": they are lines of the file, never the next file's header (cold review, L13 round 5).
22
+ export function hunkReader() {
23
+ let old = 0;
24
+ let now = 0;
25
+ return (line) => {
26
+ if (old > 0 || now > 0) {
27
+ const c = line[0];
28
+ if (c === '\\') return true;
29
+ if (c === '-' && old > 0) return old--, true;
30
+ if (c === '+' && now > 0) return now--, true;
31
+ // an empty line is a blank context line written without its space (diff.suppressBlankEmpty)
32
+ if ((c === ' ' || line === '') && old > 0 && now > 0) return old--, now--, true;
33
+ old = now = 0; // the line does not fit the counts: the hunk has ended
34
+ }
35
+ const m = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@/.exec(line);
36
+ if (m) [old, now] = [m[1] === undefined ? 1 : +m[1], m[2] === undefined ? 1 : +m[2]];
37
+ return false;
38
+ };
39
+ }
40
+
41
+ // A path as git writes it in a diff: quoted, with C escapes, when it holds a quote, a backslash or a control
42
+ // character, so unquotePath gives it back whole.
43
+ export function quotePath(p) {
44
+ if (!/["\\\x00-\x1f\x7f]/.test(p)) return p;
45
+ const esc = (b) => (b === 34 || b === 92 ? `\\${String.fromCharCode(b)}` : b < 32 || b >= 127 ? `\\${b.toString(8).padStart(3, '0')}` : String.fromCharCode(b));
46
+ return `"${[...Buffer.from(p)].map(esc).join('')}"`;
47
+ }