@cchistory/lite 0.4.2 → 0.4.3

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 (88) hide show
  1. package/INSTALL.md +1 -1
  2. package/README.md +10 -1
  3. package/apps/lite-cli/dist/agent-contract.d.ts +83 -0
  4. package/apps/lite-cli/dist/agent-contract.d.ts.map +1 -0
  5. package/apps/lite-cli/dist/agent-contract.js +271 -0
  6. package/apps/lite-cli/dist/agent-contract.js.map +1 -0
  7. package/apps/lite-cli/dist/index.d.ts +1 -0
  8. package/apps/lite-cli/dist/index.d.ts.map +1 -1
  9. package/apps/lite-cli/dist/index.js +115 -44
  10. package/apps/lite-cli/dist/index.js.map +1 -1
  11. package/apps/lite-cli/dist/index.test.js +445 -18
  12. package/apps/lite-cli/dist/index.test.js.map +1 -1
  13. package/apps/lite-cli/dist/json-v2.js +1 -1
  14. package/apps/lite-cli/dist/json-v2.js.map +1 -1
  15. package/apps/lite-cli/dist/version.d.ts +11 -0
  16. package/apps/lite-cli/dist/version.d.ts.map +1 -0
  17. package/apps/lite-cli/dist/version.js +11 -0
  18. package/apps/lite-cli/dist/version.js.map +1 -0
  19. package/apps/lite-tui/dist/index.d.ts.map +1 -1
  20. package/apps/lite-tui/dist/index.js +26 -4
  21. package/apps/lite-tui/dist/index.js.map +1 -1
  22. package/apps/lite-tui/dist/index.test.js +97 -2
  23. package/apps/lite-tui/dist/index.test.js.map +1 -1
  24. package/apps/lite-tui/dist/model.d.ts.map +1 -1
  25. package/apps/lite-tui/dist/model.js +16 -8
  26. package/apps/lite-tui/dist/model.js.map +1 -1
  27. package/apps/lite-tui/dist/render.d.ts +1 -1
  28. package/apps/lite-tui/dist/render.js +1 -1
  29. package/apps/lite-tui/dist/render.js.map +1 -1
  30. package/apps/lite-tui/dist/render.test.js +38 -13
  31. package/apps/lite-tui/dist/render.test.js.map +1 -1
  32. package/apps/lite-tui/dist/text.d.ts +2 -2
  33. package/apps/lite-tui/dist/text.d.ts.map +1 -1
  34. package/apps/lite-tui/dist/text.js +2 -23
  35. package/apps/lite-tui/dist/text.js.map +1 -1
  36. package/apps/lite-tui/dist/version.d.ts +3 -2
  37. package/apps/lite-tui/dist/version.d.ts.map +1 -1
  38. package/apps/lite-tui/dist/version.js +3 -2
  39. package/apps/lite-tui/dist/version.js.map +1 -1
  40. package/apps/lite-tui/dist/view-model.d.ts +7 -6
  41. package/apps/lite-tui/dist/view-model.d.ts.map +1 -1
  42. package/apps/lite-tui/dist/view-model.js +10 -8
  43. package/apps/lite-tui/dist/view-model.js.map +1 -1
  44. package/docs/guide/for-agents.md +113 -0
  45. package/docs/guide/lite.md +343 -0
  46. package/node_modules/@cchistory/canonical/dist/index.test.js +47 -0
  47. package/node_modules/@cchistory/canonical/dist/index.test.js.map +1 -1
  48. package/node_modules/@cchistory/canonical/dist/project-linker.d.ts.map +1 -1
  49. package/node_modules/@cchistory/canonical/dist/project-linker.js +5 -2
  50. package/node_modules/@cchistory/canonical/dist/project-linker.js.map +1 -1
  51. package/node_modules/@cchistory/canonical/dist/projection-audit.d.ts +1 -1
  52. package/node_modules/@cchistory/canonical/dist/projection-audit.d.ts.map +1 -1
  53. package/node_modules/@cchistory/canonical/dist/projection-audit.js +11 -0
  54. package/node_modules/@cchistory/canonical/dist/projection-audit.js.map +1 -1
  55. package/node_modules/@cchistory/canonical/package.json +1 -1
  56. package/node_modules/@cchistory/domain/dist/index.d.ts +7 -0
  57. package/node_modules/@cchistory/domain/dist/index.d.ts.map +1 -1
  58. package/node_modules/@cchistory/domain/dist/index.js +25 -0
  59. package/node_modules/@cchistory/domain/dist/index.js.map +1 -1
  60. package/node_modules/@cchistory/domain/dist/index.test.js +17 -1
  61. package/node_modules/@cchistory/domain/dist/index.test.js.map +1 -1
  62. package/node_modules/@cchistory/domain/package.json +1 -1
  63. package/node_modules/@cchistory/live-runtime/dist/index.d.ts +31 -1
  64. package/node_modules/@cchistory/live-runtime/dist/index.d.ts.map +1 -1
  65. package/node_modules/@cchistory/live-runtime/dist/index.js +85 -1
  66. package/node_modules/@cchistory/live-runtime/dist/index.js.map +1 -1
  67. package/node_modules/@cchistory/live-runtime/dist/node-memory.d.ts +5 -2
  68. package/node_modules/@cchistory/live-runtime/dist/node-memory.d.ts.map +1 -1
  69. package/node_modules/@cchistory/live-runtime/dist/node-memory.js +32 -5
  70. package/node_modules/@cchistory/live-runtime/dist/node-memory.js.map +1 -1
  71. package/node_modules/@cchistory/live-runtime/dist/scan-guard.d.ts +146 -0
  72. package/node_modules/@cchistory/live-runtime/dist/scan-guard.d.ts.map +1 -0
  73. package/node_modules/@cchistory/live-runtime/dist/scan-guard.js +434 -0
  74. package/node_modules/@cchistory/live-runtime/dist/scan-guard.js.map +1 -0
  75. package/node_modules/@cchistory/live-runtime/dist/scan-guard.test.d.ts +2 -0
  76. package/node_modules/@cchistory/live-runtime/dist/scan-guard.test.d.ts.map +1 -0
  77. package/node_modules/@cchistory/live-runtime/dist/scan-guard.test.js +532 -0
  78. package/node_modules/@cchistory/live-runtime/dist/scan-guard.test.js.map +1 -0
  79. package/node_modules/@cchistory/live-runtime/dist/system-memory.d.ts +19 -0
  80. package/node_modules/@cchistory/live-runtime/dist/system-memory.d.ts.map +1 -0
  81. package/node_modules/@cchistory/live-runtime/dist/system-memory.js +56 -0
  82. package/node_modules/@cchistory/live-runtime/dist/system-memory.js.map +1 -0
  83. package/node_modules/@cchistory/live-runtime/package.json +1 -1
  84. package/node_modules/@cchistory/source-adapters/package.json +1 -1
  85. package/package.json +13 -5
  86. package/schemas/cchistory-lite-agent-v1.schema.json +205 -0
  87. package/schemas/cchistory-lite-v2.schema.json +1 -1
  88. package/skills/using-cchistory-lite/SKILL.md +74 -0
@@ -1,13 +1,14 @@
1
1
  import assert from "node:assert/strict";
2
- import { access, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises";
2
+ import { access, cp, mkdir, mkdtemp, readFile, rm, symlink, truncate, writeFile } from "node:fs/promises";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { PassThrough } from "node:stream";
6
6
  import { setTimeout as delay } from "node:timers/promises";
7
7
  import test from "node:test";
8
8
  import { fileURLToPath } from "node:url";
9
- import { LiveHistorySnapshot, scanLiteHistory, } from "@cchistory/live-runtime";
10
- import { formatTuiLaunchError, runLiteCli } from "./index.js";
9
+ import { FULL_SCAN_MEMORY_MULTIPLIER, LIGHT_SCAN_MEMORY_MULTIPLIER, LiveHistorySnapshot, MAX_OLD_SPACE_MIB, MIN_OLD_SPACE_MIB, SCAN_GUARD_REFUSE_AVAILABLE_FRACTION, SCAN_GUARD_WARN_AVAILABLE_FRACTION, SCAN_LOCK_WAIT_MS, SCAN_WATCHDOG_MIN_FLOOR_BYTES, SCAN_WATCHDOG_TOTAL_FLOOR_FRACTION, scanLiteHistory, ScanGuardAbortedError, ScanGuardRefusedError, } from "@cchistory/live-runtime";
10
+ import { formatTuiLaunchError, runLiteCli, VERSION } from "./index.js";
11
+ import { buildAgentContract } from "./agent-contract.js";
11
12
  import { compactPayload } from "./json-v2.js";
12
13
  const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../..");
13
14
  const codexRoot = path.join(repoRoot, "mock_data", ".codex", "sessions");
@@ -83,7 +84,7 @@ test("Lite CLI searches, reports stats, and writes one-way export", async () =>
83
84
  assert.equal(statsPayload.kind, "stats");
84
85
  assert.ok(statsPayload.overview.total_turns > 0);
85
86
  const humanStats = captureIo(tempHome);
86
- assert.equal(await runLiteCli(["stats", ...sourceArgs], humanStats.io), 0);
87
+ assert.equal(await runLiteCli(["stats", ...sourceArgs, "--no-dir"], humanStats.io), 0);
87
88
  assert.match(humanStats.stdout.join(""), /Excluded zero-token turns:/);
88
89
  const rollup = captureIo(tempHome);
89
90
  assert.equal(await runLiteCli(["stats", "--by", "source", ...unscopedArgs], rollup.io), 0);
@@ -635,7 +636,7 @@ test("Lite CLI latest parses defaults, aliases, and positional counts", async ()
635
636
  turns: [pendingTurn, ...snapshot.data.turns],
636
637
  });
637
638
  const latestSessions = captureIo(repoRoot, undefined, { scan: async () => zeroTurnSnapshot });
638
- assert.equal(await runLiteCli(["latest"], latestSessions.io), 0);
639
+ assert.equal(await runLiteCli(["latest", "--no-dir"], latestSessions.io), 0);
639
640
  const latestSessionText = latestSessions.stdout.join("");
640
641
  assert.match(latestSessionText, /Latest sessions \(6, newest first; one record = one session\)/);
641
642
  assert.match(latestSessionText, /● just now ·/);
@@ -651,12 +652,12 @@ test("Lite CLI latest parses defaults, aliases, and positional counts", async ()
651
652
  const resumableSessionRef = snapshot.getSessionDisplayRef(resumableSession.id) ?? resumableSession.id;
652
653
  assert.equal(latestSessionText.includes(`session ${resumableSessionRef}`), false, "latest must not repeat a session id when a resume command already identifies the session");
653
654
  const narrowSessions = captureIo(repoRoot, undefined, { scan: scanner, columns: 40 });
654
- assert.equal(await runLiteCli(["ls", "sessions", "--all"], narrowSessions.io), 0);
655
+ assert.equal(await runLiteCli(["ls", "sessions", "--all", "--no-dir"], narrowSessions.io), 0);
655
656
  const narrowSessionText = narrowSessions.stdout.join("");
656
657
  assert.ok(narrowSessionText.split("\n").slice(1).every((line) => displayColumnsForTest(line) <= 40), "session rows must stay within the injected terminal width");
657
658
  assert.ok(narrowSessionText.replace(/\s+/gu, "").includes(resumableSession.resume_command.replace(/\s+/gu, "")), "wrapped resume commands must retain every non-whitespace character");
658
659
  const latestTurns = captureIo(repoRoot, undefined, { scan: scanner });
659
- assert.equal(await runLiteCli(["latest", "turns", "1"], latestTurns.io), 0);
660
+ assert.equal(await runLiteCli(["latest", "turns", "1", "--no-dir"], latestTurns.io), 0);
660
661
  const latestTurnText = latestTurns.stdout.join("");
661
662
  const firstTurn = snapshot.listResolvedTurns()[0];
662
663
  assert.ok(firstTurn);
@@ -676,7 +677,7 @@ test("Lite CLI latest parses defaults, aliases, and positional counts", async ()
676
677
  assert.ok(latestTurnText.includes(new Intl.NumberFormat("en-US").format(firstTurnTokens)));
677
678
  }
678
679
  const narrowTurns = captureIo(repoRoot, undefined, { scan: scanner, columns: 70 });
679
- assert.equal(await runLiteCli(["latest", "turns", "1"], narrowTurns.io), 0);
680
+ assert.equal(await runLiteCli(["latest", "turns", "1", "--no-dir"], narrowTurns.io), 0);
680
681
  assert.ok(narrowTurns.stdout.join("").split("\n").every((line) => displayColumnsForTest(line) <= 70), "latest output must stay within a narrow terminal width");
681
682
  const defaults = captureIo(repoRoot, undefined, { scan: async () => zeroTurnSnapshot });
682
683
  assert.equal(await runLiteCli(["latest", "--json", "--no-dir"], defaults.io), 0);
@@ -723,12 +724,12 @@ test("Lite CLI ls limits human and JSON output and rejects conflicting controls
723
724
  const snapshot = await getCodexSnapshot();
724
725
  const scanner = async () => snapshot;
725
726
  const projects = captureIo(repoRoot, undefined, { scan: scanner });
726
- assert.equal(await runLiteCli(["ls", "projects", "--limit", "1"], projects.io), 0);
727
+ assert.equal(await runLiteCli(["ls", "projects", "--limit", "1", "--no-dir"], projects.io), 0);
727
728
  assert.match(projects.stdout.join(""), /Projects \(1 of \d+, most active first; one record = one project\)/);
728
729
  assert.match(projects.stdout.join(""), /● /);
729
730
  assert.doesNotMatch(projects.stdout.join(""), /ACTIVITY\s+LINKAGE\s+SESS\s+TURNS\s+DIRECTORY/);
730
731
  const limited = captureIo(repoRoot, undefined, { scan: scanner });
731
- assert.equal(await runLiteCli(["ls", "sessions", "--limit", "1"], limited.io), 0);
732
+ assert.equal(await runLiteCli(["ls", "sessions", "--limit", "1", "--no-dir"], limited.io), 0);
732
733
  assert.match(limited.stdout.join(""), /Sessions \(1 of 5, newest first; one record = one session\)/);
733
734
  assert.match(limited.stdout.join(""), /● .* · Codex/);
734
735
  assert.doesNotMatch(limited.stdout.join(""), /UPDATED\s+SOURCE\s+SESSION\s+TURNS/);
@@ -860,6 +861,29 @@ test("Lite CLI show resolves canonical session refs before a source-wide detail
860
861
  assert.doesNotMatch(rendered.stdout.join(""), /\n\{/);
861
862
  }
862
863
  });
864
+ test("Lite CLI markdown export uses the light scan-guard profile; JSON export stays full", async () => {
865
+ const snapshot = await getCodexSnapshot();
866
+ const scanFor = async (args) => {
867
+ const calls = [];
868
+ const captured = captureIo(repoRoot, undefined, {
869
+ scan: async (options) => {
870
+ calls.push(options);
871
+ return snapshot;
872
+ },
873
+ });
874
+ assert.equal(await runLiteCli(args, captured.io), 0, captured.stderr.join(""));
875
+ return calls[0];
876
+ };
877
+ const markdown = await scanFor(["export", "--format", "markdown", "--out", "-"]);
878
+ assert.equal(markdown?.contextMode, "none");
879
+ assert.equal(markdown?.scanGuard?.profile, "light");
880
+ const json = await scanFor(["export", "--format", "json", "--out", "-"]);
881
+ assert.equal(json?.contextMode, "full");
882
+ assert.equal(json?.scanGuard?.profile, "full");
883
+ const jsonl = await scanFor(["export", "--format", "jsonl", "--out", "-"]);
884
+ assert.equal(jsonl?.contextMode, "full");
885
+ assert.equal(jsonl?.scanGuard?.profile, "full");
886
+ });
863
887
  test("Lite CLI sample is a bounded latest-shaped preview", async () => {
864
888
  const snapshot = await getCodexSnapshot();
865
889
  const scanOptions = [];
@@ -871,12 +895,19 @@ test("Lite CLI sample is a bounded latest-shaped preview", async () => {
871
895
  });
872
896
  assert.equal(await runLiteCli(["sample", "3", "--json"], captured.io), 0);
873
897
  assert.equal(scanOptions[0]?.sample?.perSource, 3);
874
- assert.equal(scanOptions[0]?.directoryScope, undefined);
898
+ assert.equal(scanOptions[0]?.directoryScope, repoRoot);
875
899
  const payload = JSON.parse(captured.stdout.join(""));
876
900
  assert.equal(payload.kind, "sessions");
877
901
  assert.equal(payload.sampled, true);
878
902
  assert.equal(payload.sample_per_source, 3);
879
903
  });
904
+ test("the CLI version matches the package manifest", async () => {
905
+ const manifest = JSON.parse(await readFile(path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "package.json"), "utf8"));
906
+ assert.equal(VERSION, manifest.version);
907
+ const captured = captureIo(repoRoot);
908
+ assert.equal(await runLiteCli(["--version"], captured.io), 0);
909
+ assert.equal(captured.stdout.join(""), `${VERSION}\n`);
910
+ });
880
911
  test("Lite CLI help documents latest, limits, and directory scope", async () => {
881
912
  const captured = captureIo(repoRoot);
882
913
  assert.equal(await runLiteCli(["help"], captured.io), 0);
@@ -892,6 +923,46 @@ test("Lite CLI help documents latest, limits, and directory scope", async () =>
892
923
  assert.match(help, /last real message activity/);
893
924
  assert.match(help, /Sessions without a\nworking directory are excluded/);
894
925
  assert.match(help, /does not open parent project folders or later Codex cwd lines/);
926
+ assert.match(help, /default: current directory/);
927
+ assert.match(help, /can use a lot of memory/);
928
+ assert.match(help, /TUI and export still scan every selected source/);
929
+ assert.match(help, /--offset <n>/);
930
+ assert.match(help, /--project <ref>/);
931
+ assert.match(help, /--by <dimension>/);
932
+ assert.match(help, /--format jsonl\|json\|markdown/);
933
+ assert.match(help, /--out <file\|->/);
934
+ assert.match(help, /cchistory-lite help \[command\]/);
935
+ // store/db appear only in the closing line that documents their absence.
936
+ const knownFlags = new Set([
937
+ "source-root",
938
+ "source",
939
+ "limit-files",
940
+ "limit",
941
+ "offset",
942
+ "project",
943
+ "by",
944
+ "format",
945
+ "out",
946
+ "dir",
947
+ "request",
948
+ "safe",
949
+ "json",
950
+ "help",
951
+ "version",
952
+ "all",
953
+ "no-dir",
954
+ "store",
955
+ "db",
956
+ ]);
957
+ const documentedFlags = new Set([...help.matchAll(/--([a-z][a-z-]*)/gu)].map((match) => match[1]));
958
+ for (const flag of documentedFlags) {
959
+ assert.ok(knownFlags.has(flag), `help documents unknown option --${flag}`);
960
+ }
961
+ for (const flag of knownFlags) {
962
+ if (flag === "store" || flag === "db")
963
+ continue;
964
+ assert.ok(documentedFlags.has(flag), `help omits accepted option --${flag}`);
965
+ }
895
966
  });
896
967
  test("Lite CLI colorizes collection cards semantically on a TTY", async () => {
897
968
  const snapshot = await getCodexSnapshot();
@@ -904,7 +975,7 @@ test("Lite CLI colorizes collection cards semantically on a TTY", async () => {
904
975
  process.env.TERM = "xterm-256color";
905
976
  try {
906
977
  const tty = captureIo(repoRoot, undefined, { scan: scanner, isTTY: true });
907
- assert.equal(await runLiteCli(["ls", "sessions", "--all"], tty.io), 0);
978
+ assert.equal(await runLiteCli(["ls", "sessions", "--all", "--no-dir"], tty.io), 0);
908
979
  const text = tty.stdout.join("");
909
980
  // Gray tier: heading, timestamps, counts, session ids, resume command body.
910
981
  assert.ok(text.includes(`${E}[2mSessions (`));
@@ -945,22 +1016,22 @@ test("Lite CLI colorizes collection cards semantically on a TTY", async () => {
945
1016
  assert.ok(text.includes(`${E}[35m`) && text.includes(`${E}[0m ${E}[1m${E}[32m`));
946
1017
  assert.ok(!text.includes(`${E}[4m`));
947
1018
  const ttyTurns = captureIo(repoRoot, undefined, { scan: scanner, isTTY: true });
948
- assert.equal(await runLiteCli(["latest", "turns", "2"], ttyTurns.io), 0);
1019
+ assert.equal(await runLiteCli(["latest", "turns", "2", "--no-dir"], ttyTurns.io), 0);
949
1020
  const turnsText = ttyTurns.stdout.join("");
950
1021
  assert.ok(turnsText.includes(`${E}[34mCodex${E}[0m`));
951
1022
  assert.ok(turnsText.includes(`${E}[1m${E}[32m `));
952
1023
  assert.ok(turnsText.includes(`${E}[35m`));
953
1024
  const ttyProjects = captureIo(repoRoot, undefined, { scan: scanner, isTTY: true });
954
- assert.equal(await runLiteCli(["ls", "projects", "--all"], ttyProjects.io), 0);
1025
+ assert.equal(await runLiteCli(["ls", "projects", "--all", "--no-dir"], ttyProjects.io), 0);
955
1026
  assert.ok(ttyProjects.stdout.join("").includes(`${E}[2m● ${E}[0m${E}[1m${E}[32m`));
956
1027
  const ttySearch = captureIo(repoRoot, undefined, { scan: scanner, isTTY: true });
957
- assert.equal(await runLiteCli(["search", "mock"], ttySearch.io), 0);
1028
+ assert.equal(await runLiteCli(["search", "mock", "--no-dir"], ttySearch.io), 0);
958
1029
  const searchText = ttySearch.stdout.join("");
959
1030
  assert.ok(searchText.includes(`${E}[2m- sess:`));
960
1031
  assert.ok(searchText.includes(`${E}[1m${E}[32m `));
961
1032
  // Non-TTY output stays pure text.
962
1033
  const plain = captureIo(repoRoot, undefined, { scan: scanner });
963
- assert.equal(await runLiteCli(["ls", "sessions", "--all"], plain.io), 0);
1034
+ assert.equal(await runLiteCli(["ls", "sessions", "--all", "--no-dir"], plain.io), 0);
964
1035
  assert.ok(!plain.stdout.join("").includes(E));
965
1036
  }
966
1037
  finally {
@@ -1003,7 +1074,7 @@ test("Lite CLI renders container storage as an estimated share and omits zero by
1003
1074
  ],
1004
1075
  });
1005
1076
  const captured = captureIo(repoRoot, undefined, { scan: async () => sharedSnapshot });
1006
- assert.equal(await runLiteCli(["ls", "sessions", "--all"], captured.io), 0);
1077
+ assert.equal(await runLiteCli(["ls", "sessions", "--all", "--no-dir"], captured.io), 0);
1007
1078
  const text = captured.stdout.join("");
1008
1079
  assert.ok(text.includes("≈12KB of 10.0MB db"));
1009
1080
  assert.ok(!text.includes("· 0B"));
@@ -1045,7 +1116,7 @@ test("Lite CLI puts the session title after the model and omits prompt-history i
1045
1116
  sessions: [promptHistory, ...snapshot.data.sessions],
1046
1117
  });
1047
1118
  const captured = captureIo(repoRoot, undefined, { scan: async () => mixedSnapshot });
1048
- assert.equal(await runLiteCli(["ls", "sessions", "--all"], captured.io), 0);
1119
+ assert.equal(await runLiteCli(["ls", "sessions", "--all", "--no-dir"], captured.io), 0);
1049
1120
  const text = captured.stdout.join("");
1050
1121
  const model = target.model?.trim();
1051
1122
  assert.ok(model);
@@ -1081,6 +1152,36 @@ test("Lite CLI JSON search defaults to cwd and --no-dir restores the unscoped sn
1081
1152
  assert.equal(await runLiteCli(["search", "Review", "--json", "--dir", scoped.working_directory, "--no-dir"], conflict.io), 2);
1082
1153
  assert.match(conflict.stderr.join(""), /--no-dir and --dir cannot be used together/);
1083
1154
  });
1155
+ test("Lite CLI human collection commands default to cwd and announce the scope", async () => {
1156
+ const snapshot = await getCodexSnapshot();
1157
+ const scanOptions = [];
1158
+ const scanner = async (options) => {
1159
+ scanOptions.push(options);
1160
+ return snapshot;
1161
+ };
1162
+ const human = captureIo(repoRoot, undefined, { scan: scanner });
1163
+ assert.equal(await runLiteCli(["latest"], human.io), 0);
1164
+ assert.equal(scanOptions.at(-1)?.directoryScope, repoRoot);
1165
+ assert.match(human.stderr.join(""), /Looking for history under /);
1166
+ assert.match(human.stderr.join(""), /\(current directory\)/);
1167
+ assert.match(human.stderr.join(""), /Whole-machine scan: --no-dir/);
1168
+ assert.doesNotMatch(human.stdout.join(""), /Looking for history under /);
1169
+ const json = captureIo(repoRoot, undefined, { scan: scanner });
1170
+ assert.equal(await runLiteCli(["latest", "--json"], json.io), 0);
1171
+ assert.equal(scanOptions.at(-1)?.directoryScope, repoRoot);
1172
+ assert.doesNotMatch(json.stderr.join(""), /Looking for history under /);
1173
+ assert.doesNotMatch(json.stderr.join(""), /Whole-machine scan/);
1174
+ const unscoped = captureIo(repoRoot, undefined, { scan: scanner });
1175
+ assert.equal(await runLiteCli(["latest", "--no-dir"], unscoped.io), 0);
1176
+ assert.equal(scanOptions.at(-1)?.directoryScope, undefined);
1177
+ assert.match(unscoped.stderr.join(""), /Scanning all selected sources on this machine/);
1178
+ assert.match(unscoped.stderr.join(""), /This can use a lot of memory/);
1179
+ const exportRun = captureIo(repoRoot, undefined, { scan: scanner });
1180
+ assert.equal(await runLiteCli(["export", "--format", "markdown", "--out", "-"], exportRun.io), 0);
1181
+ assert.equal(scanOptions.at(-1)?.directoryScope, undefined);
1182
+ assert.doesNotMatch(exportRun.stderr.join(""), /Looking for history under /);
1183
+ assert.doesNotMatch(exportRun.stderr.join(""), /Scanning all selected sources on this machine/);
1184
+ });
1084
1185
  test("Lite CLI query latest and list count the same unit they return", async () => {
1085
1186
  const snapshot = await getCodexSnapshot();
1086
1187
  const request = JSON.stringify({
@@ -1235,6 +1336,332 @@ test("Lite shell JSON-lines keeps the snapshot when refresh fails and uses struc
1235
1336
  assert.equal(startupError.schema, "cchistory-lite-error/v1");
1236
1337
  assert.equal(startupError.error.code, "scan_failed");
1237
1338
  });
1339
+ test("Lite CLI scan guard refuses a scan whose estimate risks the machine, teaches the bounds, and bends to the kill-switch", async () => {
1340
+ const tempHome = await mkdtemp(path.join(os.tmpdir(), "cchistory-lite-guard-cli-"));
1341
+ const hugeRoot = path.join(tempHome, "huge-codex");
1342
+ try {
1343
+ await cp(codexRoot, hugeRoot, { recursive: true });
1344
+ // Sparse: reports 256 GiB without allocating real bytes.
1345
+ const hugeFile = path.join(hugeRoot, "huge.bin");
1346
+ await writeFile(hugeFile, "");
1347
+ await truncate(hugeFile, 256 * 1024 ** 3);
1348
+ const sourceArgs = ["--source-root", `codex=${hugeRoot}`, "--source", "codex", "--safe"];
1349
+ const refused = captureIo(tempHome);
1350
+ assert.equal(await runLiteCli(["sources", ...sourceArgs], refused.io), 1);
1351
+ assert.equal(refused.stdout.join(""), "");
1352
+ const message = refused.stderr.join("");
1353
+ assert.match(message, /Refusing to scan/);
1354
+ assert.match(message, /--source/);
1355
+ assert.match(message, /--dir/);
1356
+ assert.match(message, /--limit-files/);
1357
+ assert.match(message, /sample/);
1358
+ assert.match(message, /shell/);
1359
+ assert.match(message, /query/);
1360
+ assert.match(message, /CCHISTORY_SCAN_GUARD=0/);
1361
+ const refusedJson = captureIo(tempHome);
1362
+ assert.equal(await runLiteCli(["sources", "--json", ...sourceArgs], refusedJson.io), 1);
1363
+ assert.equal(refusedJson.stdout.join(""), "");
1364
+ const errorPayload = JSON.parse(refusedJson.stderr.join(""));
1365
+ assert.equal(errorPayload.schema, "cchistory-lite-error/v1");
1366
+ assert.equal(errorPayload.error.code, "scan_guard_refused");
1367
+ assert.match(errorPayload.error.message, /Refusing to scan/);
1368
+ // Bounded probes bypass the lock and the estimate even on the same root.
1369
+ const sampled = captureIo(tempHome);
1370
+ assert.equal(await runLiteCli(["sample", "1", ...sourceArgs, "--no-dir"], sampled.io), 0, sampled.stderr.join(""));
1371
+ const shown = captureIo(tempHome);
1372
+ assert.equal(await runLiteCli(["show", "session", "sess:codex:019ce4fd-8290-7501-afc4-0e9486733614", ...sourceArgs], shown.io), 0, shown.stderr.join(""));
1373
+ process.env.CCHISTORY_SCAN_GUARD = "0";
1374
+ try {
1375
+ const allowed = captureIo(tempHome);
1376
+ assert.equal(await runLiteCli(["sources", ...sourceArgs], allowed.io), 0, allowed.stderr.join(""));
1377
+ }
1378
+ finally {
1379
+ delete process.env.CCHISTORY_SCAN_GUARD;
1380
+ }
1381
+ }
1382
+ finally {
1383
+ await rm(tempHome, { recursive: true, force: true });
1384
+ }
1385
+ });
1386
+ test("Lite CLI maps scan guard refusals and aborts to exit 1 with distinct structured codes", async () => {
1387
+ const tempHome = await mkdtemp(path.join(os.tmpdir(), "cchistory-lite-guard-errors-"));
1388
+ try {
1389
+ const aborted = captureIo(tempHome, undefined, {
1390
+ scan: async () => {
1391
+ throw new ScanGuardAbortedError({ availableBytes: 300 * 1024 ** 2, floorBytes: 512 * 1024 ** 2 });
1392
+ },
1393
+ });
1394
+ assert.equal(await runLiteCli(["sources", "--json"], aborted.io), 1);
1395
+ assert.equal(aborted.stdout.join(""), "");
1396
+ const abortPayload = JSON.parse(aborted.stderr.join(""));
1397
+ assert.equal(abortPayload.schema, "cchistory-lite-error/v1");
1398
+ assert.equal(abortPayload.error.code, "scan_guard_aborted");
1399
+ const refused = captureIo(tempHome, undefined, {
1400
+ scan: async () => {
1401
+ throw new ScanGuardRefusedError({
1402
+ reason: "scan_in_progress",
1403
+ holder: { pid: 4321, startedAt: "2026-08-30T00:00:00.000Z" },
1404
+ waitedMs: 30_000,
1405
+ });
1406
+ },
1407
+ });
1408
+ assert.equal(await runLiteCli(["latest", "--json"], refused.io), 1);
1409
+ assert.equal(refused.stdout.join(""), "");
1410
+ const refusalPayload = JSON.parse(refused.stderr.join(""));
1411
+ assert.equal(refusalPayload.error.code, "scan_guard_refused");
1412
+ assert.match(refusalPayload.error.message, /another cchistory-lite scan/);
1413
+ // Human mode prints the plain message, not the JSON envelope.
1414
+ const human = captureIo(tempHome, undefined, {
1415
+ scan: async () => {
1416
+ throw new ScanGuardRefusedError({ reason: "scan_in_progress", holder: { pid: 4321 }, waitedMs: 30_000 });
1417
+ },
1418
+ });
1419
+ assert.equal(await runLiteCli(["sources"], human.io), 1);
1420
+ assert.match(human.stderr.join(""), /Refusing to scan/);
1421
+ assert.throws(() => JSON.parse(human.stderr.join("")));
1422
+ }
1423
+ finally {
1424
+ await rm(tempHome, { recursive: true, force: true });
1425
+ }
1426
+ });
1427
+ test("Lite CLI prints a one-line scan guard warning on stderr and proceeds", async () => {
1428
+ const tempHome = await mkdtemp(path.join(os.tmpdir(), "cchistory-lite-guard-warn-"));
1429
+ try {
1430
+ const warned = captureIo(tempHome, undefined, {
1431
+ scan: async (options) => {
1432
+ options.onScanGuardEvent?.({
1433
+ type: "warn",
1434
+ assessment: {
1435
+ status: "warn",
1436
+ profile: "light",
1437
+ estimatedBytes: 600,
1438
+ availableBytes: 1000,
1439
+ scannedBytes: 150,
1440
+ detail: "synthetic",
1441
+ },
1442
+ });
1443
+ return getCodexSnapshot();
1444
+ },
1445
+ });
1446
+ assert.equal(await runLiteCli(["sources", "--json"], warned.io), 0);
1447
+ assert.match(warned.stderr.join(""), /Scan guard warning/);
1448
+ assert.match(warned.stderr.join(""), /CCHISTORY_SCAN_GUARD=0/);
1449
+ assert.equal(JSON.parse(warned.stdout.join("")).kind, "sources");
1450
+ }
1451
+ finally {
1452
+ await rm(tempHome, { recursive: true, force: true });
1453
+ }
1454
+ });
1455
+ test("Lite CLI agent prints the machine-readable contract without scanning", async () => {
1456
+ const captured = captureIo(repoRoot, undefined, {
1457
+ scan: async () => {
1458
+ throw new Error("agent must not scan");
1459
+ },
1460
+ });
1461
+ assert.equal(await runLiteCli(["agent"], captured.io), 0);
1462
+ assert.equal(captured.stderr.join(""), "");
1463
+ const contract = JSON.parse(captured.stdout.join(""));
1464
+ assert.equal(contract.schema, "cchistory-lite-agent/v1");
1465
+ assert.equal(contract.kind, "agent_contract");
1466
+ assert.equal(contract.cli.name, "cchistory-lite");
1467
+ assert.match(contract.cli.version, /^\d+\.\d+\.\d+/u);
1468
+ const commandNames = ["sources", "ls", "latest", "sample", "tree", "search", "show", "stats", "query", "shell", "export", "tui", "help", "agent"];
1469
+ assert.deepEqual(Object.keys(contract.commands).sort(), [...commandNames].sort());
1470
+ for (const name of commandNames) {
1471
+ const command = contract.commands[name];
1472
+ assert.equal(command.name, name);
1473
+ assert.ok(command.summary.length > 0, `${name} is missing a summary`);
1474
+ assert.ok(command.usage.startsWith(`cchistory-lite ${name}`), `${name} usage must start with the command line`);
1475
+ assert.ok(Array.isArray(command.flags), `${name} flags must be an array`);
1476
+ }
1477
+ assert.deepEqual(contract.exit_codes.map((entry) => entry.code).sort(), [0, 1, 2]);
1478
+ const envNames = contract.env.map((entry) => entry.name);
1479
+ for (const name of ["NO_COLOR", "FORCE_COLOR", "CCHISTORY_SHOW_RUNTIME_WARNINGS", "CCHISTORY_SCAN_GUARD"]) {
1480
+ assert.ok(envNames.includes(name), `contract env omits ${name}`);
1481
+ }
1482
+ // The documented guard numbers are the runtime constants, not copies.
1483
+ const guard = contract.cost_model.scan_guard;
1484
+ assert.equal(guard.light_scan_memory_multiplier, LIGHT_SCAN_MEMORY_MULTIPLIER);
1485
+ assert.equal(guard.full_scan_memory_multiplier, FULL_SCAN_MEMORY_MULTIPLIER);
1486
+ assert.equal(guard.warn_available_fraction, SCAN_GUARD_WARN_AVAILABLE_FRACTION);
1487
+ assert.equal(guard.refuse_available_fraction, SCAN_GUARD_REFUSE_AVAILABLE_FRACTION);
1488
+ assert.equal(guard.lock_wait_ms, SCAN_LOCK_WAIT_MS);
1489
+ assert.equal(guard.watchdog_floor.min_floor_bytes, SCAN_WATCHDOG_MIN_FLOOR_BYTES);
1490
+ assert.equal(guard.watchdog_floor.total_floor_fraction, SCAN_WATCHDOG_TOTAL_FLOOR_FRACTION);
1491
+ assert.deepEqual(guard.kill_switch, { env: "CCHISTORY_SCAN_GUARD", value: "0" });
1492
+ assert.deepEqual([...guard.error_codes].sort(), ["scan_guard_aborted", "scan_guard_refused"]);
1493
+ assert.equal(contract.cost_model.heap_ceiling.min_old_space_mib, MIN_OLD_SPACE_MIB);
1494
+ assert.equal(contract.cost_model.heap_ceiling.max_old_space_mib, MAX_OLD_SPACE_MIB);
1495
+ assert.equal(contract.trust_model.content_trust, "untrusted_history");
1496
+ const schemaIds = contract.output_schemas.map((entry) => entry.id);
1497
+ for (const id of [
1498
+ "cchistory-lite/v2",
1499
+ "cchistory-lite-canonical/v1",
1500
+ "cchistory-lite-query/v2",
1501
+ "cchistory-lite-query-result/v2",
1502
+ "cchistory-lite-error/v1",
1503
+ "cchistory-lite-export/v1",
1504
+ "cchistory-lite-agent/v1",
1505
+ ]) {
1506
+ assert.ok(schemaIds.includes(id), `contract output_schemas omits ${id}`);
1507
+ }
1508
+ assert.equal(contract.docs.agent_guide, "docs/guide/for-agents.md");
1509
+ assert.equal(contract.docs.cli_guide, "docs/guide/lite.md");
1510
+ assert.equal(contract.docs.skill, "skills/using-cchistory-lite/SKILL.md");
1511
+ });
1512
+ test("Lite CLI agent contract satisfies its shipped JSON schema structurally", async () => {
1513
+ const captured = captureIo(repoRoot, undefined, {
1514
+ scan: async () => {
1515
+ throw new Error("agent must not scan");
1516
+ },
1517
+ });
1518
+ assert.equal(await runLiteCli(["agent"], captured.io), 0);
1519
+ const contract = JSON.parse(captured.stdout.join(""));
1520
+ const schema = JSON.parse(await readFile(path.join(repoRoot, "schemas", "cchistory-lite-agent-v1.schema.json"), "utf8"));
1521
+ for (const key of schema.required) {
1522
+ assert.ok(key in contract, `contract is missing required key ${key}`);
1523
+ }
1524
+ assert.equal(contract.schema, schema.properties.schema.const);
1525
+ assert.equal(contract.kind, schema.properties.kind.const);
1526
+ const commands = contract.commands;
1527
+ assert.deepEqual(Object.keys(commands).sort(), [...schema.properties.commands.required].sort());
1528
+ for (const [name, command] of Object.entries(commands)) {
1529
+ for (const key of schema.$defs.command.required) {
1530
+ assert.ok(key in command, `command ${name} is missing ${key}`);
1531
+ }
1532
+ for (const flag of command.flags) {
1533
+ assert.ok(schema.$defs.flag.properties.kind.enum.includes(flag.kind), `command ${name} has a flag with unknown kind ${flag.kind}`);
1534
+ }
1535
+ }
1536
+ const exitCodes = contract.exit_codes.map((entry) => entry.code);
1537
+ const allowedCodes = schema.properties.exit_codes.items.properties.code.enum;
1538
+ assert.deepEqual(exitCodes.sort(), [...allowedCodes].sort());
1539
+ assert.equal(contract.trust_model.content_trust, schema.properties.trust_model.properties.content_trust.const);
1540
+ const docs = contract.docs;
1541
+ assert.equal(docs.agent_guide, schema.properties.docs.properties.agent_guide.const);
1542
+ assert.equal(docs.cli_guide, schema.properties.docs.properties.cli_guide.const);
1543
+ assert.equal(docs.skill, schema.properties.docs.properties.skill.const);
1544
+ });
1545
+ test("Lite CLI agent contract flags match the parser in both directions", async () => {
1546
+ const snapshot = await getCodexSnapshot();
1547
+ const project = snapshot.listProjects()[0];
1548
+ const session = snapshot.listResolvedSessions()[0];
1549
+ assert.ok(project && session);
1550
+ const contract = buildAgentContract("0.0.0-test");
1551
+ const globalFlags = new Set(contract.global_flags.map((flag) => flag.name));
1552
+ const universe = new Set(globalFlags);
1553
+ for (const command of Object.values(contract.commands)) {
1554
+ for (const flag of command.flags)
1555
+ universe.add(flag.name);
1556
+ }
1557
+ // The parser's full flag vocabulary; like the help test's knownFlags, drift
1558
+ // here must be reflected in the contract before this audit can pass.
1559
+ const parserFlags = [
1560
+ "--source-root", "--source", "--limit-files", "--limit", "--offset", "--project", "--by",
1561
+ "--format", "--out", "--dir", "--request", "--safe", "--json", "--all", "--no-dir",
1562
+ "--help", "--version",
1563
+ ];
1564
+ assert.deepEqual([...universe].sort(), [...parserFlags].sort());
1565
+ const tails = {
1566
+ sources: [],
1567
+ ls: ["sessions"],
1568
+ latest: ["sessions", "1"],
1569
+ sample: ["1"],
1570
+ tree: ["projects"],
1571
+ search: ["mock"],
1572
+ show: ["session", session.id],
1573
+ stats: [],
1574
+ query: ["--request", "-"],
1575
+ shell: [],
1576
+ export: ["--format", "jsonl", "--out", "-"],
1577
+ tui: [],
1578
+ help: [],
1579
+ agent: [],
1580
+ };
1581
+ const flagArgs = (name) => {
1582
+ switch (name) {
1583
+ case "--source-root": return [name, `codex=${codexRoot}`];
1584
+ case "--source": return [name, "codex"];
1585
+ case "--limit-files": return [name, "4"];
1586
+ case "--limit": return [name, "1"];
1587
+ case "--offset": return [name, "0"];
1588
+ case "--project": return [name, project.project_id];
1589
+ case "--by": return [name, "source"];
1590
+ case "--format": return [name, "jsonl"];
1591
+ case "--out": return [name, "-"];
1592
+ case "--dir": return [name, repoRoot];
1593
+ case "--request": return [name, "-"];
1594
+ default: return [name];
1595
+ }
1596
+ };
1597
+ const run = async (argv) => {
1598
+ const captured = captureIo(repoRoot, async () => 0, {
1599
+ scan: async () => snapshot,
1600
+ readStdin: async () => `${JSON.stringify({
1601
+ schema: "cchistory-lite-query/v2",
1602
+ operations: [{ id: "s", kind: "list", collection: "sessions", limit: 1 }],
1603
+ })}\n`,
1604
+ readLine: async () => null,
1605
+ });
1606
+ return runLiteCli(argv, captured.io);
1607
+ };
1608
+ for (const [name, command] of Object.entries(contract.commands)) {
1609
+ const tail = tails[name];
1610
+ if (name === "help") {
1611
+ // help renders before option validation, so every known flag is accepted
1612
+ // and ignored; the rejection direction does not apply to it.
1613
+ for (const flag of universe) {
1614
+ assert.equal(await run([name, ...tail, ...flagArgs(flag)]), 0, `help must accept ${flag}`);
1615
+ }
1616
+ assert.equal(await run([name, ...tail, "--json=canonical"]), 0, "help must accept --json=canonical");
1617
+ continue;
1618
+ }
1619
+ const accepted = new Set([...globalFlags, ...command.flags.map((flag) => flag.name)]);
1620
+ for (const flag of universe) {
1621
+ const argv = tail.includes(flag) ? [name, ...tail] : [name, ...tail, ...flagArgs(flag)];
1622
+ const code = await run(argv);
1623
+ if (accepted.has(flag)) {
1624
+ assert.equal(code, 0, `${name} must accept ${flag} (argv: ${argv.join(" ")})`);
1625
+ }
1626
+ else {
1627
+ assert.equal(code, 2, `${name} must reject ${flag} (argv: ${argv.join(" ")})`);
1628
+ }
1629
+ }
1630
+ const canonicalAccepted = command.flags.some((flag) => flag.name === "--json" && flag.values?.includes("canonical"));
1631
+ const canonicalArgv = [name, ...tail, "--json=canonical"];
1632
+ assert.equal(await run(canonicalArgv), canonicalAccepted ? 0 : 2, `${name} ${canonicalAccepted ? "must accept" : "must reject"} --json=canonical`);
1633
+ }
1634
+ });
1635
+ test("Lite CLI agent skill and guide print the shipped docs", async () => {
1636
+ const noScan = {
1637
+ scan: async () => {
1638
+ throw new Error("agent must not scan");
1639
+ },
1640
+ };
1641
+ const skill = captureIo(repoRoot, undefined, noScan);
1642
+ assert.equal(await runLiteCli(["agent", "skill"], skill.io), 0);
1643
+ const skillDoc = await readFile(path.join(repoRoot, "skills", "using-cchistory-lite", "SKILL.md"), "utf8");
1644
+ assert.equal(skill.stdout.join(""), skillDoc);
1645
+ const guide = captureIo(repoRoot, undefined, noScan);
1646
+ assert.equal(await runLiteCli(["agent", "guide"], guide.io), 0);
1647
+ const guideDoc = await readFile(path.join(repoRoot, "docs", "guide", "for-agents.md"), "utf8");
1648
+ assert.equal(guide.stdout.join(""), guideDoc);
1649
+ const unknown = captureIo(repoRoot, undefined, noScan);
1650
+ assert.equal(await runLiteCli(["agent", "bogus"], unknown.io), 2);
1651
+ const unknownError = JSON.parse(unknown.stderr.join(""));
1652
+ assert.equal(unknownError.schema, "cchistory-lite-error/v1");
1653
+ assert.equal(unknownError.error.code, "invalid_usage");
1654
+ const extra = captureIo(repoRoot, undefined, noScan);
1655
+ assert.equal(await runLiteCli(["agent", "skill", "extra"], extra.io), 2);
1656
+ });
1657
+ test("Lite CLI help points agents at the agent contract and docs", async () => {
1658
+ const captured = captureIo(repoRoot);
1659
+ assert.equal(await runLiteCli(["help"], captured.io), 0);
1660
+ const help = captured.stdout.join("");
1661
+ assert.match(help, /cchistory-lite agent/);
1662
+ assert.match(help, /agent skill/);
1663
+ assert.match(help, /agent guide/);
1664
+ });
1238
1665
  function captureIo(cwd, spawnTui, overrides = {}) {
1239
1666
  const stdout = [];
1240
1667
  const stderr = [];