@moretea-labs/forge 1.7.0 → 1.7.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 (175) hide show
  1. package/AGENTS.md +2 -0
  2. package/CHANGELOG.md +13 -0
  3. package/CLAUDE.md +2 -0
  4. package/THIRD_PARTY_NOTICES.md +1 -1
  5. package/agents/openai.yaml +1 -1
  6. package/assets/partials-agents/02-operating-mode.partial.md +2 -0
  7. package/assets/plugin-registry.v1.json +3 -3
  8. package/assets/skill-version.json +2 -2
  9. package/assets/templates/helpers/check-architecture-sync.sh +17 -0
  10. package/assets/templates/helpers/inspect-project-state.ts +8 -6
  11. package/assets/templates/helpers/migrate-workflow-docs.ts +9 -7
  12. package/assets/templates/helpers/workflow-contract.ts +5 -1
  13. package/docs/architecture/CURRENT.md +12 -4
  14. package/docs/forge-plugin-management.md +1 -1
  15. package/docs/operations/controller-performance-and-502.md +19 -0
  16. package/docs/operations/homebrew.md +2 -2
  17. package/package.json +5 -2
  18. package/scripts/architecture-event.ts +2 -820
  19. package/scripts/architecture-queue.sh +2 -645
  20. package/scripts/archive-architecture-request.sh +2 -242
  21. package/scripts/archive-workflow.sh +1 -291
  22. package/scripts/benchmark-work-efficiency.ts +0 -0
  23. package/scripts/capability-config.ts +2 -392
  24. package/scripts/capability-resolver.ts +2 -503
  25. package/scripts/capture-plan.sh +1 -332
  26. package/scripts/check-agent-tooling.sh +2 -1531
  27. package/scripts/check-architecture-sync.sh +2 -302
  28. package/scripts/check-brain-manifest.sh +2 -253
  29. package/scripts/check-context-files.sh +2 -47
  30. package/scripts/check-deploy-sql-order.sh +2 -115
  31. package/scripts/check-runtime-architecture.mjs +243 -16
  32. package/scripts/check-skill-version.ts +3 -191
  33. package/scripts/check-source-duplication.mjs +61 -0
  34. package/scripts/check-stable-baseline.ts +0 -0
  35. package/scripts/check-task-sync.sh +2 -63
  36. package/scripts/check-task-workflow.sh +2 -1000
  37. package/scripts/codex-handoff-resume.sh +2 -267
  38. package/scripts/context-contract-sync.sh +2 -514
  39. package/scripts/contract-run.ts +2 -463
  40. package/scripts/contract-worktree.sh +1 -702
  41. package/scripts/ensure-task-workflow.sh +1 -1192
  42. package/scripts/inspect-project-state.ts +4 -279
  43. package/scripts/lib/project-init-lib.sh +7 -2
  44. package/scripts/lib/run-forge-helper.sh +19 -0
  45. package/scripts/lib/run-forge-helper.ts +26 -0
  46. package/scripts/migrate-project-template.sh +1 -33
  47. package/scripts/migrate-workflow-docs.ts +4 -412
  48. package/scripts/new-plan.sh +1 -180
  49. package/scripts/new-spec.sh +1 -47
  50. package/scripts/new-sprint.sh +1 -46
  51. package/scripts/plan-to-todo.sh +1 -771
  52. package/scripts/prepare-codex-handoff.sh +2 -201
  53. package/scripts/prepare-handoff.sh +1 -78
  54. package/scripts/refresh-current-status.sh +2 -467
  55. package/scripts/run-governed-gate.ts +3 -0
  56. package/scripts/select-agent-context-blocks.sh +2 -64
  57. package/scripts/ship-worktrees.sh +1 -531
  58. package/scripts/sprint-backlog.sh +1 -834
  59. package/scripts/stage-runtime-release.ts +2 -1
  60. package/scripts/summarize-failures.sh +2 -123
  61. package/scripts/switch-plan.sh +1 -150
  62. package/scripts/sync-brain-docs.sh +2 -379
  63. package/scripts/sync-generated-authority.mjs +175 -0
  64. package/scripts/verify-contract.sh +2 -593
  65. package/scripts/verify-sprint.sh +1 -500
  66. package/scripts/workflow-contract.ts +4 -201
  67. package/scripts/workstream-sync.sh +2 -261
  68. package/src/cli/agent-jobs/executor-health.ts +1 -1
  69. package/src/cli/commands/plugin.ts +12 -3
  70. package/src/cli/controller/check-runner.ts +7 -2
  71. package/src/cli/controller/context-pack.ts +46 -21
  72. package/src/cli/github/contracts.ts +16 -0
  73. package/src/cli/github/github.ts +2 -16
  74. package/src/cli/github/session.ts +2 -1
  75. package/src/cli/local-bridge/facade-api.ts +37 -47
  76. package/src/cli/local-bridge/server.ts +2 -2
  77. package/src/cli/mcp/legacy-tool-service.ts +10 -33
  78. package/src/cli/mcp/post-finalize-work-attribution.ts +150 -0
  79. package/src/cli/mcp/repository-tools.ts +85 -89
  80. package/src/cli/mcp/server.ts +57 -13
  81. package/src/cli/mcp/tool-contract.ts +14 -0
  82. package/src/cli/mcp/toolset.ts +2 -2
  83. package/src/cli/mcp/transports/http.ts +23 -0
  84. package/src/cli/repositories/command-classifier.ts +2 -2
  85. package/src/cli/repositories/command-executor.ts +24 -6
  86. package/src/cli/repositories/repository-snapshot.ts +5 -2
  87. package/src/cli/repositories/structured-git.ts +57 -3
  88. package/src/cli/repository/inspector.ts +11 -3
  89. package/src/runtime/context/generic-lsp-provider.ts +1 -1
  90. package/src/runtime/context/semantic-navigation-contract.ts +61 -0
  91. package/src/runtime/context/semantic-navigation.ts +9 -61
  92. package/src/runtime/control-plane/execution/direct-edit-work-completion.ts +18 -25
  93. package/src/runtime/control-plane/execution/repository-work-attribution.ts +106 -0
  94. package/src/runtime/control-plane/execution/retained-work-resume.ts +203 -0
  95. package/src/runtime/control-plane/execution/work-completion-authority.ts +58 -0
  96. package/src/runtime/control-plane/execution/work-evidence-policy.ts +200 -0
  97. package/src/runtime/control-plane/execution/work-execution-support.ts +386 -0
  98. package/src/runtime/control-plane/execution/work-finalization-service.ts +1913 -0
  99. package/src/runtime/control-plane/execution/work-handle-authority.ts +96 -0
  100. package/src/runtime/control-plane/execution/work-handle-store.ts +1 -1
  101. package/src/runtime/control-plane/execution/work-operation-service.ts +468 -0
  102. package/src/runtime/control-plane/execution/work-path-scope.ts +37 -0
  103. package/src/runtime/control-plane/execution/work-preparation-service.ts +479 -0
  104. package/src/runtime/control-plane/execution/work-process-evidence.ts +129 -0
  105. package/src/runtime/control-plane/execution/work-task-receipt.ts +4 -43
  106. package/src/runtime/control-plane/execution/work-terminal-cleanup.ts +13 -3
  107. package/src/runtime/control-plane/execution/work-verification-context.ts +56 -0
  108. package/src/runtime/control-plane/execution/work-verification-service.ts +388 -0
  109. package/src/runtime/control-plane/execution/work-verification-snapshot.ts +5 -1
  110. package/src/runtime/control-plane/facade/controller-round-relay.ts +164 -37
  111. package/src/runtime/control-plane/facade/controller-session-store.ts +183 -24
  112. package/src/runtime/control-plane/facade/goal-workloop-access.ts +15 -1
  113. package/src/runtime/control-plane/facade/goal-workloop.ts +329 -148
  114. package/src/runtime/control-plane/facade/index.ts +2 -0
  115. package/src/runtime/control-plane/facade/plan-contract-store.ts +90 -22
  116. package/src/runtime/control-plane/facade/repository-work-admission.ts +147 -0
  117. package/src/runtime/control-plane/facade/requirement-authority.ts +83 -0
  118. package/src/runtime/control-plane/facade/types.ts +68 -5
  119. package/src/runtime/control-plane/facade/work-contract-store.ts +3 -209
  120. package/src/runtime/control-plane/facade/work-state-machine.ts +250 -0
  121. package/src/runtime/control-plane/global-scheduler/maintenance.ts +14 -7
  122. package/src/runtime/control-plane/global-scheduler/scheduler.ts +5 -1
  123. package/src/runtime/control-plane/launcher/chatgpt-work-binding-store.ts +13 -0
  124. package/src/runtime/control-plane/launcher/chatgpt-work-continuation.ts +15 -6
  125. package/src/runtime/control-plane/launcher/launch-reservation-store.ts +54 -5
  126. package/src/runtime/control-plane/launcher/thin-launcher.ts +56 -7
  127. package/src/runtime/control-plane/persistence/requirement-store.ts +0 -12
  128. package/src/runtime/control-plane/repo-actor/registry.ts +4 -2
  129. package/src/runtime/control-plane/routing/route-policy.ts +18 -6
  130. package/src/runtime/control-plane/routing/workspace-admission.ts +70 -0
  131. package/src/runtime/evidence/process-check-execution.ts +18 -0
  132. package/src/runtime/execution/jobs/child-reference.ts +6 -2
  133. package/src/runtime/execution/process-runtime/check-result.ts +53 -18
  134. package/src/runtime/execution/process-runtime/check-runner-sidecar.ts +7 -1
  135. package/src/runtime/execution/process-runtime/command-facade.ts +39 -17
  136. package/src/runtime/execution/process-runtime/lightweight-managed.ts +20 -3
  137. package/src/runtime/execution/process-runtime/persisted-check.ts +4 -1
  138. package/src/runtime/execution/process-runtime/runtime.ts +10 -0
  139. package/src/runtime/execution/process-runtime/types.ts +2 -12
  140. package/src/runtime/execution/work-activity.ts +21 -0
  141. package/src/runtime/execution/workers/executor.ts +18 -13
  142. package/src/runtime/gateway/mcp/execution-tools.ts +35 -2930
  143. package/src/runtime/gateway/mcp/legacy-ios-tool-adapter.ts +61 -0
  144. package/src/runtime/gateway/mcp/router.ts +2 -2
  145. package/src/runtime/gateway/mcp/runtime-tool-definitions.ts +21 -2
  146. package/src/runtime/gateway/mcp/runtime-tools.ts +805 -1009
  147. package/src/runtime/plugins/app-store-connect-adapter.ts +93 -28
  148. package/src/runtime/plugins/browser-adapter.ts +256 -1083
  149. package/src/runtime/plugins/browser-handoff-host.ts +2 -25
  150. package/src/runtime/plugins/browser-handoff.ts +18 -3
  151. package/src/runtime/plugins/browser-macos-bridge.ts +121 -16
  152. package/src/runtime/plugins/browser-manifest-surface.ts +603 -0
  153. package/src/runtime/plugins/browser-native-session-service.ts +222 -0
  154. package/src/runtime/plugins/browser-runtime-contract.ts +2 -0
  155. package/src/runtime/plugins/browser-runtime.ts +10 -0
  156. package/src/runtime/plugins/browser-session-store.ts +121 -0
  157. package/src/runtime/plugins/browser-session-types.ts +98 -0
  158. package/src/runtime/plugins/desktop-operator-registration.ts +4 -4
  159. package/src/runtime/plugins/external-adapter.ts +92 -58
  160. package/src/runtime/plugins/macos-capability-broker.ts +0 -8
  161. package/src/runtime/plugins/store.ts +66 -9
  162. package/src/runtime/plugins/types.ts +3 -1
  163. package/src/runtime/recovery/maintenance-executor.ts +61 -25
  164. package/src/runtime/root/package-connector-service.ts +46 -4
  165. package/src/runtime/root/package-runtime-release.ts +1 -1
  166. package/src/runtime/root/package-runtime-service.ts +33 -2
  167. package/src/runtime/root/release-manifest.ts +137 -16
  168. package/src/runtime/root/release-materialize.ts +109 -35
  169. package/src/runtime/root/types.ts +10 -0
  170. package/src/runtime/standalone-recovery/core.ts +425 -194
  171. package/src/runtime/standalone-recovery/entry.ts +1 -1
  172. package/src/runtime/standalone-recovery/installer.ts +1 -1
  173. package/src/runtime/workflow/schedules/engine.ts +113 -87
  174. package/src/runtime/workflow/schedules/settlement.ts +26 -23
  175. package/src/runtime/workflow/schedules/store.ts +79 -10
@@ -0,0 +1,386 @@
1
+ import type { MultiRepositoryMcpToolContext } from '../../../cli/mcp/multi-repository';
2
+ import { getRepository, listRepositories, selectRepositoryCheckout } from '../../../cli/repositories/registry';
3
+ import { reconcileWorkValidation } from './work-validation-reconciler';
4
+ import { assertControllerOwnershipAuthority, claimControllerSession, controllerSessionPrincipalId, getControllerSession, releaseControllerSessionWithAuthority, resumeControllerSession } from '../facade/controller-session-store';
5
+ import { appendWorkEvidence, getWorkContract } from '../facade/work-contract-store';
6
+ import { resolveLegacyWorkContractIdentity } from './execution-identity';
7
+ import type { ExecutionSessionContext, SessionIdentity } from './session-store';
8
+ import { currentControllerInstanceId, requireExecutionSession, updateExecutionSession } from './session-store';
9
+ import type { WorkHandleState, WorkTerminalOutcome } from './work-handle-store';
10
+ import { readWorkHandle, writeWorkHandle } from './work-handle-store';
11
+ import { cleanupTerminalWork } from './work-terminal-cleanup';
12
+ import { spawnSync } from 'child_process';
13
+ import { writeControllerResult } from '../../evidence/result-store';
14
+
15
+
16
+ const MAX_INLINE_RESULT_BYTES = 64 * 1024;
17
+
18
+ export function makeBoundedWorkResult(ctx: MultiRepositoryMcpToolContext, session: ExecutionSessionContext, repoId: string, workIdValue: string | undefined, kind: 'inspection' | 'command' | 'validation' | 'finalization' | 'generic', value: Record<string, unknown>): Record<string, unknown> {
19
+ const serialized = JSON.stringify(value);
20
+ if (Buffer.byteLength(serialized, 'utf8') <= MAX_INLINE_RESULT_BYTES) return value;
21
+ const started = performance.now();
22
+ const stored = writeControllerResult({ controllerHome: ctx.controllerHome, repoId, sessionId: session.sessionId, principalId: session.principalId, workId: workIdValue, kind, value });
23
+ return {
24
+ summary: { itemCount: Array.isArray(value.items) ? value.items.length : undefined, truncated: true, warnings: ['Full result is available through the secure result reference.'] },
25
+ items: Array.isArray(value.items) ? value.items.slice(0, 25) : { preview: serialized.slice(0, 16_384) },
26
+ resultRef: stored.resultRef,
27
+ resultId: stored.resultId,
28
+ byteLength: stored.byteLength,
29
+ _resultPersistenceMs: Math.round((performance.now() - started) * 100) / 100,
30
+ };
31
+ }
32
+
33
+ export function principalFor(ctx: MultiRepositoryMcpToolContext): string {
34
+ return ctx.principalId?.trim() || `controller-issued:${ctx.controllerInstanceId ?? currentControllerInstanceId()}`;
35
+ }
36
+
37
+ export function identityFor(ctx: MultiRepositoryMcpToolContext, args: Record<string, unknown>): SessionIdentity {
38
+ return {
39
+ sessionId: typeof args.session_id === 'string' && args.session_id.trim() ? args.session_id.trim() : ctx.sessionId,
40
+ principalId: principalFor(ctx),
41
+ controllerInstanceId: ctx.controllerInstanceId ?? currentControllerInstanceId(),
42
+ };
43
+ }
44
+
45
+ export function requireSession(ctx: MultiRepositoryMcpToolContext, args: Record<string, unknown>): ExecutionSessionContext {
46
+ return requireExecutionSession(ctx.controllerHome, identityFor(ctx, args));
47
+ }
48
+
49
+ export function compactHandle(handle: WorkHandleState): Record<string, unknown> {
50
+ return {
51
+ workId: handle.workId, sessionId: handle.sessionId, repoId: handle.repositoryId, checkoutId: handle.checkoutId,
52
+ worktreePath: handle.worktreePath, branch: handle.branch, sourceCheckoutId: handle.sourceCheckoutId, goalId: handle.goalId, delegationVersion: handle.delegationVersion,
53
+ workContractId: handle.workContractId, baseCommit: handle.baseCommit, deliveryBaseCommit: handle.deliveryBaseCommit, expectedHead: handle.expectedHead,
54
+ permissionSnapshotVersion: handle.permissionSnapshotVersion, state: handle.state, managedWorktree: handle.managedWorktree,
55
+ createdAt: handle.createdAt, updatedAt: handle.updatedAt, finalization: handle.finalization,
56
+ ...(handle.failureReason ? { failureReason: handle.failureReason } : {}),
57
+ ...(handle.cleanupResponsibility ? { cleanupResponsibility: handle.cleanupResponsibility } : {}),
58
+ ...(handle.terminalResourceDisposition ? { terminalResourceDisposition: handle.terminalResourceDisposition } : {}),
59
+ ...(handle.cleanupReceipt ? { cleanupReceipt: handle.cleanupReceipt } : {}),
60
+ };
61
+ }
62
+
63
+ export function gitRevision(root: string, revision: string): string | undefined {
64
+ const output = spawnSync('git', ['-C', root, 'rev-parse', '--verify', `${revision}^{commit}`], { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 10_000 });
65
+ return output.status === 0 && typeof output.stdout === 'string' && output.stdout.trim() ? output.stdout.trim() : undefined;
66
+ }
67
+
68
+ export function gitHead(root: string): string | undefined {
69
+ return gitRevision(root, 'HEAD');
70
+ }
71
+
72
+ export function gitCommit(root: string, revision: string, label: string): string {
73
+ const output = spawnSync('git', ['-C', root, 'rev-parse', '--verify', `${revision}^{commit}`], {
74
+ encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 10_000,
75
+ });
76
+ if (output.status !== 0 || output.error || typeof output.stdout !== 'string' || !output.stdout.trim()) {
77
+ throw new Error(`WORK_HEAD_ADOPTION_${label}_INVALID: ${revision}`);
78
+ }
79
+ return output.stdout.trim();
80
+ }
81
+
82
+ export function gitChangedPaths(root: string, previousHead: string, candidateHead: string): string[] {
83
+ const output = spawnSync('git', ['-C', root, 'diff', '--name-only', '-z', previousHead, candidateHead], {
84
+ encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 10_000, maxBuffer: 8 * 1024 * 1024,
85
+ });
86
+ if (output.status !== 0 || output.error || typeof output.stdout !== 'string') {
87
+ throw new Error('WORK_HEAD_ADOPTION_CHANGED_PATHS_UNAVAILABLE');
88
+ }
89
+ return [...new Set(output.stdout.split('\0').filter(Boolean))].sort((left, right) => left.localeCompare(right));
90
+ }
91
+
92
+ export function gitMergeBase(root: string, leftHead: string, rightHead: string): string {
93
+ const output = spawnSync('git', ['-C', root, 'merge-base', leftHead, rightHead], {
94
+ encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 10_000,
95
+ });
96
+ if (output.status !== 0 || output.error || typeof output.stdout !== 'string' || !output.stdout.trim()) {
97
+ throw new Error('WORK_HEAD_ADOPTION_SCOPE_BASE_UNAVAILABLE');
98
+ }
99
+ return output.stdout.trim();
100
+ }
101
+
102
+ export function selectWorkFinalizationTarget(
103
+ repository: ReturnType<typeof getRepository>,
104
+ handle: Pick<WorkHandleState, 'sourceCheckoutId' | 'checkoutId'>,
105
+ ) {
106
+ const preferredCheckoutId = handle.sourceCheckoutId?.trim();
107
+ if (preferredCheckoutId) {
108
+ try {
109
+ return selectRepositoryCheckout(repository, preferredCheckoutId, { allowArchived: true });
110
+ } catch (error) {
111
+ const message = error instanceof Error ? error.message : String(error);
112
+ // Legacy Work can outlive the registry entry for the source checkout after
113
+ // an earlier partial cleanup. Git refs/worktree administration are
114
+ // repository-common operations, so fall back only for a positively
115
+ // identified missing/removed source checkout; all other errors fail closed.
116
+ if (!message.startsWith('CHECKOUT_NOT_ACTIVE:') && !message.startsWith('checkout not found for ')) throw error;
117
+ }
118
+ }
119
+ return repository;
120
+ }
121
+
122
+ export function workReturnCheckoutId(
123
+ ctx: MultiRepositoryMcpToolContext,
124
+ handle: Pick<WorkHandleState, 'repositoryId' | 'sourceCheckoutId' | 'checkoutId'>,
125
+ fallbackCheckoutId?: string,
126
+ ): string | undefined {
127
+ const repository = getRepository(handle.repositoryId, ctx.controllerHome, { includeRemoved: true });
128
+ const target = selectWorkFinalizationTarget(repository, handle);
129
+ return target.activeCheckoutId ?? repository.activeCheckoutId ?? fallbackCheckoutId;
130
+ }
131
+
132
+ export function contractFor(ctx: MultiRepositoryMcpToolContext, handle: WorkHandleState) {
133
+ // WorkContract is the semantic lifecycle authority. Legacy WorkHandles can
134
+ // predate the explicit workContractId binding, but their exact workId is the
135
+ // same stable authority key inside the same repository. Falling back only to
136
+ // that exact id keeps cleanup fail-closed without inventing a second lookup or
137
+ // fuzzy ownership rule.
138
+ const workContractId = handle.workContractId?.trim() || handle.workId;
139
+ return getWorkContract({ controllerHome: ctx.controllerHome, repoId: handle.repositoryId }, workContractId);
140
+ }
141
+
142
+ export function findWorkHandle(
143
+ ctx: MultiRepositoryMcpToolContext,
144
+ session: ExecutionSessionContext,
145
+ args: Record<string, unknown>,
146
+ ): WorkHandleState {
147
+ const requested = typeof args.work_id === 'string' ? args.work_id.trim() : '';
148
+ const workIdValue = requested || session.activeWorkId || '';
149
+ if (!workIdValue) throw new Error('WORK_ID_REQUIRED: provide work_id or call work_prepare first');
150
+ const requestedRepoId = typeof args.repo_id === 'string' && args.repo_id.trim() ? args.repo_id.trim() : undefined;
151
+ const requestedCheckoutId = typeof args.checkout_id === 'string' && args.checkout_id.trim()
152
+ ? args.checkout_id.trim()
153
+ : undefined;
154
+ const repoCandidates = [
155
+ requestedRepoId,
156
+ session.activeRepositoryId,
157
+ ].filter((value, index, values): value is string => Boolean(value) && values.indexOf(value) === index);
158
+ for (const repositoryId of repoCandidates) {
159
+ const handle = readWorkHandle(ctx.controllerHome, repositoryId, workIdValue);
160
+ if (!handle) continue;
161
+ if (requestedCheckoutId && handle.checkoutId !== requestedCheckoutId) {
162
+ throw new Error(
163
+ `WORK_HANDLE_CHECKOUT_DRIFT: work ${workIdValue} is bound to checkout ${handle.checkoutId}, not ${requestedCheckoutId}`,
164
+ );
165
+ }
166
+ return handle;
167
+ }
168
+ const matches = listRepositories(ctx.controllerHome, { includeRemoved: true })
169
+ .map((repository) => readWorkHandle(ctx.controllerHome, repository.repoId, workIdValue))
170
+ .filter((handle): handle is WorkHandleState => Boolean(handle));
171
+ // Legacy incomplete identity: only a unique exact WorkHandle match may execute.
172
+ return resolveLegacyWorkContractIdentity({
173
+ workId: workIdValue,
174
+ repoId: requestedRepoId,
175
+ checkoutId: requestedCheckoutId,
176
+ candidates: matches,
177
+ });
178
+ }
179
+
180
+ function currentControllerClaimAuthorizesTerminalCleanup(
181
+ ctx: MultiRepositoryMcpToolContext,
182
+ session: ExecutionSessionContext,
183
+ handle: WorkHandleState,
184
+ ): boolean {
185
+ if (!terminalCleanupOutcome(ctx, handle)) return false;
186
+ const workIdValue = handle.workContractId ?? handle.workId;
187
+ const owner = getControllerSession({ controllerHome: ctx.controllerHome, repoId: handle.repositoryId }, workIdValue);
188
+ if (!owner) return false;
189
+ return controllerSessionPrincipalId(owner) === session.principalId
190
+ && owner.controllerInstanceId === session.controllerInstanceId;
191
+ }
192
+
193
+ export function workForSession(
194
+ ctx: MultiRepositoryMcpToolContext,
195
+ session: ExecutionSessionContext,
196
+ args: Record<string, unknown>,
197
+ options: { reconcileValidation?: boolean; allowClaimedTerminalCleanup?: boolean } = {},
198
+ ): WorkHandleState {
199
+ let handle = findWorkHandle(ctx, session, args);
200
+ if (
201
+ handle.principalId !== session.principalId
202
+ && !(options.allowClaimedTerminalCleanup === true && currentControllerClaimAuthorizesTerminalCleanup(ctx, session, handle))
203
+ ) throw new Error('WORK_HANDLE_PRINCIPAL_MISMATCH: work handle belongs to another principal');
204
+ if (options.reconcileValidation !== false) handle = reconcileWorkValidation(ctx.controllerHome, handle).handle;
205
+ if (
206
+ session.activeRepositoryId !== handle.repositoryId
207
+ || session.activeCheckoutId !== handle.checkoutId
208
+ || session.activeWorkId !== handle.workId
209
+ ) {
210
+ updateExecutionSession(ctx.controllerHome, identityFor(ctx, args), {
211
+ activeRepositoryId: handle.repositoryId,
212
+ activeCheckoutId: handle.checkoutId,
213
+ activeWorkId: handle.workId,
214
+ permissionSnapshotVersion: handle.permissionSnapshotVersion,
215
+ lastValidatedAt: new Date().toISOString(),
216
+ });
217
+ }
218
+ return handle;
219
+ }
220
+
221
+ export function assertWorkControllerOwnership(
222
+ ctx: MultiRepositoryMcpToolContext,
223
+ session: ExecutionSessionContext,
224
+ handle: WorkHandleState,
225
+ args: Record<string, unknown>,
226
+ ) {
227
+ const workIdValue = handle.workContractId ?? handle.workId;
228
+ const options = { controllerHome: ctx.controllerHome, repoId: handle.repositoryId };
229
+ const owner = getControllerSession(options, workIdValue);
230
+ const controllerId = typeof args.controller_id === 'string' && args.controller_id.trim()
231
+ ? args.controller_id.trim()
232
+ : session.principalId;
233
+ if (controllerId !== session.principalId) {
234
+ throw new Error('WORK_CONTROLLER_IDENTITY_MISMATCH: controller_id must match the authenticated principal');
235
+ }
236
+ if (owner) {
237
+ const authority = assertControllerOwnershipAuthority(owner, {
238
+ workId: workIdValue,
239
+ controllerId,
240
+ principalId: session.principalId,
241
+ controllerInstanceId: session.controllerInstanceId,
242
+ });
243
+ const resumed = resumeControllerSession(options, {
244
+ workId: workIdValue,
245
+ controllerId,
246
+ controllerType: authority.controllerType,
247
+ sessionId: session.sessionId,
248
+ principalId: session.principalId,
249
+ controllerInstanceId: session.controllerInstanceId,
250
+ expectedClaimGeneration: authority.claimGeneration,
251
+ leaseMs: 3_600_000,
252
+ });
253
+ if (
254
+ resumed.controllerId !== authority.controllerId
255
+ || controllerSessionPrincipalId(resumed) !== authority.principalId
256
+ || resumed.controllerInstanceId !== authority.controllerInstanceId
257
+ || resumed.claimGeneration !== authority.claimGeneration
258
+ ) {
259
+ throw new Error(`WORK_CONTROLLER_OWNER_MISMATCH: ${workIdValue} ownership epoch changed during resume`);
260
+ }
261
+ return resumed;
262
+ }
263
+ return claimControllerSession(options, {
264
+ workId: workIdValue,
265
+ controllerId,
266
+ controllerType: 'chatgpt',
267
+ sessionId: session.sessionId,
268
+ principalId: session.principalId,
269
+ controllerInstanceId: session.controllerInstanceId,
270
+ expectedClaimGeneration: 0,
271
+ leaseMs: 3_600_000,
272
+ });
273
+ }
274
+
275
+ export function releasePreparedWorkOwnership(
276
+ ctx: MultiRepositoryMcpToolContext,
277
+ handle: WorkHandleState,
278
+ ): 'released' | 'already_released' {
279
+ const workIdValue = handle.workContractId ?? handle.workId;
280
+ const options = { controllerHome: ctx.controllerHome, repoId: handle.repositoryId };
281
+ const current = getControllerSession(options, workIdValue);
282
+ if (!current) return 'already_released';
283
+
284
+ const callerPrincipal = principalFor(ctx);
285
+ const callerInstanceId = ctx.controllerInstanceId ?? currentControllerInstanceId();
286
+ const ownerPrincipal = current.principalId?.trim() || current.controllerId;
287
+ const ownerInstanceId = current.controllerInstanceId?.trim() || '';
288
+ if (ownerPrincipal !== callerPrincipal) {
289
+ throw new Error(`WORK_CONTROLLER_PRINCIPAL_MISMATCH: ${workIdValue}`);
290
+ }
291
+ if (!ownerInstanceId || ownerInstanceId !== callerInstanceId) {
292
+ throw new Error(`WORK_CONTROLLER_INSTANCE_MISMATCH: ${workIdValue}`);
293
+ }
294
+ if (typeof current.claimGeneration !== 'number' || current.claimGeneration < 1) {
295
+ throw new Error(`WORK_CONTROLLER_CLAIM_GENERATION_REQUIRED: ${workIdValue}`);
296
+ }
297
+
298
+ const released = releaseControllerSessionWithAuthority(options, {
299
+ workId: workIdValue,
300
+ actor: `legacy-work-release:${callerPrincipal}:${callerInstanceId}`,
301
+ authority: {
302
+ controllerId: current.controllerId,
303
+ controllerType: current.controllerType,
304
+ principalId: ownerPrincipal,
305
+ controllerInstanceId: ownerInstanceId,
306
+ claimGeneration: current.claimGeneration,
307
+ },
308
+ });
309
+ if (!released.allowed) {
310
+ throw new Error(`WORK_CONTROLLER_RELEASE_FENCED: ${workIdValue}:${released.reason}`);
311
+ }
312
+ return 'released';
313
+ }
314
+
315
+ export function terminalCleanupOutcome(
316
+ ctx: MultiRepositoryMcpToolContext,
317
+ handle: WorkHandleState,
318
+ ): WorkTerminalOutcome | undefined {
319
+ if (handle.cleanupReceipt) return handle.cleanupReceipt.terminalOutcome;
320
+ const contract = contractFor(ctx, handle);
321
+ if (contract?.status === 'cancelled') return 'cancelled';
322
+ if (contract?.status === 'completed') return 'completed_cleanup';
323
+ const reason = `${handle.failureReason ?? ''} ${handle.finalization.lastError ?? ''}`.toLowerCase();
324
+ if (contract?.status === 'blocked' && reason.includes('terminal')) return 'blocked_terminal';
325
+ // `failed` is a retryable execution-handle state (its transition table allows
326
+ // failed -> validating/editing). Do not reinterpret it as terminal cleanup
327
+ // unless the durable Work itself is terminal. `failed_terminal_cleanup` is
328
+ // the explicit point of no return for resource cleanup reconciliation.
329
+ if (contract?.status === 'failed' || handle.state === 'failed_terminal_cleanup') {
330
+ if (reason.includes('infrastructure') || reason.includes('timed out') || reason.includes('unavailable')) {
331
+ return 'infrastructure_failed';
332
+ }
333
+ if (handle.finalization.validation === 'failed') return 'validation_failed';
334
+ return 'failed';
335
+ }
336
+ return undefined;
337
+ }
338
+
339
+ export async function reconcileTerminalCleanup(
340
+ ctx: MultiRepositoryMcpToolContext,
341
+ session: ExecutionSessionContext,
342
+ handle: WorkHandleState,
343
+ args: Record<string, unknown>,
344
+ outcome: WorkTerminalOutcome,
345
+ ): Promise<Record<string, unknown>> {
346
+ const wasComplete = handle.cleanupReceipt?.complete === true;
347
+ const cleaned = await cleanupTerminalWork({
348
+ controllerHome: ctx.controllerHome,
349
+ handle,
350
+ targetBranch: typeof args.target_branch === 'string' ? args.target_branch : undefined,
351
+ deleteBranch: args.delete_branch !== false,
352
+ terminalOutcome: outcome,
353
+ failureReason: handle.failureReason ?? handle.finalization.lastError,
354
+ });
355
+ const ownership = releasePreparedWorkOwnership(ctx, cleaned.handle);
356
+ cleaned.receipt.ownership.controllerLease = ownership;
357
+ const persisted = writeWorkHandle(ctx.controllerHome, {
358
+ ...cleaned.handle,
359
+ cleanupReceipt: cleaned.receipt,
360
+ });
361
+ updateExecutionSession(ctx.controllerHome, identityFor(ctx, args), {
362
+ activeWorkId: undefined,
363
+ activeCheckoutId: workReturnCheckoutId(ctx, persisted, session.activeCheckoutId),
364
+ });
365
+ if (cleaned.receipt.complete && !wasComplete) {
366
+ appendWorkEvidence(
367
+ { controllerHome: ctx.controllerHome, repoId: persisted.repositoryId },
368
+ persisted.workContractId ?? persisted.workId,
369
+ {
370
+ title: 'terminal cleanup receipt',
371
+ summary: `Cleanup ${cleaned.receipt.receiptId} completed for ${outcome}; Work outcome was preserved and no completion receipt was fabricated.`,
372
+ detailLevel: 'summary',
373
+ },
374
+ );
375
+ }
376
+ return {
377
+ work: compactHandle(persisted),
378
+ stages: persisted.finalization,
379
+ completed: false,
380
+ cleanupCompleted: cleaned.receipt.complete,
381
+ cleanupPartial: cleaned.receipt.partial,
382
+ failurePreserved: true,
383
+ cleanupReceipt: cleaned.receipt,
384
+ idempotent: wasComplete,
385
+ };
386
+ }