@aryam/fixmap 0.8.8 → 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, validateFixMapReport } 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,20 +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/**"
25
+ fixmap plan --no-cache --issue "Fix login" --repo .
21
26
  fixmap plan --issue "Fix login" --format json --output plan.json
22
27
  fixmap plan --issue "Fix login in auth middleware" --compare plan.json
23
28
  fixmap plan --base main --head HEAD --format json
24
29
  fixmap verify --report plan.json --diff main...HEAD
25
30
  fixmap verify --report plan.json --working-tree
31
+ fixmap verify --report plan.json --working-tree --fail-on warning
26
32
  fixmap doctor --format json
27
- 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>]
28
37
 
29
38
  Commands:
30
39
  plan Generate a FixMap report for a task or diff
31
40
  verify Compare a saved report against the diff that followed it
32
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
33
45
  mcp Run FixMap as an MCP server over stdio for AI coding agents
34
46
 
35
47
  Options:
@@ -42,6 +54,7 @@ Options:
42
54
  --include-untracked With --working-tree, also include untracked files
43
55
  --no-cache Bypass the exact git-state repository scan cache
44
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
45
58
  --limit <n> Maximum context files to report (default 8, max 20)
46
59
  --exclude <glob> Path pattern to leave out of ranking (repeatable)
47
60
  --format <fmt> Output format: markdown (default) or json
@@ -49,15 +62,21 @@ Options:
49
62
  --explain <path> Explain why one file was ranked where it was, or left out
50
63
  --compare <file> Compare this plan against an earlier JSON report
51
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
52
66
  --help, -h Show this help
53
67
  --version, -v Show the FixMap version
54
68
 
55
69
  A repository may also list exclusion patterns in .fixmapignore, one per line. Supported
56
- 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.
57
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.
58
74
  `;
59
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`;
60
- 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`;
61
80
  export async function runCli(args, dependencies = {}) {
62
81
  const stdout = dependencies.stdout ?? ((text) => process.stdout.write(text));
63
82
  const stderr = dependencies.stderr ?? ((text) => process.stderr.write(text));
@@ -71,25 +90,229 @@ export async function runCli(args, dependencies = {}) {
71
90
  return 0;
72
91
  }
73
92
  if (args[0] === "version" || args[0] === "--version" || args[0] === "-v") {
74
- stdout(`${(dependencies.readVersion ?? readVersion)()}\n`);
75
- 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
+ }
76
101
  }
77
102
  if (args[0] === "mcp") {
78
103
  if (args[1] === "--help" || args[1] === "-h") {
79
104
  stdout(MCP_USAGE);
80
105
  return 0;
81
106
  }
82
- if (args.length > 1) {
83
- 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}`);
84
125
  return 1;
85
126
  }
86
127
  const runMcpServer = dependencies.runMcpServer ?? (async () => {
87
128
  const module = await import("./mcp.js");
88
- await module.runMcpServer();
129
+ await module.runMcpServer(defaultRepo);
89
130
  });
90
- 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));
91
155
  return 0;
92
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
+ }
93
316
  if (args[0] === "doctor") {
94
317
  if (args[1] === "--help" || args[1] === "-h") {
95
318
  stdout(DOCTOR_USAGE);
@@ -100,7 +323,7 @@ export async function runCli(args, dependencies = {}) {
100
323
  if (doctorArgs.length > 0) {
101
324
  const match = doctorArgs.length === 2 && doctorArgs[0] === "--format" ? doctorArgs[1] :
102
325
  doctorArgs.length === 1 ? doctorArgs[0]?.match(/^--format=(.+)$/)?.[1] : undefined;
103
- const normalized = match?.toLowerCase();
326
+ const normalized = match?.trim().toLowerCase();
104
327
  if (normalized === "markdown" || normalized === "json")
105
328
  doctorFormat = normalized;
106
329
  else {
@@ -114,7 +337,7 @@ export async function runCli(args, dependencies = {}) {
114
337
  // not read the text and carry on.
115
338
  return report.healthy ? 0 : 1;
116
339
  }
117
- 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)) {
118
341
  stdout(USAGE);
119
342
  return 0;
120
343
  }
@@ -146,6 +369,11 @@ export async function runCli(args, dependencies = {}) {
146
369
  stderr(`verify does not accept plan-only option(s): ${planOnly.join(", ")}.\n`);
147
370
  return 1;
148
371
  }
372
+ const outputCollision = await describeOutputInputCollision(options);
373
+ if (outputCollision) {
374
+ stderr(`${outputCollision}\n`);
375
+ return 1;
376
+ }
149
377
  return runVerify(options, {
150
378
  stdout,
151
379
  stderr,
@@ -156,6 +384,15 @@ export async function runCli(args, dependencies = {}) {
156
384
  stderr(withUsageHint("--report is a verify option. Did you mean --output to write this plan to a file?"));
157
385
  return 1;
158
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
+ }
159
396
  try {
160
397
  options.issueText = loadIssueText(options, dependencies.readIssueFile ?? defaultReadIssueFile);
161
398
  }
@@ -175,7 +412,7 @@ export async function runCli(args, dependencies = {}) {
175
412
  stderr("--include-untracked only applies with --working-tree.\n");
176
413
  return 1;
177
414
  }
178
- if (options.workingTree && (options.diffSpec || options.baseRef)) {
415
+ if (options.workingTree && (options.diffSpec || options.baseRef || options.headRef)) {
179
416
  stderr("Use either --working-tree or --diff/--base, not both: they name different sets of changes.\n");
180
417
  return 1;
181
418
  }
@@ -195,6 +432,12 @@ export async function runCli(args, dependencies = {}) {
195
432
  stderr("--working-tree and --include-untracked need a local checkout; remote URL checkouts are always clean.\n");
196
433
  return 1;
197
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
+ }
198
441
  const unsupportedTaskUrl = describeUnsupportedTaskUrl(options.issueText);
199
442
  if (unsupportedTaskUrl) {
200
443
  stderr(`${unsupportedTaskUrl}\n`);
@@ -210,19 +453,48 @@ export async function runCli(args, dependencies = {}) {
210
453
  }
211
454
  try {
212
455
  const repoRoot = options.repo ?? process.cwd();
213
- const repo = await scanRepo({ repoRoot, diffSpec: options.diffSpec, baseRef: options.baseRef, headRef: options.headRef, workingTree: options.workingTree, includeUntracked: options.includeUntracked, useCache: !options.noCache });
214
- 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, {
215
472
  issueText: options.issueText,
216
473
  diffText: repo.diffText,
217
474
  // Without this, a file left out by .fixmapignore would be reported as having
218
475
  // scored below the cutoff — a false answer to the exact question --explain exists
219
476
  // to answer.
220
- exclude: await resolveExclusions(repoRoot, options.exclude),
477
+ exclude: await resolveExclusions(repoRoot, [
478
+ ...options.exclude,
479
+ ...localPlanArtifactExclusions(options)
480
+ ]),
221
481
  limit: options.limit
222
- }, options.explainPath);
223
- stdout(options.format === "json"
482
+ }, options.explainPath), repo, options.explainPath);
483
+ const renderedExplanation = options.format === "json"
224
484
  ? `${JSON.stringify(explanation, null, 2)}\n`
225
- : 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
+ }
226
498
  return 0;
227
499
  }
228
500
  catch (error) {
@@ -238,11 +510,13 @@ export async function runCli(args, dependencies = {}) {
238
510
  diffSpec: options.diffSpec,
239
511
  baseRef: options.baseRef,
240
512
  headRef: options.headRef,
513
+ checkoutRef: options.checkoutRef,
241
514
  workingTree: options.workingTree,
242
515
  includeUntracked: options.includeUntracked,
243
516
  useCache: !options.noCache,
244
517
  limit: options.limit,
245
- exclude: options.exclude
518
+ exclude: options.exclude,
519
+ internalExclude: localPlanArtifactExclusions(options)
246
520
  });
247
521
  }
248
522
  catch (error) {
@@ -285,7 +559,7 @@ export async function runCli(args, dependencies = {}) {
285
559
  let previous;
286
560
  let previousText;
287
561
  try {
288
- previousText = readFileSync(options.comparePath, "utf8");
562
+ previousText = stripByteOrderMark(readFileSync(options.comparePath, "utf8"));
289
563
  }
290
564
  catch (error) {
291
565
  stderr(`Could not read comparison file "${options.comparePath}": ${error instanceof Error ? error.message : String(error)}\n` +
@@ -452,6 +726,8 @@ export function expandIssueShorthand(args) {
452
726
  if (!shorthand)
453
727
  return args;
454
728
  const [, owner, repository, number] = shorthand;
729
+ if (!/[A-Za-z]/.test(owner ?? ""))
730
+ return ["plan", "--issue", first, ...args.slice(1)];
455
731
  return ["plan", "--issue", `https://github.com/${owner}/${repository}/issues/${number}`, ...args.slice(1)];
456
732
  }
457
733
  // --exclude is deliberately absent: it is the one flag that accumulates, because naming
@@ -462,14 +738,34 @@ const SINGLE_VALUE_FLAGS = new Set([
462
738
  "--diff",
463
739
  "--base",
464
740
  "--head",
741
+ "--ref",
465
742
  "--repo",
466
743
  "--format",
467
744
  "--report",
468
745
  "--explain",
469
746
  "--compare",
470
747
  "--limit",
748
+ "--fail-on",
471
749
  "--output"
472
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
+ }
473
769
  export const MAX_CONTEXT_FILE_LIMIT = 20;
474
770
  export function parseArgs(args) {
475
771
  const command = args[0] ?? "";
@@ -479,12 +775,14 @@ export function parseArgs(args) {
479
775
  let diffSpec;
480
776
  let baseRef;
481
777
  let headRef;
778
+ let checkoutRef;
482
779
  let format = "markdown";
483
780
  let output;
484
781
  let explainPath;
485
782
  let reportPath;
486
783
  let comparePath;
487
784
  let limit;
785
+ let failOn;
488
786
  let workingTree = false;
489
787
  let includeUntracked = false;
490
788
  let noCache = false;
@@ -504,6 +802,7 @@ export function parseArgs(args) {
504
802
  const canConsumeFollowing = inlineValue === undefined &&
505
803
  followingValue !== undefined &&
506
804
  (!followingValue.startsWith("-") ||
805
+ (arg === "--issue" && !isKnownOptionToken(followingValue)) ||
507
806
  (arg === "--limit" && /^-\d/.test(followingValue)) ||
508
807
  ((arg === "--issue" || arg === "--issue-file") && followingValue === "-"));
509
808
  const value = inlineValue ?? (canConsumeFollowing ? followingValue : undefined);
@@ -535,41 +834,50 @@ export function parseArgs(args) {
535
834
  else if (arg === "--issue-file") {
536
835
  consumeValue();
537
836
  if (value?.trim())
538
- issueFile = value.trim();
837
+ issueFile = expandHomePath(value.trim());
539
838
  else
540
839
  invalidValues.push("--issue-file requires a UTF-8 file path or - for stdin");
541
840
  }
542
841
  else if (arg === "--diff") {
543
842
  consumeValue();
544
843
  if (value?.trim())
545
- diffSpec = value;
844
+ diffSpec = value.trim();
546
845
  else
547
846
  invalidValues.push("--diff requires a non-empty git diff spec");
548
847
  }
549
848
  else if (arg === "--base") {
550
849
  consumeValue();
551
850
  if (value?.trim())
552
- baseRef = value;
851
+ baseRef = value.trim();
553
852
  else
554
853
  invalidValues.push("--base requires a non-empty git ref");
555
854
  }
556
855
  else if (arg === "--head") {
557
856
  consumeValue();
558
857
  if (value?.trim())
559
- headRef = value;
858
+ headRef = value.trim();
560
859
  else
561
860
  invalidValues.push("--head requires a non-empty git ref");
562
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
+ }
563
871
  else if (arg === "--repo") {
564
872
  consumeValue();
565
873
  if (value?.trim())
566
- repo = value;
874
+ repo = expandHomePath(value.trim());
567
875
  else
568
876
  invalidValues.push("--repo requires a local path or public GitHub repository URL");
569
877
  }
570
878
  else if (arg === "--format") {
571
879
  consumeValue();
572
- const normalized = value?.toLowerCase();
880
+ const normalized = value?.trim().toLowerCase();
573
881
  if (normalized === "markdown" || normalized === "json") {
574
882
  format = normalized;
575
883
  }
@@ -580,7 +888,7 @@ export function parseArgs(args) {
580
888
  else if (arg === "--report") {
581
889
  consumeValue();
582
890
  if (value?.trim())
583
- reportPath = value.trim();
891
+ reportPath = expandHomePath(value.trim());
584
892
  else
585
893
  invalidValues.push("--report requires a path to a FixMap JSON report");
586
894
  }
@@ -594,7 +902,7 @@ export function parseArgs(args) {
594
902
  else if (arg === "--compare") {
595
903
  consumeValue();
596
904
  if (value?.trim())
597
- comparePath = value.trim();
905
+ comparePath = expandHomePath(value.trim());
598
906
  else
599
907
  invalidValues.push("--compare requires a path to an earlier FixMap JSON report");
600
908
  }
@@ -607,36 +915,54 @@ export function parseArgs(args) {
607
915
  }
608
916
  else if (arg === "--limit") {
609
917
  consumeValue();
610
- const parsed = Number(value);
611
- 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) {
612
921
  limit = parsed;
613
922
  }
614
923
  else {
615
924
  invalidValues.push(`--limit received ${JSON.stringify(value ?? "(missing)")}; expected a whole number from 1 to ${MAX_CONTEXT_FILE_LIMIT}`);
616
925
  }
617
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
+ }
618
935
  else if (arg === "--working-tree") {
619
936
  if (flagCounts.has(arg))
620
937
  invalidValues.push(`pass ${arg} only once`);
621
938
  flagCounts.set(arg, 1);
622
- workingTree = true;
939
+ if (inlineValue !== undefined)
940
+ invalidValues.push(`${arg} does not accept a value; pass ${arg} by itself`);
941
+ else
942
+ workingTree = true;
623
943
  }
624
944
  else if (arg === "--include-untracked") {
625
945
  if (flagCounts.has(arg))
626
946
  invalidValues.push(`pass ${arg} only once`);
627
947
  flagCounts.set(arg, 1);
628
- includeUntracked = true;
948
+ if (inlineValue !== undefined)
949
+ invalidValues.push(`${arg} does not accept a value; pass ${arg} by itself`);
950
+ else
951
+ includeUntracked = true;
629
952
  }
630
953
  else if (arg === "--no-cache") {
631
954
  if (flagCounts.has(arg))
632
955
  invalidValues.push(`pass ${arg} only once`);
633
956
  flagCounts.set(arg, 1);
634
- noCache = true;
957
+ if (inlineValue !== undefined)
958
+ invalidValues.push(`${arg} does not accept a value; pass ${arg} by itself`);
959
+ else
960
+ noCache = true;
635
961
  }
636
962
  else if (arg === "--output") {
637
963
  consumeValue();
638
964
  if (value?.trim())
639
- output = value;
965
+ output = expandHomePath(value.trim());
640
966
  else
641
967
  invalidValues.push("--output requires a non-empty file path");
642
968
  }
@@ -652,12 +978,14 @@ export function parseArgs(args) {
652
978
  diffSpec,
653
979
  baseRef,
654
980
  headRef,
981
+ checkoutRef,
655
982
  format,
656
983
  output,
657
984
  explainPath,
658
985
  reportPath,
659
986
  comparePath,
660
987
  limit,
988
+ failOn,
661
989
  exclude,
662
990
  workingTree,
663
991
  includeUntracked,
@@ -666,6 +994,100 @@ export function parseArgs(args) {
666
994
  invalidValues
667
995
  };
668
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
+ }
669
1091
  function loadIssueText(options, read) {
670
1092
  const path = options.issueFile ?? (options.issueText === "-" ? "-" : undefined);
671
1093
  if (!path) {
@@ -707,14 +1129,39 @@ function decodeIssueText(raw) {
707
1129
  }
708
1130
  return swapped.toString("utf16le").replace(/^\uFEFF/, "");
709
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
+ }
710
1147
  return raw.toString("utf8").replace(/^\uFEFF/, "");
711
1148
  }
712
1149
  function quoteCliValue(value) {
713
- return /\s/.test(value) ? `"${value.replaceAll('"', '\\"')}"` : value;
1150
+ return formatCliValue(value, process.platform === "win32" ? "powershell" : "posix");
714
1151
  }
715
1152
  function readVersion() {
716
- const packageJson = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "..", "package.json"), "utf8"));
717
- 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
+ }
718
1165
  }
719
1166
  /**
720
1167
  * Compares a saved plan against the diff that followed it. Both inputs are things the
@@ -754,7 +1201,7 @@ async function runVerify(options, io) {
754
1201
  }
755
1202
  let reportText;
756
1203
  try {
757
- reportText = readFileSync(options.reportPath, "utf8");
1204
+ reportText = stripByteOrderMark(readFileSync(options.reportPath, "utf8"));
758
1205
  }
759
1206
  catch (error) {
760
1207
  io.stderr(`Could not read "${options.reportPath}": ${error instanceof Error ? error.message : String(error)}\n` +
@@ -801,7 +1248,8 @@ async function runVerify(options, io) {
801
1248
  headRef: options.headRef,
802
1249
  workingTree: options.workingTree,
803
1250
  includeUntracked: options.includeUntracked,
804
- useCache: !options.noCache
1251
+ useCache: !options.noCache,
1252
+ internalExclude: localPlanArtifactExclusions(options)
805
1253
  });
806
1254
  const unresolvedDiff = repo.diagnostics.find((diagnostic) => diagnostic.code === "diff-unavailable");
807
1255
  if (unresolvedDiff) {
@@ -826,7 +1274,8 @@ async function runVerify(options, io) {
826
1274
  }
827
1275
  // A generated-location edit is discarded by the next build, so it fails the command
828
1276
  // rather than being reported and ignored. Everything else is advisory.
829
- 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;
830
1279
  }
831
1280
  catch (error) {
832
1281
  io.stderr(`${error instanceof Error ? error.message : String(error)}\n`);
@@ -848,7 +1297,8 @@ function describeUnsupportedTaskUrl(issueText) {
848
1297
  return undefined;
849
1298
  return "Unsupported task URL. Use a public GitHub issue or pull request URL such as " +
850
1299
  "https://github.com/owner/repository/issues/123 or /pull/123, or pass descriptive task text. " +
851
- "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.";
852
1302
  }
853
1303
  function formatOutputError(path, error, kind) {
854
1304
  const candidate = error;