@orbit-build/cli 0.8.5 → 0.8.6

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.
@@ -8,4 +8,6 @@ argumentHint: <项目目录;可附“生成/修订/仅审计”,留空使用
8
8
  逐页检查—交付包”,不得停在脚手架、提纲或示例段落。自动判断生成、修订或审计模式,保护题目原件,以最新代码和程序生成的
9
9
  JSON/CSV 为数值事实源,完成模型—代码—结果—图表—论文一致性核验、真实
10
10
  TeX Live 编译和逐页排版检查。不要只润色或给提纲;不得编造代码中不存在的
11
- 模型、算法、数据和数值。仅在会改变模型方向或可能误删重要资料时询问。
11
+ 模型、算法、数据和数值。最终 `paper/` 仅保留主论文、AI 使用详情及 PDF/ZIP
12
+ 交付物;每问的 `main.py` 只负责编排,真实建模与检验代码必须按职责拆分到同级
13
+ 模块,禁止用单文件脚手架冒充完成。仅在会改变模型方向或可能误删重要资料时询问。
package/dist/index.js CHANGED
@@ -242963,7 +242963,6 @@ async function fetchWithRetry(url, init, maxRetries = 3) {
242963
242963
  const timeoutId = setTimeout(() => {
242964
242964
  controller.abort();
242965
242965
  }, timeoutMs);
242966
- timeoutId.unref?.();
242967
242966
  try {
242968
242967
  const response = await fetch(url, {
242969
242968
  ...init,
@@ -243036,6 +243035,33 @@ function sanitizeProviderError(value, secrets = [], fallbackMessage = "Unknown p
243036
243035
  error.name = source.name;
243037
243036
  return error;
243038
243037
  }
243038
+ function normalizeProviderStreamError(value, secrets = [], partialOutput = false) {
243039
+ const source = sanitizeProviderError(value, secrets);
243040
+ if (source.name === "AbortError") return source;
243041
+ if (source instanceof ProviderError) {
243042
+ return new ProviderError(source.code, source.message, {
243043
+ status: source.status,
243044
+ retryAfterMs: source.retryAfterMs,
243045
+ requestId: source.requestId,
243046
+ retryable: source.retryable,
243047
+ partialOutput,
243048
+ cause: source.cause
243049
+ });
243050
+ }
243051
+ const timeout = source.name === "TimeoutError" || /(?:timed?\s*out|timeout)/i.test(source.message);
243052
+ const closed = /(?:\bterminated\b|premature(?:ly)?\s+closed|other side closed|socket(?:\s+hang\s+up|\s+closed)?|stream (?:ended|closed) before|fetch failed|network connection (?:was )?lost|ECONNRESET|EPIPE|UND_ERR_(?:SOCKET|ABORTED))/i.test(
243053
+ source.message
243054
+ );
243055
+ return new ProviderError(
243056
+ timeout ? "TIMEOUT" : closed ? "STREAM_CLOSED" : "MALFORMED_RESPONSE",
243057
+ source.message,
243058
+ {
243059
+ retryable: timeout || closed,
243060
+ partialOutput,
243061
+ cause: source
243062
+ }
243063
+ );
243064
+ }
243039
243065
  function providerHttpError(provider, status, responseBody, secrets = [], metadata = {}) {
243040
243066
  const detail = sanitizeProviderErrorText(responseBody, secrets);
243041
243067
  const normalized = detail.toLowerCase();
@@ -243084,7 +243110,6 @@ function abortableDelay(delayMs, signal) {
243084
243110
  cleanup();
243085
243111
  resolve26();
243086
243112
  }, delayMs);
243087
- timeoutId.unref?.();
243088
243113
  function onAbort() {
243089
243114
  clearTimeout(timeoutId);
243090
243115
  cleanup();
@@ -243736,9 +243761,14 @@ var AnthropicCompatibleProvider = class {
243736
243761
  this.options.maxRetries ?? (this.isOfficialDeepSeekEndpoint() ? 0 : 2)
243737
243762
  );
243738
243763
  } catch (error) {
243764
+ const sanitized = sanitizeProviderError(error, [key]);
243739
243765
  yield {
243740
243766
  type: "error",
243741
- error: sanitizeProviderError(error, [key])
243767
+ error: isProviderError(sanitized) ? sanitized : new ProviderError(
243768
+ sanitized.name === "TimeoutError" ? "TIMEOUT" : "TRANSPORT",
243769
+ sanitized.message,
243770
+ { retryable: true, cause: sanitized }
243771
+ )
243742
243772
  };
243743
243773
  return;
243744
243774
  }
@@ -244073,9 +244103,14 @@ var AnthropicCompatibleProvider = class {
244073
244103
  yield { type: "done" };
244074
244104
  }
244075
244105
  } catch (error) {
244106
+ const abortReason = chatController.signal.aborted ? chatController.signal.reason : input.abortSignal?.aborted ? input.abortSignal.reason : void 0;
244076
244107
  yield {
244077
244108
  type: "error",
244078
- error: sanitizeProviderError(error, [key])
244109
+ error: normalizeProviderStreamError(
244110
+ abortReason ?? error,
244111
+ [key],
244112
+ emittedToolCalls > 0
244113
+ )
244079
244114
  };
244080
244115
  } finally {
244081
244116
  if (streamTimeoutId) clearTimeout(streamTimeoutId);
@@ -244500,7 +244535,6 @@ async function* parseStreamingResponse(input, options, response, controller) {
244500
244535
  )
244501
244536
  );
244502
244537
  }, streamTimeoutMs);
244503
- timeoutId.unref?.();
244504
244538
  };
244505
244539
  const outputKey = (outputIndex, itemId) => {
244506
244540
  const aliased = itemId ? outputAliases.get(itemId) : void 0;
@@ -244736,25 +244770,11 @@ async function* parseStreamingResponse(input, options, response, controller) {
244736
244770
  );
244737
244771
  }
244738
244772
  } catch (error) {
244739
- const source = toError(error);
244740
- if (source instanceof ProviderError) {
244741
- throw new ProviderError(source.code, source.message, {
244742
- status: source.status,
244743
- retryAfterMs: source.retryAfterMs,
244744
- requestId: source.requestId,
244745
- retryable: source.retryable,
244746
- partialOutput: emittedOutput || tools.size > 0,
244747
- cause: source.cause
244748
- });
244749
- }
244750
- throw new ProviderError(
244751
- source.name === "TimeoutError" ? "TIMEOUT" : "MALFORMED_RESPONSE",
244752
- source.message,
244753
- {
244754
- retryable: source.name === "TimeoutError",
244755
- partialOutput: emittedOutput || tools.size > 0,
244756
- cause: source
244757
- }
244773
+ const abortReason = controller.signal.aborted ? controller.signal.reason : input.abortSignal?.aborted ? input.abortSignal.reason : void 0;
244774
+ throw normalizeProviderStreamError(
244775
+ abortReason ?? error,
244776
+ [options.apiKey],
244777
+ emittedOutput || tools.size > 0
244758
244778
  );
244759
244779
  } finally {
244760
244780
  if (timeoutId) clearTimeout(timeoutId);
@@ -245876,22 +245896,11 @@ ${jsonInstruction}`;
245876
245896
  yield { type: "done" };
245877
245897
  }
245878
245898
  } catch (error) {
245879
- const sanitized = sanitizeProviderError(error, [key]);
245880
- const streamError = isProviderError(sanitized) ? new ProviderError(sanitized.code, sanitized.message, {
245881
- status: sanitized.status,
245882
- retryAfterMs: sanitized.retryAfterMs,
245883
- requestId: sanitized.requestId,
245884
- retryable: sanitized.retryable,
245885
- partialOutput: emittedOutput || streamingTools.size > 0,
245886
- cause: sanitized.cause
245887
- }) : new ProviderError(
245888
- sanitized.name === "TimeoutError" ? "TIMEOUT" : "MALFORMED_RESPONSE",
245889
- sanitized.message,
245890
- {
245891
- retryable: sanitized.name === "TimeoutError",
245892
- partialOutput: emittedOutput || streamingTools.size > 0,
245893
- cause: sanitized
245894
- }
245899
+ const abortReason = chatController.signal.aborted ? chatController.signal.reason : input.abortSignal?.aborted ? input.abortSignal.reason : void 0;
245900
+ const streamError = normalizeProviderStreamError(
245901
+ abortReason ?? error,
245902
+ [key],
245903
+ emittedOutput || streamingTools.size > 0
245895
245904
  );
245896
245905
  yield {
245897
245906
  type: "error",
@@ -249646,7 +249655,7 @@ var BashInputSchema = z17.object({
249646
249655
  });
249647
249656
  var BashTool = class {
249648
249657
  name = "bash";
249649
- description = process.platform === "win32" ? "Run a command in native Windows PowerShell. The working directory is already the project root: use PowerShell cmdlets and do not prepend cd or use POSIX grep/sed/head/tail/heredoc syntax. Set background=true only for dev servers, watchers, or long builds." : "Run a command in non-interactive Bash/POSIX sh. The working directory is already the project root; do not prepend cd. Set background=true only for dev servers, watchers, or long builds.";
249658
+ description = process.platform === "win32" ? "Run a command in native Windows PowerShell. The working directory is already the project root: use PowerShell cmdlets and do not prepend cd or use POSIX grep/sed/head/tail/heredoc syntax. A failed result already includes captured stdout/stderr, so diagnose that output instead of rerunning the same command through redirection. Set background=true only for dev servers, watchers, or long builds." : "Run a command in non-interactive Bash/POSIX sh. The working directory is already the project root; do not prepend cd. A failed result already includes captured stdout/stderr, so diagnose that output instead of rerunning the same command through redirection. Set background=true only for dev servers, watchers, or long builds.";
249650
249659
  inputSchema = BashInputSchema;
249651
249660
  risk = "execute";
249652
249661
  async execute(input, ctx) {
@@ -250988,7 +250997,6 @@ var WebSearchTool = class {
250988
250997
  const controller = new AbortController();
250989
250998
  const abort = () => controller.abort();
250990
250999
  const timeoutId = setTimeout(abort, timeoutMs);
250991
- timeoutId.unref?.();
250992
251000
  if (parentSignal) {
250993
251001
  if (parentSignal.aborted) {
250994
251002
  controller.abort();
@@ -251746,7 +251754,6 @@ async function waitWithTimeout(promise, timeoutMs, abortSignal) {
251746
251754
  promise.then(() => true),
251747
251755
  new Promise((resolve43) => {
251748
251756
  timeout = setTimeout(() => resolve43(false), timeoutMs);
251749
- timeout.unref?.();
251750
251757
  }),
251751
251758
  new Promise((resolve43) => {
251752
251759
  if (!abortSignal) return;
@@ -253934,6 +253941,28 @@ var CODEBASE_FORCE_MARKER_ALL = /@codebase\b/gi;
253934
253941
  var CODEBASE_DISABLE_MARKER_ALL = /@no-codebase\b/gi;
253935
253942
  var CODE_INTENT = /\b(?:implement|fix|debug|refactor|review|inspect|trace|codebase|repository|repo|function|class|module|dependency|build|test|error|stack\s*trace)\b|(?:实现|修改|修复|调试|重构|审查|检查|代码|项目|仓库|函数|类|模块|依赖|构建|测试|报错|异常|架构)/i;
253936
253943
  var SOURCE_REFERENCE = /(?:^|[\s`'"(])[^\s`'"()]+\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs|py|pyw)(?=$|[\s`'"),:])/i;
253944
+ var CODEBASE_CONTEXT_BUDGETS = {
253945
+ automatic: {
253946
+ queryTokens: 256,
253947
+ searchTokens: 3072,
253948
+ referenceTokens: 1024,
253949
+ repoMapTokens: 512,
253950
+ totalTokens: 6144,
253951
+ resultLimit: 4,
253952
+ referencesPerSymbol: 2,
253953
+ totalReferences: 6
253954
+ },
253955
+ explicit: {
253956
+ queryTokens: 512,
253957
+ searchTokens: 8192,
253958
+ referenceTokens: 4096,
253959
+ repoMapTokens: 2048,
253960
+ totalTokens: 16384,
253961
+ resultLimit: 8,
253962
+ referencesPerSymbol: 3,
253963
+ totalReferences: 12
253964
+ }
253965
+ };
253937
253966
  function selectCodebaseRetrievalMode(userQuery, autoEnabled) {
253938
253967
  if (!userQuery || CODEBASE_DISABLE_MARKER.test(userQuery)) return "off";
253939
253968
  if (CODEBASE_FORCE_MARKER.test(userQuery)) {
@@ -253955,9 +253984,13 @@ var CodebaseContextRetriever = class {
253955
253984
  cwd;
253956
253985
  retrieval;
253957
253986
  async retrieve(userQuery, config, mode) {
253987
+ const budget = CODEBASE_CONTEXT_BUDGETS[mode];
253958
253988
  const cleanQuery = cleanCodebaseQuery(userQuery);
253959
- const searchQuery = cleanQuery || "repository architecture and entrypoints";
253960
- const prepared = await this.retrieval.prepare(2048);
253989
+ const searchQuery = truncateTextToTokenBudget(
253990
+ cleanQuery || "repository architecture and entrypoints",
253991
+ budget.queryTokens
253992
+ );
253993
+ const prepared = await this.retrieval.prepare(budget.repoMapTokens);
253961
253994
  let chunksText = "";
253962
253995
  let referencesText = "";
253963
253996
  try {
@@ -253973,14 +254006,17 @@ var CodebaseContextRetriever = class {
253973
254006
  return provider.embed(texts, { model: modelName });
253974
254007
  };
253975
254008
  const results = await prepared.search.search(searchQuery, embedFn, {
253976
- limit: 5
254009
+ limit: budget.resultLimit
253977
254010
  });
253978
254011
  if (results.length > 0) {
253979
- chunksText = results.map(
253980
- (result, index) => `--- Search Match #${index + 1} (Score: ${result.hybridScore.toFixed(4)}) ---
254012
+ chunksText = truncateTextToTokenBudget(
254013
+ results.map(
254014
+ (result, index) => `--- Search Match #${index + 1} (Score: ${result.hybridScore.toFixed(4)}) ---
253981
254015
  ${result.text}
253982
254016
  `
253983
- ).join("\n");
254017
+ ).join("\n"),
254018
+ budget.searchTokens
254019
+ );
253984
254020
  const referencedSymbols = Array.from(
253985
254021
  new Set(
253986
254022
  results.map((result) => result.metadata.symbolName).filter((name) => Boolean(name))
@@ -253989,7 +254025,15 @@ ${result.text}
253989
254025
  if (referencedSymbols.length > 0) {
253990
254026
  referencesText = await new ReferencesRetriever(
253991
254027
  this.cwd
253992
- ).getReferencesContext(referencedSymbols);
254028
+ ).getReferencesContext(
254029
+ referencedSymbols,
254030
+ budget.referencesPerSymbol,
254031
+ budget.totalReferences
254032
+ );
254033
+ referencesText = truncateTextToTokenBudget(
254034
+ referencesText,
254035
+ budget.referenceTokens
254036
+ );
253993
254037
  }
253994
254038
  } else {
253995
254039
  chunksText = "(No relevant code matches found in search index.)\n";
@@ -254001,13 +254045,18 @@ ${result.text}
254001
254045
  chunksText = `(RAG retrieval failed: ${message2})
254002
254046
  `;
254003
254047
  }
254004
- return `=== ${mode === "explicit" ? "Requested" : "Automatic"} Codebase Search Context for Query: "${searchQuery}" ===
254048
+ const repoMap = truncateTextToTokenBudget(
254049
+ prepared.repoMap || "(No landmarks mapped.)",
254050
+ budget.repoMapTokens
254051
+ );
254052
+ const context = `=== ${mode === "explicit" ? "Requested" : "Automatic"} Codebase Search Context for Query: "${searchQuery}" ===
254005
254053
  Use the following repository evidence when it is relevant; verify files before editing.
254006
254054
 
254007
254055
  ${chunksText}
254008
254056
  ${referencesText}=== Codebase Landmark Repo Map ===
254009
- ${prepared.repoMap || "(No landmarks mapped.)"}
254057
+ ${repoMap}
254010
254058
  ================================================================`;
254059
+ return truncateTextToTokenBudget(context, budget.totalTokens);
254011
254060
  }
254012
254061
  };
254013
254062
  var IGNORED_DIRECTORY_NAMES = /* @__PURE__ */ new Set([
@@ -254053,6 +254102,7 @@ var WEAK_TERM_SCORE = 1;
254053
254102
  var NAME_MENTION_SCORE = 8;
254054
254103
  var STRONG_TERM_MIN_LENGTH = 5;
254055
254104
  var MIN_AUTO_SCORE = 3;
254105
+ var MIN_AUTO_MATCHED_TERMS = 2;
254056
254106
  function normalizePath3(path9) {
254057
254107
  return path9.replace(/\\/g, "/");
254058
254108
  }
@@ -254397,13 +254447,18 @@ function selectSkills(skills, userQuery, config) {
254397
254447
  if (!explicit2 && config.activation === "auto" && skill.allowImplicitInvocation) {
254398
254448
  const metadata = normalize2(`${skill.name} ${skill.description}`);
254399
254449
  const metadataTerms = new Set(terms(metadata));
254450
+ let matchedTerms = 0;
254400
254451
  for (const term of queryTerms) {
254401
254452
  if (metadataTerms.has(term)) {
254453
+ matchedTerms += 1;
254402
254454
  score += term.length >= STRONG_TERM_MIN_LENGTH ? STRONG_TERM_SCORE : WEAK_TERM_SCORE;
254403
254455
  }
254404
254456
  }
254405
- if (mentionsName(query, name)) score += NAME_MENTION_SCORE;
254406
- if (score < MIN_AUTO_SCORE) score = 0;
254457
+ const nameMentioned = mentionsName(query, name);
254458
+ if (nameMentioned) score += NAME_MENTION_SCORE;
254459
+ if (score < MIN_AUTO_SCORE || !nameMentioned && matchedTerms < MIN_AUTO_MATCHED_TERMS) {
254460
+ score = 0;
254461
+ }
254407
254462
  }
254408
254463
  return { skill, explicit: explicit2, score };
254409
254464
  }).filter(({ score }) => score > 0).sort(
@@ -257989,8 +258044,13 @@ var WorktreeManager = class {
257989
258044
  );
257990
258045
  }
257991
258046
  }
258047
+ const baseCommit = this.git(["rev-parse", "HEAD"]).trim();
257992
258048
  this.git(["worktree", "add", "-b", branchName, worktreePath, "HEAD"]);
257993
- const session = { path: worktreePath, branchName };
258049
+ const session = {
258050
+ path: worktreePath,
258051
+ branchName,
258052
+ baseCommit
258053
+ };
257994
258054
  if (options.snapshotWorkingTree) {
257995
258055
  try {
257996
258056
  session.baselineCommit = this.snapshotWorkingTree(worktreePath);
@@ -258020,19 +258080,7 @@ var WorktreeManager = class {
258020
258080
  };
258021
258081
  }
258022
258082
  try {
258023
- this.git(["add", "-A"], session.path);
258024
- if (this.git(["status", "--porcelain"], session.path).trim()) {
258025
- this.git(
258026
- [
258027
- "commit",
258028
- "--no-verify",
258029
- "--no-gpg-sign",
258030
- "-m",
258031
- "subagent automatic worktree commit"
258032
- ],
258033
- session.path
258034
- );
258035
- }
258083
+ this.commitWorktreeChanges(session);
258036
258084
  } catch (error) {
258037
258085
  return {
258038
258086
  success: false,
@@ -258075,6 +258123,97 @@ var WorktreeManager = class {
258075
258123
  }
258076
258124
  return { success: true };
258077
258125
  }
258126
+ /**
258127
+ * Combine independent writer deltas inside another managed worktree. The
258128
+ * main workspace remains untouched until the integration worktree passes
258129
+ * review and is merged with `mergeAndCleanup`.
258130
+ */
258131
+ integrateWorktrees(sources, target) {
258132
+ try {
258133
+ this.assertManagedSession(target);
258134
+ for (const source of sources) {
258135
+ this.assertManagedSession(source);
258136
+ if (path4.resolve(source.path) === path4.resolve(target.path) || source.branchName === target.branchName) {
258137
+ throw new Error("A writer worktree cannot integrate into itself.");
258138
+ }
258139
+ }
258140
+ } catch (error) {
258141
+ return { success: false, error: toErrorMessage2(error), preserved: true };
258142
+ }
258143
+ let integratedCount = 0;
258144
+ try {
258145
+ for (const source of sources) {
258146
+ this.commitWorktreeChanges(source);
258147
+ const baseline = source.baselineCommit || source.baseCommit;
258148
+ if (!baseline) {
258149
+ throw new Error(
258150
+ `Writer worktree has no trusted baseline: ${source.branchName}`
258151
+ );
258152
+ }
258153
+ const delta = this.gitBuffer(
258154
+ ["diff", "--binary", baseline, source.branchName],
258155
+ source.path
258156
+ );
258157
+ if (delta.length > 0) {
258158
+ execFileSync4("git", ["apply", "--whitespace=nowarn", "-"], {
258159
+ ...HIDDEN_CHILD_PROCESS_OPTIONS,
258160
+ cwd: target.path,
258161
+ input: delta,
258162
+ stdio: ["pipe", "pipe", "pipe"],
258163
+ maxBuffer: 64 * 1024 * 1024
258164
+ });
258165
+ }
258166
+ integratedCount += 1;
258167
+ }
258168
+ } catch (error) {
258169
+ try {
258170
+ this.git(["reset", "--hard", "HEAD"], target.path);
258171
+ this.git(["clean", "-fd"], target.path);
258172
+ } catch {
258173
+ }
258174
+ return {
258175
+ success: false,
258176
+ integratedCount,
258177
+ error: `Failed to integrate writer changes: ${toErrorMessage2(error)}`,
258178
+ preserved: true
258179
+ };
258180
+ }
258181
+ const cleanupErrors = [];
258182
+ for (const source of sources) {
258183
+ try {
258184
+ this.discardWorktree(source);
258185
+ } catch (error) {
258186
+ cleanupErrors.push(`${source.branchName}: ${toErrorMessage2(error)}`);
258187
+ }
258188
+ }
258189
+ return {
258190
+ success: true,
258191
+ integratedCount,
258192
+ ...cleanupErrors.length ? {
258193
+ preserved: true,
258194
+ error: `Writer changes were integrated, but cleanup is incomplete: ${cleanupErrors.join(" | ")}`
258195
+ } : {}
258196
+ };
258197
+ }
258198
+ /** List the complete writer delta before integration or review. */
258199
+ listChangedFiles(session) {
258200
+ this.assertManagedSession(session);
258201
+ const baseline = session.baselineCommit || session.baseCommit;
258202
+ if (!baseline) {
258203
+ throw new Error(
258204
+ `Managed worktree has no trusted baseline: ${session.branchName}`
258205
+ );
258206
+ }
258207
+ const tracked = this.git(
258208
+ ["diff", "--name-only", "-z", baseline],
258209
+ session.path
258210
+ ).split("\0").filter(Boolean);
258211
+ const untracked = this.git(
258212
+ ["ls-files", "--others", "--exclude-standard", "-z"],
258213
+ session.path
258214
+ ).split("\0").filter(Boolean);
258215
+ return Array.from(/* @__PURE__ */ new Set([...tracked, ...untracked])).map((file) => file.replace(/\\/g, "/")).filter((file) => file !== ".orbit" && !file.startsWith(".orbit/")).sort();
258216
+ }
258078
258217
  discardWorktree(session) {
258079
258218
  this.assertManagedSession(session);
258080
258219
  if (fs4.existsSync(session.path)) {
@@ -258105,6 +258244,20 @@ var WorktreeManager = class {
258105
258244
  return [];
258106
258245
  }
258107
258246
  }
258247
+ commitWorktreeChanges(session) {
258248
+ this.git(["add", "-A"], session.path);
258249
+ if (!this.git(["status", "--porcelain"], session.path).trim()) return;
258250
+ this.git(
258251
+ [
258252
+ "commit",
258253
+ "--no-verify",
258254
+ "--no-gpg-sign",
258255
+ "-m",
258256
+ "subagent automatic worktree commit"
258257
+ ],
258258
+ session.path
258259
+ );
258260
+ }
258108
258261
  /** Copy the user's tracked and safe untracked state into the isolated branch. */
258109
258262
  snapshotWorkingTree(worktreePath) {
258110
258263
  const patch = this.gitBuffer(["diff", "HEAD", "--binary", "--no-ext-diff"]);
@@ -260352,10 +260505,11 @@ import path52 from "path";
260352
260505
  import { z as z73 } from "zod";
260353
260506
  import { z as z103 } from "zod";
260354
260507
  import { z as z93 } from "zod";
260508
+ import { z as z112 } from "zod";
260355
260509
  import path8 from "path";
260356
260510
  import { existsSync as existsSync34, statSync as statSync3 } from "fs";
260357
- import { z as z112 } from "zod";
260358
260511
  import { z as z122 } from "zod";
260512
+ import { z as z132 } from "zod";
260359
260513
  function createInitialState(sessionId, task, maxAttempts = 8) {
260360
260514
  return {
260361
260515
  sessionId,
@@ -263278,17 +263432,27 @@ var NETWORK_SUMMARY_CHARS = 280;
263278
263432
  var NETWORK_RESULT_CHARS = 6e3;
263279
263433
  var TOOL_RESULT_MAX_CHARS = 24e3;
263280
263434
  var TOOL_STATUS_MAX_CHARS = 2e3;
263435
+ var TOOL_ERROR_MAX_CHARS = 8e3;
263281
263436
  function buildToolResultContent(toolName, result) {
263282
- const content = result.ok ? serializeToolResultData(result.data, result.display) : result.error || "Unknown error";
263437
+ const content = result.ok ? serializeToolResultData(result.data, result.display) : serializeToolFailure(result.error, result.display);
263283
263438
  const redacted = redactSecrets(content);
263284
263439
  if (!result.ok || toolName !== "web_search") {
263285
263440
  return truncateToolText(
263286
263441
  redacted,
263287
- result.ok ? TOOL_RESULT_MAX_CHARS : TOOL_STATUS_MAX_CHARS
263442
+ result.ok ? TOOL_RESULT_MAX_CHARS : TOOL_ERROR_MAX_CHARS
263288
263443
  );
263289
263444
  }
263290
263445
  return compactSearchResult(redacted, redactSecrets(result.display || ""));
263291
263446
  }
263447
+ function serializeToolFailure(error, display) {
263448
+ const message2 = error?.trim() || "Unknown error";
263449
+ const output = display?.trim();
263450
+ if (!output || output === message2) return message2;
263451
+ return `${message2}
263452
+
263453
+ Captured command output:
263454
+ ${output}`;
263455
+ }
263292
263456
  function truncateToolText(text2, maxChars) {
263293
263457
  if (text2.length <= maxChars) return text2;
263294
263458
  const suffix = "\n... [truncated for context budget]";
@@ -263383,7 +263547,6 @@ function waitForAgentRetry(delayMs, signal) {
263383
263547
  cleanup();
263384
263548
  resolve26();
263385
263549
  }, delayMs);
263386
- timeout.unref?.();
263387
263550
  const onAbort = () => {
263388
263551
  clearTimeout(timeout);
263389
263552
  cleanup();
@@ -264366,9 +264529,14 @@ Note: To find where a symbol (class, function, etc.) is declared or referenced,
264366
264529
  continue;
264367
264530
  }
264368
264531
  }
264369
- const canFallbackToFlash = !this.fallbackModelForRun && activeModel2 !== this.config.models.fast && Boolean(this.config.models.fast) && !requestHasPartialOutput && (providerFailure ? ["RATE_LIMIT", "SERVER", "OVERLOADED", "TIMEOUT"].includes(
264370
- providerFailure.code
264371
- ) : /(?:insufficient_system_resource|resources were insufficient|overloaded|temporarily unavailable|HTTP 429|HTTP 500|HTTP 503|timed out)/i.test(
264532
+ const canFallbackToFlash = !this.fallbackModelForRun && activeModel2 !== this.config.models.fast && Boolean(this.config.models.fast) && !requestHasPartialOutput && (providerFailure ? [
264533
+ "RATE_LIMIT",
264534
+ "SERVER",
264535
+ "OVERLOADED",
264536
+ "TIMEOUT",
264537
+ "TRANSPORT",
264538
+ "STREAM_CLOSED"
264539
+ ].includes(providerFailure.code) : /(?:insufficient_system_resource|resources were insufficient|overloaded|temporarily unavailable|HTTP 429|HTTP 500|HTTP 503|timed out)/i.test(
264372
264540
  chatErrorMessage
264373
264541
  ));
264374
264542
  if (canFallbackToFlash) {
@@ -265972,6 +266140,10 @@ ${stdout2.substring(0, 2e4)}`
265972
266140
  kind: terminalSuccess
265973
266141
  });
265974
266142
  }
266143
+ const modelVisibleToolResult = buildToolResultContent(
266144
+ tc.name,
266145
+ finalResult
266146
+ );
265975
266147
  if (finalResult.ok) {
265976
266148
  const statusText = truncateToolText(
265977
266149
  redactSecrets(finalResult.display || "Done"),
@@ -265989,7 +266161,7 @@ ${stdout2.substring(0, 2e4)}`
265989
266161
  }
265990
266162
  } else {
265991
266163
  const statusError = truncateToolText(
265992
- redactSecrets(finalResult.error || "Unknown error"),
266164
+ modelVisibleToolResult,
265993
266165
  TOOL_STATUS_MAX_CHARS
265994
266166
  );
265995
266167
  this.interaction.showText(
@@ -266001,7 +266173,7 @@ ${stdout2.substring(0, 2e4)}`
266001
266173
  toolName: tc.name,
266002
266174
  result: finalResult.ok ? redactSensitiveValue(finalResult.data) : void 0,
266003
266175
  display: finalResult.ok ? redactSecrets(finalResult.display || "") : void 0,
266004
- error: finalResult.ok ? void 0 : redactSecrets(finalResult.error || "Unknown error")
266176
+ error: finalResult.ok ? void 0 : modelVisibleToolResult
266005
266177
  });
266006
266178
  const guardNudge = this.progressGuard.record({
266007
266179
  name: tc.name,
@@ -266025,7 +266197,7 @@ ${stdout2.substring(0, 2e4)}`
266025
266197
  toolResult: {
266026
266198
  toolCallId: tc.id,
266027
266199
  name: tc.name,
266028
- content: buildToolResultContent(tc.name, finalResult) + (guardNudge ? `
266200
+ content: modelVisibleToolResult + (guardNudge ? `
266029
266201
 
266030
266202
  ${guardNudge.message}` : ""),
266031
266203
  isError: !finalResult.ok
@@ -267183,6 +267355,15 @@ function agentOwnershipScopesOverlap(left, right) {
267183
267355
  const comparableRight = comparableScope(normalizedRight);
267184
267356
  return comparableLeft === comparableRight || comparableLeft.startsWith(`${comparableRight}/`) || comparableRight.startsWith(`${comparableLeft}/`);
267185
267357
  }
267358
+ function agentOwnershipScopeContains(scope, filePath) {
267359
+ const normalizedScope = normalizeAgentOwnershipScope(scope);
267360
+ const normalizedFile = normalizeUnchecked(filePath);
267361
+ if (!normalizedFile || normalizedFile === "*") return false;
267362
+ if (normalizedScope === "*") return true;
267363
+ const comparableOwner = comparableScope(normalizedScope);
267364
+ const comparableFile = comparableScope(normalizedFile);
267365
+ return comparableFile === comparableOwner || comparableFile.startsWith(`${comparableOwner}/`);
267366
+ }
267186
267367
  function normalizeUnchecked(scope) {
267187
267368
  const portable = scope.trim().replace(/\\/g, "/");
267188
267369
  if (portable === "*" || portable.toLowerCase() === "workspace") return "*";
@@ -267406,7 +267587,6 @@ var AgentTaskScheduler = class {
267406
267587
  runResult.then(() => void 0),
267407
267588
  new Promise((resolve26) => {
267408
267589
  graceTimer = setTimeout(resolve26, this.abortGraceMs);
267409
- graceTimer.unref?.();
267410
267590
  })
267411
267591
  ]);
267412
267592
  } finally {
@@ -267440,6 +267620,61 @@ function abortError2(signal) {
267440
267620
  function toError2(error) {
267441
267621
  return error instanceof Error ? error : new Error(String(error));
267442
267622
  }
267623
+ var ParallelWriterTaskSchema = z112.object({
267624
+ id: z112.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/),
267625
+ task: z112.string().trim().min(1).max(2e4),
267626
+ scopes: z112.array(AgentOwnershipScopeSchema).min(1).max(50)
267627
+ });
267628
+ var ParallelWorkPlanSchema = z112.object({
267629
+ summary: z112.string().trim().min(1).max(2e4),
267630
+ tasks: z112.array(ParallelWriterTaskSchema).min(1).max(4)
267631
+ }).superRefine((plan, context) => {
267632
+ const ids = /* @__PURE__ */ new Set();
267633
+ for (const [index, task] of plan.tasks.entries()) {
267634
+ if (ids.has(task.id)) {
267635
+ context.addIssue({
267636
+ code: z112.ZodIssueCode.custom,
267637
+ path: ["tasks", index, "id"],
267638
+ message: `Duplicate writer task id: ${task.id}`
267639
+ });
267640
+ }
267641
+ ids.add(task.id);
267642
+ }
267643
+ if (plan.tasks.length < 2) return;
267644
+ for (let left = 0; left < plan.tasks.length; left++) {
267645
+ for (let right = left + 1; right < plan.tasks.length; right++) {
267646
+ const overlap = plan.tasks[left].scopes.some(
267647
+ (leftScope) => plan.tasks[right].scopes.some(
267648
+ (rightScope) => agentOwnershipScopesOverlap(leftScope, rightScope)
267649
+ )
267650
+ );
267651
+ if (!overlap) continue;
267652
+ context.addIssue({
267653
+ code: z112.ZodIssueCode.custom,
267654
+ path: ["tasks", right, "scopes"],
267655
+ message: `Writer scopes overlap with task ${plan.tasks[left].id}.`
267656
+ });
267657
+ }
267658
+ }
267659
+ });
267660
+ function parseParallelWorkPlan(text2) {
267661
+ const candidate = extractJsonObject(text2);
267662
+ if (!candidate) return void 0;
267663
+ try {
267664
+ const result = ParallelWorkPlanSchema.safeParse(JSON.parse(candidate));
267665
+ return result.success ? result.data : void 0;
267666
+ } catch {
267667
+ return void 0;
267668
+ }
267669
+ }
267670
+ function extractJsonObject(text2) {
267671
+ const fenced = /```(?:json)?\s*([\s\S]*?)```/i.exec(text2)?.[1]?.trim();
267672
+ const source = fenced || text2.trim();
267673
+ const start = source.indexOf("{");
267674
+ const end = source.lastIndexOf("}");
267675
+ if (start < 0 || end <= start) return void 0;
267676
+ return source.slice(start, end + 1);
267677
+ }
267443
267678
  var AgentRunTracker = class {
267444
267679
  constructor(cwd, task, budgetUsd, warn) {
267445
267680
  this.cwd = cwd;
@@ -267588,9 +267823,9 @@ function resolveAgentTeam(config) {
267588
267823
  reviewers
267589
267824
  };
267590
267825
  }
267591
- var ReviewVerdictSchema = z112.object({
267592
- verdict: z112.enum(["approved", "rejected"]),
267593
- feedback: z112.string().default("")
267826
+ var ReviewVerdictSchema = z122.object({
267827
+ verdict: z122.enum(["approved", "rejected"]),
267828
+ feedback: z122.string().default("")
267594
267829
  });
267595
267830
  var Orchestrator = class {
267596
267831
  constructor(cwd, config, provider, task, interaction) {
@@ -267664,8 +267899,10 @@ var Orchestrator = class {
267664
267899
  this.abortedOutcome(0, "Orchestration was interrupted.")
267665
267900
  );
267666
267901
  }
267667
- const planText = planner.plan;
267668
- this.persistPlan(planText);
267902
+ const planText = planner.workPlan?.summary || planner.plan;
267903
+ this.persistPlan(
267904
+ planner.workPlan ? JSON.stringify(planner.workPlan, null, 2) : planner.plan
267905
+ );
267669
267906
  const worktrees = new WorktreeManager(this.cwd);
267670
267907
  let worktree;
267671
267908
  let agentCwd = this.cwd;
@@ -267673,12 +267910,25 @@ var Orchestrator = class {
267673
267910
  let mergeFailureMessage = "";
267674
267911
  let completed = false;
267675
267912
  let completedAttempts = 0;
267913
+ let parallelPrepared = false;
267676
267914
  if (worktrees.isGitRepo()) {
267677
267915
  try {
267678
- const worktreeId = generateId("wt").slice(0, 12);
267679
- worktree = worktrees.createWorktree(worktreeId, {
267680
- snapshotWorkingTree: true
267681
- });
267916
+ if (planner.workPlan && planner.workPlan.tasks.length > 1) {
267917
+ const prepared = await this.prepareParallelWorkspace(
267918
+ worktrees,
267919
+ planner.workPlan
267920
+ );
267921
+ if (!prepared.success) {
267922
+ return this.finalizeOutcome(prepared.outcome);
267923
+ }
267924
+ worktree = prepared.integration;
267925
+ parallelPrepared = true;
267926
+ } else {
267927
+ const worktreeId = generateId("wt").slice(0, 12);
267928
+ worktree = worktrees.createWorktree(worktreeId, {
267929
+ snapshotWorkingTree: true
267930
+ });
267931
+ }
267682
267932
  if (!existsSync34(worktree.path) || !statSync3(worktree.path).isDirectory()) {
267683
267933
  throw new Error(
267684
267934
  `Worktree manager returned a missing directory: ${worktree.path}`
@@ -267686,7 +267936,7 @@ var Orchestrator = class {
267686
267936
  }
267687
267937
  agentCwd = worktree.path;
267688
267938
  this.interaction.showText(
267689
- ` \u25CF Running Coder and Reviewer in isolated git worktree: ${agentCwd}`
267939
+ parallelPrepared ? ` \u25CF Reviewing the combined parallel implementation in: ${agentCwd}` : ` \u25CF Running Coder and Reviewer in isolated git worktree: ${agentCwd}`
267690
267940
  );
267691
267941
  } catch (error) {
267692
267942
  if (worktree) {
@@ -267711,15 +267961,17 @@ var Orchestrator = class {
267711
267961
  try {
267712
267962
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
267713
267963
  if (this.aborted) break;
267714
- const coderOutcome = await this.runCoder(
267715
- agentCwd,
267716
- planText,
267717
- feedback,
267718
- attempt,
267719
- maxAttempts
267720
- );
267721
- if (coderOutcome.status !== "completed") {
267722
- return this.finalizeOutcome(coderOutcome);
267964
+ if (!(parallelPrepared && attempt === 1)) {
267965
+ const coderOutcome = await this.runCoder(
267966
+ agentCwd,
267967
+ planText,
267968
+ feedback,
267969
+ attempt,
267970
+ maxAttempts
267971
+ );
267972
+ if (coderOutcome.status !== "completed") {
267973
+ return this.finalizeOutcome(coderOutcome);
267974
+ }
267723
267975
  }
267724
267976
  if (this.aborted) break;
267725
267977
  const review = await this.runReviewer(agentCwd, attempt, maxAttempts);
@@ -267818,8 +268070,10 @@ var Orchestrator = class {
267818
268070
  {
267819
268071
  modelOverride: this.config.models.planner,
267820
268072
  systemPromptOverride: `You are the Orbit Planner Agent.
267821
- Analyze the codebase and produce a detailed implementation plan.
267822
- Do not modify files. Return the plan as plain text.`,
268073
+ Analyze the codebase and produce a bounded implementation plan. Do not modify files.
268074
+ Return ONLY one JSON object with this shape:
268075
+ {"summary":"shared architecture and acceptance criteria","tasks":[{"id":"short-id","task":"self-contained writer assignment","scopes":["workspace-relative/path"]}]}
268076
+ Use 2-4 tasks only when their write scopes are provably disjoint and they can be implemented independently from the same baseline. Use one task with scope "workspace" for coupled work. Never invent absolute paths or parent traversal.`,
267823
268077
  allowedTools: [
267824
268078
  "read_file",
267825
268079
  "list_files",
@@ -267841,8 +268095,10 @@ Do not modify files. Return the plan as plain text.`,
267841
268095
  let outcome;
267842
268096
  try {
267843
268097
  outcome = await loop.run();
268098
+ const plan = lastAssistantText(loop) || "No plan generated.";
267844
268099
  return {
267845
- plan: lastAssistantText(loop) || "No plan generated.",
268100
+ plan,
268101
+ workPlan: parseParallelWorkPlan(plan),
267846
268102
  outcome
267847
268103
  };
267848
268104
  } catch (error) {
@@ -267865,15 +268121,48 @@ ${feedback}
267865
268121
  Original plan:
267866
268122
  ${plan}` : `Implement the following plan:
267867
268123
  ${plan}`;
267868
- const tracked = this.addTrackedAgent(
268124
+ return this.runWriter(
268125
+ cwd,
268126
+ prompt,
267869
268127
  `coder:${attempt}`,
268128
+ ["workspace"],
268129
+ 0.45 / maxAttempts,
268130
+ `You are the Orbit Coder Agent.
268131
+ Make precise changes in the current isolated workspace. Run focused verification when useful. Do not commit or merge.`
268132
+ );
268133
+ }
268134
+ async runParallelCoder(cwd, plan, task, signal) {
268135
+ this.interaction.showText(
268136
+ `
268137
+ [Phase 2: Parallel writer ${task.id}] Owning ${task.scopes.join(", ")}...`
268138
+ );
268139
+ const prompt = [
268140
+ `Shared plan: ${plan.summary}`,
268141
+ `Your assignment: ${task.task}`,
268142
+ `You exclusively own these write scopes: ${task.scopes.join(", ")}.`,
268143
+ "Do not modify files outside those scopes. Run focused verification for your changes."
268144
+ ].join("\n\n");
268145
+ return this.runWriter(
268146
+ cwd,
268147
+ prompt,
268148
+ `writer:${task.id}`,
268149
+ task.scopes,
268150
+ 0.45 / plan.tasks.length,
268151
+ `You are an Orbit parallel Writer Agent.
268152
+ Work only in your assigned isolated worktree and only inside the declared write scopes. Read broader context when necessary, but never edit outside your ownership. Do not commit or merge.`,
268153
+ signal
268154
+ );
268155
+ }
268156
+ async runWriter(cwd, prompt, role, scopes, budgetFraction, systemPrompt, signal) {
268157
+ const tracked = this.addTrackedAgent(
268158
+ role,
267870
268159
  prompt,
267871
268160
  this.config.models.coder,
267872
- 0.45 / maxAttempts,
268161
+ budgetFraction,
267873
268162
  "write",
267874
- ["workspace"]
268163
+ scopes
267875
268164
  );
267876
- const activeId = tracked?.id || `coder-${attempt}`;
268165
+ const activeId = tracked?.id || role.replace(/[^a-zA-Z0-9_-]/g, "-").slice(0, 64);
267877
268166
  const loop = AgentLoop.initialize(
267878
268167
  cwd,
267879
268168
  this.config,
@@ -267882,8 +268171,7 @@ ${plan}`;
267882
268171
  this.interaction,
267883
268172
  {
267884
268173
  modelOverride: this.config.models.coder,
267885
- systemPromptOverride: `You are the Orbit Coder Agent.
267886
- Make precise changes in the current isolated workspace. Do not commit or merge.`,
268174
+ systemPromptOverride: systemPrompt,
267887
268175
  allowedTools: [
267888
268176
  "read_file",
267889
268177
  "write_file",
@@ -267892,13 +268180,21 @@ Make precise changes in the current isolated workspace. Do not commit or merge.`
267892
268180
  "glob",
267893
268181
  "grep",
267894
268182
  "git_status",
267895
- "git_diff"
268183
+ "git_diff",
268184
+ "run_tests",
268185
+ "bash",
268186
+ "get_background_task_output",
268187
+ "kill_background_task",
268188
+ "list_background_tasks"
267896
268189
  ],
267897
268190
  disableMcp: true,
267898
- agent: { id: activeId, role: `coder:${attempt}` },
268191
+ agent: { id: activeId, role },
267899
268192
  sessionStorage: this.agentSessionStorage()
267900
268193
  }
267901
268194
  );
268195
+ const abortLoop = () => loop.abort("immediate");
268196
+ if (signal?.aborted) abortLoop();
268197
+ signal?.addEventListener("abort", abortLoop, { once: true });
267902
268198
  this.agentRunTracker.attachSession(tracked, loop.getSessionId());
267903
268199
  this.activeLoops.set(activeId, loop);
267904
268200
  this.markAgentRunning(tracked);
@@ -267911,10 +268207,131 @@ Make precise changes in the current isolated workspace. Do not commit or merge.`
267911
268207
  throw error;
267912
268208
  } finally {
267913
268209
  if (outcome) this.markAgentFinished(tracked, loop, outcome);
268210
+ signal?.removeEventListener("abort", abortLoop);
267914
268211
  this.activeLoops.delete(activeId);
267915
268212
  await loop.dispose();
267916
268213
  }
267917
268214
  }
268215
+ async prepareParallelWorkspace(worktrees, plan) {
268216
+ const integration = worktrees.createWorktree(
268217
+ generateId("integration").slice(0, 24),
268218
+ { snapshotWorkingTree: true }
268219
+ );
268220
+ const writers = [];
268221
+ let cleanup = true;
268222
+ try {
268223
+ for (const task of plan.tasks) {
268224
+ writers.push({
268225
+ task,
268226
+ session: worktrees.createWorktree(
268227
+ `${task.id}-${generateId("writer").slice(0, 12)}`.slice(0, 63),
268228
+ { snapshotWorkingTree: true }
268229
+ )
268230
+ });
268231
+ }
268232
+ this.interaction.showText(
268233
+ ` \u25CF Running ${writers.length} isolated writers with disjoint ownership scopes...`
268234
+ );
268235
+ const scheduler = new AgentTaskScheduler({
268236
+ maxConcurrency: Math.min(
268237
+ writers.length,
268238
+ this.config.agent.maxReviewConcurrency
268239
+ )
268240
+ });
268241
+ this.activeTaskScheduler = scheduler;
268242
+ const results = await (async () => {
268243
+ try {
268244
+ return await scheduler.run(
268245
+ writers.map(({ task, session }) => ({
268246
+ id: task.id,
268247
+ timeoutMs: this.reviewerTimeoutMs(),
268248
+ access: { mode: "write", scopes: task.scopes },
268249
+ run: (signal) => this.runParallelCoder(session.path, plan, task, signal)
268250
+ }))
268251
+ );
268252
+ } finally {
268253
+ if (this.activeTaskScheduler === scheduler) {
268254
+ this.activeTaskScheduler = void 0;
268255
+ }
268256
+ }
268257
+ })();
268258
+ for (const [index, result] of results.entries()) {
268259
+ if (result.status !== "completed") {
268260
+ return {
268261
+ success: false,
268262
+ preserved: false,
268263
+ outcome: result.status === "aborted" ? this.abortedOutcome(0, result.error.message) : this.failedOutcome(0, result.error.message)
268264
+ };
268265
+ }
268266
+ if (result.value.status !== "completed") {
268267
+ return { success: false, preserved: false, outcome: result.value };
268268
+ }
268269
+ const { task, session } = writers[index];
268270
+ const changedFiles = worktrees.listChangedFiles(session);
268271
+ const outsideScope = changedFiles.filter(
268272
+ (file) => !task.scopes.some(
268273
+ (scope) => agentOwnershipScopeContains(scope, file)
268274
+ )
268275
+ );
268276
+ if (outsideScope.length > 0) {
268277
+ return {
268278
+ success: false,
268279
+ preserved: false,
268280
+ outcome: this.failedOutcome(
268281
+ 0,
268282
+ `Writer ${task.id} modified files outside its ownership: ${outsideScope.join(", ")}`
268283
+ )
268284
+ };
268285
+ }
268286
+ if (changedFiles.length === 0) {
268287
+ return {
268288
+ success: false,
268289
+ preserved: false,
268290
+ outcome: this.failedOutcome(
268291
+ 0,
268292
+ `Writer ${task.id} completed without producing its assigned change.`
268293
+ )
268294
+ };
268295
+ }
268296
+ }
268297
+ const integrated = worktrees.integrateWorktrees(
268298
+ writers.map(({ session }) => session),
268299
+ integration
268300
+ );
268301
+ if (!integrated.success) {
268302
+ cleanup = false;
268303
+ this.interaction.showText(
268304
+ ` \u2716 Parallel integration failed; worktrees were preserved for recovery: ${errorMessage22(integrated.error || "unknown integration error")}`
268305
+ );
268306
+ return {
268307
+ success: false,
268308
+ preserved: true,
268309
+ outcome: this.failedOutcome(
268310
+ 0,
268311
+ integrated.error || "Parallel writer integration failed."
268312
+ )
268313
+ };
268314
+ }
268315
+ cleanup = false;
268316
+ this.interaction.showText(
268317
+ ` \u2714 Integrated ${integrated.integratedCount || writers.length} writer deltas into one review worktree.`
268318
+ );
268319
+ return { success: true, integration };
268320
+ } finally {
268321
+ if (cleanup) {
268322
+ for (const { session } of writers) {
268323
+ try {
268324
+ worktrees.discardWorktree(session);
268325
+ } catch {
268326
+ }
268327
+ }
268328
+ try {
268329
+ worktrees.discardWorktree(integration);
268330
+ } catch {
268331
+ }
268332
+ }
268333
+ }
268334
+ }
267918
268335
  async runReviewer(cwd, attempt, maxAttempts) {
267919
268336
  const team = resolveAgentTeam(this.config);
267920
268337
  const reviewerNames = team.reviewers.map(({ perspective }) => perspective).join(", ");
@@ -268155,62 +268572,62 @@ function errorMessage22(error) {
268155
268572
  const raw = error instanceof Error ? error.message : String(error);
268156
268573
  return redactSecrets(raw).replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").replace(/\s+/g, " ").trim().slice(0, 2e3);
268157
268574
  }
268158
- var AcceptanceVerificationSchema = z122.object({
268159
- name: z122.string().trim().min(1).max(120),
268160
- command: z122.string().trim().min(1).max(4e3),
268161
- timeoutMs: z122.number().int().min(1e3).max(30 * 6e4).default(12e4)
268575
+ var AcceptanceVerificationSchema = z132.object({
268576
+ name: z132.string().trim().min(1).max(120),
268577
+ command: z132.string().trim().min(1).max(4e3),
268578
+ timeoutMs: z132.number().int().min(1e3).max(30 * 6e4).default(12e4)
268162
268579
  });
268163
- var AcceptanceTaskSchema = z122.object({
268164
- id: z122.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/),
268165
- prompt: z122.string().trim().min(1).max(2e4),
268166
- mode: z122.enum(["single", "multi"]).default("single"),
268167
- provider: z122.string().trim().min(1).optional(),
268168
- model: z122.string().trim().min(1).optional(),
268169
- verification: z122.array(AcceptanceVerificationSchema).max(20).default([]),
268170
- requiredChangedFiles: z122.array(z122.string().trim().min(1)).max(100).default([]),
268171
- forbiddenChangedFiles: z122.array(z122.string().trim().min(1)).max(100).default([]),
268172
- maxChangedFiles: z122.number().int().min(0).max(1e4).optional(),
268173
- limits: z122.object({
268174
- maxDurationMs: z122.number().int().min(1e3).max(24 * 60 * 6e4).optional(),
268175
- maxInputTokens: z122.number().int().nonnegative().optional(),
268176
- maxOutputTokens: z122.number().int().nonnegative().optional(),
268177
- maxCostUsd: z122.number().finite().nonnegative().optional(),
268178
- minCacheHitRate: z122.number().finite().min(0).max(1).optional()
268580
+ var AcceptanceTaskSchema = z132.object({
268581
+ id: z132.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/),
268582
+ prompt: z132.string().trim().min(1).max(2e4),
268583
+ mode: z132.enum(["single", "multi"]).default("single"),
268584
+ provider: z132.string().trim().min(1).optional(),
268585
+ model: z132.string().trim().min(1).optional(),
268586
+ verification: z132.array(AcceptanceVerificationSchema).max(20).default([]),
268587
+ requiredChangedFiles: z132.array(z132.string().trim().min(1)).max(100).default([]),
268588
+ forbiddenChangedFiles: z132.array(z132.string().trim().min(1)).max(100).default([]),
268589
+ maxChangedFiles: z132.number().int().min(0).max(1e4).optional(),
268590
+ limits: z132.object({
268591
+ maxDurationMs: z132.number().int().min(1e3).max(24 * 60 * 6e4).optional(),
268592
+ maxInputTokens: z132.number().int().nonnegative().optional(),
268593
+ maxOutputTokens: z132.number().int().nonnegative().optional(),
268594
+ maxCostUsd: z132.number().finite().nonnegative().optional(),
268595
+ minCacheHitRate: z132.number().finite().min(0).max(1).optional()
268179
268596
  }).optional()
268180
268597
  });
268181
- var AcceptanceSuiteSchema = z122.object({
268182
- schemaVersion: z122.literal(1),
268183
- name: z122.string().trim().min(1).max(200),
268184
- description: z122.string().trim().max(2e3).optional(),
268185
- tasks: z122.array(AcceptanceTaskSchema).min(1).max(100)
268598
+ var AcceptanceSuiteSchema = z132.object({
268599
+ schemaVersion: z132.literal(1),
268600
+ name: z132.string().trim().min(1).max(200),
268601
+ description: z132.string().trim().max(2e3).optional(),
268602
+ tasks: z132.array(AcceptanceTaskSchema).min(1).max(100)
268186
268603
  });
268187
- var AcceptanceCheckResultSchema = z122.object({
268188
- name: z122.string(),
268189
- passed: z122.boolean(),
268190
- durationMs: z122.number().int().nonnegative(),
268191
- exitCode: z122.number().int().optional(),
268192
- summary: z122.string().max(4e3)
268604
+ var AcceptanceCheckResultSchema = z132.object({
268605
+ name: z132.string(),
268606
+ passed: z132.boolean(),
268607
+ durationMs: z132.number().int().nonnegative(),
268608
+ exitCode: z132.number().int().optional(),
268609
+ summary: z132.string().max(4e3)
268193
268610
  });
268194
- var AcceptanceTaskResultSchema = z122.object({
268195
- taskId: z122.string(),
268196
- sessionId: z122.string().optional(),
268197
- traceFile: z122.string().optional(),
268198
- passed: z122.boolean(),
268199
- agentStatus: z122.enum(["completed", "failed", "aborted"]),
268200
- durationMs: z122.number().int().nonnegative(),
268201
- requestedProvider: z122.string().optional(),
268202
- requestedModel: z122.string().optional(),
268203
- resolvedModels: z122.array(z122.string()).default([]),
268204
- usage: z122.object({
268205
- inputTokens: z122.number().int().nonnegative(),
268206
- outputTokens: z122.number().int().nonnegative(),
268207
- cacheReadTokens: z122.number().int().nonnegative(),
268208
- cacheHitRate: z122.number().finite().min(0).max(1),
268209
- costUsd: z122.number().finite().nonnegative()
268611
+ var AcceptanceTaskResultSchema = z132.object({
268612
+ taskId: z132.string(),
268613
+ sessionId: z132.string().optional(),
268614
+ traceFile: z132.string().optional(),
268615
+ passed: z132.boolean(),
268616
+ agentStatus: z132.enum(["completed", "failed", "aborted"]),
268617
+ durationMs: z132.number().int().nonnegative(),
268618
+ requestedProvider: z132.string().optional(),
268619
+ requestedModel: z132.string().optional(),
268620
+ resolvedModels: z132.array(z132.string()).default([]),
268621
+ usage: z132.object({
268622
+ inputTokens: z132.number().int().nonnegative(),
268623
+ outputTokens: z132.number().int().nonnegative(),
268624
+ cacheReadTokens: z132.number().int().nonnegative(),
268625
+ cacheHitRate: z132.number().finite().min(0).max(1),
268626
+ costUsd: z132.number().finite().nonnegative()
268210
268627
  }).optional(),
268211
- changedFiles: z122.array(z122.string()),
268212
- checks: z122.array(AcceptanceCheckResultSchema),
268213
- failureReasons: z122.array(z122.string())
268628
+ changedFiles: z132.array(z132.string()),
268629
+ checks: z132.array(AcceptanceCheckResultSchema),
268630
+ failureReasons: z132.array(z132.string())
268214
268631
  });
268215
268632
  function scoreAcceptanceTask(input) {
268216
268633
  const task = AcceptanceTaskSchema.parse(input.task);
@@ -269057,7 +269474,6 @@ async function probeProviderCapabilities(cwd, config, provider, options = {}) {
269057
269474
  () => controller.abort(),
269058
269475
  options.timeoutMs ?? DEFAULT_PROVIDER_PROBE_TIMEOUT_MS
269059
269476
  );
269060
- timeout.unref?.();
269061
269477
  const result = {
269062
269478
  providerId: provider.id,
269063
269479
  model,
@@ -300170,6 +300586,9 @@ async function runEval(cwd, suiteFile, options = {}) {
300170
300586
  `eval-${task.id}`.replace(/[^a-zA-Z0-9_-]/g, "-").slice(0, 60)
300171
300587
  );
300172
300588
  snapshotWorkspaceIntoWorktree(cwd, worktree.path);
300589
+ if (value.allowCommands) {
300590
+ writeAcceptanceVerificationContract(worktree.path, task);
300591
+ }
300173
300592
  const outcome = await runAgent(
300174
300593
  worktree.path,
300175
300594
  task.prompt,
@@ -300182,6 +300601,12 @@ async function runEval(cwd, suiteFile, options = {}) {
300182
300601
  requireApprovalForWrite: false,
300183
300602
  requireApprovalForBash: !value.allowCommands
300184
300603
  },
300604
+ security: {
300605
+ ...DEFAULT_CONFIG.security,
300606
+ // The suite commands were explicitly reviewed and authorized by
300607
+ // --allow-commands, and execute only in this disposable worktree.
300608
+ trustProjectExecutables: value.allowCommands
300609
+ },
300185
300610
  agent: {
300186
300611
  ...DEFAULT_CONFIG.agent,
300187
300612
  // Acceptance tasks commonly include implementation plus their
@@ -300309,6 +300734,22 @@ function loadAcceptanceSuite(cwd, suiteFile) {
300309
300734
  const raw = filePath.endsWith(".json") ? JSON.parse(text2) : parseYaml4(text2);
300310
300735
  return AcceptanceSuiteSchema.parse(raw);
300311
300736
  }
300737
+ function writeAcceptanceVerificationContract(cwd, task) {
300738
+ if (task.verification.length === 0) return void 0;
300739
+ const suites = Object.fromEntries(
300740
+ task.verification.map((check, index) => [
300741
+ `${String(index + 1).padStart(2, "0")}-${check.name}`,
300742
+ check.command
300743
+ ])
300744
+ );
300745
+ const contract = VerificationContractSchema.parse({
300746
+ suites,
300747
+ maxRepairAttempts: 3
300748
+ });
300749
+ const filePath = resolveSafePath(cwd, join19(".orbit", "verification.json"));
300750
+ writeJsonAtomically2(filePath, contract);
300751
+ return filePath;
300752
+ }
300312
300753
  async function runVerificationChecks(cwd, checks) {
300313
300754
  const results = [];
300314
300755
  for (const check of checks) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orbit-build/cli",
3
- "version": "0.8.5",
3
+ "version": "0.8.6",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Local-first AI coding agent CLI, TUI, Web UI, diagnostics, and LSP runtime",
6
6
  "keywords": [
@@ -246,6 +246,16 @@ the outcome. Record explicit upstream artifact contracts between subproblems.
246
246
  into the support ZIP before removing any reproducible workspace figures.
247
247
  Do not remove reproducible figures that are cited by the paper or required by
248
248
  the support archive.
249
+ - Treat `paper/` as the human-facing delivery area, not a build workspace. The
250
+ hidden `.cumcm/finalize.py` is only a workspace-scoped launcher for Orbit's
251
+ trusted build/audit/package gate. It is not modeling code, never belongs under
252
+ `code/`, never appears in the source appendix or support ZIP, and may be
253
+ ignored by users reviewing the model implementation.
254
+ - A completed `code/qN` must never contain only `main.py`. The entry point must
255
+ remain orchestral while responsibility-named sibling modules contain the
256
+ actual preprocessing, model/optimization, validation, and reporting logic
257
+ that the question needs. The finalizer rejects main-only and TODO scaffold
258
+ projects before spending time on LaTeX compilation.
249
259
 
250
260
  ```powershell
251
261
  python <project-root>/code/run_all.py
@@ -38,6 +38,7 @@ def main() -> None:
38
38
  created: list[str] = []
39
39
  updated: list[str] = []
40
40
  preserved: list[str] = []
41
+ removed: list[str] = []
41
42
  for directory in (
42
43
  root / "question",
43
44
  root / "code",
@@ -50,6 +51,7 @@ def main() -> None:
50
51
 
51
52
  migrate_legacy_control_files(root, created, preserved)
52
53
  copy_template_tree(root, created, preserved)
54
+ remove_empty_legacy_layout_directories(root, removed)
53
55
  declared = read_declared_count(root)
54
56
  discovered = max(question_numbers(root), default=0)
55
57
  question_count = max(args.questions, declared, discovered)
@@ -67,6 +69,20 @@ def main() -> None:
67
69
  )
68
70
  if updated:
69
71
  print(" Updated orchestrators: " + ", ".join(updated))
72
+ if removed:
73
+ print(" Removed empty legacy layout shells: " + ", ".join(removed))
74
+
75
+
76
+ def remove_empty_legacy_layout_directories(root: Path, removed: list[str]) -> None:
77
+ """Drop empty legacy shells without touching authored files or build output."""
78
+ for directory in (root / "paper" / "sections", root / "paper" / "build"):
79
+ if not directory.is_dir() or directory.is_symlink():
80
+ continue
81
+ try:
82
+ next(directory.iterdir())
83
+ except StopIteration:
84
+ directory.rmdir()
85
+ removed.append(directory.relative_to(root).as_posix() + "/")
70
86
 
71
87
 
72
88
  def migrate_legacy_control_files(
@@ -6,6 +6,8 @@ import sys
6
6
  from pathlib import Path
7
7
 
8
8
  from evidence_freeze import require_refresh_authorization, write_freeze
9
+ from project_utils import question_numbers
10
+ from validate_project import code_architecture_errors
9
11
 
10
12
 
11
13
  SCRIPT_ROOT = Path(__file__).resolve().parent
@@ -38,6 +40,16 @@ def main() -> None:
38
40
  completed = subprocess.run([sys.executable, str(entry)], cwd=root / "code", check=False)
39
41
  if completed.returncode:
40
42
  raise SystemExit("code/run_all.py failed; paper was not rebuilt from stale evidence.")
43
+ discovered_questions = question_numbers(root)
44
+ architecture_errors = code_architecture_errors(
45
+ root, max(discovered_questions, default=0)
46
+ )
47
+ if architecture_errors:
48
+ for error in architecture_errors:
49
+ print(f"[ERROR] {error}")
50
+ raise SystemExit(
51
+ "Finalization stopped before compilation because modeling code is incomplete."
52
+ )
41
53
  run("capture_environment.py", root)
42
54
  run("build_paper.py", root, *(["--strict-layout"] if args.strict_layout else []))
43
55
  audit_flags = ["--fail-on-errors"]
@@ -880,9 +880,9 @@ def validate_evidence(root: Path, count: int, errors: list[str], warnings: list[
880
880
  warnings.append(f"unresolved evidence claim: {claim_id or location}")
881
881
 
882
882
 
883
- def code_architecture_warnings(root: Path, count: int) -> list[str]:
884
- """Find review-hostile Python layouts without prescribing one fixed architecture."""
885
- warnings: list[str] = []
883
+ def code_architecture_errors(root: Path, count: int) -> list[str]:
884
+ """Reject incomplete qN implementations that cannot support a final paper."""
885
+ errors: list[str] = []
886
886
  for number in range(1, count + 1):
887
887
  question_dir = root / "code" / f"q{number}"
888
888
  if not question_dir.is_dir():
@@ -894,10 +894,33 @@ def code_architecture_warnings(root: Path, count: int) -> list[str]:
894
894
  )
895
895
  names = {path.name for path in modules}
896
896
  if names == {"main.py"}:
897
- warnings.append(
897
+ errors.append(
898
898
  f"q{number} contains only main.py; keep it orchestral and add "
899
899
  "responsibility-named modules for the actual model and validation"
900
900
  )
901
+ main_path = question_dir / "main.py"
902
+ if main_path.is_file():
903
+ main_text = main_path.read_text(encoding="utf-8", errors="replace")
904
+ if "NotImplementedError" in main_text or "TODO" in main_text:
905
+ errors.append(
906
+ f"code/q{number}/main.py is still an unimplemented scaffold"
907
+ )
908
+ return errors
909
+
910
+
911
+ def code_architecture_warnings(root: Path, count: int) -> list[str]:
912
+ """Find review-hostile Python layouts without prescribing one fixed architecture."""
913
+ warnings: list[str] = []
914
+ for number in range(1, count + 1):
915
+ question_dir = root / "code" / f"q{number}"
916
+ if not question_dir.is_dir():
917
+ continue
918
+ modules = sorted(
919
+ path
920
+ for path in question_dir.glob("*.py")
921
+ if path.name != "__init__.py" and path.is_file()
922
+ )
923
+ names = {path.name for path in modules}
901
924
  if names == {"main.py", "model.py", "output.py"}:
902
925
  warnings.append(
903
926
  f"q{number} uses the generic main.py + model.py + output.py trio; "
@@ -915,10 +938,6 @@ def code_architecture_warnings(root: Path, count: int) -> list[str]:
915
938
  main_path = question_dir / "main.py"
916
939
  if main_path.is_file():
917
940
  main_text = main_path.read_text(encoding="utf-8", errors="replace")
918
- if "NotImplementedError" in main_text or "TODO" in main_text:
919
- warnings.append(
920
- f"code/q{number}/main.py is still an unimplemented scaffold"
921
- )
922
941
  main_lines = [
923
942
  line
924
943
  for line in main_text.splitlines()
@@ -1175,6 +1194,7 @@ def main() -> None:
1175
1194
  errors.append(
1176
1195
  f"Python syntax failed for {source.relative_to(root).as_posix()}: {error}"
1177
1196
  )
1197
+ errors.extend(code_architecture_errors(root, count))
1178
1198
  warnings.extend(code_architecture_warnings(root, count))
1179
1199
  warnings.extend(delivery_hygiene_warnings(root))
1180
1200
  if result_artifact_profile is not None: