Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
Merge main, and keep the skip report out of the payload
KageBinarybb40e29433ad
diff --cc ix-cli/src/cli/__tests__/context-investigation.test.tsindex 26c50bd8,3aff7aa7..675a913d--- a/ix-cli/src/cli/__tests__/context-investigation.test.ts+++ b/ix-cli/src/cli/__tests__/context-investigation.test.ts@@@ -15,7 -15,6 +15,8 @@@ import type { EntityFacts } from "../eximport {buildBundle,diffInvestigations,+ listInvestigations,++ renderInvestigationList,loadInvestigation,mergeDiffOptions,saveInvestigation,@@@ -266,44 -419,4 +421,108 @@@ describe("ix context investigation statexpect(existsSync(join(home, "..", "escape.json"))).toBe(false);expect(existsSync(join(home, ".version-check.json"))).toBe(false);});++ // `ix context --list` enumerates saved investigations for discovery.+ // Without it, neither humans nor agents can see what they have stored —+ // the only path was reading the JSON files directly.+ describe("listInvestigations", () => {+ it("returns saved investigations newest-first", () => {+ saveInvestigation("widget-a", bundleWith([makeClaim("renders to DOM", 0.9)]));+ saveInvestigation("widget-b", bundleWith([makeClaim("mounts to DOM", 0.7)]));+ const list = listInvestigations();- expect(list.map((s) => s.id).sort()).toEqual(["widget-a", "widget-b"]);++ expect(list.saved.map((s) => s.id).sort()).toEqual(["widget-a", "widget-b"]);++ expect(list.skipped).toBe(0);+ // savedAt differs at least by a millisecond across the two writes; even+ // on the rare same-ms tie the id tiebreaker keeps order deterministic.- expect(list[0].id === "widget-a" || list[0].id === "widget-b").toBe(true);++ expect(list.saved[0].id === "widget-a" || list.saved[0].id === "widget-b").toBe(true);+ });++ it("skips files whose envelope or bundle does not match the contract", () => {+ saveInvestigation("good", bundleWith([makeClaim("renders to DOM", 0.9)]));+ const dir = investigationsDir();+ writeFileSync(join(dir, "corrupt-envelope.json"), JSON.stringify({ schema: "ix-investigation/9", bundle: {} }));+ writeFileSync(join(dir, "truncated.json"), "{not json");+ writeFileSync(join(dir, "tampered-body.json"), JSON.stringify({+ schema: "ix-investigation/1",+ id: "tampered-body",+ savedAt: "2026-01-01T00:00:00Z",+ bundle: { schema: "ix-context-bundle/1", generatedAt: "x", entities: "not-an-array" },+ }));+ writeFileSync(join(dir, "readme.md"), "not a state file");++ const list = listInvestigations();- expect(list.map((s) => s.id)).toEqual(["good"]);++ expect(list.saved.map((s) => s.id)).toEqual(["good"]);++ // Counted and handed back, not printed: the enumerator runs before the++ // renderer knows whether the caller asked for JSON.++ expect(list.skipped).toBe(3);+ // The three corrupt files do not poison the listing.+ expect(readdirSync(dir).filter((f) => f.endsWith(".json"))).toHaveLength(4);+ });+- it("returns an empty array when the investigations dir does not exist yet", () => {- expect(listInvestigations()).toEqual([]);++ it("returns an empty listing when the investigations dir does not exist yet", () => {++ expect(listInvestigations()).toEqual({ saved: [], skipped: 0 });+ saveInvestigation("first", bundleWith([makeClaim("renders to DOM", 0.9)]));- expect(listInvestigations()).toHaveLength(1);++ expect(listInvestigations().saved).toHaveLength(1);++ });++++ it("keeps the skip report off stdout in every machine format", () => {++ // json must stay parseable and llm must stay records, so the human++ // warning goes to stderr and the machine formats carry a count instead.++ saveInvestigation("good", bundleWith([makeClaim("renders to DOM", 0.9)]));++ const { saved } = listInvestigations();++++ const capture = (fn: () => void) => {++ const out: string[] = [];++ const err: string[] = [];++ const origLog = console.log;++ const origErr = console.error;++ console.log = (...a: unknown[]) => void out.push(a.join(" "));++ console.error = (...a: unknown[]) => void err.push(a.join(" "));++ try {++ fn();++ } finally {++ console.log = origLog;++ console.error = origErr;++ }++ return { out: out.join("\n"), err: err.join("\n") };++ };++++ const json = capture(() => renderInvestigationList(saved, 3, "json"));++ expect(() => JSON.parse(json.out)).not.toThrow();++ expect(JSON.parse(json.out)).toHaveLength(1);++ expect(json.err).toContain("3 saved investigation file(s)");++++ const llm = capture(() => renderInvestigationList(saved, 3, "llm"));++ expect(llm.out.split("\n")[0]).toBe("investigations total=1 skipped=3");++ // The count is the record's business; nothing is written beside it.++ expect(llm.err).toBe("");++++ // And with nothing skipped the field is simply absent.++ const clean = capture(() => renderInvestigationList(saved, 0, "llm"));++ expect(clean.out.split("\n")[0]).toBe("investigations total=1");++ expect(clean.err).toBe("");++ });++++ it("prints nothing itself, whatever it finds", () => {++ // The defect this replaces: the warning was a `renderWarning` inside the++ // enumerator, and every renderer in ui.ts writes to stdout. One corrupt++ // file therefore prepended a chalk-coloured prose line to the payload,++ // and `ix context --list --format json | jq` failed on it.++ saveInvestigation("good", bundleWith([makeClaim("renders to DOM", 0.9)]));++ writeFileSync(join(investigationsDir(), "truncated.json"), "{not json");++++ const lines: string[] = [];++ const origLog = console.log;++ const origErr = console.error;++ console.log = (...a: unknown[]) => void lines.push(a.join(" "));++ console.error = (...a: unknown[]) => void lines.push(a.join(" "));++ try {++ listInvestigations();++ } finally {++ console.log = origLog;++ console.error = origErr;++ }++ expect(lines).toEqual([]);+ });+ });});diff --cc ix-cli/src/cli/commands/context.tsindex cc402742,a2d7b846..34a4fb23--- a/ix-cli/src/cli/commands/context.ts+++ b/ix-cli/src/cli/commands/context.ts@@@ -15,7 -19,7 +19,7 @@@ import type} from "../../client/types.js";import { getEndpoint } from "../config.js";import { collectFacts, type EntityFacts } from "../explain/facts.js";--import { printLlmLines } from "../llm.js";++import { llmLine, printLlmLines } from "../llm.js";import { parsePickOption } from "../options.js";import { resolveFileOrEntity } from "../resolve.js";import { createStaleProbe } from "../stale.js";@@@ -143,14 -139,6 +141,19 @@@ export function registerContextCommand(renderSavedInvestigation(opts.resume, opts.format);return;}+ if (opts.list) {- if (opts.save || opts.diff) {- renderWarning("--list cannot be combined with --save or --diff.");++ if (opts.save || opts.diff || opts.resume) {++ // A refusal exits non-zero, the way `refuseInvestigation` does two++ // functions down and the way the sibling commands do: a warning with++ // a success status tells a script the listing it never got was fine.++ renderWarning("--list cannot be combined with --save, --diff or --resume.");++ process.exitCode = 1;+ return;+ }- renderInvestigationList(listInvestigations(), opts.format);++ const listed = listInvestigations();++ renderInvestigationList(listed.saved, listed.skipped, opts.format);+ return;+ }if (opts.diff) {const saved = loadInvestigation(opts.diff);if (!saved) return;@@@ -370,141 -358,17 +373,151 @@@ export function mergeDiffOptions};}+/**+ * Enumerate every saved investigation under IX_HOME/investigations.+ *- * Mirrors the read-side validation `loadInvestigation` performs on a single- * file (envelope + bundle.safeParse) so a corrupt or version-skewed file is- * skipped silently rather than poison the listing — but a corrupt file is- * still surfaced through a single warning so the operator can prune it.++ * Validated with `savedInvestigationSchema` — the same contract the write side++ * and `loadInvestigation` enforce — rather than a hand-rolled envelope check++ * beside it. A file that fails it is skipped and counted; the count is++ * returned, not printed, because this runs before the renderer knows which++ * format was asked for.+ *- * Determinism: results are sorted newest-first by `savedAt`, falling back to- * the sanitized `id` so two files saved in the same millisecond still have a- * stable order across runs.++ * Determinism: newest first by `savedAt`, falling back to the id so two files++ * saved in the same millisecond still order stably across runs.+ */- export function listInvestigations(): SavedInvestigation[] {++export function listInvestigations(): { saved: SavedInvestigation[]; skipped: number } {+ const dir = investigationDir();- if (!existsSync(dir)) return [];++ if (!existsSync(dir)) return { saved: [], skipped: 0 };+ const entries = readdirSync(dir).filter((f) => f.endsWith(".json"));+ const out: SavedInvestigation[] = [];+ let skipped = 0;+ for (const file of entries) {- const filePath = join(dir, file);- let parsed: unknown;++ let raw: unknown;++ // Scoped to the read and the parse, as in `loadInvestigation`: they are the++ // only calls here that throw.+ try {- parsed = JSON.parse(readFileSync(filePath, "utf8"));++ raw = JSON.parse(readFileSync(join(dir, file), "utf8"));+ } catch {+ skipped += 1;+ continue;+ }- if (- !parsed ||- typeof parsed !== "object" ||- (parsed as { schema?: unknown }).schema !== "ix-investigation/1" ||- !(parsed as { bundle?: unknown }).bundle- ) {- skipped += 1;- continue;- }- // Validate the body's contract matches the same versioned schema the- // write side enforces. We trust the original parsed JSON (cast as the- // SavedInvestigation type, exactly like loadInvestigation does on the- // happy path) instead of safeParse's data, because the on-disk envelope- // here was produced by saveInvestigation and the renderer only needs to- // forward the bundle through unchanged. That keeps the read-side- // validation contract symmetric with `loadInvestigation` without- // re-running the schema's structural narrowing (which would lose the- // richer record types claims/decisions/assets carry internally).- const bundleCheck = contextBundleSchema.safeParse((parsed as SavedInvestigation).bundle);- if (!bundleCheck.success) {++ const parsed = savedInvestigationSchema.safeParse(raw);++ if (!parsed.success) {+ skipped += 1;+ continue;+ }- out.push(parsed as SavedInvestigation);- }- if (skipped > 0) {- renderWarning(- `${skipped} saved investigation file(s) did not match the contract; skipped. Run \`ix context --resume <id>\` for a per-file report.`,- );++ // The validated value, not the raw parse — the same assertion++ // `loadInvestigation` makes, and for the same reason: it re-narrows the++ // open report arrays the schema leaves as records, and every field the++ // renderer dereferences has been checked by this point.++ out.push(parsed.data as unknown as SavedInvestigation);+ }- return out.sort((a, b) => {++ out.sort((a, b) => {+ if (a.savedAt !== b.savedAt) return a.savedAt < b.savedAt ? 1 : -1;+ return cmp(a.id, b.id);+ });++ return { saved: out, skipped };+}++/**+ * Render the saved investigations produced by `listInvestigations`.+ *- * The wire formats mirror the rest of the CLI: JSON is the full saved- * envelope so it round-trips through `--resume <id>`; LLM emits one- * metadata record per saved investigation; text prints a tabular- * summary with truncation/savedAt/target so a human can choose what- * to resume or diff.++ * JSON stays the array of saved envelopes; llm emits a summary record and one++ * record per investigation; text prints the tabular summary.++ *++ * `skipped` is reported in each format's own terms, and never on stdout except++ * as a field. It used to be a `renderWarning` inside the enumerator — which is++ * `console.log` — so a single corrupt file prepended a chalk-coloured prose++ * line to the payload and `ix context --list --format json | jq` failed on it.++ * The human warning goes to stderr; the machine formats carry a count.+ */- function renderInvestigationList(items: SavedInvestigation[], format: string): void {++export function renderInvestigationList(++ items: SavedInvestigation[],++ skipped: number,++ format: string,++): void {++ if (skipped > 0 && format !== "llm") {++ // `console.error`, not `renderWarning`: every renderer in ui.ts writes to++ // stdout, which is exactly how this line used to end up inside the JSON a++ // caller was piping. Plain text rather than chalk — nothing else in this++ // file writes to stderr, and a colour code is not worth an import that++ // only this line needs.++ console.error(++ ` Warning ${skipped} saved investigation file(s) did not match the contract; skipped.` +++ " Run `ix context --resume <id>` for a per-file report.",++ );++ }+ if (format === "json") {+ console.log(JSON.stringify(items, null, 2));+ return;+ }+ if (format === "llm") {- if (items.length === 0) {- printLlmLines(["investigations total=0"]);- return;- }+ printLlmLines([- `investigations total=${items.length}`,++ // `skipped` is a field rather than a warning: it is the one thing about++ // the listing an agent cannot see from the records themselves.++ llmLine("investigations", { total: items.length, skipped: skipped || undefined }),+ ...items.map((s) =>- [- `investigation id=${s.id}`,- `saved_at=${s.savedAt}`,- `target=${s.bundle.target.name}`,- `target_kind=${s.bundle.target.kind}`,- `classification=${s.bundle.freshness.classification}`,- `stale=${s.bundle.freshness.stale}`,- `entities=${s.bundle.entities.length}`,- `relationships=${s.bundle.relationships.length}`,- `evidence=${s.bundle.evidence.length}`,- `truncated_entities=${s.bundle.truncation.entitiesTruncated}`,- `truncated_relationships=${s.bundle.truncation.relationshipsTruncated}`,- `truncated_evidence=${s.bundle.truncation.evidenceTruncated}`,- `truncated_chars=${s.bundle.truncation.charactersTruncated}`,- ].join(" "),++ llmLine("investigation", {++ id: s.id,++ saved_at: s.savedAt,++ target: s.bundle.target.name,++ target_kind: s.bundle.target.kind,++ classification: s.bundle.freshness.classification,++ stale: s.bundle.freshness.stale,++ entities: s.bundle.entities.length,++ relationships: s.bundle.relationships.length,++ evidence: s.bundle.evidence.length,++ truncated_entities: s.bundle.truncation.entitiesTruncated,++ truncated_relationships: s.bundle.truncation.relationshipsTruncated,++ truncated_evidence: s.bundle.truncation.evidenceTruncated,++ truncated_chars: s.bundle.truncation.charactersTruncated,++ }),+ ),+ ]);+ return;+ }++ if (items.length === 0) {+ renderNote("No saved investigations. Use `ix context <target> --save <id>` to create one.");+ return;+ }+ renderSection(`Saved investigations (${items.length})`);+ for (const s of items) {+ const b = s.bundle;+ console.log(` ${s.id}`);+ console.log(` target: ${b.target.name} (${b.target.kind})`);+ console.log(` saved_at: ${s.savedAt}`);+ console.log(` freshness: ${b.freshness.classification}`);+ console.log(+ ` counts: entities=${b.entities.length} relationships=${b.relationships.length} evidence=${b.evidence.length}`,+ );+ if (+ b.truncation.entitiesTruncated ||+ b.truncation.relationshipsTruncated ||+ b.truncation.evidenceTruncated ||+ b.truncation.charactersTruncated+ ) {+ console.log(+ ` truncated: entities=${b.truncation.entitiesTruncated} relationships=${b.truncation.relationshipsTruncated} evidence=${b.truncation.evidenceTruncated} chars=${b.truncation.charactersTruncated}`,+ );+ }+ }+ console.log();+ console.log(`Resume with: ix context --resume <id>`);+ console.log(`Diff with: ix context --diff <id>`);+}++ /**+ * Refuse a saved investigation: warn, and set a non-zero status so a scripted+ * `--resume`/`--diff` can tell a refusal from a successful render. The sibling+ * commands (config, init, map) already signal refusals this way.+ */+ function refuseInvestigation(message: string): undefined {+ renderWarning(message);+ process.exitCode = 1;+ return undefined;+ }+export function loadInvestigation(id: string): SavedInvestigation | undefined {const path = investigationPath(id);if (!existsSync(path)) {