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

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 (45) 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-refresh-report.ts +19 -0
  8. package/src/cli/commands/companion/link.ts +3 -2
  9. package/src/cli/commands/companion/sync.ts +25 -1
  10. package/src/cli/commands/companion/update.ts +1 -17
  11. package/src/cli/commands/plugin/plugin.ts +6 -1
  12. package/src/cli/commands/vscode/release-vsix.json +2 -2
  13. package/src/cli/main.ts +12 -2
  14. package/src/hooks/validate-artifact-path.ts +140 -22
  15. package/src/lib/delivery/record-delivery.ts +14 -0
  16. package/src/lib/delivery/staging/apply-chain.ts +61 -31
  17. package/src/lib/delivery/staging/pending.ts +13 -0
  18. package/src/lib/delivery/staging/project.ts +22 -6
  19. package/src/lib/delivery/staging/publish.ts +10 -11
  20. package/src/lib/delivery/staging/submit.ts +2 -8
  21. package/src/lib/orchestrator/companion-git-sync.ts +53 -24
  22. package/src/lib/orchestrator/projection-claude-skills.ts +13 -2
  23. package/src/lib/orchestrator/refresh-working-claude-links.ts +48 -30
  24. package/src/lib/workset/worktree.ts +1 -0
  25. package/src/opencode/companion-hooks.ts +3 -1
  26. package/src/runtime/artifact-refusal.ts +17 -7
  27. package/src/runtime/companion-guidance.ts +2 -2
  28. package/src/runtime/companion-sync.ts +24 -3
  29. package/src/runtime/shell-heredoc.ts +70 -28
  30. package/src/runtime/shell-variables.ts +257 -0
  31. package/src/templates/capabilities/openspec-cap/mate-full/schema.yaml +5 -0
  32. package/src/templates/capabilities/openspec-cap/mate-minimal/schema.yaml +7 -0
  33. package/src/templates/capabilities/react-doctor/mate-react-doctor/SKILL.md +20 -2
  34. package/src/templates/mate-skills/agents/mate-publish-artifact/SKILL.md +2 -2
  35. package/src/templates/mate-skills/agents/mate-publish-artifact/references/openspec.md +6 -6
  36. package/src/templates/mate-skills/agents/mate-submit-change/SKILL.md +4 -4
  37. package/src/templates/mate-skills/claude/mate-publish-artifact/SKILL.md +2 -2
  38. package/src/templates/mate-skills/claude/mate-publish-artifact/references/openspec.md +6 -6
  39. package/src/templates/mate-skills/claude/mate-submit-change/SKILL.md +4 -4
  40. package/src/tools/setup/__snapshots__/runtime-surface-golden.test.ts.snap +30 -30
  41. package/src/tools/setup/capabilities/openspec.ts +3 -1
  42. package/src/tools/setup/capabilities/tokensave.ts +8 -1
  43. package/src/tools/setup/dynamic-plugins/verify.ts +1 -2
  44. package/src/tools/setup/mate.ts +2 -1
  45. package/src/tools/setup.ts +22 -1
@@ -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)})`;
@@ -135,7 +139,7 @@ export function describeFailure(failure: ChainFailure, defaultBranch: string): s
135
139
  }
136
140
 
137
141
  /** `value` as one POSIX shell word: names come from teammates' specs. */
138
- function shellQuote(value: string): string {
142
+ export function shellQuote(value: string): string {
139
143
  return `'${value.replaceAll("'", `'\\''`)}'`;
140
144
  }
141
145
 
@@ -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.
@@ -21,10 +21,11 @@ import {
21
21
  describeFailure,
22
22
  failureRemedy,
23
23
  isChainFailure,
24
+ shellQuote,
24
25
  type AppliedChain,
25
26
  type ChainFailure,
26
27
  } from "./apply-chain";
27
- import { sourceDir, type ArtifactType } from "./artifact-type";
28
+ import { recordDir, sourceDir, type ArtifactType } from "./artifact-type";
28
29
  import {
29
30
  deltaBase,
30
31
  orderByDependencies,
@@ -317,6 +318,12 @@ export async function projectChange(
317
318
  }
318
319
  }
319
320
 
321
+ async function archivedHere(companionPath: string, type: ArtifactType): Promise<Set<string>> {
322
+ const dir = recordDir(companionPath, type);
323
+ const ids = dir ? await fs.readdir(dir).catch(() => [] as string[]) : [];
324
+ return new Set(ids.filter(type.isRecordId).map(type.recordName));
325
+ }
326
+
320
327
  async function project(
321
328
  companionPath: string,
322
329
  name: string,
@@ -341,11 +348,20 @@ async function project(
341
348
  return writeProjection(dir, derived, deps.outRoot ?? os.tmpdir());
342
349
  });
343
350
  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
- );
351
+ const archived = await archivedHere(companionPath, type);
352
+ const absent = run.missing.filter((dependency) => !archived.has(dependency));
353
+ const reasons: string[] = [];
354
+ if (absent.length > 0) {
355
+ reasons.push(
356
+ `${name} depends on ${absent.map(inboxText).join(", ")}, which is neither here, submitted nor published.`,
357
+ );
358
+ }
359
+ for (const dependency of run.missing.filter((missing) => archived.has(missing))) {
360
+ reasons.push(
361
+ `${name} depends on ${inboxText(dependency)}, which is archived in this checkout but not published; run \`${FRAMEWORK_NAME} artifact publish ${shellQuote(inboxText(dependency))}\` to make it count.`,
362
+ );
363
+ }
364
+ return failed(name, "error", `mate: ${reasons.join(" ")}`);
349
365
  }
350
366
  if (run.status === "empty") {
351
367
  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
  }
@@ -46,7 +46,7 @@ import {
46
46
  import { isSettled } from "../refresh";
47
47
  import { recordDir, sourceDir, type ArtifactType } from "./artifact-type";
48
48
  import { deliveryGroupFor, type DeliveryGroupName } from "./naming";
49
- import { sourcePathOf, staleParts, STALE_SCAN_LIMIT } from "./pending";
49
+ import { resubmitAccepts, sourcePathOf, staleParts } from "./pending";
50
50
  import { commitToPending } from "./pending-edit";
51
51
  import {
52
52
  defaultRef,
@@ -424,13 +424,7 @@ export async function acceptsBlock(
424
424
  base: string,
425
425
  tip: string,
426
426
  ): Promise<boolean> {
427
- const stale = await staleParts(type, work, ref, folder, base, tip);
428
- // Nothing stale: the block has another cause, which a new base would not lift.
429
- return (
430
- stale.length > 0 &&
431
- stale.length < STALE_SCAN_LIMIT &&
432
- stale.every((part) => part.overwrites === false)
433
- );
427
+ return resubmitAccepts(await staleParts(type, work, ref, folder, base, tip));
434
428
  }
435
429
 
436
430
  /** {@link acceptsBlock} for the folder as staged in the pending checkout `work`. */
@@ -7,6 +7,8 @@ import {
7
7
  companionGit,
8
8
  describeGitFailure,
9
9
  isAuthenticationFailure,
10
+ LITERAL_PATHSPECS,
11
+ nulPaths,
10
12
  outputLines,
11
13
  type GitResult,
12
14
  type UpstreamTarget,
@@ -25,6 +27,7 @@ import {
25
27
  import { FRAMEWORK_NAME } from "../../framework";
26
28
  import { artifactTypes, defaultArtifactType } from "../delivery/staging/registry";
27
29
  import { loadWorkflow } from "../workflow/declaration";
30
+ import { mateManagedSkillNames } from "../../tools/setup";
28
31
  import { LaunchPreflightError } from "./types";
29
32
 
30
33
  type GitCommandResult = GitResult;
@@ -121,11 +124,24 @@ const MANAGED_ROOTS = [".mate", ".opencode", ".claude", ".agents", ".graphify"];
121
124
 
122
125
  type SyncTarget = UpstreamTarget;
123
126
 
124
- function isManagedPath(filePath: string): boolean {
125
- const normalized = filePath.replaceAll("\\", "/").replace(/^\.\//, "");
127
+ const SKILL_ROOTS = new Set([".claude/skills", ".agents/skills", ".opencode/skills"]);
128
+
129
+ function normalizedPath(filePath: string): string {
130
+ return filePath.replaceAll("\\", "/").replace(/^\.\//, "");
131
+ }
132
+
133
+ function isManagedPath(normalized: string): boolean {
126
134
  return MANAGED_ROOTS.some((root) => normalized === root || normalized.startsWith(`${root}/`));
127
135
  }
128
136
 
137
+ function isForcedPath(filePath: string, mateSkillNames: ReadonlySet<string>): boolean {
138
+ const normalized = normalizedPath(filePath);
139
+ if (!isManagedPath(normalized)) return false;
140
+ const [root, folder, entry] = normalized.split("/");
141
+ if (entry === undefined || !SKILL_ROOTS.has(`${root}/${folder}`)) return true;
142
+ return mateSkillNames.has(entry);
143
+ }
144
+
129
145
  export class CompanionGitSync {
130
146
  constructor(private readonly options: CompanionGitSyncOptions = {}) {}
131
147
 
@@ -308,8 +324,10 @@ export class CompanionGitSync {
308
324
  "--no-progress",
309
325
  "--no-edit",
310
326
  ]);
327
+ if (merge.status === 0 && !stashRef) return;
328
+ const skillNames = await mateManagedSkillNames(companionPath);
311
329
  if (merge.status !== 0) {
312
- await this.resolveManagedConflicts(companionPath, target.ref);
330
+ await this.resolveManagedConflicts(companionPath, target.ref, skillNames);
313
331
  const conflicts = await this.unresolvedPaths(companionPath);
314
332
  if (conflicts.length > 0) {
315
333
  throw this.failure(
@@ -334,7 +352,7 @@ export class CompanionGitSync {
334
352
  const apply = await this.command(companionPath, ["stash", "apply", "--index", stashRef]);
335
353
  if (apply.status !== 0) {
336
354
  const applyConflicts = await this.unresolvedPaths(companionPath);
337
- await this.resolveManagedConflicts(companionPath, target.ref);
355
+ await this.resolveManagedConflicts(companionPath, target.ref, skillNames);
338
356
  const conflicts = await this.unresolvedPaths(companionPath);
339
357
  if (conflicts.length > 0) {
340
358
  throw this.failure(
@@ -354,7 +372,7 @@ export class CompanionGitSync {
354
372
  }
355
373
  }
356
374
 
357
- await this.discardManagedChanges(companionPath);
375
+ await this.discardManagedChanges(companionPath, skillNames);
358
376
  const remaining = await this.unresolvedPaths(companionPath);
359
377
  if (remaining.length > 0) {
360
378
  throw this.failure(
@@ -467,10 +485,15 @@ export class CompanionGitSync {
467
485
  return result.status === 0 ? outputLines(result.stdout) : [];
468
486
  }
469
487
 
470
- private async resolveManagedConflicts(companionPath: string, targetRef: string): Promise<void> {
488
+ private async resolveManagedConflicts(
489
+ companionPath: string,
490
+ targetRef: string,
491
+ skillNames: ReadonlySet<string>,
492
+ ): Promise<void> {
471
493
  const conflicts = await this.unresolvedPaths(companionPath);
472
- for (const conflict of conflicts.filter(isManagedPath)) {
494
+ for (const conflict of conflicts.filter((entry) => isForcedPath(entry, skillNames))) {
473
495
  const restore = await this.command(companionPath, [
496
+ ...LITERAL_PATHSPECS,
474
497
  "restore",
475
498
  `--source=${targetRef}`,
476
499
  "--staged",
@@ -485,26 +508,41 @@ export class CompanionGitSync {
485
508
  [conflict],
486
509
  );
487
510
  }
488
- await this.command(companionPath, ["add", "-A", "--", conflict]);
511
+ await this.command(companionPath, [...LITERAL_PATHSPECS, "add", "-A", "--", conflict]);
489
512
  }
490
513
  }
491
514
 
492
- private async discardManagedChanges(companionPath: string): Promise<void> {
493
- const tracked = await this.command(companionPath, [
494
- "ls-files",
495
- "--cached",
515
+ private async discardManagedChanges(
516
+ companionPath: string,
517
+ skillNames: ReadonlySet<string>,
518
+ ): Promise<void> {
519
+ const committed = await this.command(companionPath, [
520
+ "ls-tree",
521
+ "-r",
522
+ "--name-only",
523
+ "-z",
524
+ "HEAD",
496
525
  "--",
497
526
  ...MANAGED_ROOTS,
498
527
  ]);
499
- const trackedPaths = outputLines(tracked.stdout);
500
- if (trackedPaths.length > 0) {
528
+ if (committed.status !== 0) {
529
+ throw this.failure(
530
+ companionPath,
531
+ `Unable to list managed paths in HEAD: ${this.detail(committed)}`,
532
+ );
533
+ }
534
+ const committedPaths = nulPaths(committed.stdout).filter((entry) =>
535
+ isForcedPath(entry, skillNames),
536
+ );
537
+ if (committedPaths.length > 0) {
501
538
  const restore = await this.command(companionPath, [
539
+ ...LITERAL_PATHSPECS,
502
540
  "restore",
503
541
  "--source=HEAD",
504
542
  "--staged",
505
543
  "--worktree",
506
544
  "--",
507
- ...trackedPaths,
545
+ ...committedPaths,
508
546
  ]);
509
547
  if (restore.status !== 0) {
510
548
  throw this.failure(
@@ -513,15 +551,6 @@ export class CompanionGitSync {
513
551
  );
514
552
  }
515
553
  }
516
-
517
- // -x is intentionally omitted: ignored files are local state and must survive.
518
- const clean = await this.command(companionPath, ["clean", "-fd", "--", ...MANAGED_ROOTS]);
519
- if (clean.status !== 0) {
520
- throw this.failure(
521
- companionPath,
522
- `Unable to remove unmanaged managed-path files: ${this.detail(clean)}`,
523
- );
524
- }
525
554
  }
526
555
 
527
556
  private command(companionPath: string, args: readonly string[]): Promise<GitCommandResult> {
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
 
4
+ import { isDirectory } from "../../runtime/git-layout";
4
5
  import { otherServingClaudeWrapRoot } from "../../runtime/serving-claude-wrap";
5
6
  import {
6
7
  carriesClaudeLinks,
@@ -40,15 +41,25 @@ async function servedByMainWorktree(
40
41
  );
41
42
  }
42
43
 
43
- /** Places none, and withdraws earlier ones, where the main worktree serves them. */
44
+ export interface SkillLinkOptions {
45
+ keepExistingFolder?: boolean;
46
+ }
47
+
48
+ /**
49
+ * Places none, and withdraws earlier ones, where the main worktree serves them,
50
+ * unless `keepExistingFolder` keeps an existing folder.
51
+ */
44
52
  export async function reconcileWorkingRepoClaudeSkillLinks(
45
53
  repoPath: string,
46
54
  companionPath: string | null,
47
55
  enabled: boolean,
48
56
  registeredCompanionPaths: string[] = [],
57
+ options: SkillLinkOptions = {},
49
58
  ): ReturnType<typeof reconcileClaudeLinks> {
50
59
  const placed =
51
- enabled && !(await servedByMainWorktree(repoPath, companionPath, registeredCompanionPaths));
60
+ enabled &&
61
+ ((options.keepExistingFolder && isDirectory(path.join(repoPath, ".claude", SKILLS.dir))) ||
62
+ !(await servedByMainWorktree(repoPath, companionPath, registeredCompanionPaths)));
52
63
  return reconcileClaudeLinks(SKILLS, repoPath, companionPath, placed, registeredCompanionPaths);
53
64
  }
54
65
 
@@ -1,4 +1,6 @@
1
- // oxlint-disable no-await-in-loop -- one repository at a time
1
+ // oxlint-disable no-await-in-loop -- one Checkout at a time, the main worktree first
2
+ import { checkoutCommonDir, liveCheckouts, realPath } from "../../runtime/git-layout";
3
+ import { resolveProjection } from "../../runtime/projection";
2
4
  import { readWrapState } from "../../runtime/wrap-state";
3
5
  import { GlobalConfigStore } from "./global-config-store";
4
6
  import { reconcileWorkingRepoClaudeCommandLinks } from "./projection-claude-commands";
@@ -38,10 +40,21 @@ const linkRefreshDeps: LinkRefreshDeps = {
38
40
  reconcileCommandLinks: reconcileWorkingRepoClaudeCommandLinks,
39
41
  };
40
42
 
43
+ function checkoutsOf(repository: LinkedRepository): string[] {
44
+ const commonDir = repository.gitCommonDir ?? checkoutCommonDir(repository.path);
45
+ const checkouts = commonDir ? [...liveCheckouts(commonDir)] : [];
46
+ return checkouts.length > 0 ? checkouts : [repository.path];
47
+ }
48
+
49
+ function servedByOtherCompanion(checkout: string, companionPath: string): boolean {
50
+ const served = resolveProjection(checkout)?.companionPath;
51
+ return served !== undefined && realPath(served) !== realPath(companionPath);
52
+ }
53
+
41
54
  /**
42
- * Re-links the companion's Claude skills and commands into every linked Claude-wrapped
43
- * Working Repository. Links only; runtime documents wait for the wrap pass. Failures
44
- * are reported per repository, never thrown.
55
+ * Re-links the companion's Claude skills and commands into every Claude-wrapped
56
+ * Checkout of each linked Working Repository's clone. Links only; runtime documents
57
+ * wait for the wrap pass. Failures are reported per Checkout, never thrown.
45
58
  */
46
59
  export async function refreshWorkingClaudeLinks(
47
60
  companionPath: string,
@@ -50,6 +63,7 @@ export async function refreshWorkingClaudeLinks(
50
63
  ): Promise<LinkRefreshResult[]> {
51
64
  const enabled = config.allowedAgents?.includes("claude") ?? false;
52
65
  const results: LinkRefreshResult[] = [];
66
+ const seen = new Set<string>();
53
67
  let registered: string[] | undefined;
54
68
  let repositories: LinkedRepository[];
55
69
  try {
@@ -58,32 +72,36 @@ export async function refreshWorkingClaudeLinks(
58
72
  return [{ repository: null, outcome: "failed", error: errorMessage(error) }];
59
73
  }
60
74
 
61
- for (const repository of repositories) {
62
- try {
63
- if (!(await deps.isWrappedForClaude(repository.path))) continue;
64
- registered ??= await deps.registeredCompanionPaths();
65
- const skills = await deps.reconcileSkillLinks(
66
- repository.path,
67
- companionPath,
68
- enabled,
69
- registered,
70
- );
71
- const commands = await deps.reconcileCommandLinks(
72
- repository.path,
73
- companionPath,
74
- enabled,
75
- registered,
76
- );
77
- const written = [skills, commands].some(
78
- (result) => (typeof result === "string" ? result : result.state) === "written",
79
- );
80
- results.push({ repository, outcome: written ? "written" : "current" });
81
- } catch (error) {
82
- results.push({
83
- repository,
84
- outcome: "failed",
85
- error: errorMessage(error),
86
- });
75
+ for (const entry of repositories) {
76
+ for (const checkout of checkoutsOf(entry)) {
77
+ const key = realPath(checkout);
78
+ if (seen.has(key)) continue;
79
+ seen.add(key);
80
+ const repository = { ...entry, path: checkout };
81
+ try {
82
+ if (servedByOtherCompanion(checkout, companionPath)) continue;
83
+ if (!(await deps.isWrappedForClaude(checkout))) continue;
84
+ registered ??= await deps.registeredCompanionPaths();
85
+ const skills = await deps.reconcileSkillLinks(
86
+ checkout,
87
+ companionPath,
88
+ enabled,
89
+ registered,
90
+ { keepExistingFolder: true },
91
+ );
92
+ const commands = await deps.reconcileCommandLinks(
93
+ checkout,
94
+ companionPath,
95
+ enabled,
96
+ registered,
97
+ );
98
+ const written = [skills, commands].some(
99
+ (result) => (typeof result === "string" ? result : result.state) === "written",
100
+ );
101
+ results.push({ repository, outcome: written ? "written" : "current" });
102
+ } catch (error) {
103
+ results.push({ repository, outcome: "failed", error: errorMessage(error) });
104
+ }
87
105
  }
88
106
  }
89
107
  return results;
@@ -439,6 +439,7 @@ async function recordTarget(companionPath: string, worksetId: string): Promise<T
439
439
  if (record) return record;
440
440
  return [
441
441
  `no valid Workset ${worksetId}`,
442
+ `a Workset submitted to the inbox but not in this checkout needs \`${FRAMEWORK_NAME} artifact take "<change>"\` first, or pass --change <change>`,
442
443
  ...problems.map((problem) => `${problem.path}: ${problem.reason}`),
443
444
  ];
444
445
  }
@@ -97,7 +97,9 @@ export async function refuseForkedCompanionWrite(
97
97
  ): Promise<void> {
98
98
  if (!filePath || !isArtifactPath(filePath)) return;
99
99
  if (!isCompanionTarget(context, filePath)) return;
100
- const refusal = await companionForkRefusal(env, context.companionPath);
100
+ const refusal = await companionForkRefusal(env, context.companionPath, {
101
+ target: resolveArtifactTarget(filePath, context.repositoryPath),
102
+ });
101
103
  if (refusal) throw new GuardRefusal("fork", refusal);
102
104
  }
103
105
 
@@ -14,6 +14,8 @@ export interface ArtifactRefusalInput {
14
14
  companion: string;
15
15
  /** The Working Repository root relative targets resolve against. */
16
16
  repoRoot: string;
17
+ /** A shell expansion in the target, as written, that the command text does not settle. */
18
+ unresolved?: string;
17
19
  }
18
20
 
19
21
  /** The absolute path both guards judge: a relative target resolves against the repo root, never a `cd`. */
@@ -34,9 +36,10 @@ export function artifactRefusal({
34
36
  resolved,
35
37
  companion,
36
38
  repoRoot,
39
+ unresolved,
37
40
  }: ArtifactRefusalInput): string {
38
- const isRelative = !path.isAbsolute(target);
39
- const inside = relativeInside(resolved, repoRoot);
41
+ const isRelative = !unresolved && !path.isAbsolute(target);
42
+ const inside = unresolved ? null : relativeInside(resolved, repoRoot);
40
43
  const suggested = inside ? path.join(companion, inside) : null;
41
44
 
42
45
  const lines = [
@@ -51,11 +54,18 @@ export function artifactRefusal({
51
54
  "Relative paths resolve against the working repository; a preceding `cd` is not followed.",
52
55
  );
53
56
  }
54
- lines.push(
55
- suggested
56
- ? "Rewrite to the suggested absolute path and retry."
57
- : `Use an absolute path under ${companion}.`,
58
- );
57
+ if (unresolved) {
58
+ lines.push(
59
+ `The guardrail cannot expand ${unresolved}: it follows only a variable assigned a literal value earlier in the same straight-line command, quoted where the value holds a space or glob character.`,
60
+ `Use a literal absolute path under ${companion}.`,
61
+ );
62
+ } else {
63
+ lines.push(
64
+ suggested
65
+ ? "Rewrite to the suggested absolute path and retry."
66
+ : `Use an absolute path under ${companion}.`,
67
+ );
68
+ }
59
69
  if (path.basename(target) === "CLAUDE.md") {
60
70
  lines.push(`Note: CLAUDE.md already lives in the companion repo at ${companion}/CLAUDE.md.`);
61
71
  }