diff --git a/README.md b/README.md index e82439a..8362661 100644 --- a/README.md +++ b/README.md @@ -376,6 +376,7 @@ Architecture rules live in a reviewed `.fixmap/policy.json` file. Every rule has - Its public API also exposes Explain, Compare, and Verify builders and result types, so another tool can compose the same workflow without shelling out to the CLI. - `fixmap annotate` writes a versioned `.fixmap/annotations.json` with stable content identities, file/symbol/service/contract scopes, optional owner and expiry, and rename/missing-target checks. Relevant notes retain the store fingerprint in Markdown, JSON, and compact agent reports. See the [candidate annotation guide](docs/annotations.md) for workflows, ownership boundaries, and interrupted-lock recovery. - The candidate MCP tool `fixmap_annotate` shares that store and its locking/validation. It requires an explicit `action`: `add` accepts `target`/`symbol` or `service`/`contract`, `note`, optional `owner`/`expires`, and local `repo`; `list` accepts `repo` and `format`; `remove` requires the exact annotation `id` and optional `repo`. Only add/remove writes files. The tool advertises mutation/destructive hints; those hints are not authorization, and agents must obtain the user's request before changing notes. Invalid or action-inapplicable fields fail before mutation. This candidate tool is not a claim that the published npm release already supports it. +- Preview: `fixmap outcome record|list|show|remove|calibrate|prune` and `fixmap dossier create|list|show|remove` save predicted-versus-edited outcomes and fingerprinted change dossiers under `.fixmap/outcomes/` and `.fixmap/dossiers/` with atomic writes, link refusal, `--redact` (free text stored as SHA-256), and age-based pruning. Calibration is report-only (`automaticWeightChanges: false`). The read-only MCP tools `fixmap_outcomes` and `fixmap_dossier` list and show them. See [outcomes and change dossiers](docs/outcomes-and-dossiers.md). - `.fixmap/policy.json` defines bounded, repository-owned dependency boundaries, required test changes, reviewer routing, and breaking-contract rules. Plan and Verify use the same evaluator and retain the exact policy fingerprint; Core can also compare deterministic architecture snapshots for new edges, cyclic components, boundary violations, and coupling growth. - Historical Core APIs resolve refs to immutable commits and compare exact Git-blob architecture snapshots without checking out a branch, moving `HEAD`, or writing into the worktree. - The opt-in local sensitive-data evidence provider emits provenance-marked credential/token/PII/payment indicators and structural proximity to logging/network/storage/analytics sinks. It never copies detected values or snippets and explicitly labels every result as low-confidence, incomplete evidence rather than a taint or security proof. diff --git a/docs/outcomes-and-dossiers.md b/docs/outcomes-and-dossiers.md new file mode 100644 index 0000000..5be24e2 --- /dev/null +++ b/docs/outcomes-and-dossiers.md @@ -0,0 +1,81 @@ +# Outcomes and change dossiers (preview) + +Preview: these commands may change before v0.10.0. + +FixMap can save two kinds of local record after a change is done. Both live inside the +repository, one JSON file per record, and nothing leaves the machine. + +| Record | Directory | Command | MCP (read-only) | +| --- | --- | --- | --- | +| Outcome | `.fixmap/outcomes/` | `fixmap outcome record\|list\|show\|remove\|calibrate\|prune` | `fixmap_outcomes` (list, show, calibrate) | +| Change dossier | `.fixmap/dossiers/` | `fixmap dossier create\|list\|show\|remove` | `fixmap_dossier` (list, show) | + +## Outcomes + +An outcome record keeps what a saved plan predicted (`contextFiles`) next to the paths that were +actually edited, the commands that ran, and who judged the task. + +```sh +fixmap plan --issue "Fix login redirect" --format json --output plan.json +# ... make the change ... +fixmap outcome record --report plan.json --working-tree \ + --command-result test-result.json --assessment agent --status succeeded +fixmap outcome calibrate +``` + +- `--diff ` or `--working-tree [--include-untracked]` is required: it is where the edited paths come from. +- `--command-result ` (repeatable) takes one object or an array. Each entry is either a + `fixmap sandbox` result or `{ "command", "status", "evidence"?, "relatedPaths"? }` with status + `passed`, `failed`, `timeout`, `crashed`, or `unavailable`. +- `--assessment human|agent|external|unassessed` and `--status succeeded|failed|partial|unknown` + record who judged the task. A passing command is never treated as task success. + +`fixmap outcome calibrate` reports precision (predicted paths that were edited), recall (edited +paths that were predicted), misses, false positives, and command and assessment counts across every +stored record. It is a report. Ranking weights never change automatically, and the output always +says `automaticWeightChanges: false`. + +## Change dossiers + +```sh +fixmap dossier create --report plan.json --task "Fix login redirect" \ + --diff main...HEAD --pr https://github.com/owner/repo/pull/12 --commit +``` + +A dossier links the request text and its SHA-256, the report and Impact Graph fingerprints, the +report's ADR references, the diff's changed paths, command results, and commit/PR identifiers. +The record carries a content fingerprint; a hand-edited file fails validation and is reported. + +## Privacy: `--redact` + +`--redact` stores `sha256:` in place of free text: + +- `outcome record`: the assessment reason and each command's evidence. +- `dossier create`: the task text (`request.summary`). + +Paths, commands, and fingerprints are kept, since calibration needs them. Outcome records never +store task text; the task id defaults to `plan-` unless you +pass `--task-id`. + +## Retention: `prune` + +```sh +fixmap outcome prune --older-than 90 +``` + +deletes outcome records recorded more than 90 days ago. Malformed files are listed, never deleted. +`fixmap outcome remove ` and `fixmap dossier remove ` delete a single record. + +## Safety and recovery + +- Writes go to a temp file and are renamed into place, so a reader never sees half a record. +- `.fixmap`, `.fixmap/outcomes`, and `.fixmap/dossiers` must be real directories: links and + junctions are refused. Record files and locks must be regular files with one link. +- Record ids are letters, digits, `.`, `_`, and `-` only, so an id cannot name a path outside the store. +- Writers take `.fixmap/outcomes.lock` or `.fixmap/dossiers.lock`. A second writer waits about a + second, then stops. FixMap never takes over a lock, however old: if a writer was interrupted, + confirm no FixMap process is running, then delete the lock file by hand. +- `list` and `calibrate` report unreadable or invalid files under "Unreadable stored files" (or + `problems` in JSON) and keep going. +- Decide whether to commit these directories. They are plain JSON and reviewable; add them to + `.gitignore` if they should stay on one machine. diff --git a/packages/cli/src/cli-runner.ts b/packages/cli/src/cli-runner.ts index 66feda9..de31e41 100644 --- a/packages/cli/src/cli-runner.ts +++ b/packages/cli/src/cli-runner.ts @@ -118,6 +118,8 @@ Usage: fixmap sandbox --request sandbox.json --execute-declared-command fixmap watch --report plan.json --repo . fixmap annotate src/auth/token.ts --note "Do not refactor; external contract" + fixmap outcome record --report plan.json --working-tree --assessment agent --status succeeded + fixmap dossier create --report plan.json --task "Fix login" --diff main...HEAD --pr fixmap features fixmap setup [--agent claude|cursor|copilot|agents|all] [--repo ] fixmap mcp [--repo ] @@ -143,6 +145,8 @@ Commands: runtime Preview: Map redaction-reviewed runtime evidence to exact files sandbox Preview: Run one explicitly consented command in an isolated container watch Recheck working-tree drift and impact whenever edits change + outcome Preview: Save predicted-versus-edited outcomes locally and calibrate them + dossier Preview: Save a fingerprinted change dossier for a finished change annotate Attach reviewable tribal knowledge to files, symbols, services, or contracts features List every FixMap capability and its command setup Preview workflows, or explicitly install /fixmap for coding agents @@ -238,6 +242,11 @@ export async function runCli(args: string[], dependencies: CliDependencies = {}) return 0; } + if (args[0] === "outcome" || args[0] === "dossier") { + const module = await import("./outcome-command.js"); + return (args[0] === "outcome" ? module.runOutcomeCommand : module.runDossierCommand)(args.slice(1), { stdout, stderr }); + } + if (args[0] === "annotate") { const module = await import("./annotation-command.js"); return module.runAnnotateCommand(args.slice(1), { stdout, stderr }); diff --git a/packages/cli/src/mcp.ts b/packages/cli/src/mcp.ts index 70326eb..de5f53f 100644 --- a/packages/cli/src/mcp.ts +++ b/packages/cli/src/mcp.ts @@ -1,5 +1,6 @@ import { readFileSync } from "node:fs"; import { ANNOTATION_TOOL, runAnnotationTool } from "./annotation-tool.js"; +import { DOSSIER_TOOL, OUTCOMES_TOOL, runDossierTool, runOutcomesTool } from "./record-tools.js"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { Server } from "@modelcontextprotocol/sdk/server/index.js"; @@ -516,11 +517,13 @@ export function createFixMapMcpServer( const server = new Server({ name: "fixmap", version: readVersion() }, { capabilities: { tools: {} } }); server.setRequestHandler(ListToolsRequestSchema, async () => ({ - tools: [PLAN_TOOL, CONTEXT_TOOL, GRAPH_TOOL, CHANGE_SCOPE_TOOL, CAPABILITY_TOOL, WORKSPACE_TOOL, ASK_TOOL, MIGRATION_TOOL, REVERSE_DOCS_TOOL, HISTORY_TOOL, SUPPLY_CHAIN_TOOL, RUNTIME_TOOL, VERIFY_TOOL, EXPLAIN_TOOL, COMPARE_TOOL, DOCTOR_TOOL, ANNOTATION_TOOL] + tools: [PLAN_TOOL, CONTEXT_TOOL, GRAPH_TOOL, CHANGE_SCOPE_TOOL, CAPABILITY_TOOL, WORKSPACE_TOOL, ASK_TOOL, MIGRATION_TOOL, REVERSE_DOCS_TOOL, HISTORY_TOOL, SUPPLY_CHAIN_TOOL, RUNTIME_TOOL, VERIFY_TOOL, EXPLAIN_TOOL, COMPARE_TOOL, DOCTOR_TOOL, ANNOTATION_TOOL, OUTCOMES_TOOL, DOSSIER_TOOL] })); server.setRequestHandler(CallToolRequestSchema, async (request) => { if (request.params.name === ANNOTATION_TOOL.name) return runAnnotationTool(request.params.arguments, defaultRepo); + if (request.params.name === OUTCOMES_TOOL.name) return runOutcomesTool(request.params.arguments, defaultRepo); + if (request.params.name === DOSSIER_TOOL.name) return runDossierTool(request.params.arguments, defaultRepo); if (request.params.name === CONTEXT_TOOL.name || request.params.name === GRAPH_TOOL.name) { const kind = request.params.name === CONTEXT_TOOL.name ? "context" : "graph"; const parsed = parseAnalysisToolArguments(request.params.arguments ?? {}, kind); diff --git a/packages/cli/src/outcome-command.ts b/packages/cli/src/outcome-command.ts new file mode 100644 index 0000000..448b10d --- /dev/null +++ b/packages/cli/src/outcome-command.ts @@ -0,0 +1,412 @@ +import { createHash, randomBytes } from "node:crypto"; +import { realpath } from "node:fs/promises"; +import { basename, isAbsolute, relative, resolve } from "node:path"; +import { + buildChangeDossier, + createGraphIdentity, + createOutcomeRecord, + deleteStoredDossier, + deleteStoredOutcome, + pruneStoredOutcomes, + readStoredDossier, + readStoredDossiers, + readStoredOutcome, + readStoredOutcomes, + saveStoredDossier, + saveStoredOutcome, + scanRepo, + summarizeOutcomeCalibration, + validateFixMapReport, + type ChangeDossier, + type ChangeDossierInput, + type FixMapReport, + type OutcomeCalibration, + type OutcomeRecord, + type StoredRecordProblem, + type TestOutcomeStatus +} from "@aryam/fixmap-core"; +import { describeInputReadError, readDecodedTextFile } from "./decode-input.js"; + +export const OUTCOME_USAGE = `Usage: + fixmap outcome record --report (--diff | --working-tree [--include-untracked]) + [--command-result ...] [--assessment human|agent|external|unassessed] + [--status succeeded|failed|partial|unknown] [--reason ] [--task-id ] [--redact] + fixmap outcome list [--format markdown|json] + fixmap outcome show [--format markdown|json] + fixmap outcome remove + fixmap outcome calibrate [--format markdown|json] + fixmap outcome prune --older-than + +Saves what a plan predicted next to what was actually edited, one file per record under +.fixmap/outcomes/. Calibration is a visible report only: it never changes ranking weights. +--redact stores the SHA-256 of the assessment reason and command evidence instead of their text. +Every command also accepts --repo (default current directory). +`; + +export const DOSSIER_USAGE = `Usage: + fixmap dossier create --report --task [--diff | --working-tree [--include-untracked]] + [--command-result ...] [--pr ] [--commit ] [--redact] + fixmap dossier list [--format markdown|json] + fixmap dossier show [--format markdown|json] + fixmap dossier remove + +Saves a fingerprinted change dossier (request, plan and graph references, ADRs, diff, command +results, commit/PR identifiers) under .fixmap/dossiers/. --redact stores the task text as its SHA-256. +Every command also accepts --repo (default current directory). +`; + +/** --command-result accepts one object or an array: a FixMap sandbox result, or {command, status, evidence?, relatedPaths?}. */ +type CommandResult = { command: string; status: TestOutcomeStatus; evidence: string; relatedPaths: string[] }; + +export type RecordCommandIo = { + stdout: (text: string) => void; + stderr: (text: string) => void; + now?: () => Date; + /** Test seam: resolve changed paths without scanning. */ + changedFiles?: (repoRoot: string, change: ChangeSource) => Promise; +}; + +type ChangeSource = { diffSpec?: string; workingTree?: boolean; includeUntracked?: boolean }; +type Parsed = { action: string; positional: string[]; values: Map; flags: Set }; + +const VALUE_FLAGS = new Set(["--repo", "--report", "--diff", "--command-result", "--assessment", "--status", "--reason", + "--task-id", "--task", "--pr", "--commit", "--format", "--older-than"]); +const BOOLEAN_FLAGS = new Set(["--working-tree", "--include-untracked", "--redact"]); +const REPEATABLE = new Set(["--command-result"]); +const ACTION_OPTIONS: Record = { + "outcome record": ["--repo", "--report", "--diff", "--working-tree", "--include-untracked", "--command-result", "--assessment", "--status", "--reason", "--task-id", "--redact"], + "outcome list": ["--repo", "--format"], + "outcome show": ["--repo", "--format"], + "outcome remove": ["--repo"], + "outcome calibrate": ["--repo", "--format"], + "outcome prune": ["--repo", "--older-than"], + "dossier create": ["--repo", "--report", "--task", "--diff", "--working-tree", "--include-untracked", "--command-result", "--pr", "--commit", "--redact"], + "dossier list": ["--repo", "--format"], + "dossier show": ["--repo", "--format"], + "dossier remove": ["--repo"] +}; +const ASSESSMENT_SOURCE = { human: "human", agent: "agent", external: "external-system", unassessed: "unassessed" } as const; +const STATUSES = ["passed", "failed", "timeout", "crashed", "unavailable"] as const; + +export function runOutcomeCommand(args: string[], io: RecordCommandIo): Promise { return run("outcome", OUTCOME_USAGE, args, io); } +export function runDossierCommand(args: string[], io: RecordCommandIo): Promise { return run("dossier", DOSSIER_USAGE, args, io); } + +async function run(group: "outcome" | "dossier", usage: string, args: string[], io: RecordCommandIo): Promise { + if (args.length === 0 || args[0] === "--help" || args[0] === "-h" || args.includes("--help") || args.includes("-h")) { + io.stdout(usage); + return args.length === 0 ? 1 : 0; + } + const fail = (message: string) => { io.stderr(`${message}\n\n${usage}`); return 1; }; + const parsed = parseArgs(args); + if (typeof parsed === "string") return fail(parsed); + const allowed = ACTION_OPTIONS[`${group} ${parsed.action}`]; + if (!allowed) return fail(`Unknown ${group} action: ${parsed.action}`); + for (const flag of [...parsed.values.keys(), ...parsed.flags]) { + if (!allowed.includes(flag)) return fail(`${flag} does not apply to ${group} ${parsed.action}.`); + } + const takesId = parsed.action === "show" || parsed.action === "remove"; + if (takesId ? parsed.positional.length !== 1 : parsed.positional.length > 0) { + return fail(takesId ? `${group} ${parsed.action} needs exactly one record id.` : `Unexpected argument: ${parsed.positional[0]}`); + } + const format = one(parsed, "--format") ?? "markdown"; + if (format !== "markdown" && format !== "json") return fail("--format must be markdown or json."); + try { + const repoRoot = await realpath(resolve(one(parsed, "--repo") ?? process.cwd())); + const id = parsed.positional[0]!; + if (group === "outcome") { + switch (parsed.action) { + case "record": return await recordOutcome(repoRoot, parsed, io, fail); + case "list": return print(io, format, await readStoredOutcomes(repoRoot), renderOutcomeList); + case "show": return show(io, format, await readStoredOutcome(repoRoot, id), renderOutcome); + case "remove": await deleteStoredOutcome(repoRoot, id); io.stdout(`Removed .fixmap/outcomes/${id}.json.\n`); return 0; + case "calibrate": return calibrate(io, format, await readStoredOutcomes(repoRoot)); + default: return await prune(repoRoot, parsed, io, fail); + } + } + switch (parsed.action) { + case "create": return await createDossier(repoRoot, parsed, io, fail); + case "list": return print(io, format, await readStoredDossiers(repoRoot), renderDossierList); + case "show": return show(io, format, await readStoredDossier(repoRoot, id), renderDossier); + default: await deleteStoredDossier(repoRoot, id); io.stdout(`Removed .fixmap/dossiers/${id}.json.\n`); return 0; + } + } catch (error) { + io.stderr(`${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } +} + +async function recordOutcome(repoRoot: string, parsed: Parsed, io: RecordCommandIo, fail: (message: string) => number): Promise { + const assessmentName = one(parsed, "--assessment") ?? "unassessed"; + if (!(assessmentName in ASSESSMENT_SOURCE)) return fail("--assessment must be human, agent, external, or unassessed."); + const source = ASSESSMENT_SOURCE[assessmentName as keyof typeof ASSESSMENT_SOURCE]; + const status = one(parsed, "--status") ?? (source === "unassessed" ? "unknown" : undefined); + if (!status) return fail("--status succeeded|failed|partial|unknown is required with an assessment source."); + if (!["succeeded", "failed", "partial", "unknown"].includes(status)) return fail("--status must be succeeded, failed, partial, or unknown."); + if (source === "unassessed" && status !== "unknown") return fail("An unassessed outcome can only have --status unknown."); + const change = changeSource(parsed, true); + if (typeof change === "string") return fail(change); + const plan = loadReport(one(parsed, "--report")); + if (typeof plan === "string") return fail(plan); + const redact = parsed.flags.has("--redact"); + const commands = loadCommandResults(parsed.values.get("--command-result") ?? []); + const now = io.now?.() ?? new Date(); + const reason = one(parsed, "--reason") ?? (source === "unassessed" ? "Not assessed." : `Assessed by ${assessmentName}.`); + const record = createOutcomeRecord({ + id: newId("outcome", now), + taskId: one(parsed, "--task-id") ?? `plan-${plan.hash.slice(0, 16)}`, + repositoryIdentity: repositoryIdentity(repoRoot), + planFingerprint: `sha256:${plan.hash}`, + recordedAt: now.toISOString(), + predictedPaths: plan.report.contextFiles.map((file) => file.path), + editedPaths: await resolveChangedFiles(repoRoot, change!, io), + testOutcomes: commands.map((entry) => ({ + command: entry.command, + status: entry.status, + relatedPaths: entry.relatedPaths, + evidence: redact ? sha256Text(entry.evidence) : entry.evidence + })), + taskAssessment: { status: status as OutcomeRecord["taskAssessment"]["status"], source, reason: redact ? sha256Text(reason) : reason } + }); + await saveStoredOutcome(repoRoot, record); + const calibration = summarizeOutcomeCalibration({ outcomeStoreVersion: 1, records: [record] }).perRecord[0]!; + io.stdout(`Saved .fixmap/outcomes/${record.id}.json: ${calibration.correctlyPredicted.length} of ${record.editedPaths.length} edited ` + + `path(s) were predicted; ${calibration.predictedButUnedited.length} predicted path(s) were not edited.${redact ? " Free text was redacted to SHA-256." : ""}\n`); + return 0; +} + +async function createDossier(repoRoot: string, parsed: Parsed, io: RecordCommandIo, fail: (message: string) => number): Promise { + const task = one(parsed, "--task"); + if (!task) return fail("dossier create requires --task describing the request."); + const change = changeSource(parsed, false); + if (typeof change === "string") return fail(change); + const reportPath = one(parsed, "--report"); + const plan = loadReport(reportPath); + if (typeof plan === "string") return fail(plan); + const redact = parsed.flags.has("--redact"); + const commands = loadCommandResults(parsed.values.get("--command-result") ?? []); + const now = (io.now?.() ?? new Date()).toISOString(); + const commit = one(parsed, "--commit"); + const pullRequest = one(parsed, "--pr"); + let diff: ChangeDossierInput["diff"] = null; + if (change) { + const changedFiles = await resolveChangedFiles(repoRoot, change, io); + diff = { + sourceFingerprint: `sha256:${sha256(JSON.stringify({ change, changedFiles }))}`, + changedFiles, + ...(change.diffSpec ? { base: change.diffSpec } : { base: "HEAD", head: "working-tree" }) + }; + } + // repoRoot is a realpath (macOS /private/var, Windows 8.3 names), so compare against the report's realpath too. + const artifact = relative(repoRoot, await realpath(resolve(reportPath!))).replace(/\\/g, "/"); + const dossier = buildChangeDossier({ + id: newId("dossier", new Date(now)), + repositoryIdentity: repositoryIdentity(repoRoot), + createdAt: now, + updatedAt: now, + request: { summary: redact ? sha256Text(task) : task, sourceFingerprint: `sha256:${sha256(task)}` }, + assumptions: [], + plan: { + reportFingerprint: `sha256:${plan.hash}`, + graphFingerprint: `sha256:${sha256(JSON.stringify(plan.report.impact ?? null))}`, + ...(artifact && !artifact.startsWith("..") && !isAbsolute(artifact) ? { artifactPath: artifact } : {}) + }, + decisions: (plan.report.decisions ?? []).map((decision) => ({ id: decision.id, path: decision.path, sourceFingerprint: decision.sourceFingerprint })), + diff, + tests: commands.map((entry) => ({ command: entry.command, status: entry.status, evidenceFingerprint: `sha256:${sha256(entry.evidence)}`, relatedPaths: entry.relatedPaths })), + runtimeEvidence: [], + reviews: [], + releaseIdentifiers: { + ...(commit ? { commit } : {}), + ...(pullRequest ? { pullRequest } : {}) + } + }); + await saveStoredDossier(repoRoot, dossier); + io.stdout(`Saved .fixmap/dossiers/${dossier.id}.json (${dossier.fingerprint}).${redact ? " Task text was redacted to SHA-256." : ""}\n`); + return 0; +} + +async function prune(repoRoot: string, parsed: Parsed, io: RecordCommandIo, fail: (message: string) => number): Promise { + const raw = one(parsed, "--older-than"); + if (!raw || !/^\d{1,5}$/.test(raw)) return fail("outcome prune requires --older-than (a whole number of days, 0-99999)."); + const cutoff = new Date((io.now?.() ?? new Date()).getTime() - Number(raw) * 86_400_000); + const result = await pruneStoredOutcomes(repoRoot, cutoff); + io.stdout(`Removed ${result.removed.length} outcome record(s) recorded before ${cutoff.toISOString()}; kept ${result.kept}.\n` + + result.removed.map((id) => `- ${id}\n`).join("") + renderProblems(result.problems)); + return 0; +} + +function calibrate(io: RecordCommandIo, format: string, stored: { records: OutcomeRecord[]; problems: StoredRecordProblem[] }): number { + const calibration = summarizeOutcomeCalibration({ outcomeStoreVersion: 1, records: stored.records }); + if (format === "json") io.stdout(`${JSON.stringify({ ...calibration, problems: stored.problems }, null, 2)}\n`); + else io.stdout(renderCalibration(calibration) + renderProblems(stored.problems)); + return 0; +} + +function print(io: RecordCommandIo, format: string, stored: { records: T[]; problems: StoredRecordProblem[] }, render: (records: T[]) => string): number { + io.stdout(format === "json" ? `${JSON.stringify(stored, null, 2)}\n` : render(stored.records) + renderProblems(stored.problems)); + return 0; +} + +function show(io: RecordCommandIo, format: string, record: T, render: (record: T) => string): number { + io.stdout(format === "json" ? `${JSON.stringify(record, null, 2)}\n` : render(record)); + return 0; +} + +function parseArgs(args: string[]): Parsed | string { + const [action, ...rest] = args; + if (!action || action.startsWith("-")) return "Name an action first."; + const values = new Map(); + const flags = new Set(); + const positional: string[] = []; + for (let index = 0; index < rest.length; index += 1) { + const raw = rest[index]!; + if (!raw.startsWith("--")) { positional.push(raw); continue; } + const separator = raw.indexOf("="); + const flag = separator === -1 ? raw : raw.slice(0, separator); + if (BOOLEAN_FLAGS.has(flag)) { + if (separator !== -1) return `${flag} does not take a value.`; + if (flags.has(flag)) return `Pass ${flag} only once.`; + flags.add(flag); + continue; + } + if (!VALUE_FLAGS.has(flag)) return `Unknown option: ${raw}`; + if (values.has(flag) && !REPEATABLE.has(flag)) return `Pass ${flag} only once.`; + const inline = separator === -1 ? undefined : raw.slice(separator + 1); + const following = rest[index + 1]; + const value = inline ?? (following !== undefined && !following.startsWith("--") ? following : undefined); + if (inline === undefined && value !== undefined) index += 1; + if (!value?.trim()) return `${flag} requires a non-blank value.`; + values.set(flag, [...(values.get(flag) ?? []), value.trim()]); + } + return { action, positional, values, flags }; +} + +function changeSource(parsed: Parsed, required: boolean): ChangeSource | undefined | string { + const diffSpec = one(parsed, "--diff"); + const workingTree = parsed.flags.has("--working-tree"); + if (diffSpec && workingTree) return "Use either --diff or --working-tree, not both."; + if (parsed.flags.has("--include-untracked") && !workingTree) return "--include-untracked only applies with --working-tree."; + if (!diffSpec && !workingTree) return required ? "Provide --diff or --working-tree so FixMap can see what was actually edited." : undefined; + return diffSpec ? { diffSpec } : { workingTree: true, includeUntracked: parsed.flags.has("--include-untracked") }; +} + +function loadReport(path: string | undefined): { report: FixMapReport; hash: string } | string { + if (!path) return "Provide --report with the JSON report the change was planned from."; + let text: string; + try { + text = readDecodedTextFile(path); + } catch (error) { + return `Could not read "${path}": ${describeInputReadError(path, error)}`; + } + let candidate: unknown; + try { + candidate = JSON.parse(text); + } catch { + return `"${path}" is not a JSON FixMap report. Save one with: fixmap plan --issue "..." --format json --output plan.json`; + } + const loaded = validateFixMapReport(candidate, `"${path}"`); + if (!loaded.success) return loaded.message; + return { report: loaded.report, hash: sha256(text) }; +} + +function loadCommandResults(paths: string[]): CommandResult[] { + return paths.flatMap((path) => { + let candidate: unknown; + try { + candidate = JSON.parse(readDecodedTextFile(path)); + } catch (error) { + throw new Error(`Could not read command result "${path}": ${error instanceof SyntaxError ? "not valid JSON" : describeInputReadError(path, error)}`); + } + return (Array.isArray(candidate) ? candidate : [candidate]).map((entry, index) => commandResult(entry, `${path}[${index}]`)); + }); +} + +function commandResult(value: unknown, label: string): CommandResult { + const entry = value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; + if (typeof entry.command !== "string" || !entry.command.trim() || !STATUSES.includes(entry.status as TestOutcomeStatus)) { + throw new Error(`Command result ${label} needs a command and a status of ${STATUSES.join(", ")}.`); + } + const evidence = typeof entry.evidence === "string" && entry.evidence.trim() + ? entry.evidence + : entry.sandboxResultVersion === 1 + ? `sandbox ${String(entry.executionId)} exit ${String(entry.exitCode)} image ${String(entry.image)}` + : `${String(entry.status)} (from ${label})`; + const relatedPaths = Array.isArray(entry.relatedPaths) ? entry.relatedPaths : []; + if (!relatedPaths.every((path) => typeof path === "string")) throw new Error(`Command result ${label} relatedPaths must be strings.`); + return { command: entry.command, status: entry.status as TestOutcomeStatus, evidence: evidence.slice(0, 2_000), relatedPaths: relatedPaths as string[] }; +} + +async function resolveChangedFiles(repoRoot: string, change: ChangeSource, io: RecordCommandIo): Promise { + if (io.changedFiles) return io.changedFiles(repoRoot, change); + const repo = await scanRepo({ repoRoot, ...change, useCache: true }); + const unresolved = repo.diagnostics.find((diagnostic) => diagnostic.code === "diff-unavailable"); + if (unresolved) throw new Error(`${unresolved.message}\nFixMap needs a resolvable diff to record what was edited.`); + return repo.changedFiles; +} + +function repositoryIdentity(repoRoot: string): string { + const name = basename(repoRoot).replace(/[^A-Za-z0-9._-]/g, "-").replace(/^[^A-Za-z0-9]+/, "") || "repository"; + return createGraphIdentity({ workspace: "local", kind: "repository", key: name.slice(0, 100) }); +} + +function newId(prefix: string, now: Date): string { + return `${prefix}-${now.toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z")}-${randomBytes(4).toString("hex")}`; +} +function sha256(text: string): string { return createHash("sha256").update(text, "utf8").digest("hex"); } +function sha256Text(text: string): string { return `sha256:${sha256(text)}`; } +function one(parsed: Parsed, flag: string): string | undefined { return parsed.values.get(flag)?.[0]; } +function percent(value: number | null): string { return value === null ? "n/a" : `${(value * 100).toFixed(1)}%`; } + +function renderProblems(problems: StoredRecordProblem[]): string { + if (problems.length === 0) return ""; + return `\n## Unreadable stored files (${problems.length})\n\n${problems.map((problem) => `- ${problem.file}: ${problem.message}`).join("\n")}\n`; +} + +function renderOutcomeList(records: OutcomeRecord[]): string { + if (records.length === 0) return "# FixMap Outcomes\n\nNo outcome records found.\n"; + return `# FixMap Outcomes\n\n${records.map((record) => + `- ${record.id} (${record.recordedAt}): ${record.predictedPaths.length} predicted, ${record.editedPaths.length} edited, ` + + `task ${record.taskAssessment.status} (${record.taskAssessment.source})`).join("\n")}\n`; +} + +function renderOutcome(record: OutcomeRecord): string { + const list = (paths: string[]) => paths.length ? paths.map((path) => `- ${path}`).join("\n") : "- none"; + return [`# Outcome ${record.id}`, "", `Recorded: ${record.recordedAt}`, `Task: ${record.taskId}`, `Plan: ${record.planFingerprint}`, + `Assessment: ${record.taskAssessment.status} (${record.taskAssessment.source}): ${record.taskAssessment.reason}`, "", + "## Predicted paths", list(record.predictedPaths), "", "## Edited paths", list(record.editedPaths), "", "## Commands", + record.testOutcomes.length ? record.testOutcomes.map((test) => `- ${test.status}: ${test.command}`).join("\n") : "- none", ""].join("\n"); +} + +function renderCalibration(calibration: OutcomeCalibration): string { + const { totals } = calibration; + return [ + "# FixMap Outcome Calibration", "", + `Records: ${calibration.records}`, + `Precision: ${percent(calibration.precision)} (${totals.correctlyPredictedEdits} of ${totals.predictedPaths} predicted paths were edited)`, + `Recall: ${percent(calibration.recall)} (${totals.correctlyPredictedEdits} of ${totals.editedPaths} edited paths were predicted)`, + `Predicted but not edited: ${totals.predictedButUnedited}`, + `Edited but not predicted: ${totals.editedButUnpredicted}`, + `Commands: ${Object.entries(calibration.testOutcomes).map(([status, count]) => `${status} ${count}`).join(", ")}`, + `Task assessments: ${Object.entries(calibration.taskAssessments).map(([status, count]) => `${status} ${count}`).join(", ")}`, + "", + "Report only: ranking weights are never changed automatically (automaticWeightChanges: false).", "" + ].join("\n"); +} + +function renderDossierList(records: ChangeDossier[]): string { + if (records.length === 0) return "# FixMap Change Dossiers\n\nNo change dossiers found.\n"; + return `# FixMap Change Dossiers\n\n${records.map((record) => + `- ${record.id} (${record.createdAt}): ${record.request.summary.slice(0, 120)}`).join("\n")}\n`; +} + +function renderDossier(dossier: ChangeDossier): string { + const release = Object.entries(dossier.releaseIdentifiers).map(([key, value]) => `- ${key}: ${value}`); + return [`# Change dossier ${dossier.id}`, "", `Fingerprint: ${dossier.fingerprint}`, `Created: ${dossier.createdAt}`, + `Request: ${dossier.request.summary}`, `Plan report: ${dossier.plan.reportFingerprint}${dossier.plan.artifactPath ? ` (${dossier.plan.artifactPath})` : ""}`, + `Graph: ${dossier.plan.graphFingerprint}`, "", + "## Decisions", dossier.decisions.length ? dossier.decisions.map((entry) => `- ${entry.id}: ${entry.path}`).join("\n") : "- none", "", + "## Diff", dossier.diff ? `${dossier.diff.changedFiles.length} changed path(s)${dossier.diff.base ? ` against ${dossier.diff.base}` : ""}\n` + + dossier.diff.changedFiles.map((path) => `- ${path}`).join("\n") : "- not recorded", "", + "## Commands", dossier.tests.length ? dossier.tests.map((test) => `- ${test.status}: ${test.command}`).join("\n") : "- none", "", + "## Release identifiers", release.length ? release.join("\n") : "- none", ""].join("\n"); +} diff --git a/packages/cli/src/record-tools.ts b/packages/cli/src/record-tools.ts new file mode 100644 index 0000000..6a6cadd --- /dev/null +++ b/packages/cli/src/record-tools.ts @@ -0,0 +1,71 @@ +import { runDossierCommand, runOutcomeCommand } from "./outcome-command.js"; + +const PREVIEW = "Preview (may change before v0.10.0): "; + +export const OUTCOMES_TOOL = { + name: "fixmap_outcomes", + title: "FixMap outcomes", + description: `${PREVIEW}Read saved outcome records from .fixmap/outcomes/: list them, show one, or calibrate predicted versus edited paths across all of them. ` + + "Read-only; calibration never changes ranking weights. Record new outcomes with the fixmap outcome CLI.", + annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, + inputSchema: { + type: "object" as const, + properties: { + action: { type: "string", enum: ["list", "show", "calibrate"] }, + repo: { type: "string", description: "Local repository directory" }, + id: { type: "string", description: "Outcome record id (show only)" }, + format: { type: "string", enum: ["markdown", "json"] } + }, + required: ["action"], additionalProperties: false + } +}; + +export const DOSSIER_TOOL = { + name: "fixmap_dossier", + title: "FixMap change dossiers", + description: `${PREVIEW}Read saved change dossiers from .fixmap/dossiers/: list them or show one with its request, plan and graph fingerprints, ADRs, diff, commands, and commit/PR identifiers. ` + + "Read-only; create dossiers with the fixmap dossier CLI.", + annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, + inputSchema: { + type: "object" as const, + properties: { + action: { type: "string", enum: ["list", "show"] }, + repo: { type: "string", description: "Local repository directory" }, + id: { type: "string", description: "Change dossier id (show only)" }, + format: { type: "string", enum: ["markdown", "json"] } + }, + required: ["action"], additionalProperties: false + } +}; + +export function runOutcomesTool(value: unknown, defaultRepo: string) { + return runReadTool(value, defaultRepo, ["list", "show", "calibrate"], runOutcomeCommand); +} + +export function runDossierTool(value: unknown, defaultRepo: string) { + return runReadTool(value, defaultRepo, ["list", "show"], runDossierCommand); +} + +async function runReadTool( + value: unknown, + defaultRepo: string, + actions: string[], + command: typeof runOutcomeCommand +) { + const failure = (message: string) => ({ isError: true, content: [{ type: "text" as const, text: `Invalid arguments: ${message}` }] }); + if (!value || typeof value !== "object" || Array.isArray(value)) return failure("expected an object."); + const args = value as Record; + if (!actions.includes(String(args.action))) return failure(`action must be ${actions.join(", ")}.`); + for (const [key, entry] of Object.entries(args)) { + if (!["action", "repo", "id", "format"].includes(key)) return failure(`field ${key} is not allowed.`); + if (typeof entry !== "string" || !entry.trim() || entry.length > 4_096) return failure(`${key} must be a bounded non-empty string.`); + } + if ((args.action === "show") !== (args.id !== undefined)) return failure(args.action === "show" ? "id is required for show." : "id only applies to show."); + if (typeof args.id === "string" && args.id.startsWith("-")) return failure("id cannot begin with '-'."); + if (args.repo && /^[a-z][a-z0-9+.-]*:\/\//i.test(String(args.repo))) return failure("repo must be a local directory."); + const cliArgs = [String(args.action), ...(args.id ? [String(args.id)] : []), `--repo=${args.repo ?? defaultRepo}`, `--format=${args.format ?? "json"}`]; + const output: string[] = []; + const errors: string[] = []; + const code = await command(cliArgs, { stdout: (text) => { output.push(text); }, stderr: (text) => { errors.push(text); } }); + return { ...(code ? { isError: true } : {}), content: [{ type: "text" as const, text: (code ? errors : output).join("") }] }; +} diff --git a/packages/cli/test/cli-runner.test.ts b/packages/cli/test/cli-runner.test.ts index 7920fb2..55c3277 100644 --- a/packages/cli/test/cli-runner.test.ts +++ b/packages/cli/test/cli-runner.test.ts @@ -200,7 +200,7 @@ describe("CLI argument handling", () => { const features = (JSON.parse(catalog.stdout.join("")) as { features: Array<{ name: string; preview?: true }> }).features; expect(features.filter((feature) => feature.preview).map((feature) => feature.name)).toEqual([ "Change scope", "Product capabilities", "Cross-repository workspace", "Repository Q&A", "Migration planning", - "Reverse documentation", "Architecture history", "Supply-chain evidence", "Runtime evidence", "Evidence import", "Execution sandbox", + "Reverse documentation", "Architecture history", "Supply-chain evidence", "Runtime evidence", "Evidence import", "Outcome feedback loop", "Change dossier", "Execution sandbox", "Local hybrid retrieval" ]); expect(features.find((feature) => feature.name === "Plan")?.preview).toBeUndefined(); diff --git a/packages/cli/test/mcp.test.ts b/packages/cli/test/mcp.test.ts index 8c444a5..426b097 100644 --- a/packages/cli/test/mcp.test.ts +++ b/packages/cli/test/mcp.test.ts @@ -195,8 +195,8 @@ describe("fixmap mcp server", () => { const { tools } = await client.listTools(); const preview = tools.filter((tool) => tool.description?.startsWith("Preview (may change before v0.10.0): ")).map((tool) => tool.name).sort(); expect(preview).toEqual([ - "fixmap_ask", "fixmap_capability", "fixmap_change_scope", "fixmap_history", "fixmap_migrate", - "fixmap_reverse_docs", "fixmap_runtime", "fixmap_supply_chain", "fixmap_workspace" + "fixmap_ask", "fixmap_capability", "fixmap_change_scope", "fixmap_dossier", "fixmap_history", "fixmap_migrate", + "fixmap_outcomes", "fixmap_reverse_docs", "fixmap_runtime", "fixmap_supply_chain", "fixmap_workspace" ]); for (const finished of ["fixmap_plan", "fixmap_context", "fixmap_graph", "fixmap_verify", "fixmap_explain", "fixmap_compare", "fixmap_doctor"]) { expect(preview).not.toContain(finished); @@ -393,7 +393,7 @@ describe("fixmap mcp server", () => { const tools = await client.listTools(); expect(tools.tools.map((tool) => tool.name)).toEqual([ - "fixmap_plan", "fixmap_context", "fixmap_graph", "fixmap_change_scope", "fixmap_capability", "fixmap_workspace", "fixmap_ask", "fixmap_migrate", "fixmap_reverse_docs", "fixmap_history", "fixmap_supply_chain", "fixmap_runtime", "fixmap_verify", "fixmap_explain", "fixmap_compare", "fixmap_doctor", "fixmap_annotate" + "fixmap_plan", "fixmap_context", "fixmap_graph", "fixmap_change_scope", "fixmap_capability", "fixmap_workspace", "fixmap_ask", "fixmap_migrate", "fixmap_reverse_docs", "fixmap_history", "fixmap_supply_chain", "fixmap_runtime", "fixmap_verify", "fixmap_explain", "fixmap_compare", "fixmap_doctor", "fixmap_annotate", "fixmap_outcomes", "fixmap_dossier" ]); const plan = tools.tools.find((tool) => tool.name === "fixmap_plan"); const verify = tools.tools.find((tool) => tool.name === "fixmap_verify"); diff --git a/packages/cli/test/outcome-command.test.ts b/packages/cli/test/outcome-command.test.ts new file mode 100644 index 0000000..b24d214 --- /dev/null +++ b/packages/cli/test/outcome-command.test.ts @@ -0,0 +1,293 @@ +import { execFile } from "node:child_process"; +import { createHash } from "node:crypto"; +import { mkdir, mkdtemp, readdir, readFile, rm, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { promisify } from "node:util"; +import { afterEach, describe, expect, it } from "vitest"; +import type { FixMapReport, OutcomeRecord } from "@aryam/fixmap-core"; +import { runCli } from "../src/cli-runner.js"; +import { runDossierCommand, runOutcomeCommand, type RecordCommandIo } from "../src/outcome-command.js"; +import { runDossierTool, runOutcomesTool } from "../src/record-tools.js"; + +const exec = promisify(execFile); +const roots: string[] = []; +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }))); +}); + +const report: FixMapReport = { + reportVersion: 1, + summary: "Ranked.", + contextFiles: [ + { rank: 1, path: "src/a.ts", score: 9, confidence: "high", reasons: ["named"] }, + { rank: 2, path: "src/b.ts", score: 5, confidence: "medium", reasons: ["imports"] } + ], + testRoutes: [], + risks: [], + changedFiles: [], + diagnostics: [] +}; + +async function setup() { + const root = await mkdtemp(join(tmpdir(), "fixmap-outcome-cli-")); + roots.push(root); + const reportPath = join(root, "plan.json"); + await writeFile(reportPath, JSON.stringify(report)); + return { root, reportPath }; +} + +function io(edited: string[] = [], now = "2026-11-20T10:00:00.000Z") { + const stdout: string[] = []; + const stderr: string[] = []; + const value: RecordCommandIo = { + stdout: (text) => { stdout.push(text); }, + stderr: (text) => { stderr.push(text); }, + now: () => new Date(now), + changedFiles: async () => edited + }; + return { stdout, stderr, io: value, out: () => stdout.join(""), err: () => stderr.join("") }; +} + +async function storedOutcomes(root: string) { + const result = io(); + expect(await runOutcomeCommand(["list", `--repo=${root}`, "--format=json"], result.io)).toBe(0); + return JSON.parse(result.out()) as { records: OutcomeRecord[]; problems: unknown[] }; +} + +const sha = (text: string) => `sha256:${createHash("sha256").update(text).digest("hex")}`; + +describe("fixmap outcome", () => { + it("records predicted versus edited paths and command results, then shows and removes the record", async () => { + const { root, reportPath } = await setup(); + const commandPath = join(root, "tests.json"); + await writeFile(commandPath, JSON.stringify([ + { command: "npm test", status: "passed", evidence: "exit 0", relatedPaths: ["test/a.test.ts"] }, + { sandboxResultVersion: 1, executionId: "run-1", image: "node@sha256:abc", command: "npm run lint", status: "failed", exitCode: 1 } + ])); + const recorded = io(["src/a.ts", "src/c.ts"]); + expect(await runOutcomeCommand(["record", "--repo", root, "--report", reportPath, "--working-tree", "--command-result", commandPath, + "--assessment", "agent", "--status", "succeeded", "--reason", "Tests pass"], recorded.io)).toBe(0); + expect(recorded.out()).toContain("1 of 2 edited path(s) were predicted; 1 predicted path(s) were not edited."); + const [record] = (await storedOutcomes(root)).records; + expect(record).toMatchObject({ + predictedPaths: ["src/a.ts", "src/b.ts"], + editedPaths: ["src/a.ts", "src/c.ts"], + recordedAt: "2026-11-20T10:00:00.000Z", + planFingerprint: sha(JSON.stringify(report)), + repositoryIdentity: expect.stringMatching(/^fixmap:\/\/workspace\/local\/repository\//), + taskAssessment: { status: "succeeded", source: "agent", reason: "Tests pass" } + }); + expect(record!.id).toMatch(/^outcome-20261120T100000Z-[a-f0-9]{8}$/); + expect(record!.testOutcomes).toEqual([ + { command: "npm run lint", status: "failed", relatedPaths: [], evidence: "sandbox run-1 exit 1 image node@sha256:abc" }, + { command: "npm test", status: "passed", relatedPaths: ["test/a.test.ts"], evidence: "exit 0" } + ]); + + const shown = io(); + expect(await runOutcomeCommand(["show", record!.id, `--repo=${root}`], shown.io)).toBe(0); + expect(shown.out()).toContain("## Edited paths\n- src/a.ts\n- src/c.ts"); + const removed = io(); + expect(await runOutcomeCommand(["remove", record!.id, `--repo=${root}`], removed.io)).toBe(0); + expect((await storedOutcomes(root)).records).toEqual([]); + }); + + it("redacts the assessment reason and command evidence to SHA-256", async () => { + const { root, reportPath } = await setup(); + const commandPath = join(root, "tests.json"); + await writeFile(commandPath, JSON.stringify({ command: "npm test", status: "passed", evidence: "token=secret in log" })); + const result = io(["src/a.ts"]); + expect(await runOutcomeCommand(["record", `--repo=${root}`, `--report=${reportPath}`, "--diff=main...HEAD", `--command-result=${commandPath}`, + "--assessment=human", "--status=partial", "--reason=Customer ACME complained", "--redact"], result.io)).toBe(0); + const stored = await readFile(join(root, ".fixmap", "outcomes", (await readdir(join(root, ".fixmap", "outcomes")))[0]!), "utf8"); + expect(stored).not.toContain("ACME"); + expect(stored).not.toContain("secret"); + const [record] = (await storedOutcomes(root)).records; + expect(record!.taskAssessment.reason).toBe(sha("Customer ACME complained")); + expect(record!.testOutcomes[0]!.evidence).toBe(sha("token=secret in log")); + }); + + it("calibrates across stored records without changing ranking weights", async () => { + const { root, reportPath } = await setup(); + // Record 1: predicted a,b; edited a,c → 1 correct, 1 false positive, 1 miss. + expect(await runOutcomeCommand(["record", `--repo=${root}`, `--report=${reportPath}`, "--working-tree"], io(["src/a.ts", "src/c.ts"]).io)).toBe(0); + // Record 2: predicted a,b; edited a,b → 2 correct. + expect(await runOutcomeCommand(["record", `--repo=${root}`, `--report=${reportPath}`, "--working-tree", "--assessment=human", "--status=failed"], + io(["src/a.ts", "src/b.ts"], "2026-11-21T10:00:00.000Z").io)).toBe(0); + const json = io(); + expect(await runOutcomeCommand(["calibrate", `--repo=${root}`, "--format", "json"], json.io)).toBe(0); + const calibration = JSON.parse(json.out()); + expect(calibration).toMatchObject({ + records: 2, + totals: { predictedPaths: 4, editedPaths: 4, correctlyPredictedEdits: 3, predictedButUnedited: 1, editedButUnpredicted: 1 }, + precision: 0.75, + recall: 0.75, + taskAssessments: { failed: 1, unknown: 1, succeeded: 0, partial: 0 }, + automaticWeightChanges: false, + problems: [] + }); + const markdown = io(); + expect(await runOutcomeCommand(["calibrate", `--repo=${root}`], markdown.io)).toBe(0); + expect(markdown.out()).toContain("Precision: 75.0% (3 of 4 predicted paths were edited)"); + expect(markdown.out()).toContain("automaticWeightChanges: false"); + const empty = io(); + expect(await runOutcomeCommand(["calibrate", `--repo=${(await setup()).root}`], empty.io)).toBe(0); + expect(empty.out()).toContain("Precision: n/a"); + }); + + it("prunes records older than a number of days", async () => { + const { root, reportPath } = await setup(); + await runOutcomeCommand(["record", `--repo=${root}`, `--report=${reportPath}`, "--working-tree"], io([], "2026-01-01T00:00:00.000Z").io); + await runOutcomeCommand(["record", `--repo=${root}`, `--report=${reportPath}`, "--working-tree"], io([], "2026-11-19T00:00:00.000Z").io); + const pruned = io([], "2026-11-20T00:00:00.000Z"); + expect(await runOutcomeCommand(["prune", `--repo=${root}`, "--older-than", "30"], pruned.io)).toBe(0); + expect(pruned.out()).toContain("Removed 1 outcome record(s)"); + expect((await storedOutcomes(root)).records.map((record) => record.recordedAt)).toEqual(["2026-11-19T00:00:00.000Z"]); + expect(await runOutcomeCommand(["prune", `--repo=${root}`, "--older-than", "-1"], io().io)).toBe(1); + }); + + it("lists malformed stored files as problems instead of failing", async () => { + const { root, reportPath } = await setup(); + await runOutcomeCommand(["record", `--repo=${root}`, `--report=${reportPath}`, "--working-tree"], io(["src/a.ts"]).io); + await writeFile(join(root, ".fixmap", "outcomes", "broken.json"), "{"); + const listed = io(); + expect(await runOutcomeCommand(["list", `--repo=${root}`], listed.io)).toBe(0); + expect(listed.out()).toContain("## Unreadable stored files (1)\n\n- .fixmap/outcomes/broken.json: Not valid JSON"); + const calibrated = io(); + expect(await runOutcomeCommand(["calibrate", `--repo=${root}`, "--format=json"], calibrated.io)).toBe(0); + expect(JSON.parse(calibrated.out())).toMatchObject({ records: 1, problems: [{ file: ".fixmap/outcomes/broken.json" }] }); + }); + + it("rejects invalid arguments with a clear message", async () => { + const { root, reportPath } = await setup(); + const cases: Array<[string[], string]> = [ + [["record", `--report=${reportPath}`], "Provide --diff or --working-tree"], + [["record", `--report=${reportPath}`, "--working-tree", "--diff=a..b"], "not both"], + [["record", `--report=${reportPath}`, "--working-tree", "--assessment=human"], "--status succeeded|failed|partial|unknown is required"], + [["record", `--report=${reportPath}`, "--working-tree", "--status=succeeded"], "An unassessed outcome can only have --status unknown"], + [["record", `--report=${join(root, "missing.json")}`, "--working-tree"], "does not exist"], + [["list", "--older-than=3"], "--older-than does not apply to outcome list"], + [["show"], "needs exactly one record id"], + [["show", "../../etc/passwd"], "Invalid outcome record id"], + [["explode"], "Unknown outcome action: explode"], + [["list", "--format=xml"], "--format must be markdown or json"] + ]; + for (const [args, message] of cases) { + const result = io(["src/a.ts"]); + expect(await runOutcomeCommand([...args, `--repo=${root}`], result.io), args.join(" ")).toBe(1); + expect(result.err(), args.join(" ")).toContain(message); + } + const markdown = join(root, "plan.md"); + await writeFile(markdown, "# FixMap report"); + const result = io(); + expect(await runOutcomeCommand(["record", `--repo=${root}`, `--report=${markdown}`, "--working-tree"], result.io)).toBe(1); + expect(result.err()).toContain("is not a JSON FixMap report"); + expect(await readdir(root)).not.toContain(".fixmap"); + }); + + it("reads edited paths from a real Git working tree through the CLI", async () => { + const { root, reportPath } = await setup(); + await mkdir(join(root, "src")); + await writeFile(join(root, "src", "a.ts"), "export const a = 1;\n"); + await writeFile(join(root, "src", "b.ts"), "export const b = 1;\n"); + await exec("git", ["init", "--quiet"], { cwd: root }); + await exec("git", ["config", "user.email", "fixmap@example.test"], { cwd: root }); + await exec("git", ["config", "user.name", "FixMap Test"], { cwd: root }); + await exec("git", ["add", "src"], { cwd: root }); + await exec("git", ["commit", "--quiet", "-m", "init"], { cwd: root }); + await writeFile(join(root, "src", "a.ts"), "export const a = 2;\n"); + const stdout: string[] = []; + const stderr: string[] = []; + expect(await runCli(["outcome", "record", "--repo", root, "--report", reportPath, "--working-tree"], { + stdout: (text) => { stdout.push(text); }, stderr: (text) => { stderr.push(text); } + }), stderr.join("")).toBe(0); + expect((await storedOutcomes(root)).records[0]).toMatchObject({ editedPaths: ["src/a.ts"] }); + }); +}); + +describe("fixmap dossier", () => { + it("creates, lists, shows, and removes a fingerprinted dossier with diff and release identifiers", async () => { + const { root, reportPath } = await setup(); + const created = io(["src/a.ts"]); + expect(await runDossierCommand(["create", `--repo=${root}`, `--report=${reportPath}`, "--task", "Fix login redirect", + "--diff=main...HEAD", "--pr=https://github.com/o/r/pull/9", "--commit=abc123"], created.io)).toBe(0); + expect(created.out()).toMatch(/Saved \.fixmap\/dossiers\/dossier-20261120T100000Z-[a-f0-9]{8}\.json \(dossier:[a-f0-9]{16}\)/); + const listed = io(); + expect(await runDossierCommand(["list", `--repo=${root}`, "--format=json"], listed.io)).toBe(0); + const [dossier] = JSON.parse(listed.out()).records; + expect(dossier).toMatchObject({ + request: { summary: "Fix login redirect", sourceFingerprint: sha("Fix login redirect") }, + plan: { reportFingerprint: sha(JSON.stringify(report)), artifactPath: "plan.json" }, + diff: { changedFiles: ["src/a.ts"], base: "main...HEAD" }, + releaseIdentifiers: { pullRequest: "https://github.com/o/r/pull/9", commit: "abc123" } + }); + const shown = io(); + expect(await runDossierCommand(["show", dossier.id, `--repo=${root}`], shown.io)).toBe(0); + expect(shown.out()).toContain("- pullRequest: https://github.com/o/r/pull/9"); + expect(await runDossierCommand(["remove", dossier.id, `--repo=${root}`], io().io)).toBe(0); + expect(await readdir(join(root, ".fixmap", "dossiers"))).toEqual([]); + }); + + it("keeps the plan artifact path when the repository or report is reached through a link", async () => { + // Regression: the repository root is a realpath (macOS /var -> /private/var, Windows 8.3 + // names), and a lexically resolved report path made the artifact look outside the repository. + const { root, reportPath } = await setup(); + const aliasParent = await mkdtemp(join(tmpdir(), "fixmap-dossier-alias-")); + roots.push(aliasParent); + const alias = join(aliasParent, "repo"); + await symlink(root, alias, process.platform === "win32" ? "junction" : "dir"); + for (const [repo, plan] of [[alias, reportPath], [root, join(alias, "plan.json")]]) { + expect(await runDossierCommand(["create", `--repo=${repo}`, `--report=${plan}`, "--task=Fix"], io().io)).toBe(0); + } + const listed = io(); + expect(await runDossierCommand(["list", `--repo=${root}`, "--format=json"], listed.io)).toBe(0); + const records = JSON.parse(listed.out()).records as Array<{ plan: { artifactPath?: string } }>; + expect(records.map((record) => record.plan.artifactPath)).toEqual(["plan.json", "plan.json"]); + }); + + it("redacts the task text and allows a dossier without a diff", async () => { + const { root, reportPath } = await setup(); + expect(await runDossierCommand(["create", `--repo=${root}`, `--report=${reportPath}`, "--task=Patient Jane Doe data leak", "--redact"], io().io)).toBe(0); + const directory = join(root, ".fixmap", "dossiers"); + const text = await readFile(join(directory, (await readdir(directory))[0]!), "utf8"); + expect(text).not.toContain("Jane"); + expect(JSON.parse(text)).toMatchObject({ request: { summary: sha("Patient Jane Doe data leak") }, diff: null }); + const missingTask = io(); + expect(await runDossierCommand(["create", `--repo=${root}`, `--report=${reportPath}`], missingTask.io)).toBe(1); + expect(missingTask.err()).toContain("requires --task"); + }); +}); + +describe("read-only MCP record tools", () => { + it("lists, shows, and calibrates outcomes and dossiers without writing", async () => { + const { root, reportPath } = await setup(); + await runOutcomeCommand(["record", `--repo=${root}`, `--report=${reportPath}`, "--working-tree"], io(["src/a.ts"]).io); + await runDossierCommand(["create", `--repo=${root}`, `--report=${reportPath}`, "--task=Fix"], io().io); + const listed = await runOutcomesTool({ action: "list", repo: root }, root); + const id = JSON.parse(listed.content[0]!.text).records[0].id as string; + const shown = await runOutcomesTool({ action: "show", id }, root); + expect(JSON.parse(shown.content[0]!.text).id).toBe(id); + const calibration = JSON.parse((await runOutcomesTool({ action: "calibrate", repo: root }, root)).content[0]!.text); + expect(calibration).toMatchObject({ records: 1, precision: 0.5, recall: 1, automaticWeightChanges: false }); + const dossiers = JSON.parse((await runDossierTool({ action: "list" }, root)).content[0]!.text); + expect(dossiers.records).toHaveLength(1); + + for (const [tool, args, message] of [ + [runOutcomesTool, { action: "record" }, "action must be"], + [runOutcomesTool, { action: "remove", id }, "action must be"], + [runDossierTool, { action: "calibrate" }, "action must be"], + [runDossierTool, { action: "show" }, "id is required"], + [runOutcomesTool, { action: "list", id }, "id only applies"], + [runOutcomesTool, { action: "list", olderThan: "3" }, "not allowed"], + [runOutcomesTool, { action: "show", id: "--repo=/" }, "cannot begin"], + [runDossierTool, { action: "list", repo: "https://example.com/r" }, "local directory"] + ] as const) { + const result = await tool(args, root); + expect(result.isError).toBe(true); + expect(result.content[0]!.text).toContain(message); + } + const missing = await runOutcomesTool({ action: "show", id: "outcome-missing" }, root); + expect(missing.isError).toBe(true); + expect(missing.content[0]!.text).toContain("No outcome record found"); + }); +}); diff --git a/packages/core/src/feature-catalog.ts b/packages/core/src/feature-catalog.ts index afdea7f..36ec399 100644 --- a/packages/core/src/feature-catalog.ts +++ b/packages/core/src/feature-catalog.ts @@ -25,13 +25,15 @@ export const FIXMAP_FEATURES: readonly FixMapFeature[] = [ { name: "Supply-chain evidence", preview: true, command: "fixmap supply-chain --input ", detail: "Validate normalized external scanner or SBOM evidence with exact tool, database, document, advisory, version, and license provenance." }, { name: "Runtime evidence", preview: true, command: "fixmap runtime --input ", detail: "Map redaction-reviewed OpenTelemetry, APM, Speedscope, or pprof observations only through exact repository paths and file fingerprints." }, { name: "Evidence import", preview: true, command: "fixmap plan --evidence ", detail: "Attach findings from other tools (scanners, CI, runtime monitors) to the files in a plan from a version-1 data-only bundle; claims are shown as supplied and never executed." }, + { name: "Outcome feedback loop", preview: true, command: "fixmap outcome record --report --working-tree", detail: "Save what a plan predicted next to what was edited and which commands passed, one atomic file per record in .fixmap/outcomes/, then calibrate precision and recall; ranking weights never change automatically." }, + { name: "Change dossier", preview: true, command: "fixmap dossier create --report --task ", detail: "Save a fingerprinted record linking the request, plan and graph fingerprints, ADRs, diff, command results, and commit/PR identifiers in .fixmap/dossiers/, with optional SHA-256 redaction of the task text." }, { name: "Execution sandbox", preview: true, command: "fixmap sandbox --request --execute-declared-command", detail: "Run exactly one reviewed command in an already-present digest-pinned Docker image with network off and source/root read-only by default." }, { name: "Explain", command: "fixmap plan --explain ", detail: "Show whether a path ranked, tied below the limit, was excluded, or was never scanned." }, { name: "Compare", command: "fixmap plan --compare ", detail: "Compare a refined task and current plan with an earlier JSON report." }, { name: "Verify", command: "fixmap verify --report ", detail: "Compare the completed diff or working tree with the saved plan; add --fail-on warning for a strict CI gate." }, { name: "Validate", command: "fixmap validate ", detail: "Check a saved report against FixMap's structural compatibility contract." }, { name: "Doctor", command: "fixmap doctor", detail: "Diagnose stale local, global, PATH, and npx install shadows." }, - { name: "MCP", command: "fixmap mcp", detail: "Expose Plan, Context, Graph, Change Scope, Capability maps, Workspace, Ask, Migrate, Reverse Docs, History, Supply Chain, Runtime, Explain, Compare, Verify, and Doctor over local stdio." }, + { name: "MCP", command: "fixmap mcp", detail: "Expose Plan, Context, Graph, Change Scope, Capability maps, Workspace, Ask, Migrate, Reverse Docs, History, Supply Chain, Runtime, Outcomes, Dossiers, Explain, Compare, Verify, and Doctor over local stdio." }, { name: "Public tasks", command: "fixmap owner/repository#123", detail: "Fetch public GitHub issue or pull-request text anonymously and scan its repository in an isolated checkout." }, { name: "Repository sources", command: "--repo --ref ", detail: "Map a local checkout, file URL, directory archive, or a named branch or tag from a public GitHub repository." }, { name: "Task files", command: "--issue-file ", detail: "Read long task text from UTF-8, UTF-16, or stdin, including BOM-less UTF-16 from common Windows tools." }, diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index a7cd0cd..8855376 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -50,6 +50,11 @@ export { addOutcomeRecord, createOutcomeRecord, emptyOutcomeStore, removeOutcome export type { OutcomeCalibration, OutcomeRecord, OutcomeStore, TestOutcomeStatus } from "./outcomes.js"; export { buildChangeDossier, validateChangeDossier } from "./dossier.js"; export type { ChangeDossier, ChangeDossierInput, DossierAssumption } from "./dossier.js"; +export { + deleteStoredDossier, deleteStoredOutcome, isStoredRecordId, pruneStoredOutcomes, readStoredDossier, readStoredDossiers, + readStoredOutcome, readStoredOutcomes, saveStoredDossier, saveStoredOutcome +} from "./record-store.js"; +export type { StoredRecordProblem, StoredRecords } from "./record-store.js"; export { routeReviewers } from "./ownership.js"; export type { ReviewEvidence, ReviewRoutingResult, ReviewSuggestion } from "./ownership.js"; export { buildSandboxInvocation, runSandbox } from "./sandbox.js"; diff --git a/packages/core/src/record-store.ts b/packages/core/src/record-store.ts new file mode 100644 index 0000000..f41d81b --- /dev/null +++ b/packages/core/src/record-store.ts @@ -0,0 +1,276 @@ +import { lstat, mkdir, open, readdir, readFile, realpath, rename, rm, stat } from "node:fs/promises"; +import { resolve } from "node:path"; +import { randomUUID } from "node:crypto"; +import { validateChangeDossier, type ChangeDossier } from "./dossier.js"; +import { createOutcomeRecord, type OutcomeRecord } from "./outcomes.js"; + +/** + * Repository-local persistence for outcome records (.fixmap/outcomes/) and change dossiers + * (.fixmap/dossiers/), one JSON file per record. Follows the annotation store: writes go + * through a temp file and rename, links and junctions are refused, and a lock held by + * another writer is never taken over, however old it looks. + */ + +export type StoredRecordProblem = { file: string; message: string }; +export type StoredRecords = { records: T[]; problems: StoredRecordProblem[] }; + +/** Stored IDs double as file names, so they exclude ':' (invalid on Windows) and a trailing dot. */ +const STORED_ID = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,126}[A-Za-z0-9_-])?$/; +const LOCK_ATTEMPTS = 40; +const LOCK_RETRY_MS = 25; + +type Kind = { + directory: "outcomes" | "dossiers"; + label: string; + validate: (value: unknown) => T; + id: (record: T) => string; + date: (record: T) => string; +}; + +const OUTCOMES: Kind = { + directory: "outcomes", + label: "outcome record", + validate: (value) => { + if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid outcome record envelope."); + const { outcomeRecordVersion, ...rest } = value as OutcomeRecord; + if (outcomeRecordVersion !== 1) throw new Error("Invalid outcome record envelope."); + return createOutcomeRecord(rest); + }, + id: (record) => record.id, + date: (record) => record.recordedAt +}; + +const DOSSIERS: Kind = { + directory: "dossiers", + label: "change dossier", + validate: validateChangeDossier, + id: (record) => record.id, + date: (record) => record.createdAt +}; + +export function isStoredRecordId(id: string): boolean { return STORED_ID.test(id); } + +export const readStoredOutcomes = (repoRoot: string) => listRecords(OUTCOMES, repoRoot); +export const readStoredOutcome = (repoRoot: string, id: string) => readRecord(OUTCOMES, repoRoot, id); +export const saveStoredOutcome = (repoRoot: string, record: OutcomeRecord) => saveRecord(OUTCOMES, repoRoot, record); +export const deleteStoredOutcome = (repoRoot: string, id: string) => deleteRecord(OUTCOMES, repoRoot, id); +/** Delete outcome records recorded strictly before `cutoff`. Malformed files are reported, never deleted. */ +export const pruneStoredOutcomes = (repoRoot: string, cutoff: Date) => pruneRecords(OUTCOMES, repoRoot, cutoff); + +export const readStoredDossiers = (repoRoot: string) => listRecords(DOSSIERS, repoRoot); +export const readStoredDossier = (repoRoot: string, id: string) => readRecord(DOSSIERS, repoRoot, id); +export const saveStoredDossier = (repoRoot: string, record: ChangeDossier) => saveRecord(DOSSIERS, repoRoot, record); +export const deleteStoredDossier = (repoRoot: string, id: string) => deleteRecord(DOSSIERS, repoRoot, id); + +async function listRecords(kind: Kind, repoRoot: string): Promise> { + const root = await repositoryRoot(repoRoot); + const directory = await existingKindDirectory(kind, root); + if (!directory) return { records: [], problems: [] }; + const records: T[] = []; + const problems: StoredRecordProblem[] = []; + for (const name of (await readdir(directory)).sort()) { + if (name.startsWith(".")) continue; // in-flight or abandoned temp files + const file = `.fixmap/${kind.directory}/${name}`; + const id = name.endsWith(".json") ? name.slice(0, -".json".length) : ""; + if (!isStoredRecordId(id)) { problems.push({ file, message: "Not a record file (expected .json)." }); continue; } + try { + records.push(await readRecordFile(kind, directory, id)); + } catch (error) { + problems.push({ file, message: errorMessage(error) }); + } + } + records.sort((a, b) => kind.date(a).localeCompare(kind.date(b)) || kind.id(a).localeCompare(kind.id(b))); + return { records, problems }; +} + +async function readRecord(kind: Kind, repoRoot: string, id: string): Promise { + assertId(kind, id); + const root = await repositoryRoot(repoRoot); + const directory = await existingKindDirectory(kind, root); + if (!directory) throw new Error(`No ${kind.label} found: ${id}`); + try { + return await readRecordFile(kind, directory, id); + } catch (error) { + if (isNodeError(error, "ENOENT")) throw new Error(`No ${kind.label} found: ${id}`); + throw error; + } +} + +async function saveRecord(kind: Kind, repoRoot: string, record: T): Promise { + const validated = kind.validate(record); + const id = kind.id(validated); + assertId(kind, id); + const root = await repositoryRoot(repoRoot); + return withLock(kind, root, async (directory) => { + const target = recordPath(directory, id); + if (await fileInfo(target)) throw new Error(`A ${kind.label} with id ${id} already exists.`); + const temporary = resolve(directory, `.${id}.${process.pid}.${randomUUID()}.tmp`); + const handle = await open(temporary, "wx", 0o600); + try { + await handle.writeFile(`${JSON.stringify(validated, null, 2)}\n`, "utf8"); + await handle.sync(); + } finally { + await handle.close(); + } + try { + await rename(temporary, target); + } catch (error) { + await rm(temporary, { force: true }); + throw error; + } + return validated; + }); +} + +async function deleteRecord(kind: Kind, repoRoot: string, id: string): Promise { + assertId(kind, id); + const root = await repositoryRoot(repoRoot); + await withLock(kind, root, async (directory) => { + const target = recordPath(directory, id); + const info = await fileInfo(target); + if (!info) throw new Error(`No ${kind.label} found: ${id}`); + assertRegularFile(kind, info); + await rm(target); + }); +} + +async function pruneRecords(kind: Kind, repoRoot: string, cutoff: Date): Promise<{ removed: string[]; kept: number; problems: StoredRecordProblem[] }> { + if (!Number.isFinite(cutoff.getTime())) throw new Error("Prune cutoff must be a valid date."); + const root = await repositoryRoot(repoRoot); + if (!(await existingKindDirectory(kind, root))) return { removed: [], kept: 0, problems: [] }; + return withLock(kind, root, async (directory) => { + const { records, problems } = await listRecords(kind, root); + const removed: string[] = []; + for (const record of records) { + if (Date.parse(kind.date(record)) >= cutoff.getTime()) continue; + const target = recordPath(directory, kind.id(record)); + const info = await fileInfo(target); + if (!info) continue; + assertRegularFile(kind, info); + await rm(target); + removed.push(kind.id(record)); + } + return { removed, kept: records.length - removed.length, problems }; + }); +} + +async function readRecordFile(kind: Kind, directory: string, id: string): Promise { + const path = recordPath(directory, id); + const info = await lstat(path); + assertRegularFile(kind, info); + let parsed: unknown; + try { + parsed = JSON.parse(await readFile(path, "utf8")) as unknown; + } catch (error) { + if (error instanceof SyntaxError) throw new Error(`Not valid JSON: ${error.message}`); + throw error; + } + const record = kind.validate(parsed); + if (kind.id(record) !== id) throw new Error(`File name does not match its ${kind.label} id ${kind.id(record)}.`); + return record; +} + +async function withLock(kind: Kind, root: string, operation: (directory: string) => Promise): Promise { + const directory = await createKindDirectory(kind, root); + const lockPath = resolve(root, ".fixmap", `${kind.directory}.lock`); + let handle; + for (let attempt = 1; !handle; attempt += 1) { + const existing = await fileInfo(lockPath); + if (existing) assertRegularFile(kind, existing); + try { + handle = await open(lockPath, "wx", 0o600); + } catch (error) { + if (!isNodeError(error, "EEXIST")) throw error; + // Age cannot prove that a writer has stopped (it may be suspended), so the lock is never + // taken over. Wait a bounded time for a live writer, then refuse. + if (attempt >= LOCK_ATTEMPTS) { + throw new Error(`Another FixMap ${kind.label} update is in progress or left a lock. Retry after it finishes; if interrupted, confirm no FixMap writer is running before manually removing .fixmap/${kind.directory}.lock.`); + } + await new Promise((done) => setTimeout(done, LOCK_RETRY_MS)); + } + } + try { + await handle.writeFile(`${JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString() })}\n`, "utf8"); + await handle.sync(); + await assertDirectory(kind, root, directory); + return await operation(directory); + } finally { + try { + await handle.close(); + } finally { + await rm(lockPath, { force: true }); + } + } +} + +async function repositoryRoot(path: string): Promise { + const root = await realpath(path); + if (!(await stat(root)).isDirectory()) throw new Error("FixMap repository must be a directory."); + return root; +} + +async function existingKindDirectory(kind: Kind, root: string): Promise { + const fixmap = resolve(root, ".fixmap"); + if (!(await fileInfo(fixmap))) return undefined; + await assertDirectory(kind, root, fixmap); + const directory = resolve(fixmap, kind.directory); + if (!(await fileInfo(directory))) return undefined; + await assertDirectory(kind, root, directory); + return directory; +} + +async function createKindDirectory(kind: Kind, root: string): Promise { + const fixmap = resolve(root, ".fixmap"); + if (await fileInfo(fixmap)) await assertDirectory(kind, root, fixmap); + else await makeDirectory(fixmap); + await assertDirectory(kind, root, fixmap); + const directory = resolve(fixmap, kind.directory); + if (!(await fileInfo(directory))) await makeDirectory(directory); + await assertDirectory(kind, root, directory); + return directory; +} + +/** A concurrent writer may create the directory first; the link check that follows still applies. */ +async function makeDirectory(path: string): Promise { + await mkdir(path).catch((error: unknown) => { + if (!isNodeError(error, "EEXIST")) throw error; + }); +} + +/** Refuse a link, junction, or anything that resolves somewhere other than its lexical path. */ +async function assertDirectory(kind: Kind, root: string, directory: string): Promise { + const info = await lstat(directory); + if (!info.isDirectory() || info.isSymbolicLink() || await realpath(directory) !== directory || !directory.startsWith(root)) { + throw new Error(`The ${kind.label} store must be a real repository-local directory (.fixmap/${kind.directory}), not a link or junction.`); + } +} + +function assertRegularFile(kind: Kind, info: Awaited>): void { + if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1) { + throw new Error(`Stored ${kind.label} files and locks must be regular, unlinked repository-local files.`); + } +} + +function recordPath(directory: string, id: string): string { + const path = resolve(directory, `${id}.json`); + if (resolve(path, "..") !== directory) throw new Error("Record path escapes its store directory."); + return path; +} + +function assertId(kind: Kind, id: string): void { + if (typeof id !== "string" || !isStoredRecordId(id)) { + throw new Error(`Invalid ${kind.label} id: use letters, digits, '.', '_' or '-' (at most 128 characters, no path separators).`); + } +} + +async function fileInfo(path: string) { + return lstat(path).catch((error: unknown) => { + if (isNodeError(error, "ENOENT")) return undefined; + throw error; + }); +} + +function errorMessage(error: unknown): string { return error instanceof Error ? error.message : String(error); } +function isNodeError(error: unknown, code: string): error is NodeJS.ErrnoException { + return error instanceof Error && "code" in error && (error as NodeJS.ErrnoException).code === code; +} diff --git a/packages/core/test/record-store.test.ts b/packages/core/test/record-store.test.ts new file mode 100644 index 0000000..8fc0e45 --- /dev/null +++ b/packages/core/test/record-store.test.ts @@ -0,0 +1,188 @@ +import { link, mkdir, mkdtemp, readdir, readFile, rm, symlink, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { afterEach, describe, expect, it } from "vitest"; +import { buildChangeDossier } from "../src/dossier.js"; +import { createOutcomeRecord, type OutcomeRecord } from "../src/outcomes.js"; +import { + deleteStoredDossier, + deleteStoredOutcome, + pruneStoredOutcomes, + readStoredDossier, + readStoredDossiers, + readStoredOutcome, + readStoredOutcomes, + saveStoredDossier, + saveStoredOutcome +} from "../src/record-store.js"; + +const roots: string[] = []; +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }))); +}); + +async function repo(): Promise { + const root = await mkdtemp(join(tmpdir(), "fixmap-record-store-")); + roots.push(root); + return root; +} + +function outcome(id: string, recordedAt = "2026-11-01T00:00:00Z", overrides: Partial = {}): OutcomeRecord { + return createOutcomeRecord({ + id, + taskId: "task-1", + repositoryIdentity: "fixmap://workspace/local/repository/api", + planFingerprint: "sha256:0123456789abcdef", + recordedAt, + predictedPaths: ["src/a.ts", "src/b.ts"], + editedPaths: ["src/a.ts", "src/c.ts"], + testOutcomes: [], + taskAssessment: { status: "unknown", source: "unassessed", reason: "Not assessed." }, + ...overrides + }); +} + +function dossier(id: string) { + return buildChangeDossier({ + id, + repositoryIdentity: "fixmap://workspace/local/repository/api", + createdAt: "2026-11-01T00:00:00Z", + updatedAt: "2026-11-01T00:00:00Z", + request: { summary: "Fix login", sourceFingerprint: "sha256:abcdef012345" }, + assumptions: [], + plan: { reportFingerprint: "sha256:111111111111", graphFingerprint: "sha256:222222222222" }, + decisions: [], + diff: null, + tests: [], + runtimeEvidence: [], + reviews: [], + releaseIdentifiers: { pullRequest: "https://github.com/o/r/pull/1" } + }); +} + +describe("outcome and dossier store", () => { + it("reads nothing and creates nothing in a repository without a store", async () => { + const root = await repo(); + expect(await readStoredOutcomes(root)).toEqual({ records: [], problems: [] }); + expect(await readStoredDossiers(root)).toEqual({ records: [], problems: [] }); + await expect(readStoredOutcome(root, "missing")).rejects.toThrow("No outcome record found: missing"); + expect(await readdir(root)).toEqual([]); + }); + + it("writes one file per record atomically, leaves no temp file, and releases the lock", async () => { + const root = await repo(); + const saved = await saveStoredOutcome(root, outcome("outcome-1")); + expect(await readdir(join(root, ".fixmap"))).toEqual(["outcomes"]); + expect(await readdir(join(root, ".fixmap", "outcomes"))).toEqual(["outcome-1.json"]); + expect(JSON.parse(await readFile(join(root, ".fixmap", "outcomes", "outcome-1.json"), "utf8"))).toEqual(saved); + expect(await readStoredOutcome(root, "outcome-1")).toEqual(saved); + await expect(saveStoredOutcome(root, outcome("outcome-1"))).rejects.toThrow("already exists"); + await saveStoredDossier(root, dossier("dossier-1")); + expect(await readStoredDossier(root, "dossier-1")).toEqual(dossier("dossier-1")); + expect((await readdir(join(root, ".fixmap"))).sort()).toEqual(["dossiers", "outcomes"]); + }); + + it("serializes concurrent writers without corrupting or losing a saved record", async () => { + const root = await repo(); + const ids = Array.from({ length: 12 }, (_, index) => `outcome-${index}`); + const results = await Promise.allSettled(ids.map((id) => saveStoredOutcome(root, outcome(id)))); + for (const result of results) { + if (result.status === "rejected") expect(String(result.reason)).toContain("in progress or left a lock"); + } + const saved = ids.filter((_, index) => results[index]!.status === "fulfilled"); + expect(saved.length).toBeGreaterThan(0); + const stored = await readStoredOutcomes(root); + expect(stored.problems).toEqual([]); + expect(stored.records.map((record) => record.id).sort()).toEqual(saved.sort()); + expect(await readdir(join(root, ".fixmap", "outcomes"))).toHaveLength(saved.length); + expect(await readdir(join(root, ".fixmap"))).not.toContain("outcomes.lock"); + }); + + it("refuses to take over a lock another writer holds, however old", async () => { + const root = await repo(); + await mkdir(join(root, ".fixmap")); + const lock = join(root, ".fixmap", "outcomes.lock"); + await writeFile(lock, '{"pid":1}\n'); + await expect(saveStoredOutcome(root, outcome("outcome-1"))).rejects.toThrow("in progress or left a lock"); + await expect(deleteStoredOutcome(root, "outcome-1")).rejects.toThrow("in progress or left a lock"); + expect(await readFile(lock, "utf8")).toBe('{"pid":1}\n'); + expect(await readdir(join(root, ".fixmap", "outcomes"))).toEqual([]); + }); + + it("rejects ids that could traverse out of the store", async () => { + const root = await repo(); + for (const id of ["../escape", "..", "a/b", "a\\b", "C:evil", "name.", ".hidden", ""]) { + await expect(readStoredOutcome(root, id)).rejects.toThrow("Invalid outcome record id"); + await expect(deleteStoredDossier(root, id)).rejects.toThrow("Invalid change dossier id"); + } + await expect(saveStoredOutcome(root, outcome("x:y"))).rejects.toThrow("Invalid outcome record id"); + }); + + it("refuses a linked .fixmap directory, a linked store directory, and hardlinked records", async () => { + const outside = await repo(); + const root = await repo(); + await symlink(outside, join(root, ".fixmap"), process.platform === "win32" ? "junction" : "dir"); + await expect(saveStoredOutcome(root, outcome("outcome-1"))).rejects.toThrow("not a link or junction"); + await expect(readStoredOutcomes(root)).rejects.toThrow("not a link or junction"); + expect(await readdir(outside)).toEqual([]); + + const second = await repo(); + await mkdir(join(second, ".fixmap")); + await symlink(outside, join(second, ".fixmap", "dossiers"), process.platform === "win32" ? "junction" : "dir"); + await expect(saveStoredDossier(second, dossier("dossier-1"))).rejects.toThrow("not a link or junction"); + expect(await readdir(outside)).toEqual([]); + + const third = await repo(); + await saveStoredOutcome(third, outcome("outcome-1")); + await link(join(third, ".fixmap", "outcomes", "outcome-1.json"), join(outside, "copy.json")); + await expect(readStoredOutcome(third, "outcome-1")).rejects.toThrow("regular, unlinked"); + await expect(deleteStoredOutcome(third, "outcome-1")).rejects.toThrow("regular, unlinked"); + expect((await readStoredOutcomes(third)).problems).toEqual([ + { file: ".fixmap/outcomes/outcome-1.json", message: expect.stringContaining("regular, unlinked") } + ]); + }); + + it("reports malformed stored files without crashing or hiding valid records", async () => { + const root = await repo(); + await saveStoredOutcome(root, outcome("good")); + const directory = join(root, ".fixmap", "outcomes"); + await writeFile(join(directory, "broken.json"), "{not json"); + await writeFile(join(directory, "invalid.json"), JSON.stringify({ outcomeRecordVersion: 1, id: "invalid" })); + await writeFile(join(directory, "renamed.json"), JSON.stringify(outcome("other"))); + await writeFile(join(directory, "notes.txt"), "hello"); + await writeFile(join(directory, ".good.123.tmp"), "partial"); + const stored = await readStoredOutcomes(root); + expect(stored.records.map((record) => record.id)).toEqual(["good"]); + expect(stored.problems).toEqual([ + { file: ".fixmap/outcomes/broken.json", message: expect.stringContaining("Not valid JSON") }, + { file: ".fixmap/outcomes/invalid.json", message: "Invalid outcome record envelope." }, + { file: ".fixmap/outcomes/notes.txt", message: "Not a record file (expected .json)." }, + { file: ".fixmap/outcomes/renamed.json", message: expect.stringContaining("does not match") } + ]); + const tampered = { ...dossier("dossier-1"), request: { summary: "edited", sourceFingerprint: "sha256:abcdef012345" } }; + await mkdir(join(root, ".fixmap", "dossiers")); + await writeFile(join(root, ".fixmap", "dossiers", "dossier-1.json"), JSON.stringify(tampered)); + expect((await readStoredDossiers(root)).problems[0]?.message).toContain("fingerprint does not match"); + }); + + it("prunes only records older than the cutoff and never deletes malformed files", async () => { + const root = await repo(); + await saveStoredOutcome(root, outcome("old", "2026-01-01T00:00:00Z")); + await saveStoredOutcome(root, outcome("edge", "2026-06-01T00:00:00Z")); + await saveStoredOutcome(root, outcome("new", "2026-11-01T00:00:00Z")); + await writeFile(join(root, ".fixmap", "outcomes", "broken.json"), "{"); + const result = await pruneStoredOutcomes(root, new Date("2026-06-01T00:00:00Z")); + expect(result).toMatchObject({ removed: ["old"], kept: 2 }); + expect(result.problems).toHaveLength(1); + expect((await readdir(join(root, ".fixmap", "outcomes"))).sort()).toEqual(["broken.json", "edge.json", "new.json"]); + expect(await pruneStoredOutcomes(await repo(), new Date())).toEqual({ removed: [], kept: 0, problems: [] }); + }); + + it("removes a record and reports a missing one", async () => { + const root = await repo(); + await saveStoredDossier(root, dossier("dossier-1")); + await deleteStoredDossier(root, "dossier-1"); + expect((await readStoredDossiers(root)).records).toEqual([]); + await expect(deleteStoredDossier(root, "dossier-1")).rejects.toThrow("No change dossier found: dossier-1"); + }); +});