@aryam/fixmap 0.8.8 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  **Give your coding agent a map before it starts editing.**
4
4
 
5
- FixMap turns an issue, prompt, or git diff into ranked context files, test routes, and risk notes — with no account or API key and no source upload.
5
+ FixMap turns an issue, prompt, or git diff into ranked primary context, an evidence-backed Impact Graph, test routes, and risk notes — with no account or API key and no source upload.
6
6
 
7
7
  ## Quick start
8
8
 
@@ -27,6 +27,15 @@ For private source or working-tree changes, run from a local JavaScript or TypeS
27
27
  fixmap plan --issue "password reset emails fail"
28
28
  ```
29
29
 
30
+ Install a discoverable `/fixmap` command for supported coding agents, then invoke it without a task to see the complete workflow menu:
31
+
32
+ ```bash
33
+ fixmap setup
34
+ fixmap features
35
+ ```
36
+
37
+ `fixmap setup` supports Claude Code, Cursor, GitHub Copilot prompt files, and the open Agent Skills layout. It preflights every target, is idempotent, and refuses to overwrite customized commands unless you explicitly pass `--force` after reviewing them.
38
+
30
39
  Use a real branch diff:
31
40
 
32
41
  ```bash
@@ -39,13 +48,66 @@ Machine-readable output:
39
48
  fixmap plan --base main --head HEAD --format json --output fixmap-report.json
40
49
  ```
41
50
 
51
+ Compact output for an agent context window:
52
+
53
+ ```bash
54
+ fixmap plan --issue "password reset emails fail" --format agent
55
+ ```
56
+
57
+ Backtest BM25, FixMap, and Impact Graph against pre-change snapshots from your own repository:
58
+
59
+ ```bash
60
+ fixmap benchmark --repo . --last 50
61
+ ```
62
+
63
+ Build a deterministic source pack for an agent, bounded by an estimated source-token budget:
64
+
65
+ ```bash
66
+ fixmap context --issue "password reset emails fail" --budget 10000
67
+ ```
68
+
69
+ Export the Impact Graph for an issue as Mermaid or JSON:
70
+
71
+ ```bash
72
+ fixmap graph --issue "password reset emails fail" --format mermaid
73
+ ```
74
+
75
+ Continuously compare agent edits with a saved plan and recalculate impact:
76
+
77
+ ```bash
78
+ fixmap watch --report plan.json --repo . --include-untracked
79
+ ```
80
+
42
81
  Public GitHub issue, pull request, and repository URL modes are available in the CLI and MCP server for issue-only analysis. FixMap fetches task context anonymously, shallow-clones the default branch into an isolated temporary directory, disables credentials and repository execution surfaces, and removes the checkout before returning. Clone locally to use `--diff`, `--base`, `--head`, or working-tree inputs.
43
82
 
44
83
  For long task text, use `--issue-file task.md` or pipe text to `--issue -`. A leading `@` in `--issue` is ordinary task text; only the explicit file flag reads from disk. A one-off `npx -y @aryam/fixmap@latest ...` run is also available, but npm may choose an existing project-local FixMap first. Run `fixmap doctor`, treat its printed running version as authoritative, and update or remove a stale install. For a reproducible clean test, install the exact version into an isolated npm prefix and invoke that prefix's `fixmap` shim directly; the repository README includes complete PowerShell and POSIX commands.
45
84
 
85
+ ## Complete feature catalog
86
+
87
+ - **Plan** — rank primary context, then map likely impact from imports, reverse dependents, related tests, and repeated Git co-change relationships. Impact paths are inspection candidates, not assumed edits.
88
+ - **Context Pack** — use `fixmap context` to package deterministic line ranges from primary and impact files within an estimated source-token budget. Markdown is readable by people and agents; JSON preserves roles, reasons, line ranges, truncation, and omitted-file diagnostics.
89
+ - **Graph export** — use `fixmap graph` to export the evidence-backed Impact Graph as portable Mermaid or versioned JSON while preserving relationship direction.
90
+ - **Explain** — use `--explain <path>` to distinguish ranked, below-cutoff, tie-truncated, excluded, and not-scanned paths.
91
+ - **Compare** — use `--compare <report.json>` to measure how a refined task changed ranks, scores, confidence, and grounding.
92
+ - **Verify** — compare a saved plan with the completed diff or working tree and recalculate impact around the files actually changed; errors fail by default and `--fail-on warning` provides an opt-in strict CI gate without pretending FixMap ran tests or proved correctness.
93
+ - **Repository benchmark** — use `fixmap benchmark --repo . --last 50` to compare BM25, FixMap, and Impact Graph on identical parent-snapshot corpora. Primary hits use maintained source rather than generated twins, and repository code is never executed.
94
+ - **Watch** — use `fixmap watch --report plan.json --repo .` to emit drift findings and a recalculated Impact Graph whenever the working tree changes. JSON format is newline-delimited for agent consumers.
95
+ - **Validate** — run `fixmap validate <report.json>` to check report compatibility without writing custom JavaScript.
96
+ - **Focus controls** — cap output with `--limit`, repeat `--exclude`, or use ordered `.fixmapignore` patterns with negation. Pasted absolute paths inside the repository are normalized, and unmatched patterns produce a warning.
97
+ - **Live changes** — `--working-tree` maps staged and unstaged tracked edits; `--include-untracked` opts new files into the changed-file set.
98
+ - **Exact-state cache** — clean and tracked dirty git states are cached by repository, commit, status, and binary diff. Cache hits report age, entries expire after seven days, and `--no-cache` reports a fresh bypass.
99
+ - **Artifact isolation** — current issue, comparison, verification, and output files are removed from ranking, change detection, and cache state, so a saved plan cannot recommend or invalidate itself.
100
+ - **Doctor** — report the running version, resolved binary, global/PATH shadows, Node compatibility, and an optionally requested npm version.
101
+ - **MCP** — expose Plan, Context, Graph, Explain, Compare, Verify, and Doctor as seven local stdio tools.
102
+ - **Slash-command discovery** — `fixmap setup` installs `/fixmap`; `fixmap features` prints the same complete catalog in Markdown or JSON.
103
+ - **Safe repository handling** — public repositories use isolated temporary checkouts with credentials, hooks, filters, and submodule recursion disabled. Local source is read without installing dependencies or running repository scripts.
104
+ - **Human, agent, and machine output** — Markdown is the default; `--format agent` is a compact handoff, and JSON reports carry `reportVersion: 1` with the documented additive compatibility policy.
105
+
46
106
  ## MCP server
47
107
 
48
- FixMap ships as a Model Context Protocol server with `fixmap_plan` and `fixmap_verify`, so coding agents can plan first and compare the resulting diff with that plan afterwards.
108
+ FixMap ships seven Model Context Protocol tools: `fixmap_plan`, `fixmap_context`, `fixmap_graph`, `fixmap_explain`, `fixmap_compare`, `fixmap_verify`, and `fixmap_doctor`. Plan, Context, Graph, Explain, and Verify accept `noCache: true` when an agent needs a fresh repository scan rather than an exact-state cache hit.
109
+
110
+ Context budgets use a deterministic estimate of one token per four UTF-8 bytes of source. Metadata does not consume that source budget. Scanner sample limits are reported per snippet with `sourceTruncated`, so consumers can distinguish a complete file from a bounded sample.
49
111
 
50
112
  Claude Code:
51
113
 
@@ -70,12 +132,19 @@ Cursor, Windsurf, or any MCP client:
70
132
 
71
133
  ```text
72
134
  fixmap plan Generate a FixMap report for a task or diff
135
+ fixmap context Build a budgeted Markdown or JSON source pack
136
+ fixmap graph Export the Impact Graph as Mermaid or JSON
73
137
  fixmap verify Compare a saved plan with the diff that followed
138
+ fixmap benchmark Backtest BM25, FixMap, and Impact Graph on local Git history
139
+ fixmap watch Recheck working-tree drift and impact whenever edits change
74
140
  fixmap doctor Report the resolved version and any shadowing install
141
+ fixmap validate Validate a saved FixMap JSON report
142
+ fixmap features List every FixMap capability in Markdown or JSON
143
+ fixmap setup Install /fixmap discovery for supported coding agents
75
144
  fixmap mcp Run FixMap as an MCP server over stdio
76
145
 
77
146
  --issue <text|url> Issue text, task description, or public GitHub issue or pull request URL
78
- --issue-file <file> Read task text from a UTF-8 or UTF-16 file, or - for stdin
147
+ --issue-file <file> Read UTF-8/UTF-16 task text (including BOM-less UTF-16), or - for stdin
79
148
  --diff <spec> Git diff spec, such as main...HEAD
80
149
  --base <ref> Base ref for diffing when --diff is not given
81
150
  --head <ref> Head ref for diffing (defaults to HEAD)
@@ -85,9 +154,12 @@ fixmap mcp Run FixMap as an MCP server over stdio
85
154
  --compare <file> Diff this plan against a saved JSON plan
86
155
  --limit <n> Cap reported context files, 1 to 20 (default 8)
87
156
  --exclude <pattern> Leave paths out of ranking; repeatable, gitignore-flavored
157
+ --no-cache Bypass the exact-state repository scan cache
88
158
  --repo <source> Local path, file:// URL, or public GitHub HTTPS/SSH URL
89
- --format <fmt> Output format: markdown (default) or json
159
+ --format <fmt> Plan: markdown, agent, or json; context: markdown or json; graph: mermaid or json
160
+ --budget <tokens> Context estimated source-token budget, 256 to 200000 (default 10000)
90
161
  --output <file> Write the report to a file instead of stdout
162
+ --fail-on <level> Verify exit policy: error (default) or warning
91
163
  ```
92
164
 
93
165
  ## Example output
@@ -96,6 +168,9 @@ fixmap mcp Run FixMap as an MCP server over stdio
96
168
  ## Context Files
97
169
  - src/auth/reset-password.ts (high confidence): path and content match
98
170
 
171
+ ## Impact Graph
172
+ - src/session.ts (high confidence): imported by the primary edit candidate
173
+
99
174
  ## Test Route
100
175
  - npm --prefix apps/api run test
101
176
 
@@ -0,0 +1,113 @@
1
+ export type AgentTarget = "claude" | "cursor" | "copilot" | "agents";
2
+ export declare const FIXMAP_FEATURES: readonly [{
3
+ readonly name: "Plan";
4
+ readonly command: "fixmap plan";
5
+ readonly detail: "Rank context files, test routes, risks, changed files, and uncertainty from a task, issue URL, diff, or working tree.";
6
+ }, {
7
+ readonly name: "Impact Graph";
8
+ readonly command: "fixmap plan";
9
+ readonly detail: "Map likely dependents, dependencies, tests, and repeated Git co-change relationships around the primary context, with explicit evidence.";
10
+ }, {
11
+ readonly name: "Context Pack";
12
+ readonly command: "fixmap context --issue <task> --budget 10000";
13
+ readonly detail: "Select task-aware source ranges from primary and impact files within a deterministic token budget.";
14
+ }, {
15
+ readonly name: "Graph export";
16
+ readonly command: "fixmap graph --issue <task> --format mermaid";
17
+ readonly detail: "Export imports, reverse dependents, routed tests, and co-change evidence as Mermaid or JSON.";
18
+ }, {
19
+ readonly name: "Explain";
20
+ readonly command: "fixmap plan --explain <path>";
21
+ readonly detail: "Show whether a path ranked, tied below the limit, was excluded, or was never scanned.";
22
+ }, {
23
+ readonly name: "Compare";
24
+ readonly command: "fixmap plan --compare <report.json>";
25
+ readonly detail: "Compare a refined task and current plan with an earlier JSON report.";
26
+ }, {
27
+ readonly name: "Verify";
28
+ readonly command: "fixmap verify --report <report.json>";
29
+ readonly detail: "Compare the completed diff or working tree with the saved plan; add --fail-on warning for a strict CI gate.";
30
+ }, {
31
+ readonly name: "Validate";
32
+ readonly command: "fixmap validate <report.json>";
33
+ readonly detail: "Check a saved report against FixMap's structural compatibility contract.";
34
+ }, {
35
+ readonly name: "Doctor";
36
+ readonly command: "fixmap doctor";
37
+ readonly detail: "Diagnose stale local, global, PATH, and npx install shadows.";
38
+ }, {
39
+ readonly name: "MCP";
40
+ readonly command: "fixmap mcp";
41
+ readonly detail: "Expose Plan, Context, Graph, Explain, Compare, Verify, and Doctor over local stdio.";
42
+ }, {
43
+ readonly name: "Public tasks";
44
+ readonly command: "fixmap owner/repository#123";
45
+ readonly detail: "Fetch public GitHub issue or pull-request text anonymously and scan its repository in an isolated checkout.";
46
+ }, {
47
+ readonly name: "Repository sources";
48
+ readonly command: "--repo <path|url> --ref <branch|tag>";
49
+ readonly detail: "Map a local checkout, file URL, directory archive, or a named branch or tag from a public GitHub repository.";
50
+ }, {
51
+ readonly name: "Task files";
52
+ readonly command: "--issue-file <file|->";
53
+ readonly detail: "Read long task text from UTF-8, UTF-16, or stdin, including BOM-less UTF-16 from common Windows tools.";
54
+ }, {
55
+ readonly name: "Focus";
56
+ readonly command: "--limit, --exclude, .fixmapignore";
57
+ readonly detail: "Narrow ranking without changing the repository.";
58
+ }, {
59
+ readonly name: "Live changes";
60
+ readonly command: "--working-tree --include-untracked";
61
+ readonly detail: "Map staged, unstaged, and optionally untracked work against HEAD.";
62
+ }, {
63
+ readonly name: "Fresh scan";
64
+ readonly command: "--no-cache";
65
+ readonly detail: "Bypass the exact git-state cache with CLI --no-cache, MCP noCache: true, or Action no-cache: true, and report that a fresh scan was used.";
66
+ }, {
67
+ readonly name: "Machine output";
68
+ readonly command: "--format json --output <file>";
69
+ readonly detail: "Emit a versioned JSON contract or readable Markdown without executing repository code.";
70
+ }, {
71
+ readonly name: "Compact agent output";
72
+ readonly command: "--format agent";
73
+ readonly detail: "Emit EDIT CANDIDATE, INSPECT, TEST, RISK, AVOID, and UNCERTAINTY sections for a small context window.";
74
+ }, {
75
+ readonly name: "Repository benchmark";
76
+ readonly command: "fixmap benchmark --repo . --last 50";
77
+ readonly detail: "Backtest BM25, FixMap, and Impact Graph on historical parent snapshots with history cut off before each target change.";
78
+ }, {
79
+ readonly name: "Watch";
80
+ readonly command: "fixmap watch --report plan.json --repo .";
81
+ readonly detail: "Continuously verify working-tree drift and recalculate impact as an agent edits.";
82
+ }, {
83
+ readonly name: "Test routing";
84
+ readonly command: "fixmap plan";
85
+ readonly detail: "Detect package, workspace, and language test commands, related tests, and skipped or gated suites.";
86
+ }, {
87
+ readonly name: "Risk and diagnostics";
88
+ readonly command: "fixmap plan";
89
+ readonly detail: "Report bounded risk areas, grounding quality, unread content, scan limits, package-manager conflicts, and unresolved diffs.";
90
+ }, {
91
+ readonly name: "GitHub Action";
92
+ readonly command: "uses: aryamthecodebreaker/FixMap@<version>";
93
+ readonly detail: "Plan or verify pull requests with bounded summaries, outputs, and one updated comment.";
94
+ }, {
95
+ readonly name: "Agent setup";
96
+ readonly command: "fixmap setup";
97
+ readonly detail: "Install the discoverable /fixmap command for Claude Code, Cursor, GitHub Copilot, or Agent Skills.";
98
+ }];
99
+ export declare function renderFeatureCatalog(format?: "markdown" | "json"): string;
100
+ export declare function installAgentCommands(input: {
101
+ repoRoot: string;
102
+ targets: AgentTarget[];
103
+ force?: boolean;
104
+ }, dependencies?: {
105
+ /** Internal seam for deterministic race/failure tests; production setup never supplies it. */
106
+ beforeCommit?: (entry: {
107
+ path: string;
108
+ displayPath: string;
109
+ }, index: number) => Promise<void>;
110
+ }): Promise<Array<{
111
+ path: string;
112
+ status: "created" | "unchanged" | "updated";
113
+ }>>;
@@ -0,0 +1,369 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { lstat, mkdir, open, readFile, realpath, rename, rmdir, stat, unlink, writeFile } from "node:fs/promises";
3
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { setTimeout as delay } from "node:timers/promises";
5
+ export const FIXMAP_FEATURES = [
6
+ { name: "Plan", command: "fixmap plan", detail: "Rank context files, test routes, risks, changed files, and uncertainty from a task, issue URL, diff, or working tree." },
7
+ { name: "Impact Graph", command: "fixmap plan", detail: "Map likely dependents, dependencies, tests, and repeated Git co-change relationships around the primary context, with explicit evidence." },
8
+ { name: "Context Pack", command: "fixmap context --issue <task> --budget 10000", detail: "Select task-aware source ranges from primary and impact files within a deterministic token budget." },
9
+ { name: "Graph export", command: "fixmap graph --issue <task> --format mermaid", detail: "Export imports, reverse dependents, routed tests, and co-change evidence as Mermaid or JSON." },
10
+ { name: "Explain", command: "fixmap plan --explain <path>", detail: "Show whether a path ranked, tied below the limit, was excluded, or was never scanned." },
11
+ { name: "Compare", command: "fixmap plan --compare <report.json>", detail: "Compare a refined task and current plan with an earlier JSON report." },
12
+ { name: "Verify", command: "fixmap verify --report <report.json>", detail: "Compare the completed diff or working tree with the saved plan; add --fail-on warning for a strict CI gate." },
13
+ { name: "Validate", command: "fixmap validate <report.json>", detail: "Check a saved report against FixMap's structural compatibility contract." },
14
+ { name: "Doctor", command: "fixmap doctor", detail: "Diagnose stale local, global, PATH, and npx install shadows." },
15
+ { name: "MCP", command: "fixmap mcp", detail: "Expose Plan, Context, Graph, Explain, Compare, Verify, and Doctor over local stdio." },
16
+ { 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." },
17
+ { name: "Repository sources", command: "--repo <path|url> --ref <branch|tag>", detail: "Map a local checkout, file URL, directory archive, or a named branch or tag from a public GitHub repository." },
18
+ { name: "Task files", command: "--issue-file <file|->", detail: "Read long task text from UTF-8, UTF-16, or stdin, including BOM-less UTF-16 from common Windows tools." },
19
+ { name: "Focus", command: "--limit, --exclude, .fixmapignore", detail: "Narrow ranking without changing the repository." },
20
+ { name: "Live changes", command: "--working-tree --include-untracked", detail: "Map staged, unstaged, and optionally untracked work against HEAD." },
21
+ { name: "Fresh scan", command: "--no-cache", detail: "Bypass the exact git-state cache with CLI --no-cache, MCP noCache: true, or Action no-cache: true, and report that a fresh scan was used." },
22
+ { name: "Machine output", command: "--format json --output <file>", detail: "Emit a versioned JSON contract or readable Markdown without executing repository code." },
23
+ { name: "Compact agent output", command: "--format agent", detail: "Emit EDIT CANDIDATE, INSPECT, TEST, RISK, AVOID, and UNCERTAINTY sections for a small context window." },
24
+ { name: "Repository benchmark", command: "fixmap benchmark --repo . --last 50", detail: "Backtest BM25, FixMap, and Impact Graph on historical parent snapshots with history cut off before each target change." },
25
+ { name: "Watch", command: "fixmap watch --report plan.json --repo .", detail: "Continuously verify working-tree drift and recalculate impact as an agent edits." },
26
+ { name: "Test routing", command: "fixmap plan", detail: "Detect package, workspace, and language test commands, related tests, and skipped or gated suites." },
27
+ { name: "Risk and diagnostics", command: "fixmap plan", detail: "Report bounded risk areas, grounding quality, unread content, scan limits, package-manager conflicts, and unresolved diffs." },
28
+ { name: "GitHub Action", command: "uses: aryamthecodebreaker/FixMap@<version>", detail: "Plan or verify pull requests with bounded summaries, outputs, and one updated comment." },
29
+ { name: "Agent setup", command: "fixmap setup", detail: "Install the discoverable /fixmap command for Claude Code, Cursor, GitHub Copilot, or Agent Skills." }
30
+ ];
31
+ export function renderFeatureCatalog(format = "markdown") {
32
+ if (format === "json")
33
+ return `${JSON.stringify({ features: FIXMAP_FEATURES }, null, 2)}\n`;
34
+ return [
35
+ "# FixMap features",
36
+ "",
37
+ ...FIXMAP_FEATURES.flatMap((feature) => [
38
+ `- **${feature.name}** — \`${feature.command}\``,
39
+ ` ${feature.detail}`
40
+ ]),
41
+ "",
42
+ "Run `fixmap setup` to install `/fixmap` discovery for supported coding agents.",
43
+ ""
44
+ ].join("\n");
45
+ }
46
+ const SHARED_INSTRUCTIONS = `You are the FixMap workflow assistant for this repository.
47
+
48
+ When this command is invoked without a task, run \`fixmap features\` and present every feature in a compact menu. Do not edit files. Ask which workflow the user wants.
49
+
50
+ When the invocation includes a task, issue URL, diff, file path, or workflow name:
51
+
52
+ 1. Run \`fixmap features\` if the requested capability is ambiguous.
53
+ 2. Use the matching local command: Plan, Context, Graph, Explain, Compare, Verify, Watch, Benchmark, Validate, Doctor, or MCP.
54
+ 3. Read the Impact Graph as files to inspect, not a claim that each file must change. Preserve each relationship's evidence.
55
+ 4. Prefer \`--format agent\` when context is constrained, \`fixmap watch\` while an agent is editing, and \`fixmap benchmark\` when the user asks whether FixMap works on this repository.
56
+ 5. Preserve the user's repository and never imply that FixMap ran tests or proved correctness; it produces a starting map and verification findings.
57
+ 6. Report the exact command used and summarize files, impact, checks, risks, and diagnostics.
58
+
59
+ Prefer \`fixmap plan --issue "$ARGUMENTS" --repo .\` for task text. Use a canonical public GitHub issue URL directly when one is provided.`;
60
+ const templates = {
61
+ claude: {
62
+ path: ".claude/skills/fixmap/SKILL.md",
63
+ contents: `---\nname: fixmap\ndescription: Discover and run every FixMap repository-mapping workflow\ndisable-model-invocation: true\nargument-hint: [task, issue URL, file, diff, or workflow]\n---\n\n${SHARED_INSTRUCTIONS}\n`
64
+ },
65
+ cursor: {
66
+ path: ".cursor/commands/fixmap.md",
67
+ contents: `---\ndescription: List or run every FixMap repository-mapping workflow\n---\n\n${SHARED_INSTRUCTIONS}\n`
68
+ },
69
+ copilot: {
70
+ path: ".github/prompts/fixmap.prompt.md",
71
+ contents: `---\nagent: 'agent'\ndescription: 'List or run every FixMap repository-mapping workflow'\n---\n\n${SHARED_INSTRUCTIONS}\n`
72
+ },
73
+ agents: {
74
+ path: ".agents/skills/fixmap/SKILL.md",
75
+ contents: `---\nname: fixmap\ndescription: Discover and run every FixMap repository-mapping workflow\n---\n\n${SHARED_INSTRUCTIONS}\n`
76
+ }
77
+ };
78
+ export async function installAgentCommands(input, dependencies = {}) {
79
+ const requestedRoot = resolve(input.repoRoot);
80
+ try {
81
+ if (!(await stat(requestedRoot)).isDirectory())
82
+ throw new Error("not a directory");
83
+ }
84
+ catch {
85
+ throw new Error(`Setup repository "${requestedRoot}" does not exist or is not a directory.`);
86
+ }
87
+ const root = await realpath(requestedRoot);
88
+ const setupLock = await acquireSetupLock(root);
89
+ try {
90
+ const prepared = [];
91
+ // Preflight every target before writing any of them. A customized command or unsafe link
92
+ // must not leave a half-installed multi-agent setup behind.
93
+ for (const target of input.targets) {
94
+ const template = templates[target];
95
+ const path = join(root, template.path);
96
+ const displayPath = relative(root, path).replace(/\\/g, "/");
97
+ await assertSafeTarget(root, path, displayPath);
98
+ let existing;
99
+ try {
100
+ existing = await readFile(path, "utf8");
101
+ }
102
+ catch (error) {
103
+ if (error.code !== "ENOENT") {
104
+ throw new Error(`Could not inspect existing ${displayPath}: ${error instanceof Error ? error.message : String(error)}`);
105
+ }
106
+ }
107
+ if (existing !== undefined && !input.force) {
108
+ if (existing !== template.contents) {
109
+ throw new Error(`Refusing to overwrite existing ${displayPath}. Re-run with --force after reviewing it.`);
110
+ }
111
+ }
112
+ prepared.push({ path, displayPath, contents: template.contents, existing });
113
+ }
114
+ const changed = prepared.filter((entry) => entry.existing !== entry.contents);
115
+ const staged = [];
116
+ const committed = [];
117
+ const createdDirectories = new Set();
118
+ try {
119
+ // Stage every new command beside its destination before mutating any destination. The
120
+ // random sibling name means a parent link swapped after preflight cannot redirect the
121
+ // final rename: that name will not exist in the attacker's directory, so rename fails.
122
+ for (const entry of changed) {
123
+ const parent = dirname(entry.path);
124
+ const firstCreated = await mkdir(parent, { recursive: true });
125
+ if (firstCreated)
126
+ rememberCreatedDirectories(createdDirectories, firstCreated, parent);
127
+ await assertSafeTarget(root, entry.path, entry.displayPath);
128
+ const stagedPath = join(parent, `.${basename(entry.path)}.fixmap-${randomUUID()}.tmp`);
129
+ await writeFile(stagedPath, entry.contents, { encoding: "utf8", flag: "wx" });
130
+ await assertSafeTarget(root, stagedPath, `${entry.displayPath} staging file`);
131
+ staged.push({ ...entry, stagedPath });
132
+ }
133
+ for (let index = 0; index < staged.length; index += 1) {
134
+ const entry = staged[index];
135
+ await dependencies.beforeCommit?.({ path: entry.path, displayPath: entry.displayPath }, index);
136
+ // Close the original check-then-write window. rename replaces a final symlink or
137
+ // hardlink directory entry rather than following it, but rejecting one is clearer and
138
+ // preserves an unexpected concurrent change instead of silently replacing it.
139
+ await assertTargetUnchanged(root, entry.path, entry.displayPath, entry.existing);
140
+ await assertSafeTarget(root, entry.stagedPath, `${entry.displayPath} staging file`);
141
+ await rename(entry.stagedPath, entry.path);
142
+ committed.push(entry);
143
+ }
144
+ }
145
+ catch (error) {
146
+ const rollbackErrors = [];
147
+ for (const entry of committed.reverse()) {
148
+ try {
149
+ if (entry.existing === undefined) {
150
+ await assertSafeTarget(root, entry.path, entry.displayPath);
151
+ const current = await readFile(entry.path, "utf8");
152
+ if (current !== entry.contents) {
153
+ throw new Error("the installed file changed before rollback");
154
+ }
155
+ await unlink(entry.path);
156
+ }
157
+ else {
158
+ await replaceWithContents(root, entry.path, entry.displayPath, entry.existing);
159
+ }
160
+ }
161
+ catch (rollbackError) {
162
+ rollbackErrors.push(`${entry.displayPath}: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`);
163
+ }
164
+ }
165
+ await cleanupStagingFiles(staged);
166
+ await cleanupCreatedDirectories(createdDirectories);
167
+ const detail = error instanceof Error ? error.message : String(error);
168
+ if (rollbackErrors.length > 0) {
169
+ throw new Error(`${detail} Setup rollback also failed for ${rollbackErrors.join("; ")}.`);
170
+ }
171
+ throw error;
172
+ }
173
+ const results = prepared.map((entry) => ({
174
+ path: entry.displayPath,
175
+ status: entry.existing === entry.contents
176
+ ? "unchanged"
177
+ : entry.existing === undefined
178
+ ? "created"
179
+ : "updated"
180
+ }));
181
+ return results;
182
+ }
183
+ finally {
184
+ await releaseSetupLock(setupLock);
185
+ }
186
+ }
187
+ async function assertTargetUnchanged(root, target, displayPath, expectedContents) {
188
+ await assertSafeTarget(root, target, displayPath);
189
+ try {
190
+ const currentContents = await readFile(target, "utf8");
191
+ if (expectedContents === undefined || currentContents !== expectedContents) {
192
+ throw new Error(`Refusing to write ${displayPath} because it changed while setup was running.`);
193
+ }
194
+ }
195
+ catch (error) {
196
+ if (error.code !== "ENOENT")
197
+ throw error;
198
+ if (expectedContents !== undefined) {
199
+ throw new Error(`Refusing to write ${displayPath} because it changed while setup was running.`);
200
+ }
201
+ }
202
+ }
203
+ async function assertSafeTarget(root, target, displayPath) {
204
+ try {
205
+ const targetMetadata = await lstat(target);
206
+ if (targetMetadata.isSymbolicLink()) {
207
+ throw new Error(`Refusing to write ${displayPath} because the target is a symbolic link.`);
208
+ }
209
+ if (!targetMetadata.isFile()) {
210
+ throw new Error(`Refusing to write ${displayPath} because the target is not a regular file.`);
211
+ }
212
+ if (targetMetadata.nlink > 1) {
213
+ throw new Error(`Refusing to write ${displayPath} because the target is hard-linked to another file.`);
214
+ }
215
+ }
216
+ catch (error) {
217
+ if (error.code !== "ENOENT")
218
+ throw error;
219
+ }
220
+ let ancestor = dirname(target);
221
+ while (true) {
222
+ try {
223
+ const ancestorMetadata = await lstat(ancestor);
224
+ if (!ancestorMetadata.isDirectory() && !ancestorMetadata.isSymbolicLink()) {
225
+ throw new Error(`Refusing to write ${displayPath} because ${ancestor} is not a directory.`);
226
+ }
227
+ const resolvedAncestor = await realpath(ancestor);
228
+ const distance = relative(root, resolvedAncestor);
229
+ if (distance === ".." || distance.startsWith(`..${sep}`) || isAbsolute(distance)) {
230
+ throw new Error(`Refusing to write ${displayPath} because its parent resolves outside the setup repository.`);
231
+ }
232
+ if (ancestorMetadata.isSymbolicLink()) {
233
+ throw new Error(`Refusing to write ${displayPath} because parent ${ancestor} is a symbolic link.`);
234
+ }
235
+ return;
236
+ }
237
+ catch (error) {
238
+ if (error.code !== "ENOENT")
239
+ throw error;
240
+ const parent = dirname(ancestor);
241
+ if (parent === ancestor) {
242
+ throw new Error(`Could not find a safe parent directory for ${displayPath}.`);
243
+ }
244
+ ancestor = parent;
245
+ }
246
+ }
247
+ }
248
+ async function replaceWithContents(root, target, displayPath, contents) {
249
+ const parent = dirname(target);
250
+ await assertSafeTarget(root, target, displayPath);
251
+ const stagedPath = join(parent, `.${basename(target)}.fixmap-rollback-${randomUUID()}.tmp`);
252
+ try {
253
+ await writeFile(stagedPath, contents, { encoding: "utf8", flag: "wx" });
254
+ await assertSafeTarget(root, stagedPath, `${displayPath} rollback file`);
255
+ await assertSafeTarget(root, target, displayPath);
256
+ await rename(stagedPath, target);
257
+ }
258
+ finally {
259
+ try {
260
+ await unlink(stagedPath);
261
+ }
262
+ catch (error) {
263
+ if (error.code !== "ENOENT")
264
+ throw error;
265
+ }
266
+ }
267
+ }
268
+ async function cleanupStagingFiles(entries) {
269
+ for (const entry of entries) {
270
+ try {
271
+ await unlink(entry.stagedPath);
272
+ }
273
+ catch (error) {
274
+ if (error.code !== "ENOENT") {
275
+ // Cleanup cannot make the original installation failure safer or more actionable.
276
+ // A unique .tmp file may remain, but no /fixmap command points at it.
277
+ }
278
+ }
279
+ }
280
+ }
281
+ function rememberCreatedDirectories(paths, firstCreated, leaf) {
282
+ const boundary = dirname(resolve(firstCreated));
283
+ let current = resolve(leaf);
284
+ while (current !== boundary) {
285
+ paths.add(current);
286
+ const parent = dirname(current);
287
+ if (parent === current)
288
+ break;
289
+ current = parent;
290
+ }
291
+ }
292
+ async function cleanupCreatedDirectories(paths) {
293
+ const deepestFirst = [...paths].sort((left, right) => right.length - left.length);
294
+ for (const path of deepestFirst) {
295
+ try {
296
+ await rmdir(path);
297
+ }
298
+ catch (error) {
299
+ if (!new Set(["ENOENT", "ENOTEMPTY", "EEXIST"]).has(String(error.code))) {
300
+ // Never turn cleanup of an empty setup directory into a broader deletion.
301
+ }
302
+ }
303
+ }
304
+ }
305
+ async function acquireSetupLock(root) {
306
+ const path = join(root, ".fixmap-setup.lock");
307
+ const deadline = Date.now() + 10_000;
308
+ while (true) {
309
+ const token = `${process.pid}:${Date.now()}:${randomUUID()}`;
310
+ try {
311
+ const handle = await open(path, "wx", 0o600);
312
+ try {
313
+ await handle.writeFile(token, "utf8");
314
+ return { handle, path, token };
315
+ }
316
+ catch (error) {
317
+ await handle.close();
318
+ try {
319
+ await unlink(path);
320
+ }
321
+ catch { /* preserve the original lock creation error */ }
322
+ throw error;
323
+ }
324
+ }
325
+ catch (error) {
326
+ const code = String(error.code ?? "");
327
+ if (!new Set(["EEXIST", "EPERM", "EACCES"]).has(code))
328
+ throw error;
329
+ // Windows can briefly report EPERM while another setup closes and removes the lock.
330
+ // Retry that directory-entry transition, but preserve a persistent permission error
331
+ // when no lock file actually exists instead of misreporting it as another setup.
332
+ let lockPresent = code === "EEXIST";
333
+ if (!lockPresent) {
334
+ try {
335
+ await lstat(path);
336
+ lockPresent = true;
337
+ }
338
+ catch (inspectionError) {
339
+ if (inspectionError.code !== "ENOENT")
340
+ lockPresent = true;
341
+ }
342
+ }
343
+ if (Date.now() >= deadline) {
344
+ if (!lockPresent && code !== "EEXIST")
345
+ throw error;
346
+ throw new Error(`Another FixMap setup is still using "${path}". Wait for it to finish, or remove the lock only after confirming no setup process is running.`);
347
+ }
348
+ await delay(25);
349
+ }
350
+ }
351
+ }
352
+ async function releaseSetupLock(lock) {
353
+ await lock.handle.close();
354
+ try {
355
+ const [contents, metadata] = await Promise.all([
356
+ readFile(lock.path, "utf8"),
357
+ lstat(lock.path)
358
+ ]);
359
+ if (!metadata.isFile() || metadata.isSymbolicLink() || metadata.nlink > 1 || contents !== lock.token) {
360
+ throw new Error(`FixMap setup lock "${lock.path}" changed while setup was running; it was left in place for review.`);
361
+ }
362
+ await unlink(lock.path);
363
+ }
364
+ catch (error) {
365
+ if (error.code !== "ENOENT")
366
+ throw error;
367
+ }
368
+ }
369
+ //# sourceMappingURL=agent-setup.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-setup.js","sourceRoot":"","sources":["../src/agent-setup.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAmB,MAAM,kBAAkB,CAAC;AACnI,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACxF,OAAO,EAAE,UAAU,IAAI,KAAK,EAAE,MAAM,sBAA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