@uniqbit/mate-core 1.0.1-canary.0 → 1.0.1-canary.1

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.
Files changed (38) hide show
  1. package/claude-capability-plugins/companion-mentions/.claude-plugin/plugin.json +1 -1
  2. package/package.json +1 -1
  3. package/src/cli/commands/artifact/finish/command.ts +18 -6
  4. package/src/cli/commands/artifact/finish/engine.ts +3 -1
  5. package/src/cli/commands/artifact/finish/git.ts +4 -2
  6. package/src/cli/commands/artifact/pending/discovery.ts +2 -2
  7. package/src/cli/commands/companion/link.ts +3 -2
  8. package/src/cli/commands/vscode/release-vsix.json +2 -2
  9. package/src/cli/main.ts +12 -2
  10. package/src/hooks/validate-artifact-path.ts +79 -17
  11. package/src/lib/delivery/record-delivery.ts +14 -0
  12. package/src/lib/delivery/staging/apply-chain.ts +60 -30
  13. package/src/lib/delivery/staging/pending.ts +13 -0
  14. package/src/lib/delivery/staging/project.ts +21 -6
  15. package/src/lib/delivery/staging/publish.ts +10 -11
  16. package/src/lib/delivery/staging/submit.ts +2 -8
  17. package/src/lib/orchestrator/companion-git-sync.ts +53 -24
  18. package/src/lib/workset/worktree.ts +1 -0
  19. package/src/opencode/companion-hooks.ts +3 -1
  20. package/src/runtime/artifact-refusal.ts +17 -7
  21. package/src/runtime/companion-guidance.ts +2 -2
  22. package/src/runtime/companion-sync.ts +21 -1
  23. package/src/runtime/shell-heredoc.ts +67 -26
  24. package/src/runtime/shell-variables.ts +257 -0
  25. package/src/templates/capabilities/openspec-cap/mate-full/schema.yaml +3 -0
  26. package/src/templates/capabilities/openspec-cap/mate-minimal/schema.yaml +4 -0
  27. package/src/templates/capabilities/react-doctor/mate-react-doctor/SKILL.md +20 -2
  28. package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +2 -2
  29. package/src/templates/mate-skills/agents/mate-publish-artifact/references/openspec.md +6 -6
  30. package/src/templates/mate-skills/agents/mate-submit-change/SKILL.md +4 -4
  31. package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +2 -2
  32. package/src/templates/mate-skills/claude/mate-publish-artifact/references/openspec.md +6 -6
  33. package/src/templates/mate-skills/claude/mate-submit-change/SKILL.md +4 -4
  34. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +30 -30
  35. package/src/tools/setup/capabilities/openspec.ts +3 -1
  36. package/src/tools/setup/capabilities/tokensave.ts +8 -1
  37. package/src/tools/setup/mate.ts +2 -1
  38. package/src/tools/setup.ts +22 -1
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mate-companion-mentions",
3
- "version": "1.0.1-canary.0",
3
+ "version": "1.0.1-canary.1",
4
4
  "description": "@mate:<path> mentions: find and attach files from the mate companion repo in the @ menu.",
5
5
  "author": {
6
6
  "name": "Kevin Tornquist"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uniqbit/mate-core",
3
- "version": "1.0.1-canary.0",
3
+ "version": "1.0.1-canary.1",
4
4
  "description": "Core framework and plugin APIs for Mate.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -91,6 +91,8 @@ const BOOLEAN_FLAGS: BooleanFlagSet = new Set([
91
91
  ...CONFIRM_FLAGS,
92
92
  ]);
93
93
 
94
+ const KNOWN_FLAGS: ReadonlySet<string> = new Set([...BOOLEAN_FLAGS, "type"]);
95
+
94
96
  async function defaultHasRemote(companionPath: string): Promise<boolean> {
95
97
  return (await stagingRemote(companionGit(companionPath, { prompt: "never" }))) !== null;
96
98
  }
@@ -153,6 +155,7 @@ function publicationResult(
153
155
  ...(publication.merges ? { merges: publication.merges } : {}),
154
156
  ...(publication.blocked ? { blocked: true } : {}),
155
157
  ...(publication.conflict ? { conflict: publication.conflict } : {}),
158
+ ...(publication.conflicts ? { conflicts: publication.conflicts } : {}),
156
159
  ...(publication.dependencies
157
160
  ? {
158
161
  dependencies: publication.dependencies.map((dependency) =>
@@ -298,7 +301,22 @@ export async function runArtifactPublishCommand(
298
301
  const emitOut = deps.stdout ?? ((line: string) => process.stdout.write(`${line}\n`));
299
302
  const emitErr = deps.stderr ?? ((line: string) => process.stderr.write(`${line}\n`));
300
303
 
304
+ /** Argument refusals go to stderr in every mode: nothing was resolved to report on. */
305
+ const refuse = (message: string): void => {
306
+ emitErr(message);
307
+ process.exitCode = 1;
308
+ };
309
+
301
310
  const flags = parseFlags(argv, BOOLEAN_FLAGS);
311
+ const unknown = Object.keys(flags).find((name) => !KNOWN_FLAGS.has(name));
312
+ if (unknown !== undefined) {
313
+ refuse(
314
+ unknown === "fetch"
315
+ ? 'mate: unknown option: --fetch. Fetch with `mate artifact link "<change>" --refresh --fetch --json`, then publish with --refresh again.'
316
+ : `mate: unknown option: --${unknown}`,
317
+ );
318
+ return;
319
+ }
302
320
  const noPush = flags["no-push"] === true;
303
321
  const json = flags.json === true;
304
322
  const type = typeof flags.type === "string" ? flags.type : DEFAULT_FINISHER_TYPE;
@@ -312,12 +330,6 @@ export async function runArtifactPublishCommand(
312
330
  ? positionals.filter((token) => !token.includes("/"))
313
331
  : positionals;
314
332
 
315
- /** Argument refusals go to stderr in every mode: nothing was resolved to report on. */
316
- const refuse = (message: string): void => {
317
- emitErr(message);
318
- process.exitCode = 1;
319
- };
320
-
321
333
  if (allMode && (specsMode || positionals.length > 0)) {
322
334
  refuse(
323
335
  "mate: --all already publishes both pending changes and drifted specs; drop the extra target.",
@@ -65,8 +65,10 @@ export interface FinishResult {
65
65
  dependencies?: FinishResult[];
66
66
  /** The conflict is recorded as `blocked` on the pending branch. */
67
67
  blocked?: boolean;
68
- /** A requirement changed since the delta was written, with the texts to resolve it from. */
68
+ /** The first of `conflicts`, kept for readers of one conflict. */
69
69
  conflict?: PublicationConflict;
70
+ /** One per stale requirement of the failing change, in scan order, at most `STALE_SCAN_LIMIT`. */
71
+ conflicts?: PublicationConflict[];
70
72
  /** True when a prior publication already committed or pushed this publication. */
71
73
  resumed: boolean;
72
74
  step: FinishStep;
@@ -32,7 +32,7 @@ export class RemoteFetchError extends Error {
32
32
  }
33
33
  }
34
34
 
35
- export type WorkingTreeChange = "new" | "modified";
35
+ export type WorkingTreeChange = "new" | "modified" | "deleted";
36
36
 
37
37
  /**
38
38
  * Git operations the finish engine needs, injectable for deterministic tests. All
@@ -139,7 +139,9 @@ function parsePorcelainPath(line: string): string {
139
139
  }
140
140
 
141
141
  function parsePorcelainKind(line: string): WorkingTreeChange {
142
- return /[?A]/.test(line.slice(0, 2)) ? "new" : "modified";
142
+ const status = line.slice(0, 2);
143
+ if (status.includes("D")) return "deleted";
144
+ return /[?A]/.test(status) ? "new" : "modified";
143
145
  }
144
146
 
145
147
  /** `ls-files --stage -z` output (`<mode> <sha> <stage>\t<path>`) as `update-index` arguments. */
@@ -27,7 +27,7 @@ export interface SpecAttribution {
27
27
  export interface UnattributedSpec {
28
28
  /** Companion-relative POSIX path of the canonical spec. */
29
29
  path: string;
30
- /** Whether the spec is new or already tracked and modified. */
30
+ /** Whether the spec is new, modified, or deleted from the working tree or index. */
31
31
  kind: WorkingTreeChange;
32
32
  /** Every archive naming this spec, oldest anchor first; empty when none does. */
33
33
  touchedByArchives: SpecAttribution[];
@@ -36,7 +36,7 @@ export interface UnattributedSpec {
36
36
  export interface UncommittedSpecChange {
37
37
  /** Companion-relative POSIX path of the canonical spec. */
38
38
  path: string;
39
- /** Whether the spec is new or already tracked and modified. */
39
+ /** Whether the spec is new, modified, or deleted from the working tree or index. */
40
40
  kind: WorkingTreeChange;
41
41
  }
42
42
 
@@ -33,6 +33,7 @@ import type { CompanionSource, LinkedRepository } from "../../../lib/orchestrato
33
33
  import { invalidateInstallState } from "../../../lib/install";
34
34
  import { createStartupProgress } from "../../../lib/components/startup-progress";
35
35
  import { companionGit, describeGitFailure, type GitResult } from "../../../runtime/companion-git";
36
+ import { expandHome } from "../../../opencode/companion-policy";
36
37
 
37
38
  interface CompanionLinkCommandDeps {
38
39
  selectCompanionLinkInputs?: (
@@ -144,7 +145,7 @@ function chosenCompanionPaths(
144
145
  extractName: (url: string) => string | null,
145
146
  ): string[] {
146
147
  if (inputs.source === "git") {
147
- if (inputs.clonePath) return [path.resolve(inputs.clonePath)];
148
+ if (inputs.clonePath) return [path.resolve(expandHome(inputs.clonePath))];
148
149
  const repoName = extractName(inputs.gitUrl ?? "");
149
150
  return repoName ? [path.join(companionsDir, repoName)] : [];
150
151
  }
@@ -152,7 +153,7 @@ function chosenCompanionPaths(
152
153
  return (inputs.companionPaths ?? []).map((companionPath) => path.resolve(companionPath));
153
154
  }
154
155
  const localPath = inputs.localPath?.trim();
155
- return localPath ? [path.resolve(localPath)] : [];
156
+ return localPath ? [path.resolve(expandHome(localPath))] : [];
156
157
  }
157
158
 
158
159
  export const companionLinkCommandDeps = {
@@ -1,4 +1,4 @@
1
1
  {
2
- "version": "1.0.1-canary.0",
3
- "sha512": "sha512-5MM2kuh/ihpcEgM2DQhi0SeXbOahrasT0uaBgjUTdO7A5W1gComjzEcRbgqp2hikQH5K9NsrL9OiFun1Vwgx5A=="
2
+ "version": "1.0.1-canary.1",
3
+ "sha512": "sha512-POY5kGVRAUOfB07GTSiaK3Z2rvGEn4R8eM3iV6epjxP6HaTC1+NEgsZP+II287gVtt7km4q3Vz7R/Hx09OvXJQ=="
4
4
  }
package/src/cli/main.ts CHANGED
@@ -19,7 +19,7 @@ import { runPluginCommand } from "./commands/plugin/plugin";
19
19
  import { runReportCommand } from "./commands/report";
20
20
  import { runSessionContextCommand } from "./commands/session/context";
21
21
  import { runSessionCommand } from "./commands/session/prepare";
22
- import { runStudioCommand } from "./commands/studio";
22
+ import { parseStudioServeArgs, runStudioCommand } from "./commands/studio";
23
23
  import { runTriageCommand } from "./commands/triage";
24
24
  import { runUpdateCommand } from "./commands/update";
25
25
  import { runUnwrapCommand } from "./commands/unwrap";
@@ -113,6 +113,7 @@ const MAIN_ANSWERS_HELP = new Set([
113
113
 
114
114
  /** True when `args` ask for help before a `--`, which passes what follows on untouched. */
115
115
  function asksForHelp(command: string, args: readonly string[]): boolean {
116
+ if (command === "cap") return args[0] === "--help" || args[0] === "-h";
116
117
  if (!MAIN_ANSWERS_HELP.has(command) || (command === "plugin" && args[0] === "install")) {
117
118
  return false;
118
119
  }
@@ -167,7 +168,16 @@ export async function main(argv = process.argv, deps: MainDeps = mainDeps): Prom
167
168
  // A package registers once per process, so a load here would pin the
168
169
  // pre-install version for the install's own sync; both installs load after their plugin step.
169
170
  if (!(command === "install" || (command === "plugin" && subcommand === "install"))) {
170
- await deps.hydrateDynamicPlugins({ includeLocal: !ignoresLocalPlugins });
171
+ const served =
172
+ command === "studio" && subcommand === "serve"
173
+ ? parseStudioServeArgs(rest, process.env)
174
+ : undefined;
175
+ const companionPath =
176
+ served && "launchCompanion" in served ? served.launchCompanion : undefined;
177
+ await deps.hydrateDynamicPlugins({
178
+ includeLocal: !ignoresLocalPlugins,
179
+ ...(companionPath ? { companionPath } : {}),
180
+ });
171
181
  }
172
182
 
173
183
  if (!command || command === "help" || command === "--help" || command === "-h" || helpRequest) {
@@ -22,7 +22,8 @@ import type { FrictionCheck } from "../runtime/friction-fingerprint";
22
22
  import { guardLaunchEnvironment } from "../runtime/launch-env-guard";
23
23
  import { companionLinkPath } from "../runtime/repo-local";
24
24
  import { checkSecretAccess, type SecretToolCall } from "../runtime/secret-guard";
25
- import { stripHeredocBodies } from "../runtime/shell-heredoc";
25
+ import { commandTextMask, stripHeredocBodies } from "../runtime/shell-heredoc";
26
+ import { wordExpander } from "../runtime/shell-variables";
26
27
  import { hookFolder, type HookEnv } from "./hook-io";
27
28
 
28
29
  export interface HookOutcome {
@@ -53,8 +54,11 @@ const ARTIFACT_PATH_MARKERS = [
53
54
  ];
54
55
 
55
56
  /** `[ \t]`, not `\s`: a redirect or `tee` names its target on its own line. */
56
- const MD_REDIRECT_PATTERN = />{1,2}[ \t]*([^\s;|&<>]+\.md)\b/g;
57
- const MD_TEE_PATTERN = /\btee[ \t]+(?:-a[ \t]+)?([^\s;|&<>]+\.md)\b/g;
57
+ const MD_WORD = String.raw`([^\s;|&<>]+\.md)(?=[\s;|&<>'"\`)\\]|$)`;
58
+ const MD_REDIRECT_PATTERN = new RegExp(String.raw`>{1,2}[ \t]*` + MD_WORD, "g");
59
+ const MD_TEE_PATTERN = new RegExp(String.raw`\btee[ \t]+(?:-a[ \t]+)?` + MD_WORD, "g");
60
+ /** Any shell's or `su`'s `-c` string, or an `eval` string. */
61
+ const NESTED_SHELL_PATTERN = /(?<![^\s;&|(`])(?:-[A-Za-z]*c(?:[ \t]+--)?|eval)[ \t]+\$?(['"])/g;
58
62
 
59
63
  export function artifactLikePath(filePath: string): boolean {
60
64
  if (!filePath) return false;
@@ -185,21 +189,32 @@ function isProductDocumentationPath(target: string, ctx: GuardContext): boolean
185
189
  return false;
186
190
  }
187
191
 
188
- function blockWrite(target: string, resolved: string, ctx: GuardContext): HookOutcome {
192
+ interface CommandTarget {
193
+ path: string;
194
+ unresolved?: string;
195
+ }
196
+
197
+ function blockWrite(
198
+ { path: target, unresolved }: CommandTarget,
199
+ resolved: string,
200
+ ctx: GuardContext,
201
+ ): HookOutcome {
189
202
  const refusal = artifactRefusal({
190
203
  target,
191
204
  resolved,
192
205
  companion: ctx.companion,
193
206
  repoRoot: ctx.repoRoot,
207
+ unresolved,
194
208
  });
195
209
  return { exitCode: 2, stderr: `${refusal}\n`, check: "artifact" };
196
210
  }
197
211
 
198
212
  function checkFilePath(
199
- filePath: string,
213
+ target: CommandTarget,
200
214
  ctx: GuardContext,
201
215
  allowExisting = false,
202
216
  ): HookOutcome | null {
217
+ const filePath = target.path;
203
218
  if (!filePath) return null;
204
219
 
205
220
  const normalized = resolveArtifactTarget(filePath, ctx.repoRoot);
@@ -220,7 +235,7 @@ function checkFilePath(
220
235
  return null;
221
236
  }
222
237
 
223
- return blockWrite(filePath, normalized, ctx);
238
+ return blockWrite(target, normalized, ctx);
224
239
  }
225
240
 
226
241
  /**
@@ -235,23 +250,66 @@ async function checkForkedCompanion(
235
250
  ctx: GuardContext,
236
251
  ): Promise<HookOutcome | null> {
237
252
  if (!filePath || !artifactLikePath(filePath)) return null;
238
- if (!isCompanionPath(resolveArtifactTarget(filePath, ctx.repoRoot), ctx)) return null;
253
+ const target = resolveArtifactTarget(filePath, ctx.repoRoot);
254
+ if (!isCompanionPath(target, ctx)) return null;
239
255
 
240
- const refusal = await companionForkRefusal(ctx.env, ctx.companion);
256
+ const refusal = await companionForkRefusal(ctx.env, ctx.companion, { target });
241
257
  return refusal ? { exitCode: 2, stderr: `${refusal}\n`, check: "fork" } : null;
242
258
  }
243
259
 
244
- /** Heredoc bodies are what a command writes, not what it runs: they are not scanned. */
245
- export function commandMatches(command: string): string[] {
246
- const targets: string[] = [];
260
+ type Expand = ReturnType<typeof wordExpander>;
261
+
262
+ function nestedScript(text: string, start: number): { script: string; doubleQuoted: boolean } {
263
+ const quote = text[start];
264
+ if (quote === "'" && text[start - 1] === "$") {
265
+ let end = start + 1;
266
+ while (end < text.length && text[end] !== "'") end += text[end] === "\\" ? 2 : 1;
267
+ return { script: text.slice(start + 1, end).replace(/\\(.)/g, "$1"), doubleQuoted: false };
268
+ }
269
+ if (quote === "'") {
270
+ const end = text.indexOf("'", start + 1);
271
+ return { script: text.slice(start + 1, end === -1 ? undefined : end), doubleQuoted: false };
272
+ }
273
+ let end = start + 1;
274
+ while (end < text.length && text[end] !== '"') end += text[end] === "\\" ? 2 : 1;
275
+ const script = text.slice(start + 1, end).replace(/\\([$`"\\\n])/g, "$1");
276
+ return { script, doubleQuoted: true };
277
+ }
278
+
279
+ function commandTargets(
280
+ command: string,
281
+ expandInCallingShell?: (raw: string) => ReturnType<Expand>,
282
+ ): CommandTarget[] {
283
+ if (!command.includes(".md")) return [];
284
+ const targets: CommandTarget[] = [];
247
285
  const commandText = stripHeredocBodies(command);
286
+ const isCommand = commandTextMask(commandText);
287
+ let own: Expand | undefined;
288
+ const expand = (raw: string, offset: number) =>
289
+ expandInCallingShell
290
+ ? expandInCallingShell(raw)
291
+ : (own ??= wordExpander(commandText))(raw, offset);
248
292
  for (const pattern of [MD_REDIRECT_PATTERN, MD_TEE_PATTERN]) {
249
293
  const matcher = new RegExp(pattern.source, pattern.flags);
250
294
  for (const match of commandText.matchAll(matcher)) {
251
- const target = match[1].trim().replace(/^["']+|["']+$/g, "");
252
- if (target) targets.push(target);
295
+ if (!isCommand[match.index]) continue;
296
+ const raw = match[1].trim();
297
+ const expanded = expand(raw, match.index);
298
+ const target =
299
+ expanded.unresolved === undefined
300
+ ? { path: expanded.text }
301
+ : { path: raw.replace(/^["']+|["']+$/g, ""), unresolved: expanded.unresolved };
302
+ if (target.path) targets.push(target);
253
303
  }
254
304
  }
305
+ for (const match of commandText.matchAll(new RegExp(NESTED_SHELL_PATTERN))) {
306
+ if (!isCommand[match.index]) continue;
307
+ const quoteAt = match.index + match[0].length - 1;
308
+ const { script, doubleQuoted } = nestedScript(commandText, quoteAt);
309
+ targets.push(
310
+ ...commandTargets(script, doubleQuoted ? (raw) => expand(raw, quoteAt) : undefined),
311
+ );
312
+ }
255
313
  return targets;
256
314
  }
257
315
 
@@ -361,7 +419,7 @@ function recordHookRefusal(
361
419
  const { toolName, toolInput } = call;
362
420
  const command = toolName === "Bash" ? stringOrEmpty(toolInput.command) : "";
363
421
  const paths = command
364
- ? commandMatches(command)
422
+ ? commandTargets(command).map((target) => target.path)
365
423
  : [toolInput.file_path, toolInput.notebook_path, toolInput.path].map(stringOrEmpty);
366
424
  return recordRefusal({
367
425
  check,
@@ -414,7 +472,11 @@ async function decide({ toolName, toolInput }: ToolCall, ctx: GuardContext): Pro
414
472
  if (toolName === "Write" || toolName === "Edit" || toolName === "MultiEdit") {
415
473
  const filePath = String(toolInput.file_path ?? "");
416
474
  /** The path refusal wins when both apply: its message is not replaced. */
417
- const outcome = checkFilePath(filePath, ctx, toolName === "Edit" || toolName === "MultiEdit");
475
+ const outcome = checkFilePath(
476
+ { path: filePath },
477
+ ctx,
478
+ toolName === "Edit" || toolName === "MultiEdit",
479
+ );
418
480
  return outcome ?? (await checkForkedCompanion(filePath, ctx)) ?? allow;
419
481
  }
420
482
 
@@ -423,12 +485,12 @@ async function decide({ toolName, toolInput }: ToolCall, ctx: GuardContext): Pro
423
485
  const attribution = checkCommitAttribution(command);
424
486
  if (attribution) return { exitCode: 2, stderr: `${attribution}\n`, check: "attribution" };
425
487
 
426
- const targets = commandMatches(command);
488
+ const targets = commandTargets(command);
427
489
  for (const target of targets) {
428
490
  const outcome = checkFilePath(target, ctx);
429
491
  if (outcome) return outcome;
430
492
  }
431
- for (const target of targets) {
493
+ for (const { path: target } of targets) {
432
494
  // oxlint-disable-next-line no-await-in-loop -- the first refusal wins
433
495
  const outcome = await checkForkedCompanion(target, ctx);
434
496
  if (outcome) return outcome;
@@ -324,6 +324,20 @@ export async function recordDelivery(
324
324
  };
325
325
  }
326
326
  }
327
+ const confirmOnly =
328
+ edit.confirm !== undefined &&
329
+ edit.delivery === undefined &&
330
+ edit.pr === undefined &&
331
+ edit.ticket === undefined;
332
+ if (!repository && confirmOnly) {
333
+ const recorded = new Set<string>();
334
+ for (const { dir, change } of located) {
335
+ for (const delivery of (await readOrUnlinkedRecord(dir, change)).deliveries) {
336
+ if (delivery.branch !== undefined) recorded.add(delivery.repository);
337
+ }
338
+ }
339
+ if (recorded.size === 1) repository = [...recorded][0]!;
340
+ }
327
341
  if (edits && !repository) return { refusal: { reason: "no-repository" } };
328
342
  const refuseProtected = async (
329
343
  repo: string,
@@ -1,7 +1,7 @@
1
1
  import { nulPaths, type CompanionGit } from "../../../runtime/companion-git";
2
2
  import { inboxText } from "../../../runtime/pending-records";
3
3
  import type { ArtifactType, ValidationFailure } from "./artifact-type";
4
- import { sourcePathOf } from "./pending";
4
+ import { resubmitAccepts, sourcePathOf, staleParts, STALE_SCAN_LIMIT } from "./pending";
5
5
  import type { DeltaFailure } from "./replay";
6
6
 
7
7
  /** A change to apply, with the commit its delta was written against (null: unknown). */
@@ -10,9 +10,12 @@ export interface ChainMember {
10
10
  base: string | null;
11
11
  }
12
12
 
13
- /** Why a chain cannot be applied, with the change that failed when known. */
13
+ /**
14
+ * Why a chain cannot be applied, with the change that failed when known. A `stale` failure holds
15
+ * every stale part of that change, up to {@link STALE_SCAN_LIMIT}.
16
+ */
14
17
  export type ChainFailure =
15
- | { kind: "stale"; change: string; failure: DeltaFailure }
18
+ | { kind: "stale"; change: string; parts: [DeltaFailure, ...DeltaFailure[]] }
16
19
  | { kind: "apply"; change: string; failure?: DeltaFailure; detail: string }
17
20
  | { kind: "invalid"; change: string | null; failure: ValidationFailure };
18
21
 
@@ -70,12 +73,11 @@ export async function applyChain(options: ApplyChainOptions): Promise<AppliedCha
70
73
  const records: string[] = [];
71
74
  for (const member of members) {
72
75
  // A part someone changed since goes to a human: applying would overwrite that change.
73
- const stale =
74
- member.base && type.stale
75
- ? // oxlint-disable-next-line no-await-in-loop -- each change applies on the one before
76
- await type.stale(work, ref, sourcePathOf(type, member.name), member.base, start)
77
- : null;
78
- if (stale) return { kind: "stale", change: member.name, failure: stale };
76
+ const [first, ...rest] = member.base
77
+ ? // oxlint-disable-next-line no-await-in-loop -- each change applies on the one before
78
+ await staleParts(type, work, ref, sourcePathOf(type, member.name), member.base, start)
79
+ : [];
80
+ if (first) return { kind: "stale", change: member.name, parts: [first, ...rest] };
79
81
  // oxlint-disable-next-line no-await-in-loop -- same change
80
82
  const applied = await type.apply(dir, member.name);
81
83
  if (!applied.ok) {
@@ -106,12 +108,14 @@ export function isChainFailure(result: AppliedChain | ChainFailure): result is C
106
108
  return "kind" in result;
107
109
  }
108
110
 
109
- /** Paths a failure concerns: the spec a delta names, or the invalid file. */
110
111
  export function failurePaths(
111
112
  failure: ChainFailure,
112
113
  pathOf: (capability: string) => string,
113
114
  ): string[] {
114
115
  if (failure.kind === "invalid") return [failure.failure.path];
116
+ if (failure.kind === "stale") {
117
+ return [...new Set(failure.parts.map((part) => pathOf(part.capability)))];
118
+ }
115
119
  return failure.failure ? [pathOf(failure.failure.capability)] : [];
116
120
  }
117
121
 
@@ -125,7 +129,7 @@ export function describeFailure(failure: ChainFailure, defaultBranch: string): s
125
129
  }
126
130
  const change = inboxText(failure.change);
127
131
  if (failure.kind === "stale") {
128
- return `${change}: "${inboxText(failure.failure.requirement)}" in ${inboxText(failure.failure.capability)} changed on ${defaultBranch} since the delta was written`;
132
+ return `${change}: ${partList(failure.parts)} changed on ${defaultBranch} since the delta was written`;
129
133
  }
130
134
  if (!failure.failure) {
131
135
  return `${change}: it no longer applies to ${defaultBranch} (${inboxText(failure.detail)})`;
@@ -144,33 +148,59 @@ function submitCommand(names: readonly string[]): string {
144
148
  return `\`mate artifact submit${names.map((name) => ` ${shellQuote(name)}`).join("")}\``;
145
149
  }
146
150
 
151
+ function partList(parts: readonly DeltaFailure[]): string {
152
+ return parts
153
+ .map((part) => `"${inboxText(part.requirement)}" in ${inboxText(part.capability)}`)
154
+ .join(", ");
155
+ }
156
+
157
+ const printable = (name: string): boolean => inboxText(name) === name;
158
+
159
+ function resolveCommand(change: string, overwritten: readonly DeltaFailure[]): string | null {
160
+ const resolvable = (part: DeltaFailure): boolean =>
161
+ printable(part.capability) &&
162
+ printable(part.requirement) &&
163
+ part.versions !== undefined &&
164
+ part.versions.ours !== null &&
165
+ part.versions.theirs !== null;
166
+ if (overwritten.length === 0 || !printable(change) || !overwritten.every(resolvable)) {
167
+ return null;
168
+ }
169
+ const triples = overwritten.map((part, index) => {
170
+ const file = overwritten.length > 1 ? `<file${index + 1}>` : "<file>";
171
+ return ` --capability ${shellQuote(part.capability)} --requirement ${shellQuote(part.requirement)} --file ${file}`;
172
+ });
173
+ return `\`mate artifact resolve ${shellQuote(change)}${triples.join("")}\``;
174
+ }
175
+
147
176
  /**
148
177
  * How to get past a failure. With `resubmit`, the changes a submit named, the remedy ends with
149
178
  * submitting them again instead of publishing: submit's pre-flight found the failure.
150
179
  */
151
180
  export function failureRemedy(failure: ChainFailure, resubmit?: readonly string[]): string {
152
- const versions = failure.kind === "stale" ? failure.failure.versions : undefined;
153
- // A name that does not print as it is cannot be passed on a command line.
154
- const printable =
155
- failure.kind === "stale" &&
156
- [failure.change, failure.failure.capability, failure.failure.requirement].every(
157
- (name) => inboxText(name) === name,
158
- );
159
- if (
160
- failure.kind === "stale" &&
161
- printable &&
162
- versions &&
163
- versions.ours !== null &&
164
- versions.theirs !== null
165
- ) {
181
+ const stale = failure.kind === "stale" ? failure : null;
182
+ // A part removed on the default branch only a delta fix gets past: OpenSpec cannot apply to it.
183
+ const removed = stale?.parts.some((part) => part.versions?.theirs === null) ?? false;
184
+ const accepts = stale !== null && !removed && resubmitAccepts(stale.parts);
185
+ const overwritten = stale?.parts.filter((part) => part.overwrites !== false) ?? [];
186
+ const resolve = stale && !removed ? resolveCommand(stale.change, overwritten) : null;
187
+ if (stale && resolve) {
166
188
  const next = resubmit ? `run ${submitCommand(resubmit)} again` : "publish again";
167
- return `Resolve it from any machine: write the requirement's body as it should read (without its \`### Requirement:\` heading) to a file, run \`mate artifact resolve ${shellQuote(failure.change)} --capability ${shellQuote(failure.failure.capability)} --requirement ${shellQuote(failure.failure.requirement)} --file <file>\` (one triple per requirement it reports unresolved), then ${next}.`;
189
+ const more =
190
+ stale.parts.length >= STALE_SCAN_LIMIT
191
+ ? " (add a triple per requirement it reports unresolved)"
192
+ : "";
193
+ const rest = stale.parts.filter((part) => !overwritten.includes(part));
194
+ const accepted =
195
+ rest.length > 0 ? ` That also accepts what the delta does to ${partList(rest)}.` : "";
196
+ return `Resolve it from any machine: write each requirement's body as it should read (without its \`### Requirement:\` heading) to a file, run ${resolve}${more}, then ${next}.${accepted}`;
168
197
  }
169
198
  const change = failure.change === null ? "the change that changes it" : inboxText(failure.change);
170
- const keep =
171
- failure.kind === "stale" && failure.failure.overwrites === false && versions?.ours === null
172
- ? " To keep it as it is, submit it again unchanged: that accepts the conflict."
173
- : "";
199
+ const keep = !accepts
200
+ ? ""
201
+ : (stale?.parts.length ?? 0) > 1
202
+ ? " To keep what the delta does to them, submit it again unchanged: that accepts the conflict."
203
+ : " To keep it as it is, submit it again unchanged: that accepts the conflict.";
174
204
  // Submitting the fixed change runs the pre-flight again; only other named changes need a rerun.
175
205
  const others = resubmit?.filter((name) => name !== failure.change) ?? [];
176
206
  const next = !resubmit
@@ -447,6 +447,19 @@ export async function staleParts(
447
447
  return found;
448
448
  }
449
449
 
450
+ /**
451
+ * True when submitting the change again unchanged accepts a block over `parts`, its
452
+ * {@link staleParts}: each replaces no one's text. False when nothing is stale (the block has
453
+ * another cause, which a new base would not lift) or the scan hit {@link STALE_SCAN_LIMIT}.
454
+ */
455
+ export function resubmitAccepts(parts: readonly Pick<DeltaFailure, "overwrites">[]): boolean {
456
+ return (
457
+ parts.length > 0 &&
458
+ parts.length < STALE_SCAN_LIMIT &&
459
+ parts.every((part) => part.overwrites === false)
460
+ );
461
+ }
462
+
450
463
  /**
451
464
  * `changes` ordered so each comes after the ones it declares in `dependsOn` among them, else in
452
465
  * their given order. A cycle keeps the given order for its members.
@@ -24,7 +24,7 @@ import {
24
24
  type AppliedChain,
25
25
  type ChainFailure,
26
26
  } from "./apply-chain";
27
- import { sourceDir, type ArtifactType } from "./artifact-type";
27
+ import { recordDir, sourceDir, type ArtifactType } from "./artifact-type";
28
28
  import {
29
29
  deltaBase,
30
30
  orderByDependencies,
@@ -317,6 +317,12 @@ export async function projectChange(
317
317
  }
318
318
  }
319
319
 
320
+ async function archivedHere(companionPath: string, type: ArtifactType): Promise<Set<string>> {
321
+ const dir = recordDir(companionPath, type);
322
+ const ids = dir ? await fs.readdir(dir).catch(() => [] as string[]) : [];
323
+ return new Set(ids.filter(type.isRecordId).map(type.recordName));
324
+ }
325
+
320
326
  async function project(
321
327
  companionPath: string,
322
328
  name: string,
@@ -341,11 +347,20 @@ async function project(
341
347
  return writeProjection(dir, derived, deps.outRoot ?? os.tmpdir());
342
348
  });
343
349
  if (run.status === "missing") {
344
- return failed(
345
- name,
346
- "error",
347
- `mate: ${name} depends on ${run.missing.map(inboxText).join(", ")}, which is neither here, submitted nor published.`,
348
- );
350
+ const archived = await archivedHere(companionPath, type);
351
+ const absent = run.missing.filter((dependency) => !archived.has(dependency));
352
+ const reasons: string[] = [];
353
+ if (absent.length > 0) {
354
+ reasons.push(
355
+ `${name} depends on ${absent.map(inboxText).join(", ")}, which is neither here, submitted nor published.`,
356
+ );
357
+ }
358
+ for (const dependency of run.missing.filter((missing) => archived.has(missing))) {
359
+ reasons.push(
360
+ `${name} depends on ${inboxText(dependency)}, which is archived in this checkout but not published; run \`${FRAMEWORK_NAME} artifact publish "${inboxText(dependency)}"\` to make it count.`,
361
+ );
362
+ }
363
+ return failed(name, "error", `mate: ${reasons.join(" ")}`);
349
364
  }
350
365
  if (run.status === "empty") {
351
366
  return {
@@ -126,7 +126,10 @@ export interface PublicationResult {
126
126
  dependencies?: PublicationResult[];
127
127
  conflictedPaths: string[];
128
128
  warnings: string[];
129
+ /** The first of {@link conflicts}, kept for readers of one conflict. */
129
130
  conflict?: PublicationConflict;
131
+ /** One per stale requirement of the failing change, in scan order, at most `STALE_SCAN_LIMIT`. */
132
+ conflicts?: PublicationConflict[];
130
133
  /** The conflict is recorded as `blocked` in the change's Delivery Record on the pending branch. */
131
134
  blocked?: boolean;
132
135
  secretFindings?: SecretFinding[];
@@ -828,22 +831,18 @@ function chainConflict(
828
831
  tip: string,
829
832
  ): Outcome {
830
833
  const reason = describeFailure(failure, run.remote.defaultBranch);
831
- const versions = failure.kind === "stale" ? failure.failure.versions : undefined;
834
+ const conflicts: PublicationConflict[] =
835
+ failure.kind === "stale"
836
+ ? failure.parts.flatMap(({ capability, requirement, versions }) =>
837
+ versions ? [{ change: failure.change, capability, requirement, ...versions }] : [],
838
+ )
839
+ : [];
832
840
  return {
833
841
  ...base,
834
842
  status: "conflict",
835
843
  conflictedPaths: failurePaths(failure, capabilitySpecPath),
836
844
  blocker: { change: failure.change, reason, tip },
837
- ...(failure.kind === "stale" && versions
838
- ? {
839
- conflict: {
840
- change: failure.change,
841
- capability: failure.failure.capability,
842
- requirement: failure.failure.requirement,
843
- ...versions,
844
- },
845
- }
846
- : {}),
845
+ ...(conflicts[0] ? { conflict: conflicts[0], conflicts } : {}),
847
846
  message: `mate: ${base.group} cannot be published: ${reason}. Nothing was published and the submitted changes are unchanged. ${failureRemedy(failure)}`,
848
847
  };
849
848
  }