mirror-mind 0.33.4 → 0.34.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.
@@ -460,6 +460,42 @@ export const RETIRED: readonly RetiredSurface[] = [
460
460
  // exploration's record is `docs/project/exploration/es-004-*.md`.
461
461
  exemptions: {},
462
462
  },
463
+ {
464
+ surfaceId: "codex-wrapper",
465
+ story: "CV21.DS4.TS5",
466
+ // The v0.32.1 Codex wiring: a wrapper script around the `codex` command,
467
+ // its two generated hooks, the `codex:*` hook family, and the JSONL
468
+ // backfill the wrapper drove at exit. Retired once US4 measured Codex at
469
+ // L4 through the shipped plugin, live: the plugin's Claude-family hooks
470
+ // log Codex turns as they happen, so nothing re-imports the transcript.
471
+ // The backfill's only caller was the wrapper's session-end hook, and the
472
+ // plugin's SessionEnd closes the session without reading it -- the
473
+ // condition DS4 set for keeping it was not met.
474
+ absentPaths: [
475
+ "scripts/codex-mirror.sh",
476
+ "scripts/codex-hooks/",
477
+ "ts/src/hooks/codex.ts",
478
+ "scripts/smoke_codex.sh",
479
+ "ts/test/fixtures/backfill/codex/",
480
+ ],
481
+ // File and route names, never vocabulary: "codex" is a living word (the
482
+ // plugin serves Codex; `runtimeDetection.ts` labels its payloads).
483
+ forbiddenPatterns: [
484
+ "codex-mirror\\.sh",
485
+ "codex-hooks",
486
+ "codex:session-(start|end)",
487
+ "backfill-codex-session",
488
+ "backfill_codex_session",
489
+ "backfillCodexSession",
490
+ "smoke_codex",
491
+ ],
492
+ exemptions: {
493
+ "docs/getting-started.md":
494
+ "the un-wiring guidance: a user who started codex through the retired wrapper needs its name to undo that wiring",
495
+ "ts/src/conversation/backfill.ts":
496
+ "the header names the retired importer to say where it went, beside the Pi importer that stays",
497
+ },
498
+ },
463
499
  {
464
500
  // Not a deleted surface: a retired IDIOM. A URL's pathname is not a
465
501
  // filesystem path -- it percent-encodes `Código` and `John Doe`, and on
@@ -87,9 +87,21 @@ export async function claudeStop(stdin: string): Promise<number> {
87
87
  return 0;
88
88
  }
89
89
 
90
- /** `log-session-end.sh`: close the session, then take the silent backup. */
91
- export async function claudeSessionEnd(): Promise<number> {
92
- await runFrontDoorQuietly("claude:session-end", ["conversation-logger", "session-end"]);
90
+ /**
91
+ * `log-session-end.sh`: close the session, then take the silent backup.
92
+ *
93
+ * The runtime goes along as `--interface`, as Stop's does, for a session row
94
+ * with no label. On a runtime that bounds this hook (Codex 1 s, Grok 1.5 s)
95
+ * the close runs no LLM work and the next session start finishes the tail
96
+ * (CV21.DS4.TS2); both calls then fit inside the bound.
97
+ */
98
+ export async function claudeSessionEnd(stdin: string): Promise<number> {
99
+ const runtime = detectHookRuntime(parseHookPayload(stdin).raw);
100
+ await runFrontDoorQuietly(
101
+ "claude:session-end",
102
+ ["conversation-logger", "session-end", "--interface", runtime],
103
+ { stdin },
104
+ );
93
105
  await runFrontDoorQuietly("claude:session-end", ["backup", "--silent"]);
94
106
  return 0;
95
107
  }
@@ -204,7 +216,7 @@ export async function claudeHook(name: string): Promise<number> {
204
216
  case "stop":
205
217
  return claudeStop(readStdin());
206
218
  case "session-end":
207
- return claudeSessionEnd();
219
+ return claudeSessionEnd(readStdin());
208
220
  case "inject":
209
221
  return claudeInject(readStdin());
210
222
  default:
@@ -14,6 +14,7 @@
14
14
  // `GEMINI_SESSION_ID` still wins over the payload's `session_id`, because the
15
15
  // runtime sets it and the payload is the fallback.
16
16
 
17
+ import { isCommandTurn } from "#conversation/commandTurn.ts";
17
18
  import { parseHookPayload } from "./payload.ts";
18
19
  import {
19
20
  operatingInstructionsFor,
@@ -37,7 +38,8 @@ export async function geminiLogUser(stdin: string): Promise<number> {
37
38
  const payload = parseHookPayload(stdin);
38
39
  const sessionId = sessionIdFrom(payload.sessionId);
39
40
 
40
- if (payload.prompt.startsWith("/")) {
41
+ // The same rule as the Claude-family logger's (CV21.DS4.TS3): one home.
42
+ if (isCommandTurn(payload.prompt)) {
41
43
  process.stdout.write("{}\n");
42
44
  return 0;
43
45
  }
@@ -8,8 +8,10 @@
8
8
  //
9
9
  // node ts/src/hooks/main.ts claude:inject
10
10
  //
11
- // Arguments after the name are the hook's own; only the Codex wrapper passes
12
- // any, since Codex has no hook payload to read (`codex.ts`).
11
+ // Arguments after the name are the hook's own; every current hook reads its
12
+ // payload from stdin and passes none. (The Codex wrapper's `codex:*` entries
13
+ // were the exception, until CV21.DS4.TS5 retired them with the wrapper: the
14
+ // plugin's Claude-family hooks are the Codex path now.)
13
15
  //
14
16
  // One entry rather than one file per hook because the generated wrappers then
15
17
  // differ only in the hook name and their depth, and `hooks.test.ts` asserts
@@ -34,7 +36,6 @@
34
36
  import { pathToFileURL } from "node:url";
35
37
  import { loadConfiguration, silenceExperimentalWarnings } from "#runtime/config.ts";
36
38
  import { claudeHook } from "./claude.ts";
37
- import { codexSessionEnd, codexSessionStart } from "./codex.ts";
38
39
  import {
39
40
  geminiLogAssistant,
40
41
  geminiLogUser,
@@ -44,7 +45,7 @@ import {
44
45
  import { readStdin } from "./payload.ts";
45
46
  import { noteHookFailure } from "./runtime.ts";
46
47
 
47
- async function dispatch(name: string, args: readonly string[]): Promise<number> {
48
+ async function dispatch(name: string): Promise<number> {
48
49
  const [runtime, hook] = name.split(":");
49
50
 
50
51
  switch (runtime) {
@@ -64,17 +65,6 @@ async function dispatch(name: string, args: readonly string[]): Promise<number>
64
65
  break;
65
66
  }
66
67
  break;
67
- case "codex":
68
- // Called by `scripts/codex-mirror.sh` through its generated wrappers.
69
- switch (hook) {
70
- case "session-start":
71
- return codexSessionStart();
72
- case "session-end":
73
- return codexSessionEnd(args[0] ?? "", args[1] ?? "");
74
- default:
75
- break;
76
- }
77
- break;
78
68
  default:
79
69
  break;
80
70
  }
@@ -94,7 +84,7 @@ export async function runAsEntry(rawArgv = process.argv.slice(2)): Promise<numbe
94
84
  loadConfiguration({ entryPath: import.meta.filename });
95
85
  const name = rawArgv[0] ?? "";
96
86
  try {
97
- return await dispatch(name, rawArgv.slice(1));
87
+ return await dispatch(name);
98
88
  } catch (error) {
99
89
  // The last line of defense. A hook that throws must still not break the
100
90
  // turn, and must still leave a trace that it happened.
@@ -120,6 +120,17 @@ export function resolveMaintenanceMaxExtractions(options: ModelPinOptions = {}):
120
120
  return parsePythonInt(env.MEMORY_MAINTENANCE_MAX_EXTRACTIONS, 10);
121
121
  }
122
122
 
123
+ /**
124
+ * `MIRROR_STALE_ORPHAN_MINUTES` (CV21.DS4.US4): how long an open conversation
125
+ * may sit idle before session maintenance closes it as an orphan. On a runtime
126
+ * whose session outlives the TUI (Codex 0.163.0) this is the close path, so an
127
+ * operator may shorten it; a route sets it to 0 to prove the close now.
128
+ */
129
+ export function resolveStaleOrphanMinutes(options: ModelPinOptions = {}): number {
130
+ const env = options.env ?? process.env;
131
+ return parsePythonInt(env.MIRROR_STALE_ORPHAN_MINUTES, 30);
132
+ }
133
+
123
134
  /** Python `int(os.getenv("MEMORY_EXTRACTION_MAX_ATTEMPTS", "3"))` (CV9.E2.S7). */
124
135
  export function resolveExtractionMaxAttempts(options: ModelPinOptions = {}): number {
125
136
  const env = options.env ?? process.env;
@@ -31,7 +31,13 @@ import { identityKeyBreaksGrammar, SLUG_KEYED_LAYERS } from "#identity/identityK
31
31
  import { pyRepr, sortByCodePoint } from "#util/pythonText.ts";
32
32
  import { configFilePath } from "./config.ts";
33
33
  import type { GitWorktreeEntry } from "./git.ts";
34
+ import {
35
+ claudePluginLinkState,
36
+ codexPluginCacheState,
37
+ installedPluginVersion,
38
+ } from "./pluginWiring.ts";
34
39
  import type { RuntimeStatusReport } from "./status.ts";
40
+ import { CODEX_PLUGIN_ADD_COMMAND } from "./wiring.ts";
35
41
 
36
42
  export interface DriftFinding {
37
43
  code: string;
@@ -114,7 +120,7 @@ export function rootStateFindings(homesRoot: string): DriftFinding[] {
114
120
  detail: path,
115
121
  recommendation:
116
122
  "relocate into the owning mirror home " +
117
- "(see REFERENCE.md \u2014 Relocating legacy root runtime state)",
123
+ "(see REFERENCE.md — Relocating legacy root runtime state)",
118
124
  repair_route: "manual relocation",
119
125
  }));
120
126
  }
@@ -319,6 +325,60 @@ export function ftsConsistencyFindings(report: RuntimeStatusReport): DriftFindin
319
325
  return [];
320
326
  }
321
327
 
328
+ /** A deferred close tail waits for a session start; after this long, nobody started one. */
329
+ const DEFERRED_CLOSE_TAIL_STALE_MS = 24 * 60 * 60 * 1000;
330
+
331
+ /**
332
+ * CV21.DS4.TS2: a runtime that bounds its SessionEnd hook (Codex, Grok) closes
333
+ * without the LLM tail and flags the conversation for the next session start to
334
+ * finish. A user whose last session was on such a runtime, and who starts no
335
+ * session for a day, has memories and titles waiting and nothing saying so:
336
+ * this is the one place that says so. Younger flags are the normal state
337
+ * between two sessions, not a finding.
338
+ */
339
+ export function deferredCloseTailFindings(
340
+ report: Pick<RuntimeStatusReport, "db_path" | "db_exists">,
341
+ now: Date = new Date(),
342
+ ): DriftFinding[] {
343
+ if (report.db_path === null || !report.db_exists) return [];
344
+ let row: { n: number; oldest: string } | null;
345
+ try {
346
+ const db = openDatabaseReadOnly(report.db_path);
347
+ try {
348
+ const found = db
349
+ .prepare(
350
+ `SELECT COUNT(*) AS n, MIN(ended_at) AS oldest FROM conversations
351
+ WHERE ended_at IS NOT NULL
352
+ AND json_extract(metadata, '$.close_tail_pending') IS 1`,
353
+ )
354
+ .get();
355
+ row =
356
+ found && Number(found.n) > 0 ? { n: Number(found.n), oldest: String(found.oldest) } : null;
357
+ } finally {
358
+ db.close();
359
+ }
360
+ } catch {
361
+ return [];
362
+ }
363
+ if (row === null) return [];
364
+ const oldest = Date.parse(row.oldest);
365
+ if (Number.isNaN(oldest) || now.getTime() - oldest < DEFERRED_CLOSE_TAIL_STALE_MS) return [];
366
+ return [
367
+ {
368
+ code: "deferred_close_tails_waiting",
369
+ severity: "attention",
370
+ subject: "conversations",
371
+ detail:
372
+ `${row.n} conversation(s) closed by a runtime that defers the close tail are waiting ` +
373
+ `for a session start to finish it; the oldest ended ${row.oldest}`,
374
+ recommendation:
375
+ "start a session on any runtime: its maintenance extracts and finalizes them, " +
376
+ "five per start",
377
+ repair_route: "session start",
378
+ },
379
+ ];
380
+ }
381
+
322
382
  export interface DiagnoseOptions {
323
383
  /** Injected only so the 24h boundary is testable; production passes none. */
324
384
  now?: Date;
@@ -340,6 +400,7 @@ export function diagnoseRuntime(
340
400
  findings.push(...frontDoorErrorFindings(report, options.now));
341
401
  findings.push(...ftsConsistencyFindings(report));
342
402
  findings.push(...identityKeyFindings(report));
403
+ findings.push(...deferredCloseTailFindings(report, options.now));
343
404
 
344
405
  if (report.mirror_home_error) {
345
406
  findings.push({
@@ -442,6 +503,59 @@ export function diagnoseRuntime(
442
503
  return findings;
443
504
  }
444
505
 
506
+ /**
507
+ * The plugin wiring findings (CV21.DS4.TS6; the debt US1 carried). Codex
508
+ * copies the plugin into a versioned cache, so an npm update leaves it
509
+ * behind; Claude Code links it in place, so its failure mode is a dangling
510
+ * link. Absence is not drift: no cache and no link fire nothing, so an
511
+ * unwired machine stays green.
512
+ *
513
+ * The defaulting happens HERE, from the env the caller hands in — CODEX_HOME
514
+ * else ~/.codex, and ~/.claude — never inside the readers, so every reader
515
+ * test is hermetic on a maintainer's machine with real wiring
516
+ * (CR123/128/137/142).
517
+ */
518
+ export function pluginWiringFindings(
519
+ installRoot: string | null,
520
+ env: NodeJS.ProcessEnv,
521
+ ): DriftFinding[] {
522
+ const findings: DriftFinding[] = [];
523
+ const home = env.HOME?.trim() || null;
524
+
525
+ const codexHome = env.CODEX_HOME?.trim() || (home ? join(home, ".codex") : null);
526
+ const installedVersion = installRoot ? installedPluginVersion(installRoot) : null;
527
+ if (codexHome && installedVersion) {
528
+ const cache = codexPluginCacheState(codexHome, installedVersion);
529
+ if (cache.state === "behind") {
530
+ findings.push({
531
+ code: "codex_plugin_cache_behind",
532
+ severity: "warning",
533
+ subject: cache.cachePath,
534
+ detail: `cached ${cache.newestCached} < installed ${installedVersion}; Codex runs the copy it cached at install`,
535
+ recommendation: `run \`${CODEX_PLUGIN_ADD_COMMAND}\` to bring the cached plugin level (Codex has no plugin-update verb; re-adding refreshes the cache)`,
536
+ repair_route: CODEX_PLUGIN_ADD_COMMAND,
537
+ });
538
+ }
539
+ }
540
+
541
+ if (home) {
542
+ const link = claudePluginLinkState(join(home, ".claude"));
543
+ if (link.state === "dangling") {
544
+ findings.push({
545
+ code: "claude_plugin_link_dangling",
546
+ severity: "warning",
547
+ subject: link.linkPath,
548
+ detail: `the link points at ${link.target ?? "an unreadable target"}, which cannot be read`,
549
+ recommendation:
550
+ 'relink it — `ln -s "<pkg>/plugins/mirror-mind" ~/.claude/skills/mirror-mind` — or remove it if Claude Code is no longer wired',
551
+ repair_route: "relink or remove",
552
+ });
553
+ }
554
+ }
555
+
556
+ return findings;
557
+ }
558
+
445
559
  /** The catalog read `probeModelPins` needs. DS5 replay only until DS8. */
446
560
  export interface ModelCatalogProvider {
447
561
  listAvailableModels(): Promise<Set<string>>;
@@ -0,0 +1,135 @@
1
+ // The plugin wiring readers (CV21.DS4.TS6).
2
+ //
3
+ // Two runtimes hold the plugin outside the install tree. Codex copies it into
4
+ // a versioned cache (`$CODEX_HOME/plugins/cache/mirror-mind/mirror-mind/
5
+ // <version>`; CV21.DS4.US1), so an npm update changes the install but not
6
+ // that copy — the one wiring that goes stale. Claude Code links the plugin in
7
+ // place (`~/.claude/skills/mirror-mind`), so its failure mode is a dangling
8
+ // link, not a stale copy.
9
+ //
10
+ // Both readers take their roots as ARGUMENTS, always. The defaulting —
11
+ // `$CODEX_HOME` else `~/.codex`, and the Claude home — happens once, at the
12
+ // diagnose entry, from the env the caller already carries, never in here.
13
+ // That is the CR123/128/137/142 lesson: a maintainer's machine has a real
14
+ // ~/.codex and a real ~/.claude, and a reader that consults the environment
15
+ // makes every fixture test machine-dependent exactly where maintainers work.
16
+ //
17
+ // Nothing here runs `codex` or mutates anything: Mirror reads directories and
18
+ // prints a command for the person to run. On the installed Codex 0.163.0,
19
+ // `codex plugin` has no update verb (add, list, marketplace, remove), so the
20
+ // level-up command is the re-add — `CODEX_PLUGIN_ADD_COMMAND`, the same
21
+ // constant `mirror init`'s wiring lines print (the CR071 lesson at the
22
+ // string level).
23
+
24
+ import { lstatSync, readdirSync, readFileSync, readlinkSync, statSync } from "node:fs";
25
+ import { join } from "node:path";
26
+ import { compareSemver, parseSemver } from "#util/semver.ts";
27
+
28
+ /** Where Codex keeps its copy, below a Codex home. */
29
+ export const CODEX_PLUGIN_CACHE_SEGMENTS: readonly string[] = [
30
+ "plugins",
31
+ "cache",
32
+ "mirror-mind",
33
+ "mirror-mind",
34
+ ];
35
+
36
+ export interface CodexCacheState {
37
+ /** `absent` covers no cache and a cache with no version-named entry. */
38
+ state: "absent" | "current" | "behind" | "ahead";
39
+ cachePath: string;
40
+ /** The newest version-named entry, by semver — never a string sort. */
41
+ newestCached: string | null;
42
+ }
43
+
44
+ /**
45
+ * Read the Codex plugin cache below `codexHome`, read-only. Entries whose
46
+ * names do not parse as versions (a partial download, an editor's leavings)
47
+ * are ignored; a cache holding only those claims nothing and reads as absent.
48
+ *
49
+ * `ahead` is a state, not a finding: `runtime update` refuses downgrades but
50
+ * `npm install -g mirror-mind@old` does not ask, and the person who
51
+ * downgraded on purpose needs no Codex advice from the older tree.
52
+ */
53
+ export function codexPluginCacheState(
54
+ codexHome: string,
55
+ installedVersion: string,
56
+ ): CodexCacheState {
57
+ const cachePath = join(codexHome, ...CODEX_PLUGIN_CACHE_SEGMENTS);
58
+ let entries: string[];
59
+ try {
60
+ entries = readdirSync(cachePath);
61
+ } catch {
62
+ return { state: "absent", cachePath, newestCached: null };
63
+ }
64
+ let newest: string | null = null;
65
+ for (const entry of entries) {
66
+ if (parseSemver(entry)[0] < 0) continue;
67
+ try {
68
+ if (!statSync(join(cachePath, entry)).isDirectory()) continue;
69
+ } catch {
70
+ continue;
71
+ }
72
+ if (newest === null || compareSemver(entry, newest) > 0) newest = entry;
73
+ }
74
+ if (newest === null) return { state: "absent", cachePath, newestCached: null };
75
+ const order = compareSemver(newest, installedVersion);
76
+ const state = order < 0 ? "behind" : order > 0 ? "ahead" : "current";
77
+ return { state, cachePath, newestCached: newest };
78
+ }
79
+
80
+ export interface ClaudeLinkState {
81
+ /** `healthy` means the target reads — including a plain directory copy. */
82
+ state: "absent" | "healthy" | "dangling";
83
+ linkPath: string;
84
+ /** The link's own target when it is a symlink, else null. */
85
+ target: string | null;
86
+ }
87
+
88
+ /**
89
+ * Read the Claude Code wiring below `claudeHome`. Healthy means the target
90
+ * reads; a link that resolves to *another* install tree is deliberately
91
+ * healthy too (TS6's documented silence) — chasing where it points is a
92
+ * one-line amendment here if that case ever bites.
93
+ */
94
+ export function claudePluginLinkState(claudeHome: string): ClaudeLinkState {
95
+ const linkPath = join(claudeHome, "skills", "mirror-mind");
96
+ let isLink = false;
97
+ try {
98
+ isLink = lstatSync(linkPath).isSymbolicLink();
99
+ } catch {
100
+ return { state: "absent", linkPath, target: null };
101
+ }
102
+ const target = isLink ? readlinkSync(linkPath) : null;
103
+ try {
104
+ statSync(linkPath);
105
+ } catch {
106
+ return { state: "dangling", linkPath, target };
107
+ }
108
+ return { state: "healthy", linkPath, target };
109
+ }
110
+
111
+ /**
112
+ * The install tree's own plugin version, from the generated manifest.
113
+ * `plugins/mirror-mind/.claude-plugin/plugin.json` is written by
114
+ * `claudePlugin.ts` from `packageVersion()`, and the guard holds the
115
+ * committed manifest equal to the generated one — the file is the authority,
116
+ * not an assumption. Reading it FROM DISK is also what makes a post-update
117
+ * hint honest: the process that ran the update is the old version's code,
118
+ * but the tree it reads has already landed the new one.
119
+ */
120
+ export function installedPluginVersion(installRoot: string): string | null {
121
+ try {
122
+ const raw = readFileSync(
123
+ join(installRoot, "plugins", "mirror-mind", ".claude-plugin", "plugin.json"),
124
+ "utf8",
125
+ );
126
+ const parsed: unknown = JSON.parse(raw);
127
+ const version =
128
+ typeof parsed === "object" && parsed !== null
129
+ ? (parsed as Record<string, unknown>).version
130
+ : undefined;
131
+ return typeof version === "string" && version !== "" ? version : null;
132
+ } catch {
133
+ return null;
134
+ }
135
+ }
@@ -26,8 +26,10 @@
26
26
  // chosen once, below; no step asks which lane it is in.
27
27
 
28
28
  import { spawnSync } from "node:child_process";
29
+ import { join } from "node:path";
29
30
  import { verifyBackupArchive } from "#runtime/backup.ts";
30
31
  import type { InstallKind } from "#runtime/installKind.ts";
32
+ import { codexPluginCacheState, installedPluginVersion } from "#runtime/pluginWiring.ts";
31
33
  import { cloneStrategy, defaultGitRunner, type GitRunner } from "#runtime/strategies/clone.ts";
32
34
  import { defaultNpmRunner, type NpmRunner, packageStrategy } from "#runtime/strategies/package.ts";
33
35
  import type { statusAllowsUpdatePreflight } from "#runtime/updateGate.ts";
@@ -37,6 +39,7 @@ import {
37
39
  type UpdateResult,
38
40
  type UpdateStage,
39
41
  } from "#runtime/updatePipeline.ts";
42
+ import { CODEX_PLUGIN_ADD_COMMAND } from "#runtime/wiring.ts";
40
43
  import { commandOnPath } from "#util/paths.ts";
41
44
  import { PROGRAM } from "#util/program.ts";
42
45
  import { shellWord } from "#util/shellWord.ts";
@@ -405,12 +408,42 @@ export function postUpdateHints(
405
408
  env: NodeJS.ProcessEnv,
406
409
  canExecute?: (path: string) => boolean,
407
410
  ): string[] {
408
- if (install.kind !== "clone" || !result.success) return [];
409
- if (commandOnPath(PROGRAM, env, canExecute) !== null) return [];
410
- // A command the person will paste: the path is one shell word (CR104).
411
- return [
412
- `\`${PROGRAM}\` is not on the PATH: run \`npm link\` once in ${shellWord(install.repository)}, so the skills can call it.`,
413
- ];
411
+ if (!result.success) return [];
412
+ const hints: string[] = [];
413
+
414
+ if (install.kind === "clone" && commandOnPath(PROGRAM, env, canExecute) === null) {
415
+ // A command the person will paste: the path is one shell word (CR104).
416
+ hints.push(
417
+ `\`${PROGRAM}\` is not on the PATH: run \`npm link\` once in ${shellWord(install.repository)}, so the skills can call it.`,
418
+ );
419
+ }
420
+
421
+ // CV21.DS4.TS6: Codex runs the plugin copy it cached at install, so the
422
+ // update that just landed did not reach it. The version authority is the
423
+ // LANDED version, read from the just-updated tree's plugin.json -- this
424
+ // process is the old version's code, and its own constant would read a
425
+ // just-staled cache as current.
426
+ const installRoot =
427
+ install.kind === "clone"
428
+ ? install.repository
429
+ : install.kind === "package"
430
+ ? install.root
431
+ : null;
432
+ const home = env.HOME?.trim() || null;
433
+ const codexHome = env.CODEX_HOME?.trim() || (home ? join(home, ".codex") : null);
434
+ if (installRoot && codexHome) {
435
+ const landed = installedPluginVersion(installRoot);
436
+ if (landed) {
437
+ const cache = codexPluginCacheState(codexHome, landed);
438
+ if (cache.state === "behind") {
439
+ hints.push(
440
+ `Codex's cached plugin is behind the update (${cache.newestCached} < ${landed}): run \`${CODEX_PLUGIN_ADD_COMMAND}\` to bring it level.`,
441
+ );
442
+ }
443
+ }
444
+ }
445
+
446
+ return hints;
414
447
  }
415
448
 
416
449
  function firstLine(text: string): string {
@@ -23,17 +23,31 @@
23
23
  // and hooks live in `~/.gemini/settings.json`, absolute paths.
24
24
  // Two steps. The Operating Instructions arrive through the
25
25
  // SessionStart hook (D13).
26
- // Codex `~/.codex/skills/<dir>` is discovered recursively, and
27
- // `~/.codex/AGENTS.md` is the global instructions file
28
- // (`codex debug prompt-input`, 0.157.0). Two steps, and the
29
- // session is run through the shipped wrapper, since Codex has
30
- // no hooks this integration uses.
26
+ // Codex `codex plugin marketplace add <root>` reads the package's
27
+ // `.agents/plugins/marketplace.json`, and `codex plugin add
28
+ // mirror-mind@mirror-mind` copies the plugin into Codex's cache
29
+ // with its skills, hooks, and MCP server (0.162.1, CV21.DS12.TS2
30
+ // static 5-7; CV21.DS4.US1). Two steps. Codex asks once, at the
31
+ // next session, to trust the plugin's hooks (L1); the Operating
32
+ // Instructions then arrive through its SessionStart hook as a
33
+ // developer message (L4). Until DS4.US1 the two steps were a
34
+ // skills link and an AGENTS.md link, with sessions run through
35
+ // the shipped wrapper.
31
36
 
32
37
  import { join } from "node:path";
33
38
  import { commandOnPath } from "#util/paths.ts";
34
39
 
35
40
  export type RuntimeName = "pi" | "claude" | "gemini" | "codex";
36
41
 
42
+ /**
43
+ * The one Codex level-up command (CV21.DS4.TS6). Codex 0.163.0 has no
44
+ * plugin-update verb, so re-adding is how a cached plugin reaches the
45
+ * installed version. One constant so the wiring line `mirror init` prints
46
+ * and the recommendation `runtime diagnose` prints cannot disagree (the
47
+ * CR071 lesson at the string level).
48
+ */
49
+ export const CODEX_PLUGIN_ADD_COMMAND = "codex plugin add mirror-mind@mirror-mind";
50
+
37
51
  export interface RuntimeWiring {
38
52
  /** The runtime, as a person names it. */
39
53
  readonly title: string;
@@ -94,11 +108,11 @@ export const RUNTIME_WIRING: Readonly<Record<RuntimeName, RuntimeWiring>> = {
94
108
  title: "Codex",
95
109
  command: "codex",
96
110
  steps: [
97
- (root) => [`ln -s "${join(root, ".pi/skills")}" ~/.codex/skills/mirror-mind`],
98
- (root) => [
99
- `ln -s "${join(root, "AGENTS.md")}" ~/.codex/AGENTS.md`,
100
- "(or append that file to the ~/.codex/AGENTS.md you already have)",
101
- `then start Codex through "${join(root, "scripts/codex-mirror.sh")}" instead of codex`,
111
+ (root) => [`codex plugin marketplace add "${root}"`],
112
+ () => [
113
+ CODEX_PLUGIN_ADD_COMMAND,
114
+ "(Codex asks once, at the next session, to trust the plugin's hooks; the plugin",
115
+ "then loads every session: its skills, the hooks, and the MCP server)",
102
116
  ],
103
117
  ],
104
118
  },
@@ -1,85 +0,0 @@
1
- #!/usr/bin/env bash
2
- # Mirror Mind hook wrapper — GENERATED by scripts/generate_hook_wrappers.sh.
3
- # Edit the generator, never this file: every wrapper shares these bytes and
4
- # differs only in the hook name and in how it finds the Mirror entry
5
- # (CV22.DS10.TS5 decision D4; CV22.DS10.US3 decision D5).
6
- set -uo pipefail
7
- HOOK="codex:session-end"
8
-
9
- # Resolve the tree from THIS FILE, never from the cwd: a runtime spawns hooks
10
- # from whatever directory the session is in. The tree is a checkout or the
11
- # installed package; the wrapper's depth to its root is the same in both.
12
- HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
13
- REPO_ROOT="$(cd "$HERE/../.." && pwd -P)"
14
-
15
- # A hook never fails the user's turn, and never fails in silence: when it
16
- # cannot do its job it appends ONE line to <mirror home>/hooks.log and exits 0.
17
- # The home is found the way the core finds it -- MIRROR_HOME, else
18
- # MIRROR_USER -- from the environment when set there, else from the tree's
19
- # .env when the wrapper is in a tree, else from the user's config file
20
- # (~/.config/mirror/env), in the core's order (US3, D3). A GUI launch carries
21
- # neither variable, and the first wrappers then wrote to a home nobody reads.
22
- env_file_value() {
23
- [ -f "$2" ] || return 0
24
- sed -n -E "s/^[[:space:]]*(export[[:space:]]+)?$1[[:space:]]*=[[:space:]]*//p" "$2" \
25
- | tail -n 1 | tr -d "\"'\r"
26
- }
27
- env_value() {
28
- local value=""
29
- if [ -n "${!1+set}" ]; then printf '%s' "${!1}"; return; fi
30
- [ -z "$REPO_ROOT" ] || value="$(env_file_value "$1" "$REPO_ROOT/.env")"
31
- [ -n "$value" ] || value="$(env_file_value "$1" "${XDG_CONFIG_HOME:-$HOME/.config}/mirror/env")"
32
- printf '%s' "$value"
33
- }
34
- note() {
35
- local home user
36
- home="$(env_value MIRROR_HOME)"
37
- user="$(env_value MIRROR_USER)"
38
- if [ -n "$home" ]; then
39
- home="${home/#\~/$HOME}"
40
- elif [ -n "$user" ]; then
41
- home="$HOME/.mirror-minds/$user"
42
- [ -d "$home" ] || [ ! -d "$HOME/.mirror/$user" ] || home="$HOME/.mirror/$user"
43
- else
44
- return 0
45
- fi
46
- mkdir -p "$home" 2>/dev/null \
47
- && printf '%s %s: %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$HOOK" "$1" >> "$home/hooks.log" 2>/dev/null
48
- }
49
-
50
- ENTRY="$REPO_ROOT/bin/mirror-hook.js"
51
-
52
- # Find Node. /usr/bin/python3 exists on every macOS; node usually lives under
53
- # nvm or Homebrew and is NOT on the PATH of a GUI-launched runtime. The Python
54
- # hooks could end in `|| true` because they always found their interpreter;
55
- # the same silence here would hide a new failure — no logging, no inject, no
56
- # close tail — that a user would meet weeks later as "Mirror stopped
57
- # remembering". So an unresolvable Node is RECORDED, never swallowed. The
58
- # directory the entry was found in is searched first: an npm global bin holds
59
- # the `node` that installed the package beside `mirror-hook`, while a system
60
- # `/usr/local/bin/node` can be years older (CI's Ubuntu runner has one).
61
- NODE="${MIRROR_NODE:-}"
62
- if [ -z "$NODE" ] || [ ! -x "$NODE" ]; then
63
- NODE="$(command -v node 2>/dev/null || true)"
64
- fi
65
- for candidate in "$(dirname "$ENTRY")/node" "$HOME/.nvm/current/bin/node" /opt/homebrew/bin/node /usr/local/bin/node; do
66
- [ -n "$NODE" ] && break
67
- [ -x "$candidate" ] && NODE="$candidate"
68
- done
69
-
70
- if [ -z "$NODE" ]; then
71
- note "node not found on PATH; hook skipped. Set MIRROR_NODE."
72
- exit 0
73
- fi
74
-
75
- # Not `exec`: the entry exits 0 whatever happens inside it, so a non-zero exit
76
- # means Node itself could not run the hook -- too old for the loader shim, or
77
- # it crashed. That used to vanish into a stderr no runtime shows (TS5 handoff
78
- # review, finding N1). No flags: the entry reads configuration and silences
79
- # its own warnings (US3, D3).
80
- "$NODE" "$ENTRY" "$HOOK" "$@"
81
- status=$?
82
- if [ "$status" -ne 0 ]; then
83
- note "node exited $status before the hook finished ($NODE, $("$NODE" --version 2>/dev/null || echo 'version unknown')); Mirror needs Node 24 or later. Set MIRROR_NODE."
84
- fi
85
- exit 0