geneseed 4.21.0 → 4.22.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/CHANGELOG.md +10 -0
- package/DESIGN.md +1 -1
- package/README.md +2 -2
- package/SHIPPED.md +1 -1
- package/adapters/bob/README.md +5 -0
- package/adapters/claude-code/README.md +4 -0
- package/adapters/openclaude/README.md +2 -1
- package/adapters/opencode/plugins/geneseed-activity.js +2 -2
- package/adapters/opencode/plugins/geneseed-guard.js +1 -1
- package/bin/geneseed-cli.mjs +1 -1
- package/bin/geneseed-hook.mjs +44 -3
- package/docs/concepts/hooks.md +4 -0
- package/docs/concepts/host-matrix.md +1 -0
- package/docs/reference/environment.md +1 -0
- package/docs/reference/plugin-activity.md +7 -3
- package/docs/web-ui.md +2 -1
- package/harness.config.json +1 -1
- package/js/README.md +2 -1
- package/js/cli-table.json +39 -0
- package/js/hosts/activity.mjs +429 -0
- package/js/hosts/hooks-prims.mjs +47 -4
- package/js/hosts/hooks.mjs +6 -9
- package/js/hosts/settings.mjs +9 -0
- package/js/web/activity.mjs +76 -108
- package/js/web/server.mjs +6 -0
- package/package.json +1 -1
- package/src/modes/foreman.md +2 -1
- package/src/skills/pipeline.md +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -8,6 +8,16 @@ label. For the capability ↔ spec map, see [SHIPPED.md](SHIPPED.md).
|
|
|
8
8
|
|
|
9
9
|
## [Unreleased]
|
|
10
10
|
|
|
11
|
+
## [4.22.0] — 2026-10-25
|
|
12
|
+
|
|
13
|
+
Minor: the Activity view is fed on every host, and pipelines no longer stall on a silent crew.
|
|
14
|
+
|
|
15
|
+
### Added
|
|
16
|
+
- **Claude Code, OpenClaude and Bob feed the Activity view**, like OpenCode: `geneseed-hook activity` runs on UserPromptSubmit (and SessionEnd on Claude and OpenClaude), and Claude's full timeline is read from its transcript at Stop. Recording is on by default on every host and follows the same `.geneseed-activity` switch; with it off, the writer is never loaded. Snapshots are redacted with the Law I secret patterns and git-ignored; ended sessions are archived (newest 50, 7 days) instead of deleted, and viewing the page never deletes anything. Run `geneseed rebuild-all` to wire the new hook. Bob is covered by unit tests only (IBM does not publish Bob Shell on npm).
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
- **Pipelines no longer stall on a silent crew.** The parent now watches every crew it dispatches: an envelope without proof, or a crew that goes silent for 15 minutes with no live child process, is resumed or taken over instead of waited on. A crew lead holds every member's result before it ends, so no member reports past it to the parent.
|
|
20
|
+
|
|
11
21
|
## [4.21.0] — 2026-10-25
|
|
12
22
|
|
|
13
23
|
Minor: Activity "Today", per-install rebuild, usage in the Library, sync with source in Hosts, a command palette, and `user` as an alias of `global`.
|
package/DESIGN.md
CHANGED
|
@@ -203,7 +203,7 @@ theme file defines a `DIR_*` key, so `laws/` is `laws/` in all fourteen voices.
|
|
|
203
203
|
| Generator | `bin/build-driver.mjs` (`geneseed-build`) | — | substitution + `<!-- INCLUDE: -->` inlining, and the eleven `--emit` targets |
|
|
204
204
|
| CLI, as data | `js/cli-table.json` | — | the owned document the entry point parses its own argv from |
|
|
205
205
|
| Automation | `bin/geneseed-cli.mjs` (`geneseed`) | — | 25 verbs — `build` / `doctor` / `status` / `prompt` / `diff` / `setup` / `web` / `upgrade` / … |
|
|
206
|
-
| Hooks | `bin/geneseed-hook.mjs` (`geneseed-hook`) | — | the
|
|
206
|
+
| Hooks | `bin/geneseed-hook.mjs` (`geneseed-hook`) | — | the six verbs an emitted hook config invokes: `context` / `git-gate` / `rule-gate` / `tool-gate` / `learn` / `activity` |
|
|
207
207
|
| Adapters | `adapters/` | — | optional per-tool glue (hooks, OpenCode plugins) |
|
|
208
208
|
|
|
209
209
|
## ⚙️ Generator contract
|
package/README.md
CHANGED
|
@@ -128,7 +128,7 @@ Both launchers are thin shims over the Node CLI: they need `node` (22.7+) on `PA
|
|
|
128
128
|
|
|
129
129
|
### 🟩 One runtime — Node, and nothing else
|
|
130
130
|
|
|
131
|
-
Node ≥ 22.7 is the entire dependency list — every command, all
|
|
131
|
+
Node ≥ 22.7 is the entire dependency list — every command, all six hook verbs, the web console and both generators run from it, and nothing any bundle ships needs a second interpreter.
|
|
132
132
|
|
|
133
133
|
### ✅ After installing
|
|
134
134
|
|
|
@@ -268,7 +268,7 @@ Token cost per host: **[docs/token-footprint.md](docs/token-footprint.md)**.
|
|
|
268
268
|
Geneseed/
|
|
269
269
|
├── package.json the npm package: three commands, zero dependencies
|
|
270
270
|
├── bin/ the Node entry points — geneseed-cli.mjs (the CLI), geneseed-hook.mjs
|
|
271
|
-
│ (the
|
|
271
|
+
│ (the six hook verbs), build-driver.mjs (the generator driver)
|
|
272
272
|
├── js/ the Node harness — generator, hooks, web server, doctor, installs
|
|
273
273
|
│ (js/cli-table.json is the CLI as data; the CLI reads it)
|
|
274
274
|
├── geneseed launcher (bash): a shim over bin/geneseed-cli.mjs — bare `./geneseed`
|
package/SHIPPED.md
CHANGED
|
@@ -20,7 +20,7 @@ historical references, not files distributed with the repo.
|
|
|
20
20
|
> **On version numbers.** [`harness.config.json`](harness.config.json)'s `version` is a
|
|
21
21
|
> human-readable label only. The canonical identity of an installed harness is the
|
|
22
22
|
> **source fingerprint** stamped in `.geneseed-version` (see `geneseed version`), not the
|
|
23
|
-
> string. Current label: **4.
|
|
23
|
+
> string. Current label: **4.22.0**.
|
|
24
24
|
|
|
25
25
|
## Capabilities
|
|
26
26
|
|
package/adapters/bob/README.md
CHANGED
|
@@ -104,6 +104,11 @@ What the global emit writes into `~/.bob/settings/settings.json`:
|
|
|
104
104
|
| `SessionStart` | `context --host bob` | plain stdout, as on Claude |
|
|
105
105
|
| `PreToolUse` | `tool-gate --host bob` — one group, no matcher | Laws I/IV, rigor-5 and ops-2: **exit 2**, reason on stderr — it says no chat confirmation lifts the block, since Bob has no ask tier; process 1/5: a stderr line, exit 0 |
|
|
106
106
|
| `Stop` | `learn` | never a verdict |
|
|
107
|
+
| `UserPromptSubmit` | `activity --host bob` | never a verdict; records the turn for the web console's Activity view |
|
|
108
|
+
|
|
109
|
+
Every hook also feeds the Activity view after it decides (off with `GENESEED_ACTIVITY=off`).
|
|
110
|
+
Bob sends no transcript, so a Bob session shows only the calls `tool-gate` sees; see
|
|
111
|
+
`docs/reference/plugin-activity.md`.
|
|
107
112
|
|
|
108
113
|
No matcher on `PreToolUse`, deliberately: Bob's tools page already drifts from its own
|
|
109
114
|
changelog (`web_fetch`, the 2.1.0 Office/IBM-docs tools are undocumented there), so an
|
|
@@ -70,6 +70,10 @@ absolute-path hooks instead — `geneseed setup` does that for you.) It:
|
|
|
70
70
|
and auto-compaction is the moment that window is about to be summarised away.
|
|
71
71
|
This captures memory *before* the summary; the SessionStart `context` hook (which
|
|
72
72
|
also fires on the `compact` source) re-seeds context *after* it.
|
|
73
|
+
- on **UserPromptSubmit** and **SessionEnd**, runs `geneseed-hook activity`, which decides
|
|
74
|
+
nothing and prints nothing: it records the session for the web console's Activity view.
|
|
75
|
+
Every other hook above feeds that view too, after it has decided. `GENESEED_ACTIVITY=off`
|
|
76
|
+
(or the console's toggle) turns it off; see `docs/reference/plugin-activity.md`.
|
|
73
77
|
|
|
74
78
|
This step is **opt-in on a model CLI**: set `GENESEED_LLM` (e.g. `claude -p`,
|
|
75
79
|
`llm`, `ollama run …`) for `learn` to actually distil. With it unset the hook is
|
|
@@ -57,7 +57,8 @@ global config file.
|
|
|
57
57
|
The Claude group set, unchanged: `PreToolUse` (git gate on `Bash|PowerShell`, rule gate on
|
|
58
58
|
writes), `SessionStart` (context on every source — one matcher-less group covers
|
|
59
59
|
`startup`, `resume`, `clear`, `compact` and `fork` alike), `Stop`,
|
|
60
|
-
`SubagentStop` and `PreCompact` (learn)
|
|
60
|
+
`SubagentStop` and `PreCompact` (learn), and `UserPromptSubmit` and `SessionEnd`
|
|
61
|
+
(`activity`, which feeds the web console's Activity view). OpenClaude reads Claude's
|
|
61
62
|
`hookSpecificOutput.permissionDecision`, so the gates **ask** where Claude asks.
|
|
62
63
|
The context hook carries `--host openclaude` for one reason. It tells the hook
|
|
63
64
|
which root file OpenClaude already loads (`AGENTS.md` when present, else
|
|
@@ -11,8 +11,8 @@
|
|
|
11
11
|
// ONE FILE PER SESSION (`activity/<session_id>.json`), owned exclusively by the
|
|
12
12
|
// process that created the session — so concurrent `opencode` invocations never
|
|
13
13
|
// contend on a shared file and no lock is needed. Atomic write (tmp + rename) keeps
|
|
14
|
-
// the reader from ever seeing a torn file. The reader
|
|
15
|
-
// dead or whose `updated_at` is stale
|
|
14
|
+
// the reader from ever seeing a torn file. The reader lists an entry whose `pid` is
|
|
15
|
+
// dead or whose `updated_at` is stale as ended, and never deletes it.
|
|
16
16
|
//
|
|
17
17
|
// FLAT: one entry per top-level session. Sub-agent fan-out (subtask parts,
|
|
18
18
|
// parent→children tree) is deferred — child sessions (those with a parentID) and the
|
|
@@ -220,7 +220,7 @@ const SECRET_RE = [
|
|
|
220
220
|
// as-is rather than silently changing guard behaviour for a parity task.
|
|
221
221
|
const SECRET_WARN_RE = [/(^|\/)\.env(\.[\w.-]+)?$/i]
|
|
222
222
|
|
|
223
|
-
// Twin of js/hosts/hooks.mjs's SECRET_RE (Law I's boundary half) — scans WRITE CONTENT for a
|
|
223
|
+
// Twin of js/hosts/hooks-prims.mjs's SECRET_RE (Law I's boundary half) — scans WRITE CONTENT for a
|
|
224
224
|
// credential-shaped string, not the target path (SECRET_RE above is the path twin, file names
|
|
225
225
|
// only). High-precision vendor prefixes only, same rationale as the Node side: a generic
|
|
226
226
|
// "looks like entropy" scan fires on every hash and lockfile. Kept byte-identical by the parity
|
package/bin/geneseed-cli.mjs
CHANGED
|
@@ -348,7 +348,7 @@ async function main(argv) {
|
|
|
348
348
|
// just about to become false — it was already claiming a third place for verbs that do
|
|
349
349
|
// not exist.
|
|
350
350
|
return die(2, `invalid choice: '${verb}'. This entry point carries only `
|
|
351
|
-
+ `${Object.keys(VERBS).join(', ')}; the
|
|
351
|
+
+ `${Object.keys(VERBS).join(', ')}; the six hook verbs live in `
|
|
352
352
|
+ 'bin/geneseed-hook.mjs.');
|
|
353
353
|
}
|
|
354
354
|
// `js/cli-table.json`, the CLI as data. A verb this table dispatches and the file does not
|
package/bin/geneseed-hook.mjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/**
|
|
3
3
|
* The hook entry point — a Node twin of `rituals/harness.py` for the verbs the emitted
|
|
4
|
-
* `settings.json` actually invokes (four from the reference, plus `tool-gate` for Bob
|
|
4
|
+
* `settings.json` actually invokes (four from the reference, plus `tool-gate` for Bob and
|
|
5
|
+
* `activity` for the web console's Activity view).
|
|
5
6
|
*
|
|
6
7
|
* WHY IT IS A SECOND BINARY AND NOT A SUBCOMMAND OF `bin/build-driver.mjs`. Three reasons,
|
|
7
8
|
* and each alone would be enough:
|
|
@@ -50,6 +51,11 @@ import '../js/lib/node-floor.mjs';
|
|
|
50
51
|
// Not a new module on the hot path: every verb's module imports `js/lib/fs.mjs` too, so this
|
|
51
52
|
// edge only loads early a file the process would load anyway.
|
|
52
53
|
import { printErr } from '../js/lib/fs.mjs';
|
|
54
|
+
// Also not a new module: every verb's module imports it. It carries the activity switch, so the
|
|
55
|
+
// off path costs one file read and no import of the writer.
|
|
56
|
+
import { activityOn, readStdin } from '../js/hosts/hooks-prims.mjs';
|
|
57
|
+
import { isatty } from 'node:tty';
|
|
58
|
+
import path from 'node:path';
|
|
53
59
|
|
|
54
60
|
// `--host` selects the verdict dialect (see js/hosts/hooks.mjs's header); the emitter bakes
|
|
55
61
|
// it into the command for every host that is not Claude Code, so the hook never has to guess
|
|
@@ -92,8 +98,37 @@ const VERBS = {
|
|
|
92
98
|
switches: { '--consolidate': 'consolidate', '--no-done-gate': 'noDoneGate' },
|
|
93
99
|
positional: 'file',
|
|
94
100
|
},
|
|
101
|
+
// UserPromptSubmit and SessionEnd: no verb runs there, and the activity view needs both.
|
|
102
|
+
activity: { load: () => import('../js/hosts/hooks-prims.mjs'), fn: 'cmdActivity', flags: HOSTED },
|
|
95
103
|
};
|
|
96
104
|
|
|
105
|
+
/**
|
|
106
|
+
* Records the payload the verb just answered into `<root>/activity/` (js/hosts/activity.mjs),
|
|
107
|
+
* AFTER the verb has decided and printed, so a verdict never waits on it and never sees it.
|
|
108
|
+
* Here rather than inside each verb because Claude routes its gated tools through THREE verbs
|
|
109
|
+
* (git-gate, rule-gate, tool-gate) and the same payload shape reaches all of them; the stdin they
|
|
110
|
+
* consumed is kept by `readStdin`. Never prints, never changes the exit code. Stands down inside a
|
|
111
|
+
* model-CLI child `learn` spawned (its own hooks would record a phantom session), on a terminal
|
|
112
|
+
* (a hand-run `context` must not block on a stdin nobody will send), and when tracking is off —
|
|
113
|
+
* then the writer module is never imported.
|
|
114
|
+
*/
|
|
115
|
+
async function trackActivity(verb, args) {
|
|
116
|
+
try {
|
|
117
|
+
// `learn` names its install by `--memory`, and a `--file` run is a person, not a hook.
|
|
118
|
+
const root = verb === 'learn' ? (args.memory && !args.file ? path.dirname(args.memory) : null)
|
|
119
|
+
: args.root;
|
|
120
|
+
if (!root || process.env.GENESEED_LEARN_CHILD || isatty(0) || !activityOn(root)) return;
|
|
121
|
+
// `context` never read stdin before this writer, and whether Bob's SessionStart pipes one
|
|
122
|
+
// and closes it is unverified: a read there could hold the session's start. A Bob session
|
|
123
|
+
// is first recorded by its first prompt or tool call instead.
|
|
124
|
+
if (verb === 'context' && args.host === 'bob') return;
|
|
125
|
+
const raw = readStdin();
|
|
126
|
+
if (!raw.includes('session_id')) return;
|
|
127
|
+
const { recordActivity } = await import('../js/hosts/activity.mjs');
|
|
128
|
+
recordActivity(root, raw, { host: args.host || 'claude' });
|
|
129
|
+
} catch { /* the activity view is best-effort; a hook that fails is a tool call that fails */ }
|
|
130
|
+
}
|
|
131
|
+
|
|
97
132
|
function die(code, msg) {
|
|
98
133
|
// CRLF on Windows, for the same reason the hook verbs' funnels translate: argparse
|
|
99
134
|
// writes this line through `sys.stderr`, which does. `printErr` owns the `\n`-to-`os.linesep` rule.
|
|
@@ -181,7 +216,11 @@ async function main(argv) {
|
|
|
181
216
|
// PreToolUse, from the gate deliberately blocking (see I3/B1 above). Print the same message
|
|
182
217
|
// to stderr for a human debugging the shim, but return 0 with no stdout, exactly like a gate
|
|
183
218
|
// that chose not to act.
|
|
184
|
-
|
|
219
|
+
// `activity` too: it runs on UserPromptSubmit, where exit 2 erases the user's prompt.
|
|
220
|
+
if (GATE_VERBS.has(verb) || verb === 'activity') {
|
|
221
|
+
printErr(`geneseed-hook: error: ${parsed.error}\n`);
|
|
222
|
+
return 0;
|
|
223
|
+
}
|
|
185
224
|
// `context` and `learn` are not gate verbs, but their own argv errors are not a decision
|
|
186
225
|
// either, so still 1, not 2 (I3/B1): a `<hook name> hook error` notice, and nothing more.
|
|
187
226
|
// `learn` is the one that matters here — it runs on Stop/SubagentStop, where exit 2 ALSO has
|
|
@@ -189,7 +228,9 @@ async function main(argv) {
|
|
|
189
228
|
// `hooks.md`, "Stop, SubagentStop, TaskCompleted, and TeammateIdle").
|
|
190
229
|
return die(1, parsed.error);
|
|
191
230
|
}
|
|
192
|
-
|
|
231
|
+
const rc = (await spec.load())[spec.fn](parsed.args);
|
|
232
|
+
await trackActivity(verb, parsed.args);
|
|
233
|
+
return rc;
|
|
193
234
|
}
|
|
194
235
|
|
|
195
236
|
main(process.argv.slice(2)).then((code) => { process.exitCode = code; });
|
package/docs/concepts/hooks.md
CHANGED
|
@@ -22,6 +22,10 @@ Geneseed writes its hooks into the host's settings file. Every hook calls one pr
|
|
|
22
22
|
| `Stop` | the agent finishes a reply | `geneseed-hook learn` | distils durable facts into `memory/` | needs `GENESEED_LLM` |
|
|
23
23
|
| `SubagentStop` | a subagent finishes | `geneseed-hook learn` | records a lesson for that agent in `memory/agents/<name>.md` | needs `GENESEED_LLM` |
|
|
24
24
|
| `PreCompact` | before auto-compaction | `geneseed-hook learn` | captures memory before the transcript is summarised | needs `GENESEED_LLM` |
|
|
25
|
+
| `UserPromptSubmit` | you send a message | `geneseed-hook activity` | records the turn's start for the web console's Activity view; prints nothing | off with `GENESEED_ACTIVITY=off` |
|
|
26
|
+
| `SessionEnd` | the session closes | `geneseed-hook activity` | marks the session ended and archives it | off with `GENESEED_ACTIVITY=off` |
|
|
27
|
+
|
|
28
|
+
Every hook above also feeds the [Activity view](../reference/plugin-activity.md) after it has decided, unless tracking is off: one file per session under `activity/` beside the install. The gates' verdicts never wait on it.
|
|
25
29
|
|
|
26
30
|
## What each one does, and what you see
|
|
27
31
|
|
|
@@ -14,6 +14,7 @@ Every [host](hosts.md) gets the same content. This table is what each one lets G
|
|
|
14
14
|
| Agents · Skills · Memory · Notebook | ✅ | ✅ | ✅ | ✅ |
|
|
15
15
|
| Project context loaded at session start | ⚙️ plugin | 🪝 hook | 🪝 hook¹ | 🪝 hook² |
|
|
16
16
|
| Memory written back at session end (learn) | ⚙️ plugin | 🪝 hook | 🪝 hook¹ | 🪝 hook² |
|
|
17
|
+
| Live sessions in the web console's [Activity view](../reference/plugin-activity.md) | ⚙️ plugin | 🪝 hook | 🪝 hook, per tool call only (no transcript)¹ | 🪝 hook² |
|
|
17
18
|
| Real data loss (force-push to `main`, discarding uncommitted work, `rm` of untracked files…) | ⚙️ block³ · 🔒 ask (reflog, gc) | 🪝 ask | 🪝 block¹ | 🪝 ask² |
|
|
18
19
|
| Secrets kept out of files | ⚙️ block⁴ | 🪝 ask | 🪝 block¹ | 🪝 ask² |
|
|
19
20
|
| Consent before every commit and push | 🔒 permission ask | 🪝 ask | 🪝 warning¹ | 🪝 ask² |
|
|
@@ -19,6 +19,7 @@ Where Geneseed writes an install, and what an upgrade re-renders.
|
|
|
19
19
|
| Variable | Read by | Effect |
|
|
20
20
|
| --- | --- | --- |
|
|
21
21
|
| `GENESEED_HOME` | build / hooks | Directory holding the hook shim `bin/geneseed-hook` (default `~/.geneseed`). Change it, then rebuild, so the emitted hooks point at the new location. |
|
|
22
|
+
| `GENESEED_ACTIVITY` | hooks, OpenCode plugin | `off` (or `0`, `false`, `no`) stops the activity writer; the hooks then load none of its code. Absent means on. See [geneseed-activity](plugin-activity.md). |
|
|
22
23
|
| `GENESEED_NO_SHIM_CHECK` | CLI | `1` silences the warning every `geneseed` command prints when the hook shim points at a path that no longer exists. For scripted callers; the `status` gates row still says `DEAD`. |
|
|
23
24
|
| `OPENCODE_CONFIG_DIR` | OpenCode emits, `diff`, plugins | OpenCode's config dir — where the global install is written. OpenCode still loads `$XDG_CONFIG_HOME/opencode` beside it, so `status` and `doctor` warn when both hold a Geneseed install. |
|
|
24
25
|
| `XDG_CONFIG_HOME` | OpenCode emits, plugins | Used when `OPENCODE_CONFIG_DIR` is unset: the install goes to `$XDG_CONFIG_HOME/opencode` (default `~/.config/opencode`). |
|
|
@@ -8,13 +8,17 @@ description: "Feeds the web console's Activity view, one small file per session.
|
|
|
8
8
|
---
|
|
9
9
|
One of the [OpenCode plugins](opencode-plugins.md). [Environment variables](environment.md) points here for its switches.
|
|
10
10
|
|
|
11
|
-
**What it does.** Feeds the web console's **Activity** view: one small JSON file per session under `activity/` beside OpenCode's config, recording what the session is doing — phase, model, token and cost totals, files touched, plan, last error. The console reads
|
|
11
|
+
**What it does.** Feeds the web console's **Activity** view: one small JSON file per session under `activity/` beside OpenCode's config, recording what the session is doing — phase, model, token and cost totals, files touched, plan, last error. The console only reads those files; the two only meet on disk, so a crash on either side never blocks a session.
|
|
12
12
|
|
|
13
|
-
**When it runs.** On session events, for top-level sessions only (sub-agents and learn's sessions are skipped).
|
|
13
|
+
**When it runs.** On session events, for top-level sessions only (sub-agents and learn's sessions are skipped). A session whose process died, went stale (30 minutes untouched) or ended leaves the live list and is listed as ended; the reader never deletes a file.
|
|
14
|
+
|
|
15
|
+
**Claude Code, OpenClaude and Bob.** Their hooks write the same files into `activity/` beside the install (`~/.claude/activity/`, `<repo>/.claude/activity/`, `~/.bob/activity/`). No hook is added per tool call: the writer runs after the hooks that already run — the gates, `context` and `learn` — plus `geneseed-hook activity` on `UserPromptSubmit` and, on Claude Code and OpenClaude, `SessionEnd`. So a Claude session's phase moves on the gated tools (`Bash`, `PowerShell`, `Write`, `Edit`, `NotebookEdit`, `Skill`, `Agent`, `Task`), and the rest of the turn — every tool call, the model, the token totals, the last reply — arrives at `Stop`, read from the transcript where the previous `Stop` left off (at most 2 MB per turn). Bob sends no transcript, so a Bob session shows only the calls its `tool-gate` sees, and leaves the live list by staleness alone (Bob has no `SessionEnd`). Bob's `SessionStart` is not recorded either — whether Bob pipes a payload there is unverified, and reading one that never closes would hold the session's start — so a Bob session first appears at its first prompt or tool call. These writers have no resident process, so their snapshots carry `pid: null` and stay live by staleness alone. Recorded: tool names, file basenames, line counts, todo text, and 240-character snippets of the prompt and the last reply — never a shell command, a file's content or an edit's text — and any credential the secrets gate would catch in a snippet is written as `[redacted]`. A project install's `activity/` gets its own `.gitignore` (`*`), and the writer never writes through, or sweeps, an `activity/` or `activity/archive/` that is a link. Nothing is recorded in a repo listed in `excludes.json`, or inside a model CLI that `learn` started.
|
|
16
|
+
|
|
17
|
+
**Archive.** On `SessionStart` and `SessionEnd` the hook writer moves every snapshot that is no longer live into `activity/archive/`, keeping the newest 50 and none older than 7 days. `/api/activity` returns them, with the stale and dead ones still in `activity/`, in its `ended` list — capped there by the same rule, since the OpenCode plugin never sweeps.
|
|
14
18
|
|
|
15
19
|
**What you see.** A card per live session in **Activity** (`geneseed web`).
|
|
16
20
|
|
|
17
21
|
**Switches.**
|
|
18
|
-
- `GENESEED_ACTIVITY=off` — kill switch at startup.
|
|
22
|
+
- `GENESEED_ACTIVITY=off` — kill switch: at startup for the plugin, on every call for the hooks (which then load no writer code at all).
|
|
19
23
|
- The Activity page's own toggle writes a `.geneseed-activity` flag file, read per event — no restart needed.
|
|
20
24
|
- `GENESEED_DEBUG=1` — logs each write as `[geneseed-activity] …`.
|
package/docs/web-ui.md
CHANGED
|
@@ -179,7 +179,8 @@ streams the output of background jobs and keeps their history across reloads.
|
|
|
179
179
|
### 🩺 Care
|
|
180
180
|
|
|
181
181
|
- **Activity** (`#/activity`) — the agent sessions on this machine: each one's status,
|
|
182
|
-
the files it touched and its todo progress; open one for its detail.
|
|
182
|
+
the files it touched and its todo progress; open one for its detail. Every host records it:
|
|
183
|
+
the OpenCode plugin, and `geneseed-hook activity` on Claude Code, OpenClaude and Bob.
|
|
183
184
|
- **Changes** (`#/diff`) — the diff between the deployed harness and the source: edited /
|
|
184
185
|
added / missing files, and files only behind the source (unedited; a rebuild updates them)
|
|
185
186
|
listed apart under **Behind source**, with per-file expansion and coloured unified-diff lines. Select
|
package/harness.config.json
CHANGED
|
@@ -2,5 +2,5 @@
|
|
|
2
2
|
"_comment": "version is a human-readable release label only; the canonical identity of an installed harness is the source fingerprint stamped in .geneseed-version (see `harness version`), not this string.",
|
|
3
3
|
"theme": "neutral",
|
|
4
4
|
"product": "Geneseed",
|
|
5
|
-
"version": "4.
|
|
5
|
+
"version": "4.22.0"
|
|
6
6
|
}
|
package/js/README.md
CHANGED
|
@@ -93,7 +93,8 @@ user co-owns, and the hook verbs those emitted configs then run.
|
|
|
93
93
|
| `hooks-context.mjs` | The `context` verb — SessionStart: session files plus the repo's context docs |
|
|
94
94
|
| `hooks-done.mjs` | The done gate (#289): on Stop, inside `learn` and before its spawn, blocks a turn that edited files until `.geneseed/done-checks.txt`'s checks passed after the last edit |
|
|
95
95
|
| `hooks-learn.mjs` | The `learn` verb — Stop/SubagentStop/PreCompact distiller; the hook path's ONE spawn (`$GENESEED_LLM`) |
|
|
96
|
-
| `hooks-prims.mjs` | The Python path/text primitives the hook verbs share (`splitLines`, `readStdin`, a never-throwing `isFile`) |
|
|
96
|
+
| `hooks-prims.mjs` | The Python path/text primitives the hook verbs share (`splitLines`, `readStdin`, a never-throwing `isFile`), plus the activity off switch (`activityOn`) and the do-nothing `activity` verb |
|
|
97
|
+
| `activity.mjs` | The hook-side activity writer and the owner of snapshot liveness: `recordActivity` (one payload into `<root>/activity/`), `readTranscriptDelta`, `sweepActivity` (archive, newest 50, 7 days). Loaded only when tracking is on; never prints |
|
|
97
98
|
| `usage.mjs` | The usage counter `tool-gate` runs: one `{day, kind, name}` line per Skill or subagent call into `notebook/usage.jsonl`. Hook path: builtins only, silent, never throws |
|
|
98
99
|
| `memory-files.mjs` | The memory store's file format — `frontmatter`, `MEMORY.md` index writes, agent lessons, consolidate. No spawn: the CLI and web console import it |
|
|
99
100
|
| `gitref.mjs` | fs/path-only: `gitRootOf`, `gitDirOf`, `gitCommonDirOf`, `currentBranch`, `protectedBranches`, `stashExists`, `loopLaunched` — read straight off `.git`, never spawn git. Shared by `hooks.mjs`'s git-gate, `loss.mjs` and `js/loop/cli.mjs`'s commit-message writer |
|
package/js/cli-table.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"prog": "geneseed",
|
|
3
3
|
"commands": [
|
|
4
|
+
{
|
|
5
|
+
"name": "activity",
|
|
6
|
+
"help": "UserPromptSubmit/SessionEnd hook: records the session into <root>/activity/ for the web console's live view; decides nothing and prints nothing (off with $GENESEED_ACTIVITY=off or the console toggle)",
|
|
7
|
+
"description": "",
|
|
8
|
+
"positionals": [],
|
|
9
|
+
"options": [
|
|
10
|
+
{
|
|
11
|
+
"names": [
|
|
12
|
+
"--root"
|
|
13
|
+
],
|
|
14
|
+
"dest": "root",
|
|
15
|
+
"metavar": null,
|
|
16
|
+
"help": "the install's own dir (set by the emitted hook); the snapshots go to <root>/activity/",
|
|
17
|
+
"choices": null,
|
|
18
|
+
"default": null,
|
|
19
|
+
"required": false,
|
|
20
|
+
"nargs": null,
|
|
21
|
+
"is_flag": false,
|
|
22
|
+
"type": null,
|
|
23
|
+
"hidden": false
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
"names": [
|
|
27
|
+
"--host"
|
|
28
|
+
],
|
|
29
|
+
"dest": "host",
|
|
30
|
+
"metavar": null,
|
|
31
|
+
"help": "the host that sent the payload (set by the emitted hook): 'claude' (default), 'openclaude' or 'bob'; recorded in the snapshot",
|
|
32
|
+
"choices": null,
|
|
33
|
+
"default": null,
|
|
34
|
+
"required": false,
|
|
35
|
+
"nargs": null,
|
|
36
|
+
"is_flag": false,
|
|
37
|
+
"type": null,
|
|
38
|
+
"hidden": false
|
|
39
|
+
}
|
|
40
|
+
],
|
|
41
|
+
"mutex": []
|
|
42
|
+
},
|
|
4
43
|
{
|
|
5
44
|
"name": "bootstrap",
|
|
6
45
|
"help": "update everything (sync + upgrade) with a progress UI, then run setup",
|
|
@@ -0,0 +1,429 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The hook-side activity writer, and the one owner of what an activity snapshot's LIVENESS means.
|
|
3
|
+
*
|
|
4
|
+
* The OpenCode plugin (`adapters/opencode/plugins/geneseed-activity.js`) writes one snapshot per
|
|
5
|
+
* session into `<cfg>/activity/`; this module writes the same files for the hosts whose hooks are
|
|
6
|
+
* processes rather than a resident plugin — Claude Code, OpenClaude and Bob. The web reader
|
|
7
|
+
* (`js/web/activity.mjs`) cannot tell the two writers apart, and must not need to: the schema is
|
|
8
|
+
* the plugin's, plus `writer: "hook"`, `host`, and the two private cursors below (`normalizeEntry`
|
|
9
|
+
* never returns them).
|
|
10
|
+
*
|
|
11
|
+
* NOT A NEW HOOK ON EVERY TOOL CALL. `bin/geneseed-hook.mjs` calls `recordActivity` after the verb
|
|
12
|
+
* the host ran anyway has decided (the gates, `context`, `learn`), plus the `activity` verb for
|
|
13
|
+
* the two events no other verb is wired to (UserPromptSubmit, SessionEnd). So a Claude session's
|
|
14
|
+
* live phase moves only on the gated tools (`Bash|PowerShell`, `Write|Edit|NotebookEdit`,
|
|
15
|
+
* `Skill|Agent|Task`); the rest of the turn's tool calls arrive at Stop, read out of the
|
|
16
|
+
* transcript from a stored byte offset (`readTranscriptDelta`). Bob sends no `transcript_path`,
|
|
17
|
+
* so a Bob session shows only what its matcher-less `tool-gate` sees, call by call.
|
|
18
|
+
*
|
|
19
|
+
* THIS MODULE IS NEVER LOADED WHEN TRACKING IS OFF — the entry checks the flag first, then imports
|
|
20
|
+
* this file dynamically. It must never print: a hook's stdout is its verdict, and every write
|
|
21
|
+
* here is best-effort (a hook that fails is a tool call that fails).
|
|
22
|
+
*
|
|
23
|
+
* WHAT IS RECORDED, AND WHAT NEVER IS. A tool's name, a file path's BASENAME, line counts, todo
|
|
24
|
+
* text, a prompt snippet and the last assistant message snippet (240 characters each). Never a
|
|
25
|
+
* shell command, a file's content or an edit's text: those are where secrets live.
|
|
26
|
+
*
|
|
27
|
+
* Liveness is owned here because two writers need it now. The hooks have no resident process,
|
|
28
|
+
* so they record `pid: null` and are live by staleness alone; a plugin snapshot keeps its pid
|
|
29
|
+
* probe. `status: "ended"` (SessionEnd) is never live. `sweepActivity` moves what is not live
|
|
30
|
+
* into `activity/archive/`, and the reader lists the archive as ended sessions without ever
|
|
31
|
+
* deleting or moving anything itself.
|
|
32
|
+
*/
|
|
33
|
+
import {
|
|
34
|
+
closeSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readSync,
|
|
35
|
+
renameSync, statSync, unlinkSync, writeFileSync,
|
|
36
|
+
} from 'node:fs';
|
|
37
|
+
import path from 'node:path';
|
|
38
|
+
import { parseIntStrict, stripWhitespace } from '../lib/text.mjs';
|
|
39
|
+
import { SECRET_RE } from './hooks-prims.mjs';
|
|
40
|
+
import { sovereignBypass } from './hosts.mjs';
|
|
41
|
+
|
|
42
|
+
// Every snippet passes Law I's own pattern before it reaches disk; a match becomes this.
|
|
43
|
+
const SECRET_ALL = new RegExp(SECRET_RE.source, 'g');
|
|
44
|
+
// The names `safeStem` can produce, and only those: the sweep moves or deletes nothing else.
|
|
45
|
+
const SNAPSHOT_NAME = /^[A-Za-z0-9_.-]{1,128}\.json$/;
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* A snapshot not touched in this long is not live. pid-liveness is the plugin's real signal; for
|
|
49
|
+
* a hook writer, with no pid, this is the only one, so a session left waiting on the user for
|
|
50
|
+
* longer than this moves to the archive at the next sweep and comes back on its next prompt.
|
|
51
|
+
*/
|
|
52
|
+
export const ACTIVITY_STALE_SECONDS = 1800;
|
|
53
|
+
/** The archive keeps the newest this many ended sessions, and none older than a week. */
|
|
54
|
+
export const ARCHIVE_KEEP = 50;
|
|
55
|
+
export const ARCHIVE_MAX_AGE_SECONDS = 7 * 24 * 3600;
|
|
56
|
+
/** One Stop reads at most this much new transcript; a longer delta keeps its newest bytes. */
|
|
57
|
+
export const TRANSCRIPT_CAP = 2 * 1024 * 1024;
|
|
58
|
+
|
|
59
|
+
// The plugin's caps, so a hook snapshot is the same size as a plugin one.
|
|
60
|
+
const FILE_CAP = 8;
|
|
61
|
+
const TODO_CAP = 12;
|
|
62
|
+
const LOG_CAP = 200;
|
|
63
|
+
const CONV_CAP = 60;
|
|
64
|
+
const CONV_LEN = 240;
|
|
65
|
+
const SNIPPET_LEN = 160;
|
|
66
|
+
const SID_CAP = 128;
|
|
67
|
+
// Edit tools count as touching a file only when they carry an edit, so a Read never counts.
|
|
68
|
+
const EDIT_FIELDS = ['content', 'new_string', 'new_source', 'diff'];
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The plugin's safe-name scheme, capped: every separator, `..`-forming slash and drive colon
|
|
72
|
+
* becomes `_`, so a hostile session id can never steer the join out of the directory. The `u`
|
|
73
|
+
* flag makes an astral character ONE replacement rather than one per surrogate half.
|
|
74
|
+
*/
|
|
75
|
+
export const safeStem = (sid) => String(sid).replace(/[^A-Za-z0-9_.-]/gu, '_').slice(0, SID_CAP);
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* A raw pid value as an integer, or `null`. A parsed JSON number may be the reader's `JsonNumber`
|
|
79
|
+
* wrapper, recognised by its numeric `valueOf`; a decimal string, a boolean and a float (truncated)
|
|
80
|
+
* are what a hand-edited snapshot can produce.
|
|
81
|
+
*/
|
|
82
|
+
function toIntOr(raw) {
|
|
83
|
+
if (raw === true) return 1;
|
|
84
|
+
if (raw === false) return 0;
|
|
85
|
+
if (typeof raw === 'string') return parseIntStrict(stripWhitespace(raw));
|
|
86
|
+
const n = (raw !== null && typeof raw === 'object' && !Array.isArray(raw)) ? raw.valueOf() : raw;
|
|
87
|
+
if (typeof n !== 'number' || !Number.isFinite(n)) return null;
|
|
88
|
+
return Math.trunc(n);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* `process.kill(pid, 0)` probes without a spawn. ESRCH is dead; anything else (EPERM, a
|
|
93
|
+
* locked-down host) errs toward alive, and staleness decides.
|
|
94
|
+
*/
|
|
95
|
+
function pidAlive(raw) {
|
|
96
|
+
const pid = toIntOr(raw);
|
|
97
|
+
if (pid === null || pid <= 0) return false;
|
|
98
|
+
try {
|
|
99
|
+
process.kill(pid, 0);
|
|
100
|
+
return true;
|
|
101
|
+
} catch (e) {
|
|
102
|
+
return !(e && e.code === 'ESRCH');
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Not ended, not stale, and — when the snapshot names a writer pid — that pid alive. A missing or
|
|
108
|
+
* null pid is a hook writer's: staleness alone decides.
|
|
109
|
+
*/
|
|
110
|
+
export function isLive(entry, now) {
|
|
111
|
+
if (entry.status === 'ended') return false;
|
|
112
|
+
if ((now - (Number(entry.updated_at) || 0)) > ACTIVITY_STALE_SECONDS) return false;
|
|
113
|
+
const pid = Object.hasOwn(entry, 'pid') ? entry.pid : null;
|
|
114
|
+
return pid === null || pidAlive(pid);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** A JSON object from `p`, or `null` for a missing, garbage or non-object file. */
|
|
118
|
+
function readJson(p) {
|
|
119
|
+
try {
|
|
120
|
+
const v = JSON.parse(readFileSync(p, 'utf8'));
|
|
121
|
+
return v && typeof v === 'object' && !Array.isArray(v) ? v : null;
|
|
122
|
+
} catch {
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** tmp + rename, so a reader never sees half a file; last writer wins. */
|
|
128
|
+
function writeAtomic(file, obj) {
|
|
129
|
+
const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2, 8)}.tmp`;
|
|
130
|
+
writeFileSync(tmp, JSON.stringify(obj), { mode: 0o600 });
|
|
131
|
+
try {
|
|
132
|
+
renameSync(tmp, file);
|
|
133
|
+
} catch (e) {
|
|
134
|
+
// A reader holding the file open on Windows: drop this write, the next event rewrites it.
|
|
135
|
+
try { unlinkSync(tmp); } catch { /* nothing more to do */ }
|
|
136
|
+
if (!['EPERM', 'EBUSY', 'EACCES'].includes(e && e.code)) throw e;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Redacted on the WHOLE text, before the cut, so a secret the cut lands in is still whole.
|
|
141
|
+
const snip = (s, n = SNIPPET_LEN) => String(s ?? '').replace(SECRET_ALL, '[redacted]')
|
|
142
|
+
.replace(/\s+/g, ' ').trim().slice(0, n);
|
|
143
|
+
|
|
144
|
+
/** True when `p` exists and is a symlink (or junction): the writer and sweep never follow one. */
|
|
145
|
+
function isLink(p) {
|
|
146
|
+
try { return lstatSync(p).isSymbolicLink(); } catch { return false; }
|
|
147
|
+
}
|
|
148
|
+
const lineCount = (s) => (typeof s === 'string' && s ? s.split('\n').length : 0);
|
|
149
|
+
const baseOf = (p) => (typeof p === 'string' && p ? path.basename(p.replace(/\\/g, '/')) : null);
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* The bytes of `file` written since `offset`, as parsed JSONL objects, and the offset to resume
|
|
153
|
+
* from. Only COMPLETE lines are consumed, so a line the host is still writing is read next time.
|
|
154
|
+
* A file shorter than the offset was replaced, and is read from the start; a delta longer than
|
|
155
|
+
* `cap` keeps its newest `cap` bytes, minus the partial line the cut lands in.
|
|
156
|
+
*/
|
|
157
|
+
export function readTranscriptDelta(file, offset = 0, cap = TRANSCRIPT_CAP) {
|
|
158
|
+
let fd;
|
|
159
|
+
try {
|
|
160
|
+
// A regular file only: opening a FIFO or a named pipe blocks the hook until a writer comes.
|
|
161
|
+
if (!statSync(file).isFile()) return { entries: [], offset };
|
|
162
|
+
fd = openSync(file, 'r');
|
|
163
|
+
} catch {
|
|
164
|
+
return { entries: [], offset };
|
|
165
|
+
}
|
|
166
|
+
try {
|
|
167
|
+
const size = fstatSync(fd).size;
|
|
168
|
+
let start = Number.isInteger(offset) && offset >= 0 && offset <= size ? offset : 0;
|
|
169
|
+
let cut = false;
|
|
170
|
+
if (size - start > cap) { start = size - cap; cut = true; }
|
|
171
|
+
const buf = Buffer.alloc(size - start);
|
|
172
|
+
const got = buf.length ? readSync(fd, buf, 0, buf.length, start) : 0;
|
|
173
|
+
const end = buf.subarray(0, got).lastIndexOf(10);
|
|
174
|
+
if (end < 0) return { entries: [], offset: start };
|
|
175
|
+
let lines = buf.subarray(0, end).toString('utf8').split('\n');
|
|
176
|
+
if (cut) lines = lines.slice(1);
|
|
177
|
+
const entries = [];
|
|
178
|
+
for (const l of lines) {
|
|
179
|
+
try {
|
|
180
|
+
const v = JSON.parse(l);
|
|
181
|
+
if (v && typeof v === 'object') entries.push(v);
|
|
182
|
+
} catch { /* a line that is not JSON is skipped, never fatal */ }
|
|
183
|
+
}
|
|
184
|
+
return { entries, offset: start + end + 1 };
|
|
185
|
+
} finally {
|
|
186
|
+
closeSync(fd);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** A tool call's one-line label: the tool and, at most, a file's basename or a skill's name. */
|
|
191
|
+
function toolLabel(name, input) {
|
|
192
|
+
const file = baseOf(input.file_path ?? input.path ?? input.notebook_path);
|
|
193
|
+
if (file) return `${name} ${file}`;
|
|
194
|
+
const named = input.skill ?? input.subagent_type;
|
|
195
|
+
return typeof named === 'string' && named ? `${name} ${snip(named, 60)}` : name;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Folds one tool call into the session's state: a timeline row, and its file or todo list. */
|
|
199
|
+
function applyTool(st, name, input, t, id, status) {
|
|
200
|
+
if (typeof name !== 'string' || !name) return;
|
|
201
|
+
const label = toolLabel(name, input);
|
|
202
|
+
const kind = ['Agent', 'Task'].includes(name) ? 'subtask' : 'tool';
|
|
203
|
+
const row = id ? st.timeline.find((r) => r.id === id) : null;
|
|
204
|
+
if (row) {
|
|
205
|
+
row.status = status;
|
|
206
|
+
} else {
|
|
207
|
+
st.timeline.push({ t, kind, label, tool: name, status, ...(id ? { id } : {}) });
|
|
208
|
+
const file = baseOf(input.file_path ?? input.path ?? input.notebook_path);
|
|
209
|
+
if (file && EDIT_FIELDS.some((k) => typeof input[k] === 'string')) {
|
|
210
|
+
let f = st.files.find((x) => x.file === file);
|
|
211
|
+
if (!f) { f = { file, additions: 0, deletions: 0 }; st.files.push(f); }
|
|
212
|
+
f.additions += lineCount(input.content ?? input.new_string ?? input.new_source);
|
|
213
|
+
f.deletions += lineCount(input.old_string);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
if (Array.isArray(input.todos)) {
|
|
217
|
+
st.todos = input.todos.filter((x) => x && typeof x === 'object')
|
|
218
|
+
.map((x) => ({ content: snip(x.content, CONV_LEN), status: String(x.status ?? 'pending') }));
|
|
219
|
+
}
|
|
220
|
+
return label;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Folds a transcript delta (Claude's JSONL) in: model, token totals, tool calls, last reply. */
|
|
224
|
+
function applyTranscript(st, entries, nowMs) {
|
|
225
|
+
const counted = new Set(st.last_message_id ? [st.last_message_id] : []);
|
|
226
|
+
let reply = null;
|
|
227
|
+
for (const e of entries) {
|
|
228
|
+
const m = e.type === 'assistant' && e.message && typeof e.message === 'object' ? e.message : null;
|
|
229
|
+
if (!m) continue;
|
|
230
|
+
if (typeof m.model === 'string' && m.model && !m.model.startsWith('<')) st.model = m.model;
|
|
231
|
+
if (typeof m.id === 'string' && m.usage && !counted.has(m.id)) {
|
|
232
|
+
counted.add(m.id);
|
|
233
|
+
st.last_message_id = m.id;
|
|
234
|
+
st.tokens += (Number(m.usage.input_tokens) || 0) + (Number(m.usage.output_tokens) || 0);
|
|
235
|
+
}
|
|
236
|
+
const t = Date.parse(e.timestamp) || nowMs;
|
|
237
|
+
for (const b of Array.isArray(m.content) ? m.content : []) {
|
|
238
|
+
if (b && b.type === 'tool_use') {
|
|
239
|
+
applyTool(st, b.name, b.input && typeof b.input === 'object' ? b.input : {}, t, b.id, 'completed');
|
|
240
|
+
} else if (b && b.type === 'text' && typeof b.text === 'string' && b.text.trim()) {
|
|
241
|
+
reply = { text: b.text, t };
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return reply;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** `{count, additions, deletions, items}` over a file list, `items` capped at `cap`. */
|
|
249
|
+
function filesSummary(items, cap) {
|
|
250
|
+
if (!items.length) return null;
|
|
251
|
+
const sum = (k) => items.reduce((a, f) => a + f[k], 0);
|
|
252
|
+
return { count: items.length, additions: sum('additions'), deletions: sum('deletions'),
|
|
253
|
+
items: items.slice(0, cap) };
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function todosSummary(items, cap) {
|
|
257
|
+
if (!items) return null;
|
|
258
|
+
return { done: items.filter((x) => x.status === 'completed').length, total: items.length,
|
|
259
|
+
items: items.slice(0, cap) };
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const ROLL = { SessionStart: 'idle', UserPromptSubmit: 'busy', PreToolUse: 'busy',
|
|
263
|
+
Stop: 'waiting-input', SessionEnd: 'ended' };
|
|
264
|
+
const KNOWN = new Set([...Object.keys(ROLL), 'SubagentStop', 'PreCompact']);
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* The previous snapshot and detail (or null), a hook payload, and the clock → the next
|
|
268
|
+
* `{snap, detail}`, or `null` when the event is not one this writer records. NOT pure: the new
|
|
269
|
+
* detail reuses, and updates in place, `prevDetail`'s lists — the caller writes the result and
|
|
270
|
+
* discards the input, so a copy would only cost time on the hook path. `delta` is what
|
|
271
|
+
* `readTranscriptDelta` returned for a Stop, or null. Claude-shaped and Bob-shaped payloads
|
|
272
|
+
* (`{event, tool, input}`) are both read; a tool payload with no event name is a PreToolUse.
|
|
273
|
+
*/
|
|
274
|
+
export function applyHookEvent(prev, prevDetail, payload, now, { host = 'claude', delta = null } = {}) {
|
|
275
|
+
const p = payload;
|
|
276
|
+
const tool = typeof p.tool_name === 'string' ? p.tool_name : (typeof p.tool === 'string' ? p.tool : null);
|
|
277
|
+
let ev = typeof p.hook_event_name === 'string' ? p.hook_event_name
|
|
278
|
+
: (typeof p.event === 'string' ? p.event : null);
|
|
279
|
+
if (!ev && tool) ev = 'PreToolUse';
|
|
280
|
+
if (!KNOWN.has(ev)) return null;
|
|
281
|
+
const nowMs = Math.round(now * 1000);
|
|
282
|
+
const det = prevDetail || {};
|
|
283
|
+
const snap = prev ? { ...prev } : {
|
|
284
|
+
session_id: p.session_id, agent: null, title: null, cwd: null, status: 'idle', pid: null,
|
|
285
|
+
writer: 'hook', host,
|
|
286
|
+
};
|
|
287
|
+
const st = {
|
|
288
|
+
timeline: Array.isArray(det.timeline) ? det.timeline : [],
|
|
289
|
+
conversation: Array.isArray(det.conversation) ? det.conversation : [],
|
|
290
|
+
files: Array.isArray(det.files?.items) ? det.files.items : [],
|
|
291
|
+
todos: Array.isArray(det.todos?.items) ? det.todos.items : null,
|
|
292
|
+
model: snap.model ?? null,
|
|
293
|
+
tokens: Number(snap.tokens) || 0,
|
|
294
|
+
last_message_id: snap.last_message_id ?? null,
|
|
295
|
+
};
|
|
296
|
+
snap.updated_at = now;
|
|
297
|
+
if (typeof p.cwd === 'string' && p.cwd) snap.cwd = p.cwd;
|
|
298
|
+
if (typeof p.model === 'string' && p.model) st.model = p.model;
|
|
299
|
+
if (ROLL[ev]) snap.status = ROLL[ev];
|
|
300
|
+
if (ev === 'SessionStart') {
|
|
301
|
+
st.timeline.push({ t: nowMs, kind: 'step', label: `Session ${snip(p.source || 'start', 20)}`, status: 'completed' });
|
|
302
|
+
} else if (ev === 'UserPromptSubmit') {
|
|
303
|
+
snap.turn_started_at = now;
|
|
304
|
+
snap.phase = null;
|
|
305
|
+
if (typeof p.prompt === 'string' && p.prompt.trim()) {
|
|
306
|
+
if (!snap.title) snap.title = snip(p.prompt);
|
|
307
|
+
st.conversation.push({ role: 'user', text: snip(p.prompt, CONV_LEN), t: nowMs });
|
|
308
|
+
}
|
|
309
|
+
} else if (ev === 'PreToolUse') {
|
|
310
|
+
const input = (p.tool_input && typeof p.tool_input === 'object') ? p.tool_input
|
|
311
|
+
: ((p.input && typeof p.input === 'object') ? p.input : {});
|
|
312
|
+
const label = applyTool(st, tool, input, nowMs, typeof p.tool_use_id === 'string' ? p.tool_use_id : null, 'running');
|
|
313
|
+
if (label) snap.phase = label;
|
|
314
|
+
} else if (ev === 'Stop') {
|
|
315
|
+
const reply = delta ? applyTranscript(st, delta.entries, nowMs) : null;
|
|
316
|
+
if (delta) snap.transcript_offset = delta.offset;
|
|
317
|
+
const last = typeof p.last_assistant_message === 'string' ? p.last_assistant_message : reply?.text;
|
|
318
|
+
if (last && last.trim()) st.conversation.push({ role: 'assistant', text: snip(last, CONV_LEN), t: nowMs });
|
|
319
|
+
for (const r of st.timeline) if (r.status === 'running') r.status = 'completed';
|
|
320
|
+
snap.phase = null;
|
|
321
|
+
snap.turn_started_at = null;
|
|
322
|
+
} else if (ev === 'SubagentStop') {
|
|
323
|
+
const who = typeof p.agent_type === 'string' && p.agent_type ? ` ${snip(p.agent_type, 60)}` : '';
|
|
324
|
+
st.timeline.push({ t: nowMs, kind: 'subtask', label: `Subagent${who} done`, status: 'completed' });
|
|
325
|
+
} else if (ev === 'PreCompact') {
|
|
326
|
+
st.timeline.push({ t: nowMs, kind: 'step', label: 'Compacting', status: 'completed' });
|
|
327
|
+
} else if (ev === 'SessionEnd') {
|
|
328
|
+
snap.phase = null;
|
|
329
|
+
snap.turn_started_at = null;
|
|
330
|
+
}
|
|
331
|
+
snap.model = st.model;
|
|
332
|
+
snap.tokens = st.tokens;
|
|
333
|
+
if (st.last_message_id) snap.last_message_id = st.last_message_id;
|
|
334
|
+
snap.files = filesSummary(st.files, FILE_CAP);
|
|
335
|
+
snap.todos = todosSummary(st.todos, TODO_CAP);
|
|
336
|
+
const detail = {
|
|
337
|
+
files: filesSummary(st.files, Infinity),
|
|
338
|
+
todos: todosSummary(st.todos, Infinity),
|
|
339
|
+
conversation: st.conversation.slice(-CONV_CAP),
|
|
340
|
+
timeline: st.timeline.slice(-LOG_CAP),
|
|
341
|
+
};
|
|
342
|
+
return { snap, detail };
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* One hook event, recorded. `raw` is the payload text exactly as the host sent it on stdin.
|
|
347
|
+
* Returns whether a snapshot was written. Throws only on an unexpected filesystem error, which
|
|
348
|
+
* the entry swallows; a payload with no `session_id` or a sovereign-bypassed repo writes nothing.
|
|
349
|
+
*/
|
|
350
|
+
export function recordActivity(root, raw, { host = 'claude', now = Date.now() / 1000 } = {}) {
|
|
351
|
+
let p;
|
|
352
|
+
try { p = JSON.parse(raw); } catch { return false; }
|
|
353
|
+
if (!p || typeof p !== 'object' || typeof p.session_id !== 'string' || !p.session_id.trim()) return false;
|
|
354
|
+
if (sovereignBypass(root)) return false;
|
|
355
|
+
const dir = path.join(root, 'activity');
|
|
356
|
+
// A linked `activity/` (one a repo could commit) is never written through.
|
|
357
|
+
if (isLink(dir)) return false;
|
|
358
|
+
const stem = safeStem(p.session_id);
|
|
359
|
+
const snapFile = path.join(dir, `${stem}.json`);
|
|
360
|
+
const detFile = path.join(dir, `${stem}.detail.json`);
|
|
361
|
+
// A session the sweep archived (stale while waiting on the user) resumes from its archived
|
|
362
|
+
// copy, so its title and totals survive; the reader lets the live copy win the duplicate.
|
|
363
|
+
let prev = readJson(snapFile);
|
|
364
|
+
let prevDet = prev ? readJson(detFile) : null;
|
|
365
|
+
if (!prev) {
|
|
366
|
+
prev = readJson(path.join(dir, 'archive', `${stem}.json`));
|
|
367
|
+
if (prev) prevDet = readJson(path.join(dir, 'archive', `${stem}.detail.json`));
|
|
368
|
+
}
|
|
369
|
+
const ev = p.hook_event_name ?? p.event;
|
|
370
|
+
const delta = ev === 'Stop' && typeof p.transcript_path === 'string'
|
|
371
|
+
? readTranscriptDelta(p.transcript_path, prev ? Number(prev.transcript_offset) || 0 : 0) : null;
|
|
372
|
+
const next = applyHookEvent(prev, prevDet, p, now, { host, delta });
|
|
373
|
+
if (!next) return false;
|
|
374
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
375
|
+
// A project install's `activity/` sits inside the repo (`<repo>/.claude/activity/`): it must
|
|
376
|
+
// never be committed. Create-if-absent, so a user's own edit to the file survives.
|
|
377
|
+
try { writeFileSync(path.join(dir, '.gitignore'), '*\n', { flag: 'wx', mode: 0o600 }); } catch { /* exists */ }
|
|
378
|
+
writeAtomic(detFile, next.detail);
|
|
379
|
+
writeAtomic(snapFile, next.snap);
|
|
380
|
+
if (ev === 'SessionStart' || ev === 'SessionEnd') sweepActivity(dir, now);
|
|
381
|
+
return true;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* `[name, entry]` for every session snapshot in `d` that this module may touch: a name
|
|
386
|
+
* `safeStem` can produce, and a JSON object carrying a string `session_id` — what both writers
|
|
387
|
+
* put in every snapshot. A file that fails either test (a user's file, a garbage file) is never
|
|
388
|
+
* listed, so it is never moved or deleted.
|
|
389
|
+
*/
|
|
390
|
+
function snapshots(d) {
|
|
391
|
+
let names;
|
|
392
|
+
try {
|
|
393
|
+
names = readdirSync(d);
|
|
394
|
+
} catch {
|
|
395
|
+
return [];
|
|
396
|
+
}
|
|
397
|
+
return names.filter((n) => SNAPSHOT_NAME.test(n) && !n.endsWith('.detail.json')).sort()
|
|
398
|
+
.map((n) => [n, readJson(path.join(d, n))])
|
|
399
|
+
.filter(([, e]) => e !== null && typeof e.session_id === 'string');
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* Moves every snapshot in `dir` that is not live into `dir/archive/` (its detail file with it),
|
|
404
|
+
* then keeps the archive to the newest `ARCHIVE_KEEP`, none older than `ARCHIVE_MAX_AGE_SECONDS`.
|
|
405
|
+
* Called by the writer on SessionStart and SessionEnd — never by a GET. Stands down when `dir`
|
|
406
|
+
* or `archive/` is a link: a repo that committed `activity/archive` as a link to elsewhere
|
|
407
|
+
* would otherwise have the sweep move and delete files there.
|
|
408
|
+
*/
|
|
409
|
+
export function sweepActivity(dir, now = Date.now() / 1000) {
|
|
410
|
+
const arch = path.join(dir, 'archive');
|
|
411
|
+
if (isLink(dir) || isLink(arch)) return;
|
|
412
|
+
const move = (name) => {
|
|
413
|
+
try { renameSync(path.join(dir, name), path.join(arch, name)); } catch { /* best-effort */ }
|
|
414
|
+
};
|
|
415
|
+
for (const [name, e] of snapshots(dir)) {
|
|
416
|
+
if (isLive(e, now)) continue;
|
|
417
|
+
try { mkdirSync(arch, { recursive: true, mode: 0o700 }); } catch { return; }
|
|
418
|
+
move(`${name.slice(0, -'.json'.length)}.detail.json`);
|
|
419
|
+
move(name);
|
|
420
|
+
}
|
|
421
|
+
const kept = snapshots(arch).map(([name, e]) => ({ name, updated: Number(e.updated_at) || 0 }))
|
|
422
|
+
.sort((a, b) => b.updated - a.updated);
|
|
423
|
+
kept.forEach(({ name, updated }, i) => {
|
|
424
|
+
if (i < ARCHIVE_KEEP && now - updated <= ARCHIVE_MAX_AGE_SECONDS) return;
|
|
425
|
+
for (const n of [name, `${name.slice(0, -'.json'.length)}.detail.json`]) {
|
|
426
|
+
try { unlinkSync(path.join(arch, n)); } catch { /* already gone */ }
|
|
427
|
+
}
|
|
428
|
+
});
|
|
429
|
+
}
|
package/js/hosts/hooks-prims.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The primitives the hook verbs share — `js/hosts/hooks.mjs` (the gates), `hooks-context.mjs`,
|
|
3
|
-
* `hooks-learn.mjs` and `memory-files.mjs
|
|
3
|
+
* `hooks-learn.mjs` and `memory-files.mjs` — plus the activity writer's off switch and its
|
|
4
|
+
* do-nothing `activity` verb, which `bin/geneseed-hook.mjs` reaches without loading the writer.
|
|
4
5
|
*
|
|
5
6
|
* Its own module because the verbs no longer share one: each loads only the code its verb runs
|
|
6
7
|
* (`bin/geneseed-hook.mjs` imports per verb), and a gate is paid on every tool call. What lives
|
|
@@ -105,15 +106,57 @@ export function splitWords(s) {
|
|
|
105
106
|
return s.split(/\s+/).filter(Boolean);
|
|
106
107
|
}
|
|
107
108
|
|
|
108
|
-
/**
|
|
109
|
+
/**
|
|
110
|
+
* stdin, decoded as UTF-8 with Python's universal newlines. Absent stdin reads empty.
|
|
111
|
+
*
|
|
112
|
+
* Read ONCE per process and kept: fd 0 drains on the first read, and the activity writer
|
|
113
|
+
* (`bin/geneseed-hook.mjs`'s `trackActivity`) needs the payload the verb already consumed.
|
|
114
|
+
*/
|
|
115
|
+
let stdinText = null;
|
|
109
116
|
export function readStdin() {
|
|
117
|
+
if (stdinText !== null) return stdinText;
|
|
110
118
|
try {
|
|
111
|
-
|
|
119
|
+
stdinText = readFileSync(0, 'utf8').replaceAll('\r\n', '\n').replaceAll('\r', '\n');
|
|
112
120
|
} catch {
|
|
113
|
-
|
|
121
|
+
stdinText = '';
|
|
114
122
|
}
|
|
123
|
+
return stdinText;
|
|
115
124
|
}
|
|
116
125
|
|
|
126
|
+
// Law I's boundary half — rule-gate's credential scan, and the activity writer's redaction of
|
|
127
|
+
// every snippet it puts on disk. Here, not in `./hooks.mjs`, so the writer reads the one copy
|
|
128
|
+
// without loading the gates. High-precision vendor prefixes only — a generic "looks like
|
|
129
|
+
// entropy" scan would fire on every hash and lockfile, and a gate that cries wolf gets
|
|
130
|
+
// allow-listed. `sk-ant-` takes `_`: Anthropic keys are base64url, and a key whose first `_`
|
|
131
|
+
// fell inside the first 20 characters slipped through. GitHub's classic `ghp_` tokens really are
|
|
132
|
+
// alphanumeric only.
|
|
133
|
+
export const SECRET_RE =
|
|
134
|
+
/\b(?:AKIA[0-9A-Z]{16}|ghp_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}|sk-ant-[A-Za-z0-9_-]{20,}|xox[abprs]-[0-9A-Za-z-]{10,})\b|-----BEGIN [A-Z ]*PRIVATE KEY-----/;
|
|
135
|
+
|
|
136
|
+
const OFF = ['off', '0', 'false', 'no'];
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Whether the activity writer runs for the install at `root`: on unless `$GENESEED_ACTIVITY` or
|
|
140
|
+
* the web console's `<root>/.geneseed-activity` flag says off — the same words, and the same
|
|
141
|
+
* absent-means-on default, as the OpenCode plugin and `js/web/activity.mjs`. One file read: this
|
|
142
|
+
* is paid on every hook call, and it is the only thing paid when tracking is off.
|
|
143
|
+
*/
|
|
144
|
+
export function activityOn(root) {
|
|
145
|
+
if (OFF.includes(String(process.env.GENESEED_ACTIVITY ?? 'on').trim().toLowerCase())) return false;
|
|
146
|
+
try {
|
|
147
|
+
return !OFF.includes(readFileSync(path.join(root, '.geneseed-activity'), 'utf8').trim().toLowerCase());
|
|
148
|
+
} catch {
|
|
149
|
+
return true;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* The `activity` verb, wired to the two events no other verb runs on (UserPromptSubmit;
|
|
155
|
+
* SessionEnd on Claude and OpenClaude). It decides nothing and prints nothing: the entry's
|
|
156
|
+
* `trackActivity` records the payload after every verb alike, this one included.
|
|
157
|
+
*/
|
|
158
|
+
export const cmdActivity = () => 0;
|
|
159
|
+
|
|
117
160
|
// The two output funnels, with Python's newline translation reproduced, are `printOut`/`printErr`
|
|
118
161
|
// in `js/lib/fs.mjs` — they moved there in P5c, beside `writeText`, which is the same rule for
|
|
119
162
|
// FILES, when `js/inspect/excludes.mjs` became the second caller; see that docblock for why the
|
package/js/hosts/hooks.mjs
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* Five of the six HOOK verbs — `context`, `git-gate`, `rule-gate`, `tool-gate`, `learn` — in Node.
|
|
3
|
+
* The sixth, `activity`, decides nothing and lives in `./hooks-prims.mjs`; the activity writer
|
|
4
|
+
* every verb feeds after it decides is `./activity.mjs`, called from `bin/geneseed-hook.mjs`.
|
|
3
5
|
*
|
|
4
6
|
* These are the commands the emitted `settings.json` actually invokes on a user's machine,
|
|
5
7
|
* every session: a SessionStart injector, two PreToolUse gates (and `tool-gate`, the two
|
|
@@ -59,7 +61,7 @@ import {
|
|
|
59
61
|
} from './hosts.mjs';
|
|
60
62
|
import { currentBranch, gitRootOf, loopLaunched } from './gitref.mjs';
|
|
61
63
|
import { LOSS_CANDIDATE_RE, catastrophic, lossReason, stripStructure } from './loss.mjs';
|
|
62
|
-
import { selfAndParents, readStdin } from './hooks-prims.mjs';
|
|
64
|
+
import { selfAndParents, readStdin, SECRET_RE } from './hooks-prims.mjs';
|
|
63
65
|
import { recordUse } from './usage.mjs';
|
|
64
66
|
|
|
65
67
|
// ======================================================================================
|
|
@@ -527,13 +529,8 @@ function ruleGateTarget(p, root) {
|
|
|
527
529
|
}
|
|
528
530
|
}
|
|
529
531
|
|
|
530
|
-
// Law I's boundary half
|
|
531
|
-
//
|
|
532
|
-
// `.env*` is exempt because Law I names it as the place a secret may live. `sk-ant-` takes `_`:
|
|
533
|
-
// Anthropic keys are base64url, and a key whose first `_` fell inside the first 20 characters
|
|
534
|
-
// slipped through. GitHub's classic `ghp_` tokens really are alphanumeric only.
|
|
535
|
-
const SECRET_RE =
|
|
536
|
-
/\b(?:AKIA[0-9A-Z]{16}|ghp_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}|sk-ant-[A-Za-z0-9_-]{20,}|xox[abprs]-[0-9A-Za-z-]{10,})\b|-----BEGIN [A-Z ]*PRIVATE KEY-----/;
|
|
532
|
+
// Law I's boundary half is `SECRET_RE` (`./hooks-prims.mjs`, where the activity writer reads it
|
|
533
|
+
// too). `.env*` is exempt because Law I names it as the place a secret may live.
|
|
537
534
|
const DOTENV_RE = /(^|[\\/])\.env(\.[^\\/]*)?$/;
|
|
538
535
|
|
|
539
536
|
export const SENSOR_LIST = '.geneseed/protected-checks.txt';
|
package/js/hosts/settings.mjs
CHANGED
|
@@ -781,6 +781,9 @@ export function claudeHookGroups(cfg, hookOpts, doctrines = null, excluded = [],
|
|
|
781
781
|
// if Bob ever starts sending one, learning on Bob starts working with no emit change —
|
|
782
782
|
// dropping the group would need a second one re-added later for the same reason.
|
|
783
783
|
Stop: [{ hooks: [{ type: 'command', command: `${run} learn ${mem}${b}${dn} || exit 0` }] }],
|
|
784
|
+
// The activity view's turn start (js/hosts/activity.mjs). Bob has no SessionEnd, so a Bob
|
|
785
|
+
// session leaves the live list by staleness alone.
|
|
786
|
+
UserPromptSubmit: [{ hooks: [{ type: 'command', command: `${run} activity --root "${cfg}"${b} || exit 0` }] }],
|
|
784
787
|
};
|
|
785
788
|
}
|
|
786
789
|
// OpenClaude takes Claude's whole group set and verdicts unchanged. `context` needs the host
|
|
@@ -798,6 +801,7 @@ export function claudeHookGroups(cfg, hookOpts, doctrines = null, excluded = [],
|
|
|
798
801
|
// feeds Stop, SubagentStop and PreCompact, and the flag sits before `|| exit 0`.
|
|
799
802
|
const ruleGate = `${run} rule-gate --root "${cfg}"${secretsGate === false ? ' --no-secrets-gate' : ''}`;
|
|
800
803
|
const learn = `${run} learn ${mem}${h}${doneGate === false ? ' --no-done-gate' : ''} || exit 0`;
|
|
804
|
+
const activity = `${run} activity --root "${cfg}"${h} || exit 0`;
|
|
801
805
|
// Claude Code only (hooks.md, v2.1.295+; Task 1): a `command` hook that can't start, times
|
|
802
806
|
// out, or exits anything but 0 or 2 — even one whose stdout happens to be valid JSON — now
|
|
803
807
|
// BLOCKS the tool call instead of sliding through as the non-blocking default. Only safe to
|
|
@@ -849,6 +853,11 @@ export function claudeHookGroups(cfg, hookOpts, doctrines = null, excluded = [],
|
|
|
849
853
|
// (its `compact` source) re-seeds context AFTER, this captures memory BEFORE. Same
|
|
850
854
|
// `|| exit 0`: never block.
|
|
851
855
|
PreCompact: [{ hooks: [{ type: 'command', command: learn }] }],
|
|
856
|
+
// The activity view's turn start and session end (js/hosts/activity.mjs) — the two events no
|
|
857
|
+
// other verb runs on. Never `onFailure: 'block'`: on UserPromptSubmit a block erases the
|
|
858
|
+
// user's prompt, and the `activity` verb decides nothing.
|
|
859
|
+
UserPromptSubmit: [{ hooks: [{ type: 'command', command: activity }] }],
|
|
860
|
+
SessionEnd: [{ hooks: [{ type: 'command', command: activity }] }],
|
|
852
861
|
};
|
|
853
862
|
// Claude Code only: OpenClaude always runs Git Bash on Windows (its `findGitBashPath` exits
|
|
854
863
|
// without one), and Bob takes the early return above.
|
package/js/web/activity.mjs
CHANGED
|
@@ -1,27 +1,29 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The live-activity surface
|
|
3
|
-
* DELETES.
|
|
2
|
+
* The live-activity surface. A GET reads; it never deletes or moves a file.
|
|
4
3
|
*
|
|
5
|
-
* It reads the per-session JSON files
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
4
|
+
* It reads the per-session JSON files two writers put into `<cfg>/activity/`: the
|
|
5
|
+
* `geneseed-activity` OpenCode plugin, and the hook-side writer for Claude Code, OpenClaude
|
|
6
|
+
* and Bob (`js/hosts/activity.mjs`). Writers and reader share only that directory: no RPC,
|
|
7
|
+
* crash-isolated, and cross-tool by construction. A live session is in `activity`; a stale,
|
|
8
|
+
* dead or ended one — in the directory still, or already swept into `activity/archive/` — is
|
|
9
|
+
* in `ended`, marked `ended: true`, and the live copy wins a duplicate.
|
|
10
|
+
*
|
|
11
|
+
* WHY THE GET STOPPED PRUNING. It used to unlink every snapshot that failed the liveness test,
|
|
12
|
+
* which made a page view the one web read that deleted, and left nothing to show of a session
|
|
13
|
+
* that had just finished. Moving belongs to `sweepActivity`, which the hook writer runs on
|
|
14
|
+
* SessionStart and SessionEnd and which archives instead of deleting. The OpenCode plugin never
|
|
15
|
+
* sweeps, so its dead snapshots stay in place: `ended` is therefore capped HERE, in what is
|
|
16
|
+
* returned, to the archive's own rule (the newest `ARCHIVE_KEEP`, none older than
|
|
17
|
+
* `ARCHIVE_MAX_AGE_SECONDS`) — without touching a file.
|
|
9
18
|
*
|
|
10
19
|
* `/api/activity` answers a GET through `apiActivity` and a POST through `apiActivityToggle`
|
|
11
20
|
* at the bottom of this file. It is the one POST route whose result is sent at 200 whatever
|
|
12
21
|
* `ok` says, which is why `POST_ROUTES` in `js/web/routes.mjs` carries a 409 COLUMN rather
|
|
13
22
|
* than a rule — and giving this row the 409 treatment is mutation M22.
|
|
14
23
|
*
|
|
15
|
-
* `
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
* "no such process" vs "err toward alive".
|
|
19
|
-
*
|
|
20
|
-
* `process.kill` alone cannot tell a truly-dead pid from one that EXITED but whose handle is
|
|
21
|
-
* still held: it reports the latter alive too. The staleness backstop (below) is what prunes
|
|
22
|
-
* it, thirty minutes later — reproducing an exit-code read would need a native binding, not
|
|
23
|
-
* worth it for a best-effort probe that already errs toward "alive" on any inconclusive
|
|
24
|
-
* answer.
|
|
24
|
+
* Liveness (`isLive`) is owned by `js/hosts/activity.mjs`, because the sweep needs the same
|
|
25
|
+
* answer: a hook snapshot carries `pid: null` and is live by staleness alone; a plugin one is
|
|
26
|
+
* also probed with `process.kill(pid, 0)`, which is a core `process` API, not `child_process`.
|
|
25
27
|
*
|
|
26
28
|
* `parseJson`, NOT `JSON.parse` — NOT a style choice. These files are written by a third
|
|
27
29
|
* party and carry `cost` as a float. `JSON.parse` collapses `1.0` to the bare integer `1`,
|
|
@@ -33,28 +35,22 @@
|
|
|
33
35
|
* `0.0` instead of collapsing to the fallback `0`. `isTruthy` is what makes a wrapped zero
|
|
34
36
|
* read as falsy, so a `"cost": 0.0` entry correctly comes back `0`.
|
|
35
37
|
*/
|
|
36
|
-
import { mkdirSync, readdirSync
|
|
38
|
+
import { mkdirSync, readdirSync } from 'node:fs';
|
|
37
39
|
import path from 'node:path';
|
|
38
40
|
|
|
39
41
|
import { readText, writeText, isDir, isFile } from '../lib/fs.mjs';
|
|
40
42
|
import { parseJson, isTruthy } from '../lib/json.mjs';
|
|
41
43
|
import { normcase } from '../lib/paths.mjs';
|
|
42
|
-
import {
|
|
44
|
+
import { stripWhitespace } from '../lib/text.mjs';
|
|
45
|
+
import { ARCHIVE_KEEP, ARCHIVE_MAX_AGE_SECONDS, isLive, safeStem } from '../hosts/activity.mjs';
|
|
43
46
|
import { NotFound, stemOf } from './catalog.mjs';
|
|
44
47
|
|
|
45
|
-
/**
|
|
46
|
-
* A session whose writer is gone, or that has not been touched in this long, is pruned.
|
|
47
|
-
* pid-liveness is the real signal; the staleness backstop covers a reused pid and a
|
|
48
|
-
* platform where the probe cannot tell. Generous on purpose: streaming bumps `updated_at`
|
|
49
|
-
* constantly, so only a genuinely abandoned (process-still-alive) session ages out.
|
|
50
|
-
*/
|
|
51
|
-
const ACTIVITY_STALE_SECONDS = 1800;
|
|
52
|
-
|
|
53
48
|
const nowSeconds = () => Date.now() / 1000;
|
|
54
49
|
|
|
55
50
|
/**
|
|
56
|
-
* `<target>/activity`. `state.target` is ALREADY the
|
|
57
|
-
* append `opencode/` again; that double-join is the
|
|
51
|
+
* `<target>/activity`. `state.target` is ALREADY the viewed install's config dir (OpenCode's, or
|
|
52
|
+
* a Claude-shaped host's), so this must not append `opencode/` again; that double-join is the
|
|
53
|
+
* classic seam bug.
|
|
58
54
|
*/
|
|
59
55
|
const activityDir = (state) => path.join(state.target, 'activity');
|
|
60
56
|
|
|
@@ -76,40 +72,6 @@ function activityEnabled(state) {
|
|
|
76
72
|
return !['off', '0', 'false', 'no'].includes(stripWhitespace(raw).toLowerCase());
|
|
77
73
|
}
|
|
78
74
|
|
|
79
|
-
/**
|
|
80
|
-
* Coerces a raw pid value to an integer, or `null` for anything unusable.
|
|
81
|
-
*
|
|
82
|
-
* The value came out of `parseJson`, so a JSON number may arrive wrapped in `JsonNumber`,
|
|
83
|
-
* which this module cannot import by name (only `parseJson`/`isTruthy`/etc are exported). It
|
|
84
|
-
* is recognised by the only thing the wrapper promises: a numeric `valueOf`. A plain
|
|
85
|
-
* object's `valueOf` returns itself (rejected by the `typeof n !== 'number'` check below)
|
|
86
|
-
* and an array is excluded outright. Also handles a decimal string, a boolean (`true` → 1),
|
|
87
|
-
* and a float (truncated) — whatever a hand-edited snapshot can produce.
|
|
88
|
-
*/
|
|
89
|
-
function toIntOr(raw) {
|
|
90
|
-
if (raw === true) return 1;
|
|
91
|
-
if (raw === false) return 0;
|
|
92
|
-
if (typeof raw === 'string') return parseIntStrict(stripWhitespace(raw));
|
|
93
|
-
const n = (raw !== null && typeof raw === 'object' && !Array.isArray(raw))
|
|
94
|
-
? raw.valueOf() : raw;
|
|
95
|
-
if (typeof n !== 'number' || !Number.isFinite(n)) return null;
|
|
96
|
-
return Math.trunc(n);
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
/** Best-effort liveness for the writer process. See this file's header. */
|
|
100
|
-
function pidAlive(raw) {
|
|
101
|
-
const pid = toIntOr(raw);
|
|
102
|
-
if (pid === null || pid <= 0) return false;
|
|
103
|
-
try {
|
|
104
|
-
process.kill(pid, 0);
|
|
105
|
-
return true;
|
|
106
|
-
} catch (e) {
|
|
107
|
-
// ESRCH → dead. Anything else (`EPERM`, and whatever a locked-down host answers) →
|
|
108
|
-
// alive, and the staleness backstop decides.
|
|
109
|
-
return !(e && e.code === 'ESRCH');
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
|
|
113
75
|
/**
|
|
114
76
|
* One session snapshot normalised into the stable shape the UI consumes. v1 writers omit
|
|
115
77
|
* the enrichment keys, so those default to null/0 and the UI hides what is absent. The KEY
|
|
@@ -148,24 +110,12 @@ function readEntry(p) {
|
|
|
148
110
|
return (entry !== null && typeof entry === 'object' && !Array.isArray(entry)) ? entry : null;
|
|
149
111
|
}
|
|
150
112
|
|
|
151
|
-
/** The writer's pid is alive AND the snapshot is not stale. */
|
|
152
|
-
function isLive(entry, now) {
|
|
153
|
-
const updated = isTruthy(Object.hasOwn(entry, 'updated_at') ? entry.updated_at : null)
|
|
154
|
-
? entry.updated_at : 0;
|
|
155
|
-
return (now - Number(updated)) <= ACTIVITY_STALE_SECONDS && pidAlive(
|
|
156
|
-
Object.hasOwn(entry, 'pid') ? entry.pid : null);
|
|
157
|
-
}
|
|
158
|
-
|
|
159
113
|
/**
|
|
160
|
-
*
|
|
161
|
-
* missing dir is `[]`, a garbage file is skipped
|
|
162
|
-
* failed the liveness test is unlinked), newest first.
|
|
114
|
+
* `[name, entry]` for every snapshot that parses in `d`, sorted by name. Never throws: a
|
|
115
|
+
* missing dir is `[]`, and a garbage file is skipped and left where it is.
|
|
163
116
|
*/
|
|
164
|
-
function
|
|
165
|
-
const d = activityDir(state);
|
|
117
|
+
function snapshots(d) {
|
|
166
118
|
if (!isDir(d)) return [];
|
|
167
|
-
const now = nowSeconds();
|
|
168
|
-
const out = [];
|
|
169
119
|
let names;
|
|
170
120
|
try {
|
|
171
121
|
names = readdirSync(d);
|
|
@@ -175,48 +125,66 @@ function activityEntries(state) {
|
|
|
175
125
|
// Case-INSENSITIVE for the `.json` suffix (matches Windows filesystem behaviour); the
|
|
176
126
|
// `.detail.json` check below is case-SENSITIVE on both platforms. Two different rules,
|
|
177
127
|
// deliberately.
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
128
|
+
return names.filter((n) => normcase(n).endsWith('.json') && !n.endsWith('.detail.json')).sort()
|
|
129
|
+
.map((name) => [name, readEntry(path.join(d, name))]).filter(([, e]) => e !== null);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// STABLE sort matters when `updated_at` ties: a `b - a` comparator over ES2019's
|
|
133
|
+
// guaranteed-stable `Array.sort` preserves the original (directory-listing) order for equal keys.
|
|
134
|
+
const newestFirst = (list) => list.sort((a, b) => Number(b.updated_at) - Number(a.updated_at));
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* `{activity, ended}`: the live sessions, and the ones that are not — still in the directory
|
|
138
|
+
* or already archived — each listed once, the live copy and then the directory's winning.
|
|
139
|
+
*/
|
|
140
|
+
function activityEntries(state) {
|
|
141
|
+
const d = activityDir(state);
|
|
142
|
+
const now = nowSeconds();
|
|
143
|
+
const live = [];
|
|
144
|
+
const ended = [];
|
|
145
|
+
const seen = new Set();
|
|
146
|
+
const rest = [];
|
|
147
|
+
for (const [name, entry] of snapshots(d)) {
|
|
148
|
+
const e = normalizeEntry(entry, stemOf(name));
|
|
149
|
+
if (isLive(entry, now)) { live.push(e); seen.add(String(e.session_id)); } else rest.push(e);
|
|
191
150
|
}
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
151
|
+
for (const [name, entry] of snapshots(path.join(d, 'archive'))) {
|
|
152
|
+
rest.push(normalizeEntry(entry, stemOf(name)));
|
|
153
|
+
}
|
|
154
|
+
for (const e of rest) {
|
|
155
|
+
if (seen.has(String(e.session_id))) continue;
|
|
156
|
+
seen.add(String(e.session_id));
|
|
157
|
+
if (now - Number(e.updated_at) > ARCHIVE_MAX_AGE_SECONDS) continue;
|
|
158
|
+
ended.push({ ...e, ended: true });
|
|
159
|
+
}
|
|
160
|
+
return { activity: newestFirst(live), ended: newestFirst(ended).slice(0, ARCHIVE_KEEP) };
|
|
197
161
|
}
|
|
198
162
|
|
|
199
163
|
export function apiActivity(state) {
|
|
200
164
|
const enabled = activityEnabled(state);
|
|
201
|
-
return { enabled,
|
|
165
|
+
return { enabled, ...(enabled ? activityEntries(state) : { activity: [], ended: [] }) };
|
|
202
166
|
}
|
|
203
167
|
|
|
204
168
|
/**
|
|
205
|
-
* One session's snapshot plus its step timeline and its UNCAPPED files/todos.
|
|
206
|
-
*
|
|
207
|
-
*
|
|
169
|
+
* One session's snapshot plus its step timeline and its UNCAPPED files/todos. A session that is
|
|
170
|
+
* no longer live — still in the directory, or archived — is returned too, with `ended: true`.
|
|
171
|
+
* 404 only if neither holds it; a missing or garbage detail file degrades to an empty timeline
|
|
172
|
+
* rather than a 500.
|
|
208
173
|
*/
|
|
209
174
|
export function apiActivityDetail(state, sid) {
|
|
210
|
-
|
|
211
|
-
//
|
|
212
|
-
//
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
175
|
+
// Resolve by the writer's safe-name scheme (`safeStem`), which is also what keeps the read
|
|
176
|
+
// inside the directory: every separator, `..` and drive colon becomes `_`, so there is no
|
|
177
|
+
// join to steer.
|
|
178
|
+
const stem = safeStem(sid);
|
|
179
|
+
let d = activityDir(state);
|
|
180
|
+
let entry = isFile(path.join(d, `${stem}.json`)) ? readEntry(path.join(d, `${stem}.json`)) : null;
|
|
181
|
+
if (entry === null) {
|
|
182
|
+
d = path.join(d, 'archive');
|
|
183
|
+
entry = isFile(path.join(d, `${stem}.json`)) ? readEntry(path.join(d, `${stem}.json`)) : null;
|
|
184
|
+
}
|
|
185
|
+
if (entry === null) throw new NotFound(sid);
|
|
219
186
|
const session = normalizeEntry(entry, stem);
|
|
187
|
+
if (!isLive(entry, nowSeconds())) session.ended = true;
|
|
220
188
|
let timeline = [];
|
|
221
189
|
let full = {};
|
|
222
190
|
const det = readEntry(path.join(d, `${stem}.detail.json`));
|
package/js/web/server.mjs
CHANGED
|
@@ -37,6 +37,7 @@ import { existsSync } from 'node:fs';
|
|
|
37
37
|
import { createServer } from 'node:http';
|
|
38
38
|
import { join, resolve as pathResolve } from 'node:path';
|
|
39
39
|
import { fileURLToPath } from 'node:url';
|
|
40
|
+
import { sweepActivity } from '../hosts/activity.mjs';
|
|
40
41
|
|
|
41
42
|
const ROOT = pathResolve(import.meta.dirname, '..', '..');
|
|
42
43
|
|
|
@@ -153,6 +154,11 @@ export async function serve({ theme = null, port = 4747, openBrowser = true,
|
|
|
153
154
|
// Read by `/api/update`, whose background `git fetch` must not race a running update's pull.
|
|
154
155
|
state.jobBusy = () => jm.busy;
|
|
155
156
|
const srv = createServer(makeHandler(state, jm, token, dist, holder));
|
|
157
|
+
// A GET only reads, and the OpenCode plugin never sweeps: ended sessions are archived here,
|
|
158
|
+
// once at start and every 10 minutes. Best-effort — a sweep failure never stops the console.
|
|
159
|
+
const sweep = () => { try { sweepActivity(join(state.target, 'activity')); } catch { /* best-effort */ } };
|
|
160
|
+
sweep();
|
|
161
|
+
setInterval(sweep, 600_000).unref();
|
|
156
162
|
// A client trickling headers or a body (slowloris) would hold a socket forever otherwise; every
|
|
157
163
|
// real request here is a few KB from the same machine.
|
|
158
164
|
srv.requestTimeout = 30_000;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"//": "Every field here is argued and gated in tests/unit/package_manifest.test.mjs. `files`, `bin` and `engines` each have a test that fails when reality drifts from this file; `version` mirrors harness.config.json and is gated too. Read that docblock before editing this one.",
|
|
3
3
|
"name": "geneseed",
|
|
4
|
-
"version": "4.
|
|
4
|
+
"version": "4.22.0",
|
|
5
5
|
"description": "A portable, theme-able harness you implant once and use everywhere to grow a disciplined AI coding agent.",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"ai",
|
package/src/modes/foreman.md
CHANGED
|
@@ -24,4 +24,5 @@ crews for what's substantial, and keeps answering the user without blocking.
|
|
|
24
24
|
commits and merges only once the user accepts ({{DOCTRINE:consent-before-push}}). Commit, push and
|
|
25
25
|
merge stay the parent's alone.
|
|
26
26
|
- **Report.** Surface pipeline completions, failures, and merges to the user as
|
|
27
|
-
they happen
|
|
27
|
+
they happen; a crew that returns no proof, or goes silent, is handled as the
|
|
28
|
+
pipeline {{SKILL}}'s step 2 says.
|
package/src/skills/pipeline.md
CHANGED
|
@@ -26,8 +26,8 @@ The minimum roster per task type. The crew lead chooses the crew from the whole
|
|
|
26
26
|
## Procedure
|
|
27
27
|
|
|
28
28
|
1. Take the triage as given. Under foreman mode the task reached you because it met the mode's count; invoked directly, the user's request is the trigger. Do not weigh it again and fall back to doing the work yourself.
|
|
29
|
-
2. **Dispatch the crew lead** in the background, using the host's general-purpose {{AGENT}}. Before dispatch, record BASE and set the crew's **write set**; check it against every other pipeline in flight ({{DOCTRINE:one-writer-per-file}}) — two crews whose sets overlap do not run at once. The brief carries: the task as the user stated it, the task type, BASE, the write set, the proof commands, a pointer to this {{SKILL}}, and the rule that it never commits, pushes or merges. Tell the user the pipeline is running, then go back to the user. Do not wait on the crew lead.
|
|
30
|
-
3. **The crew lead composes the crew** from the floor above and adds any {{AGENT}} the task needs. It dispatches each crew member as its own subagent, each handed what the previous one produced. Where the crew lead holds no dispatch tool (see *Hosts* below), it plays each role in turn itself, with the same hand-offs and the same envelope. Steps 4 to 7 are the crew lead's, except where they name the parent.
|
|
29
|
+
2. **Dispatch the crew lead** in the background, using the host's general-purpose {{AGENT}}. Before dispatch, record BASE and set the crew's **write set**; check it against every other pipeline in flight ({{DOCTRINE:one-writer-per-file}}) — two crews whose sets overlap do not run at once. The brief carries: the task as the user stated it, the task type, BASE, the write set, the proof commands, a pointer to this {{SKILL}}, and the rule that it never commits, pushes or merges. Tell the user the pipeline is running, then go back to the user. Do not wait on the crew lead. **Then watch what you dispatched.** An envelope without proof, or one that says the crew is still waiting, is a failure: act on it at once — resume the crew lead (`SendMessage` on Claude Code) or take over its worktree — never wait for a notification it promised. A crew member's report that reaches you directly means its crew lead has already ended; act on it the same way. Before you end a turn with a crew still out, set a check where the host offers one (`CronCreate` on Claude Code, top level only); elsewhere, check at the start of every turn. A crew is stalled when its transcript and output have not grown for 15 minutes **and** it has no live child process: ping it once; if the next check shows no change, stop it, then take over from its worktree. A crew whose output still grows, or that runs a child process, is never taken over — a long suite or canary is not a stall.
|
|
30
|
+
3. **The crew lead composes the crew** from the floor above and adds any {{AGENT}} the task needs. It dispatches each crew member as its own subagent, each handed what the previous one produced. **The crew lead never ends with a member unresolved.** Its last message is its result: once it ends, nothing wakes it, and a member that outlives it reports past it, to the parent. It may run members in parallel, but holds every member's result before it ends — returned, or failed and then redone or named as failed in the envelope. A member that returns nothing has failed. Where the crew lead holds no dispatch tool (see *Hosts* below), it plays each role in turn itself, with the same hand-offs and the same envelope. Steps 4 to 7 are the crew lead's, except where they name the parent.
|
|
31
31
|
4. Isolate the crew's work in its own git worktree/branch. Where worktrees are unavailable, fall back to a single tree, one pipeline at a time, and say so. The crew writes only inside its write set; shared append files (registries, index tables, lockfiles, generated bundles) are the parent's to apply, never a crew's.
|
|
32
32
|
5. **The dev↔tester loop:** the developer implements, the tester validates — runs the tests and lint, produces raw logs. On failure, the findings go back to the developer — two repair rounds at most, then one fresh developer (a higher model tier where the host offers one) carrying the tester's findings ({{DOCTRINE:bound-the-loop}}); if that fails too, stop, do not merge, and report the failure with the branch left in place for inspection. A conflict or ambiguity between the plan, the findings and the code is yours to decide: decide it, record `Ruling: <choice> — <why> — <cost if wrong>` in the worklog, and continue. Stop only for what {{LAW:echo-the-intent}}, {{LAW:deletion-is-deliberate}} or {{DOCTRINE:consent-before-push}} names; every ruling goes in the final report ({{DOCTRINE:declare-the-judgment-calls}}). When the plan names a `Spec:`, the analyst reads it once; the spec outranks the plan.
|
|
33
33
|
6. **Pick the shape by host** (table below). Where the host offers a workflow tool the {{SKILL}} may use without a fresh opt-in, a saved script may stand in for the crew lead: analyst → developer → (tester ⇄ developer)×≤2 → fresh developer → proof ([workflow {{SKILL}}](workflow.md)). Everywhere else the crew lead runs the same stages, with the same hand-offs and the same delivery contract.
|