@buffcore/cli 0.8.47 → 0.8.48

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 (93) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/commands/build/server-text.en.d.ts +5 -0
  3. package/dist/commands/build/server-text.en.js +5 -0
  4. package/dist/commands/build/server-text.js +5 -0
  5. package/dist/commands/build/server.d.ts +4 -0
  6. package/dist/commands/build/server.js +10 -1
  7. package/dist/commands/change-merge.d.ts +2 -2
  8. package/dist/commands/dev.d.ts +9 -2
  9. package/dist/commands/dev.js +24 -5
  10. package/dist/commands/hardening.d.ts +3 -0
  11. package/dist/commands/hardening.en.d.ts +3 -0
  12. package/dist/commands/hardening.en.js +3 -0
  13. package/dist/commands/hardening.es.d.ts +2 -0
  14. package/dist/commands/hardening.es.js +3 -0
  15. package/dist/commands/hardening.js +19 -0
  16. package/dist/commands/prototype/comp-record.d.ts +5 -0
  17. package/dist/commands/prototype/comp-record.js +22 -0
  18. package/dist/commands/server/build.d.ts +2 -1
  19. package/dist/commands/server/build.js +10 -2
  20. package/dist/commands/server/deploy-local.d.ts +3 -0
  21. package/dist/commands/server/deploy-local.js +9 -0
  22. package/dist/commands/server/deploy-plan.d.ts +5 -0
  23. package/dist/commands/server/deploy-plan.js +56 -0
  24. package/dist/commands/server/deploy-result.d.ts +7 -0
  25. package/dist/commands/server/deploy-result.js +1 -0
  26. package/dist/commands/server/deploy-script.d.ts +2 -0
  27. package/dist/commands/server/deploy-script.js +3 -2
  28. package/dist/commands/server/deploy.d.ts +9 -6
  29. package/dist/commands/server/deploy.js +39 -61
  30. package/dist/commands/server/files.d.ts +9 -1
  31. package/dist/commands/server/files.js +25 -5
  32. package/dist/commands/server/image.d.ts +4 -2
  33. package/dist/commands/server/image.js +6 -5
  34. package/dist/commands/server/setup.js +4 -0
  35. package/dist/commands/server/system-packages.d.ts +29 -0
  36. package/dist/commands/server/system-packages.js +103 -0
  37. package/dist/commands/services/compose.d.ts +1 -1
  38. package/dist/commands/services/compose.js +5 -3
  39. package/dist/commands/ui/agents-route.js +2 -0
  40. package/dist/commands/ui/approval-authority.en.d.ts +1 -0
  41. package/dist/commands/ui/approval-authority.en.js +1 -0
  42. package/dist/commands/ui/approval-authority.es.d.ts +1 -0
  43. package/dist/commands/ui/approval-authority.es.js +1 -0
  44. package/dist/commands/ui/approval-authority.js +7 -2
  45. package/dist/commands/ui/approve.js +2 -4
  46. package/dist/commands/ui/autopilot-records.d.ts +2 -0
  47. package/dist/commands/ui/autopilot-records.js +5 -0
  48. package/dist/commands/ui/brand-approval.js +5 -1
  49. package/dist/commands/ui/chat/permissions.js +1 -1
  50. package/dist/commands/ui/chat/routes.js +4 -0
  51. package/dist/commands/ui/comp-approval.d.ts +14 -2
  52. package/dist/commands/ui/comp-approval.js +45 -8
  53. package/dist/commands/ui/level-route.js +3 -0
  54. package/dist/commands/ui/merge-authority.d.ts +4 -1
  55. package/dist/commands/ui/merge-authority.en.d.ts +4 -0
  56. package/dist/commands/ui/merge-authority.en.js +5 -1
  57. package/dist/commands/ui/merge-authority.es.d.ts +4 -0
  58. package/dist/commands/ui/merge-authority.es.js +5 -1
  59. package/dist/commands/ui/merge-authority.js +6 -3
  60. package/dist/commands/ui/merge-claims.d.ts +7 -0
  61. package/dist/commands/ui/merge-claims.js +21 -0
  62. package/dist/commands/ui/merge-delegation.js +8 -3
  63. package/dist/commands/ui/merge-hold-name.d.ts +5 -0
  64. package/dist/commands/ui/merge-hold-name.js +5 -0
  65. package/dist/commands/ui/merge-hold.d.ts +6 -1
  66. package/dist/commands/ui/merge-hold.js +23 -5
  67. package/dist/commands/ui/merge-publish-host.d.ts +1 -0
  68. package/dist/commands/ui/merge-publish-host.js +2 -2
  69. package/dist/commands/ui/merge-record.d.ts +2 -0
  70. package/dist/commands/ui/merge-record.js +1 -1
  71. package/dist/commands/ui/merge-route.js +17 -1
  72. package/dist/commands/ui/merge-settle.d.ts +32 -0
  73. package/dist/commands/ui/merge-settle.js +133 -0
  74. package/dist/commands/ui/merge-state.d.ts +5 -0
  75. package/dist/commands/ui/merge-state.js +7 -1
  76. package/dist/commands/ui/merge-withdraw.d.ts +9 -0
  77. package/dist/commands/ui/merge-withdraw.js +29 -0
  78. package/dist/commands/ui/plan-files.js +5 -2
  79. package/dist/commands/ui/plan-structure.js +5 -7
  80. package/dist/commands/ui/prototype-comp-route.d.ts +12 -3
  81. package/dist/commands/ui/prototype-comp-route.js +35 -17
  82. package/dist/commands/ui/real-file.d.ts +11 -0
  83. package/dist/commands/ui/real-file.js +84 -0
  84. package/dist/commands/ui/save-route.js +4 -1
  85. package/dist/commands/ui/server.d.ts +1 -0
  86. package/dist/commands/ui/server.js +1 -0
  87. package/dist/commands/ui/studio-state.d.ts +1 -0
  88. package/dist/commands/ui/studio-versions.js +19 -3
  89. package/dist/ui/page.js +79 -79
  90. package/docs/PROTOTYPE.md +13 -0
  91. package/docs/WORKBENCH.md +30 -0
  92. package/package.json +11 -11
  93. package/skills/ape-deploy/SKILL.md +4 -2
@@ -7,6 +7,7 @@ import { ApprovalRefusal, approvalRule, signApproval } from '../approval-rules.j
7
7
  import { loadTheme } from '../design/sources.js';
8
8
  import { themeHash } from '../design/state.js';
9
9
  import { themeSources } from '../design/theme-sources.js';
10
+ import { readInsideSync } from './real-file.js';
10
11
  export class BrandChanged extends ApprovalRefusal {
11
12
  }
12
13
  /** The colors and the fingerprint a card must carry come from one resolved source snapshot. */
@@ -27,7 +28,10 @@ export async function brandPreview(root) {
27
28
  export async function brandFingerprint(root, direction, snapshot) {
28
29
  const sources = snapshot?.sources ?? themeSources(root);
29
30
  const theme = snapshot?.theme ?? (await loadTheme(root, sources));
30
- const design = readFileSync(join(root, 'design', 'DESIGN.md'), 'utf8').replace(/\r\n/g, '\n');
31
+ const read = readInsideSync(join(root, 'design', 'DESIGN.md'), [root]);
32
+ if (!read)
33
+ throw new Error('design/DESIGN.md');
34
+ const design = read.toString('utf8').replace(/\r\n/g, '\n');
31
35
  const hash = createHash('sha256')
32
36
  .update(JSON.stringify({ theme: themeHash(theme), design, sources: sources.files }))
33
37
  .digest('hex');
@@ -1,6 +1,6 @@
1
1
  import { matchesGlob } from 'node:path';
2
2
  import { branchChange } from '../../change-trailers.js';
3
- import { mergeHoldName } from '../merge-hold.js';
3
+ import { mergeHoldName } from '../merge-hold-name.js';
4
4
  import { LINKED_SECRETS, linkedPackages } from './linked.js';
5
5
  import { verificationShimRules } from './verification.js';
6
6
  const PLANNING = ['pnpm ape change', 'pnpm ape change new:*'];
@@ -1,4 +1,5 @@
1
1
  import { chatIdSchema, newChatBody, sendBody, stopAnswer, stopBody, } from '@buffcore/contracts/workbench';
2
+ import { withdrawAutopilotClaims } from '../merge-withdraw.js';
2
3
  import { allowFolderRoute } from './allow-folder-route.js';
3
4
  import { readSendBody } from './attachments.js';
4
5
  import { CodingApprovalRefusal } from './coding-approval.js';
@@ -111,6 +112,9 @@ function stopRoute(engine) {
111
112
  return guarded('POST', '/api/chats/:id/stop', forChat(engine, async (chat, request) => {
112
113
  const body = await parsedBody(request, stopBody);
113
114
  const result = await engine.stop(chat.id, body.confirm === true);
115
+ // Stop ends Autopilot's waiting merge for this change too (main not holding it).
116
+ if (chat.change)
117
+ await withdrawAutopilotClaims(engine.root, [chat.change]).catch(() => 0);
114
118
  return result === 'confirm'
115
119
  ? {
116
120
  status: 202,
@@ -1,6 +1,18 @@
1
- import type { ApprovalArtifact } from './approval-authority.ts';
1
+ import type { Approval } from '@buffcore/contracts/approvals';
2
+ import { type CompSnapshot } from '../prototype/comp.ts';
3
+ import { type CompRecord } from '../prototype/comp-record.ts';
4
+ import { type ApprovalArtifact, type ApprovalContext } from './approval-authority.ts';
2
5
  import { type SaveSource } from './host-save.ts';
3
6
  import type { UiAnswer } from './routes.ts';
4
- export declare function compApproval(root: string, fingerprint: string, signer?: string, role?: string, agent?: string, source?: SaveSource): Promise<UiAnswer>;
7
+ export declare function compApproval(root: string, fingerprint: string, signer?: string, role?: string, agent?: string, source?: SaveSource, context?: ApprovalContext): Promise<UiAnswer>;
5
8
  /** What a host's authority judges: the comp the page showed, at the commit checked out. */
6
9
  export declare function compResolver(root: string, fingerprint: string): Promise<() => ApprovalArtifact>;
10
+ /**
11
+ * Under a host's authority the comp read says approved only when the host confirms the grant the
12
+ * record names (`action: 'check'`); a refusal, error or timeout leaves it unapproved, with the reason.
13
+ */
14
+ export declare function hostedComp(root: string, record: CompRecord | undefined, comp: CompSnapshot | undefined, context: ApprovalContext): Promise<{
15
+ approved: boolean;
16
+ approval: Approval | null;
17
+ approvalRefusal?: string;
18
+ }>;
@@ -1,17 +1,15 @@
1
- // Approve the look: the guarded approval route's door for the comp. A person's only, at every level;
2
- // there is no agent, MCP or Autopilot door, and `approveComp` refuses an agent's name. The record is
3
- // saved as its own isolated commit, as a version approval is (`saveApprovalRecord`).
4
1
  import { ApprovalRefusal } from '../approval-rules.js';
5
2
  import { newestComp } from '../prototype/comp.js';
6
- import { approveComp, COMP_FILE } from '../prototype/comp-record.js';
3
+ import { approveComp, COMP_FILE, compApproved, compGrantRecord, } from '../prototype/comp-record.js';
7
4
  import { compT } from '../prototype/comp-words.js';
8
5
  import { VersionRefusal } from '../prototype/versions.js';
9
6
  import { hostGit } from '../safe-git.js';
10
- import { HostSaveRefusal } from './host-save.js';
7
+ import { authorityMessage, authorityRefusal, judge, } from './approval-authority.js';
8
+ import { HostSaveRefusal, saveRefused } from './host-save.js';
11
9
  import { saveApprovalRecord } from './save-route.js';
12
10
  const git = async (root, args) => (await hostGit(root, args)).trim();
13
- export async function compApproval(root, fingerprint, signer, role, agent, source) {
14
- if (agent !== undefined)
11
+ export async function compApproval(root, fingerprint, signer, role, agent, source, context) {
12
+ if (agent !== undefined || context?.agent !== undefined || context?.ai !== undefined)
15
13
  return { status: 409, body: { error: compT('comp.person') } };
16
14
  const by = signer ?? (await git(root, ['config', 'user.email']).catch(() => ''));
17
15
  if (!by)
@@ -20,7 +18,25 @@ export async function compApproval(root, fingerprint, signer, role, agent, sourc
20
18
  if (!commit)
21
19
  return { status: 409, body: { error: compT('comp.commitFirst') } };
22
20
  try {
23
- const record = await saveApprovalRecord(root, COMP_FILE, (write = true) => approveComp(root, { by, commit, fingerprint, role }, write), by, undefined, source);
21
+ // Under a host's authority the host decides, once; its grant is recorded as the studio's own.
22
+ const resolve = context ? await compResolver(root, fingerprint) : undefined;
23
+ const answer = context && resolve ? await judge(context, resolve, 'approve') : undefined;
24
+ if (answer && !answer.allowed)
25
+ return authorityRefusal(answer.code);
26
+ if (answer?.allowed && !answer.approval)
27
+ return { status: 202, body: null };
28
+ const granted = answer?.allowed ? answer.approval : null;
29
+ const record = await saveApprovalRecord(root, COMP_FILE, (write = true) => granted
30
+ ? compGrantRecord(root, granted, write)
31
+ : approveComp(root, { by, commit, fingerprint, role }, write), by, undefined, source, resolve &&
32
+ (() => {
33
+ try {
34
+ resolve();
35
+ }
36
+ catch {
37
+ throw saveRefused('save_artifact_changed');
38
+ }
39
+ }));
24
40
  return { status: 201, body: record.approval };
25
41
  }
26
42
  catch (error) {
@@ -40,3 +56,24 @@ export async function compResolver(root, fingerprint) {
40
56
  return { kind: 'comp', version: null, commit, fingerprint };
41
57
  };
42
58
  }
59
+ /**
60
+ * Under a host's authority the comp read says approved only when the host confirms the grant the
61
+ * record names (`action: 'check'`); a refusal, error or timeout leaves it unapproved, with the reason.
62
+ */
63
+ export async function hostedComp(root, record, comp, context) {
64
+ const commit = record?.approval.signatures[0]?.commit;
65
+ if (!record || !comp || !commit)
66
+ return { approved: false, approval: null };
67
+ const fingerprint = comp.fingerprint;
68
+ const answer = await judge(context, () => {
69
+ if (newestComp(root)?.fingerprint !== fingerprint)
70
+ throw new Error();
71
+ return { kind: 'comp', version: null, commit, fingerprint };
72
+ }, 'check', root);
73
+ if (!answer.allowed)
74
+ return { approved: false, approval: null, approvalRefusal: authorityMessage(answer.code) };
75
+ if (!answer.approval)
76
+ return { approved: false, approval: null };
77
+ const held = { folder: record.folder, approval: answer.approval };
78
+ return { approved: compApproved(held, comp), approval: answer.approval };
79
+ }
@@ -4,6 +4,7 @@ import { personForTurn } from './chat/person.js';
4
4
  import { hostT, levelElsewhere } from './host.js';
5
5
  import { publishSave } from './host-save.js';
6
6
  import { factsChanged, mergeEvent } from './merge-events.js';
7
+ import { afterLevel } from './merge-withdraw.js';
7
8
  import { studioSave } from './save-route.js';
8
9
  /** A person's settings action: save only this selection, even while a turn is running. */
9
10
  export function levelRoute(root) {
@@ -43,6 +44,8 @@ export function levelRoute(root) {
43
44
  prepare: () => publishSave(target, 'level', 'plan/agents.md', content, request),
44
45
  }
45
46
  : undefined);
47
+ if (level !== 'auto')
48
+ await afterLevel(target);
46
49
  return { status: result.ok ? 202 : 409, body: result };
47
50
  },
48
51
  };
@@ -19,6 +19,8 @@ export type HostMergeInput = MergeFacts & Readonly<{
19
19
  signal: AbortSignal;
20
20
  /** Run the final write here, including when publishing a queued request. */
21
21
  publish: HostPublish;
22
+ /** Autopilot's ask only: names it to `settleHostMerge` when a queue merges it later. */
23
+ claim?: string;
22
24
  }>;
23
25
  export type HostMergeAnswer = {
24
26
  status: 'merged';
@@ -46,6 +48,7 @@ export type MergeContext = Readonly<{
46
48
  agent?: string;
47
49
  }>;
48
50
  export declare const mergeT: (key: keyof typeof en, values?: Record<string, unknown>) => string;
51
+ export declare const reservedCode: (code: string) => boolean;
49
52
  export declare const mergeHeldCode = "autopilot_merge_held";
50
53
  export declare const mergeMessage: (code: string) => string;
51
54
  export declare const mergeRefusal: (code: string) => {
@@ -74,4 +77,4 @@ export declare const refusalCode: z.ZodString;
74
77
  export declare const receiptText: z.ZodString;
75
78
  export declare function immutableFacts(facts: MergeFacts): MergeFacts;
76
79
  /** One bounded call, with late settlements consumed and no fallback or retry. */
77
- export declare function callMerge(context: MergeContext, facts: MergeFacts, publication: 'person' | HostPublish, signal?: AbortSignal, current?: () => boolean): Promise<HostMergeAnswer>;
80
+ export declare function callMerge(context: MergeContext, facts: MergeFacts, publication: 'person' | HostPublish, signal?: AbortSignal, current?: () => boolean, claim?: string): Promise<HostMergeAnswer>;
@@ -6,6 +6,10 @@ export declare const en: {
6
6
  'ui.merge.stopped': string;
7
7
  'ui.merge.pending': string;
8
8
  'ui.merge.since': string;
9
+ 'ui.merge.settleRefused': string;
10
+ 'ui.merge.settleHeld': string;
11
+ 'ui.merge.withdrawn': string;
12
+ 'ui.merge.notWithdrawn': string;
9
13
  'ui.merge.refused': string;
10
14
  'ui.merge.error': string;
11
15
  'ui.merge.timeout': string;
@@ -5,7 +5,11 @@ export const en = {
5
5
  'ui.merge.config': 'The host merge configuration conflicts or its timeout is not an integer from 1 to 30000 milliseconds.',
6
6
  'ui.merge.stopped': 'The last merge of this change ended without an answer (the studio stopped). Merge again.',
7
7
  'ui.merge.pending': 'Waiting for the host to merge.',
8
- 'ui.merge.since': 'Waiting for the host to merge. Asked {at}.',
8
+ 'ui.merge.since': 'Waiting for the host to merge. Asked {at}, {hours, plural, =0 {{minutes, plural, one {# minute} other {# minutes}}} one {# hour} other {# hours}} ago.',
9
+ 'ui.merge.settleRefused': 'The host could not settle this merge request. Reason: {code}.',
10
+ 'ui.merge.settleHeld': 'Autopilot merges are held, so the host could not settle this merge request.',
11
+ 'ui.merge.withdrawn': 'The merge request was withdrawn. The change can be merged again.',
12
+ 'ui.merge.notWithdrawn': 'There is no merge request to withdraw, or main already holds the change.',
9
13
  'ui.merge.refused': 'The host did not merge this change. Reason: {code}.',
10
14
  'ui.merge.error': 'The host merge could not be confirmed. Check its result before continuing.',
11
15
  'ui.merge.timeout': 'The host did not answer in time. Check its result before continuing.',
@@ -6,6 +6,10 @@ export declare const es: {
6
6
  'ui.merge.stopped': string;
7
7
  'ui.merge.pending': string;
8
8
  'ui.merge.since': string;
9
+ 'ui.merge.settleRefused': string;
10
+ 'ui.merge.settleHeld': string;
11
+ 'ui.merge.withdrawn': string;
12
+ 'ui.merge.notWithdrawn': string;
9
13
  'ui.merge.refused': string;
10
14
  'ui.merge.error': string;
11
15
  'ui.merge.timeout': string;
@@ -5,7 +5,11 @@ export const es = {
5
5
  'ui.merge.config': 'La configuración de integración del anfitrión entra en conflicto o su tiempo límite no es un entero de 1 a 30000 milisegundos.',
6
6
  'ui.merge.stopped': 'La última integración de este cambio terminó sin respuesta (el estudio se detuvo). Vuelve a integrar.',
7
7
  'ui.merge.pending': 'Esperando a que el anfitrión integre el cambio.',
8
- 'ui.merge.since': 'Esperando a que el anfitrión integre el cambio. Solicitado {at}.',
8
+ 'ui.merge.since': 'Esperando a que el anfitrión integre el cambio. Solicitado {at}, hace {hours, plural, =0 {{minutes, plural, one {# minuto} other {# minutos}}} one {# hora} other {# horas}}.',
9
+ 'ui.merge.settleRefused': 'El anfitrión no pudo resolver esta solicitud de integración. Motivo: {code}.',
10
+ 'ui.merge.settleHeld': 'Las integraciones de Autopilot están en pausa, así que el anfitrión no pudo resolver esta solicitud.',
11
+ 'ui.merge.withdrawn': 'Se retiró la solicitud de integración. El cambio se puede volver a integrar.',
12
+ 'ui.merge.notWithdrawn': 'No hay ninguna solicitud de integración que retirar, o main ya contiene el cambio.',
9
13
  'ui.merge.refused': 'El anfitrión no integró este cambio. Motivo: {code}.',
10
14
  'ui.merge.error': 'No se pudo confirmar la integración del anfitrión. Revisa el resultado antes de continuar.',
11
15
  'ui.merge.timeout': 'El anfitrión no respondió a tiempo. Revisa el resultado antes de continuar.',
@@ -14,7 +14,10 @@ const reserved = {
14
14
  merge_not_observed: 'ui.merge.unobserved',
15
15
  merge_record_failed: 'ui.merge.record',
16
16
  merge_publication_lock: 'ui.merge.publicationLock',
17
+ merge_settle_invalid: 'ui.merge.settleRefused',
18
+ merge_settle_unknown: 'ui.merge.settleRefused',
17
19
  };
20
+ export const reservedCode = (code) => Object.hasOwn(reserved, code) || code === mergeHeldCode;
18
21
  export const mergeHeldCode = 'autopilot_merge_held';
19
22
  export const mergeMessage = (code) => mergeT(Object.hasOwn(reserved, code) ? reserved[code] : 'ui.merge.refused', {
20
23
  code,
@@ -102,8 +105,7 @@ function validated(value, head) {
102
105
  const parsed = answerSchema.safeParse(value);
103
106
  if (!parsed.success || (parsed.data.status === 'merged' && parsed.data.head !== head))
104
107
  return refused('merge_authority_invalid');
105
- if (parsed.data.status === 'not_merged' &&
106
- (Object.hasOwn(reserved, parsed.data.code) || parsed.data.code === mergeHeldCode))
108
+ if (parsed.data.status === 'not_merged' && reservedCode(parsed.data.code))
107
109
  return refused('merge_authority_invalid');
108
110
  return parsed.data;
109
111
  }
@@ -125,7 +127,7 @@ export function immutableFacts(facts) {
125
127
  });
126
128
  }
127
129
  /** One bounded call, with late settlements consumed and no fallback or retry. */
128
- export async function callMerge(context, facts, publication, signal, current = () => true) {
130
+ export async function callMerge(context, facts, publication, signal, current = () => true, claim) {
129
131
  try {
130
132
  if (signal?.aborted)
131
133
  return refused('merge_authority_error');
@@ -133,6 +135,7 @@ export async function callMerge(context, facts, publication, signal, current = (
133
135
  ...immutableFacts(facts),
134
136
  viewer: context.viewer,
135
137
  ...(context.agent ? { agent: context.agent } : {}),
138
+ ...(claim ? { claim } : {}),
136
139
  };
137
140
  if (!current())
138
141
  return refused('merge_artifact_changed');
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Under the publication lock the caller holds: withdraw each waiting Autopilot claim (of the named
3
+ * changes, or all) whose head main does not hold, so a host's later settle of it is unknown. A
4
+ * head main already holds is a merge, left for the next read to record. A Git that cannot say
5
+ * withdraws: Autopilot never keeps a claim it cannot judge.
6
+ */
7
+ export declare function withdrawWaiting(root: string, changes?: readonly string[]): Promise<number>;
@@ -0,0 +1,21 @@
1
+ import { readRecord } from './autopilot-records.js';
2
+ import { mainHas } from './merge-observed.js';
3
+ import { closeRecord, withdraw } from './merge-record.js';
4
+ /**
5
+ * Under the publication lock the caller holds: withdraw each waiting Autopilot claim (of the named
6
+ * changes, or all) whose head main does not hold, so a host's later settle of it is unknown. A
7
+ * head main already holds is a merge, left for the next read to record. A Git that cannot say
8
+ * withdraws: Autopilot never keeps a claim it cannot judge.
9
+ */
10
+ export async function withdrawWaiting(root, changes) {
11
+ let count = 0;
12
+ for (const pending of readRecord(root)?.pending ?? []) {
13
+ if (!pending.automatic || (changes && !changes.includes(pending.change)))
14
+ continue;
15
+ if (await mainHas(root, pending.head).catch(() => false))
16
+ continue;
17
+ if (await closeRecord(root, withdraw(pending, undefined)))
18
+ count++;
19
+ }
20
+ return count;
21
+ }
@@ -1,4 +1,4 @@
1
- import { randomUUID } from 'node:crypto';
1
+ import { createHash, randomBytes, randomUUID } from 'node:crypto';
2
2
  import { defaultMergeTools, locked } from '../change-merge.js';
3
3
  import { readRecord, updateRecord, } from './autopilot-records.js';
4
4
  import { mergeRefusal, mergeWaiting, } from './merge-authority.js';
@@ -74,6 +74,8 @@ const alreadyMerged = (root, facts) => isAncestor(root, facts.head, facts.base);
74
74
  async function requestMerge(root, authority, facts, signal, saw, current, artifact, previous, holdFile, checkMain) {
75
75
  if (await alreadyMerged(root, facts))
76
76
  return mergeWaiting();
77
+ // Autopilot's ask names itself to the host with a secret; the record keeps only its hash.
78
+ const secret = holdFile ? randomBytes(32).toString('base64url') : undefined;
77
79
  const claim = {
78
80
  change: facts.change,
79
81
  head: facts.head,
@@ -82,14 +84,17 @@ async function requestMerge(root, authority, facts, signal, saw, current, artifa
82
84
  // The base this merge verified, not a fresh read: a host merge landing meanwhile must not become
83
85
  // the claim's main, or the wait could never be observed (currentMerge checks main again).
84
86
  main: facts.base,
85
- ...(holdFile && { automatic: true }),
87
+ ...(secret && {
88
+ automatic: true,
89
+ claimHash: createHash('sha256').update(secret).digest('hex'),
90
+ }),
86
91
  };
87
92
  if (holdFile && mergeHeld(holdFile))
88
93
  return heldMerge(facts.head);
89
94
  if (!updateRecord(root, ask(saw, claim)))
90
95
  return mergeWaiting();
91
96
  const { answer, withdrawn, publicationRefusal } = current()
92
- ? await askHost(authority, facts, signal, () => current() && artifact() && current() && !(holdFile && mergeHeld(holdFile)), holdFile ? { root, path: holdFile, claim } : undefined, current, checkMain)
97
+ ? await askHost(authority, facts, signal, () => current() && artifact() && current() && !(holdFile && mergeHeld(holdFile)), holdFile && secret ? { root, path: holdFile, claim, secret } : undefined, current, checkMain)
93
98
  : { answer: { status: 'not_merged', code: 'merge_artifact_changed' } };
94
99
  if (withdrawn && answer.status !== 'merged') {
95
100
  try {
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The hold file's name, in a module with no imports: the turn permissions read it while the merge
3
+ * modules may still be loading (merge-hold imports merge-claims, which reaches back to chat).
4
+ */
5
+ export declare const mergeHoldName = "ape-autopilot-merge-hold";
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The hold file's name, in a module with no imports: the turn permissions read it while the merge
3
+ * modules may still be loading (merge-hold imports merge-claims, which reaches back to chat).
4
+ */
5
+ export const mergeHoldName = 'ape-autopilot-merge-hold';
@@ -1,3 +1,4 @@
1
+ import { mergeHoldName } from './merge-hold-name.ts';
1
2
  export declare const heldMerge: (head?: string) => {
2
3
  ok: false;
3
4
  reason: 'held';
@@ -5,7 +6,7 @@ export declare const heldMerge: (head?: string) => {
5
6
  detail: string;
6
7
  head: string | undefined;
7
8
  };
8
- export declare const mergeHoldName = "ape-autopilot-merge-hold";
9
+ export { mergeHoldName };
9
10
  /** Both local and hosted Autopilot run the actual write inside this gate. */
10
11
  export declare function publishAutomatic<T>(path: string, head: string, current: () => boolean, write: () => Promise<T> | T): Promise<T | {
11
12
  ok: false;
@@ -28,6 +29,10 @@ export declare class MergePublicationLockError extends Error {
28
29
  }
29
30
  /** Order the switch write against an in-flight ref transaction, never against the merge checks. */
30
31
  export declare function mergePublication<T>(path: string, action: () => Promise<T> | T): Promise<T>;
32
+ /**
33
+ * Turning the hold on withdraws, under the same lock, the waiting Autopilot claims of every product
34
+ * root this process has seen for the file (a settle also refuses a hold written after its ask).
35
+ */
31
36
  export declare function writeMergeHold(path: string, held: boolean): Promise<void>;
32
37
  /** Release can come from another studio. Wait without holding the merge or turn reservation. */
33
38
  export declare function waitForMergeHold(root: string, signal: AbortSignal, blocked: () => boolean): Promise<boolean>;
@@ -1,13 +1,15 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { lstatSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
- import { dirname, join } from 'node:path';
3
+ import { dirname, join, resolve } from 'node:path';
4
4
  import { setTimeout } from 'node:timers/promises';
5
5
  import { t } from '../change-merge.en.js';
6
6
  import { lockText, mergeLockName, reclaimDeadLock } from '../change-merge-lock.js';
7
7
  import { hostGit, hostGitSync, localGitEnv } from '../safe-git.js';
8
8
  import { autoT } from './autopilot-person.js';
9
9
  import { mergeHeldCode, mergeMessage } from './merge-authority.js';
10
+ import { withdrawWaiting } from './merge-claims.js';
10
11
  import { mergeEvent } from './merge-events.js';
12
+ import { mergeHoldName } from './merge-hold-name.js';
11
13
  export const heldMerge = (head) => ({
12
14
  ok: false,
13
15
  reason: 'held',
@@ -15,7 +17,7 @@ export const heldMerge = (head) => ({
15
17
  detail: autoT('auto.mergeHeld'),
16
18
  head,
17
19
  });
18
- export const mergeHoldName = 'ape-autopilot-merge-hold';
20
+ export { mergeHoldName };
19
21
  /** Both local and hosted Autopilot run the actual write inside this gate. */
20
22
  export function publishAutomatic(path, head, current, write) {
21
23
  return mergePublication(path, () => {
@@ -26,6 +28,15 @@ export function publishAutomatic(path, head, current, write) {
26
28
  return write();
27
29
  });
28
30
  }
31
+ /** Each product root seen per hold file: turning the hold on withdraws their waiting claims. */
32
+ const holdRoots = new Map();
33
+ function known(root, common) {
34
+ const path = join(common, mergeHoldName);
35
+ const roots = holdRoots.get(resolve(path)) ?? new Set();
36
+ roots.add(resolve(root));
37
+ holdRoots.set(resolve(path), roots);
38
+ return path;
39
+ }
29
40
  export function mergeHoldPath(root) {
30
41
  try {
31
42
  const common = hostGitSync(root, ['rev-parse', '--path-format=absolute', '--git-common-dir'], {
@@ -33,7 +44,7 @@ export function mergeHoldPath(root) {
33
44
  env: localGitEnv,
34
45
  }).trim();
35
46
  if (common)
36
- return join(common, mergeHoldName);
47
+ return known(root, common);
37
48
  }
38
49
  catch {
39
50
  // Git did not identify the repository. Its state cannot grant permission to merge.
@@ -47,7 +58,7 @@ export async function mergeHoldPathAsync(root) {
47
58
  env: localGitEnv,
48
59
  })).trim();
49
60
  if (common)
50
- return join(common, mergeHoldName);
61
+ return known(root, common);
51
62
  }
52
63
  catch {
53
64
  // Git did not identify the repository. Its state cannot grant permission to merge.
@@ -140,8 +151,12 @@ export async function mergePublication(path, action) {
140
151
  await releasePublication(lock, owner);
141
152
  }
142
153
  }
154
+ /**
155
+ * Turning the hold on withdraws, under the same lock, the waiting Autopilot claims of every product
156
+ * root this process has seen for the file (a settle also refuses a hold written after its ask).
157
+ */
143
158
  export async function writeMergeHold(path, held) {
144
- await mergePublication(path, () => {
159
+ await mergePublication(path, async () => {
145
160
  const temporary = `${path}.${randomUUID()}.tmp`;
146
161
  try {
147
162
  writeFileSync(temporary, held ? 'on\n' : 'off\n', { flag: 'wx', mode: 0o600 });
@@ -152,6 +167,9 @@ export async function writeMergeHold(path, held) {
152
167
  finally {
153
168
  rmSync(temporary, { force: true });
154
169
  }
170
+ if (held)
171
+ for (const root of holdRoots.get(resolve(path)) ?? [])
172
+ await withdrawWaiting(root).catch(() => 0);
155
173
  });
156
174
  }
157
175
  /** Release can come from another studio. Wait without holding the merge or turn reservation. */
@@ -6,6 +6,7 @@ export declare function askHost(authority: MergeContext, facts: MergeFacts, sign
6
6
  root: string;
7
7
  path: string;
8
8
  claim: PendingMerge;
9
+ secret: string;
9
10
  } | undefined, permitted?: () => boolean, checkMain?: MainPublicationCheck): Promise<{
10
11
  answer: import("./merge-authority.ts").HostMergeAnswer;
11
12
  withdrawn?: undefined;
@@ -6,7 +6,7 @@ import { closeRecord, rememberPublication, withdraw } from './merge-record.js';
6
6
  export async function askHost(authority, facts, signal, current, automatic, permitted = () => true, checkMain) {
7
7
  if (!automatic)
8
8
  return { answer: await callMerge(authority, facts, 'person', signal, current) };
9
- const { root, path, claim } = automatic;
9
+ const { root, path, claim, secret } = automatic;
10
10
  const hold = new AbortController();
11
11
  let waiting = true;
12
12
  let eligible = true;
@@ -56,7 +56,7 @@ export async function askHost(authority, facts, signal, current, automatic, perm
56
56
  const timer = setInterval(inspect, 50);
57
57
  try {
58
58
  const ends = signal ? AbortSignal.any([signal, hold.signal]) : hold.signal;
59
- const answer = await callMerge(authority, facts, publish, ends, current);
59
+ const answer = await callMerge(authority, facts, publish, ends, current, secret);
60
60
  inspect();
61
61
  eligible = answer.status === 'pending' && !publicationRefusal;
62
62
  return {
@@ -18,6 +18,8 @@ export declare const asksAgain: (pending: PendingMerge, timeout: number, now?: n
18
18
  * file holds now and returns undefined (no write) when they differ, so a stale caller does nothing.
19
19
  */
20
20
  export declare const ask: (saw: PendingMerge | undefined, claim: PendingMerge) => (record: StudioRecord) => StudioRecord | undefined;
21
+ /** A queued automatic result is observable only after its guarded write returned success. */
22
+ export declare const published: (claim: PendingMerge) => (record: StudioRecord) => StudioRecord | undefined;
21
23
  export declare const hostPublished: (claim: PendingMerge) => boolean;
22
24
  export declare function rememberPublication(root: string, claim: PendingMerge): Promise<void>;
23
25
  /** Ends the wait this claim started and keeps what became of it; never touches another head's. */
@@ -44,7 +44,7 @@ export const ask = (saw, claim) => (record) => same(record.pending.find((entry)
44
44
  }
45
45
  : undefined;
46
46
  /** A queued automatic result is observable only after its guarded write returned success. */
47
- const published = (claim) => (record) => record.pending.some((entry) => same(entry, claim))
47
+ export const published = (claim) => (record) => record.pending.some((entry) => same(entry, claim))
48
48
  ? {
49
49
  ...record,
50
50
  pending: record.pending.map((entry) => same(entry, claim) ? { ...entry, published: true } : entry),
@@ -6,12 +6,13 @@ import { sweepAfterMerge } from '../worktree-sweep.js';
6
6
  import { hostMergeAuthority } from './approval-artifact.js';
7
7
  import { authorityFor, authorityMessage } from './approval-authority.js';
8
8
  import { catchUpOne } from './catch-up.js';
9
- import { mergeContext, mergeWaiting } from './merge-authority.js';
9
+ import { mergeContext, mergeT, mergeWaiting } from './merge-authority.js';
10
10
  import { delegatedTools, waitingMerge } from './merge-delegation.js';
11
11
  import { factsChanged } from './merge-events.js';
12
12
  import { MergePublicationLockError } from './merge-hold.js';
13
13
  import { mergePreviewRoutes } from './merge-preview-route.js';
14
14
  import { beginLocalMerge, endLocalMerge } from './merge-record.js';
15
+ import { withdrawMerge } from './merge-withdraw.js';
15
16
  import { checkAfterMerge } from './post-merge.js';
16
17
  import { identityEnv } from './save-git.js';
17
18
  import { mergeView } from './snapshot-view.js';
@@ -29,6 +30,21 @@ export function mergeRoutes(root) {
29
30
  return [
30
31
  personMergeRoute(root),
31
32
  ...mergePreviewRoutes(root),
33
+ {
34
+ // A person ends a wait the host never answered, so it cannot hold Autopilot for good.
35
+ method: 'POST',
36
+ path: '/api/merge/withdraw',
37
+ right: 'build',
38
+ handle: async ({ body }) => {
39
+ const parsed = mergeBody.safeParse(await body());
40
+ if (!parsed.success)
41
+ return { status: 400, body: { error: t('change.merge.invalid') } };
42
+ const done = await withdrawMerge(root, parsed.data.change).catch(() => false);
43
+ return done
44
+ ? { status: 200, body: { ok: true, detail: mergeT('ui.merge.withdrawn') } }
45
+ : { status: 409, body: { ok: false, detail: mergeT('ui.merge.notWithdrawn') } };
46
+ },
47
+ },
32
48
  {
33
49
  method: 'POST',
34
50
  path: '/api/worktree',
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The host's later word on a queued Autopilot merge it answered `pending`. `claim` is the
3
+ * `HostMergeInput.claim` the host was given with that ask. The studio's record keeps only its
4
+ * SHA-256, so reading the record does not give it; it names that one ask, never another.
5
+ */
6
+ export type HostMergeSettlement = Readonly<{
7
+ change: string;
8
+ head: string;
9
+ claim: string;
10
+ /** `check` writes nothing: whether a `merged` settle would pass the gate now (main aside). */
11
+ outcome: 'merged' | 'not_merged' | 'check';
12
+ code?: string;
13
+ }>;
14
+ export type HostMergeSettled = {
15
+ status: 'merged' | 'not_merged' | 'ready';
16
+ } | {
17
+ status: 'refused';
18
+ code: string;
19
+ detail: string;
20
+ };
21
+ /**
22
+ * Settles one waiting Autopilot claim from the host's own process; no HTTP route reaches it. It
23
+ * runs under the same publication gate as `publish`: a held repository, a level other than
24
+ * Autopilot, an edit of `plan/agents.md` or of the hold since the ask (which also withdraws the
25
+ * claim), another change's or head's claim, a withdrawn claim, a moved branch, or (for `merged`)
26
+ * a main without the exact head refuses; a record that cannot be written answers
27
+ * `merge_record_failed`, and a publication lock that stays busy `merge_publication_lock`. A claim
28
+ * that has ended is withdrawn by any settle, so Autopilot asks again. A `merged` settlement records what `publish` records; the studio's next
29
+ * read records the merge and starts its Snapshot, exactly as for a published claim. `check`
30
+ * answers `ready` when a `merged` settle would pass the gate now, and writes nothing.
31
+ */
32
+ export declare function settleHostMerge(root: string, input: HostMergeSettlement): Promise<HostMergeSettled>;