sneakoscope 8.0.2 → 8.0.3

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 (122) hide show
  1. package/README.md +47 -23
  2. package/config/skills-hash-ledger.v1.json +1 -1
  3. package/crates/sks-core/Cargo.lock +1 -1
  4. package/crates/sks-core/Cargo.toml +1 -1
  5. package/dist/bin/fast-inline.js +55 -13
  6. package/dist/bin/sks-dispatch.js +1 -1
  7. package/dist/cli/command-manifest-lite.js +4 -0
  8. package/dist/cli/command-registry.js +4 -0
  9. package/dist/cli/install-helpers-codex-lb-chain.js +187 -0
  10. package/dist/cli/install-helpers-codex-lb-config.js +74 -8
  11. package/dist/cli/install-helpers.js +89 -44
  12. package/dist/commands/codex-lb.js +117 -19
  13. package/dist/commands/doctor.js +697 -37
  14. package/dist/config/skills-manifest.json +3 -2
  15. package/dist/core/agents/agent-runner-codex-exec.js +5 -3
  16. package/dist/core/codex/codex-config-guard.js +238 -52
  17. package/dist/core/codex-adapter.js +5 -3
  18. package/dist/core/codex-app/menubar/constants.js +10 -1
  19. package/dist/core/codex-app/menubar/global-install.js +288 -0
  20. package/dist/core/codex-app/menubar/installer.js +79 -14
  21. package/dist/core/codex-app/menubar/launch-agent.js +267 -45
  22. package/dist/core/codex-app/menubar/paths.js +3 -0
  23. package/dist/core/codex-app/menubar/rollback.js +55 -7
  24. package/dist/core/codex-app/menubar/status.js +75 -4
  25. package/dist/core/codex-control/codex-0139-image-path-real-probe.js +3 -1
  26. package/dist/core/codex-control/codex-0139-web-search-probe.js +3 -1
  27. package/dist/core/codex-control/codex-app-server-runtime-env.js +13 -4
  28. package/dist/core/codex-control/codex-app-server-v2-client.js +3 -3
  29. package/dist/core/codex-exec-output-schema.js +4 -1
  30. package/dist/core/codex-lb/codex-lb-env.js +63 -72
  31. package/dist/core/codex-lb/codex-lb-setup.js +15 -2
  32. package/dist/core/codex-lb/desktop-center-credentials.js +517 -58
  33. package/dist/core/codex-lb/desktop-controller.js +153 -24
  34. package/dist/core/codex-lb/routing-truth.js +327 -0
  35. package/dist/core/codex-native/core-skill-manifest.js +1 -1
  36. package/dist/core/commands/basic-cli.js +7 -1
  37. package/dist/core/commands/qa-loop-command.js +3 -1
  38. package/dist/core/commands/telegram-command.js +241 -0
  39. package/dist/core/config-adopt/config-adopt-command.js +35 -0
  40. package/dist/core/config-adopt/config-adopt.js +346 -0
  41. package/dist/core/config-adopt/index.js +3 -0
  42. package/dist/core/doctor/command-alias-cleanup.js +4 -1
  43. package/dist/core/doctor/current-project-guidance-nested.js +37 -6
  44. package/dist/core/doctor/current-project-guidance.js +11 -6
  45. package/dist/core/doctor/doctor-readiness-matrix.js +14 -0
  46. package/dist/core/doctor/retired-managed-residue-private.js +1 -1
  47. package/dist/core/doctor/sks-menubar-doctor.js +4 -0
  48. package/dist/core/feature-fixtures.js +8 -0
  49. package/dist/core/hooks-runtime/hook-context.js +9 -0
  50. package/dist/core/hooks-runtime/managed-skill-admission.js +54 -4
  51. package/dist/core/hooks-runtime/official-subagent-lifecycle.js +69 -1
  52. package/dist/core/hooks-runtime/subagent-skill-availability-contract.js +2 -2
  53. package/dist/core/hooks-runtime/subagent-skill-availability-evidence.js +3 -3
  54. package/dist/core/hooks-runtime/subagent-skill-availability-guards.js +43 -5
  55. package/dist/core/hooks-runtime/subagent-skill-availability.js +64 -30
  56. package/dist/core/hooks-runtime/subagent-stop-hook.js +15 -2
  57. package/dist/core/hooks-runtime.js +148 -4
  58. package/dist/core/imagegen/imagegen-capability.js +46 -0
  59. package/dist/core/imagegen/require-imagegen.js +2 -2
  60. package/dist/core/init/skills.js +17 -3
  61. package/dist/core/install/installed-package-smoke.js +8 -2
  62. package/dist/core/naruto/hardware-capacity-probe.js +9 -3
  63. package/dist/core/naruto/naruto-concurrency-governor.js +68 -24
  64. package/dist/core/perf/import-graph-budget.js +0 -1
  65. package/dist/core/product-design-app-server.js +13 -1
  66. package/dist/core/release/package-size-budget.js +2 -2
  67. package/dist/core/release/release-pack-receipt.js +1 -2
  68. package/dist/core/routes/dollar-manifest-lite.js +1 -1
  69. package/dist/core/routes.js +1 -1
  70. package/dist/core/security/private-credential-file.js +209 -0
  71. package/dist/core/subagents/agent-catalog.js +17 -32
  72. package/dist/core/subagents/naruto-help-contract.js +5 -5
  73. package/dist/core/subagents/official-subagent-config.js +16 -6
  74. package/dist/core/subagents/official-subagent-preparation.js +34 -15
  75. package/dist/core/subagents/official-subagent-prompt.js +4 -4
  76. package/dist/core/subagents/official-subagent-runner.js +27 -4
  77. package/dist/core/subagents/thread-budget.js +19 -12
  78. package/dist/core/subagents/wave-lifecycle.js +18 -6
  79. package/dist/core/telegram/access.js +54 -0
  80. package/dist/core/telegram/client.js +144 -0
  81. package/dist/core/telegram/confirmation.js +37 -0
  82. package/dist/core/telegram/doctor.js +151 -0
  83. package/dist/core/telegram/index.js +9 -0
  84. package/dist/core/telegram/keychain.js +265 -0
  85. package/dist/core/telegram/liveness.js +109 -0
  86. package/dist/core/telegram/poller.js +90 -0
  87. package/dist/core/telegram/redaction.js +15 -0
  88. package/dist/core/telegram/types.js +1 -0
  89. package/dist/core/update/update-diagnostics.js +52 -0
  90. package/dist/core/update/update-migration-state.js +5 -1
  91. package/dist/core/update/update-operation.js +2 -1
  92. package/dist/core/update/update-stage-diagnostics.js +38 -0
  93. package/dist/core/update/update-status.js +2 -9
  94. package/dist/core/update-check.js +147 -31
  95. package/dist/core/version.js +1 -1
  96. package/dist/core/zellij/zellij-launcher.js +23 -4
  97. package/dist/native/sks-menubar/Sources/AppDelegate.swift +13 -0
  98. package/dist/native/sks-menubar/Sources/AppIdentity.swift +7 -0
  99. package/dist/native/sks-menubar/Sources/OperationCoordinator.swift +3 -2
  100. package/dist/native/sks-menubar/Sources/ProvidersConnectTest.swift +115 -0
  101. package/dist/native/sks-menubar/Sources/ProvidersFastMode.swift +17 -0
  102. package/dist/native/sks-menubar/Sources/ProvidersRoutingTruth.swift +190 -0
  103. package/dist/native/sks-menubar/Sources/ProvidersViewController.swift +100 -59
  104. package/dist/native/sks-menubar/Sources/SingletonInstanceGuard.swift +328 -0
  105. package/dist/native/sks-menubar/Sources/TelegramPrivateFileStore.swift +320 -0
  106. package/dist/native/sks-menubar/Sources/TelegramPrivateFileSupport.swift +303 -0
  107. package/dist/native/sks-menubar/Sources/TelegramProcessGateway.swift +238 -0
  108. package/dist/native/sks-menubar/Sources/TelegramRuntimeSupport.swift +56 -0
  109. package/dist/native/sks-menubar/Sources/TelegramSupport.swift +56 -0
  110. package/dist/native/sks-menubar/Sources/TelegramTransport.swift +474 -0
  111. package/dist/native/sks-menubar/Sources/main.swift +15 -1
  112. package/dist/native/sks-menubar/Tests/OperationCoordinatorTests.swift +4 -3
  113. package/dist/native/sks-menubar/Tests/ProvidersViewControllerTests.swift +129 -0
  114. package/dist/native/sks-menubar/Tests/SingletonInstanceGuardTests.swift +183 -0
  115. package/dist/native/sks-menubar/Tests/TelegramRuntimeSmokeTests.swift +267 -0
  116. package/dist/native/sks-menubar/Tests/TelegramRuntimeTests.swift +222 -0
  117. package/dist/scripts/codex-lb-fast-mode-truth-check.js +1 -1
  118. package/dist/scripts/codex-lb-fast-ui-preservation-check.js +1 -1
  119. package/dist/scripts/current-command-surface-check.js +2 -4
  120. package/dist/scripts/official-subagent-workflow-check.js +1 -1
  121. package/dist/scripts/packlist-performance-check.js +1 -2
  122. package/package.json +1 -1
@@ -3,14 +3,15 @@ import { probeHardwareCapacity } from './hardware-capacity-probe.js';
3
3
  import { applyNarutoBackpressure } from './naruto-backpressure.js';
4
4
  import { monitorNarutoResourcePressure } from './resource-pressure-monitor.js';
5
5
  export function decideNarutoConcurrency(input = {}) {
6
- const frameBudget = clamp(input.maxThreads ?? DEFAULT_NARUTO_MAX_THREADS, 1, HARD_NARUTO_MAX_THREADS);
7
- const requestedWorkers = normalizePositiveInt(input.requestedWorkers, Math.min(8, frameBudget));
6
+ const frameBudget = boundedThreadCount(input.maxThreads ?? DEFAULT_NARUTO_MAX_THREADS, 'max_threads');
7
+ const requestedWorkers = boundedThreadCount(input.requestedWorkers ?? Math.min(8, frameBudget), 'requested_workers');
8
8
  const totalWorkItems = normalizePositiveInt(input.totalWorkItems, requestedWorkers);
9
9
  const pending = normalizeNonNegativeInt(input.pendingWorkQueueSize, totalWorkItems);
10
10
  const leaseConflicts = normalizeNonNegativeInt(input.activeLeaseConflicts, 0);
11
11
  const hardware = probeHardwareCapacity(input.hardware || {});
12
12
  const zellijVisiblePaneCap = normalizePositiveInt(input.zellijVisiblePaneCap, Math.min(frameBudget, Math.max(4, Math.floor(hardware.terminal_rows / 5))));
13
13
  const backend = String(input.backend || 'codex-sdk');
14
+ const officialSubagentLane = backend === 'official-subagent';
14
15
  const parallelismMode = normalizeParallelismMode(input.parallelismMode);
15
16
  const freeGb = hardware.free_memory_bytes / (1024 * 1024 * 1024);
16
17
  const totalGb = hardware.total_memory_bytes / (1024 * 1024 * 1024);
@@ -29,17 +30,28 @@ export function decideNarutoConcurrency(input = {}) {
29
30
  const gitWorktreeCap = normalizePositiveInt(process.env.SKS_NARUTO_GIT_WORKTREE_CAP, Math.min(requestedWorkers, processCap));
30
31
  const localLlmParallel = Math.max(1, Math.min(frameBudget, hardware.local_llm_max_parallel_requests));
31
32
  const remoteCodexParallel = Math.max(1, Math.min(hardware.remote_api_rate_limit_budget, requestedWorkers, frameBudget));
32
- const backendBudget = backend === 'ollama' || backend === 'local-llm'
33
- ? localLlmParallel
34
- : backend === 'codex-sdk' || backend === 'zellij'
35
- ? Math.min(remoteCodexParallel, processCap)
36
- : processCap;
33
+ const externalCodexHostCap = input.externalCodexHostCap === undefined
34
+ ? null
35
+ : boundedThreadCount(input.externalCodexHostCap, 'external_codex_host_cap');
36
+ const explicitRemoteApiBudget = hardware.remote_api_rate_limit_budget_source !== 'default_unmeasured';
37
+ const backendBudget = officialSubagentLane
38
+ ? explicitRemoteApiBudget ? remoteCodexParallel : frameBudget
39
+ : backend === 'ollama' || backend === 'local-llm'
40
+ ? localLlmParallel
41
+ : backend === 'codex-sdk' || backend === 'zellij'
42
+ ? Math.min(remoteCodexParallel, processCap)
43
+ : processCap;
37
44
  const queueCap = Math.max(1, Math.min(requestedWorkers, pending || totalWorkItems));
38
45
  const leaseCap = Math.max(1, requestedWorkers - leaseConflicts);
39
- const rawSafe = Math.max(1, Math.min(requestedWorkers, totalWorkItems, memoryCap, fdCap, cpuCap, gitWorktreeCap, processCap, backendBudget, queueCap, leaseCap, frameBudget));
46
+ const localWorkerBounds = officialSubagentLane
47
+ ? []
48
+ : [memoryCap, fdCap, cpuCap, gitWorktreeCap, processCap];
49
+ const rawSafe = Math.max(1, Math.min(requestedWorkers, totalWorkItems, ...localWorkerBounds, backendBudget, queueCap, leaseCap, ...(externalCodexHostCap === null ? [] : [externalCodexHostCap]), frameBudget));
40
50
  const pressure = monitorNarutoResourcePressure(hardware, { activeWorkers: rawSafe, zellijVisiblePaneCap });
41
51
  const backpressure = applyNarutoBackpressure(rawSafe, pressure);
42
- const currentSafeActiveWorkers = Math.max(1, Math.min(rawSafe, backpressure.adjusted_active_workers));
52
+ const currentSafeActiveWorkers = officialSubagentLane
53
+ ? rawSafe
54
+ : Math.max(1, Math.min(rawSafe, backpressure.adjusted_active_workers));
43
55
  const modeCap = parallelismMode === 'safe'
44
56
  ? Math.max(1, Math.ceil(rawSafe * 0.5))
45
57
  : parallelismMode === 'balanced'
@@ -47,17 +59,46 @@ export function decideNarutoConcurrency(input = {}) {
47
59
  : rawSafe;
48
60
  const safeActiveWorkers = Math.max(1, Math.min(modeCap, currentSafeActiveWorkers));
49
61
  const safeVisible = Math.min(safeActiveWorkers, zellijVisiblePaneCap);
62
+ const exactLimiters = [
63
+ ...(externalCodexHostCap !== null && externalCodexHostCap === rawSafe
64
+ ? [`external_codex_host_cap:${externalCodexHostCap}`]
65
+ : []),
66
+ ...(frameBudget === rawSafe && frameBudget < requestedWorkers
67
+ ? [`naruto_max_threads_child_slot_cap:${frameBudget}`]
68
+ : []),
69
+ ...(backendBudget === rawSafe && backendBudget < requestedWorkers
70
+ ? [`backend_parallel_budget:${backendBudget}`]
71
+ : []),
72
+ ...(officialSubagentLane && explicitRemoteApiBudget && remoteCodexParallel === rawSafe
73
+ && remoteCodexParallel < requestedWorkers
74
+ ? [`remote_api_rate_limit_budget:${remoteCodexParallel}`]
75
+ : []),
76
+ ...(!officialSubagentLane && memoryCap === rawSafe && memoryCap < requestedWorkers ? [`memory_cap:${memoryCap}`] : []),
77
+ ...(!officialSubagentLane && fdCap === rawSafe && fdCap < requestedWorkers ? [`file_descriptor_budget:${fdCap}`] : []),
78
+ ...(!officialSubagentLane && cpuCap === rawSafe && cpuCap < requestedWorkers ? [`cpu_budget:${cpuCap}`] : []),
79
+ ...(!officialSubagentLane && gitWorktreeCap === rawSafe && gitWorktreeCap < requestedWorkers
80
+ ? [`git_worktree_budget:${gitWorktreeCap}`]
81
+ : []),
82
+ ...(queueCap === rawSafe && queueCap < requestedWorkers ? [`ready_queue_cap:${queueCap}`] : []),
83
+ ...(leaseCap === rawSafe && leaseCap < requestedWorkers ? [`lease_conflict_cap:${leaseCap}`] : []),
84
+ ...(!officialSubagentLane && safeActiveWorkers < rawSafe ? [`live_backpressure:${safeActiveWorkers}`] : [])
85
+ ];
50
86
  const reasons = [
51
- ...(memoryCap < requestedWorkers ? ['memory_cap'] : []),
52
- ...(fdCap < requestedWorkers ? ['file_descriptor_budget'] : []),
53
- ...(cpuCap + ioCap < requestedWorkers ? ['cpu_io_budget'] : []),
54
- ...(gitWorktreeCap + processCap < requestedWorkers ? ['git_worktree_process_budget'] : []),
87
+ ...(!officialSubagentLane && memoryCap < requestedWorkers ? ['memory_cap'] : []),
88
+ ...(!officialSubagentLane && fdCap < requestedWorkers ? ['file_descriptor_budget'] : []),
89
+ ...(!officialSubagentLane && cpuCap + ioCap < requestedWorkers ? ['cpu_io_budget'] : []),
90
+ ...(!officialSubagentLane && gitWorktreeCap + processCap < requestedWorkers ? ['git_worktree_process_budget'] : []),
55
91
  ...(backendBudget < requestedWorkers ? ['backend_parallel_budget'] : []),
56
- ...(remoteCodexParallel < requestedWorkers ? ['remote_api_rate_limit_budget'] : []),
57
- ...(frameBudget < requestedWorkers ? ['naruto_max_threads_frame_budget'] : []),
92
+ ...((!officialSubagentLane || explicitRemoteApiBudget) && remoteCodexParallel < requestedWorkers
93
+ ? [`remote_api_rate_limit_budget:${remoteCodexParallel}`]
94
+ : []),
95
+ ...(externalCodexHostCap !== null && externalCodexHostCap < requestedWorkers
96
+ ? [`external_codex_host_cap:${externalCodexHostCap}`]
97
+ : []),
98
+ ...(frameBudget < requestedWorkers ? [`naruto_max_threads_child_slot_cap:${frameBudget}`] : []),
58
99
  ...(safeVisible < safeActiveWorkers ? ['zellij_ui_pane_budget'] : []),
59
100
  ...(leaseConflicts > 0 ? ['active_lease_conflicts'] : []),
60
- ...pressure.reasons
101
+ ...(!officialSubagentLane ? pressure.reasons : [])
61
102
  ];
62
103
  return {
63
104
  schema: 'sks.naruto-concurrency-governor.v1',
@@ -68,13 +109,15 @@ export function decideNarutoConcurrency(input = {}) {
68
109
  headless_workers: Math.max(0, safeActiveWorkers - safeVisible),
69
110
  local_llm_parallel: localLlmParallel,
70
111
  remote_codex_parallel: remoteCodexParallel,
71
- process_parallel: processCap,
72
- git_worktree_parallel: gitWorktreeCap,
73
- cpu_io_parallel: cpuCap + ioCap,
112
+ process_parallel: officialSubagentLane ? frameBudget : processCap,
113
+ git_worktree_parallel: officialSubagentLane ? frameBudget : gitWorktreeCap,
114
+ cpu_io_parallel: officialSubagentLane ? frameBudget : cpuCap + ioCap,
74
115
  verification_parallel: Math.max(1, Math.min(2, safeActiveWorkers)),
116
+ external_codex_host_cap: externalCodexHostCap,
117
+ limiting_factors: [...new Set(exactLimiters)],
75
118
  parallelism_mode: parallelismMode,
76
119
  reasons: [...new Set(reasons)],
77
- backpressure: backpressure.backpressure,
120
+ backpressure: officialSubagentLane ? 'normal' : backpressure.backpressure,
78
121
  hardware
79
122
  };
80
123
  }
@@ -100,9 +143,10 @@ function normalizeNonNegativeInt(value, fallback) {
100
143
  return Math.max(0, Math.floor(fallback));
101
144
  return Math.floor(parsed);
102
145
  }
103
- function clamp(value, minimum, maximum) {
146
+ function boundedThreadCount(value, label) {
104
147
  const parsed = Number(value);
105
- if (!Number.isFinite(parsed))
106
- return minimum;
107
- return Math.max(minimum, Math.min(maximum, Math.floor(parsed)));
148
+ if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > HARD_NARUTO_MAX_THREADS) {
149
+ throw new RangeError(`${label}_must_be_integer_1_to_${HARD_NARUTO_MAX_THREADS}:${String(value)}`);
150
+ }
151
+ return parsed;
108
152
  }
@@ -4,7 +4,6 @@ import { writeJsonAtomic } from '../fsx.js';
4
4
  const NARUTO_AGENT_BRIDGE_FORBIDDEN_MODULES = [
5
5
  forbidden('command-registry', /src\/cli\/command-registry\.ts$/),
6
6
  forbidden('route-table', /src\/core\/routes\.ts$/),
7
- forbidden('telegram', /src\/core\/(?:commands\/telegram-command\.ts|telegram(?:\/|\.ts$))/),
8
7
  forbidden('remote', /src\/core\/(?:commands\/remote-command\.ts|remote(?:\/|\.ts$))/),
9
8
  forbidden('menubar', /(?:^|\/)(?:menubar|sks-menubar)(?:\/|[-.])/),
10
9
  forbidden('provider-ui', /(?:openrouter|provider-card|provider-model-ui|multi-provider)/i),
@@ -1,6 +1,7 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { PACKAGE_VERSION } from './version.js';
3
3
  import { EMPTY_CODEX_INFO, getCodexInfo } from './codex-adapter.js';
4
+ import { prepareCodexAppServerRuntimeEnv } from './codex-control/codex-app-server-runtime-env.js';
4
5
  import { PRODUCT_DESIGN_PLUGIN, normalizeProductDesignPluginEvidence } from './product-design-plugin.js';
5
6
  export const PRODUCT_DESIGN_AUTO_INSTALL_ENV = 'SKS_PRODUCT_DESIGN_AUTO_INSTALL';
6
7
  export function productDesignAutoInstallRequested(opts = {}) {
@@ -27,10 +28,21 @@ export async function ensureProductDesignPluginInstalled(opts = {}) {
27
28
  autoInstallProductDesign
28
29
  });
29
30
  }
31
+ let runtimeEnv;
32
+ try {
33
+ runtimeEnv = await (opts.prepareCodexRuntimeEnvImpl || prepareCodexAppServerRuntimeEnv)({
34
+ env: opts.env || process.env
35
+ });
36
+ }
37
+ catch (err) {
38
+ return productDesignAppServerUnavailable('product_design_app_server_credentials_unavailable', err?.message || String(err), {
39
+ autoInstallProductDesign
40
+ });
41
+ }
30
42
  const client = new CodexAppServerJsonRpcClient({
31
43
  command: codex.bin,
32
44
  args: opts.appServerArgs || ['app-server', '--stdio'],
33
- env: opts.env || process.env,
45
+ env: runtimeEnv,
34
46
  timeoutMs: opts.timeoutMs || 20000,
35
47
  cwd: opts.cwd || process.cwd()
36
48
  });
@@ -1,2 +1,2 @@
1
- export const DEFAULT_MAX_PACK_BYTES = 2725 * 1024;
2
- export const DEFAULT_MAX_UNPACKED_BYTES = 12_500_000;
1
+ export const DEFAULT_MAX_PACK_BYTES = 2800 * 1024;
2
+ export const DEFAULT_MAX_UNPACKED_BYTES = 12_950_000;
@@ -312,8 +312,7 @@ const RETIRED_SURFACE_PATTERNS = [
312
312
  { kind: 'retired_team_lane_label', regex: /\b(?:Balanced Team Lane|Full Team Honest Path|full Team\/Honest proof path)\b/gi }
313
313
  ];
314
314
  const RETIRED_PACKAGED_FILE_PATTERNS = [
315
- /^package\/dist\/core\/commands\/telegram-command\.js$/,
316
- /^package\/dist\/core\/telegram(?:\/|\.js$)/,
315
+ /^package\/dist\/core\/telegram\/controller\.js$/,
317
316
  /^package\/dist\/core\/commands\/ui-command\.js$/,
318
317
  /^package\/dist\/core\/ui\/dashboard-html\.js$/,
319
318
  /^package\/dist\/core\/zellij\/zellij-dashboard-(?:pane|renderer)\.js$/,
@@ -1,5 +1,5 @@
1
1
  import { normalizeDollarSkillName, prefixKnownSksDollarReferences, sksPrefixedDollarCommand } from './dollar-prefix.js';
2
- const NARUTO_DESCRIPTION = '$Naruto is the lightweight Codex official subagent workflow and the default for non-trivial execution. The Sol Max parent dynamically scales useful independent children from a bounded four/six/eight starting policy up to the safe capacity ceiling (default 12); max_threads is a cap, never a target. Healthy host CPU/memory/API budget may raise the automatic count toward that ceiling, and live pressure may shrink it. Capacity is the minimum of ready DAG width, disjoint ownership, verifier/tool capacity, reserved thread slots, and positive marginal usefulness. Child routing is fixed to Luna Max mechanical, Sol High implementation, Sol Max judgment, and Terra Medium long-context/Computer Use/Browser/ImageGen execution. Duplicate slices and overlapping writes are blocked; explicit --agents remains authoritative.';
2
+ const NARUTO_DESCRIPTION = '$Naruto is the lightweight Codex official subagent workflow and the default for non-trivial execution. The Sol Max parent dynamically scales useful independent children from a bounded four/six/eight starting policy up to the SKS-owned 256-child ceiling; max_threads is a cap, never a target. A measured lower Codex host cap or explicit provider/API budget remains authoritative. Capacity is the minimum of ready DAG width, disjoint ownership, verifier/tool capacity, available child slots, and positive marginal usefulness. Child routing is fixed to Luna Max mechanical, Sol High implementation, Sol Max judgment, and Terra Medium long-context/Computer Use/Browser/ImageGen execution. Duplicate slices and overlapping writes are blocked; explicit --agents remains authoritative.';
3
3
  const COMPUTER_USE_DESCRIPTION = 'Maximum-speed Codex Computer Use lane for native macOS, desktop-app, OS-settings, and non-web visual tasks only. Browser, localhost, website, webapp, and web-based app verification must route through Codex Chrome Extension readiness first.';
4
4
  const DOLLAR_COMMANDS_LITE_BASE = [
5
5
  { command: '$DFix', route: 'fast direct fix', description: 'Tiny simple direct edits such as copy, labels, typos, wording, spacing, colors, or clearly scoped one-line changes. Bypasses the general SKS pipeline and runs an ultralight, no-record task-list path.' },
@@ -649,7 +649,7 @@ export const COMMAND_CATALOG = [
649
649
  { name: 'codex-app', usage: 'sks codex-app [check|set-openrouter-key --api-key-stdin|use-openrouter --model <id>|openrouter-status|product-design|chrome-extension|pat status|remote-control]', description: 'Check Codex App install, OpenRouter provider activation, codex-lb key-entry guidance, Product Design plugin readiness, Codex Chrome Extension web verification readiness, PAT-safe status, first-party MCP/plugin readiness, and Codex CLI remote-control availability.' },
650
650
  { name: 'codex-native', usage: 'sks codex-native status|feature-broker|invocation-plan|init-deep [--json]', description: 'Inspect Codex Native feature broker readiness, invocation routing, pattern evidence, and managed memory setup.' },
651
651
  { name: 'hooks', usage: 'sks hooks explain|status|trust-report|replay|codex-validate|warning-check ... [--json]', description: 'Explain Codex hook events, validate vendored latest 10-event output schemas, replay fixtures, and enforce warning-zero SKS hook policies under the 0.134 compatibility matrix.' },
652
- { name: 'codex-lb', usage: 'sks codex-lb status|health|metrics|doctor|circuit|repair|setup ...', description: 'Configure, health-check, repair, and record circuit evidence for codex-lb provider auth without confusing ChatGPT OAuth and proxy keys.' },
652
+ { name: 'codex-lb', usage: 'sks codex-lb status|connect-test|health|metrics|doctor|circuit|repair|setup ...', description: 'Configure, run a one-request connection proof, health-check, repair, and record circuit evidence for codex-lb provider auth without confusing ChatGPT OAuth and proxy keys.' },
653
653
  { name: 'remote', usage: 'sks remote readiness|machines|worker ... [--json]', description: 'Inspect official Codex Remote readiness and the allowlisted proof-aware SSH stdio worker surface.' },
654
654
  { name: 'zellij', usage: 'sks zellij status|repair [--json] | sks --mad', description: 'Inspect Zellij runtime status, explain repair (no auto-install), and open the SKS Zellij runtime used by MAD. Zellij panes are not official Naruto subagent evidence.' },
655
655
  { name: 'mad-sks', usage: 'sks mad-sks plan|run|apply|sql|apply-migration|status|close|rollback-apply ... | sks --mad [--high]', description: 'Open or inspect MAD-SKS scoped permission workflows, merged SQL-plane execution, and the Zellij permission launcher.' },
@@ -0,0 +1,209 @@
1
+ import fsp from 'node:fs/promises';
2
+ import { constants as fsConstants } from 'node:fs';
3
+ import { createHash, randomBytes } from 'node:crypto';
4
+ import path from 'node:path';
5
+ import { assertTestHomeWriteAllowed } from '../fsx.js';
6
+ import { ensureConfinedDirectory, inspectConfinedPath, isLexicallyConfined } from '../managed-path-safety.js';
7
+ export class PrivateCredentialFileError extends Error {
8
+ code;
9
+ file;
10
+ label;
11
+ constructor(code, file, label) {
12
+ super(`${label}_${code}:${file}`);
13
+ this.name = 'PrivateCredentialFileError';
14
+ this.code = code;
15
+ this.file = file;
16
+ this.label = label;
17
+ }
18
+ }
19
+ export async function readPrivateCredentialFile(boundary, file, label, opts = {}) {
20
+ if (opts.maxBytes !== undefined && (!Number.isSafeInteger(opts.maxBytes) || opts.maxBytes < 0)) {
21
+ throw new RangeError('maxBytes must be a non-negative safe integer');
22
+ }
23
+ if (!isLexicallyConfined(boundary, file))
24
+ throw new PrivateCredentialFileError('outside_boundary', file, label);
25
+ const inspected = await inspectConfinedPath(boundary, file);
26
+ if (!inspected.exists)
27
+ throw new PrivateCredentialFileError('missing', file, label);
28
+ if (inspected.leafSymlink || !inspected.stat?.isFile()) {
29
+ throw new PrivateCredentialFileError('not_regular', file, label);
30
+ }
31
+ if ((inspected.stat.mode & 0o777) !== 0o600) {
32
+ throw new PrivateCredentialFileError('mode_not_0600', file, label);
33
+ }
34
+ const expectedUid = typeof process.getuid === 'function' ? process.getuid() : null;
35
+ if (expectedUid !== null && inspected.stat.uid !== expectedUid) {
36
+ throw new PrivateCredentialFileError('owner_mismatch', file, label);
37
+ }
38
+ let handle = null;
39
+ try {
40
+ handle = await fsp.open(file, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
41
+ const before = await handle.stat();
42
+ if (!before.isFile()
43
+ || before.dev !== inspected.stat.dev
44
+ || before.ino !== inspected.stat.ino
45
+ || (before.mode & 0o777) !== 0o600
46
+ || (expectedUid !== null && before.uid !== expectedUid)) {
47
+ throw new PrivateCredentialFileError('identity_mismatch', file, label);
48
+ }
49
+ if (opts.maxBytes !== undefined && before.size > opts.maxBytes) {
50
+ throw new PrivateCredentialFileError('too_large', file, label);
51
+ }
52
+ const bytes = opts.maxBytes === undefined
53
+ ? await handle.readFile()
54
+ : await readBounded(handle, opts.maxBytes, file, label);
55
+ const after = await handle.stat();
56
+ const pathAfter = await inspectConfinedPath(boundary, file);
57
+ if (!pathAfter.exists
58
+ || pathAfter.leafSymlink
59
+ || !pathAfter.stat?.isFile()
60
+ || (after.mode & 0o777) !== 0o600
61
+ || (pathAfter.stat.mode & 0o777) !== 0o600
62
+ || (expectedUid !== null && (after.uid !== expectedUid || pathAfter.stat.uid !== expectedUid))
63
+ || before.dev !== after.dev
64
+ || before.ino !== after.ino
65
+ || before.size !== after.size
66
+ || before.mtimeMs !== after.mtimeMs
67
+ || after.dev !== pathAfter.stat.dev
68
+ || after.ino !== pathAfter.stat.ino) {
69
+ throw new PrivateCredentialFileError('changed_during_verification', file, label);
70
+ }
71
+ return {
72
+ bytes,
73
+ sha256: createHash('sha256').update(bytes).digest('hex')
74
+ };
75
+ }
76
+ finally {
77
+ await handle?.close().catch(() => undefined);
78
+ }
79
+ }
80
+ async function readBounded(handle, maxBytes, file, label) {
81
+ const chunks = [];
82
+ let total = 0;
83
+ for (;;) {
84
+ const chunk = Buffer.allocUnsafe(Math.min(16 * 1024, maxBytes + 1 - total));
85
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
86
+ if (bytesRead === 0)
87
+ break;
88
+ total += bytesRead;
89
+ if (total > maxBytes)
90
+ throw new PrivateCredentialFileError('too_large', file, label);
91
+ chunks.push(chunk.subarray(0, bytesRead));
92
+ }
93
+ return Buffer.concat(chunks, total);
94
+ }
95
+ export async function hardenPrivateCredentialFileMode(boundary, file, label) {
96
+ if (!isLexicallyConfined(boundary, file))
97
+ throw new PrivateCredentialFileError('outside_boundary', file, label);
98
+ const inspected = await inspectConfinedPath(boundary, file);
99
+ if (!inspected.exists)
100
+ throw new PrivateCredentialFileError('missing', file, label);
101
+ if (inspected.leafSymlink || !inspected.stat?.isFile()) {
102
+ throw new PrivateCredentialFileError('not_regular', file, label);
103
+ }
104
+ const expectedUid = typeof process.getuid === 'function' ? process.getuid() : null;
105
+ if (expectedUid !== null && inspected.stat.uid !== expectedUid) {
106
+ throw new PrivateCredentialFileError('owner_mismatch', file, label);
107
+ }
108
+ let handle = null;
109
+ try {
110
+ handle = await fsp.open(file, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
111
+ const before = await handle.stat();
112
+ if (!before.isFile()
113
+ || before.dev !== inspected.stat.dev
114
+ || before.ino !== inspected.stat.ino
115
+ || (expectedUid !== null && before.uid !== expectedUid)) {
116
+ throw new PrivateCredentialFileError('identity_mismatch', file, label);
117
+ }
118
+ await handle.chmod(0o600);
119
+ const after = await handle.stat();
120
+ if ((after.mode & 0o777) !== 0o600 || after.dev !== before.dev || after.ino !== before.ino) {
121
+ throw new PrivateCredentialFileError('identity_mismatch', file, label);
122
+ }
123
+ }
124
+ finally {
125
+ await handle?.close().catch(() => undefined);
126
+ }
127
+ }
128
+ export async function writePrivateTextAtomic(boundary, file, text, label) {
129
+ if (!isLexicallyConfined(boundary, file))
130
+ throw new PrivateCredentialFileError('outside_boundary', file, label);
131
+ assertTestHomeWriteAllowed(file);
132
+ await ensureConfinedDirectory(boundary, path.dirname(file));
133
+ const before = await inspectConfinedPath(boundary, file);
134
+ if (before.exists && (before.leafSymlink || !before.stat?.isFile())) {
135
+ throw new PrivateCredentialFileError('not_regular', file, label);
136
+ }
137
+ if (before.stat && (before.stat.mode & 0o777) !== 0o600) {
138
+ throw new PrivateCredentialFileError('mode_not_0600', file, label);
139
+ }
140
+ const expectedUid = typeof process.getuid === 'function' ? process.getuid() : null;
141
+ if (before.stat && expectedUid !== null && before.stat.uid !== expectedUid) {
142
+ throw new PrivateCredentialFileError('owner_mismatch', file, label);
143
+ }
144
+ const temp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${randomBytes(8).toString('hex')}.tmp`);
145
+ let handle = null;
146
+ try {
147
+ handle = await fsp.open(temp, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_NOFOLLOW, 0o600);
148
+ await handle.chmod(0o600);
149
+ const tempStat = await handle.stat();
150
+ if (!tempStat.isFile()
151
+ || (tempStat.mode & 0o777) !== 0o600
152
+ || (expectedUid !== null && tempStat.uid !== expectedUid)) {
153
+ throw new PrivateCredentialFileError('identity_mismatch', temp, label);
154
+ }
155
+ await handle.writeFile(text, 'utf8');
156
+ await handle.sync();
157
+ await handle.close();
158
+ handle = null;
159
+ const current = await inspectConfinedPath(boundary, file);
160
+ const unchanged = before.exists === current.exists
161
+ && (!before.exists || (!current.leafSymlink
162
+ && current.stat?.isFile() === true
163
+ && before.stat?.dev === current.stat.dev
164
+ && before.stat?.ino === current.stat.ino));
165
+ if (!unchanged)
166
+ throw new PrivateCredentialFileError('changed_during_verification', file, label);
167
+ await fsp.rename(temp, file);
168
+ const parentHandle = await fsp.open(path.dirname(file), fsConstants.O_RDONLY);
169
+ try {
170
+ await parentHandle.sync();
171
+ }
172
+ finally {
173
+ await parentHandle.close();
174
+ }
175
+ await readPrivateCredentialFile(boundary, file, label);
176
+ }
177
+ finally {
178
+ await handle?.close().catch(() => undefined);
179
+ await fsp.rm(temp, { force: true }).catch(() => undefined);
180
+ }
181
+ }
182
+ export async function createPrivateTextExclusive(boundary, file, text, label, opts = {}) {
183
+ if (!isLexicallyConfined(boundary, file))
184
+ throw new PrivateCredentialFileError('outside_boundary', file, label);
185
+ assertTestHomeWriteAllowed(file);
186
+ await ensureConfinedDirectory(boundary, path.dirname(file));
187
+ const temp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${randomBytes(8).toString('hex')}.claim`);
188
+ let handle = null;
189
+ try {
190
+ handle = await fsp.open(temp, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_NOFOLLOW, 0o600);
191
+ await handle.writeFile(text, 'utf8');
192
+ await handle.sync();
193
+ await handle.close();
194
+ handle = null;
195
+ await opts.beforePublish?.(temp);
196
+ await fsp.link(temp, file);
197
+ await readPrivateCredentialFile(boundary, file, label);
198
+ return true;
199
+ }
200
+ catch (error) {
201
+ if (error?.code === 'EEXIST')
202
+ return false;
203
+ throw error;
204
+ }
205
+ finally {
206
+ await handle?.close().catch(() => undefined);
207
+ await fsp.rm(temp, { force: true }).catch(() => undefined);
208
+ }
209
+ }
@@ -1,17 +1,16 @@
1
1
  import { MANAGED_OFFICIAL_SUBAGENT_ROLES, managedOfficialSubagentRoleByName } from '../managed-assets/managed-assets-manifest.js';
2
- import { decideNarutoConcurrency } from '../naruto/naruto-concurrency-governor.js';
3
2
  import { decideSubagentModel } from './model-policy.js';
4
- import { DEFAULT_NARUTO_MAX_THREADS } from './thread-budget.js';
3
+ import { HARD_NARUTO_MAX_THREADS } from './thread-budget.js';
5
4
  import { escapeRegExp } from '../text/regex.js';
6
5
  export const DEFAULT_AUTOMATIC_SUBAGENT_COUNT = 4;
7
6
  export const PARALLEL_AUTOMATIC_SUBAGENT_COUNT = 6;
8
7
  export const LARGE_SCALE_AUTOMATIC_SUBAGENT_COUNT = 8;
9
- export const MAX_AUTOMATIC_SUBAGENT_COUNT = 12;
8
+ export const MAX_AUTOMATIC_SUBAGENT_COUNT = HARD_NARUTO_MAX_THREADS;
10
9
  export const MAX_AUTOMATIC_REVIEWER_COUNT = 2;
11
10
  export const MAX_CRITICAL_AUTOMATIC_REVIEWER_COUNT = 3;
12
11
  export const MASS_PARALLEL_AUTOMATIC_SUBAGENT_COUNT = 16;
13
- export const MAX_MASS_AUTOMATIC_SUBAGENT_COUNT = 64;
14
- export const MAX_ON_DEMAND_SUBAGENT_ROLE_COUNT = MAX_AUTOMATIC_SUBAGENT_COUNT;
12
+ export const MAX_MASS_AUTOMATIC_SUBAGENT_COUNT = HARD_NARUTO_MAX_THREADS;
13
+ export const MAX_ON_DEMAND_SUBAGENT_ROLE_COUNT = 25;
15
14
  export function officialSubagentRoleCatalog() {
16
15
  return MANAGED_OFFICIAL_SUBAGENT_ROLES.map(roleSummary);
17
16
  }
@@ -92,9 +91,9 @@ export function officialSubagentFanoutPolicy(input = {}) {
92
91
  ? 'operator'
93
92
  : 'automatic';
94
93
  const explicit = countSource !== 'automatic';
95
- const explicitRequested = Number.isFinite(Number(input.requestedSubagents))
96
- ? Math.max(1, Math.floor(Number(input.requestedSubagents)))
97
- : DEFAULT_AUTOMATIC_SUBAGENT_COUNT;
94
+ const explicitRequested = input.requestedSubagents === undefined || input.requestedSubagents === null
95
+ ? DEFAULT_AUTOMATIC_SUBAGENT_COUNT
96
+ : boundedThreadCount(input.requestedSubagents, 'requested_subagents');
98
97
  const automatic = automaticSubagentFanout({
99
98
  ...(input.taskProfile === undefined ? {} : { taskProfile: input.taskProfile }),
100
99
  ...(input.goal === undefined ? {} : { goal: input.goal }),
@@ -152,7 +151,9 @@ function automaticSubagentFanout(input) {
152
151
  const automaticCeiling = massParallel ? MAX_MASS_AUTOMATIC_SUBAGENT_COUNT : MAX_AUTOMATIC_SUBAGENT_COUNT;
153
152
  const decomposedSliceCount = Number(input.independentSliceCount);
154
153
  const roleWidth = unique((input.suggestedRoles || []).map((role) => String(role || '').trim()).filter(Boolean)).length;
155
- const frameBudget = clamp(Number(input.maxThreads) || DEFAULT_NARUTO_MAX_THREADS, 1, automaticCeiling);
154
+ if (input.maxThreads !== undefined && input.maxThreads !== null) {
155
+ boundedThreadCount(input.maxThreads, 'max_threads');
156
+ }
156
157
  if (Number.isFinite(decomposedSliceCount) && decomposedSliceCount > 0) {
157
158
  const reviewerCeiling = criticalMultiDomain
158
159
  ? MAX_CRITICAL_AUTOMATIC_REVIEWER_COUNT
@@ -208,38 +209,22 @@ function automaticSubagentFanout(input) {
208
209
  baseCount = Math.max(DEFAULT_AUTOMATIC_SUBAGENT_COUNT, Math.min(PARALLEL_AUTOMATIC_SUBAGENT_COUNT, roleWidth + 1));
209
210
  reason = 'role_width_parallel';
210
211
  }
211
- const count = hardwareAwareAutomaticCount(baseCount, automaticCeiling, frameBudget, input.hardware);
212
+ const count = Math.min(baseCount, automaticCeiling);
212
213
  return {
213
214
  count,
214
215
  ceiling: automaticCeiling,
215
- reason: count > baseCount ? `${reason}+hardware_capacity_boost` : reason,
216
+ reason,
216
217
  riskDomains,
217
218
  criticalMultiDomain: Boolean(criticalMultiDomain),
218
219
  massParallel
219
220
  };
220
221
  }
221
- function hardwareAwareAutomaticCount(baseCount, ceiling, frameBudget, hardware) {
222
- const targetCeiling = clamp(ceiling, 1, ceiling);
223
- const floor = clamp(baseCount, 1, targetCeiling);
224
- try {
225
- const decision = decideNarutoConcurrency({
226
- requestedWorkers: targetCeiling,
227
- totalWorkItems: targetCeiling,
228
- parallelismMode: 'extreme',
229
- maxThreads: frameBudget,
230
- ...(hardware ? { hardware } : {})
231
- });
232
- const probe = decision.hardware;
233
- const cpuCap = Math.max(1, Math.floor(probe.cpu_core_count * 0.75));
234
- const freeGb = probe.free_memory_bytes / (1024 * 1024 * 1024);
235
- const memCap = Math.max(1, Math.floor(Math.max(0.5, freeGb - 2) / 1.5));
236
- const apiCap = Math.max(1, probe.remote_api_rate_limit_budget);
237
- const safe = clamp(Math.min(cpuCap, memCap, apiCap, targetCeiling), 1, targetCeiling);
238
- return Math.max(floor, safe);
239
- }
240
- catch {
241
- return floor;
222
+ function boundedThreadCount(value, label) {
223
+ const parsed = Number(value);
224
+ if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > HARD_NARUTO_MAX_THREADS) {
225
+ throw new RangeError(`${label}_must_be_integer_1_to_${HARD_NARUTO_MAX_THREADS}:${String(value)}`);
242
226
  }
227
+ return parsed;
243
228
  }
244
229
  function isReviewerOnlyFanout(roles) {
245
230
  const normalized = unique(roles.map((role) => String(role || '').trim()).filter(Boolean));
@@ -1,6 +1,6 @@
1
1
  import { NARUTO_PARENT_EFFORT, NARUTO_PARENT_MODEL } from './model-policy.js';
2
2
  import { NARUTO_ACTIONS } from '../safety/command-contract/types.js';
3
- import { DEFAULT_AUTOMATIC_SUBAGENT_COUNT, MAX_AUTOMATIC_REVIEWER_COUNT, MAX_AUTOMATIC_SUBAGENT_COUNT, MAX_CRITICAL_AUTOMATIC_REVIEWER_COUNT, officialSubagentRolePlan } from './agent-catalog.js';
3
+ import { DEFAULT_AUTOMATIC_SUBAGENT_COUNT, MAX_AUTOMATIC_REVIEWER_COUNT, MAX_AUTOMATIC_SUBAGENT_COUNT, MAX_CRITICAL_AUTOMATIC_REVIEWER_COUNT, MAX_MASS_AUTOMATIC_SUBAGENT_COUNT, officialSubagentRolePlan } from './agent-catalog.js';
4
4
  export const NARUTO_HELP_SCHEMA = 'sks.naruto-subagent-workflow.v1';
5
5
  export function renderNarutoUsage() {
6
6
  return [
@@ -28,8 +28,8 @@ export function renderNarutoUsage() {
28
28
  ' --json Emit machine-readable output.',
29
29
  '',
30
30
  'Automatic fan-out starts at 4/6/8, or 16 for eligible mass Luna/Terra work.',
31
- 'Normal automatic expansion stops at 12; the mass lane stops at 64.',
32
- 'The 256 value is a structural frame limit, not evidence of a live 256-agent load test.'
31
+ 'After decomposition, either lane may expand to 256 independent useful children.',
32
+ 'A measured lower Codex host or explicit provider/API limit remains authoritative.'
33
33
  ].join('\n');
34
34
  }
35
35
  export function buildNarutoHelpResult() {
@@ -50,9 +50,9 @@ export function buildNarutoHelpResult() {
50
50
  default_requested_subagents: DEFAULT_AUTOMATIC_SUBAGENT_COUNT,
51
51
  scaling_policy: 'dynamic_capacity_min_ready_dag_disjoint_verifier_tools_available_marginal',
52
52
  automatic_subagent_ceiling: MAX_AUTOMATIC_SUBAGENT_COUNT,
53
- mass_automatic_subagent_ceiling: 64,
53
+ mass_automatic_subagent_ceiling: MAX_MASS_AUTOMATIC_SUBAGENT_COUNT,
54
54
  absolute_hard_frame_cap: 256,
55
- fanout_contract: 'automatic fan-out starts at 4/6/8/16 for bounded, explicit-parallel, large-scale, and mass cheap-model Luna/Terra work; normal expansion ceilings at 12, mass expansion ceilings at 64, max_threads defaults to a 12-thread frame budget that is a cap rather than a target, and later waves reuse capacity up to the 256-thread absolute hard frame cap',
55
+ fanout_contract: 'automatic fan-out starts at 4/6/8/16 for bounded, explicit-parallel, large-scale, and mass cheap-model Luna/Terra work; after decomposition both lanes may expand to the 256-child SKS ceiling, max_threads defaults to a 256-child frame budget that is a cap rather than a target, measured lower Codex host and explicit provider/API limits remain authoritative, and later waves reuse capacity',
56
56
  automatic_reviewer_ceiling: MAX_AUTOMATIC_REVIEWER_COUNT,
57
57
  critical_multi_domain_reviewer_ceiling: MAX_CRITICAL_AUTOMATIC_REVIEWER_COUNT,
58
58
  max_threads_is_cap_not_target: true,
@@ -8,7 +8,7 @@ import { MANAGED_OFFICIAL_SUBAGENT_ROLES, managedOfficialSubagentRoleContent, ma
8
8
  import { DEFAULT_SUBAGENT_EFFORT, DEFAULT_SUBAGENT_MODEL } from './model-policy.js';
9
9
  import { HARD_NARUTO_MAX_THREADS } from './thread-budget.js';
10
10
  import { escapeRegExp } from '../text/regex.js';
11
- export const DEFAULT_OFFICIAL_SUBAGENT_MAX_THREADS = 12;
11
+ export const DEFAULT_OFFICIAL_SUBAGENT_MAX_THREADS = 256;
12
12
  export const DEFAULT_OFFICIAL_SUBAGENT_MAX_DEPTH = 1;
13
13
  export const DEFAULT_OFFICIAL_SUBAGENT_JOB_MAX_RUNTIME_SECONDS = 1200;
14
14
  export const DEFAULT_OFFICIAL_SUBAGENT_INTERRUPT_MESSAGE = true;
@@ -16,7 +16,7 @@ export const DEFAULT_OFFICIAL_SUBAGENT_ENABLED = true;
16
16
  export const DEFAULT_OFFICIAL_SUBAGENT_MODEL = DEFAULT_SUBAGENT_MODEL;
17
17
  export const DEFAULT_OFFICIAL_SUBAGENT_REASONING_EFFORT = DEFAULT_SUBAGENT_EFFORT;
18
18
  export const DEFAULT_MULTI_AGENT_V2_MAX_CONCURRENT_THREADS_PER_SESSION = DEFAULT_OFFICIAL_SUBAGENT_MAX_THREADS + 1;
19
- export const LEGACY_SKS_MAX_THREAD_VALUES = Object.freeze([4, 5, 6]);
19
+ export const LEGACY_SKS_MAX_THREAD_VALUES = Object.freeze([4, 5, 6, 12]);
20
20
  export const AGENTS_MAX_CONCURRENT_THREADS_KEY = 'max_concurrent_threads_per_session';
21
21
  export const LEGACY_AGENTS_MAX_THREADS_KEY = 'max_threads';
22
22
  export const LEGACY_AGENTS_JOB_MAX_RUNTIME_KEY = 'job_max_runtime_seconds';
@@ -34,7 +34,7 @@ export function mergeOfficialSubagentConfig(text = '', opts = {}) {
34
34
  next = removeExactLegacyManagedAgentBlocks(next);
35
35
  next = stripLegacyUnsupportedAgentKeys(next);
36
36
  }
37
- const targetMaxThreads = positiveInteger(opts.defaultMaxThreads) || DEFAULT_OFFICIAL_SUBAGENT_MAX_THREADS;
37
+ const targetMaxThreads = boundedManagedMaxThreads(opts.defaultMaxThreads, DEFAULT_OFFICIAL_SUBAGENT_MAX_THREADS);
38
38
  next = migrateLegacyMaxThreads(next, {
39
39
  sksOwned: opts.sksOwned === true,
40
40
  targetMaxThreads,
@@ -65,7 +65,7 @@ export function mergeOfficialMultiAgentV2FeatureConfig(text = '', opts = {}) {
65
65
  if (hasTomlTableKey(next, 'features', 'multi_agent_v2')) {
66
66
  next = removeTomlTableKey(next, 'features', 'multi_agent_v2');
67
67
  }
68
- const maxThreads = positiveInteger(opts.maxThreads) || DEFAULT_OFFICIAL_SUBAGENT_MAX_THREADS;
68
+ const maxThreads = boundedManagedMaxThreads(opts.maxThreads, DEFAULT_OFFICIAL_SUBAGENT_MAX_THREADS);
69
69
  const targetTotal = Math.max(1, maxThreads + 1);
70
70
  if (!hasTomlTable(next, 'features.multi_agent_v2')) {
71
71
  if (inheritedMaV2)
@@ -80,7 +80,8 @@ export function mergeOfficialMultiAgentV2FeatureConfig(text = '', opts = {}) {
80
80
  }
81
81
  if (opts.sksOwned === true) {
82
82
  next = upsertTomlTableKey(next, 'features.multi_agent_v2', 'enabled = true');
83
- if (!hasTomlTableKey(next, 'features.multi_agent_v2', 'max_concurrent_threads_per_session')) {
83
+ const currentTotal = readTomlTableInteger(next, 'features.multi_agent_v2', 'max_concurrent_threads_per_session');
84
+ if (currentTotal === DEFAULT_NARUTO_LEGACY_TOTAL_THREADS || currentTotal === null) {
84
85
  next = upsertTomlTableKey(next, 'features.multi_agent_v2', `max_concurrent_threads_per_session = ${targetTotal}`);
85
86
  }
86
87
  if (!hasTomlTableKey(next, 'features.multi_agent_v2', 'expose_spawn_agent_model_overrides')) {
@@ -103,6 +104,7 @@ export function mergeOfficialMultiAgentV2FeatureConfig(text = '', opts = {}) {
103
104
  }
104
105
  return ensureTrailingNewline(next);
105
106
  }
107
+ const DEFAULT_NARUTO_LEGACY_TOTAL_THREADS = 13;
106
108
  export async function readOfficialSubagentConfig(root, opts = {}) {
107
109
  const projectConfigPath = path.resolve(opts.projectConfigPath || path.join(root, '.codex', 'config.toml'));
108
110
  const home = opts.home || process.env.HOME || os.homedir();
@@ -157,7 +159,6 @@ export function officialSubagentConfigWarnings(text = '', inheritedText = '') {
157
159
  const inherited = configLayer(inheritedText, 'global');
158
160
  if (project.blockers.length || inherited.blockers.length)
159
161
  return [];
160
- const maxThreads = resolveLayeredValue(readAgentsMaxThreadsFromRecord(project.agents), readAgentsMaxThreadsFromRecord(inherited.agents), DEFAULT_OFFICIAL_SUBAGENT_MAX_THREADS, positiveInteger);
161
162
  const maxDepth = resolveLayeredValue(project.agents.max_depth, inherited.agents.max_depth, DEFAULT_OFFICIAL_SUBAGENT_MAX_DEPTH, positiveInteger);
162
163
  return [
163
164
  ...(maxDepth.value > 1
@@ -420,6 +421,15 @@ function resolveLayeredValue(projectValue, globalValue, fallback, validate) {
420
421
  function positiveInteger(value) {
421
422
  return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? value : null;
422
423
  }
424
+ function boundedManagedMaxThreads(value, fallback) {
425
+ if (value === undefined || value === null)
426
+ return fallback;
427
+ const parsed = positiveInteger(value);
428
+ if (parsed === null || parsed > HARD_NARUTO_MAX_THREADS) {
429
+ throw new RangeError(`max_threads_must_be_integer_1_to_${HARD_NARUTO_MAX_THREADS}:${String(value)}`);
430
+ }
431
+ return parsed;
432
+ }
423
433
  function booleanValue(value) {
424
434
  return typeof value === 'boolean' ? value : null;
425
435
  }