@aryam/fixmap 0.8.7 → 0.8.9

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.
@@ -1,10 +1,13 @@
1
1
  import { readFileSync } from "node:fs";
2
- import { writeFile } from "node:fs/promises";
3
- import { dirname, join } from "node:path";
2
+ import { realpath, stat, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
5
  import { fileURLToPath } from "node:url";
5
- import { compareReports, explainFile, renderComparisonMarkdown, renderExplanationMarkdown, renderJsonReport, renderVerifyMarkdown, resolveExclusions, verifyPlan, renderMarkdownReport, scanRepo } from "@aryam/fixmap-core";
6
+ import { compareReports, explainFile, quoteCliValue as formatCliValue, renderComparisonMarkdown, renderExplanationMarkdown, renderJsonReport, renderVerifyMarkdown, resolveExclusions, verifyPlan, renderMarkdownReport, scanRepo, stripByteOrderMark, validateFixMapReport } from "@aryam/fixmap-core";
6
7
  import { runDoctorChecks, renderDoctorReport } from "./doctor.js";
7
- import { buildReportForRepository, parseGitHubIssueSource, progressRequested, tryParseGitHubIssueSource } from "./repository-source.js";
8
+ import { installAgentCommands, renderFeatureCatalog } from "./agent-setup.js";
9
+ import { clarifyMissingPath } from "./explain-path.js";
10
+ import { buildReportForRepository, isSafeGitRefName, parseGitHubIssueSource, progressRequested, tryParseGitHubIssueSource } from "./repository-source.js";
8
11
  export const USAGE = `FixMap maps an issue, prompt, or diff to context files, test routes, and review risks.
9
12
 
10
13
  Usage:
@@ -16,19 +19,29 @@ Usage:
16
19
  fixmap plan --issue-file task.md
17
20
  fixmap plan --issue -
18
21
  fixmap plan --issue "Fix login" --repo https://github.com/owner/repository
22
+ fixmap plan --issue "Fix login" --repo https://github.com/owner/repository --ref release-2.x
19
23
  fixmap plan --diff main...HEAD
20
24
  fixmap plan --working-tree --include-untracked --limit 12 --exclude "docs/**"
21
- fixmap plan --issue "Fix login" --format json --output current.json --compare previous.json
25
+ fixmap plan --no-cache --issue "Fix login" --repo .
26
+ fixmap plan --issue "Fix login" --format json --output plan.json
27
+ fixmap plan --issue "Fix login in auth middleware" --compare plan.json
22
28
  fixmap plan --base main --head HEAD --format json
23
- fixmap verify --report fixmap-report.json --diff main...HEAD
24
- fixmap verify --report fixmap-report.json --working-tree
29
+ fixmap verify --report plan.json --diff main...HEAD
30
+ fixmap verify --report plan.json --working-tree
31
+ fixmap verify --report plan.json --working-tree --fail-on warning
25
32
  fixmap doctor --format json
26
- fixmap mcp
33
+ fixmap validate plan.json
34
+ fixmap features
35
+ fixmap setup [--agent claude|cursor|copilot|agents|all] [--repo <path>]
36
+ fixmap mcp [--repo <path>]
27
37
 
28
38
  Commands:
29
39
  plan Generate a FixMap report for a task or diff
30
40
  verify Compare a saved report against the diff that followed it
31
41
  doctor Check the FixMap install for stale global or npx shadows
42
+ validate Validate a saved FixMap JSON report
43
+ features List every FixMap capability and its command
44
+ setup Install a discoverable /fixmap command for coding agents
32
45
  mcp Run FixMap as an MCP server over stdio for AI coding agents
33
46
 
34
47
  Options:
@@ -39,7 +52,9 @@ Options:
39
52
  --head <ref> Head ref for diffing (defaults to HEAD)
40
53
  --working-tree Map staged and unstaged changes against HEAD
41
54
  --include-untracked With --working-tree, also include untracked files
55
+ --no-cache Bypass the exact git-state repository scan cache
42
56
  --repo <source> Local path or public GitHub HTTPS URL (defaults to current directory)
57
+ --ref <branch|tag> Branch or tag to scan when --repo is a remote GitHub URL
43
58
  --limit <n> Maximum context files to report (default 8, max 20)
44
59
  --exclude <glob> Path pattern to leave out of ranking (repeatable)
45
60
  --format <fmt> Output format: markdown (default) or json
@@ -47,15 +62,21 @@ Options:
47
62
  --explain <path> Explain why one file was ranked where it was, or left out
48
63
  --compare <file> Compare this plan against an earlier JSON report
49
64
  --report <file> Verify command only: the JSON report the change was planned from
65
+ --fail-on <level> Verify exit policy: error (default) or warning
50
66
  --help, -h Show this help
51
67
  --version, -v Show the FixMap version
52
68
 
53
69
  A repository may also list exclusion patterns in .fixmapignore, one per line. Supported
54
- syntax is *, **, ?, root-leading /, directory-trailing /, comments, and ! negation.
70
+ syntax is *, **, ?, repository-root-leading /, directory-trailing /, comments, and ! negation.
71
+ Absolute paths pasted from inside the repository are normalized to repository-relative patterns.
55
72
  Set FIXMAP_PROGRESS=1 to print scan and clone phases to stderr.
73
+ Set FIXMAP_CACHE_DIR to move the OS scan cache, and FIXMAP_VERBOSE_USAGE=1 to include this full help after argument errors.
56
74
  `;
57
75
  const DOCTOR_USAGE = `Usage: fixmap doctor [--format markdown|json]\n\nChecks the running FixMap binary, PATH/global shadows, and known install blind spots.\n`;
58
- const MCP_USAGE = `Usage: fixmap mcp\n\nRuns the FixMap MCP server over stdio. Configure your MCP client to execute \"fixmap mcp\".\n`;
76
+ const MCP_USAGE = `Usage: fixmap mcp [--repo <path>]\n\nRuns the FixMap MCP server over stdio. --repo sets the default local repository for tool calls that omit repo.\n`;
77
+ const FEATURES_USAGE = `Usage: fixmap features [--format markdown|json]\n\nLists every FixMap capability and the command that exposes it.\n`;
78
+ const SETUP_USAGE = `Usage: fixmap setup [--agent claude|cursor|copilot|agents|all] [--repo <path>] [--force]\n\nInstalls a /fixmap command that lists and runs FixMap workflows.\n`;
79
+ const VALIDATE_USAGE = `Usage: fixmap validate <report.json> [--format markdown|json]\n\nChecks a saved report against FixMap's structural compatibility contract.\n`;
59
80
  export async function runCli(args, dependencies = {}) {
60
81
  const stdout = dependencies.stdout ?? ((text) => process.stdout.write(text));
61
82
  const stderr = dependencies.stderr ?? ((text) => process.stderr.write(text));
@@ -69,25 +90,229 @@ export async function runCli(args, dependencies = {}) {
69
90
  return 0;
70
91
  }
71
92
  if (args[0] === "version" || args[0] === "--version" || args[0] === "-v") {
72
- stdout(`${(dependencies.readVersion ?? readVersion)()}\n`);
73
- return 0;
93
+ try {
94
+ stdout(`${(dependencies.readVersion ?? readVersion)()}\n`);
95
+ return 0;
96
+ }
97
+ catch (error) {
98
+ stderr(`${error instanceof Error ? error.message : String(error)}\n`);
99
+ return 1;
100
+ }
74
101
  }
75
102
  if (args[0] === "mcp") {
76
103
  if (args[1] === "--help" || args[1] === "-h") {
77
104
  stdout(MCP_USAGE);
78
105
  return 0;
79
106
  }
80
- if (args.length > 1) {
81
- stderr(`mcp takes no options.\n\n${MCP_USAGE}`);
107
+ const mcpArgs = args.slice(1);
108
+ let defaultRepo;
109
+ if (mcpArgs.length === 1 && mcpArgs[0]?.startsWith("--repo=")) {
110
+ defaultRepo = mcpArgs[0].slice("--repo=".length).trim();
111
+ }
112
+ else if (mcpArgs.length === 2 && mcpArgs[0] === "--repo") {
113
+ defaultRepo = mcpArgs[1]?.trim();
114
+ }
115
+ else if (mcpArgs.length > 0) {
116
+ stderr(`mcp accepts only --repo <path>.\n\n${MCP_USAGE}`);
117
+ return 1;
118
+ }
119
+ if (defaultRepo !== undefined && !defaultRepo) {
120
+ stderr(`--repo needs a non-blank local path.\n\n${MCP_USAGE}`);
121
+ return 1;
122
+ }
123
+ if (defaultRepo && /^https?:\/\//i.test(defaultRepo)) {
124
+ stderr(`mcp --repo needs a local checkout, not a remote URL.\n\n${MCP_USAGE}`);
82
125
  return 1;
83
126
  }
84
127
  const runMcpServer = dependencies.runMcpServer ?? (async () => {
85
128
  const module = await import("./mcp.js");
86
- await module.runMcpServer();
129
+ await module.runMcpServer(defaultRepo);
87
130
  });
88
- await runMcpServer();
131
+ await runMcpServer(defaultRepo);
132
+ return 0;
133
+ }
134
+ if (args[0] === "features") {
135
+ const featureArgs = args.slice(1);
136
+ if (featureArgs[0] === "--help" || featureArgs[0] === "-h") {
137
+ stdout(FEATURES_USAGE);
138
+ return 0;
139
+ }
140
+ let format = "markdown";
141
+ if (featureArgs.length > 0) {
142
+ const value = featureArgs.length === 2 && featureArgs[0] === "--format"
143
+ ? featureArgs[1]
144
+ : featureArgs.length === 1
145
+ ? featureArgs[0]?.match(/^--format=(.+)$/)?.[1]
146
+ : undefined;
147
+ const normalized = value?.trim().toLowerCase();
148
+ if (normalized !== "markdown" && normalized !== "json") {
149
+ stderr('features accepts only --format markdown or --format json.\n');
150
+ return 1;
151
+ }
152
+ format = normalized;
153
+ }
154
+ stdout(renderFeatureCatalog(format));
89
155
  return 0;
90
156
  }
157
+ if (args[0] === "setup") {
158
+ if (args[1] === "--help" || args[1] === "-h") {
159
+ stdout(SETUP_USAGE);
160
+ return 0;
161
+ }
162
+ let repoRoot = process.cwd();
163
+ let targets = ["claude", "cursor", "copilot", "agents"];
164
+ let force = false;
165
+ let repoSeen = false;
166
+ let agentSeen = false;
167
+ for (let index = 1; index < args.length; index += 1) {
168
+ const arg = args[index];
169
+ if (arg === "--force") {
170
+ force = true;
171
+ continue;
172
+ }
173
+ if (arg?.startsWith("--repo=")) {
174
+ if (repoSeen) {
175
+ stderr(`Pass --repo only once.\n\n${SETUP_USAGE}`);
176
+ return 1;
177
+ }
178
+ const value = arg.slice("--repo=".length).trim();
179
+ if (!value) {
180
+ stderr(`--repo requires a directory.\n\n${SETUP_USAGE}`);
181
+ return 1;
182
+ }
183
+ repoRoot = expandHomePath(value);
184
+ repoSeen = true;
185
+ continue;
186
+ }
187
+ if (arg === "--repo") {
188
+ if (repoSeen) {
189
+ stderr(`Pass --repo only once.\n\n${SETUP_USAGE}`);
190
+ return 1;
191
+ }
192
+ const value = args[index + 1];
193
+ if (!value?.trim() || value.startsWith("--")) {
194
+ stderr(`--repo requires a directory.\n\n${SETUP_USAGE}`);
195
+ return 1;
196
+ }
197
+ repoRoot = expandHomePath(value.trim());
198
+ repoSeen = true;
199
+ index += 1;
200
+ continue;
201
+ }
202
+ if (arg?.startsWith("--agent=")) {
203
+ if (agentSeen) {
204
+ stderr(`Pass --agent only once.\n\n${SETUP_USAGE}`);
205
+ return 1;
206
+ }
207
+ const value = arg.slice("--agent=".length).trim().toLowerCase();
208
+ if (!["claude", "cursor", "copilot", "agents", "all"].includes(value)) {
209
+ stderr(`--agent must be claude, cursor, copilot, agents, or all.\n\n${SETUP_USAGE}`);
210
+ return 1;
211
+ }
212
+ targets = value === "all" ? ["claude", "cursor", "copilot", "agents"] : [value];
213
+ agentSeen = true;
214
+ continue;
215
+ }
216
+ if (arg === "--agent") {
217
+ if (agentSeen) {
218
+ stderr(`Pass --agent only once.\n\n${SETUP_USAGE}`);
219
+ return 1;
220
+ }
221
+ const value = args[index + 1]?.trim().toLowerCase();
222
+ if (!value || !["claude", "cursor", "copilot", "agents", "all"].includes(value)) {
223
+ stderr(`--agent must be claude, cursor, copilot, agents, or all.\n\n${SETUP_USAGE}`);
224
+ return 1;
225
+ }
226
+ targets = value === "all" ? ["claude", "cursor", "copilot", "agents"] : [value];
227
+ agentSeen = true;
228
+ index += 1;
229
+ continue;
230
+ }
231
+ stderr(`Unknown setup option: ${arg}\n\n${SETUP_USAGE}`);
232
+ return 1;
233
+ }
234
+ try {
235
+ const installed = await installAgentCommands({ repoRoot, targets, force });
236
+ stdout(`${installed.map((entry) => `${entry.status}: ${entry.path}`).join("\n")}\n\nType /fixmap in a supported agent to open the full FixMap feature menu.\n`);
237
+ return 0;
238
+ }
239
+ catch (error) {
240
+ stderr(`${error instanceof Error ? error.message : String(error)}\n`);
241
+ return 1;
242
+ }
243
+ }
244
+ if (args[0] === "validate") {
245
+ if (args[1] === "--help" || args[1] === "-h") {
246
+ stdout(VALIDATE_USAGE);
247
+ return 0;
248
+ }
249
+ let reportPath;
250
+ let format = "markdown";
251
+ let formatSeen = false;
252
+ for (let index = 1; index < args.length; index += 1) {
253
+ const arg = args[index];
254
+ if (arg === "--format") {
255
+ if (formatSeen) {
256
+ stderr(`Pass --format only once.\n\n${VALIDATE_USAGE}`);
257
+ return 1;
258
+ }
259
+ const value = args[index + 1]?.trim().toLowerCase();
260
+ if (value !== "markdown" && value !== "json") {
261
+ stderr(`--format must be markdown or json.\n\n${VALIDATE_USAGE}`);
262
+ return 1;
263
+ }
264
+ format = value;
265
+ formatSeen = true;
266
+ index += 1;
267
+ }
268
+ else if (arg.startsWith("--format=")) {
269
+ if (formatSeen) {
270
+ stderr(`Pass --format only once.\n\n${VALIDATE_USAGE}`);
271
+ return 1;
272
+ }
273
+ const value = arg.slice("--format=".length).trim().toLowerCase();
274
+ if (value !== "markdown" && value !== "json") {
275
+ stderr(`--format must be markdown or json.\n\n${VALIDATE_USAGE}`);
276
+ return 1;
277
+ }
278
+ format = value;
279
+ formatSeen = true;
280
+ }
281
+ else if (arg.startsWith("-") || reportPath) {
282
+ stderr(`Unknown validate argument: ${arg}\n\n${VALIDATE_USAGE}`);
283
+ return 1;
284
+ }
285
+ else {
286
+ reportPath = expandHomePath(arg);
287
+ }
288
+ }
289
+ if (!reportPath) {
290
+ stderr(`validate requires a report path.\n\n${VALIDATE_USAGE}`);
291
+ return 1;
292
+ }
293
+ try {
294
+ const parsed = JSON.parse(stripByteOrderMark(readFileSync(reportPath, "utf8")));
295
+ const result = validateFixMapReport(parsed, `"${reportPath}"`);
296
+ if (!result.success) {
297
+ stderr(`${result.message}\n`);
298
+ return 1;
299
+ }
300
+ const payload = {
301
+ valid: true,
302
+ path: reportPath,
303
+ reportVersion: result.report.reportVersion ?? "legacy",
304
+ contextFiles: result.report.contextFiles.length
305
+ };
306
+ stdout(format === "json"
307
+ ? `${JSON.stringify(payload, null, 2)}\n`
308
+ : `Valid FixMap report: ${reportPath} (${payload.contextFiles} context files, reportVersion ${payload.reportVersion}).\n`);
309
+ return 0;
310
+ }
311
+ catch (error) {
312
+ stderr(`Could not validate "${reportPath}": ${error instanceof Error ? error.message : String(error)}\n`);
313
+ return 1;
314
+ }
315
+ }
91
316
  if (args[0] === "doctor") {
92
317
  if (args[1] === "--help" || args[1] === "-h") {
93
318
  stdout(DOCTOR_USAGE);
@@ -98,7 +323,7 @@ export async function runCli(args, dependencies = {}) {
98
323
  if (doctorArgs.length > 0) {
99
324
  const match = doctorArgs.length === 2 && doctorArgs[0] === "--format" ? doctorArgs[1] :
100
325
  doctorArgs.length === 1 ? doctorArgs[0]?.match(/^--format=(.+)$/)?.[1] : undefined;
101
- const normalized = match?.toLowerCase();
326
+ const normalized = match?.trim().toLowerCase();
102
327
  if (normalized === "markdown" || normalized === "json")
103
328
  doctorFormat = normalized;
104
329
  else {
@@ -112,7 +337,7 @@ export async function runCli(args, dependencies = {}) {
112
337
  // not read the text and carry on.
113
338
  return report.healthy ? 0 : 1;
114
339
  }
115
- if ((args[0] === "plan" || args[0] === "verify") && args.slice(1).some((arg) => arg === "--help" || arg === "-h")) {
340
+ if ((args[0] === "plan" || args[0] === "verify") && hasStandaloneHelpFlag(args)) {
116
341
  stdout(USAGE);
117
342
  return 0;
118
343
  }
@@ -144,12 +369,30 @@ export async function runCli(args, dependencies = {}) {
144
369
  stderr(`verify does not accept plan-only option(s): ${planOnly.join(", ")}.\n`);
145
370
  return 1;
146
371
  }
372
+ const outputCollision = await describeOutputInputCollision(options);
373
+ if (outputCollision) {
374
+ stderr(`${outputCollision}\n`);
375
+ return 1;
376
+ }
147
377
  return runVerify(options, {
148
378
  stdout,
149
379
  stderr,
150
380
  writeReport: dependencies.writeReport ?? ((path, contents) => writeFile(path, contents, "utf8"))
151
381
  });
152
382
  }
383
+ if (options.reportPath) {
384
+ stderr(withUsageHint("--report is a verify option. Did you mean --output to write this plan to a file?"));
385
+ return 1;
386
+ }
387
+ if (options.failOn) {
388
+ stderr(withUsageHint("--fail-on is a verify option. Use it with fixmap verify."));
389
+ return 1;
390
+ }
391
+ const outputCollision = await describeOutputInputCollision(options);
392
+ if (outputCollision) {
393
+ stderr(`${outputCollision}\n`);
394
+ return 1;
395
+ }
153
396
  try {
154
397
  options.issueText = loadIssueText(options, dependencies.readIssueFile ?? defaultReadIssueFile);
155
398
  }
@@ -169,7 +412,7 @@ export async function runCli(args, dependencies = {}) {
169
412
  stderr("--include-untracked only applies with --working-tree.\n");
170
413
  return 1;
171
414
  }
172
- if (options.workingTree && (options.diffSpec || options.baseRef)) {
415
+ if (options.workingTree && (options.diffSpec || options.baseRef || options.headRef)) {
173
416
  stderr("Use either --working-tree or --diff/--base, not both: they name different sets of changes.\n");
174
417
  return 1;
175
418
  }
@@ -189,6 +432,12 @@ export async function runCli(args, dependencies = {}) {
189
432
  stderr("--working-tree and --include-untracked need a local checkout; remote URL checkouts are always clean.\n");
190
433
  return 1;
191
434
  }
435
+ const remoteIssueSource = options.issueText ? tryParseGitHubIssueSource(options.issueText) : undefined;
436
+ const remoteRepository = /^https?:\/\//i.test(options.repo ?? "") || (!options.repo && remoteIssueSource !== undefined);
437
+ if (options.checkoutRef && !remoteRepository) {
438
+ stderr("--ref only applies when --repo is a remote GitHub URL or the issue URL infers one.\n");
439
+ return 1;
440
+ }
192
441
  const unsupportedTaskUrl = describeUnsupportedTaskUrl(options.issueText);
193
442
  if (unsupportedTaskUrl) {
194
443
  stderr(`${unsupportedTaskUrl}\n`);
@@ -204,18 +453,48 @@ export async function runCli(args, dependencies = {}) {
204
453
  }
205
454
  try {
206
455
  const repoRoot = options.repo ?? process.cwd();
207
- const repo = await scanRepo({ repoRoot, diffSpec: options.diffSpec, baseRef: options.baseRef, headRef: options.headRef, workingTree: options.workingTree, includeUntracked: options.includeUntracked });
208
- const explanation = explainFile(repo, {
456
+ const repo = await scanRepo({
457
+ repoRoot,
458
+ diffSpec: options.diffSpec,
459
+ baseRef: options.baseRef,
460
+ headRef: options.headRef,
461
+ workingTree: options.workingTree,
462
+ includeUntracked: options.includeUntracked,
463
+ useCache: !options.noCache,
464
+ internalExclude: localPlanArtifactExclusions(options)
465
+ });
466
+ const unresolvedDiff = repo.diagnostics.find((diagnostic) => diagnostic.code === "diff-unavailable");
467
+ if (unresolvedDiff && (options.diffSpec || options.baseRef || options.headRef || options.workingTree)) {
468
+ stderr(`${unresolvedDiff.message}\nExplanation needs a resolvable diff to include change evidence.\n`);
469
+ return 1;
470
+ }
471
+ const explanation = await clarifyMissingPath(explainFile(repo, {
209
472
  issueText: options.issueText,
473
+ diffText: repo.diffText,
210
474
  // Without this, a file left out by .fixmapignore would be reported as having
211
475
  // scored below the cutoff — a false answer to the exact question --explain exists
212
476
  // to answer.
213
- exclude: await resolveExclusions(repoRoot, options.exclude),
477
+ exclude: await resolveExclusions(repoRoot, [
478
+ ...options.exclude,
479
+ ...localPlanArtifactExclusions(options)
480
+ ]),
214
481
  limit: options.limit
215
- }, options.explainPath);
216
- stdout(options.format === "json"
482
+ }, options.explainPath), repo, options.explainPath);
483
+ const renderedExplanation = options.format === "json"
217
484
  ? `${JSON.stringify(explanation, null, 2)}\n`
218
- : renderExplanationMarkdown(explanation));
485
+ : renderExplanationMarkdown(explanation);
486
+ if (options.output) {
487
+ try {
488
+ await (dependencies.writeReport ?? ((path, contents) => writeFile(path, contents, "utf8")))(options.output, renderedExplanation);
489
+ }
490
+ catch (error) {
491
+ stderr(formatOutputError(options.output, error, "explanation"));
492
+ return 1;
493
+ }
494
+ }
495
+ else {
496
+ stdout(renderedExplanation);
497
+ }
219
498
  return 0;
220
499
  }
221
500
  catch (error) {
@@ -231,10 +510,13 @@ export async function runCli(args, dependencies = {}) {
231
510
  diffSpec: options.diffSpec,
232
511
  baseRef: options.baseRef,
233
512
  headRef: options.headRef,
513
+ checkoutRef: options.checkoutRef,
234
514
  workingTree: options.workingTree,
235
515
  includeUntracked: options.includeUntracked,
516
+ useCache: !options.noCache,
236
517
  limit: options.limit,
237
- exclude: options.exclude
518
+ exclude: options.exclude,
519
+ internalExclude: localPlanArtifactExclusions(options)
238
520
  });
239
521
  }
240
522
  catch (error) {
@@ -277,11 +559,11 @@ export async function runCli(args, dependencies = {}) {
277
559
  let previous;
278
560
  let previousText;
279
561
  try {
280
- previousText = readFileSync(options.comparePath, "utf8");
562
+ previousText = stripByteOrderMark(readFileSync(options.comparePath, "utf8"));
281
563
  }
282
564
  catch (error) {
283
565
  stderr(`Could not read comparison file "${options.comparePath}": ${error instanceof Error ? error.message : String(error)}\n` +
284
- "Save one first with: fixmap plan --issue \"...\" --format json --output previous.json\n");
566
+ "Save one first with: fixmap plan --issue \"...\" --format json --output plan.json\n");
285
567
  return 1;
286
568
  }
287
569
  if (!previousText.trim()) {
@@ -299,8 +581,14 @@ export async function runCli(args, dependencies = {}) {
299
581
  stderr(`"${options.comparePath}" is not valid JSON: ${error instanceof Error ? error.message : String(error)}\n`);
300
582
  return 1;
301
583
  }
302
- if (!Array.isArray(previous.contextFiles)) {
303
- stderr(`"${options.comparePath}" is valid JSON but not a FixMap report: no contextFiles array.\n`);
584
+ const loaded = validateFixMapReport(previous, `"${options.comparePath}"`);
585
+ if (!loaded.success) {
586
+ stderr(`${loaded.message}\n`);
587
+ return 1;
588
+ }
589
+ previous = loaded.report;
590
+ if (unresolvedChangeRequest) {
591
+ stderr("The current plan lost its requested diff signal, so it was not compared with the saved plan. Fix the ref and rerun.\n");
304
592
  return 1;
305
593
  }
306
594
  const comparison = compareReports(previous, report);
@@ -331,7 +619,7 @@ export async function runCli(args, dependencies = {}) {
331
619
  stderr(moved === 0
332
620
  ? "\nComparison complete. Nothing entered, left, moved, or changed confidence — that task edit did not affect the ranking. Try naming a symbol, error string, or path from the file you expect.\n"
333
621
  : "\nComparison complete. Refine the task or inspect the files that entered, moved, or changed confidence, then rerun the plan.\n");
334
- return 0;
622
+ return unresolvedChangeRequest ? 1 : 0;
335
623
  }
336
624
  const rendered = options.format === "json" ? renderJsonReport(report) : renderMarkdownReport(report);
337
625
  if (options.output) {
@@ -438,6 +726,8 @@ export function expandIssueShorthand(args) {
438
726
  if (!shorthand)
439
727
  return args;
440
728
  const [, owner, repository, number] = shorthand;
729
+ if (!/[A-Za-z]/.test(owner ?? ""))
730
+ return ["plan", "--issue", first, ...args.slice(1)];
441
731
  return ["plan", "--issue", `https://github.com/${owner}/${repository}/issues/${number}`, ...args.slice(1)];
442
732
  }
443
733
  // --exclude is deliberately absent: it is the one flag that accumulates, because naming
@@ -448,14 +738,34 @@ const SINGLE_VALUE_FLAGS = new Set([
448
738
  "--diff",
449
739
  "--base",
450
740
  "--head",
741
+ "--ref",
451
742
  "--repo",
452
743
  "--format",
453
744
  "--report",
454
745
  "--explain",
455
746
  "--compare",
456
747
  "--limit",
748
+ "--fail-on",
457
749
  "--output"
458
750
  ]);
751
+ const BOOLEAN_FLAGS = new Set(["--working-tree", "--include-untracked", "--no-cache"]);
752
+ function hasStandaloneHelpFlag(args) {
753
+ for (let index = 1; index < args.length; index += 1) {
754
+ const raw = args[index] ?? "";
755
+ if (raw === "--help" || raw === "-h")
756
+ return true;
757
+ const separator = raw.indexOf("=");
758
+ const flag = separator === -1 ? raw : raw.slice(0, separator);
759
+ if (separator === -1 && (SINGLE_VALUE_FLAGS.has(flag) || flag === "--exclude"))
760
+ index += 1;
761
+ }
762
+ return false;
763
+ }
764
+ function isKnownOptionToken(value) {
765
+ const separator = value.indexOf("=");
766
+ const flag = separator === -1 ? value : value.slice(0, separator);
767
+ return SINGLE_VALUE_FLAGS.has(flag) || BOOLEAN_FLAGS.has(flag) || flag === "--exclude" || flag === "--help" || flag === "-h";
768
+ }
459
769
  export const MAX_CONTEXT_FILE_LIMIT = 20;
460
770
  export function parseArgs(args) {
461
771
  const command = args[0] ?? "";
@@ -465,14 +775,17 @@ export function parseArgs(args) {
465
775
  let diffSpec;
466
776
  let baseRef;
467
777
  let headRef;
778
+ let checkoutRef;
468
779
  let format = "markdown";
469
780
  let output;
470
781
  let explainPath;
471
782
  let reportPath;
472
783
  let comparePath;
473
784
  let limit;
785
+ let failOn;
474
786
  let workingTree = false;
475
787
  let includeUntracked = false;
788
+ let noCache = false;
476
789
  const exclude = [];
477
790
  const unknownArgs = [];
478
791
  const invalidValues = [];
@@ -489,6 +802,7 @@ export function parseArgs(args) {
489
802
  const canConsumeFollowing = inlineValue === undefined &&
490
803
  followingValue !== undefined &&
491
804
  (!followingValue.startsWith("-") ||
805
+ (arg === "--issue" && !isKnownOptionToken(followingValue)) ||
492
806
  (arg === "--limit" && /^-\d/.test(followingValue)) ||
493
807
  ((arg === "--issue" || arg === "--issue-file") && followingValue === "-"));
494
808
  const value = inlineValue ?? (canConsumeFollowing ? followingValue : undefined);
@@ -520,41 +834,50 @@ export function parseArgs(args) {
520
834
  else if (arg === "--issue-file") {
521
835
  consumeValue();
522
836
  if (value?.trim())
523
- issueFile = value.trim();
837
+ issueFile = expandHomePath(value.trim());
524
838
  else
525
839
  invalidValues.push("--issue-file requires a UTF-8 file path or - for stdin");
526
840
  }
527
841
  else if (arg === "--diff") {
528
842
  consumeValue();
529
843
  if (value?.trim())
530
- diffSpec = value;
844
+ diffSpec = value.trim();
531
845
  else
532
846
  invalidValues.push("--diff requires a non-empty git diff spec");
533
847
  }
534
848
  else if (arg === "--base") {
535
849
  consumeValue();
536
850
  if (value?.trim())
537
- baseRef = value;
851
+ baseRef = value.trim();
538
852
  else
539
853
  invalidValues.push("--base requires a non-empty git ref");
540
854
  }
541
855
  else if (arg === "--head") {
542
856
  consumeValue();
543
857
  if (value?.trim())
544
- headRef = value;
858
+ headRef = value.trim();
545
859
  else
546
860
  invalidValues.push("--head requires a non-empty git ref");
547
861
  }
862
+ else if (arg === "--ref") {
863
+ consumeValue();
864
+ if (value?.trim() && isSafeGitRefName(value.trim())) {
865
+ checkoutRef = value.trim();
866
+ }
867
+ else {
868
+ invalidValues.push("--ref requires a safe branch or tag name");
869
+ }
870
+ }
548
871
  else if (arg === "--repo") {
549
872
  consumeValue();
550
873
  if (value?.trim())
551
- repo = value;
874
+ repo = expandHomePath(value.trim());
552
875
  else
553
876
  invalidValues.push("--repo requires a local path or public GitHub repository URL");
554
877
  }
555
878
  else if (arg === "--format") {
556
879
  consumeValue();
557
- const normalized = value?.toLowerCase();
880
+ const normalized = value?.trim().toLowerCase();
558
881
  if (normalized === "markdown" || normalized === "json") {
559
882
  format = normalized;
560
883
  }
@@ -565,7 +888,7 @@ export function parseArgs(args) {
565
888
  else if (arg === "--report") {
566
889
  consumeValue();
567
890
  if (value?.trim())
568
- reportPath = value.trim();
891
+ reportPath = expandHomePath(value.trim());
569
892
  else
570
893
  invalidValues.push("--report requires a path to a FixMap JSON report");
571
894
  }
@@ -579,7 +902,7 @@ export function parseArgs(args) {
579
902
  else if (arg === "--compare") {
580
903
  consumeValue();
581
904
  if (value?.trim())
582
- comparePath = value.trim();
905
+ comparePath = expandHomePath(value.trim());
583
906
  else
584
907
  invalidValues.push("--compare requires a path to an earlier FixMap JSON report");
585
908
  }
@@ -592,30 +915,54 @@ export function parseArgs(args) {
592
915
  }
593
916
  else if (arg === "--limit") {
594
917
  consumeValue();
595
- const parsed = Number(value);
596
- if (value?.trim() && Number.isSafeInteger(parsed) && parsed >= 1 && parsed <= MAX_CONTEXT_FILE_LIMIT) {
918
+ const normalized = value?.trim() ?? "";
919
+ const parsed = Number(normalized);
920
+ if (/^\d+$/.test(normalized) && Number.isSafeInteger(parsed) && parsed >= 1 && parsed <= MAX_CONTEXT_FILE_LIMIT) {
597
921
  limit = parsed;
598
922
  }
599
923
  else {
600
924
  invalidValues.push(`--limit received ${JSON.stringify(value ?? "(missing)")}; expected a whole number from 1 to ${MAX_CONTEXT_FILE_LIMIT}`);
601
925
  }
602
926
  }
927
+ else if (arg === "--fail-on") {
928
+ consumeValue();
929
+ const normalized = value?.trim().toLowerCase();
930
+ if (normalized === "error" || normalized === "warning")
931
+ failOn = normalized;
932
+ else
933
+ invalidValues.push(`--fail-on received ${JSON.stringify(value ?? "(missing)")}; expected "error" or "warning"`);
934
+ }
603
935
  else if (arg === "--working-tree") {
604
936
  if (flagCounts.has(arg))
605
937
  invalidValues.push(`pass ${arg} only once`);
606
938
  flagCounts.set(arg, 1);
607
- workingTree = true;
939
+ if (inlineValue !== undefined)
940
+ invalidValues.push(`${arg} does not accept a value; pass ${arg} by itself`);
941
+ else
942
+ workingTree = true;
608
943
  }
609
944
  else if (arg === "--include-untracked") {
610
945
  if (flagCounts.has(arg))
611
946
  invalidValues.push(`pass ${arg} only once`);
612
947
  flagCounts.set(arg, 1);
613
- includeUntracked = true;
948
+ if (inlineValue !== undefined)
949
+ invalidValues.push(`${arg} does not accept a value; pass ${arg} by itself`);
950
+ else
951
+ includeUntracked = true;
952
+ }
953
+ else if (arg === "--no-cache") {
954
+ if (flagCounts.has(arg))
955
+ invalidValues.push(`pass ${arg} only once`);
956
+ flagCounts.set(arg, 1);
957
+ if (inlineValue !== undefined)
958
+ invalidValues.push(`${arg} does not accept a value; pass ${arg} by itself`);
959
+ else
960
+ noCache = true;
614
961
  }
615
962
  else if (arg === "--output") {
616
963
  consumeValue();
617
964
  if (value?.trim())
618
- output = value;
965
+ output = expandHomePath(value.trim());
619
966
  else
620
967
  invalidValues.push("--output requires a non-empty file path");
621
968
  }
@@ -631,22 +978,118 @@ export function parseArgs(args) {
631
978
  diffSpec,
632
979
  baseRef,
633
980
  headRef,
981
+ checkoutRef,
634
982
  format,
635
983
  output,
636
984
  explainPath,
637
985
  reportPath,
638
986
  comparePath,
639
987
  limit,
988
+ failOn,
640
989
  exclude,
641
990
  workingTree,
642
991
  includeUntracked,
992
+ noCache,
643
993
  unknownArgs,
644
994
  invalidValues
645
995
  };
646
996
  }
997
+ function expandHomePath(value) {
998
+ if (value === "~")
999
+ return homedir();
1000
+ if (value.startsWith("~/") || value.startsWith("~\\")) {
1001
+ return join(homedir(), value.slice(2));
1002
+ }
1003
+ return value;
1004
+ }
1005
+ /**
1006
+ * Inputs and outputs generated by the current FixMap workflow are rich in the task's own
1007
+ * vocabulary. If they live inside the scanned checkout, ranking them as repository context
1008
+ * creates a self-fulfilling result (`plan.json` explaining why `plan.json` is relevant).
1009
+ */
1010
+ function localPlanArtifactExclusions(options) {
1011
+ const remoteIssue = options.issueText ? parseGitHubIssueSource(options.issueText) : undefined;
1012
+ const remoteRepository = /^https?:\/\//i.test(options.repo ?? "") || (remoteIssue && !options.repo);
1013
+ if (remoteRepository)
1014
+ return [];
1015
+ const root = resolve(options.repo ?? process.cwd());
1016
+ return [
1017
+ options.output,
1018
+ options.comparePath,
1019
+ options.reportPath,
1020
+ options.issueFile === "-" ? undefined : options.issueFile
1021
+ ]
1022
+ .filter((path) => path !== undefined)
1023
+ .map((path) => resolve(path))
1024
+ .filter((path) => {
1025
+ const distance = relative(root, path);
1026
+ return distance !== "" && distance !== ".." && !distance.startsWith(`..${sep}`) && !isAbsolute(distance);
1027
+ });
1028
+ }
1029
+ /**
1030
+ * A workflow input must remain usable after the command finishes. Reading a plan, task, or
1031
+ * source file and then writing the result back through the same path silently destroyed the
1032
+ * only copy while still exiting zero. Compare both path spelling and filesystem identity so
1033
+ * relative aliases, symlinks, and hardlinks receive the same protection.
1034
+ */
1035
+ async function describeOutputInputCollision(options) {
1036
+ if (!options.output)
1037
+ return undefined;
1038
+ const inputs = [];
1039
+ if (options.command === "verify" && options.reportPath) {
1040
+ inputs.push({ flag: "--report", path: options.reportPath });
1041
+ }
1042
+ else {
1043
+ if (options.issueFile && options.issueFile !== "-") {
1044
+ inputs.push({ flag: "--issue-file", path: options.issueFile });
1045
+ }
1046
+ if (options.comparePath) {
1047
+ inputs.push({ flag: "--compare", path: options.comparePath });
1048
+ }
1049
+ if (options.explainPath) {
1050
+ inputs.push({
1051
+ flag: "--explain",
1052
+ path: isAbsolute(options.explainPath)
1053
+ ? options.explainPath
1054
+ : resolve(options.repo ?? process.cwd(), options.explainPath)
1055
+ });
1056
+ }
1057
+ }
1058
+ for (const input of inputs) {
1059
+ if (await pathsReferToSameFile(options.output, input.path)) {
1060
+ return `Refusing to write --output "${options.output}" because it is the same file as ${input.flag} "${input.path}". ` +
1061
+ "Choose a different --output path so FixMap does not overwrite its input.";
1062
+ }
1063
+ }
1064
+ return undefined;
1065
+ }
1066
+ async function pathsReferToSameFile(leftPath, rightPath) {
1067
+ const left = resolve(leftPath);
1068
+ const right = resolve(rightPath);
1069
+ const normalize = process.platform === "win32"
1070
+ ? (path) => path.toLowerCase()
1071
+ : (path) => path;
1072
+ if (normalize(left) === normalize(right))
1073
+ return true;
1074
+ try {
1075
+ const [leftReal, rightReal] = await Promise.all([realpath(left), realpath(right)]);
1076
+ if (normalize(leftReal) === normalize(rightReal))
1077
+ return true;
1078
+ }
1079
+ catch {
1080
+ // A missing path cannot already alias an existing input. The command that consumes it
1081
+ // will produce the more useful read/write error later.
1082
+ }
1083
+ try {
1084
+ const [leftStat, rightStat] = await Promise.all([stat(left), stat(right)]);
1085
+ return leftStat.ino !== 0 && leftStat.dev === rightStat.dev && leftStat.ino === rightStat.ino;
1086
+ }
1087
+ catch {
1088
+ return false;
1089
+ }
1090
+ }
647
1091
  function loadIssueText(options, read) {
648
- const implicitFile = options.issueText.startsWith("@") ? options.issueText.slice(1) : undefined;
649
- const path = options.issueFile ?? implicitFile ?? (options.issueText === "-" ? "-" : undefined);
1092
+ const path = options.issueFile ?? (options.issueText === "-" ? "-" : undefined);
650
1093
  if (!path) {
651
1094
  return options.issueText.trim();
652
1095
  }
@@ -686,14 +1129,39 @@ function decodeIssueText(raw) {
686
1129
  }
687
1130
  return swapped.toString("utf16le").replace(/^\uFEFF/, "");
688
1131
  }
1132
+ if (raw.length >= 4 && raw.length % 2 === 0) {
1133
+ let evenNuls = 0;
1134
+ let oddNuls = 0;
1135
+ for (let index = 0; index < raw.length; index += 2) {
1136
+ if (raw[index] === 0)
1137
+ evenNuls += 1;
1138
+ if (raw[index + 1] === 0)
1139
+ oddNuls += 1;
1140
+ }
1141
+ const pairs = raw.length / 2;
1142
+ if (oddNuls / pairs >= 0.3 && evenNuls / pairs < 0.1)
1143
+ return raw.toString("utf16le");
1144
+ if (evenNuls / pairs >= 0.3 && oddNuls / pairs < 0.1)
1145
+ return Buffer.from(raw).swap16().toString("utf16le");
1146
+ }
689
1147
  return raw.toString("utf8").replace(/^\uFEFF/, "");
690
1148
  }
691
1149
  function quoteCliValue(value) {
692
- return /\s/.test(value) ? `"${value.replaceAll('"', '\\"')}"` : value;
1150
+ return formatCliValue(value, process.platform === "win32" ? "powershell" : "posix");
693
1151
  }
694
1152
  function readVersion() {
695
- const packageJson = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "..", "package.json"), "utf8"));
696
- return packageJson.version;
1153
+ const path = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
1154
+ try {
1155
+ const packageJson = JSON.parse(readFileSync(path, "utf8"));
1156
+ if (typeof packageJson.version !== "string" || !packageJson.version.trim()) {
1157
+ throw new Error("the version field is missing or invalid");
1158
+ }
1159
+ return packageJson.version;
1160
+ }
1161
+ catch (error) {
1162
+ throw new Error(`FixMap could not read its version from "${path}"; the installation looks incomplete: ` +
1163
+ `${error instanceof Error ? error.message : String(error)}`);
1164
+ }
697
1165
  }
698
1166
  /**
699
1167
  * Compares a saved plan against the diff that followed it. Both inputs are things the
@@ -733,11 +1201,11 @@ async function runVerify(options, io) {
733
1201
  }
734
1202
  let reportText;
735
1203
  try {
736
- reportText = readFileSync(options.reportPath, "utf8");
1204
+ reportText = stripByteOrderMark(readFileSync(options.reportPath, "utf8"));
737
1205
  }
738
1206
  catch (error) {
739
1207
  io.stderr(`Could not read "${options.reportPath}": ${error instanceof Error ? error.message : String(error)}\n` +
740
- "Generate one with: fixmap plan --issue \"...\" --format json --output fixmap-report.json\n");
1208
+ "Generate one with: fixmap plan --issue \"...\" --format json --output plan.json\n");
741
1209
  return 1;
742
1210
  }
743
1211
  // --compare already detected this and said so plainly; verify raised a raw
@@ -745,7 +1213,7 @@ async function runVerify(options, io) {
745
1213
  // mistake. Passing the markdown report is the obvious thing to try first.
746
1214
  if (/^\s*#\s*FixMap/i.test(reportText)) {
747
1215
  io.stderr(`"${options.reportPath}" is a Markdown report. verify --report requires the JSON plan saved with --format json.\n` +
748
- "Generate one with: fixmap plan --issue \"...\" --format json --output fixmap-report.json\n");
1216
+ "Generate one with: fixmap plan --issue \"...\" --format json --output plan.json\n");
749
1217
  return 1;
750
1218
  }
751
1219
  let report;
@@ -754,7 +1222,7 @@ async function runVerify(options, io) {
754
1222
  }
755
1223
  catch (error) {
756
1224
  io.stderr(`"${options.reportPath}" is not valid JSON: ${error instanceof Error ? error.message : String(error)}\n` +
757
- "Generate one with: fixmap plan --issue \"...\" --format json --output fixmap-report.json\n");
1225
+ "Generate one with: fixmap plan --issue \"...\" --format json --output plan.json\n");
758
1226
  return 1;
759
1227
  }
760
1228
  if (!Array.isArray(report.contextFiles)) {
@@ -766,6 +1234,12 @@ async function runVerify(options, io) {
766
1234
  io.stderr(`"${options.reportPath}" is not a FixMap JSON report: no contextFiles array.\n`);
767
1235
  return 1;
768
1236
  }
1237
+ const loaded = validateFixMapReport(report, `"${options.reportPath}"`);
1238
+ if (!loaded.success) {
1239
+ io.stderr(`${loaded.message}\n`);
1240
+ return 1;
1241
+ }
1242
+ report = loaded.report;
769
1243
  try {
770
1244
  const repo = await scanRepo({
771
1245
  repoRoot: options.repo ?? process.cwd(),
@@ -773,7 +1247,9 @@ async function runVerify(options, io) {
773
1247
  baseRef: options.baseRef,
774
1248
  headRef: options.headRef,
775
1249
  workingTree: options.workingTree,
776
- includeUntracked: options.includeUntracked
1250
+ includeUntracked: options.includeUntracked,
1251
+ useCache: !options.noCache,
1252
+ internalExclude: localPlanArtifactExclusions(options)
777
1253
  });
778
1254
  const unresolvedDiff = repo.diagnostics.find((diagnostic) => diagnostic.code === "diff-unavailable");
779
1255
  if (unresolvedDiff) {
@@ -798,7 +1274,8 @@ async function runVerify(options, io) {
798
1274
  }
799
1275
  // A generated-location edit is discarded by the next build, so it fails the command
800
1276
  // rather than being reported and ignored. Everything else is advisory.
801
- return result.findings.some((finding) => finding.severity === "error") ? 1 : 0;
1277
+ const failOn = options.failOn ?? "error";
1278
+ return result.findings.some((finding) => finding.severity === "error" || (failOn === "warning" && finding.severity === "warning")) ? 1 : 0;
802
1279
  }
803
1280
  catch (error) {
804
1281
  io.stderr(`${error instanceof Error ? error.message : String(error)}\n`);
@@ -820,7 +1297,8 @@ function describeUnsupportedTaskUrl(issueText) {
820
1297
  return undefined;
821
1298
  return "Unsupported task URL. Use a public GitHub issue or pull request URL such as " +
822
1299
  "https://github.com/owner/repository/issues/123 or /pull/123, or pass descriptive task text. " +
823
- "A ?query, #fragment, and a www. or api. host are accepted and normalized; other hosts, credentials and ports are not.";
1300
+ "The URL must use https. A ?query, #fragment, and a www. or api. host are accepted and normalized; " +
1301
+ "other hosts, credentials and ports are not.";
824
1302
  }
825
1303
  function formatOutputError(path, error, kind) {
826
1304
  const candidate = error;