wyrm-mcp 9.2.0 → 9.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +2 -0
  2. package/dist/auto-runs.js +1 -0
  3. package/dist/autoconfig.js +3 -3
  4. package/dist/capabilities.js +3 -3
  5. package/dist/causality.js +13 -8
  6. package/dist/cli.js +25 -22
  7. package/dist/cloud/cli.js +3 -3
  8. package/dist/cloud/sync-daemon-entrypoint.js +2 -2
  9. package/dist/cloud/sync-daemon.js +1 -1
  10. package/dist/color.js +1 -0
  11. package/dist/database.js +3 -3
  12. package/dist/deprecations.js +2 -2
  13. package/dist/events.js +6 -6
  14. package/dist/federation.js +10 -10
  15. package/dist/handlers/arg-keys.js +1 -0
  16. package/dist/handlers/capture.js +58 -58
  17. package/dist/handlers/causality.js +8 -8
  18. package/dist/handlers/cloud.js +85 -83
  19. package/dist/handlers/companion.js +10 -10
  20. package/dist/handlers/entity.js +1 -1
  21. package/dist/handlers/events.js +12 -12
  22. package/dist/handlers/failure.js +12 -12
  23. package/dist/handlers/goals.js +4 -4
  24. package/dist/handlers/intelligence.js +63 -63
  25. package/dist/handlers/mcpclient.js +1 -1
  26. package/dist/handlers/presence.js +3 -3
  27. package/dist/handlers/project-arg.js +1 -0
  28. package/dist/handlers/project.js +1 -1
  29. package/dist/handlers/quest.js +5 -3
  30. package/dist/handlers/recall.js +18 -18
  31. package/dist/handlers/registry.js +1 -1
  32. package/dist/handlers/resources.js +1 -1
  33. package/dist/handlers/review.js +3 -3
  34. package/dist/handlers/run.js +3 -3
  35. package/dist/handlers/search.js +3 -3
  36. package/dist/handlers/session.js +24 -24
  37. package/dist/handlers/share.js +5 -5
  38. package/dist/handlers/shims.js +1 -1
  39. package/dist/handlers/thread.js +2 -2
  40. package/dist/http-auth.js +1 -1
  41. package/dist/http-fast.js +15 -15
  42. package/dist/index.js +2 -2
  43. package/dist/logger.js +2 -2
  44. package/dist/receipt.js +1 -1
  45. package/dist/rehydration.js +24 -9
  46. package/dist/render.js +3 -3
  47. package/dist/setup.js +2 -3
  48. package/dist/sqlite-busy.js +1 -1
  49. package/dist/stale-servers.js +2 -0
  50. package/dist/stdio-lifecycle.js +1 -0
  51. package/dist/storage/index.js +3 -3
  52. package/dist/tool-manifest-v2.json +1 -1
  53. package/dist/tool-manifest.json +1 -1
  54. package/dist/ui-dashboard.js +9 -8
  55. package/dist/validate.js +1 -1
  56. package/dist/vault-exec.js +4 -0
  57. package/dist/vault.js +1 -1
  58. package/dist/wyrm-cli.js +105 -142
  59. package/dist/wyrm-manifest.json +3 -3
  60. package/dist/wyrm-ui.js +14 -7
  61. package/dist/wyrm.js +2 -0
  62. package/package.json +6 -4
  63. package/scripts/hooks/wyrm-citation-audit.mjs +155 -46
  64. package/scripts/hooks/wyrm-prompt-context.mjs +300 -0
  65. package/scripts/hooks/wyrm-run-auto.mjs +148 -37
  66. package/scripts/hooks/wyrm-session-rehydrate.mjs +142 -24
@@ -8,13 +8,23 @@
8
8
  * dispatches on `hook_event_name` from the Claude Code stdin payload:
9
9
  *
10
10
  * SessionStart -> `wyrm run start --orchestrator claude-code`, capture
11
- * the printed run_id, persist {session_id -> run_id} in
12
- * ~/.wyrm/auto-runs.json (read-modify-write).
11
+ * the printed run_id, persist
12
+ * {session_id -> {run_id, n, t}} in ~/.wyrm/auto-runs.json.
13
13
  * PreToolUse(Task) -> a subagent spawn (fan-out): `wyrm run join` the mapped
14
14
  * run with a stable-ish agent id derived from
15
15
  * tool_input.subagent_type/description + a short counter.
16
16
  * SessionEnd / Stop -> `wyrm run end` the mapped run; drop the mapping entry.
17
17
  *
18
+ * THE MAP FILE. `n` is the subagent counter and `t` the last time the entry
19
+ * was used (ms). Every change is a read-modify-write under a lock
20
+ * (auto-runs.json.lock, created O_EXCL) with write-then-rename, so concurrent
21
+ * sessions never write back a copy that misses another's entry, and every
22
+ * write prunes entries idle longer than MAX_AGE_MS. SessionEnd used to be the
23
+ * only removal, so a session that never reached it (a killed terminal, a
24
+ * crash) left its entry forever: 51 on the store the 2026-09-13 audit read.
25
+ * `wyrm run prune` cleans an existing file in one pass; src/auto-runs.ts
26
+ * carries the same age bound and lock timings, keep the two in step.
27
+ *
18
28
  * Pure node (builtins + a portable spawnSync of the resolved `wyrm` CLI).
19
29
  * Best-effort, NEVER blocks the harness: every error is swallowed and the
20
30
  * process ALWAYS exits 0.
@@ -34,36 +44,111 @@
34
44
  * @copyright 2026 Ghost Protocol (Pvt) Ltd.
35
45
  * @license Proprietary — (c) 2026 Ghost Protocol (Pvt) Ltd. All rights reserved. See LICENSE.
36
46
  */
37
- import { readFileSync, writeFileSync, renameSync, mkdirSync, existsSync } from 'node:fs';
47
+ import { readFileSync, writeFileSync, renameSync, mkdirSync, existsSync, openSync, closeSync, writeSync, statSync, unlinkSync } from 'node:fs';
38
48
  import { spawnSync } from 'node:child_process';
49
+ import { randomBytes } from 'node:crypto';
39
50
  import { homedir } from 'node:os';
40
51
  import { join } from 'node:path';
41
52
 
42
53
  const WYRM_DIR = join(homedir(), '.wyrm');
43
54
  const STORE = join(WYRM_DIR, 'auto-runs.json');
55
+ const LOCK = `${STORE}.lock`;
56
+
57
+ /** Entries idle longer than this are pruned on every write (src/auto-runs.ts AUTO_RUNS_MAX_AGE_DAYS). */
58
+ const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
59
+ /** How long to wait for the lock, and when a lock counts as left by a dead writer (src/auto-runs.ts). */
60
+ const LOCK_WAIT_MS = 6000;
61
+ const LOCK_STALE_MS = 5000;
44
62
 
45
- /** Read the {session_id -> {run_id, n}} map; tolerate missing/corrupt file. */
63
+ /** Read the {session_id -> {run_id, n, t}} map; tolerate missing/corrupt file. */
46
64
  function readStore() {
47
65
  try {
48
66
  const obj = JSON.parse(readFileSync(STORE, 'utf8'));
49
- return obj && typeof obj === 'object' ? obj : {};
67
+ return obj && typeof obj === 'object' && !Array.isArray(obj) ? obj : {};
50
68
  } catch { return {}; }
51
69
  }
52
70
 
71
+ /** Persist the map (0600), write-then-rename so a reader never sees a partial file. Only under the lock. */
72
+ function writeStore(obj) {
73
+ const tmp = `${STORE}.tmp.${process.pid}`;
74
+ writeFileSync(tmp, JSON.stringify(obj), { mode: 0o600 });
75
+ renameSync(tmp, STORE);
76
+ }
77
+
78
+ const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
79
+
80
+ /** The ms timestamp a ULID run id starts with, or null for anything else. */
81
+ function ulidTimeMs(id) {
82
+ if (typeof id !== 'string' || !/^[0-9A-HJKMNP-TV-Z]{26}$/.test(id)) return null;
83
+ let t = 0;
84
+ for (let i = 0; i < 10; i++) t = t * 32 + CROCKFORD.indexOf(id[i]);
85
+ return t;
86
+ }
87
+
53
88
  /**
54
- * Persist the map (best-effort, 0600). Write-then-rename so a reader never
55
- * observes a truncated/partial file. NOTE: this does not close the
56
- * read-modify-write race between concurrent hook invocations (e.g. parallel
57
- * Task fan-out can still lose a counter bump) — a cross-process lock or a
58
- * SQLite-backed counter is a ticketed follow-up, not in scope here.
89
+ * Drop entries without a run_id, and entries idle past MAX_AGE_MS: idle since
90
+ * `t`, or since the run id's ULID time for an entry written before `t`
91
+ * existed. An entry with no readable age stays and starts its clock now.
59
92
  */
60
- function writeStore(obj) {
93
+ function prune(store, now) {
94
+ for (const [session, entry] of Object.entries(store)) {
95
+ if (!entry || typeof entry !== 'object' || typeof entry.run_id !== 'string' || !entry.run_id) {
96
+ delete store[session];
97
+ continue;
98
+ }
99
+ const last = typeof entry.t === 'number' && Number.isFinite(entry.t) ? entry.t : ulidTimeMs(entry.run_id);
100
+ if (last === null) entry.t = now;
101
+ else if (now - last > MAX_AGE_MS) delete store[session];
102
+ }
103
+ }
104
+
105
+ function sleepSync(ms) {
106
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
107
+ }
108
+
109
+ /**
110
+ * Read-modify-write the map under the lock, pruning on the way out. Each
111
+ * writer holds the lock for one read and one rename. A lock older than
112
+ * LOCK_STALE_MS was left by a hook that died mid-write and is broken. When the
113
+ * lock cannot be had within LOCK_WAIT_MS the update is skipped: a missed write
114
+ * is recoverable, clobbering another session's live entry is not.
115
+ */
116
+ function updateStore(mutate) {
117
+ try { mkdirSync(WYRM_DIR, { recursive: true }); } catch { return false; }
118
+ const token = `${process.pid}:${randomBytes(8).toString('hex')}`;
119
+ const deadline = Date.now() + LOCK_WAIT_MS;
120
+ for (;;) {
121
+ try {
122
+ const fd = openSync(LOCK, 'wx', 0o600);
123
+ try { writeSync(fd, token); } finally { closeSync(fd); }
124
+ break;
125
+ } catch (err) {
126
+ if (!err || err.code !== 'EEXIST') return false;
127
+ }
128
+ let stale = false;
129
+ try {
130
+ stale = Date.now() - statSync(LOCK).mtimeMs > LOCK_STALE_MS;
131
+ } catch (err) {
132
+ if (err && err.code === 'ENOENT') continue; // released meanwhile
133
+ }
134
+ if (stale) {
135
+ try { unlinkSync(LOCK); continue; } catch { /* wait like for any other holder */ }
136
+ }
137
+ if (Date.now() >= deadline) return false;
138
+ sleepSync(10 + Math.floor(Math.random() * 30));
139
+ }
61
140
  try {
62
- mkdirSync(WYRM_DIR, { recursive: true });
63
- const tmp = `${STORE}.tmp.${process.pid}`;
64
- writeFileSync(tmp, JSON.stringify(obj), { mode: 0o600 });
65
- renameSync(tmp, STORE);
66
- } catch { /* best-effort — a memory hook never breaks the session */ }
141
+ const store = readStore();
142
+ const before = JSON.stringify(store);
143
+ mutate(store);
144
+ prune(store, Date.now());
145
+ if (JSON.stringify(store) !== before) writeStore(store);
146
+ return true;
147
+ } catch {
148
+ return false; // best-effort — a memory hook never breaks the session
149
+ } finally {
150
+ try { if (readFileSync(LOCK, 'utf8') === token) unlinkSync(LOCK); } catch { /* already gone */ }
151
+ }
67
152
  }
68
153
 
69
154
  // Portable, self-healing `wyrm` resolution: bare command first (honors PATH),
@@ -100,8 +185,21 @@ function slug(s) {
100
185
  .toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40);
101
186
  }
102
187
 
188
+ /**
189
+ * SessionStart sources that may open a run when this session has none mapped.
190
+ * `startup` (or no source, from older harnesses) is a new session. `clear`
191
+ * opens a new session id after SessionEnd closed the old run, and `resume`
192
+ * without a mapping is a chat whose run SessionEnd already closed: neither
193
+ * can orphan a run, because there is no live run to replace. `compact` fires
194
+ * mid-session and never starts one.
195
+ */
196
+ const RUN_OPENING_SOURCES = new Set(['', 'startup', 'clear', 'resume']);
197
+
103
198
  let payload = {};
104
199
  try { payload = JSON.parse(readFileSync(0, 'utf8') || '{}'); } catch { /* no/invalid stdin */ }
200
+ // JSON.parse('null') returns null without throwing; normalize so the reads
201
+ // below cannot throw outside the try and break the exit-0 contract.
202
+ if (!payload || typeof payload !== 'object') payload = {};
105
203
 
106
204
  const event = payload.hook_event_name || '';
107
205
  const sessionId = String(payload.session_id || '').slice(0, 200);
@@ -110,32 +208,45 @@ try {
110
208
  if (!sessionId) {
111
209
  // Can't map without a session id — nothing to do, but never error out.
112
210
  } else if (event === 'SessionStart') {
113
- const runId = wyrm(['run', 'start', '--orchestrator', 'claude-code', '--agent', 'claude-code']);
114
- if (runId) {
115
- const store = readStore();
116
- store[sessionId] = { run_id: runId, n: 0 };
117
- writeStore(store);
211
+ // SessionStart fires on resume and after every compaction too, with the
212
+ // same session id. Starting a run each time overwrote the mapping and left
213
+ // the previous run open forever (138 abandoned claude-code runs, 51 stale
214
+ // mappings on the store the 2026-09-13 audit read). A live mapping is
215
+ // reused whatever the source.
216
+ const source = typeof payload.source === 'string' ? payload.source : '';
217
+ const existing = readStore()[sessionId];
218
+ let runId = '';
219
+ if (!(existing && existing.run_id) && RUN_OPENING_SOURCES.has(source)) {
220
+ runId = wyrm(['run', 'start', '--orchestrator', 'claude-code', '--agent', 'claude-code']);
118
221
  }
222
+ // Re-read under the lock: the run start took time. This write also prunes.
223
+ updateStore((store) => {
224
+ const entry = store[sessionId];
225
+ if (entry && entry.run_id) entry.t = Date.now();
226
+ else if (runId) store[sessionId] = { run_id: runId, n: 0, t: Date.now() };
227
+ });
119
228
  } else if (event === 'PreToolUse' && payload.tool_name === 'Task') {
120
229
  // A Task spawn == fleet fan-out: register the subagent on the run.
121
- const store = readStore();
122
- const entry = store[sessionId];
123
- if (entry && entry.run_id) {
124
- const ti = payload.tool_input || {};
125
- const base = slug(ti.subagent_type) || slug(ti.description) || 'task';
230
+ const ti = payload.tool_input || {};
231
+ const base = slug(ti.subagent_type) || slug(ti.description) || 'task';
232
+ let join = null;
233
+ updateStore((store) => {
234
+ const entry = store[sessionId];
235
+ if (!(entry && entry.run_id)) return;
126
236
  entry.n = (entry.n || 0) + 1;
127
- const agentId = `${base}-${entry.n}`;
128
- writeStore(store); // bump the counter before the (idempotent) join
129
- wyrm(['run', 'join', '--run', entry.run_id, '--agent', agentId, '--role', 'subagent']);
130
- }
237
+ entry.t = Date.now();
238
+ join = { runId: entry.run_id, agentId: `${base}-${entry.n}` };
239
+ });
240
+ // The counter is bumped before the (idempotent) join.
241
+ if (join) wyrm(['run', 'join', '--run', join.runId, '--agent', join.agentId, '--role', 'subagent']);
131
242
  } else if (event === 'SessionEnd' || event === 'Stop') {
132
- const store = readStore();
133
- const entry = store[sessionId];
134
- if (entry && entry.run_id) {
135
- wyrm(['run', 'end', '--run', entry.run_id]);
136
- delete store[sessionId];
137
- writeStore(store);
138
- }
243
+ const entry = readStore()[sessionId];
244
+ if (entry && entry.run_id) wyrm(['run', 'end', '--run', entry.run_id]);
245
+ // Drop the mapping that was ended, not one a later start put in its place.
246
+ updateStore((store) => {
247
+ const current = store[sessionId];
248
+ if (entry && current && current.run_id === entry.run_id) delete store[sessionId];
249
+ });
139
250
  }
140
251
  } catch { /* swallow everything — never block the harness */ }
141
252
 
@@ -28,6 +28,9 @@ import { join } from 'node:path';
28
28
  // inlined here rather than shared.
29
29
  const BRAND = process.env.WYRM_BRAND ?? '\u{f115d}';
30
30
 
31
+ /** Characters of brief this hook injects at SessionStart. */
32
+ const BRIEF_CHARS = 6000;
33
+
31
34
  // ── Portable, self-healing `wyrm` resolution ────────────────────────────────
32
35
  // Claude Code can spawn hooks with a minimal PATH (containers, CI, cron, non-
33
36
  // login shells), which would silently disable memory. Try the bare command
@@ -55,6 +58,99 @@ function runWyrm(args, opts) {
55
58
  return { status: 127, stdout: '', error: new Error('wyrm not found') };
56
59
  }
57
60
 
61
+ /**
62
+ * Why the rehydrate call failed, or '' when it ran. `wyrm rehydrate` exits 0
63
+ * on every miss by contract (no project, no session), so a non-zero exit, a
64
+ * missing binary or a spawn error is breakage: a corrupt or unreadable DB, a
65
+ * broken install. Those used to fall through to "first session here", which
66
+ * told the operator memory was empty when it was unreachable.
67
+ */
68
+ function failureReason(res) {
69
+ if (!res) return 'no result from the wyrm CLI';
70
+ if (res.status === 127) return 'wyrm CLI not found';
71
+ if (res.error) {
72
+ return res.error.code === 'ETIMEDOUT'
73
+ ? 'wyrm rehydrate timed out'
74
+ : `could not run wyrm (${res.error.code || res.error.message})`;
75
+ }
76
+ if (res.signal) return `wyrm rehydrate was killed (${res.signal})`;
77
+ if (res.status !== 0) {
78
+ const detail = lastErrorLine(res.stderr);
79
+ return `wyrm rehydrate exited ${res.status}${detail ? ` (${detail})` : ''}`;
80
+ }
81
+ return '';
82
+ }
83
+
84
+ /** The stderr line most likely to name the fault, clipped for a one-line receipt. */
85
+ function lastErrorLine(stderr) {
86
+ const lines = String(stderr || '')
87
+ .replace(/\x1b\[[0-9;]*m/g, '')
88
+ .split('\n')
89
+ .map((s) => s.trim())
90
+ .filter(Boolean);
91
+ const pick = [...lines].reverse().find((l) => /error|fail|cannot|unable|not a database|sqlite|corrupt|denied/i.test(l))
92
+ ?? lines[lines.length - 1]
93
+ ?? '';
94
+ return pick.length > 140 ? `${pick.slice(0, 137)}...` : pick;
95
+ }
96
+
97
+ // Section headings the brief renders (src/rehydration.ts) and the attached
98
+ // count each one backs.
99
+ const SECTIONS = [
100
+ ['## Ground truths', 'truths'],
101
+ ['## Unresolved failure patterns', 'failures'],
102
+ ['## Validated patterns', 'artifacts'],
103
+ ['## Open quests', 'quests'],
104
+ ];
105
+
106
+ /**
107
+ * Count the items actually present in the brief text. The CLI's --max-chars
108
+ * cut happens after the counts are computed, so on a large store the JSON
109
+ * `attached` described sections the reader never received (the receipt said
110
+ * 15 failure patterns over a brief that ended at the quest list). The text is
111
+ * what was delivered, so the receipt is built from the text. An item the cut
112
+ * lands inside was not delivered whole and is not counted.
113
+ */
114
+ function deliveredCounts(md) {
115
+ const counts = { truths: 0, failures: 0, artifacts: 0, quests: 0 };
116
+ const cutAt = md.search(/\n\n_\.\.\. brief truncated at \d+ chars/);
117
+ const body = cutAt >= 0 ? md.slice(0, cutAt) : md;
118
+ let current = null;
119
+ let last = null; // section of the most recent item
120
+ let closed = true; // has anything but that item's own continuation followed it?
121
+ for (const line of body.split('\n')) {
122
+ if (line.startsWith('## ')) {
123
+ const hit = SECTIONS.find(([prefix]) => line.startsWith(prefix));
124
+ current = hit ? hit[1] : null;
125
+ closed = true;
126
+ continue;
127
+ }
128
+ if (line === '---') { current = null; closed = true; continue; }
129
+ if (current && line.startsWith('- ') && !line.startsWith('- _')) {
130
+ counts[current]++;
131
+ last = current;
132
+ closed = false;
133
+ continue;
134
+ }
135
+ if (!/^\s{2,}\S/.test(line)) closed = true;
136
+ }
137
+ if (cutAt >= 0 && last && !closed) counts[last]--;
138
+ return counts;
139
+ }
140
+
141
+ // Mirrors src/rehydration.ts (isAutomatedRunId, stripInjectedPreamble). This
142
+ // plain .mjs hook cannot import src/, so the two small rules are restated;
143
+ // tests/hook-session-rehydrate.test.ts drives both through the recency block.
144
+ function isAutomatedRunId(runId) {
145
+ if (typeof runId !== 'string' || runId.length === 0) return false;
146
+ return /(?:^|[-.:])(?:cron|scheduled|maintenance)$/.test(runId.split('_')[0].toLowerCase());
147
+ }
148
+ const SKILL_PREAMBLE =
149
+ /\[IMPORTANT: The user has invoked the "[^"\n]*" skill[^\]]*(?:\]|$)(?:\s*---\r?\n[\s\S]*?(?:\r?\n---[ \t]*(?:\r?\n|$)|$))?/g;
150
+ function stripInjectedPreamble(text) {
151
+ return String(text || '').replace(SKILL_PREAMBLE, '').replace(/\n{3,}/g, '\n\n').trim();
152
+ }
153
+
58
154
  let payload = {};
59
155
  try { payload = JSON.parse(readFileSync(0, 'utf8') || '{}'); } catch { /* no/invalid stdin */ }
60
156
  // JSON.parse('null'|'true'|'42') returns a non-object without throwing, so the
@@ -83,36 +179,47 @@ try {
83
179
  } catch { /* older wyrm without `presence`, or announce failed — never break the session */ }
84
180
 
85
181
  let brief = '';
86
- let attached = null;
87
182
  let memories = 0;
183
+ let unavailable = '';
88
184
  try {
89
185
  // --quiet keeps the "nothing to restore" note off stderr; --path scopes to
90
- // this directory's project; --max-chars bounds the injection; --json gives
91
- // us the SAME attached counts the brief was built from (one rehydrate()
92
- // call, not two) so the receipt below can say how much was restored.
93
- const res = runWyrm(['rehydrate', '--path', cwd, '--quiet', '--max-chars', '6000', '--json'], {
186
+ // this directory's project; --max-chars bounds the injection; --json also
187
+ // reports `memories` so a cold start with memories on file reads honestly.
188
+ // WYRM_REHYDRATE_MAX_CHARS asks the brief builder to pack every section into
189
+ // the same budget, so the CLI's --max-chars cut never has to fall mid-brief
190
+ // (a CLI that predates it ignores it, and the cut stays the backstop).
191
+ const res = runWyrm(['rehydrate', '--path', cwd, '--quiet', '--max-chars', String(BRIEF_CHARS), '--json'], {
94
192
  timeout: 15000,
95
193
  encoding: 'utf8',
194
+ env: { ...process.env, WYRM_REHYDRATE_MAX_CHARS: String(BRIEF_CHARS) },
96
195
  });
97
- try {
98
- const parsed = JSON.parse((res.stdout || '').trim() || '{}');
99
- brief = (parsed.brief || '').trim();
100
- attached = parsed.attached || null;
101
- memories = typeof parsed.memories === 'number' ? parsed.memories : 0;
102
- } catch { brief = (res.stdout || '').trim(); } // old CLI on PATH (pre --json): degrade gracefully
103
- } catch { /* wyrm not on PATH or rehydrate failed: never break the session */ }
104
-
105
- const restored = attached ? (attached.quests + attached.truths + attached.artifacts + attached.failures) : 0;
196
+ unavailable = failureReason(res);
197
+ if (!unavailable) {
198
+ try {
199
+ const parsed = JSON.parse((res.stdout || '').trim() || '{}');
200
+ brief = (parsed.brief || '').trim();
201
+ memories = typeof parsed.memories === 'number' ? parsed.memories : 0;
202
+ } catch { brief = (res.stdout || '').trim(); } // old CLI on PATH (pre --json): degrade gracefully
203
+ }
204
+ } catch (err) {
205
+ unavailable = `could not run wyrm (${err?.message || 'unknown error'})`;
206
+ }
207
+
208
+ const got = brief ? deliveredCounts(brief) : null;
209
+ const restored = got ? got.quests + got.truths + got.artifacts + got.failures : 0;
106
210
  // Cold-start honesty (live-test finding #7): a project can have memories on
107
211
  // file with no PRIOR SESSION to restore (fresh project, or sessions never
108
212
  // logged there) — that used to read as "first session here", which is false
109
213
  // the moment memories > 0. Only a truly empty project gets the first-session
110
- // copy; a memory-bearing cold start says so instead.
111
- const receipt = brief
112
- ? `${BRAND} Wyrm restored ${restored} memories (${attached ? `${attached.truths} truths · ${attached.quests} quests · ${attached.artifacts} lessons · ${attached.failures} failure patterns` : 'summary attached'}). Auto-capture is on.`
113
- : memories > 0
114
- ? `${BRAND} Wyrm: ${memories} memories on file. No previous session to restore. Auto-capture is on.`
115
- : `${BRAND} Wyrm: first session here. Nothing to restore yet. Auto-capture is on.`;
214
+ // copy; a memory-bearing cold start says so instead. An unreachable Wyrm says
215
+ // that, and claims nothing about what memory holds.
216
+ const receipt = unavailable
217
+ ? `${BRAND} Wyrm unavailable: ${unavailable}. Nothing was restored.`
218
+ : brief
219
+ ? `${BRAND} Wyrm restored ${restored} memories (${got.truths} truths · ${got.quests} quests · ${got.artifacts} lessons · ${got.failures} failure patterns). Auto-capture is on.`
220
+ : memories > 0
221
+ ? `${BRAND} Wyrm: ${memories} memories on file. No previous session to restore. Auto-capture is on.`
222
+ : `${BRAND} Wyrm: first session here. Nothing to restore yet. Auto-capture is on.`;
116
223
 
117
224
  // The brief above is scoped to THIS directory's project, but sessions are
118
225
  // logged under whatever project their cwd mapped to at SessionEnd — so work
@@ -130,17 +237,28 @@ try {
130
237
  // ~/.wyrm/wyrm.db) so this recency query reads the same store that produced
131
238
  // the brief (crucible #16). Skip the whole block when we have no briefId.
132
239
  const dbPath = process.env.WYRM_DB_PATH || `${process.env.HOME}/.wyrm/wyrm.db`;
240
+ // Objectives come back with newlines folded to U+001F (restored below) so a
241
+ // multi-line objective cannot split a row, and with enough length to strip
242
+ // an injected skill preamble before clipping. Automated runs are fetched and
243
+ // dropped here: cron maintenance sessions are always the newest rows.
133
244
  const q = briefId ? spawnSync('sqlite3', [
134
245
  '-separator', '\t',
135
246
  dbPath,
136
- `SELECT s.id, p.name, s.date, replace(substr(coalesce(s.objectives,''),1,110), char(10), ' ')
247
+ `SELECT s.id, p.name, s.date, coalesce(s.run_id,''),
248
+ replace(replace(substr(coalesce(s.objectives,''),1,600), char(9), ' '), char(10), char(31))
137
249
  FROM sessions s JOIN projects p ON p.id = s.project_id
138
250
  WHERE s.is_archived = 0 AND s.id > ${briefId}
139
- ORDER BY s.id DESC LIMIT 4`,
251
+ ORDER BY s.id DESC LIMIT 16`,
140
252
  ], { timeout: 10000, encoding: 'utf8' }) : { stdout: '' };
141
- const rows = (q.stdout || '').trim().split('\n').filter(Boolean).map((l) => l.split('\t'));
253
+ const rows = (q.stdout || '').trim().split('\n').filter(Boolean)
254
+ .map((l) => l.split('\t'))
255
+ .filter(([, , , runId]) => !isAutomatedRunId(runId))
256
+ .slice(0, 4);
142
257
  if (briefId && rows.length) {
143
- const lines = rows.map(([id, name, date, obj]) => `- #${id} · ${name} · ${date} — ${obj}`);
258
+ const lines = rows.map(([id, name, date, , obj]) => {
259
+ const text = stripInjectedPreamble(String(obj || '').replace(/\x1f/g, '\n')).replace(/\s+/g, ' ').slice(0, 110);
260
+ return `- #${id} · ${name} · ${date} — ${text}`;
261
+ });
144
262
  brief += `\n\n## Newer sessions since this brief (other projects, machine-wide)\n${lines.join('\n')}\n_This project's own brief is #${briefId}; the sessions above are more recent. Query \`wyrm show session:<id>\` if one looks relevant._`;
145
263
  }
146
264
  } catch { /* sqlite3 missing or query failed — the plain brief is still good */ }