pi-better-server 0.6.0 → 0.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 (142) hide show
  1. package/package.json +4 -3
  2. package/scripts/measure-full-runtime/frontend.ts +10 -2
  3. package/scripts/measure-full-runtime.mjs +2 -0
  4. package/src/codex/return.ts +3 -2
  5. package/src/detach/extension.ts +20 -3
  6. package/src/event-log.ts +40 -12
  7. package/src/hosted-session.ts +11 -5
  8. package/src/remote-client/packages.ts +1 -4
  9. package/src/runtime/background-tools.ts +54 -8
  10. package/src/runtime/background.ts +16 -4
  11. package/src/runtime/domain/background/process.mjs +49 -11
  12. package/src/runtime/domain/background/supervisor/store.mjs +3 -3
  13. package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -3
  14. package/src/runtime/domain/background-service/index.domain.mjs +19 -0
  15. package/src/runtime/domain/background-service/index.ts +19 -0
  16. package/src/runtime/domain/background-service/managed-frontend.domain.mjs +87 -5
  17. package/src/runtime/domain/background-service/managed-frontend.ts +76 -5
  18. package/src/runtime/domain/background-service/navigator-provider.domain.mjs +5 -0
  19. package/src/runtime/domain/background-service/navigator-provider.ts +4 -0
  20. package/src/runtime/domain/background-service/observed-waits.domain.mjs +203 -31
  21. package/src/runtime/domain/background-service/observed-waits.ts +168 -24
  22. package/src/runtime/domain/background-service/process.domain.mjs +49 -11
  23. package/src/runtime/domain/background-service/process.ts +45 -11
  24. package/src/runtime/domain/background-service/review-settings.domain.mjs +16 -0
  25. package/src/runtime/domain/background-service/review-settings.ts +18 -0
  26. package/src/runtime/domain/background-service/runtime.domain.mjs +8 -70
  27. package/src/runtime/domain/background-service/runtime.ts +8 -73
  28. package/src/runtime/domain/background-service/shared-harness-settings.domain.mjs +2 -3
  29. package/src/runtime/domain/background-service/shared-harness-settings.ts +2 -5
  30. package/src/runtime/domain/background-service/shared-navigator.domain.mjs +55 -28
  31. package/src/runtime/domain/background-service/shared-navigator.ts +47 -26
  32. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  33. package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
  34. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +5 -1
  35. package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +6 -0
  36. package/src/runtime/domain/background-service/shared-ssh-core/index.domain.mjs +1 -1
  37. package/src/runtime/domain/background-service/shared-ssh-core/index.ts +1 -1
  38. package/src/runtime/domain/background-service/stall.domain.mjs +5 -3
  39. package/src/runtime/domain/background-service/stall.ts +7 -4
  40. package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
  41. package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
  42. package/src/runtime/domain/background-service/supervisor/README.md +1 -4
  43. package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
  44. package/src/runtime/domain/background-service/supervisor/generated/process.mjs +49 -11
  45. package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
  46. package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
  47. package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
  48. package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
  49. package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
  50. package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
  51. package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
  52. package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
  53. package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -3
  54. package/src/runtime/domain/background-service/tools.domain.mjs +22 -16
  55. package/src/runtime/domain/background-service/tools.ts +26 -16
  56. package/src/runtime/domain/background-service/types.ts +4 -2
  57. package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
  58. package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
  59. package/src/runtime/domain/catalog/catalog-preferences.mjs +1 -3
  60. package/src/runtime/domain/coordinator/src/outbox.mjs +7 -0
  61. package/src/runtime/domain/coordinator/src/store.mjs +5 -1
  62. package/src/runtime/domain/log-paths.mjs +8 -1
  63. package/src/runtime/domain/parse.mjs +9 -5
  64. package/src/runtime/domain/sandbox-policy/README.md +3 -3
  65. package/src/runtime/domain/sandbox-policy/package.json +1 -1
  66. package/src/runtime/domain/sandbox-policy/shared-harness-settings.domain.mjs +2 -3
  67. package/src/runtime/domain/sandbox-policy/shared-harness-settings.ts +2 -5
  68. package/src/runtime/domain/session-store.mjs +7 -0
  69. package/src/runtime/domain/shared-harness-settings.mjs +2 -3
  70. package/src/runtime/domain/subagents/README.md +12 -10
  71. package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +2 -5
  72. package/src/runtime/domain/subagents/assignment-outcomes.ts +2 -5
  73. package/src/runtime/domain/subagents/assignment-report.domain.mjs +22 -0
  74. package/src/runtime/domain/subagents/assignment-report.ts +20 -0
  75. package/src/runtime/domain/subagents/batch.mjs +13 -5
  76. package/src/runtime/domain/subagents/catalog-preferences.domain.mjs +1 -3
  77. package/src/runtime/domain/subagents/catalog-preferences.ts +1 -5
  78. package/src/runtime/domain/subagents/cleanup.domain.mjs +11 -2
  79. package/src/runtime/domain/subagents/cleanup.ts +10 -2
  80. package/src/runtime/domain/subagents/config.domain.mjs +5 -0
  81. package/src/runtime/domain/subagents/config.ts +8 -2
  82. package/src/runtime/domain/subagents/continuation.domain.mjs +4 -2
  83. package/src/runtime/domain/subagents/continuation.ts +4 -2
  84. package/src/runtime/domain/subagents/extensions.mjs +1 -0
  85. package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
  86. package/src/runtime/domain/subagents/failures.ts +10 -2
  87. package/src/runtime/domain/subagents/finalization.domain.mjs +39 -32
  88. package/src/runtime/domain/subagents/finalization.ts +37 -30
  89. package/src/runtime/domain/subagents/git-workspace.domain.mjs +51 -6
  90. package/src/runtime/domain/subagents/git-workspace.ts +48 -6
  91. package/src/runtime/domain/subagents/index.domain.mjs +208 -75
  92. package/src/runtime/domain/subagents/index.ts +213 -75
  93. package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +508 -0
  94. package/src/runtime/domain/subagents/isolated-workspace.ts +551 -0
  95. package/src/runtime/domain/subagents/list.mjs +2 -2
  96. package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +22 -5
  97. package/src/runtime/domain/subagents/managed-launch-client.ts +23 -6
  98. package/src/runtime/domain/subagents/output-payload.domain.mjs +24 -9
  99. package/src/runtime/domain/subagents/output-payload.ts +26 -12
  100. package/src/runtime/domain/subagents/package.json +4 -2
  101. package/src/runtime/domain/subagents/parse.domain.mjs +9 -5
  102. package/src/runtime/domain/subagents/parse.ts +10 -5
  103. package/src/runtime/domain/subagents/registry.domain.mjs +31 -25
  104. package/src/runtime/domain/subagents/registry.ts +31 -13
  105. package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
  106. package/src/runtime/domain/subagents/retained-result.ts +65 -0
  107. package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
  108. package/src/runtime/domain/subagents/session-selection.ts +2 -1
  109. package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
  110. package/src/runtime/domain/subagents/session-store.ts +9 -0
  111. package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
  112. package/src/runtime/domain/subagents/settings-page.ts +147 -108
  113. package/src/runtime/domain/subagents/shared-catalog.domain.mjs +23 -7
  114. package/src/runtime/domain/subagents/shared-catalog.ts +23 -7
  115. package/src/runtime/domain/subagents/shared-harness-settings.domain.mjs +2 -3
  116. package/src/runtime/domain/subagents/shared-harness-settings.ts +2 -5
  117. package/src/runtime/domain/subagents/shared-navigator.domain.mjs +55 -28
  118. package/src/runtime/domain/subagents/shared-navigator.ts +47 -26
  119. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
  120. package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
  121. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +5 -1
  122. package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +6 -0
  123. package/src/runtime/domain/subagents/task-guard.domain.mjs +14 -1
  124. package/src/runtime/domain/subagents/task-guard.ts +13 -1
  125. package/src/runtime/domain/subagents/task-policy.domain.mjs +2 -1
  126. package/src/runtime/domain/subagents/task-policy.ts +5 -1
  127. package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
  128. package/src/runtime/domain/subagents/tools.ts +4 -7
  129. package/src/runtime/domain/subagents/work-observation.domain.mjs +25 -1
  130. package/src/runtime/domain/subagents/work-observation.ts +20 -1
  131. package/src/runtime/domain/subagents/workspace-files.domain.mjs +103 -0
  132. package/src/runtime/domain/subagents/workspace-files.ts +114 -0
  133. package/src/runtime/domain/subagents/workspace-prepare-worker.mjs +12 -0
  134. package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
  135. package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
  136. package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
  137. package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
  138. package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
  139. package/src/runtime/read-model.ts +4 -2
  140. package/src/runtime/root.ts +5 -2
  141. package/src/shared-ssh-core/index.ts +1 -1
  142. package/src/version.ts +1 -1
@@ -22,7 +22,7 @@ export function reconcileInterruptedRun(meta, probe, now, hooks = {}) {
22
22
  if ((meta.status === "running" || meta.status === "orphaned") && meta.supervisionInterruptedAt !== undefined && reconciliation.status === "lost") {
23
23
  const run = parseRunForLifecycle(meta.id);
24
24
  if (run.sawEnd && run.unmatchedToolCalls.length === 0) {
25
- return { reconciliation, finalization: finalizeRun(meta.id, null, hooks) };
25
+ return { reconciliation, finalization: finalizeRun(meta.id, null, { ...hooks, recoveredWriterExit: true }) };
26
26
  }
27
27
  }
28
28
  return { reconciliation };
@@ -33,15 +33,15 @@ export function reconcileInterruptedRun(meta, probe, now, hooks = {}) {
33
33
  * and builds the completion callback delivery from real log evidence.
34
34
  */
35
35
  export function finalizeRun(id, code, hooks = {}) {
36
- const meta = readMeta(id);
36
+ const initial = readMeta(id);
37
37
  // Coherent child-exit evidence may supersede provisional orphaned/lost
38
38
  // reconciliation, but never overwrites a true terminal record.
39
- if (!meta || !canExitFinalize(meta.status))
39
+ if (!initial || !canExitFinalize(initial.status))
40
40
  return { applied: false };
41
41
  // Lifecycle authority streams the complete NDJSON log; result text stays bounded.
42
42
  const r = parseRunForLifecycle(id);
43
43
  const outcome = classifyChildExit(code, r);
44
- collectRunFailures(id, meta.cwd, true);
44
+ collectRunFailures(id, initial.cwd, true);
45
45
  // A run can now end exit 0 as failed (a final request the model could not
46
46
  // serve), so "not incomplete and has an exit code" no longer means success.
47
47
  const completed = outcome.status === "completed";
@@ -59,42 +59,49 @@ export function finalizeRun(id, code, hooks = {}) {
59
59
  operation: "child-exit", kind: outcome.incomplete ? "incomplete" : "failure",
60
60
  category: "exit", summary }]);
61
61
  }
62
- meta.status = outcome.status;
63
- meta.lifecycleClassification = outcome.classification;
64
- if (outcome.incomplete)
65
- meta.failureReason = "incomplete-stream";
66
- meta.exitCode = code;
67
- meta.endedAt = Date.now();
68
62
  // A clean park finishes this ATTEMPT, not the assignment. It is only accepted
69
63
  // with a durable park record whose saved-conversation checkpoint still
70
64
  // verifies; a failed, incoherent or unverifiable exit stays an ordinary exit
71
65
  // and the recorded wait is held for its owner.
72
66
  const park = evaluateParkDisposition({
73
67
  runId: id,
74
- cleanExit: code === 0 && !outcome.incomplete && !outcome.diagnostics.modelError,
68
+ // Preserve a verified staged checkpoint for post-restart park recovery.
69
+ // The coordinator still requires writer-exit and lease-release proof.
70
+ cleanExit: (code === 0 || (code === null && hooks.recoveredWriterExit === true))
71
+ && completed && !outcome.incomplete && !outcome.diagnostics.modelError,
75
72
  });
76
73
  const parked = park.parked && park.record !== undefined;
77
- if (parked && park.record) {
78
- meta.park = park.record;
79
- // The rest of the attempt is complete; the assignment is still waiting.
80
- meta.status = "completed";
81
- }
74
+ const endedAt = Date.now();
75
+ const meta = writeMeta(initial, { patch: current => {
76
+ if (!canExitFinalize(current.status))
77
+ return undefined;
78
+ const patch = {
79
+ status: outcome.status,
80
+ lifecycleClassification: outcome.classification,
81
+ ...(outcome.incomplete ? { failureReason: "incomplete-stream" } : {}),
82
+ exitCode: code,
83
+ endedAt,
84
+ };
85
+ if (parked && park.record)
86
+ patch.park = park.record;
87
+ if (current.callback !== false
88
+ && current.completionCallbackPendingAt === undefined
89
+ && current.completionCallbackSentAt === undefined
90
+ && current.completionCallbackSuppressedAt === undefined) {
91
+ if (parked) {
92
+ // The continuation reports the assignment's result.
93
+ patch.completionCallbackSuppressedAt = endedAt;
94
+ patch.completionCallbackSuppressedReason = `parked on wait ${park.record?.waitId} generation ${park.record?.generation}`;
95
+ }
96
+ else {
97
+ patch.completionCallbackPendingAt = endedAt;
98
+ }
99
+ }
100
+ return patch;
101
+ } });
102
+ if (!meta)
103
+ return { applied: false };
82
104
  const callback = meta.callback !== false;
83
- if (callback
84
- && meta.completionCallbackPendingAt === undefined
85
- && meta.completionCallbackSentAt === undefined
86
- && meta.completionCallbackSuppressedAt === undefined) {
87
- if (parked) {
88
- // A parked attempt owes no completion callback: the continuation
89
- // resumes the same conversation and reports the assignment's result.
90
- meta.completionCallbackSuppressedAt = meta.endedAt;
91
- meta.completionCallbackSuppressedReason = `parked on wait ${park.record?.waitId} generation ${park.record?.generation}`;
92
- }
93
- else {
94
- meta.completionCallbackPendingAt = meta.endedAt;
95
- }
96
- }
97
- writeMeta(meta);
98
105
  commitAssignmentTerminal(meta);
99
106
  if (!parked && park.record) {
100
107
  // A park disposition existed but could not be proven on exit. Hold it in
@@ -109,7 +116,7 @@ export function finalizeRun(id, code, hooks = {}) {
109
116
  const verdict = parked
110
117
  ? `parked · waiting for ${park.record?.waitId ?? "its dependency"}`
111
118
  : outcome.verdict;
112
- const el = fmtElapsed(meta.endedAt - meta.startedAt);
119
+ const el = fmtElapsed(endedAt - meta.startedAt);
113
120
  const spend = fmtSpend(r.usage);
114
121
  const humanStat = `${el}${spend ? ` · ${spend}` : ""}`;
115
122
  const stat = el;
@@ -29,6 +29,8 @@ import { evaluateParkDisposition, type ParkDisposition } from "./worker-waits.ts
29
29
  import { reconcileRun, type ProcessProbe, type ReconcileResult } from "./health.ts";
30
30
 
31
31
  export interface FinalizeHooks {
32
+ /** Recovery proved the original writer gone; the exit observer was lost. */
33
+ recoveredWriterExit?: boolean;
32
34
  renderWidget?: () => void;
33
35
  notify?: (message: string, level: "info" | "warning") => void;
34
36
  sendMessage?: (
@@ -54,7 +56,7 @@ export function reconcileInterruptedRun(meta: RunMeta, probe: ProcessProbe, now:
54
56
  if ((meta.status === "running" || meta.status === "orphaned") && meta.supervisionInterruptedAt !== undefined && reconciliation.status === "lost") {
55
57
  const run = parseRunForLifecycle(meta.id);
56
58
  if (run.sawEnd && run.unmatchedToolCalls.length === 0) {
57
- return { reconciliation, finalization: finalizeRun(meta.id, null, hooks) };
59
+ return { reconciliation, finalization: finalizeRun(meta.id, null, { ...hooks, recoveredWriterExit: true }) };
58
60
  }
59
61
  }
60
62
  return { reconciliation };
@@ -70,15 +72,15 @@ export function finalizeRun(
70
72
  code: number | null,
71
73
  hooks: FinalizeHooks = {},
72
74
  ): FinalizeResult {
73
- const meta = readMeta(id);
75
+ const initial = readMeta(id);
74
76
  // Coherent child-exit evidence may supersede provisional orphaned/lost
75
77
  // reconciliation, but never overwrites a true terminal record.
76
- if (!meta || !canExitFinalize(meta.status)) return { applied: false };
78
+ if (!initial || !canExitFinalize(initial.status)) return { applied: false };
77
79
 
78
80
  // Lifecycle authority streams the complete NDJSON log; result text stays bounded.
79
81
  const r = parseRunForLifecycle(id);
80
82
  const outcome = classifyChildExit(code, r);
81
- collectRunFailures(id, meta.cwd, true);
83
+ collectRunFailures(id, initial.cwd, true);
82
84
  // A run can now end exit 0 as failed (a final request the model could not
83
85
  // serve), so "not incomplete and has an exit code" no longer means success.
84
86
  const completed = outcome.status === "completed";
@@ -96,40 +98,45 @@ export function finalizeRun(
96
98
  operation: "child-exit", kind: outcome.incomplete ? "incomplete" : "failure",
97
99
  category: "exit", summary }]);
98
100
  }
99
- meta.status = outcome.status;
100
- meta.lifecycleClassification = outcome.classification;
101
- if (outcome.incomplete) meta.failureReason = "incomplete-stream";
102
- meta.exitCode = code;
103
- meta.endedAt = Date.now();
104
101
  // A clean park finishes this ATTEMPT, not the assignment. It is only accepted
105
102
  // with a durable park record whose saved-conversation checkpoint still
106
103
  // verifies; a failed, incoherent or unverifiable exit stays an ordinary exit
107
104
  // and the recorded wait is held for its owner.
108
105
  const park = evaluateParkDisposition({
109
106
  runId: id,
110
- cleanExit: code === 0 && !outcome.incomplete && !outcome.diagnostics.modelError,
107
+ // Preserve a verified staged checkpoint for post-restart park recovery.
108
+ // The coordinator still requires writer-exit and lease-release proof.
109
+ cleanExit: (code === 0 || (code === null && hooks.recoveredWriterExit === true))
110
+ && completed && !outcome.incomplete && !outcome.diagnostics.modelError,
111
111
  });
112
112
  const parked = park.parked && park.record !== undefined;
113
- if (parked && park.record) {
114
- meta.park = park.record;
115
- // The rest of the attempt is complete; the assignment is still waiting.
116
- meta.status = "completed";
117
- }
118
- const callback = meta.callback !== false;
119
- if (callback
120
- && meta.completionCallbackPendingAt === undefined
121
- && meta.completionCallbackSentAt === undefined
122
- && meta.completionCallbackSuppressedAt === undefined) {
123
- if (parked) {
124
- // A parked attempt owes no completion callback: the continuation
125
- // resumes the same conversation and reports the assignment's result.
126
- meta.completionCallbackSuppressedAt = meta.endedAt;
127
- meta.completionCallbackSuppressedReason = `parked on wait ${park.record?.waitId} generation ${park.record?.generation}`;
128
- } else {
129
- meta.completionCallbackPendingAt = meta.endedAt;
113
+ const endedAt = Date.now();
114
+ const meta = writeMeta(initial, { patch: current => {
115
+ if (!canExitFinalize(current.status)) return undefined;
116
+ const patch: Partial<RunMeta> = {
117
+ status: outcome.status,
118
+ lifecycleClassification: outcome.classification,
119
+ ...(outcome.incomplete ? { failureReason: "incomplete-stream" } : {}),
120
+ exitCode: code,
121
+ endedAt,
122
+ };
123
+ if (parked && park.record) patch.park = park.record;
124
+ if (current.callback !== false
125
+ && current.completionCallbackPendingAt === undefined
126
+ && current.completionCallbackSentAt === undefined
127
+ && current.completionCallbackSuppressedAt === undefined) {
128
+ if (parked) {
129
+ // The continuation reports the assignment's result.
130
+ patch.completionCallbackSuppressedAt = endedAt;
131
+ patch.completionCallbackSuppressedReason = `parked on wait ${park.record?.waitId} generation ${park.record?.generation}`;
132
+ } else {
133
+ patch.completionCallbackPendingAt = endedAt;
134
+ }
130
135
  }
131
- }
132
- writeMeta(meta);
136
+ return patch;
137
+ } });
138
+ if (!meta) return { applied: false };
139
+ const callback = meta.callback !== false;
133
140
  commitAssignmentTerminal(meta);
134
141
  if (!parked && park.record) {
135
142
  // A park disposition existed but could not be proven on exit. Hold it in
@@ -145,7 +152,7 @@ export function finalizeRun(
145
152
  const verdict = parked
146
153
  ? `parked · waiting for ${park.record?.waitId ?? "its dependency"}`
147
154
  : outcome.verdict;
148
- const el = fmtElapsed(meta.endedAt - meta.startedAt);
155
+ const el = fmtElapsed(endedAt - meta.startedAt);
149
156
  const spend = fmtSpend(r.usage);
150
157
  const humanStat = `${el}${spend ? ` · ${spend}` : ""}`;
151
158
  const stat = el;
@@ -21,21 +21,27 @@
21
21
  */
22
22
  import { execFileSync } from "node:child_process";
23
23
  import { existsSync, lstatSync, mkdirSync, realpathSync } from "node:fs";
24
- import { dirname, join, resolve } from "node:path";
24
+ import { dirname, join, relative, resolve } from "node:path";
25
25
  import { readGitRemotes, syncGitRemotes } from "./git-remotes.domain.mjs";
26
26
  export { readGitRemotes, syncGitRemotes };
27
- function runGit(cwd, args, opts) {
27
+ const GIT_WORKSPACE_COMMAND_TIMEOUT_MS = 60_000;
28
+ function runGit(cwd, args, env) {
28
29
  try {
29
30
  return execFileSync("git", args, {
30
31
  cwd,
31
32
  encoding: "utf-8",
32
33
  stdio: ["ignore", "pipe", "pipe"],
33
- ...opts,
34
+ env: { ...(env ?? process.env), GIT_TERMINAL_PROMPT: "0" },
35
+ timeout: GIT_WORKSPACE_COMMAND_TIMEOUT_MS,
36
+ killSignal: "SIGKILL",
34
37
  }).trim();
35
38
  }
36
39
  catch (err) {
40
+ if (err.code === "ETIMEDOUT") {
41
+ throw new Error(`git ${args[0]} timed out after ${GIT_WORKSPACE_COMMAND_TIMEOUT_MS / 1_000} seconds in ${cwd}`, { cause: err });
42
+ }
37
43
  const message = err.message ?? String(err);
38
- throw new Error(`git ${args.join(" ")} failed in ${cwd}: ${message}`);
44
+ throw new Error(`git ${args.join(" ")} failed in ${cwd}: ${message}`, { cause: err });
39
45
  }
40
46
  }
41
47
  /** Resolve `path` to an absolute, real path. Falls back to resolve() if the path does not exist. */
@@ -226,6 +232,45 @@ function hasLinkedWorktreePointer(dir) {
226
232
  return false;
227
233
  }
228
234
  }
235
+ /** An ignored subdirectory can contain a separate, non-Git workspace. */
236
+ export function isIgnoredGitSubdirectory(root, subdir) {
237
+ if (!subdir)
238
+ return false;
239
+ try {
240
+ runGit(root, ["-c", "core.fsmonitor=false", "check-ignore", "--quiet", "--", subdir], Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_"))));
241
+ return true;
242
+ }
243
+ catch (error) {
244
+ if (error.cause?.status === 1)
245
+ return false;
246
+ throw error;
247
+ }
248
+ }
249
+ /** Locate shared metadata even when a caller supplies a subdirectory of the checkout. */
250
+ export function linkedWorktreeGitDir(cwd) {
251
+ const workspace = realPath(cwd);
252
+ let directory = workspace;
253
+ for (;;) {
254
+ const gitMarker = join(directory, ".git");
255
+ if (existsSync(gitMarker)) {
256
+ if (!hasLinkedWorktreePointer(directory))
257
+ return undefined;
258
+ try {
259
+ const info = inspectGitWorkspace(directory);
260
+ if (isIgnoredGitSubdirectory(info.repoRoot, relative(info.repoRoot, workspace)))
261
+ return undefined;
262
+ return info.gitDir;
263
+ }
264
+ catch {
265
+ throw linkedWorktreeError(directory);
266
+ }
267
+ }
268
+ const parent = dirname(directory);
269
+ if (parent === directory)
270
+ return undefined;
271
+ directory = parent;
272
+ }
273
+ }
229
274
  export function prepareGitCloneWorkspace(options) {
230
275
  const sourceDir = realPath(options.sourceDir);
231
276
  const targetDir = realPath(options.targetDir);
@@ -263,11 +308,11 @@ export function prepareGitCloneWorkspace(options) {
263
308
  // a normal clone. --dissociate removes the alternates link after setup.
264
309
  const cloneArgs = buildGitCloneArgs({ referenceRepo, cloneUrl, targetDir });
265
310
  try {
266
- runGit(dirname(targetDir), cloneArgs, { stdio: ["ignore", "pipe", "pipe"] });
311
+ runGit(dirname(targetDir), cloneArgs);
267
312
  }
268
313
  catch (err) {
269
314
  if (info.isLinkedWorktree) {
270
- throw linkedWorktreeError(sourceDir);
315
+ throw new Error(`${linkedWorktreeError(sourceDir).message} Clone preparation failed: ${err.message}`);
271
316
  }
272
317
  throw err;
273
318
  }
@@ -21,7 +21,7 @@
21
21
 
22
22
  import { execFileSync } from "node:child_process";
23
23
  import { existsSync, lstatSync, mkdirSync, realpathSync } from "node:fs";
24
- import { dirname, join, resolve } from "node:path";
24
+ import { dirname, join, relative, resolve } from "node:path";
25
25
 
26
26
  import { readGitRemotes, syncGitRemotes, type GitRemote } from "./git-remotes.ts";
27
27
 
@@ -38,17 +38,24 @@ export interface GitWorkspaceInfo {
38
38
  isLinkedWorktree: boolean;
39
39
  }
40
40
 
41
- function runGit(cwd: string, args: string[], opts?: { encoding?: BufferEncoding; stdio?: any }): string {
41
+ const GIT_WORKSPACE_COMMAND_TIMEOUT_MS = 60_000;
42
+
43
+ function runGit(cwd: string, args: string[], env?: NodeJS.ProcessEnv): string {
42
44
  try {
43
45
  return execFileSync("git", args, {
44
46
  cwd,
45
47
  encoding: "utf-8",
46
48
  stdio: ["ignore", "pipe", "pipe"],
47
- ...opts,
49
+ env: { ...(env ?? process.env), GIT_TERMINAL_PROMPT: "0" },
50
+ timeout: GIT_WORKSPACE_COMMAND_TIMEOUT_MS,
51
+ killSignal: "SIGKILL",
48
52
  }).trim();
49
53
  } catch (err) {
54
+ if ((err as NodeJS.ErrnoException).code === "ETIMEDOUT") {
55
+ throw new Error(`git ${args[0]} timed out after ${GIT_WORKSPACE_COMMAND_TIMEOUT_MS / 1_000} seconds in ${cwd}`, { cause: err });
56
+ }
50
57
  const message = (err as Error).message ?? String(err);
51
- throw new Error(`git ${args.join(" ")} failed in ${cwd}: ${message}`);
58
+ throw new Error(`git ${args.join(" ")} failed in ${cwd}: ${message}`, { cause: err });
52
59
  }
53
60
  }
54
61
 
@@ -298,6 +305,41 @@ function hasLinkedWorktreePointer(dir: string): boolean {
298
305
  }
299
306
  }
300
307
 
308
+ /** An ignored subdirectory can contain a separate, non-Git workspace. */
309
+ export function isIgnoredGitSubdirectory(root: string, subdir: string): boolean {
310
+ if (!subdir) return false;
311
+ try {
312
+ runGit(root, ["-c", "core.fsmonitor=false", "check-ignore", "--quiet", "--", subdir],
313
+ Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_"))));
314
+ return true;
315
+ } catch (error) {
316
+ if (((error as Error).cause as { status?: number } | undefined)?.status === 1) return false;
317
+ throw error;
318
+ }
319
+ }
320
+
321
+ /** Locate shared metadata even when a caller supplies a subdirectory of the checkout. */
322
+ export function linkedWorktreeGitDir(cwd: string): string | undefined {
323
+ const workspace = realPath(cwd);
324
+ let directory = workspace;
325
+ for (;;) {
326
+ const gitMarker = join(directory, ".git");
327
+ if (existsSync(gitMarker)) {
328
+ if (!hasLinkedWorktreePointer(directory)) return undefined;
329
+ try {
330
+ const info = inspectGitWorkspace(directory);
331
+ if (isIgnoredGitSubdirectory(info.repoRoot, relative(info.repoRoot, workspace))) return undefined;
332
+ return info.gitDir;
333
+ } catch {
334
+ throw linkedWorktreeError(directory);
335
+ }
336
+ }
337
+ const parent = dirname(directory);
338
+ if (parent === directory) return undefined;
339
+ directory = parent;
340
+ }
341
+ }
342
+
301
343
  export function prepareGitCloneWorkspace(options: PrepareGitCloneWorkspaceOptions): string {
302
344
  const sourceDir = realPath(options.sourceDir);
303
345
  const targetDir = realPath(options.targetDir);
@@ -343,10 +385,10 @@ export function prepareGitCloneWorkspace(options: PrepareGitCloneWorkspaceOption
343
385
  const cloneArgs = buildGitCloneArgs({ referenceRepo, cloneUrl, targetDir });
344
386
 
345
387
  try {
346
- runGit(dirname(targetDir), cloneArgs, { stdio: ["ignore", "pipe", "pipe"] });
388
+ runGit(dirname(targetDir), cloneArgs);
347
389
  } catch (err) {
348
390
  if (info.isLinkedWorktree) {
349
- throw linkedWorktreeError(sourceDir);
391
+ throw new Error(`${linkedWorktreeError(sourceDir).message} Clone preparation failed: ${(err as Error).message}`);
350
392
  }
351
393
  throw err;
352
394
  }