@moretea-labs/forge 1.5.1 → 1.6.0

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 (124) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/DESIGN.md +7 -2
  3. package/README.md +4 -4
  4. package/README.zh-CN.md +2 -2
  5. package/THIRD_PARTY_NOTICES.md +1 -1
  6. package/assets/hooks/pre-edit-guard.sh +8 -39
  7. package/assets/hooks/prompt-guard.sh +2 -2
  8. package/assets/plugin-registry.v1.json +54 -3
  9. package/assets/reference-configs/hook-operations.md +1 -1
  10. package/assets/reference-configs/sprint-contracts.md +2 -2
  11. package/assets/skill-version.json +2 -2
  12. package/assets/templates/helpers/ensure-task-workflow.sh +2 -2
  13. package/assets/templates/helpers/sprint-backlog.sh +6 -6
  14. package/docs/architecture/current/automation-and-schedule-engine.md +9 -3
  15. package/docs/architecture/current/codegraph-context-provider.md +15 -3
  16. package/docs/architecture/current/dispatch-and-agent-strategy.md +32 -13
  17. package/docs/architecture/current/entity-model.md +20 -0
  18. package/docs/architecture/current/external-plugin-governance.md +3 -3
  19. package/docs/architecture/current/system-overview.md +26 -1
  20. package/docs/architecture/current/thin-harness-v1.md +10 -0
  21. package/docs/operations/chatgpt-personal-assistant-runtime.md +12 -2
  22. package/docs/operations/controller-browser-plugin.md +12 -16
  23. package/docs/operations/features.md +1 -1
  24. package/docs/operations/homebrew.md +2 -2
  25. package/docs/tutorials/01-install-and-start.md +1 -1
  26. package/docs/tutorials/01-install-and-start.zh-CN.md +1 -1
  27. package/docs/wiki/Installation.md +1 -1
  28. package/docs/wiki/Quick-Start.md +1 -1
  29. package/package.json +1 -1
  30. package/scripts/check-public-docs.sh +14 -1
  31. package/scripts/migrate-chatgpt-automation-schedules.ts +64 -0
  32. package/scripts/sprint-backlog.sh +1 -1
  33. package/src/cli/commands/chatgpt.ts +31 -2
  34. package/src/cli/commands/plugin.ts +36 -9
  35. package/src/cli/controller/context-pack.ts +158 -6
  36. package/src/cli/hook/prompt-guard-decision.ts +17 -18
  37. package/src/cli/hook/prompt-intents.ts +1 -1
  38. package/src/cli/local-bridge/console-automations.ts +205 -23
  39. package/src/cli/local-bridge/console-view-models.ts +2 -0
  40. package/src/cli/local-bridge/facade-api.ts +2 -0
  41. package/src/cli/local-bridge/frontend/src/App.tsx +1 -1
  42. package/src/cli/local-bridge/frontend/src/features/automations/AutomationsView.tsx +143 -3
  43. package/src/cli/local-bridge/frontend/src/features/capabilities/CapabilitiesView.tsx +1 -1
  44. package/src/cli/local-bridge/frontend/src/features/overview/OverviewView.tsx +181 -3
  45. package/src/cli/local-bridge/frontend/src/features/repositories/RepositoriesView.tsx +1 -1
  46. package/src/cli/local-bridge/frontend/src/features/work/WorkView.tsx +4 -3
  47. package/src/cli/local-bridge/frontend/src/lib/api.ts +18 -6
  48. package/src/cli/local-bridge/frontend/src/shell/CommandBar.tsx +1 -1
  49. package/src/cli/local-bridge/frontend/src/shell/Sidebar.tsx +2 -1
  50. package/src/cli/local-bridge/frontend/src/styles.css +27 -11
  51. package/src/cli/local-bridge/frontend/src/types.ts +6 -2
  52. package/src/cli/local-bridge/server.ts +29 -19
  53. package/src/cli/local-bridge/ui-dist/app.css +1 -1
  54. package/src/cli/local-bridge/ui-dist/app.js +5003 -4815
  55. package/src/cli/mcp/paths.ts +8 -2
  56. package/src/cli/mcp/repository-tools.ts +124 -9
  57. package/src/cli/mcp/server.ts +164 -19
  58. package/src/cli/mcp/transports/http.ts +25 -2
  59. package/src/cli/mcp/transports/session-registry.ts +24 -0
  60. package/src/cli/repositories/command-classifier.ts +113 -0
  61. package/src/cli/repositories/safe-patch.ts +6 -4
  62. package/src/cli/repositories/structured-git.ts +49 -7
  63. package/src/cli/repository/inspector.ts +16 -3
  64. package/src/runtime/assistant/intent.ts +3 -3
  65. package/src/runtime/control-plane/execution/direct-edit-work-completion.ts +157 -2
  66. package/src/runtime/control-plane/execution/execution-identity.ts +65 -14
  67. package/src/runtime/control-plane/execution/validation.ts +15 -2
  68. package/src/runtime/control-plane/execution/work-terminal-cleanup.ts +32 -0
  69. package/src/runtime/control-plane/execution/work-validation-reconciler.ts +6 -7
  70. package/src/runtime/control-plane/execution/work-verification-snapshot.ts +2 -1
  71. package/src/runtime/control-plane/facade/capability-registry.ts +1 -1
  72. package/src/runtime/control-plane/facade/controller-session-store.ts +12 -13
  73. package/src/runtime/control-plane/facade/goal-workloop-access.ts +7 -2
  74. package/src/runtime/control-plane/facade/goal-workloop.ts +231 -8
  75. package/src/runtime/control-plane/facade/plan-contract-store.ts +32 -12
  76. package/src/runtime/control-plane/facade/requirement-board.ts +24 -8
  77. package/src/runtime/control-plane/facade/types.ts +33 -6
  78. package/src/runtime/control-plane/facade/work-contract-store.ts +31 -2
  79. package/src/runtime/control-plane/launcher/chatgpt-work-continuation.ts +375 -23
  80. package/src/runtime/control-plane/persistence/requirement-store.ts +15 -11
  81. package/src/runtime/diagnostics/mcp-timing.ts +6 -0
  82. package/src/runtime/execution/process-runtime/check-facade.ts +1 -10
  83. package/src/runtime/execution/process-runtime/check-result.ts +10 -2
  84. package/src/runtime/execution/process-runtime/command-facade.ts +1 -0
  85. package/src/runtime/execution/process-runtime/gc.ts +64 -10
  86. package/src/runtime/execution/process-runtime/persisted-check.ts +10 -2
  87. package/src/runtime/execution/process-runtime/resource-claims.ts +87 -2
  88. package/src/runtime/execution/process-runtime/runtime.ts +16 -1
  89. package/src/runtime/execution/process-runtime/store.ts +6 -0
  90. package/src/runtime/gateway/mcp/execution-tools.ts +27 -12
  91. package/src/runtime/gateway/mcp/router.ts +1 -1
  92. package/src/runtime/gateway/mcp/runtime-tools.ts +482 -178
  93. package/src/runtime/model-clients/deepseek-adapter.ts +0 -32
  94. package/src/runtime/plugins/browser-adapter.ts +19 -72
  95. package/src/runtime/plugins/browser-handoff-host.ts +6 -31
  96. package/src/runtime/plugins/browser-handoff.ts +0 -3
  97. package/src/runtime/plugins/browser-macos-bridge.ts +8 -0
  98. package/src/runtime/plugins/desktop-operator-registration.ts +8 -11
  99. package/src/runtime/plugins/external-registration.ts +84 -5
  100. package/src/runtime/plugins/first-party-registry.ts +2 -2
  101. package/src/runtime/plugins/gmail-adapter.ts +28 -2
  102. package/src/runtime/plugins/local-system-adapter.ts +2 -2
  103. package/src/runtime/plugins/plugin-management-adapter.ts +140 -0
  104. package/src/runtime/plugins/store.ts +107 -5
  105. package/src/runtime/plugins/types.ts +4 -0
  106. package/src/runtime/recovery/actions.ts +0 -10
  107. package/src/runtime/recovery/classifier.ts +0 -9
  108. package/src/runtime/recovery/maintenance-executor.ts +43 -11
  109. package/src/runtime/recovery/probe.ts +0 -1
  110. package/src/runtime/recovery/types.ts +0 -1
  111. package/src/runtime/root/release-materialize.ts +143 -19
  112. package/src/runtime/root/service.ts +6 -4
  113. package/src/runtime/safe-tooling/index.ts +0 -1
  114. package/src/runtime/safe-tooling/types.ts +0 -30
  115. package/src/runtime/standalone-recovery/core.ts +2 -2
  116. package/src/runtime/workflow/schedules/browser-probe.ts +180 -0
  117. package/src/runtime/workflow/schedules/chatgpt-automation-migration.ts +40 -0
  118. package/src/runtime/workflow/schedules/engine.ts +357 -64
  119. package/src/runtime/workflow/schedules/types.ts +5 -0
  120. package/src/runtime/workflow/schedules/work-continuation.ts +100 -27
  121. package/bin/forge-desktop-helper.mjs +0 -204
  122. package/docs/operations/controller-desktop-plugin.md +0 -112
  123. package/src/runtime/plugins/desktop-adapter.ts +0 -374
  124. package/src/runtime/safe-tooling/browser-safe.ts +0 -133
@@ -80,6 +80,77 @@ function shellSegments(command: string): string[] {
80
80
  return segments;
81
81
  }
82
82
 
83
+ function shellWordsPreservingQuotes(segment: string): string[] {
84
+ const words: string[] = [];
85
+ let current = '';
86
+ let quote: "'" | '"' | undefined;
87
+ let escaped = false;
88
+ const flush = () => {
89
+ if (current) words.push(current);
90
+ current = '';
91
+ };
92
+ for (let index = 0; index < segment.length; index += 1) {
93
+ const char = segment[index]!;
94
+ if (escaped) { current += char; escaped = false; continue; }
95
+ if (char === '\\' && quote !== "'") { escaped = true; continue; }
96
+ if (quote) {
97
+ if (char === quote) quote = undefined;
98
+ else current += char;
99
+ continue;
100
+ }
101
+ if (char === "'" || char === '"') { quote = char; continue; }
102
+ if (/\s/.test(char)) { flush(); continue; }
103
+ current += char;
104
+ }
105
+ flush();
106
+ return words;
107
+ }
108
+
109
+ const SAFE_SQLITE_READ_OPTIONS = new Set([
110
+ '-safe', '--safe', '-readonly', '--readonly', '-batch', '--batch',
111
+ '-header', '--header', '-noheader', '--noheader', '-json', '--json',
112
+ '-csv', '--csv', '-list', '--list', '-line', '--line', '-column', '--column',
113
+ '-tabs', '--tabs', '-table', '--table', '-box', '--box', '-markdown', '--markdown',
114
+ '-quote', '--quote', '-ascii', '--ascii',
115
+ ]);
116
+
117
+ function isSingleReadOnlySql(sql: string): boolean {
118
+ const normalized = sql.trim();
119
+ if (!normalized || normalized.startsWith('.')) return false;
120
+ const withoutTrailingSemicolon = normalized.endsWith(';') ? normalized.slice(0, -1).trimEnd() : normalized;
121
+ if (withoutTrailingSemicolon.includes(';')) return false;
122
+ if (!/^(?:select\b|with\b)/i.test(withoutTrailingSemicolon)) return false;
123
+ return !/\b(?:insert|update|delete|replace|create|drop|alter|vacuum|attach|detach|reindex|analyze|pragma|begin|commit|rollback|savepoint|release)\b/i.test(withoutTrailingSemicolon);
124
+ }
125
+
126
+ function isSafeReadOnlySqliteWords(rawWords: string[]): boolean {
127
+ const words = rawWords.filter(Boolean);
128
+ const program = words[0]?.split(/[\\/]/).at(-1)?.toLowerCase();
129
+ if (program !== 'sqlite3') return false;
130
+ const args = words.slice(1);
131
+ if (args.some((word) => /^(?:--?nonce)(?:=|$)/i.test(word) || /^(?:--?unsafe-testing)(?:=|$)/i.test(word))) return false;
132
+ let safe = false;
133
+ let readonly = false;
134
+ let index = 0;
135
+ for (; index < args.length; index += 1) {
136
+ const arg = args[index]!;
137
+ if (!arg.startsWith('-')) break;
138
+ if (!SAFE_SQLITE_READ_OPTIONS.has(arg.toLowerCase())) return false;
139
+ if (arg === '-safe' || arg === '--safe') safe = true;
140
+ if (arg === '-readonly' || arg === '--readonly') readonly = true;
141
+ }
142
+ if (!safe || !readonly) return false;
143
+ const database = args[index];
144
+ const sql = args[index + 1];
145
+ if (!database || !sql || args.length !== index + 2) return false;
146
+ return isSingleReadOnlySql(sql);
147
+ }
148
+
149
+ function isSafeReadOnlySqliteSegment(segment: string): boolean {
150
+ const stripped = segment.replace(/^\s*(?:[A-Za-z_][A-Za-z0-9_]*=[^\s]+\s+)*/, '');
151
+ return isSafeReadOnlySqliteWords(shellWordsPreservingQuotes(stripped));
152
+ }
153
+
83
154
  function isSedInPlaceSegment(segment: string): boolean {
84
155
  const words = firstWords(segment);
85
156
  if (words[0]?.toLowerCase() !== 'sed') return false;
@@ -177,11 +248,18 @@ function readOnlyGitSegment(words: string[], _segment: string): boolean {
177
248
  return isReadOnlyGitCommand(words);
178
249
  }
179
250
 
251
+ function isReadOnlyCodegraphCommand(words: string[]): boolean {
252
+ const program = words[0]?.split(/[\\/]/).at(-1)?.toLowerCase();
253
+ return program === 'codegraph' && words[1]?.toLowerCase() === 'status';
254
+ }
255
+
180
256
  function isReadOnlySegment(segment: string): boolean {
181
257
  const words = firstWords(segment);
182
258
  const program = words[0]?.toLowerCase();
183
259
  if (!program) return false;
184
260
  if (program === 'git') return readOnlyGitSegment(words, segment);
261
+ if (isReadOnlyCodegraphCommand(words)) return true;
262
+ if (program === 'sqlite3') return isSafeReadOnlySqliteSegment(segment);
185
263
  if (program === 'find') return !/(?:-delete|-exec|-execdir|-ok|-okdir)\b/.test(segment);
186
264
  if (program === 'sed') return !isSedInPlaceSegment(segment);
187
265
  if (program === 'gh') {
@@ -193,6 +271,26 @@ function isReadOnlySegment(segment: string): boolean {
193
271
  /** Package scripts that are local validation (not install/publish/mutate deps). */
194
272
  const SAFE_PACKAGE_SCRIPT = /^(?:test|check|lint|typecheck|format:check|tsc)(?::|$)/i;
195
273
 
274
+ function isReadOnlyLoopbackCurl(words: string[]): boolean {
275
+ const program = words[0]?.split(/[\\/]/).at(-1)?.toLowerCase();
276
+ if (program !== 'curl') return false;
277
+ const args = words.slice(1);
278
+ const writeFlags = new Set(['-d', '--data', '--data-raw', '--data-binary', '-f', '--form', '-t', '--upload-file', '-o', '--output', '-O', '--remote-name']);
279
+ if (args.some((arg) => writeFlags.has(arg))) return false;
280
+ for (let index = 0; index < args.length; index += 1) {
281
+ if (args[index] === '-X' || args[index] === '--request') {
282
+ if (!/^(?:GET|HEAD)$/i.test(args[index + 1] ?? '')) return false;
283
+ index += 1;
284
+ }
285
+ }
286
+ const urls = args.filter((arg) => /^https?:\/\//i.test(arg));
287
+ if (urls.length === 0) return false;
288
+ return urls.every((url) => {
289
+ try { return ['127.0.0.1', 'localhost', '::1'].includes(new URL(url).hostname.toLowerCase()); }
290
+ catch { return false; }
291
+ });
292
+ }
293
+
196
294
  function isSafePackageRunner(program: string, words: string[]): boolean {
197
295
  if (!['bun', 'npm', 'pnpm', 'yarn', 'node'].includes(program)) return false;
198
296
  // bun test <path>, npm test, etc.
@@ -440,6 +538,15 @@ function classifyArgvCommand(
440
538
  if (program === 'git' && isReadOnlyGitCommand(argv)) {
441
539
  return { risk: 'readonly', confirmation: 'none', reasons: ['the argv command is a recognized repository-local read operation'] };
442
540
  }
541
+ if (isReadOnlyCodegraphCommand(argv)) {
542
+ return { risk: 'readonly', confirmation: 'none', reasons: ['CodeGraph status only observes the local semantic index'] };
543
+ }
544
+ if (program === 'curl' && isReadOnlyLoopbackCurl(argv)) {
545
+ return { risk: 'readonly', confirmation: 'none', reasons: ['curl performs a read-only loopback HTTP observation without writing response data to disk'] };
546
+ }
547
+ if (program === 'sqlite3' && isSafeReadOnlySqliteWords(argv)) {
548
+ return { risk: 'readonly', confirmation: 'none', reasons: ['sqlite3 is constrained by safe mode, readonly database access, and one read-only SQL statement'] };
549
+ }
443
550
  // Explicit shell wrappers are common in generated diagnostics. Re-classify
444
551
  // the fixed inner command instead of treating `sh -c` / `bash -lc` wrappers
445
552
  // as workspace mutations. Unsafe shell constructs are still rejected by the
@@ -484,6 +591,12 @@ function classifyArgvCommand(
484
591
  || (['npm', 'bun', 'pnpm', 'yarn'].includes(program) && ['install', 'add', 'remove', 'update', 'run'].includes(subcommand ?? ''))) {
485
592
  return { risk: 'workspace_write', confirmation: 'authorization', reasons: ['writes repository files'] };
486
593
  }
594
+ // Package-manager `version` is a mutation command (for example
595
+ // `npm version 1.5.1 --no-git-tag-version` updates package metadata). Keep
596
+ // flag-style queries such as `npm --version` on the readonly path below.
597
+ if (['npm', 'pnpm', 'yarn'].includes(program) && subcommand === 'version') {
598
+ return { risk: 'workspace_write', confirmation: 'authorization', reasons: ['package-manager version command may update package metadata'] };
599
+ }
487
600
  // Lightweight project script info queries stay readonly when they only request help/version.
488
601
  if (['bun', 'node', 'npm', 'pnpm', 'yarn', 'python', 'python3', 'cargo', 'go', 'swift'].includes(program)
489
602
  && argv.slice(1).some((word) => word === '--help' || word === '-h' || word === '--version' || word === '-V' || word === 'version' || word === 'help')) {
@@ -7,6 +7,7 @@ import {
7
7
  getEditSession,
8
8
  type EditOperation,
9
9
  type EditSession,
10
+ type EditSessionBinding,
10
11
  type EditSessionPatchError,
11
12
  } from '../editing/edit-session';
12
13
  import { getMcpPolicy } from '../mcp/policy';
@@ -345,6 +346,7 @@ export function applySafePatch(repository: RepositoryRecord, input: {
345
346
  continueOnError?: unknown;
346
347
  refreshFingerprints?: unknown;
347
348
  recoverStaleSession?: unknown;
349
+ binding?: EditSessionBinding;
348
350
  }): SafePatchApplyResult {
349
351
  const operations = normalizedSafePatchOperations(input.operations);
350
352
  if (operations.length === 0) throw new Error('SAFE_PATCH_OPERATIONS_REQUIRED: provide at least one operation');
@@ -356,7 +358,7 @@ export function applySafePatch(repository: RepositoryRecord, input: {
356
358
  const allowedPaths = Array.isArray(input.allowedPaths) ? input.allowedPaths.map((item) => String(item).trim()).filter(Boolean) : undefined;
357
359
  let session = sessionId
358
360
  ? getEditSession(repository.canonicalRoot, sessionId)
359
- : beginEditSession(repository.canonicalRoot, { purpose: String(input.purpose ?? 'Safe repository patch').trim() || 'Safe repository patch', allowedPaths });
361
+ : beginEditSession(repository.canonicalRoot, { purpose: String(input.purpose ?? 'Safe repository patch').trim() || 'Safe repository patch', allowedPaths, binding: input.binding });
360
362
  const createdSession = !sessionId;
361
363
  let recoveredSession: SafePatchRecoveredSession | undefined;
362
364
  const appliedChunks: SafePatchAppliedChunk[] = [];
@@ -376,17 +378,17 @@ export function applySafePatch(repository: RepositoryRecord, input: {
376
378
  continue;
377
379
  }
378
380
  try {
379
- session = applyEditOperations(repository.canonicalRoot, policy, session.sessionId, preflight.operations.map(stripInternalIndex), { expectedRevision, maxBatchOperations: MAX_SAFE_PATCH_CHUNK_SIZE });
381
+ session = applyEditOperations(repository.canonicalRoot, policy, session.sessionId, preflight.operations.map(stripInternalIndex), { expectedRevision, maxBatchOperations: MAX_SAFE_PATCH_CHUNK_SIZE, binding: input.binding });
380
382
  } catch (error) {
381
383
  const message = error instanceof Error ? error.message : String(error);
382
384
  if (!sessionId && input.recoverStaleSession !== false && message.includes('EDIT_SESSION_FINGERPRINT_STALE')) {
383
385
  const previousSessionId = session.sessionId;
384
- session = beginEditSession(repository.canonicalRoot, { purpose: `${String(input.purpose ?? 'Safe repository patch').trim() || 'Safe repository patch'} (recovered)`, allowedPaths });
386
+ session = beginEditSession(repository.canonicalRoot, { purpose: `${String(input.purpose ?? 'Safe repository patch').trim() || 'Safe repository patch'} (recovered)`, allowedPaths, binding: input.binding });
385
387
  expectedRevision = session.currentRevision;
386
388
  recoveredSession = { reason: 'Previous edit session fingerprints were stale; remaining chunks were moved into a fresh session.', previousSessionId, newSessionId: session.sessionId };
387
389
  const retry = preflightChunk(repository, group, chunkIndex, refresh);
388
390
  if (retry.failures.length === 0) {
389
- session = applyEditOperations(repository.canonicalRoot, policy, session.sessionId, retry.operations.map(stripInternalIndex), { expectedRevision, maxBatchOperations: MAX_SAFE_PATCH_CHUNK_SIZE });
391
+ session = applyEditOperations(repository.canonicalRoot, policy, session.sessionId, retry.operations.map(stripInternalIndex), { expectedRevision, maxBatchOperations: MAX_SAFE_PATCH_CHUNK_SIZE, binding: input.binding });
390
392
  } else {
391
393
  failures.push(...retry.failures);
392
394
  failedChunk = chunkIndex;
@@ -236,18 +236,60 @@ export function repositoryGitFinishWorkflow(controllerHome: string, repository:
236
236
  const featureBranch = assertSafeBranchName(input.featureBranch ?? before.branch);
237
237
  const targetBranch = assertSafeBranchName(input.targetBranch ?? repository.defaultBranch ?? 'main');
238
238
  const steps: RepositoryGitFinishResult['steps'] = [];
239
- if (!before.clean) {
240
- return { repoId: repository.repoId, checkoutId: repository.activeCheckoutId, featureBranch, targetBranch, before, steps, after: before, completed: false, error: { code: 'GIT_WORKTREE_NOT_CLEAN', message: 'Commit or revert all changes before finishing a workflow.' } };
239
+ const alreadyOnTarget = before.branch === targetBranch;
240
+ if (!before.clean && !alreadyOnTarget) {
241
+ return { repoId: repository.repoId, checkoutId: repository.activeCheckoutId, featureBranch, targetBranch, before, steps, after: before, completed: false, error: { code: 'GIT_WORKTREE_NOT_CLEAN', message: 'Commit or revert changes before switching branches to finish a workflow.' } };
241
242
  }
242
243
  if (featureBranch === targetBranch) {
243
244
  return { repoId: repository.repoId, checkoutId: repository.activeCheckoutId, featureBranch, targetBranch, before, steps, after: before, completed: false, error: { code: 'GIT_ALREADY_ON_TARGET', message: 'Current/feature branch equals target branch; nothing to merge or delete.' } };
244
245
  }
245
- const switchTarget = executeRepositoryGitCommand(controllerHome, repository, { args: ['switch', targetBranch], authorization: 'explicit_user_request', ...input });
246
- steps.push({ name: 'switch_target', execution: switchTarget });
247
- if (switchTarget.status !== 'executed' || switchTarget.ok !== true) return { repoId: repository.repoId, checkoutId: repository.activeCheckoutId, featureBranch, targetBranch, before, steps, after: repositoryGitStatus(repository), completed: false, error: { code: 'GIT_SWITCH_TARGET_FAILED', message: switchTarget.stderr || 'git switch failed' } };
248
- const merge = executeRepositoryGitCommand(controllerHome, repository, { args: ['merge', ...(input.noFf === true ? ['--no-ff'] : ['--ff-only']), featureBranch], authorization: 'explicit_user_request', ...input });
246
+ if (!alreadyOnTarget) {
247
+ const switchTarget = executeRepositoryGitCommand(controllerHome, repository, { args: ['switch', targetBranch], authorization: 'explicit_user_request', ...input });
248
+ steps.push({ name: 'switch_target', execution: switchTarget });
249
+ if (switchTarget.status !== 'executed' || switchTarget.ok !== true) return { repoId: repository.repoId, checkoutId: repository.activeCheckoutId, featureBranch, targetBranch, before, steps, after: repositoryGitStatus(repository), completed: false, error: { code: 'GIT_SWITCH_TARGET_FAILED', message: switchTarget.stderr || 'git switch failed' } };
250
+ }
251
+ const protectTrackedChanges = alreadyOnTarget && (before.staged.length > 0 || before.unstaged.length > 0);
252
+ const finishAuthorization = 'explicit_user_request' as const;
253
+ let stashRef: string | null = null;
254
+ if (protectTrackedChanges) {
255
+ const stash = executeRepositoryGitCommand(controllerHome, repository, { args: ['stash', 'push', '-m', `forge-finish:${input.workId ?? featureBranch}`], authorization: finishAuthorization, ...input });
256
+ steps.push({ name: 'stash_target_changes', execution: stash });
257
+ if (stash.status !== 'executed' || stash.ok !== true) return { repoId: repository.repoId, checkoutId: repository.activeCheckoutId, featureBranch, targetBranch, before, steps, after: repositoryGitStatus(repository), completed: false, error: { code: 'GIT_STASH_LOCAL_CHANGES_FAILED', message: stash.stderr || 'git stash push failed' } };
258
+ stashRef = gitText(repository, ['rev-parse', 'refs/stash']);
259
+ if (!stashRef) return { repoId: repository.repoId, checkoutId: repository.activeCheckoutId, featureBranch, targetBranch, before, steps, after: repositoryGitStatus(repository), completed: false, error: { code: 'GIT_STASH_REFERENCE_MISSING', message: 'Tracked changes were stashed but the stash reference could not be resolved.' } };
260
+ const workingTreeMerge = runGit(repository, ['merge-tree', '--write-tree', featureBranch, stashRef], 128 * 1024);
261
+ const indexTreeMerge = runGit(repository, ['merge-tree', '--write-tree', featureBranch, `${stashRef}^2`], 128 * 1024);
262
+ if (!workingTreeMerge.ok || !indexTreeMerge.ok) {
263
+ const restore = executeRepositoryGitCommand(controllerHome, repository, { args: ['stash', 'apply', '--index', stashRef], authorization: finishAuthorization, ...input });
264
+ steps.push({ name: 'restore_target_changes_after_preflight_conflict', execution: restore });
265
+ if (restore.status !== 'executed' || restore.ok !== true) return { repoId: repository.repoId, checkoutId: repository.activeCheckoutId, featureBranch, targetBranch, before, steps, after: repositoryGitStatus(repository), completed: false, error: { code: 'GIT_LOCAL_CHANGES_RESTORE_FAILED', message: restore.stderr || 'Tracked target changes could not be restored after integration preflight; recovery stash was retained.' } };
266
+ const drop = executeRepositoryGitCommand(controllerHome, repository, { args: ['stash', 'drop', stashRef], authorization: finishAuthorization, ...input });
267
+ steps.push({ name: 'drop_target_stash', execution: drop });
268
+ return { repoId: repository.repoId, checkoutId: repository.activeCheckoutId, featureBranch, targetBranch, before, steps, after: repositoryGitStatus(repository), completed: false, error: { code: 'GIT_LOCAL_CHANGES_REAPPLY_CONFLICT', message: workingTreeMerge.stderr || indexTreeMerge.stderr || 'Tracked target changes conflict with the feature branch; target branch was left unchanged and local changes were restored.' } };
269
+ }
270
+ }
271
+ const applyTrackedStash = (name: string): RepositoryGitExecution | undefined => {
272
+ if (!stashRef) return undefined;
273
+ const execution = executeRepositoryGitCommand(controllerHome, repository, { args: ['stash', 'apply', '--index', stashRef], authorization: finishAuthorization, ...input });
274
+ steps.push({ name, execution });
275
+ return execution;
276
+ };
277
+ const dropTrackedStash = (): void => {
278
+ if (!stashRef) return;
279
+ const execution = executeRepositoryGitCommand(controllerHome, repository, { args: ['stash', 'drop', stashRef], authorization: finishAuthorization, ...input });
280
+ steps.push({ name: 'drop_target_stash', execution });
281
+ };
282
+ const merge = executeRepositoryGitCommand(controllerHome, repository, { args: ['merge', ...(input.noFf === true ? ['--no-ff'] : ['--ff-only']), featureBranch], authorization: finishAuthorization, ...input });
249
283
  steps.push({ name: 'merge_feature', execution: merge });
250
- if (merge.status !== 'executed' || merge.ok !== true) return { repoId: repository.repoId, checkoutId: repository.activeCheckoutId, featureBranch, targetBranch, before, steps, after: repositoryGitStatus(repository), completed: false, error: { code: 'GIT_MERGE_FAILED', message: merge.stderr || 'git merge failed' } };
284
+ if (merge.status !== 'executed' || merge.ok !== true) {
285
+ const restore = applyTrackedStash('restore_target_changes_after_merge_failure');
286
+ if (restore && (restore.status !== 'executed' || restore.ok !== true)) return { repoId: repository.repoId, checkoutId: repository.activeCheckoutId, featureBranch, targetBranch, before, steps, after: repositoryGitStatus(repository), completed: false, error: { code: 'GIT_LOCAL_CHANGES_RESTORE_FAILED', message: restore.stderr || 'git stash apply failed while restoring the pre-merge target state' } };
287
+ dropTrackedStash();
288
+ return { repoId: repository.repoId, checkoutId: repository.activeCheckoutId, featureBranch, targetBranch, before, steps, after: repositoryGitStatus(repository), completed: false, error: { code: 'GIT_MERGE_FAILED', message: merge.stderr || 'git merge failed' } };
289
+ }
290
+ const reapply = applyTrackedStash('reapply_target_changes');
291
+ if (reapply && (reapply.status !== 'executed' || reapply.ok !== true)) return { repoId: repository.repoId, checkoutId: repository.activeCheckoutId, featureBranch, targetBranch, before, steps, after: repositoryGitStatus(repository), completed: false, error: { code: 'GIT_LOCAL_CHANGES_RESTORE_FAILED', message: reapply.stderr || 'Tracked target changes passed merge-tree preflight but could not be reapplied after merge; recovery stash was retained.' } };
292
+ dropTrackedStash();
251
293
  if (input.deleteBranch !== false) {
252
294
  const del = executeRepositoryGitCommand(controllerHome, repository, { args: ['branch', '-d', featureBranch], authorization: 'explicit_user_request', ...input });
253
295
  steps.push({ name: 'delete_feature_branch', execution: del });
@@ -1,5 +1,5 @@
1
1
  import { createHash } from 'crypto';
2
- import { existsSync, lstatSync, readdirSync, readFileSync, statSync } from 'fs';
2
+ import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSync } from 'fs';
3
3
  import { join } from 'path';
4
4
  import { runProcess } from '../../effects/process-runner';
5
5
  import { globMatches, resolveMcpPath } from '../mcp/paths';
@@ -264,6 +264,8 @@ export interface SearchRepositoryOptions {
264
264
 
265
265
  export interface SearchRepositoryManyOptions {
266
266
  queries: string[];
267
+ /** Pre-resolved exact candidate files. Skips repository inventory discovery. */
268
+ files?: string[];
267
269
  includeGlobs?: string[];
268
270
  excludeGlobs?: string[];
269
271
  maxResultsPerQuery?: number;
@@ -327,7 +329,17 @@ export function searchRepositoryMany(
327
329
  const maxFiles = Math.min(Math.max(opts.maxFiles ?? 5000, 1), 20_000);
328
330
  const includes = opts.includeGlobs ?? [];
329
331
  const excludes = [...(includes.length === 0 ? DEFAULT_EXCLUDES : []), ...(opts.excludeGlobs ?? [])];
330
- const inventory = searchInventory(repoRoot, includes, excludes, maxFiles, opts.cacheKey);
332
+ const directFiles = opts.files?.map((path) => path.trim()).filter(Boolean);
333
+ const directCandidates = directFiles
334
+ ? Array.from(new Set(directFiles)).filter((path) => !isExcluded(path, excludes))
335
+ : undefined;
336
+ const inventory = directCandidates && directCandidates.length > 0
337
+ ? {
338
+ files: directCandidates.slice(0, maxFiles),
339
+ candidateCount: directCandidates.length,
340
+ cacheHit: false,
341
+ }
342
+ : searchInventory(repoRoot, includes, excludes, maxFiles, opts.cacheKey);
331
343
  const needles = queries.map((query) => ({ query, needle: opts.caseSensitive ? query : query.toLowerCase() }));
332
344
  const counts = new Map(queries.map((query) => [query, 0]));
333
345
  const results: SearchRepositoryManyResult['results'] = [];
@@ -335,10 +347,11 @@ export function searchRepositoryMany(
335
347
  let policyDeniedFiles = 0;
336
348
  let skippedLargeFiles = 0;
337
349
  let skippedBinaryFiles = 0;
350
+ const canonicalRepoRoot = realpathSync(repoRoot);
338
351
 
339
352
  for (const path of inventory.files) {
340
353
  if (needles.every(({ query }) => (counts.get(query) ?? 0) >= maxResultsPerQuery)) break;
341
- const decision = resolveMcpPath(repoRoot, path, policy, 'read');
354
+ const decision = resolveMcpPath(repoRoot, path, policy, 'read', canonicalRepoRoot);
342
355
  if (!decision.ok || !decision.absolutePath) {
343
356
  policyDeniedFiles += 1;
344
357
  continue;
@@ -370,8 +370,8 @@ export function runAssistantRoutineNow(
370
370
  relatedRoutineId: routine.routineId,
371
371
  relatedRequestId: requestId,
372
372
  jobIds: [],
373
- recommendations: ['Claim or create Work for this routine, then execute it through an explicit external Controller.'],
374
- data: { routine: touched, externalControllerRequired: true },
373
+ recommendations: ['Resume this existing Routine authority through its external Controller context. Do not create a new Work merely because the timer fired.'],
374
+ data: { routine: touched, externalControllerRequired: true, createWorkOnTrigger: false },
375
375
  });
376
376
  return {
377
377
  schemaVersion: 1,
@@ -381,7 +381,7 @@ export function runAssistantRoutineNow(
381
381
  requestId,
382
382
  understoodIntent: 'run_routine',
383
383
  displayTitle: `Routine requires an external Controller: ${routine.name}`,
384
- displayText: 'No ExecutionJob was created. Continue this routine from the recorded Inbox item with an explicitly claimed Controller session.',
384
+ displayText: 'No ExecutionJob or new Work was created. Continue the existing Routine authority from the recorded Inbox item with an explicitly claimed Controller session.',
385
385
  requiresConfirmation: false,
386
386
  plan: [],
387
387
  routine: touched,
@@ -1,8 +1,11 @@
1
1
  import { createHash } from 'crypto';
2
2
  import { getEditSession, listEditSessions, type EditSession } from '../../../cli/editing/edit-session';
3
+ import { globMatches } from '../../../cli/mcp/paths';
3
4
  import { runProcess } from '../../../effects/process-runner';
4
- import { getWorkContract, recordWorkCompletionReceipt } from '../facade/work-contract-store';
5
- import { isTerminalWorkContractStatus, type DirectEditWorkCompletionReceipt } from '../facade/types';
5
+ import { completeRequirementFromWork } from '../persistence/requirement-store';
6
+ import { getWorkContract, recordWorkCompletionReceipt, updateWorkContract } from '../facade/work-contract-store';
7
+ import { isDirectEditWorkCompletionReceipt, isTerminalWorkContractStatus, type DirectEditWorkCompletionReceipt, type WorkReconciliationRecord } from '../facade/types';
8
+ import { effectiveVerificationEvidence } from './verification-evidence';
6
9
 
7
10
  export interface DirectEditWorkCompletionReconciliation {
8
11
  completedWorkIds: string[];
@@ -149,3 +152,155 @@ export function reconcileFinalizedDirectEditWorksAfterCommit(input: {
149
152
 
150
153
  return { completedWorkIds, examinedSessionIds, skipped, targetBranch, targetRevision };
151
154
  }
155
+
156
+ export interface ReviewedDirectEditWorkReconciliationInput {
157
+ controllerHome: string;
158
+ repoId: string;
159
+ checkoutId: string;
160
+ repoRoot: string;
161
+ workId: string;
162
+ targetBranch: string;
163
+ targetRevision: string;
164
+ comparedPaths: string[];
165
+ reviewer: string;
166
+ rationale: string;
167
+ cleanupOwnershipProof: string;
168
+ reviewedAt?: string;
169
+ }
170
+
171
+ function exactCommit(repoRoot: string, revision: string, label: string): string {
172
+ const result = git(repoRoot, ['rev-parse', '--verify', `${revision}^{commit}`]);
173
+ if (!result.ok || !result.stdout.trim()) throw new Error(`DIRECT_EDIT_WORK_RECONCILIATION_${label}_INVALID`);
174
+ return result.stdout.trim();
175
+ }
176
+
177
+ function comparedRevisionPaths(repoRoot: string, baseRevision: string, targetRevision: string): string[] {
178
+ const result = git(repoRoot, ['diff', '--name-only', '-z', baseRevision, targetRevision]);
179
+ if (!result.ok) throw new Error('DIRECT_EDIT_WORK_RECONCILIATION_CHANGED_PATHS_UNAVAILABLE');
180
+ return [...new Set(result.stdout.split('\0').filter(Boolean))].sort((left, right) => left.localeCompare(right));
181
+ }
182
+
183
+ function normalizedComparedPaths(paths: string[]): string[] {
184
+ const normalized = [...new Set(paths.map((path) => path.trim()))].sort((left, right) => left.localeCompare(right));
185
+ if (normalized.length === 0 || normalized.length > 100 || normalized.some((path) => !path || path.startsWith('/') || path.includes('\0') || path.split('/').some((part) => part === '' || part === '.' || part === '..'))) {
186
+ throw new Error('DIRECT_EDIT_WORK_RECONCILIATION_PATHS_INVALID');
187
+ }
188
+ return normalized;
189
+ }
190
+
191
+ /**
192
+ * Explicitly close a historically delivered Direct Edit Work whose original
193
+ * edit-session binding was missed. This is never inferred: the caller must
194
+ * supply the exact accepted revision and the complete reviewed path set.
195
+ */
196
+ export function acceptReviewedDirectEditWorkReconciliation(input: ReviewedDirectEditWorkReconciliationInput): {
197
+ workId: string;
198
+ reconciliation: WorkReconciliationRecord;
199
+ receipt: DirectEditWorkCompletionReceipt;
200
+ } {
201
+ const work = getWorkContract({ controllerHome: input.controllerHome, repoId: input.repoId }, input.workId);
202
+ if (!work || work.repoId !== input.repoId) throw new Error(`DIRECT_EDIT_WORK_RECONCILIATION_WORK_NOT_FOUND: ${input.workId}`);
203
+ if (work.checkoutId && work.checkoutId !== input.checkoutId) throw new Error(`DIRECT_EDIT_WORK_RECONCILIATION_CHECKOUT_MISMATCH: ${input.workId}`);
204
+ if (work.completionReceipt) {
205
+ const completionReceipt = work.completionReceipt;
206
+ if (isDirectEditWorkCompletionReceipt(completionReceipt) && completionReceipt.reconciliationId) {
207
+ const existing = work.reconciliations.find((entry) => entry.reconciliationId === completionReceipt.reconciliationId);
208
+ if (existing) return { workId: work.workId, reconciliation: existing, receipt: completionReceipt };
209
+ }
210
+ throw new Error(`DIRECT_EDIT_WORK_RECONCILIATION_WORK_TERMINAL: ${input.workId}`);
211
+ }
212
+ if (isTerminalWorkContractStatus(work.status) || work.workKind !== 'repository_change') {
213
+ throw new Error(`DIRECT_EDIT_WORK_RECONCILIATION_WORK_NOT_ELIGIBLE: ${input.workId}`);
214
+ }
215
+ if (!work.baseRevision?.trim()) throw new Error('DIRECT_EDIT_WORK_RECONCILIATION_BASE_REVISION_MISSING');
216
+
217
+ const baseRevision = exactCommit(input.repoRoot, work.baseRevision, 'BASE_REVISION');
218
+ const targetRevision = exactCommit(input.repoRoot, input.targetRevision.trim(), 'TARGET_REVISION');
219
+ const targetBranch = input.targetBranch.trim();
220
+ if (!targetBranch) throw new Error('DIRECT_EDIT_WORK_RECONCILIATION_TARGET_BRANCH_REQUIRED');
221
+ if (!git(input.repoRoot, ['merge-base', '--is-ancestor', baseRevision, targetRevision]).ok) {
222
+ throw new Error('DIRECT_EDIT_WORK_RECONCILIATION_TARGET_NOT_DESCENDANT');
223
+ }
224
+ if (!git(input.repoRoot, ['merge-base', '--is-ancestor', targetRevision, targetBranch]).ok) {
225
+ throw new Error('DIRECT_EDIT_WORK_RECONCILIATION_TARGET_UNREACHABLE');
226
+ }
227
+
228
+ const comparedPaths = normalizedComparedPaths(input.comparedPaths);
229
+ const actualPaths = comparedRevisionPaths(input.repoRoot, baseRevision, targetRevision);
230
+ if (comparedPaths.length !== actualPaths.length || comparedPaths.some((path, index) => path !== actualPaths[index])) {
231
+ throw new Error('DIRECT_EDIT_WORK_RECONCILIATION_PATH_COMPARISON_MISMATCH');
232
+ }
233
+ for (const path of comparedPaths) {
234
+ if (work.forbiddenPaths.some((pattern) => globMatches(pattern, path))) throw new Error(`DIRECT_EDIT_WORK_RECONCILIATION_FORBIDDEN_PATH: ${path}`);
235
+ if (work.allowedPaths.length > 0 && !work.allowedPaths.some((pattern) => globMatches(pattern, path))) throw new Error(`DIRECT_EDIT_WORK_RECONCILIATION_PATH_OUT_OF_SCOPE: ${path}`);
236
+ }
237
+ const dirty = git(input.repoRoot, ['status', '--porcelain=v1', '--', ...comparedPaths]);
238
+ if (!dirty.ok || dirty.stdout.trim()) throw new Error('DIRECT_EDIT_WORK_RECONCILIATION_OWNED_PATHS_DIRTY');
239
+
240
+ let verifiedAt = new Date().toISOString();
241
+ for (const checkId of work.checks) {
242
+ const current = effectiveVerificationEvidence(work.checkRefs, {
243
+ sourceRevision: targetRevision,
244
+ checkId,
245
+ requestedChecks: work.checks,
246
+ }).find((entry) => entry.current && entry.record.outcome === 'valid_pass');
247
+ if (!current) throw new Error(`DIRECT_EDIT_WORK_RECONCILIATION_CHECK_EVIDENCE_STALE: ${checkId}`);
248
+ verifiedAt = current.record.completedAt ?? current.record.recordedAt ?? verifiedAt;
249
+ }
250
+
251
+ const reviewer = input.reviewer.trim();
252
+ const rationale = input.rationale.trim();
253
+ const cleanupOwnershipProof = input.cleanupOwnershipProof.trim();
254
+ const reviewedAt = input.reviewedAt ?? new Date().toISOString();
255
+ if (!reviewer || !rationale || !cleanupOwnershipProof || Number.isNaN(Date.parse(reviewedAt))) {
256
+ throw new Error('DIRECT_EDIT_WORK_RECONCILIATION_REVIEW_METADATA_INVALID');
257
+ }
258
+ const reconciliationId = `RECNC-${createHash('sha256').update([input.repoId, input.workId, baseRevision, targetRevision, comparedPaths.join('\0'), reviewer, reviewedAt].join('\0')).digest('hex').slice(0, 16)}`;
259
+ const reconciliation: WorkReconciliationRecord = {
260
+ schemaVersion: 1,
261
+ reconciliationId,
262
+ originalExpectedRevision: targetRevision,
263
+ observedTargetRevision: targetRevision,
264
+ baseRevision,
265
+ targetBranch,
266
+ reachable: true,
267
+ method: 'owned_path_tree',
268
+ comparedPaths,
269
+ reviewer: reviewer.slice(0, 200),
270
+ reviewedAt,
271
+ unrecoverableStages: ['receipt'],
272
+ cleanupOwnershipProof: cleanupOwnershipProof.slice(0, 2_000),
273
+ rationale: rationale.slice(0, 2_000),
274
+ outcome: 'accepted_equivalence',
275
+ };
276
+ updateWorkContract({ controllerHome: input.controllerHome, repoId: input.repoId }, input.workId, {
277
+ reconciliations: [reconciliation, ...work.reconciliations.filter((entry) => entry.reconciliationId !== reconciliationId)],
278
+ });
279
+
280
+ const recordedAt = new Date().toISOString();
281
+ const receipt: DirectEditWorkCompletionReceipt = {
282
+ schemaVersion: 1,
283
+ receiptId: `REC-direct-edit-reconciled-${createHash('sha256').update(`${input.repoId}\0${input.workId}\0${reconciliationId}\0${targetRevision}`).digest('hex').slice(0, 20)}`,
284
+ source: 'direct_edit_work',
285
+ workId: input.workId,
286
+ reconciliationId,
287
+ targetBranch,
288
+ targetRevision,
289
+ sourceRevision: targetRevision,
290
+ baseRevision,
291
+ changedPaths: comparedPaths,
292
+ delivery: { kind: 'commit', status: 'integrated', strategy: 'already_integrated', reachable: true, recordedAt },
293
+ cleanup: { status: 'complete', warnings: [], blockers: [], recordedAt },
294
+ verifiedAt,
295
+ recordedAt,
296
+ };
297
+ const recorded = recordWorkCompletionReceipt(
298
+ { controllerHome: input.controllerHome, repoId: input.repoId },
299
+ input.workId,
300
+ receipt,
301
+ 'completed_changed',
302
+ 'repository_change',
303
+ );
304
+ if (recorded.requirementId) completeRequirementFromWork({ controllerHome: input.controllerHome }, { requirementId: recorded.requirementId, work: recorded });
305
+ return { workId: input.workId, reconciliation, receipt };
306
+ }
@@ -134,6 +134,53 @@ function gitPath(root: string, args: string[]): string | undefined {
134
134
  }
135
135
  }
136
136
 
137
+ interface GitExecutionSnapshot {
138
+ topLevel?: string;
139
+ commonDirectory?: string;
140
+ branch?: string;
141
+ head?: string;
142
+ }
143
+
144
+ function resolvedGitPath(root: string, value: string | undefined): string | undefined {
145
+ if (!value) return undefined;
146
+ try {
147
+ return realpathSync(isAbsolute(value) ? value : resolve(root, value));
148
+ } catch {
149
+ return undefined;
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Read the checkout identity in one Git child process on the normal committed
155
+ * path. This preserves the same fail-closed fields as the former six probes;
156
+ * unborn repositories fall back to the individual observations because HEAD is
157
+ * intentionally absent there.
158
+ */
159
+ function gitExecutionSnapshot(root: string): GitExecutionSnapshot {
160
+ const combined = gitText(root, ['rev-parse', '--show-toplevel', '--git-common-dir', 'HEAD', '--abbrev-ref', 'HEAD']);
161
+ if (combined) {
162
+ const lines = combined.split('\n').map((line) => line.trim());
163
+ if (lines.length >= 4) {
164
+ return {
165
+ topLevel: resolvedGitPath(root, lines[0]),
166
+ commonDirectory: resolvedGitPath(root, lines[1]),
167
+ head: lines[2] || undefined,
168
+ branch: lines[3] && lines[3] !== 'HEAD' ? lines[3] : undefined,
169
+ };
170
+ }
171
+ }
172
+ // Rare unborn/failure fallback keeps legacy behavior rather than turning a
173
+ // missing HEAD into a false workspace identity failure.
174
+ const topLevel = gitPath(root, ['rev-parse', '--show-toplevel']);
175
+ const commonDirectory = gitPath(root, ['rev-parse', '--git-common-dir']);
176
+ return {
177
+ topLevel,
178
+ commonDirectory,
179
+ branch: topLevel ? gitText(topLevel, ['branch', '--show-current']) : undefined,
180
+ head: topLevel ? gitText(topLevel, ['rev-parse', '--verify', 'HEAD']) : undefined,
181
+ };
182
+ }
183
+
137
184
  export function classifyGitCommonDirectoryDrift(input: {
138
185
  repoId: string;
139
186
  checkoutId: string;
@@ -304,18 +351,15 @@ export function assertExecutionIdentity(input: {
304
351
  actual: resolvedCwd,
305
352
  });
306
353
  }
307
- const gitTopLevel = gitPath(resolvedCwd, ['rev-parse', '--show-toplevel']);
308
- const gitCommonDirectory = gitPath(resolvedCwd, ['rev-parse', '--git-common-dir']);
309
- const currentBranch = gitTopLevel ? gitText(gitTopLevel, ['branch', '--show-current']) : undefined;
310
- const currentHead = gitTopLevel ? gitText(gitTopLevel, ['rev-parse', '--verify', 'HEAD']) : undefined;
354
+ const gitSnapshot = gitExecutionSnapshot(resolvedCwd);
311
355
  return Object.freeze({
312
356
  ...identity,
313
357
  canonicalRoot: workspaceRoot,
314
358
  resolvedCwd,
315
- gitTopLevel,
316
- gitCommonDirectory,
317
- currentBranch,
318
- currentHead,
359
+ gitTopLevel: gitSnapshot.topLevel,
360
+ gitCommonDirectory: gitSnapshot.commonDirectory,
361
+ currentBranch: gitSnapshot.branch,
362
+ currentHead: gitSnapshot.head,
319
363
  });
320
364
  }
321
365
 
@@ -377,7 +421,8 @@ export function assertExecutionIdentity(input: {
377
421
  });
378
422
  }
379
423
 
380
- const gitTopLevel = gitPath(resolvedCwd, ['rev-parse', '--show-toplevel']);
424
+ const gitSnapshot = gitExecutionSnapshot(resolvedCwd);
425
+ const gitTopLevel = gitSnapshot.topLevel;
381
426
  if (!gitTopLevel || !samePath(gitTopLevel, registeredRoot)) {
382
427
  fail('GIT_TOPLEVEL_MISMATCH', 'Git top-level differs from expected checkout root', {
383
428
  repoId: identity.repositoryId,
@@ -387,9 +432,15 @@ export function assertExecutionIdentity(input: {
387
432
  });
388
433
  }
389
434
 
390
- const gitCommonDirectory = gitPath(resolvedCwd, ['rev-parse', '--git-common-dir']);
391
- const registeredCommonDirectory = gitPath(registeredRoot, ['rev-parse', '--git-common-dir']);
392
- const repositoryCommonDirectory = gitPath(registered.canonicalRoot, ['rev-parse', '--git-common-dir']);
435
+ const gitCommonDirectory = gitSnapshot.commonDirectory;
436
+ // Once the observed top-level is proven equal to registeredRoot, querying the
437
+ // same checkout again cannot add identity evidence. Only a linked worktree
438
+ // needs one extra canonical-repository common-dir observation.
439
+ const registeredCommonDirectory = gitCommonDirectory;
440
+ const repositoryRoot = realpathOrFail(registered.canonicalRoot, 'WORKTREE_MISSING', 'repository canonical root');
441
+ const repositoryCommonDirectory = samePath(repositoryRoot, registeredRoot)
442
+ ? gitCommonDirectory
443
+ : gitPath(repositoryRoot, ['rev-parse', '--git-common-dir']);
393
444
  const commonDirectoryDrift = classifyGitCommonDirectoryDrift({
394
445
  repoId: identity.repositoryId,
395
446
  checkoutId: identity.checkoutId,
@@ -423,8 +474,8 @@ export function assertExecutionIdentity(input: {
423
474
  });
424
475
  }
425
476
 
426
- const currentBranch = gitText(registeredRoot, ['branch', '--show-current']);
427
- const currentHead = gitText(registeredRoot, ['rev-parse', '--verify', 'HEAD']);
477
+ const currentBranch = gitSnapshot.branch;
478
+ const currentHead = gitSnapshot.head;
428
479
  if (identity.branch && currentBranch !== identity.branch) {
429
480
  fail('WORK_HANDLE_BRANCH_CHANGED', 'branch drifted from execution identity', {
430
481
  repoId: identity.repositoryId,