codehere 2.0.2 → 2.1.0-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +46 -18
- package/bin/codehere.js +4 -1
- package/package.json +1 -1
- package/src/brain.js +245 -14
- package/src/commands.js +188 -71
- package/src/gemma.js +17 -3
- package/src/hooks.js +380 -69
- package/src/signals.js +59 -11
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
**A team brain for vibe coders.** It stops your AI coding agent from going in circles, checks "done" for real, and shares what your team learns. It works through plain files in git.
|
|
4
4
|
|
|
5
|
-
Codehere is built to remove work, not add it. You keep using Claude Code, Codex CLI or Copilot CLI as usual. Codehere talks to the agent, not to you, and stays silent unless it helps.
|
|
5
|
+
Codehere is built to remove work, not add it. You keep using Claude Code, Codex CLI or Copilot CLI as usual. Codehere talks to the agent, not to you, and stays silent unless it helps. For team chores, you ask your agent, and it shows you a draft first.
|
|
6
6
|
|
|
7
7
|
## What it does
|
|
8
8
|
|
|
@@ -14,8 +14,8 @@ Codehere is built to remove work, not add it. You keep using Claude Code, Codex
|
|
|
14
14
|
| Watch the agent try the same failing fix again and again | After the same error 3 times, the agent is told to stop and find the root cause first |
|
|
15
15
|
| Trust "Done!" and find it broken later | Codehere runs your tests itself. If they fail, the agent goes back to work. |
|
|
16
16
|
| Miss that a test was skipped or deleted to make it "pass" | The agent is blocked and asked to restore it |
|
|
17
|
-
| Lose a long, messy session and start over from scratch | When a long session keeps hitting the same error, the agent
|
|
18
|
-
| Write a long message to ask a friend for help |
|
|
17
|
+
| Lose a long, messy session and start over from scratch | When a long session keeps hitting the same error, the agent offers a restart brief: one clean spec that the next session loads |
|
|
18
|
+
| Write a long message to ask a friend for help | Your agent writes a redacted help card and shows it to you |
|
|
19
19
|
| Solve a bug that a teammate already solved last week | Their fix reaches your agent the first time the error appears |
|
|
20
20
|
|
|
21
21
|
## Install (2 minutes)
|
|
@@ -42,6 +42,21 @@ The test command is in `.codehere/config.json`, which anyone with push access ca
|
|
|
42
42
|
|
|
43
43
|
## The team loop
|
|
44
44
|
|
|
45
|
+
Ask your agent in chat. It runs a Codehere command that prints a draft, shows you the draft, and Codehere saves it only if your next message is a plain yes:
|
|
46
|
+
|
|
47
|
+
```text
|
|
48
|
+
You: Add a team rule: prices are in cents, never floats.
|
|
49
|
+
Agent: Here is the draft:
|
|
50
|
+
- Prices are in cents. Never use floats for money. (Ana, 2026-11-03)
|
|
51
|
+
Save it?
|
|
52
|
+
You: yes
|
|
53
|
+
codehere › saved after your yes · rule · Prices are in cents. Never use floats for money.
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
The agent's words vary; the draft line and the `codehere ›` line come from Codehere. A reply from a fixed list saves: "yes", "ok", "sure", "save it", "go ahead", "do it" and a few more, alone or followed by "please" or "thanks". Any other reply discards the draft, including "no", "change the wording first" and "yes, save it", and you see a line saying it was not saved. Then commit and push `.codehere/` yourself: Codehere never does, and the agent is told not to. Teammates get it after `git pull`.
|
|
57
|
+
|
|
58
|
+
The same works for "ask the team for help with this", "anything from my team?" and answering a teammate's card. These are the commands the agent runs. Typed in your own terminal, they save at once, as before:
|
|
59
|
+
|
|
45
60
|
```bash
|
|
46
61
|
codehere rule "Prices are in cents. Never use floats for money." # every agent follows it
|
|
47
62
|
|
|
@@ -55,7 +70,7 @@ codehere reply <id> "Use price * qty; same bug was in checkout.js" --solved
|
|
|
55
70
|
git add .codehere && git commit -m "answer" && git push
|
|
56
71
|
```
|
|
57
72
|
|
|
58
|
-
`--solved` turns the answer into a **team lesson**. From then on, any teammate's agent that hits a similar error gets that fix automatically. When an agent solves a repeated error by itself,
|
|
73
|
+
`--solved` turns the answer into a **team lesson**. From then on, any teammate's agent that hits a similar error gets that fix automatically. When an agent solves a repeated error by itself, it offers the fix as a team lesson. When Codehere's own test run passed here, the lesson carries that proof (command, exit code, commit, the files the fix changed); otherwise it is saved as not verified. You see a line naming the error and the proof, and the lesson is saved only if you say yes.
|
|
59
74
|
|
|
60
75
|
You see one line per event:
|
|
61
76
|
|
|
@@ -65,7 +80,7 @@ codehere ✕ npm test · 2 failed · agent sent back · 1 of 3
|
|
|
65
80
|
codehere ✓ npm test · 48 passed · re-run here · 6.2 s
|
|
66
81
|
```
|
|
67
82
|
|
|
68
|
-
✓ marks only a test run Codehere just made on your machine. A teammate's "verified" is plain text: it was true on their machine, and anyone with push access can edit a lesson file. The agent is told whether the files the fix changed have changed since.
|
|
83
|
+
✓ marks only a test run Codehere just made on your machine. A run whose own summary counts a failed test is a failure, even when the command exits 0. A teammate's "verified" is plain text: it was true on their machine, and anyone with push access can edit a lesson file. A tick written into a rule or a lesson reaches the agent as `[tick]`. The agent is told whether the files the fix changed have changed since.
|
|
69
84
|
|
|
70
85
|
Don't want to commit help cards? Copy the printed text into WhatsApp, Discord or Slack instead.
|
|
71
86
|
|
|
@@ -80,11 +95,12 @@ Don't want to commit help cards? Copy the printed text into WhatsApp, Discord or
|
|
|
80
95
|
| Finish check: your tests re-run, the agent sent back | yes | yes | yes |
|
|
81
96
|
| Your one line (✓ ✕ ⊘ ›) | yes | in the interactive screen, as `↳ Hook · codehere ✓ …`; not in `codex exec` | no; when the agent is sent back, you see the full reason as the next prompt |
|
|
82
97
|
| Restart-brief suggestion in long sessions | yes | no | no |
|
|
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)) |
|
|
83
99
|
| Before it works | nothing | each developer trusts the hooks in `/hooks` | each developer trusts the folder when Copilot asks |
|
|
84
100
|
| MCP tools, instruction file | no | no | no |
|
|
85
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) |
|
|
86
102
|
|
|
87
|
-
The rows for rules, lessons and the finish check are checked on the real agent by `node scripts/conformance.mjs
|
|
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.
|
|
88
104
|
|
|
89
105
|
## Commands
|
|
90
106
|
|
|
@@ -94,7 +110,8 @@ codehere init [--agent claude,codex,copilot] [--test "npm test"]
|
|
|
94
110
|
codehere approve let the finish check run the test command on this machine
|
|
95
111
|
codehere uninstall remove Codehere from this repo (asks first)
|
|
96
112
|
codehere rule ["text"] add or list team rules
|
|
97
|
-
codehere lesson ["problem" --fix "..."
|
|
113
|
+
codehere lesson ["problem" --fix "..." [--cause "..."]]
|
|
114
|
+
add or list lessons
|
|
98
115
|
codehere brief [--gemma] restart brief for a fresh session
|
|
99
116
|
codehere help ["question"] [--gemma] help card for a teammate
|
|
100
117
|
codehere inbox [--all] teammates' help cards
|
|
@@ -104,16 +121,18 @@ codehere status what Codehere has seen
|
|
|
104
121
|
codehere stats turns to green, loops stopped, context size
|
|
105
122
|
```
|
|
106
123
|
|
|
124
|
+
When an agent runs `rule`, `lesson`, `help` or `reply`, the command prints a draft and saves nothing. Codehere saves it if your next message is a plain yes. Typed in your own terminal, they save at once.
|
|
125
|
+
|
|
107
126
|
## What lives where
|
|
108
127
|
|
|
109
128
|
```
|
|
110
129
|
.codehere/
|
|
111
|
-
rules.md team rules (
|
|
130
|
+
rules.md team rules (typed by a person, or saved after their yes)
|
|
112
131
|
lessons/ solved errors, one markdown file each
|
|
113
132
|
help/ help cards
|
|
114
133
|
briefs/ restart briefs
|
|
115
134
|
config.json test command, loop threshold
|
|
116
|
-
local/ this machine only, git-ignored (session state)
|
|
135
|
+
local/ this machine only, git-ignored (session state, drafts)
|
|
117
136
|
```
|
|
118
137
|
|
|
119
138
|
Everything is plain markdown, so you can read, edit, review and delete it like any other file.
|
|
@@ -121,13 +140,13 @@ Everything is plain markdown, so you can read, edit, review and delete it like a
|
|
|
121
140
|
## Design rules (from the research)
|
|
122
141
|
|
|
123
142
|
- **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.
|
|
124
|
-
- **It talks to the agent, not to you.** If Codehere is wrong, the agent does one extra check. You lose nothing.
|
|
125
|
-
- **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.
|
|
126
|
-
- **It only reacts to this session's work.** Changes you had before the session are ignored. If the agent changed nothing, Codehere does nothing.
|
|
143
|
+
- **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.
|
|
144
|
+
- **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.
|
|
145
|
+
- **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.
|
|
127
146
|
- **It never traps the agent.** At most 3 "not done yet" messages per session, then it lets go.
|
|
128
147
|
- **It fails open.** If anything breaks, the hook exits quietly and the agent carries on.
|
|
129
|
-
- **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`.
|
|
130
|
-
- **Only human-confirmed context at session start.** Rules are
|
|
148
|
+
- **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.
|
|
149
|
+
- **Only human-confirmed context at session start.** Rules and lessons are typed by a person, or drafted by the agent and saved after the person's yes. Lessons appear only when a matching error shows up, because auto-generated context files can make agents worse.
|
|
131
150
|
|
|
132
151
|
## Try the demo (no Claude account needed)
|
|
133
152
|
|
|
@@ -140,19 +159,28 @@ npm test # end-to-end checks
|
|
|
140
159
|
## Known limits
|
|
141
160
|
|
|
142
161
|
- 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.
|
|
143
|
-
- Lessons match by error text. 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.
|
|
162
|
+
- 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.
|
|
144
163
|
- Redaction catches common keys, tokens and emails. Always read a help card before sharing it.
|
|
145
164
|
- The "done" check needs a test command. Without one, only the tampering check runs.
|
|
146
165
|
- Approvals are per folder. Each git worktree or extra clone needs its own `codehere approve`.
|
|
147
166
|
- 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.
|
|
148
|
-
- 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 or a settings change during a session. The agent
|
|
167
|
+
- 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 or a settings change 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.
|
|
149
168
|
- Copilot's cloud agent also runs the committed `.github/hooks/codehere.json`. `codehere` is not installed there, so by GitHub's docs each hook fails and the job carries on without Codehere.
|
|
150
169
|
- `codehere approve` and `codehere uninstall` ask only in your own terminal. They refuse when Claude Code, Codex or Copilot is among the processes above them, and inside Codex's sandbox. An agent that detaches its terminal on purpose can still answer, so the finish check of a session that was open tells you when an approval or an uninstall happened (not on Copilot, which shows none of these lines).
|
|
151
170
|
- Approving `npm test` approves that command, not the scripts behind it in `package.json`. And Claude Code runs any hook a teammate adds to the committed `.claude/settings.json`, as Copilot does in a trusted folder for `.github/hooks/` and `.claude/settings.json`; Codex asks each developer to trust a new or changed hook first. Both are your repo's code, with the same trust as running it yourself.
|
|
152
|
-
- When the agent changes `.codehere/config.json`, `.codehere/rules.md
|
|
171
|
+
- When the agent changes `.codehere/config.json`, `.codehere/rules.md` (except a rule saved after your yes), the hook and env settings in `.claude/settings*.json` or `.github/copilot/settings*.json`, or `.codex/hooks.json`, `.codex/config.toml` or `.github/hooks/codehere.json` during a session, the finish check tells you. It cannot tell you if the session ends without a finish check, for example when you close it mid-turn. An agent that sets out to fake your terminal or rewrite Codehere's local files can also get around this.
|
|
153
172
|
- Only the test command needs approval. A teammate who sets `verifyOnStop` to `false` in `.codehere/config.json` turns the finish check off for everyone; `codehere status` shows it as off.
|
|
154
173
|
- Sharing is through git. There is no server, so teammates see updates after `git pull`.
|
|
174
|
+
- The yes before a draft is saved is checked by Codehere's hooks with a word list. An agent deliberately working around Codehere could fake that reply, as it could fake other hook input, or write files in `.codehere/` directly; that is not stopped or reported.
|
|
175
|
+
- A command you send through the agent drafts: Claude Code's `!` and scripts with no terminal take the agent's path, and so does every command on a machine without `ps`. In VS Code an agent's command can run in a real terminal with no agent above it, and then saves at once. No test has shown whether a `!` command reaches Codehere's hooks; if it does not, your yes gets a "nothing saved" line.
|
|
176
|
+
- A one-shot run (`claude -p`, `codex exec`) that is never resumed has no next message, so its drafts are never saved; a resumed turn (`--resume`, `codex exec resume`) can answer them. Unsaved drafts are removed after 7 days.
|
|
177
|
+
- Codex saves no drafts until you trust its hooks in `/hooks`.
|
|
178
|
+
- If the agent deletes a draft after showing it to you, your yes saves nothing and neither of you is told.
|
|
179
|
+
- Two agent sessions in one repo at once: `help` and `brief` read the session that last ran a hook, a yes in one session can get a wrong "nothing saved" line about the other session's draft, and a rule saved after a yes can be reported once as a settings change.
|
|
180
|
+
- A lesson offered at the finish check is saved only if you say yes. In 2.0.3 every solved repeated error left a lesson file.
|
|
181
|
+
- Restart briefs are written without a yes, for your own next session. They enter git only if you commit `.codehere/briefs/`.
|
|
182
|
+
- A committed link to a folder that holds another repo's `.codehere/` can lead Codehere, run from inside that folder, to write its own local files there. `init` can stop halfway on a file it may not write, such as a read-only `.gitignore`.
|
|
155
183
|
- Prompt checks are plain word lists (English and Indonesian). They can miss a short prompt in another language.
|
|
156
|
-
- The weakened-test scan catches skipped tests, deleted test files
|
|
184
|
+
- The weakened-test scan catches skipped and focused tests (`.skip`, `xit`, `{ skip: true }`, `.only`, `fit`), deleted test files, an assertion commented out with `//` or `#`, assertions that cannot fail (`assert.equal(1, 1)`), at least two more assertion lines removed than added, and a `package.json` test script changed to always pass (`|| true`). It does not catch one removed assertion, assertions wrapped in `/* */`, options spread over several lines, an edited expected value, or a `return` above an assertion; see `docs/overlap-with-check.md`.
|
|
157
185
|
|
|
158
186
|
MIT licensed.
|
package/bin/codehere.js
CHANGED
|
@@ -33,7 +33,7 @@ Setup
|
|
|
33
33
|
|
|
34
34
|
Team brain
|
|
35
35
|
codehere rule ["text"] add a team rule (or list rules)
|
|
36
|
-
codehere lesson ["problem" --fix "what fixed it" --sig "error text"]
|
|
36
|
+
codehere lesson ["problem" --fix "what fixed it" --cause "why" --sig "error text"]
|
|
37
37
|
add a lesson (or list lessons)
|
|
38
38
|
|
|
39
39
|
When you're stuck
|
|
@@ -48,6 +48,9 @@ When you're stuck
|
|
|
48
48
|
codehere status what Codehere has seen
|
|
49
49
|
codehere stats turns to green, loops stopped, session size
|
|
50
50
|
|
|
51
|
+
Run by an agent, rule, lesson, help and reply print a draft; it is saved if your next
|
|
52
|
+
message in the chat is a plain yes. Typed in your own terminal, they save at once.
|
|
53
|
+
|
|
51
54
|
Hooks (called by the agent, not by you)
|
|
52
55
|
codehere hook session-start | prompt | post-tool | stop [--agent codex|copilot]
|
|
53
56
|
`;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "codehere",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.1.0-rc.0",
|
|
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/brain.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import fs from 'node:fs';
|
|
4
4
|
import os from 'node:os';
|
|
5
5
|
import path from 'node:path';
|
|
6
|
+
import crypto from 'node:crypto';
|
|
6
7
|
import { execSync, execFileSync } from 'node:child_process';
|
|
7
8
|
|
|
8
9
|
export function findRoot(start = process.cwd()) {
|
|
@@ -26,13 +27,15 @@ export function paths(root) {
|
|
|
26
27
|
briefs: path.join(base, 'briefs'),
|
|
27
28
|
local: path.join(base, 'local'),
|
|
28
29
|
state: path.join(base, 'local', 'state.json'),
|
|
30
|
+
drafts: path.join(base, 'local', 'drafts'),
|
|
29
31
|
};
|
|
30
32
|
}
|
|
31
33
|
|
|
34
|
+
// No folder is made through a committed link (init refuses one outright).
|
|
32
35
|
export function ensureDirs(root) {
|
|
33
36
|
const p = paths(root);
|
|
34
37
|
for (const d of [p.base, p.lessons, p.help, p.briefs, p.local]) {
|
|
35
|
-
fs.mkdirSync(d, { recursive: true });
|
|
38
|
+
if (ownPath(root, d)) fs.mkdirSync(d, { recursive: true });
|
|
36
39
|
}
|
|
37
40
|
return p;
|
|
38
41
|
}
|
|
@@ -46,34 +49,79 @@ const DEFAULT_CONFIG = {
|
|
|
46
49
|
gemmaModel: 'gemma4:e4b',
|
|
47
50
|
};
|
|
48
51
|
|
|
52
|
+
// What a teammate can commit is read only as a plain file: git can commit a symlink (mode 120000),
|
|
53
|
+
// and one to /dev/zero would hang the hook that reads it. The file is opened without following a
|
|
54
|
+
// final link and without blocking, checked on the open file, and read up to max bytes: a linked
|
|
55
|
+
// folder can still reach a file such as /proc/self/pagemap, which says it is plain and never ends.
|
|
56
|
+
// encoding null gives a Buffer.
|
|
57
|
+
export function readPlain(file, encoding = 'utf8', max = 8 * 1024 * 1024) {
|
|
58
|
+
const notPlain = () => Object.assign(new Error(`not a plain file: ${file}`), { code: 'ENOTPLAIN' });
|
|
59
|
+
let fd;
|
|
60
|
+
try {
|
|
61
|
+
fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
|
|
62
|
+
} catch (e) {
|
|
63
|
+
throw e.code === 'ELOOP' ? notPlain() : e;
|
|
64
|
+
}
|
|
65
|
+
try {
|
|
66
|
+
if (!fs.fstatSync(fd).isFile()) throw notPlain();
|
|
67
|
+
const chunks = [];
|
|
68
|
+
const buf = Buffer.alloc(64 * 1024);
|
|
69
|
+
for (let total = 0, n; total < max && (n = fs.readSync(fd, buf, 0, Math.min(buf.length, max - total), null)) > 0; total += n) {
|
|
70
|
+
chunks.push(Buffer.from(buf.subarray(0, n)));
|
|
71
|
+
}
|
|
72
|
+
const data = Buffer.concat(chunks);
|
|
73
|
+
return encoding ? data.toString(encoding) : data;
|
|
74
|
+
} finally {
|
|
75
|
+
fs.closeSync(fd);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
49
79
|
export function readConfig(root) {
|
|
50
80
|
const p = paths(root);
|
|
51
81
|
try {
|
|
52
|
-
return { ...DEFAULT_CONFIG, ...JSON.parse(
|
|
82
|
+
return { ...DEFAULT_CONFIG, ...JSON.parse(readPlain(p.config)) };
|
|
53
83
|
} catch {
|
|
54
84
|
return { ...DEFAULT_CONFIG };
|
|
55
85
|
}
|
|
56
86
|
}
|
|
57
87
|
|
|
58
88
|
export function writeConfig(root, cfg) {
|
|
59
|
-
|
|
89
|
+
writePlain(root, paths(root).config, JSON.stringify(cfg, null, 2) + '\n');
|
|
60
90
|
}
|
|
61
91
|
|
|
62
92
|
// ---------- local session state ----------
|
|
63
93
|
|
|
64
94
|
export function readState(root) {
|
|
65
95
|
try {
|
|
66
|
-
const state = JSON.parse(
|
|
96
|
+
const state = JSON.parse(readPlain(paths(root).state));
|
|
67
97
|
// state.json can arrive through git: a file of the wrong shape counts as empty
|
|
68
98
|
if (state && state.sessions && typeof state.sessions === 'object') return state;
|
|
69
99
|
} catch {}
|
|
70
100
|
return { sessions: {}, lastSession: null, lastGreen: null, pendingBrief: null };
|
|
71
101
|
}
|
|
72
102
|
|
|
103
|
+
// Written to a temporary file and renamed into place: a reader never sees half a file (which
|
|
104
|
+
// readState would take as empty, erasing every session), and a committed symlink is replaced,
|
|
105
|
+
// not followed.
|
|
106
|
+
// Nothing is written when local/ is a committed symlink, and the temporary file has a random name
|
|
107
|
+
// made with exclusive create, so no planted link at that name is followed. Never throws: false when
|
|
108
|
+
// nothing was saved, and a caller that needs the state kept (the finish check's send-back count)
|
|
109
|
+
// then holds back, while what it reports still goes out.
|
|
73
110
|
export function writeState(root, state) {
|
|
74
111
|
const p = paths(root);
|
|
75
|
-
|
|
76
|
-
|
|
112
|
+
if (!ownPath(root, p.local)) return false;
|
|
113
|
+
const tmp = `${p.state}.${crypto.randomBytes(6).toString('hex')}.tmp`;
|
|
114
|
+
try {
|
|
115
|
+
fs.mkdirSync(p.local, { recursive: true });
|
|
116
|
+
fs.writeFileSync(tmp, JSON.stringify(state, null, 2), { flag: 'wx' });
|
|
117
|
+
fs.renameSync(tmp, p.state);
|
|
118
|
+
return true;
|
|
119
|
+
} catch {
|
|
120
|
+
try {
|
|
121
|
+
fs.rmSync(tmp, { force: true });
|
|
122
|
+
} catch {} // local/ may be a file: there is no temporary file to remove
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
77
125
|
}
|
|
78
126
|
|
|
79
127
|
export function session(state, id) {
|
|
@@ -128,10 +176,14 @@ export function listDocs(dir) {
|
|
|
128
176
|
.readdirSync(dir)
|
|
129
177
|
.filter((f) => f.endsWith('.md'))
|
|
130
178
|
.sort()
|
|
131
|
-
.
|
|
179
|
+
.flatMap((f) => {
|
|
132
180
|
const file = path.join(dir, f);
|
|
133
|
-
|
|
134
|
-
|
|
181
|
+
try {
|
|
182
|
+
const { meta, body } = parseDoc(readPlain(file));
|
|
183
|
+
return [{ id: f.replace(/\.md$/, ''), file, meta, body }];
|
|
184
|
+
} catch {
|
|
185
|
+
return []; // a link or a folder named like a lesson or card
|
|
186
|
+
}
|
|
135
187
|
});
|
|
136
188
|
}
|
|
137
189
|
|
|
@@ -159,9 +211,13 @@ export function today() {
|
|
|
159
211
|
|
|
160
212
|
export function readRules(root) {
|
|
161
213
|
const file = paths(root).rules;
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
214
|
+
let text = '';
|
|
215
|
+
try {
|
|
216
|
+
text = readPlain(file);
|
|
217
|
+
} catch {
|
|
218
|
+
return [];
|
|
219
|
+
}
|
|
220
|
+
return text
|
|
165
221
|
.split('\n')
|
|
166
222
|
.filter((l) => l.startsWith('- '))
|
|
167
223
|
.map((l) => l.slice(2).trim());
|
|
@@ -323,8 +379,8 @@ export function gitHashes(root, files) {
|
|
|
323
379
|
|
|
324
380
|
// A tick is Codehere's mark for a run it made on this machine (DESIGN.md §1). Text from the
|
|
325
381
|
// repo or from a teammate never brings its own.
|
|
326
|
-
export function noTick(text) {
|
|
327
|
-
return String(text).replace(/[
|
|
382
|
+
export function noTick(text, mark = '?') {
|
|
383
|
+
return String(text).replace(/[✓✔☑✅√🗸🗹\u{10102}\u{1FBB1}]/gu, mark);
|
|
328
384
|
}
|
|
329
385
|
|
|
330
386
|
// A commit id read back from state.json, or null. The state file can arrive through git,
|
|
@@ -340,3 +396,178 @@ export function isGitRepo(root) {
|
|
|
340
396
|
export function me(root) {
|
|
341
397
|
return git(root, 'config user.name') || process.env.USER || 'someone';
|
|
342
398
|
}
|
|
399
|
+
|
|
400
|
+
// ---------- records: what rule, lesson, help and reply save ----------
|
|
401
|
+
// A writing command builds its record once. Typed by the developer it is saved at once; run by an
|
|
402
|
+
// agent it becomes a draft, which the prompt hook saves only after the person's plain yes.
|
|
403
|
+
|
|
404
|
+
// True when no part of p below root is a symlink, so a write to p lands at p. A teammate can
|
|
405
|
+
// commit a symlink anywhere in .codehere/, dangling or not; git writes it on pull.
|
|
406
|
+
export function ownPath(root, p) {
|
|
407
|
+
let at = path.resolve(root);
|
|
408
|
+
for (const part of path.relative(at, path.resolve(p)).split(path.sep)) {
|
|
409
|
+
if (!part || part === '..') return false;
|
|
410
|
+
at = path.join(at, part);
|
|
411
|
+
try {
|
|
412
|
+
if (fs.lstatSync(at).isSymbolicLink()) return false;
|
|
413
|
+
} catch (e) {
|
|
414
|
+
return e.code === 'ENOENT'; // from here on nothing exists yet, and mkdir makes plain folders
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
return true;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
// A write into the repo that a committed symlink cannot redirect: no link on the path (the final
|
|
421
|
+
// name refused without a race by O_NOFOLLOW). mode 'w' replaces, 'a' appends.
|
|
422
|
+
const linkedError = (root, file) => Object.assign(new Error(`${path.relative(root, file)} is a link or under one, so Codehere will not write it.`), { code: 'ENOTPLAIN' });
|
|
423
|
+
export function writePlain(root, file, data, mode = 'w') {
|
|
424
|
+
if (!ownPath(root, file)) throw linkedError(root, file);
|
|
425
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
426
|
+
const { O_WRONLY, O_CREAT, O_TRUNC, O_APPEND, O_NOFOLLOW } = fs.constants;
|
|
427
|
+
const fd = fs.openSync(file, O_WRONLY | O_CREAT | O_NOFOLLOW | (mode === 'a' ? O_APPEND : O_TRUNC), 0o666); // the umask applies, as with writeFileSync
|
|
428
|
+
try {
|
|
429
|
+
fs.writeFileSync(fd, data);
|
|
430
|
+
} finally {
|
|
431
|
+
fs.closeSync(fd);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
export function removePlain(root, file) {
|
|
435
|
+
if (!ownPath(root, file)) throw linkedError(root, file);
|
|
436
|
+
fs.rmSync(file, { force: true });
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// A new file, never over an existing one or through a link: name.md, then name-2.md, ...
|
|
440
|
+
// 'wx' fails on any existing path, a dangling symlink included, and on a race with another save.
|
|
441
|
+
function writeNew(dir, name, text) {
|
|
442
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
443
|
+
for (let i = 1; ; i++) {
|
|
444
|
+
const base = i === 1 ? name : `${name}-${i}`;
|
|
445
|
+
try {
|
|
446
|
+
fs.writeFileSync(path.join(dir, `${base}.md`), text(base), { flag: 'wx' });
|
|
447
|
+
return path.join(dir, `${base}.md`);
|
|
448
|
+
} catch (e) {
|
|
449
|
+
if (e.code !== 'EEXIST') throw e;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
const day = (d) => (/^\d{4}-\d\d-\d\d$/.test(String(d)) ? d : today());
|
|
455
|
+
const line = (s) => String(s).replace(/\s*[\r\n]+\s*/g, ' ');
|
|
456
|
+
// The front matter a record may set. Proof fields come only from the finish check's proof, never
|
|
457
|
+
// from a record: a draft is a file the agent could have edited.
|
|
458
|
+
const LESSON_KEYS = ['title', 'signature', 'author', 'date', 'test', 'from'];
|
|
459
|
+
const HELP_KEYS = ['id', 'author', 'date', 'status', 'signature', 'test'];
|
|
460
|
+
const PROOF_KEYS = ['signature', 'test', 'state', 'proof_command', 'proof_exit', 'proof_commit', 'proof_dirty', 'files', 'file_hashes'];
|
|
461
|
+
const pick = (obj, keys) => Object.fromEntries(keys.filter((k) => obj && obj[k] != null).map((k) => [k, line(obj[k])]));
|
|
462
|
+
const isText = (s) => typeof s === 'string';
|
|
463
|
+
|
|
464
|
+
// The folder comes from the kind and the file name is built here from slugs and a checked date,
|
|
465
|
+
// so no record field becomes a path. Never throws or exits: what cannot be saved comes back as
|
|
466
|
+
// { error }, for the CLI to print and for a hook to tell the agent.
|
|
467
|
+
export function saveRecord(root, rec, proof = null) {
|
|
468
|
+
try {
|
|
469
|
+
return save(root, rec || {}, proof);
|
|
470
|
+
} catch (e) {
|
|
471
|
+
return { error: `Codehere could not save it: ${e.message}` };
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
function save(root, rec, proof) {
|
|
476
|
+
const p = paths(root);
|
|
477
|
+
const rel = (f) => path.relative(root, f);
|
|
478
|
+
const linked = (f) => (ownPath(root, f) ? null : { error: `Codehere: ${rel(f)} is a link, so nothing was saved.` });
|
|
479
|
+
const bad = { error: 'Codehere: this draft is not one Codehere wrote, so nothing was saved.' };
|
|
480
|
+
if (rec.kind === 'rule') {
|
|
481
|
+
if (!isText(rec.line) || !rec.line.startsWith('- ')) return bad;
|
|
482
|
+
if (linked(p.rules)) return linked(p.rules);
|
|
483
|
+
fs.appendFileSync(p.rules, `${line(rec.line)}\n`);
|
|
484
|
+
return { file: rel(p.rules) };
|
|
485
|
+
}
|
|
486
|
+
if (rec.kind === 'lesson') {
|
|
487
|
+
// with a proof, the error's signature and failing test come from it alone, present or not
|
|
488
|
+
const meta = { ...pick(rec.meta, proof ? LESSON_KEYS.filter((k) => k !== 'signature' && k !== 'test') : LESSON_KEYS), ...pick(proof, PROOF_KEYS) };
|
|
489
|
+
if (!meta.title || !isText(rec.body)) return bad;
|
|
490
|
+
if (linked(p.lessons)) return linked(p.lessons);
|
|
491
|
+
return { file: rel(writeNew(p.lessons, `${day(meta.date)}-${slug(meta.title)}`, () => renderDoc(meta, rec.body))) };
|
|
492
|
+
}
|
|
493
|
+
if (rec.kind === 'help') {
|
|
494
|
+
const meta = pick(rec.meta, HELP_KEYS);
|
|
495
|
+
if (!meta.id || !isText(rec.text)) return bad;
|
|
496
|
+
if (linked(p.help)) return linked(p.help);
|
|
497
|
+
return { file: rel(writeNew(p.help, slug(meta.id, 80), (id) => renderDoc({ ...meta, id, status: 'open' }, rec.text))) };
|
|
498
|
+
}
|
|
499
|
+
if (rec.kind !== 'reply' || !isText(rec.card) || !isText(rec.line) || !rec.line.startsWith('- ')) return bad;
|
|
500
|
+
const lessonMeta = rec.lesson ? pick(rec.lesson.meta, LESSON_KEYS) : null;
|
|
501
|
+
if (rec.lesson && (!lessonMeta.title || !isText(rec.lesson.body))) return bad;
|
|
502
|
+
// a reply goes into the card as it is now (a pull may have added replies since the draft),
|
|
503
|
+
// and only into the card the draft named
|
|
504
|
+
const d = listDocs(p.help).find((x) => x.id === rec.card);
|
|
505
|
+
if (!d) return { error: `No help card "${rec.card}" any more, so the reply was not saved.` };
|
|
506
|
+
if (linked(d.file) || (rec.lesson && linked(p.lessons))) return linked(d.file) || linked(p.lessons);
|
|
507
|
+
const { meta, body } = parseDoc(readPlain(d.file));
|
|
508
|
+
let lesson = null;
|
|
509
|
+
if (rec.lesson) {
|
|
510
|
+
meta.status = 'resolved';
|
|
511
|
+
meta.resolvedBy = lessonMeta.author;
|
|
512
|
+
lesson = rel(writeNew(p.lessons, `${day(lessonMeta.date)}-${slug(lessonMeta.title)}`, () => renderDoc(lessonMeta, rec.lesson.body)));
|
|
513
|
+
}
|
|
514
|
+
const replies = body.includes('## Replies') ? body.trimEnd() : `${body.trimEnd()}\n\n## Replies`;
|
|
515
|
+
fs.writeFileSync(d.file, renderDoc(meta, `${replies}\n${line(rec.line)}\n`));
|
|
516
|
+
return { file: rel(d.file), lesson, author: meta.author };
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// null when .codehere/local/drafts/ is not a plain folder in this repo: a committed symlink must
|
|
520
|
+
// not move drafts elsewhere, nor let expiry delete files there; a committed file must not be mistaken
|
|
521
|
+
// for the folder.
|
|
522
|
+
function draftsHere(root) {
|
|
523
|
+
const dir = paths(root).drafts;
|
|
524
|
+
if (!ownPath(root, dir)) return null;
|
|
525
|
+
try {
|
|
526
|
+
return fs.statSync(dir).isDirectory() ? dir : null;
|
|
527
|
+
} catch (e) {
|
|
528
|
+
return e.code === 'ENOENT' ? dir : null;
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// The id is new each time, so a draft file a teammate planted through git is never reused.
|
|
533
|
+
export function writeDraft(root, rec) {
|
|
534
|
+
const dir = draftsHere(root);
|
|
535
|
+
if (!dir) return null;
|
|
536
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
537
|
+
for (;;) {
|
|
538
|
+
const id = crypto.randomBytes(4).toString('hex');
|
|
539
|
+
try {
|
|
540
|
+
fs.writeFileSync(path.join(dir, `${id}.json`), JSON.stringify({ id, created: new Date().toISOString(), ...rec }, null, 2) + '\n', { flag: 'wx' });
|
|
541
|
+
return id;
|
|
542
|
+
} catch (e) {
|
|
543
|
+
if (e.code !== 'EEXIST') throw e;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
export function draftFile(root, id) {
|
|
549
|
+
const dir = draftsHere(root);
|
|
550
|
+
return dir && /^[0-9a-f]{8}$/.test(String(id)) ? path.join(dir, `${id}.json`) : null;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
// Runs at every session start, so it never throws: whatever a teammate committed under drafts/,
|
|
554
|
+
// session start goes on. Only plain files named like drafts are removed.
|
|
555
|
+
export function expireDrafts(root, days = 7) {
|
|
556
|
+
try {
|
|
557
|
+
const dir = draftsHere(root);
|
|
558
|
+
if (!dir || !fs.existsSync(dir) || !fs.lstatSync(dir).isDirectory()) return;
|
|
559
|
+
const cutoff = Date.now() - days * 864e5;
|
|
560
|
+
for (const f of fs.readdirSync(dir).filter((x) => /^[0-9a-f]{8}\.json$/.test(x))) {
|
|
561
|
+
const file = path.join(dir, f);
|
|
562
|
+
try {
|
|
563
|
+
if (!fs.lstatSync(file).isFile()) continue;
|
|
564
|
+
// the older of its own date and the file's: a date written into the file cannot keep it forever
|
|
565
|
+
let created = NaN;
|
|
566
|
+
try {
|
|
567
|
+
created = Date.parse(JSON.parse(fs.readFileSync(file, 'utf8')).created);
|
|
568
|
+
} catch {}
|
|
569
|
+
if (!(Math.min(created, fs.lstatSync(file).mtimeMs) >= cutoff)) fs.rmSync(file, { force: true });
|
|
570
|
+
} catch {}
|
|
571
|
+
}
|
|
572
|
+
} catch {}
|
|
573
|
+
}
|