File size: 21,075 Bytes
a861001
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import {
  mkdirSync,
  mkdtempSync,
  readFileSync,
  readdirSync,
  realpathSync,
  writeFileSync,
} from "node:fs";
import { homedir, tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import test from "node:test";
import { visibleWidth } from "@earendil-works/pi-tui";
import {
  createDefaultHarnessGenome,
  createHarnessGenome,
} from "../src/index.ts";
import { rsiHeaderLines, RsiEditor } from "../src/tui/rsih-tui.ts";
import {
  genomeAppearanceArgs,
  genomeActiveToolNames,
  genomeFooterStatus,
  parseCliArgs,
} from "../src/pi-cli-runtime.ts";
import {
  genomeResourceIsolationArgs,
  projectGenomeResources,
} from "../src/harness/pi-projection.ts";
import {
  expandGenomeShorthand,
  genomeShorthandReference,
} from "../src/cli/genome-shorthand.ts";

const codeDirectory = dirname(dirname(fileURLToPath(import.meta.url)));

function runCli(directory, args) {
  return spawnSync(
    process.execPath,
    [join(codeDirectory, "src", "cli.ts"), ...args],
    {
      cwd: codeDirectory,
      encoding: "utf8",
      env: {
        ...process.env,
        PI_OFFLINE: "1",
        PI_SKIP_VERSION_CHECK: "1",
        RSIH_CODING_AGENT_DIR: join(directory, ".rsih-agent"),
      },
    },
  );
}

/** Mirror of Pi's default session directory, which RSIH no longer overrides. */
function piSessionDir(directory) {
  const canonical = realpathSync(directory);
  const encoded = `--${canonical.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
  return join(directory, ".rsih-agent", "sessions", encoded);
}

function sessionEntries(sessionDirectory) {
  const files = readdirSync(sessionDirectory).filter((name) =>
    name.endsWith(".jsonl"),
  );
  assert.equal(files.length, 1);
  return readFileSync(join(sessionDirectory, files[0]), "utf8")
    .split(/\r?\n/)
    .filter(Boolean)
    .map((line) => JSON.parse(line));
}

test("CLI translates RSIH compatibility flags and preserves Pi flags", () => {
  assert.deepEqual(
    parseCliArgs([
      "-p",
      "Say ok.",
      "--run-id",
      "cli-args",
      "--profile",
      "test-provider",
      "--model",
      "test-model",
      "--json",
    ]),
    {
      cwd: ".",
      maxTurns: undefined,
      json: true,
      newSession: false,
      profile: "test-provider",
      piArgs: [
        "-p",
        "Say ok.",
        "--session-id",
        "cli-args",
        "--provider",
        "test-provider",
        "--model",
        "test-model",
        "--mode",
        "json",
      ],
    },
  );
});

test("Genome appearance translates to Pi theme flags without overriding CLI flags", () => {
  const genome = createHarnessGenome({
    appearance: { theme: "dark", no_themes: true },
  });
  assert.deepEqual(genomeAppearanceArgs(genome), [
    "--use-theme",
    "dark",
    "--no-themes",
  ]);
  assert.deepEqual(
    genomeAppearanceArgs(genome, ["--use-theme", "light", "--no-themes"]),
    [],
  );
});

test("Genome theme paths reach Pi through resource discovery", () => {
  const genome = createHarnessGenome({
    appearance: { themes: ["themes/coding.json"] },
    skills: [{ source: "./skills/review" }],
    prompt_templates: [
      { source: "./prompts" },
      { name: "plan", content: "Plan first." },
    ],
  });
  const projected = projectGenomeResources(genome, (path) =>
    `/tmp/project/${path.replace(/^\.\//, "")}`,
  );
  assert.deepEqual(projected.themePaths, ["/tmp/project/themes/coding.json"]);
  assert.deepEqual(projected.skillPaths, ["/tmp/project/skills/review"]);
  // Inline templates become commands instead of discovered files.
  assert.deepEqual(projected.promptPaths, ["/tmp/project/prompts"]);
});

test("resource isolation is opt-in and never hides context files", () => {
  assert.deepEqual(genomeResourceIsolationArgs(createHarnessGenome()), []);
  assert.deepEqual(
    genomeResourceIsolationArgs(
      createHarnessGenome({ resources: { isolate: true } }),
    ),
    ["--no-skills", "--no-prompt-templates", "--no-themes", "--no-extensions"],
  );
  assert.deepEqual(
    genomeResourceIsolationArgs(
      createHarnessGenome({ resources: { isolate: true } }),
      ["--no-skills"],
    ),
    ["--no-prompt-templates", "--no-themes", "--no-extensions"],
  );
});

test("Genome tools patch Pi's active set instead of replacing it", () => {
  const all = ["read", "ls", "bash", "load_skill", "mcp_search"];

  // A Genome with no tools opinion leaves Pi's selection untouched.
  assert.equal(
    genomeActiveToolNames(all, all, createHarnessGenome()),
    undefined,
  );

  // Disabling one tool keeps every other tool Pi had enabled.
  assert.deepEqual(
    genomeActiveToolNames(
      all,
      all,
      createHarnessGenome({ tools: [{ name: "bash", enabled: false }] }),
    ),
    ["read", "ls", "load_skill", "mcp_search"],
  );

  // Enabling a tool Pi left off adds it; `list` still maps to Pi's `ls`.
  assert.deepEqual(
    genomeActiveToolNames(
      ["read"],
      all,
      createHarnessGenome({
        tools: [{ name: "list", enabled: true }, { name: "bash", enabled: true }],
      }),
    ),
    ["read", "ls", "bash"],
  );
});

test("Genome footer status is labeled and purple", () => {
  assert.equal(genomeFooterStatus("coding"), "\u001b[35mGenome: coding\u001b[39m");
});

test("RSIH TUI header includes DNA logo and runtime identity", () => {
  const lines = rsiHeaderLines(
    60,
    {
      cwd: join(homedir(), "project"),
      model: "gpt-5.6-sol",
      genome: "coding",
      version: "0.1.0",
    },
    (text) => `\u001b[35m${text}\u001b[39m`,
    (text) => `\u001b[1m${text}\u001b[0m`,
  );
  const plain = lines.join("\n").replace(/\u001b\[[0-9;]*m/g, "");
  assert.match(plain, /โ•ญโ”€+โ•ฎ/);
  assert.match(plain, /[โ–€โ–„โ–ˆ]/);
  assert.match(plain, /โ–„โ–„โ–„โ–„/);
  assert.match(plain, /Workspace: ~\/project/);
  assert.match(plain, /Model: gpt-5\.6-sol/);
  assert.match(plain, /Genome: coding/);
  assert.match(plain, /Version: 0\.1\.0/);
  assert.ok(lines[0].startsWith("\u001b[35m"));
});

test("RSIH TUI header lists the loaded resources and nothing transient", () => {
  const lines = rsiHeaderLines(
    60,
    {
      cwd: join(homedir(), "project"),
      model: "gpt-5.6-sol",
      genome: "coding",
      version: "0.1.0",
      resources: {
        skills: ["code-review"],
        extensions: ["git.ts"],
      },
    },
    (text) => text,
    (text) => text,
  );
  const plain = lines.join("\n");
  assert.match(plain, /\[Skills\]/);
  assert.match(plain, /code-review/);
  assert.match(plain, /\[Extensions\]/);
  assert.match(plain, /git\.ts/);
  assert.match(plain, /โ”‚/);
  assert.match(plain, /A Genome-driven runtime f/);
  assert.match(plain, /โ”‚\s+โ”€{3,}\s+โ”‚/);
  assert.doesNotMatch(plain, /none loaded/);
  assert.doesNotMatch(plain, /Skills:/);
  assert.doesNotMatch(plain, /Extensions:/);
});

test("RSIH TUI keeps a fixed column divider and compacts long workspaces", () => {
  const lines = rsiHeaderLines(
    120,
    {
      cwd: join(homedir(), "Documents/cosmos/dopapers/rsih"),
      model: "gpt-5.6-sol",
      genome: "default",
      version: "0.1.0",
      resources: { skills: [], extensions: [] },
    },
    (text) => text,
    (text) => text,
  );
  const plain = lines.join("\n");
  const dividerPositions = lines
    .slice(1, -1)
    .map((line) => line.replace(/\u001b\[[0-9;]*m/g, "").indexOf("โ”‚", 1));
  assert.equal(new Set(dividerPositions).size, 1);
  assert.match(plain, /Workspace: ~\/\.\.\.\/dopapers\/rsih/);
});

test("RSIH editor preserves Pi cursor marker when padding is zero", () => {
  const tui = { terminal: { rows: 42 }, requestRender() {} };
  const theme = {
    borderColor: (text) => `\u001b[35m${text}\u001b[39m`,
    selectList: {},
  };
  const keybindings = { matches: () => false };
  const editor = new RsiEditor(tui, theme, keybindings);
  editor.focused = true;
  editor.setPaddingX(0);

  const inputLine = editor.render(60)[1]!;
  assert.match(inputLine, /^\u001b\[35m>\u001b\[39m\u001b_pi:c\u0007/);
  assert.doesNotMatch(inputLine, /^.*>\u001b\[39m_pi:c/);
  assert.ok(visibleWidth(inputLine) <= 60);
});

/**
 * RSIH replaces one padding cell with its prompt character and nothing else.
 * It used to also strip Pi's autocomplete rows off the end of the editor so the
 * header could redraw them, which put the slash-command list up in the startup
 * banner instead of under the input box.
 */
test("RSIH editor keeps every row Pi's editor renders", () => {
  const tui = { terminal: { rows: 42 }, requestRender() {} };
  const theme = {
    borderColor: (text) => `\u001b[35m${text}\u001b[39m`,
    selectList: {},
  };
  const keybindings = { matches: () => false };
  const editor = new RsiEditor(tui, theme, keybindings);
  editor.focused = true;

  const upstream = Object.getPrototypeOf(RsiEditor.prototype).render.call(
    editor,
    60,
  );  assert.equal(editor.render(60).length, upstream.length);
  assert.equal(typeof editor.getAutocompleteLines, "undefined");
});

test("checked-in default Genome leaves Pi defaults unchanged", () => {
  const checkedIn = JSON.parse(
    readFileSync(
      join(codeDirectory, "config", "harness.default.json"),
      "utf8",
    ),
  );
  const genome = createDefaultHarnessGenome();

  assert.deepEqual(checkedIn, genome);
  // The default Genome must not carry a single behavioral field: anything it
  // declared would be silently imposed on a bare `rsih` run.
  assert.deepEqual(Object.keys(genome).sort(), [
    "genome_id",
    "genome_schema_version",
    "parent_id",
    "version",
  ]);
});

test("CLI runs through Pi print mode and stores Genome in Pi JSONL", () => {
  const directory = mkdtempSync(join(tmpdir(), "rsih-cli-"));
  const providersPath = join(directory, "providers.json");
  const genomePath = join(directory, "genome.json");
  writeFileSync(
    providersPath,
    JSON.stringify({
      mock: {
        kind: "mock",
        model: "mock-cli",
        mock_responses: ["cli ok"],
      },
    }),
    "utf8",
  );
  writeFileSync(
    genomePath,
    JSON.stringify(
      createHarnessGenome({
        genome_id: "harness:cli",
        model: { profile: "mock", id: "mock-cli" },
      }),
    ),
    "utf8",
  );

  const result = runCli(directory, [
    "-p",
    "Say ok.",
    "--run-id",
    "cli-test",
    "--config",
    providersPath,
    "--genome",
    genomePath,
    "--cwd",
    directory,
  ]);

  assert.equal(result.status, 0, result.stderr);
  assert.equal(result.stdout.trim(), "cli ok");
  const entries = sessionEntries(piSessionDir(directory));
  assert.equal(entries[0].id, "cli-test");
  assert.ok(
    entries.some(
      (entry) =>
        entry.type === "custom" &&
        entry.customType === "rsih.genome" &&
        entry.data.genome_id === "harness:cli",
    ),
  );
  assert.ok(
    entries.some(
      (entry) =>
        entry.type === "message" &&
        entry.message.role === "assistant" &&
        entry.message.content.some(
          (content) => content.type === "text" && content.text === "cli ok",
        ),
    ),
  );
});

/**
 * Driving a Genome from the command line: one `--run-id` names a conversation,
 * and every later invocation with that id appends to it. The Genome is named
 * once and restored from the session afterwards, so a script does not have to
 * repeat it -- and cannot accidentally change it half way through.
 */
test("a run id keeps one conversation alive across separate invocations", () => {
  const directory = mkdtempSync(join(tmpdir(), "rsih-cli-runid-"));
  const providersPath = join(directory, "providers.json");
  const genomesDirectory = join(directory, ".rsih", "genomes");
  mkdirSync(genomesDirectory, { recursive: true });
  writeFileSync(
    providersPath,
    JSON.stringify({
      notes: { kind: "mock", model: "notes-model", mock_responses: ["noted"] },
    }),
    "utf8",
  );
  writeFileSync(
    join(genomesDirectory, "notes.json"),
    JSON.stringify(
      createHarnessGenome({
        genome_id: "harness:notes",
        // Only reachable through the Genome, so a reply proves it was applied.
        model: { profile: "notes", id: "notes-model" },
      }),
    ),
    "utf8",
  );

  const first = runCli(directory, [
    "-p",
    "First.",
    "--config",
    providersPath,
    "--genome",
    "notes",
    "--run-id",
    "conversation-1",
    "--cwd",
    directory,
  ]);
  assert.equal(first.status, 0, first.stderr);
  assert.equal(first.stdout.trim(), "noted");

  // No --genome this time: the session carries it.
  const second = runCli(directory, [
    "-p",
    "Second.",
    "--config",
    providersPath,
    "--run-id",
    "conversation-1",
    "--cwd",
    directory,
  ]);
  assert.equal(second.status, 0, second.stderr);
  assert.equal(second.stdout.trim(), "noted");

  const entries = sessionEntries(piSessionDir(directory));
  assert.equal(entries[0].id, "conversation-1", "--run-id names the session");
  assert.deepEqual(
    entries
      .filter((entry) => entry.type === "message" && entry.message.role === "user")
      .map((entry) => entry.message.content[0].text),
    ["First.", "Second."],
    "the second invocation appends instead of starting over",
  );
  assert.equal(
    entries.filter(
      (entry) => entry.type === "custom" && entry.customType === "rsih.genome",
    ).length,
    1,
    "the Genome is recorded once, not re-stamped every turn",
  );
});

test("CLI discovers a named Genome and resumes its Pi session", () => {
  const directory = mkdtempSync(join(tmpdir(), "rsih-cli-genome-"));
  const providersPath = join(directory, "providers.json");
  const genomesDirectory = join(directory, ".rsih", "genomes");
  mkdirSync(genomesDirectory, { recursive: true });
  writeFileSync(
    providersPath,
    JSON.stringify({
      coding: {
        kind: "mock",
        model: "genome-model",
        mock_responses: ["named genome ok"],
      },
    }),
    "utf8",
  );
  writeFileSync(
    join(genomesDirectory, "coding.json"),
    JSON.stringify(
      createHarnessGenome({
        genome_id: "harness:coding",
        model: { profile: "coding", id: "genome-model" },
        skills: [
          {
            name: "coding",
            description: "Coding workflow",
            content: "Use a focused coding workflow.",
          },
        ],
      }),
    ),
    "utf8",
  );

  const first = runCli(directory, [
    "-p",
    "First.",
    "--config",
    providersPath,
    "--genome",
    "coding",
    "--cwd",
    directory,
  ]);
  assert.equal(first.status, 0, first.stderr);
  assert.equal(first.stdout.trim(), "named genome ok");
  const firstEntries = sessionEntries(piSessionDir(directory));
  const sessionId = firstEntries[0].id;

  const second = runCli(directory, [
    "-p",
    "Second.",
    "--continue",
    "--config",
    providersPath,
    "--cwd",
    directory,
  ]);
  assert.equal(second.status, 0, second.stderr);
  assert.equal(second.stdout.trim(), "named genome ok");
  const entries = sessionEntries(piSessionDir(directory));
  assert.equal(entries[0].id, sessionId);
  assert.equal(
    entries.filter(
      (entry) =>
        entry.type === "message" && entry.message.role === "user",
    ).length,
    2,
  );
  assert.equal(
    entries.filter(
      (entry) =>
        entry.type === "custom" && entry.customType === "rsih.genome",
    ).length,
    1,
  );
});

test("the binary ships no changelog, not Pi's", () => {
  // Pi resolves CHANGELOG.md next to the package.json it reads, so pairing
  // Pi's release notes with RSIH's version makes every Pi release look unseen
  // and replays the "What's New" wall on every start. Shipping none is the
  // intended state: Pi treats a missing changelog as no entries.
  const buildScript = readFileSync(
    join(codeDirectory, "scripts", "build-binary.ts"),
    "utf8",
  );
  assert.doesNotMatch(
    buildScript,
    /copyFileSync\([^)]*CHANGELOG|cpSync\([^)]*CHANGELOG/,
    "no changelog may ship with the binary",
  );
});

test("a leading :, :: or + is shorthand for --genome", () => {
  for (const argument of ["+coding", ":coding", "::coding"]) {
    assert.deepEqual(expandGenomeShorthand([argument]), ["--genome", "coding"]);
  }
  // The rest of argv is untouched, so the shorthand composes with Pi's flags.
  assert.deepEqual(expandGenomeShorthand(["+coding", "-p", "go"]), [
    "--genome",
    "coding",
    "-p",
    "go",
  ]);
  // Path references work too; resolution is the loader's job, not the parser's.
  assert.deepEqual(expandGenomeShorthand([":./my-genome"]), [
    "--genome",
    "./my-genome",
  ]);
  // Expanding twice must not add a second --genome.
  assert.deepEqual(
    expandGenomeShorthand(expandGenomeShorthand(["+coding"])),
    ["--genome", "coding"],
  );
});

test("the Genome shorthand does not swallow messages or option values", () => {
  // Pi takes free-form messages as positional arguments and most of its options
  // take values, so only the launch position is unambiguous.
  assert.deepEqual(expandGenomeShorthand(["--thinking", "+x"]), [
    "--thinking",
    "+x",
  ]);
  assert.deepEqual(expandGenomeShorthand(["add", "+1", "to", "the", "counter"]), [
    "add",
    "+1",
    "to",
    "the",
    "counter",
  ]);
  // A bare sigil names no Genome, and whitespace means the argument is prose.
  assert.equal(genomeShorthandReference("+"), undefined);
  assert.equal(genomeShorthandReference(":"), undefined);
  assert.equal(genomeShorthandReference("::"), undefined);
  assert.equal(genomeShorthandReference(": coding"), undefined);
  assert.equal(genomeShorthandReference("coding"), undefined);
  assert.equal(genomeShorthandReference(undefined), undefined);
  assert.deepEqual(expandGenomeShorthand([]), []);
});

test("RSIH options accept both --option value and --option=value", () => {
  // The equals spelling used to fall through to Pi untouched, which silently
  // started the default Genome instead of the requested one.
  assert.equal(parseCliArgs(["--genome=coding"]).genome, "coding");
  assert.equal(parseCliArgs(["--genome", "coding"]).genome, "coding");
  assert.equal(parseCliArgs(["--max-turns=3"]).maxTurns, 3);
  assert.equal(parseCliArgs(["--cwd=/tmp"]).cwd, "/tmp");
  assert.deepEqual(parseCliArgs(["--profile=local"]).piArgs, [
    "--provider",
    "local",
  ]);
  assert.equal(parseCliArgs(["--genome=coding"]).piArgs.length, 0);
  assert.throws(() => parseCliArgs(["--genome="]), /--genome requires a value/);
});

test("launching with the +name shorthand resolves that Genome", () => {
  // The unit tests cover the rewrite; this covers the wiring in src/cli.ts,
  // which is the part that can silently not be called.
  const directory = mkdtempSync(join(tmpdir(), "rsih-cli-shorthand-"));
  const providersPath = join(directory, "providers.json");
  const genomesDirectory = join(directory, ".rsih", "genomes");
  mkdirSync(genomesDirectory, { recursive: true });
  writeFileSync(
    providersPath,
    JSON.stringify({
      coding: {
        kind: "mock",
        model: "genome-model",
        mock_responses: ["shorthand ok"],
      },
    }),
    "utf8",
  );
  writeFileSync(
    join(genomesDirectory, "coding.json"),
    JSON.stringify(
      createHarnessGenome({
        genome_id: "harness:coding-shorthand",
        model: { profile: "coding", id: "genome-model" },
      }),
    ),
    "utf8",
  );

  const result = runCli(directory, [
    "+coding",
    "-p",
    "First.",
    "--config",
    providersPath,
    "--cwd",
    directory,
  ]);
  assert.equal(result.status, 0, result.stderr);
  assert.equal(result.stdout.trim(), "shorthand ok");
  assert.ok(
    sessionEntries(piSessionDir(directory)).some(
      (entry) =>
        entry.type === "custom" &&
        entry.customType === "rsih.genome" &&
        entry.data.genome_id === "harness:coding-shorthand",
    ),
  );
});

test("installing carries the whole payload, not just the executable", () => {
  // The binary resolves its version, built-in Genome seeds and themes relative
  // to its own directory. Copying only the executable onto the PATH produced an
  // rsih that reported 0.0.0 and could not find `paperlab` at all, so the install
  // step has to move the payload and link to it.
  const buildScript = readFileSync(
    join(codeDirectory, "scripts", "build-binary.ts"),
    "utf8",
  );
  assert.match(buildScript, /cpSync\(dirname\(outputPath\), libDirectory/);
  assert.match(buildScript, /symlinkSync\(target, link\)/);
  assert.doesNotMatch(
    buildScript,
    /copyFileSync\(outputPath, installPath\)/,
    "install must not copy the bare executable onto the PATH",
  );

  // install.sh must not reimplement any of that.
  const installScript = readFileSync(join(codeDirectory, "install.sh"), "utf8");
  assert.match(installScript, /npm run --silent install:binary/);
  // And it has to prove the payload arrived rather than trust the copy.
  assert.match(installScript, /rsih" genome validate paperlab/);
});