pi-crew 0.9.68 → 0.10.2

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 (253) hide show
  1. package/CHANGELOG.md +222 -0
  2. package/NOTICE.md +21 -0
  3. package/README.md +44 -2
  4. package/agents/analyst.md +1 -1
  5. package/agents/cold-verifier.md +3 -1
  6. package/agents/critic.md +1 -1
  7. package/agents/executor.md +1 -1
  8. package/agents/explorer.md +1 -1
  9. package/agents/planner.md +1 -1
  10. package/agents/reviewer.md +1 -1
  11. package/agents/security-reviewer.md +1 -1
  12. package/agents/test-engineer.md +1 -1
  13. package/agents/verifier.md +1 -1
  14. package/agents/writer.md +1 -1
  15. package/dist/index.mjs +68113 -60774
  16. package/docs/README.md +2 -0
  17. package/docs/actions-reference.md +31 -0
  18. package/docs/commands-reference.md +17 -6
  19. package/docs/resource-formats.md +13 -0
  20. package/package.json +4 -2
  21. package/schema.json +503 -91
  22. package/scripts/resource-sampler.mjs +36 -2
  23. package/skills/requirements-to-task-packet/SKILL.md +26 -0
  24. package/skills/widget-rendering/SKILL.md +7 -7
  25. package/src/agents/agent-config.ts +2 -1
  26. package/src/agents/discover-agents.ts +23 -14
  27. package/src/config/config-merge.ts +183 -0
  28. package/src/config/config-validation.ts +687 -0
  29. package/src/config/config.ts +22 -864
  30. package/src/config/defaults.ts +43 -2
  31. package/src/config/drift-detector.ts +1 -1
  32. package/src/config/env-vars.ts +691 -0
  33. package/src/config/role-tools.ts +11 -9
  34. package/src/config/sanitize-project-config.ts +172 -0
  35. package/src/config/types.ts +49 -1
  36. package/src/extension/async-notifier.ts +25 -2
  37. package/src/extension/crew-cleanup.ts +13 -0
  38. package/src/extension/crew-vibes/config.ts +2 -1
  39. package/src/extension/crew-vibes/footer.ts +19 -0
  40. package/src/extension/crew-vibes/index.ts +11 -1
  41. package/src/extension/plan-orchestrate.ts +132 -0
  42. package/src/extension/register.ts +8 -0
  43. package/src/extension/registration/command-registration.ts +1 -0
  44. package/src/extension/registration/commands/dashboard.ts +158 -0
  45. package/src/extension/registration/commands/index.ts +35 -0
  46. package/src/extension/registration/commands/manage.ts +303 -0
  47. package/src/extension/registration/commands/run.ts +228 -0
  48. package/src/extension/registration/commands/shared.ts +639 -0
  49. package/src/extension/registration/commands/status.ts +60 -0
  50. package/src/extension/registration/commands.ts +13 -1224
  51. package/src/extension/registration/foreground-run-controller.ts +10 -2
  52. package/src/extension/registration/lifecycle-handlers.ts +178 -17
  53. package/src/extension/registration/runtime-cleanup.ts +23 -5
  54. package/src/extension/registration/subagent-tools.ts +218 -9
  55. package/src/extension/registration/team-tool.ts +5 -1
  56. package/src/extension/registration/ui.ts +5 -4
  57. package/src/extension/rpc-hmac.ts +5 -3
  58. package/src/extension/team-tool/api/heartbeat.ts +47 -10
  59. package/src/extension/team-tool/api/plan-approval.ts +9 -0
  60. package/src/extension/team-tool/api/task-claims.ts +109 -40
  61. package/src/extension/team-tool/cancel.ts +84 -50
  62. package/src/extension/team-tool/dispatch/index.ts +1 -0
  63. package/src/extension/team-tool/dispatch/run.ts +4 -1
  64. package/src/extension/team-tool/doctor.ts +103 -1
  65. package/src/extension/team-tool/orchestrate.ts +66 -1
  66. package/src/extension/team-tool/plans.ts +192 -0
  67. package/src/extension/team-tool/respond.ts +197 -65
  68. package/src/extension/team-tool/run-deadline.ts +35 -3
  69. package/src/extension/team-tool/run-intent.ts +63 -0
  70. package/src/extension/team-tool/run.ts +74 -20
  71. package/src/extension/team-tool/status.ts +84 -26
  72. package/src/extension/team-tool.ts +11 -2
  73. package/src/hooks/registry.ts +1 -6
  74. package/src/i18n.ts +9 -0
  75. package/src/prompt/prompt-runtime.ts +521 -2
  76. package/src/prompt/worker-events-channel.ts +173 -0
  77. package/src/runtime/README.md +8 -8
  78. package/src/runtime/async-runner.ts +7 -3
  79. package/src/runtime/background-runner.ts +42 -14
  80. package/src/runtime/broker/broker-issuer.ts +9 -2
  81. package/src/runtime/broker/crew-broker-tokens.ts +43 -6
  82. package/src/runtime/broker/crew-broker.ts +838 -10
  83. package/src/runtime/broker/wait-status-cache.ts +157 -0
  84. package/src/runtime/budget-enforcement.ts +281 -0
  85. package/src/runtime/child-pi/child-pi-constants.ts +8 -0
  86. package/src/runtime/child-pi/child-pi-spawn.ts +60 -14
  87. package/src/runtime/child-pi/child-pi-streams.ts +21 -1
  88. package/src/runtime/child-pi/child-pi-timers.ts +324 -0
  89. package/src/runtime/child-pi/child-pi.ts +97 -201
  90. package/src/runtime/child-pi/mock-fixtures.ts +16 -2
  91. package/src/runtime/crew-agent-records.ts +259 -14
  92. package/src/runtime/delegate-spawn.ts +148 -0
  93. package/src/runtime/detached-run-results.ts +90 -0
  94. package/src/runtime/deterministic-ast.ts +2 -1
  95. package/src/runtime/dispatch-batch.ts +945 -0
  96. package/src/runtime/finalize-run.ts +557 -0
  97. package/src/runtime/goal-workflow/adaptive-plan.ts +116 -15
  98. package/src/runtime/goal-workflow/dynamic-workflow-runner.ts +8 -3
  99. package/src/runtime/goal-workflow/goal-state-store.ts +1 -1
  100. package/src/runtime/group-join.ts +11 -125
  101. package/src/runtime/live-session/live-session-runtime.ts +26 -1
  102. package/src/runtime/merge-gate.ts +32 -10
  103. package/src/runtime/merge-loop.ts +130 -0
  104. package/src/runtime/model/model-budget-summary.ts +53 -0
  105. package/src/runtime/model/model-fallback.ts +36 -2
  106. package/src/runtime/model/pi-args.ts +10 -0
  107. package/src/runtime/model/provider-extensions.ts +10 -0
  108. package/src/runtime/orphan-worker-registry.ts +1 -1
  109. package/src/runtime/output/output-validator.ts +45 -0
  110. package/src/runtime/parent-guard.ts +3 -1
  111. package/src/runtime/peer-dep.ts +2 -1
  112. package/src/runtime/per-write-validator.ts +0 -5
  113. package/src/runtime/pi-spawn.ts +61 -15
  114. package/src/runtime/plan-approval.ts +125 -0
  115. package/src/runtime/plan-replan.ts +151 -0
  116. package/src/runtime/process-status.ts +16 -1
  117. package/src/runtime/recovery/checkpoint.ts +0 -18
  118. package/src/runtime/recovery/crash-recovery.ts +111 -46
  119. package/src/runtime/run-tracker.ts +77 -10
  120. package/src/runtime/scheduler-context.ts +98 -0
  121. package/src/runtime/scheduling/coalesce-tasks.ts +5 -0
  122. package/src/runtime/scheduling/global-worker-cap.ts +2 -1
  123. package/src/runtime/scheduling/nested-slots.ts +70 -0
  124. package/src/runtime/scheduling/run-coalesced-task-group.ts +64 -13
  125. package/src/runtime/scheduling/task-graph-scheduler.ts +0 -10
  126. package/src/runtime/settings-store.ts +219 -0
  127. package/src/runtime/spawn-policy.ts +217 -0
  128. package/src/runtime/stale-reconciler.ts +87 -6
  129. package/src/runtime/subagent-manager.ts +25 -1
  130. package/src/runtime/task-output-context.ts +230 -9
  131. package/src/runtime/task-packet.ts +23 -1
  132. package/src/runtime/task-runner/child-executor.ts +106 -7
  133. package/src/runtime/task-runner/post-execution.ts +125 -1
  134. package/src/runtime/task-runner/pre-execution.ts +39 -1
  135. package/src/runtime/task-runner/prompt-builder.ts +51 -1
  136. package/src/runtime/task-runner/retrieval-orchestrator.ts +72 -18
  137. package/src/runtime/task-runner/spec-evidence.ts +403 -0
  138. package/src/runtime/task-runner/state-helpers.ts +26 -24
  139. package/src/runtime/task-runner.ts +11 -0
  140. package/src/runtime/team-runner.ts +132 -1673
  141. package/src/runtime/verification/spec-sandbox.ts +255 -0
  142. package/src/runtime/verification/verification-gates.ts +3 -2
  143. package/src/runtime/verification/verification-worktree.ts +2 -1
  144. package/src/runtime/workflow-phase-advance.ts +100 -0
  145. package/src/runtime/workspace-tree.ts +9 -0
  146. package/src/schema/config-schema.ts +66 -26
  147. package/src/schema/sensitive-config-paths.ts +64 -0
  148. package/src/schema/team-tool-schema.ts +13 -3
  149. package/src/state/README.md +4 -10
  150. package/src/state/atomic-write.ts +20 -3
  151. package/src/state/contracts.ts +38 -0
  152. package/src/state/coordination/mailbox.ts +12 -2
  153. package/src/state/event-log/cursor.ts +223 -0
  154. package/src/state/event-log/event-log-rotation.ts +12 -4
  155. package/src/state/event-log/event-log.ts +152 -369
  156. package/src/state/event-log/sequence-cache.ts +373 -0
  157. package/src/state/event-log/worker-atomic-writer.ts +2 -1
  158. package/src/state/stores/active-run-registry.ts +3 -2
  159. package/src/state/stores/manifest-io.ts +237 -0
  160. package/src/state/stores/ownership-map.ts +162 -0
  161. package/src/state/stores/plan-store.ts +241 -0
  162. package/src/state/stores/run-cache.ts +0 -90
  163. package/src/state/stores/spec-store.ts +189 -0
  164. package/src/state/stores/state-store.ts +139 -232
  165. package/src/state/types.ts +199 -0
  166. package/src/ui/dashboard-panes/plan-pane.ts +136 -0
  167. package/src/ui/dashboard-panes/progress-pane.ts +6 -0
  168. package/src/ui/dashboard-panes/transcript-pane.ts +31 -0
  169. package/src/ui/dock-footer.ts +49 -0
  170. package/src/ui/heartbeat-aggregator.ts +9 -1
  171. package/src/ui/inline-panel/agent-pane.ts +375 -0
  172. package/src/ui/inline-panel/agent-transcript.ts +338 -0
  173. package/src/ui/inline-panel/agent-view-overlay.ts +225 -0
  174. package/src/ui/inline-panel/crew-editor.ts +192 -0
  175. package/src/ui/inline-panel/index.ts +290 -0
  176. package/src/ui/inline-panel/panel-rows.ts +37 -0
  177. package/src/ui/inline-panel/panel-selection.ts +157 -0
  178. package/src/ui/inline-panel/panel-store.ts +111 -0
  179. package/src/ui/inline-panel/view-session-store.ts +36 -0
  180. package/src/ui/keybinding-map.ts +54 -13
  181. package/src/ui/pi-ui-compat.ts +9 -0
  182. package/src/ui/powerbar-publisher.ts +52 -1
  183. package/src/ui/run-dashboard.ts +31 -5
  184. package/src/ui/run-snapshot-cache.ts +57 -30
  185. package/src/ui/snapshot-types.ts +6 -1
  186. package/src/ui/widget/index.ts +176 -22
  187. package/src/ui/widget/task-list.ts +198 -0
  188. package/src/ui/widget/widget-formatters.ts +240 -4
  189. package/src/ui/widget/widget-renderer.ts +243 -38
  190. package/src/ui/widget/widget-types.ts +11 -0
  191. package/src/utils/child-process-shield.ts +106 -0
  192. package/src/utils/file-coalescer.ts +0 -4
  193. package/src/utils/fs-errno.ts +66 -0
  194. package/src/utils/fs-watch.ts +1 -1
  195. package/src/utils/internal-error.ts +3 -1
  196. package/src/utils/paths.ts +11 -3
  197. package/src/utils/redaction.ts +7 -0
  198. package/src/utils/safe-abort.ts +45 -0
  199. package/src/utils/task-name-generator.ts +1 -8
  200. package/src/workflows/discover-workflows.ts +20 -2
  201. package/src/workflows/validate-workflow.ts +7 -1
  202. package/src/workflows/workflow-config.ts +17 -0
  203. package/src/workflows/workflow-serializer.ts +3 -0
  204. package/src/worktree/worktree-manager.ts +22 -0
  205. package/workflows/default.workflow.md +36 -26
  206. package/workflows/strict-fast-fix.workflow.md +26 -0
  207. package/src/agents/agent-search.ts +0 -98
  208. package/src/benchmark/benchmark-runner.ts +0 -313
  209. package/src/benchmark/feedback-loop.ts +0 -73
  210. package/src/config/resilient-parser.ts +0 -117
  211. package/src/extension/crew-vibes/cat-frames.ts +0 -18
  212. package/src/extension/result-watcher.ts +0 -139
  213. package/src/observability/exporters/prometheus-exporter.ts +0 -54
  214. package/src/observability/metric-retention.ts +0 -64
  215. package/src/runtime/compaction/compaction-summary.ts +0 -278
  216. package/src/runtime/errors/crew-errors.ts +0 -162
  217. package/src/runtime/live-session/intercom-bridge.ts +0 -187
  218. package/src/runtime/loop-gates.ts +0 -128
  219. package/src/runtime/metric-parser.ts +0 -36
  220. package/src/runtime/output/stream-preview.ts +0 -184
  221. package/src/runtime/output/tool-progress.ts +0 -278
  222. package/src/runtime/phase-tracker.ts +0 -385
  223. package/src/runtime/pipeline-runner.ts +0 -523
  224. package/src/runtime/process/process-lifecycle.ts +0 -491
  225. package/src/runtime/recovery/retry-runner.ts +0 -330
  226. package/src/runtime/run-drift.ts +0 -219
  227. package/src/runtime/task-quality.ts +0 -199
  228. package/src/runtime/task-runner/run-projection.ts +0 -128
  229. package/src/runtime/verification/post-checks.ts +0 -142
  230. package/src/state/coordination/schedule.ts +0 -166
  231. package/src/state/event-log/jsonl-writer.ts +0 -115
  232. package/src/state/hook-instinct-bridge.ts +0 -94
  233. package/src/state/hook-integrations.ts +0 -51
  234. package/src/state/session-state-map.ts +0 -51
  235. package/src/state/stores/blob-store.ts +0 -308
  236. package/src/state/stores/instinct-store.ts +0 -275
  237. package/src/state/stores/observation-store.ts +0 -176
  238. package/src/state/tiered-eval.ts +0 -480
  239. package/src/state/types-eval.ts +0 -58
  240. package/src/tools/safe-bash-extension.ts +0 -54
  241. package/src/tools/safe-bash.ts +0 -505
  242. package/src/ui/agent-management-overlay.ts +0 -160
  243. package/src/ui/crew-footer.ts +0 -102
  244. package/src/ui/crew-select-list.ts +0 -114
  245. package/src/ui/dashboard-panes/capability-pane.ts +0 -77
  246. package/src/ui/transcript-entries.ts +0 -256
  247. package/src/utils/conflict-detect.ts +0 -721
  248. package/src/utils/fingerprint.ts +0 -180
  249. package/src/utils/gh-protocol.ts +0 -556
  250. package/src/utils/project-detector.ts +0 -160
  251. package/src/utils/sse-parser.ts +0 -131
  252. package/src/workflows/cost-estimator.ts +0 -34
  253. package/src/workflows/intermediate-store.ts +0 -166
@@ -1,15 +1,15 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as os from "node:os";
3
3
  import * as path from "node:path";
4
- import { type Static, type TSchema, Type } from "@sinclair/typebox";
5
- import { Value } from "@sinclair/typebox/value";
6
- import { PiTeamsAutonomyProfileSchema, PiTeamsConfigSchema } from "../schema/config-schema.ts";
7
4
  import { atomicWriteFile } from "../state/atomic-write.ts";
8
5
  import { withFileLockSync } from "../state/coordination/locks.ts";
9
6
  import { logInternalError } from "../utils/internal-error.ts";
10
7
  import { projectCrewRoot, projectPiRoot } from "../utils/paths.ts";
11
- import { DEFAULT_BROKER, resolveBrokerEnvOverride } from "./defaults.ts";
12
- import { suggestConfigKey } from "./suggestions.ts";
8
+ import { mergeConfig } from "./config-merge.ts";
9
+ import { parseConfig, parseConfigWithWarnings } from "./config-validation.ts";
10
+ import { DEFAULT_BROKER, DEFAULT_NESTING, resolveBrokerEnvOverride } from "./defaults.ts";
11
+ import { getCrewEnv } from "./env-vars.ts";
12
+ import { sanitizeProjectConfig } from "./sanitize-project-config.ts";
13
13
 
14
14
  // 2.9: interface types extracted to ./types.ts; re-export for back-compat.
15
15
  export type {
@@ -42,32 +42,22 @@ export type {
42
42
  } from "./types.ts";
43
43
 
44
44
  import type {
45
- AgentOverrideConfig,
46
- ConfigValidationResult,
47
- CrewAgentsConfig,
48
45
  CrewBrokerConfig,
49
- CrewControlConfig,
50
- CrewLimitsConfig,
51
- CrewNotificationsConfig,
52
- CrewObservabilityConfig,
53
- CrewOtlpConfig,
54
- CrewPolicyConfig,
55
- CrewReliabilityConfig,
56
- CrewRetryPolicyConfig,
57
- CrewRuntimeConfig,
58
- CrewTelemetryConfig,
59
- CrewToolsConfig,
60
- CrewUiConfig,
61
- CrewWorktreeConfig,
62
- GoalWrapWorkflowConfig,
46
+ CrewNestingConfig,
63
47
  LoadedPiTeamsConfig,
64
48
  PiTeamsAutonomousConfig,
65
- PiTeamsAutonomyProfile,
66
49
  PiTeamsConfig,
67
50
  SavedPiTeamsConfig,
68
51
  UpdateConfigOptions,
69
52
  } from "./types.ts";
70
53
 
54
+ export { __test__mergeConfig } from "./config-merge.ts";
55
+ // Phase 2.2 split: config.ts is the loader + public re-export shim.
56
+ // Public surface moved to sub-modules is re-exported here unchanged.
57
+ export { asRecord, effectiveAutonomousConfig } from "./config-validation.ts";
58
+ export { __test__sanitizeProjectConfig } from "./sanitize-project-config.ts";
59
+ export { parseConfig, parseConfigWithWarnings };
60
+
71
61
  // (F16) loadConfig was called 1 Hz idle / 6 Hz active with 0 cache — added 2s TTL+mtime cache following the manifestCache pattern in state-store.ts:75-130.
72
62
  const CONFIG_CACHE_TTL_MS = 2000;
73
63
 
@@ -171,7 +161,7 @@ export function invalidateConfigCache(): void {
171
161
  }
172
162
 
173
163
  function resolveHomeDir(): string {
174
- const envValue = (process.env.PI_TEAMS_HOME ?? process.env.PI_CREW_HOME)?.trim();
164
+ const envValue = getCrewEnv("PI_CREW_HOME")?.trim();
175
165
  const defaultHome = os.homedir();
176
166
  if (!envValue) return defaultHome;
177
167
  // FIX (Round 14): When PI_TEAMS_HOME is explicitly set, validate that
@@ -182,7 +172,7 @@ function resolveHomeDir(): string {
182
172
  // directory (e.g. withIsolatedHome) set PI_TEAMS_HOME to a tmp dir
183
173
  // under /tmp; we skip the check in test environments (NODE_ENV=test)
184
174
  // so existing tests don't break.
185
- if (process.env.PI_CREW_SKIP_HOME_CHECK === "1") {
175
+ if (getCrewEnv("PI_CREW_SKIP_HOME_CHECK") === "1") {
186
176
  return envValue;
187
177
  }
188
178
  // M-7 fix (code-review 2026-06-23): the previous `NODE_ENV === "test"` bypass
@@ -228,856 +218,23 @@ export function projectPiCrewJsonPath(cwd: string): string {
228
218
  return path.join(projectPiRoot(cwd), "pi-crew.json");
229
219
  }
230
220
 
231
- function withoutUndefined<T extends Record<string, unknown>>(value: T): Partial<T> {
232
- return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined)) as Partial<T>;
233
- }
234
-
235
- function errorPathFromValidation(error: unknown): string {
236
- if (error && typeof error === "object") {
237
- if (typeof (error as { path?: unknown }).path === "string") return (error as { path: string }).path;
238
- if (typeof (error as { instancePath?: unknown }).instancePath === "string") return (error as { instancePath: string }).instancePath;
239
- if (
240
- typeof (error as { keyword?: unknown }).keyword === "string" &&
241
- typeof (error as { schemaPath?: unknown }).schemaPath === "string"
242
- )
243
- return (error as { schemaPath: string }).schemaPath;
244
- }
245
- return "config";
246
- }
247
-
248
- /** Known top-level config keys from the schema — used for fuzzy suggestions. */
249
- const KNOWN_TOP_LEVEL_KEYS = Object.keys(PiTeamsConfigSchema.properties ?? {}) as string[];
250
-
251
- function validateConfigWithWarnings(raw: unknown): string[] {
252
- if (!Value.Check(PiTeamsConfigSchema, raw)) {
253
- return [...Value.Errors(PiTeamsConfigSchema, raw)].map((error) => {
254
- const path = errorPathFromValidation(error);
255
- const message = (error as { message?: unknown }).message ?? "invalid value";
256
- // Enhance "additionalProperties" errors with fuzzy suggestions
257
- if ((error as { keyword?: unknown }).keyword === "additionalProperties") {
258
- const offendingKey = path.split("/").pop() ?? path;
259
- const suggestion = suggestConfigKey(offendingKey, KNOWN_TOP_LEVEL_KEYS);
260
- if (suggestion) return `${path}: ${message} (did you mean '${suggestion}'?)`;
261
- }
262
- return `${path}: ${message}`;
263
- });
264
- }
265
- return [];
266
- }
267
-
268
- function projectOverrideWarning(projectPath: string, dottedPath: string): string {
269
- return `${projectPath}: project-level sensitive config '${dottedPath}' is ignored; set it in user config to trust it explicitly`;
270
- }
271
-
272
- function sanitizeProjectConfig(projectPath: string, userConfig: PiTeamsConfig, config: PiTeamsConfig): ConfigValidationResult {
273
- const sanitized: PiTeamsConfig = { ...config };
274
- const warnings: string[] = [];
275
- const dropTopLevel = (key: keyof PiTeamsConfig): void => {
276
- if (config[key] === undefined) return;
277
- delete sanitized[key];
278
- warnings.push(projectOverrideWarning(projectPath, String(key)));
279
- };
280
- dropTopLevel("executeWorkers");
281
- dropTopLevel("asyncByDefault");
282
- dropTopLevel("requireCleanWorktreeLeader");
283
- if (config.runtime) {
284
- const runtime = { ...config.runtime };
285
- for (const key of [
286
- "mode",
287
- "preferLiveSession",
288
- "allowChildProcessFallback",
289
- "inheritContext",
290
- "isolationPolicy",
291
- "agentExtensions",
292
- ] as const) {
293
- if (runtime[key] !== undefined) {
294
- delete runtime[key];
295
- warnings.push(projectOverrideWarning(projectPath, `runtime.${key}`));
296
- }
297
- }
298
- if (runtime.requirePlanApproval === false) {
299
- delete runtime.requirePlanApproval;
300
- warnings.push(projectOverrideWarning(projectPath, "runtime.requirePlanApproval"));
301
- }
302
- sanitized.runtime = Object.values(runtime).some((entry) => entry !== undefined) ? runtime : undefined;
303
- }
304
- if (config.autonomous) {
305
- const autonomous = { ...config.autonomous };
306
- for (const key of ["profile", "enabled", "injectPolicy", "preferAsyncForLongTasks", "allowWorktreeSuggestion"] as const) {
307
- if (autonomous[key] !== undefined) {
308
- delete autonomous[key];
309
- warnings.push(projectOverrideWarning(projectPath, `autonomous.${key}`));
310
- }
311
- }
312
- sanitized.autonomous = Object.values(autonomous).some((entry) => entry !== undefined) ? autonomous : undefined;
313
- }
314
- if (config.worktree?.setupHook !== undefined) {
315
- sanitized.worktree = { ...config.worktree, setupHook: undefined };
316
- if (!Object.values(sanitized.worktree).some((entry) => entry !== undefined)) sanitized.worktree = undefined;
317
- warnings.push(projectOverrideWarning(projectPath, "worktree.setupHook"));
318
- }
319
- if (config.otlp?.headers !== undefined) {
320
- sanitized.otlp = { ...config.otlp, headers: undefined };
321
- if (!Object.values(sanitized.otlp).some((entry) => entry !== undefined)) sanitized.otlp = undefined;
322
- warnings.push(projectOverrideWarning(projectPath, "otlp.headers"));
323
- }
324
- // FIX: Block project config from setting otlp.endpoint — it controls where
325
- // OTLP headers (potentially containing credentials) are sent.
326
- if (config.otlp?.endpoint !== undefined) {
327
- if (!sanitized.otlp) sanitized.otlp = { ...config.otlp, endpoint: undefined };
328
- else sanitized.otlp = { ...sanitized.otlp, endpoint: undefined };
329
- if (!Object.values(sanitized.otlp).some((entry) => entry !== undefined)) sanitized.otlp = undefined;
330
- warnings.push(projectOverrideWarning(projectPath, "otlp.endpoint"));
331
- }
332
- if (config.agents?.disableBuiltins !== undefined || config.agents?.overrides !== undefined) {
333
- const agents = { ...config.agents };
334
- if (agents.disableBuiltins !== undefined) {
335
- delete agents.disableBuiltins;
336
- warnings.push(projectOverrideWarning(projectPath, "agents.disableBuiltins"));
337
- }
338
- if (agents.overrides !== undefined) {
339
- delete agents.overrides;
340
- warnings.push(projectOverrideWarning(projectPath, "agents.overrides"));
341
- }
342
- sanitized.agents = Object.values(agents).some((entry) => entry !== undefined) ? agents : undefined;
343
- }
344
- if (config.tools?.enableSteer !== undefined || config.tools?.terminateOnForeground !== undefined) {
345
- const tools = { ...config.tools };
346
- if (tools.enableSteer !== undefined) {
347
- delete tools.enableSteer;
348
- warnings.push(projectOverrideWarning(projectPath, "tools.enableSteer"));
349
- }
350
- if (tools.terminateOnForeground !== undefined) {
351
- delete tools.terminateOnForeground;
352
- warnings.push(projectOverrideWarning(projectPath, "tools.terminateOnForeground"));
353
- }
354
- sanitized.tools = Object.values(tools).some((entry) => entry !== undefined) ? tools : undefined;
355
- }
356
- return { config: sanitized, warnings };
357
- }
358
-
359
- function mergeConfig(base: PiTeamsConfig, override: PiTeamsConfig): PiTeamsConfig {
360
- const warnings: string[] = [];
361
- const merged: PiTeamsConfig = {
362
- ...base,
363
- ...withoutUndefined(override as Record<string, unknown>),
364
- };
365
- if (base.autonomous || override.autonomous) {
366
- merged.autonomous = {
367
- ...(base.autonomous ?? {}),
368
- ...withoutUndefined((override.autonomous ?? {}) as Record<string, unknown>),
369
- };
370
- }
371
- if (base.limits || override.limits) {
372
- merged.limits = {
373
- ...(base.limits ?? {}),
374
- ...withoutUndefined((override.limits ?? {}) as Record<string, unknown>),
375
- };
376
- }
377
- if (base.runtime || override.runtime) {
378
- merged.runtime = {
379
- ...(base.runtime ?? {}),
380
- ...withoutUndefined((override.runtime ?? {}) as Record<string, unknown>),
381
- };
382
- }
383
- if (base.control || override.control) {
384
- merged.control = {
385
- ...(base.control ?? {}),
386
- ...withoutUndefined((override.control ?? {}) as Record<string, unknown>),
387
- };
388
- }
389
- if (base.worktree || override.worktree) {
390
- merged.worktree = {
391
- ...(base.worktree ?? {}),
392
- ...withoutUndefined((override.worktree ?? {}) as Record<string, unknown>),
393
- };
394
- }
395
- if (base.ui || override.ui) {
396
- merged.ui = {
397
- ...(base.ui ?? {}),
398
- ...withoutUndefined((override.ui ?? {}) as Record<string, unknown>),
399
- };
400
- }
401
- if (base.agents || override.agents) {
402
- merged.agents = {
403
- ...(base.agents ?? {}),
404
- ...withoutUndefined((override.agents ?? {}) as Record<string, unknown>),
405
- overrides: {
406
- ...(base.agents?.overrides ?? {}),
407
- ...(withoutUndefined((override.agents?.overrides ?? {}) as Record<string, unknown>) as Record<string, AgentOverrideConfig>),
408
- },
409
- };
410
- }
411
- if (base.tools || override.tools) {
412
- merged.tools = {
413
- ...(base.tools ?? {}),
414
- ...withoutUndefined((override.tools ?? {}) as Record<string, unknown>),
415
- };
416
- }
417
- if (base.telemetry || override.telemetry) {
418
- merged.telemetry = {
419
- ...(base.telemetry ?? {}),
420
- ...withoutUndefined((override.telemetry ?? {}) as Record<string, unknown>),
421
- };
422
- }
423
- if (base.policy || override.policy) {
424
- merged.policy = {
425
- ...(base.policy ?? {}),
426
- ...withoutUndefined((override.policy ?? {}) as Record<string, unknown>),
427
- };
428
- }
429
- if (base.notifications || override.notifications) {
430
- merged.notifications = {
431
- ...(base.notifications ?? {}),
432
- ...withoutUndefined((override.notifications ?? {}) as Record<string, unknown>),
433
- };
434
- }
435
- if (base.observability || override.observability) {
436
- merged.observability = {
437
- ...(base.observability ?? {}),
438
- ...withoutUndefined((override.observability ?? {}) as Record<string, unknown>),
439
- };
440
- }
441
- if (base.reliability || override.reliability) {
442
- merged.reliability = {
443
- ...(base.reliability ?? {}),
444
- ...withoutUndefined((override.reliability ?? {}) as Record<string, unknown>),
445
- retryPolicy:
446
- base.reliability?.retryPolicy || override.reliability?.retryPolicy
447
- ? {
448
- ...(base.reliability?.retryPolicy ?? {}),
449
- ...withoutUndefined((override.reliability?.retryPolicy ?? {}) as Record<string, unknown>),
450
- }
451
- : undefined,
452
- };
453
- }
454
- if (base.otlp || override.otlp) {
455
- merged.otlp = {
456
- ...(base.otlp ?? {}),
457
- ...withoutUndefined((override.otlp ?? {}) as Record<string, unknown>),
458
- headers: {
459
- ...(base.otlp?.headers ?? {}),
460
- ...(override.otlp?.headers ?? {}),
461
- },
462
- };
463
- if (Object.keys(merged.otlp.headers ?? {}).length === 0) delete merged.otlp.headers;
464
- // Validate OTLP headers for injection attacks:
465
- // - Check top-level keys for dangerous prototype pollution patterns
466
- // - Block ALL control characters except tab (0x09) to prevent header
467
- // injection via CR/LF/zero-byte/etc.
468
- // BUG (Round 28, CRLF injection): the previous range
469
- // /[\x00-\x08\x0b\x0c\x0e-\x1f]/ left THREE chars unblocked: tab (0x09,
470
- // intentionally allowed), LF (0x0A) AND CR (0x0D). The comment claimed to
471
- // "prevent header injection via CR/LF" but CR was never matched, and LF
472
- // was explicitly allowed — both are CRLF injection vectors that can split
473
- // HTTP headers. Fix: block 0x00-0x08 and 0x0A-0x1F, allowing only tab.
474
- const invalidHeaders: string[] = [];
475
- for (const [k, v] of Object.entries(merged.otlp.headers ?? {})) {
476
- // Check top-level key for dangerous names (only top-level keys are checked)
477
- const checkKey = (key: string): boolean => {
478
- const lowerKey = key.toLowerCase();
479
- if (DANGEROUS_OBJECT_KEYS.has(lowerKey)) return true;
480
- return false;
481
- };
482
- if (checkKey(k)) {
483
- invalidHeaders.push(k);
484
- continue;
485
- }
486
- // Block any control characters except tab (0x09) in values.
487
- // Round 28 fix: /[\x00-\x08\x0a-\x1f]/ blocks LF (0x0A) and CR (0x0D) too.
488
- const valStr = String(v);
489
- if (/[\x00-\x08\x0a-\x1f]/.test(valStr)) {
490
- invalidHeaders.push(k);
491
- }
492
- }
493
- if (invalidHeaders.length > 0) {
494
- delete merged.otlp.headers;
495
- warnings.push(`OTLP headers blocked due to invalid characters: ${invalidHeaders.join(", ")}`);
496
- }
497
- }
498
- if (merged.agents?.overrides && Object.keys(merged.agents.overrides).length === 0) delete merged.agents.overrides;
499
- return merged;
500
- }
501
-
502
- const LIMIT_CEILINGS = {
503
- maxConcurrentWorkers: 1024,
504
- maxTaskDepth: 100,
505
- maxChildrenPerTask: 1000,
506
- maxRunMinutes: 1440,
507
- maxRetriesPerTask: 100,
508
- maxTasksPerRun: 10_000,
509
- heartbeatStaleMs: 24 * 60 * 60 * 1000,
510
- runtimeMaxTurns: 10_000,
511
- runtimeGraceTurns: 1_000,
512
- // RT-NEW-1: taskTimeoutMs is in MILLISECONDS — it must NOT reuse runtimeMaxTurns
513
- // (10_000 turns), which capped the effective timeout at 10s and silently disabled
514
- // any larger value (e.g. 300_000 = 5min) via parsePositiveInteger returning undefined.
515
- runtimeTaskTimeoutMs: 24 * 60 * 60 * 1000,
516
- } as const;
517
-
518
- /**
519
- * Keys that could allow prototype pollution if merged into plain objects.
520
- * NOTE: This set is comprehensive for ES2023 and earlier. When upgrading JavaScript
521
- * versions, verify whether new dangerous Object.prototype properties have been added
522
- * that could enable prototype pollution attacks.
523
- */
524
- const DANGEROUS_OBJECT_KEYS = new Set([
525
- "__proto__",
526
- "constructor",
527
- "prototype",
528
- "hasOwnProperty",
529
- "toString",
530
- "valueOf",
531
- "isPrototypeOf",
532
- "propertyIsEnumerable",
533
- "toLocaleString",
534
- "__defineGetter__",
535
- "__defineSetter__",
536
- "__lookupGetter__",
537
- "__lookupSetter__",
538
- ]);
539
-
540
- /**
541
- * Strips dangerous Object.prototype keys from an object.
542
- * Returns a new object built with Object.create(null) to prevent
543
- * prototype pollution attacks.
544
- */
545
- function sanitizeObject(obj: Record<string, unknown>): Record<string, unknown> {
546
- const sanitized: Record<string, unknown> = Object.create(null);
547
- for (const [key, value] of Object.entries(obj)) {
548
- // Case-insensitive check to catch __Proto__, CONSTRUCTOR, etc.
549
- const lowerKey = key.toLowerCase();
550
- if (DANGEROUS_OBJECT_KEYS.has(lowerKey)) continue;
551
- if (value && typeof value === "object" && !Array.isArray(value)) {
552
- sanitized[key] = sanitizeObject(value as Record<string, unknown>);
553
- } else {
554
- sanitized[key] = value;
555
- }
556
- }
557
- return sanitized;
558
- }
559
-
560
- export function asRecord(value: unknown): Record<string, unknown> | undefined {
561
- if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
562
- // Defensive: create a sanitized copy to prevent prototype pollution.
563
- // Uses Object.create(null) so the result has no prototype chain.
564
- // WARNING: The returned object has no prototype methods (no hasOwnProperty,
565
- // toString, etc.). Use Object.hasOwn(obj, key) or
566
- // Object.prototype.hasOwnProperty.call(obj, key) for property checks.
567
- return sanitizeObject(value as Record<string, unknown>);
568
- }
569
-
570
- function parseWithSchema<T extends TSchema>(schema: T, value: unknown, context?: string): Static<T> | undefined {
571
- if (!Value.Check(schema, value)) {
572
- if (context) {
573
- logInternalError("config.parseWithSchema", undefined, `${context}: schema validation failed`);
574
- }
575
- return undefined;
576
- }
577
- return Value.Decode(schema, value);
578
- }
579
-
580
- function parseIntegerInRange(value: unknown, minimum = 1, maximum = Number.MAX_SAFE_INTEGER): number | undefined {
581
- return parseWithSchema(Type.Integer({ minimum, maximum }), value);
582
- }
583
-
584
- function parsePositiveInteger(value: unknown, max = Number.MAX_SAFE_INTEGER): number | undefined {
585
- return parseIntegerInRange(value, 1, max);
586
- }
587
-
588
- function parseProfile(value: unknown): PiTeamsAutonomyProfile | undefined {
589
- return parseWithSchema(PiTeamsAutonomyProfileSchema, value);
590
- }
591
-
592
- function parseStringList(value: unknown): string[] | undefined {
593
- const items = parseWithSchema(Type.Array(Type.String()), value);
594
- if (!items || items.length === 0) return undefined;
595
- const normalized = items.map((entry) => entry.trim()).filter((entry) => entry.length > 0);
596
- return normalized.length > 0 ? normalized : undefined;
597
- }
598
-
599
- function parseStringArrayOrFalse(value: unknown): string[] | false | undefined {
600
- if (value === false) return false;
601
- if (typeof value === "string") return value.trim() === "" ? [] : parseStringList(value.split(","));
602
- return parseStringList(value);
603
- }
604
-
605
- export function effectiveAutonomousConfig(
606
- config: PiTeamsAutonomousConfig | undefined,
607
- ): Required<Pick<PiTeamsAutonomousConfig, "profile" | "enabled" | "injectPolicy" | "preferAsyncForLongTasks" | "allowWorktreeSuggestion">> &
608
- Pick<PiTeamsAutonomousConfig, "magicKeywords"> {
609
- const profile = config?.enabled === false ? "manual" : (config?.profile ?? "suggested");
610
- const profileDefaults: Record<
611
- PiTeamsAutonomyProfile,
612
- {
613
- enabled: boolean;
614
- injectPolicy: boolean;
615
- preferAsyncForLongTasks: boolean;
616
- allowWorktreeSuggestion: boolean;
617
- }
618
- > = {
619
- manual: {
620
- enabled: false,
621
- injectPolicy: false,
622
- preferAsyncForLongTasks: false,
623
- allowWorktreeSuggestion: false,
624
- },
625
- suggested: {
626
- enabled: true,
627
- injectPolicy: true,
628
- preferAsyncForLongTasks: false,
629
- allowWorktreeSuggestion: true,
630
- },
631
- assisted: {
632
- enabled: true,
633
- injectPolicy: true,
634
- preferAsyncForLongTasks: true,
635
- allowWorktreeSuggestion: true,
636
- },
637
- aggressive: {
638
- enabled: true,
639
- injectPolicy: true,
640
- preferAsyncForLongTasks: true,
641
- allowWorktreeSuggestion: true,
642
- },
643
- };
644
- const defaults = profileDefaults[profile];
645
- return {
646
- profile,
647
- enabled: config?.enabled ?? defaults.enabled,
648
- injectPolicy: config?.injectPolicy ?? defaults.injectPolicy,
649
- preferAsyncForLongTasks: config?.preferAsyncForLongTasks ?? defaults.preferAsyncForLongTasks,
650
- allowWorktreeSuggestion: config?.allowWorktreeSuggestion ?? defaults.allowWorktreeSuggestion,
651
- magicKeywords: config?.magicKeywords,
652
- };
653
- }
654
-
655
- function parseStringArrayRecord(value: unknown): Record<string, string[]> | undefined {
656
- const record = parseWithSchema(Type.Record(Type.String({ minLength: 1 }), Type.Array(Type.String())), value);
657
- if (!record) return undefined;
658
- const result: Record<string, string[]> = {};
659
- for (const [key, rawValues] of Object.entries(record)) {
660
- const parsed = parseStringList(rawValues);
661
- if (parsed && parsed.length > 0) result[key] = parsed;
662
- }
663
- return Object.keys(result).length > 0 ? result : undefined;
664
- }
665
-
666
- function parseAutonomousConfig(value: unknown): PiTeamsAutonomousConfig | undefined {
667
- const obj = asRecord(value);
668
- if (!obj) return undefined;
669
- const config: PiTeamsAutonomousConfig = {
670
- profile: parseProfile(obj.profile),
671
- enabled: parseWithSchema(Type.Boolean(), obj.enabled),
672
- injectPolicy: parseWithSchema(Type.Boolean(), obj.injectPolicy),
673
- preferAsyncForLongTasks: parseWithSchema(Type.Boolean(), obj.preferAsyncForLongTasks),
674
- allowWorktreeSuggestion: parseWithSchema(Type.Boolean(), obj.allowWorktreeSuggestion),
675
- magicKeywords: parseStringArrayRecord(obj.magicKeywords),
676
- };
677
- return Object.values(config).some((entry) => entry !== undefined) ? config : undefined;
678
- }
679
-
680
- function parseLimitsConfig(value: unknown): CrewLimitsConfig | undefined {
681
- const obj = asRecord(value);
682
- if (!obj) return undefined;
683
- const limits: CrewLimitsConfig = {
684
- maxConcurrentWorkers: parsePositiveInteger(obj.maxConcurrentWorkers, LIMIT_CEILINGS.maxConcurrentWorkers),
685
- allowUnboundedConcurrency: parseWithSchema(Type.Boolean(), obj.allowUnboundedConcurrency),
686
- maxTaskDepth: parsePositiveInteger(obj.maxTaskDepth, LIMIT_CEILINGS.maxTaskDepth),
687
- maxChildrenPerTask: parsePositiveInteger(obj.maxChildrenPerTask, LIMIT_CEILINGS.maxChildrenPerTask),
688
- maxRunMinutes: parsePositiveInteger(obj.maxRunMinutes, LIMIT_CEILINGS.maxRunMinutes),
689
- maxRetriesPerTask: parsePositiveInteger(obj.maxRetriesPerTask, LIMIT_CEILINGS.maxRetriesPerTask),
690
- maxTasksPerRun: parsePositiveInteger(obj.maxTasksPerRun, LIMIT_CEILINGS.maxTasksPerRun),
691
- heartbeatStaleMs: parsePositiveInteger(obj.heartbeatStaleMs, LIMIT_CEILINGS.heartbeatStaleMs),
692
- serializeOnPathOverlap: parseWithSchema(Type.Boolean(), obj.serializeOnPathOverlap),
693
- };
694
- return Object.values(limits).some((entry) => entry !== undefined) ? limits : undefined;
695
- }
696
-
697
- function parseIsolationPolicy(value: unknown): CrewRuntimeConfig["isolationPolicy"] | undefined {
698
- const obj = asRecord(value);
699
- if (!obj) return undefined;
700
- const isolatedRoles = parseStringList(obj.isolatedRoles);
701
- const defaultRuntime = parseWithSchema(Type.Union([Type.Literal("live-session"), Type.Literal("child-process")]), obj.defaultRuntime);
702
- if (isolatedRoles === undefined && defaultRuntime === undefined) return undefined;
703
- return {
704
- ...(isolatedRoles !== undefined ? { isolatedRoles } : {}),
705
- ...(defaultRuntime !== undefined ? { defaultRuntime } : {}),
706
- };
707
- }
708
-
709
- function parseRuntimeConfig(value: unknown): CrewRuntimeConfig | undefined {
710
- const obj = asRecord(value);
711
- if (!obj) return { inheritContext: true } as CrewRuntimeConfig;
712
- const runtime: CrewRuntimeConfig = {
713
- mode: parseWithSchema(
714
- Type.Union([Type.Literal("auto"), Type.Literal("scaffold"), Type.Literal("child-process"), Type.Literal("live-session")]),
715
- obj.mode,
716
- ),
717
- preferLiveSession: parseWithSchema(Type.Boolean(), obj.preferLiveSession),
718
- allowChildProcessFallback: parseWithSchema(Type.Boolean(), obj.allowChildProcessFallback),
719
- maxTurns: parsePositiveInteger(obj.maxTurns, LIMIT_CEILINGS.runtimeMaxTurns),
720
- graceTurns: parsePositiveInteger(obj.graceTurns, LIMIT_CEILINGS.runtimeGraceTurns),
721
- taskTimeoutMs: parsePositiveInteger(obj.taskTimeoutMs, LIMIT_CEILINGS.runtimeTaskTimeoutMs),
722
- inheritContext: parseWithSchema(Type.Boolean(), obj.inheritContext) ?? true,
723
- promptMode: parseWithSchema(Type.Union([Type.Literal("replace"), Type.Literal("append")]), obj.promptMode),
724
- groupJoin: parseWithSchema(Type.Union([Type.Literal("off"), Type.Literal("group"), Type.Literal("smart")]), obj.groupJoin),
725
- groupJoinAckTimeoutMs: parsePositiveInteger(obj.groupJoinAckTimeoutMs, 86_400_000),
726
- requirePlanApproval: parseWithSchema(Type.Boolean(), obj.requirePlanApproval),
727
- completionMutationGuard: parseWithSchema(
728
- Type.Union([Type.Literal("off"), Type.Literal("warn"), Type.Literal("fail")]),
729
- obj.completionMutationGuard,
730
- ),
731
- effectivenessGuard: parseWithSchema(
732
- Type.Union([Type.Literal("off"), Type.Literal("warn"), Type.Literal("block"), Type.Literal("fail")]),
733
- obj.effectivenessGuard,
734
- ),
735
- yield: (() => {
736
- const y = asRecord(obj.yield);
737
- if (!y) return undefined;
738
- const parsed: NonNullable<CrewRuntimeConfig["yield"]> = {
739
- enabled: parseWithSchema(Type.Boolean(), y.enabled),
740
- maxReminders: parseWithSchema(Type.Integer({ minimum: 0 }), y.maxReminders),
741
- reminderPrompt: parseWithSchema(Type.String({ maxLength: 1000 }), y.reminderPrompt),
742
- };
743
- return Object.values(parsed).some((v) => v !== undefined) ? parsed : undefined;
744
- })(),
745
- excludeContextBash: parseWithSchema(Type.Boolean(), obj.excludeContextBash),
746
- agentExtensions: parseStringList(obj.agentExtensions),
747
- isolationPolicy: parseIsolationPolicy(obj.isolationPolicy),
748
- };
749
- return Object.values(runtime).some((entry) => entry !== undefined) ? runtime : undefined;
750
- }
751
-
752
- function parseControlConfig(value: unknown): CrewControlConfig | undefined {
753
- const obj = asRecord(value);
754
- if (!obj) return undefined;
755
- const control: CrewControlConfig = {
756
- enabled: parseWithSchema(Type.Boolean(), obj.enabled),
757
- needsAttentionAfterMs: parsePositiveInteger(obj.needsAttentionAfterMs),
758
- };
759
- return Object.values(control).some((entry) => entry !== undefined) ? control : undefined;
760
- }
761
-
762
- /**
763
- * Phase 0 broker parser. Returns `undefined` only when input is not an object;
764
- * otherwise returns the broker config (with only defined fields populated)
765
- * so the caller can layer defaults on top.
766
- */
767
- function parseBrokerConfig(value: unknown): CrewBrokerConfig | undefined {
768
- const obj = asRecord(value);
769
- if (!obj) return undefined;
770
- // Use the exact schema bounds (4..32 / 1024..1048576 / 32..4096). The
771
- // previous version used parsePositiveInteger(value, default) which clamps
772
- // the UPPER bound to the default — effectively pathHashLen was capped
773
- // at 8, much narrower than the schema advertises.
774
- const broker: CrewBrokerConfig = {
775
- enabled: parseWithSchema(Type.Boolean(), obj.enabled),
776
- pathHashLen: parseIntegerInRange(obj.pathHashLen, 4, 32),
777
- maxFrameBytes: parseIntegerInRange(obj.maxFrameBytes, 1024, 1_048_576),
778
- outboundQueueCap: parseIntegerInRange(obj.outboundQueueCap, 32, 4096),
779
- };
780
- return Object.values(broker).some((entry) => entry !== undefined) ? broker : undefined;
781
- }
782
-
783
221
  /**
784
222
  * Apply PI_CREW_BROKER env override to the parsed broker config, then
785
223
  * layer in DEFAULT_BROKER for any field the user did not set. Keeps the
786
224
  * kill switch (enabled:false) reachable in three independent ways: env,
787
225
  * config block, or default.
788
226
  */
227
+
228
+ /** ADR-5 §10: layer DEFAULT_NESTING under any user-set keys — the
229
+ * fail-closed enabled=false default must hold when no nesting block exists. */
230
+ function applyNestingDefaults(parsed: CrewNestingConfig | undefined): CrewNestingConfig {
231
+ return { ...DEFAULT_NESTING, ...parsed };
232
+ }
789
233
  function applyBrokerEnvOverrideAndDefaults(parsed: CrewBrokerConfig | undefined): CrewBrokerConfig {
790
234
  const envOverridden = resolveBrokerEnvOverride(parsed);
791
235
  return { ...DEFAULT_BROKER, ...envOverridden };
792
236
  }
793
237
 
794
- function parseWorktreeConfig(value: unknown): CrewWorktreeConfig | undefined {
795
- const obj = asRecord(value);
796
- if (!obj) return undefined;
797
- const rawSetupHook = parseWithSchema(Type.String(), obj.setupHook);
798
- const setupHook = rawSetupHook?.trim();
799
- const worktree: CrewWorktreeConfig = {
800
- setupHook: setupHook ? setupHook : undefined,
801
- setupHookTimeoutMs: parsePositiveInteger(obj.setupHookTimeoutMs, 300_000),
802
- linkNodeModules: parseWithSchema(Type.Boolean(), obj.linkNodeModules),
803
- // C6: seedPaths was declared in the type + schema but never parsed here, so
804
- // loadedConfig.config.worktree?.seedPaths was always undefined -> the global
805
- // worktree seed overlay (worktree-manager.ts) silently never applied.
806
- seedPaths: parseStringList(obj.seedPaths),
807
- };
808
- return Object.values(worktree).some((entry) => entry !== undefined) ? worktree : undefined;
809
- }
810
-
811
- /** Parse goalWrap config (RFC v0.5 vision: apply goal completion-guarantee to builtins). */
812
- function parseGoalWrapConfig(value: unknown): Record<string, GoalWrapWorkflowConfig> | undefined {
813
- const obj = asRecord(value);
814
- if (!obj) return undefined;
815
- const result: Record<string, GoalWrapWorkflowConfig> = {};
816
- let hasAny = false;
817
- for (const [workflowName, entry] of Object.entries(obj)) {
818
- const entryObj = asRecord(entry);
819
- if (!entryObj) continue;
820
- const parsed: GoalWrapWorkflowConfig = {
821
- enabled: parseWithSchema(Type.Boolean(), entryObj.enabled),
822
- maxTurns: parseWithSchema(Type.Integer({ minimum: 1, maximum: 50 }), entryObj.maxTurns),
823
- evaluatorModel: parseWithSchema(Type.String({ minLength: 1 }), entryObj.evaluatorModel),
824
- budgetTotal: parseWithSchema(Type.Integer({ minimum: 1000 }), entryObj.budgetTotal),
825
- budgetUnlimited: parseWithSchema(Type.Boolean(), entryObj.budgetUnlimited),
826
- };
827
- // Parse verification sub-object.
828
- const verObj = asRecord(entryObj.verification);
829
- if (verObj) {
830
- const commands = Array.isArray(verObj.commands)
831
- ? verObj.commands.filter((c): c is string => typeof c === "string" && c.length > 0)
832
- : undefined;
833
- const mode = verObj.mode === "text-only" ? ("text-only" as const) : undefined;
834
- if (commands || mode) {
835
- parsed.verification = {
836
- ...(commands ? { commands } : { commands: [] }),
837
- ...(mode ? { mode } : {}),
838
- };
839
- }
840
- }
841
- if (Object.values(parsed).some((v) => v !== undefined)) {
842
- result[workflowName] = parsed;
843
- hasAny = true;
844
- }
845
- }
846
- return hasAny ? result : undefined;
847
- }
848
-
849
- function parseAgentOverride(value: unknown): AgentOverrideConfig | undefined {
850
- const obj = asRecord(value);
851
- if (!obj) return undefined;
852
- const override: AgentOverrideConfig = {
853
- disabled: parseWithSchema(Type.Boolean(), obj.disabled),
854
- model: parseWithSchema(Type.Union([Type.String(), Type.Literal(false)]), obj.model),
855
- fallbackModels: parseStringArrayOrFalse(obj.fallbackModels),
856
- thinking: parseWithSchema(Type.Union([Type.String(), Type.Literal(false)]), obj.thinking),
857
- tools: parseStringArrayOrFalse(obj.tools),
858
- skills: parseStringArrayOrFalse(obj.skills),
859
- };
860
- return Object.values(override).some((entry) => entry !== undefined) ? override : undefined;
861
- }
862
-
863
- function parseUiConfig(value: unknown): CrewUiConfig | undefined {
864
- const obj = asRecord(value);
865
- if (!obj) return undefined;
866
- const rawWidgetPlacement = parseWithSchema(Type.Union([Type.Literal("aboveEditor"), Type.Literal("belowEditor")]), obj.widgetPlacement);
867
- const rawDashboardPlacement = parseWithSchema(Type.Union([Type.Literal("center"), Type.Literal("right")]), obj.dashboardPlacement);
868
- const ui: CrewUiConfig = {
869
- widgetPlacement: rawWidgetPlacement,
870
- widgetMaxLines: parsePositiveInteger(obj.widgetMaxLines, 50),
871
- powerbar: parseWithSchema(Type.Boolean(), obj.powerbar),
872
- dashboardPlacement: rawDashboardPlacement,
873
- dashboardWidth: parseIntegerInRange(obj.dashboardWidth, 32, 120),
874
- dashboardLiveRefreshMs: parseIntegerInRange(obj.dashboardLiveRefreshMs, 250, 60_000),
875
- autoOpenDashboard: parseWithSchema(Type.Boolean(), obj.autoOpenDashboard),
876
- autoOpenDashboardForForegroundRuns: parseWithSchema(Type.Boolean(), obj.autoOpenDashboardForForegroundRuns),
877
- autoCloseDashboardMs: parseWithSchema(Type.Integer({ minimum: 0 }), obj.autoCloseDashboardMs),
878
- showModel: parseWithSchema(Type.Boolean(), obj.showModel),
879
- showTokens: parseWithSchema(Type.Boolean(), obj.showTokens),
880
- showTools: parseWithSchema(Type.Boolean(), obj.showTools),
881
- transcriptTailBytes: parseIntegerInRange(obj.transcriptTailBytes, 1024, 50 * 1024 * 1024),
882
- mascotStyle: parseWithSchema(Type.Union([Type.Literal("cat"), Type.Literal("armin")]), obj.mascotStyle),
883
- mascotEffect: parseWithSchema(
884
- Type.Union([
885
- Type.Literal("random"),
886
- Type.Literal("none"),
887
- Type.Literal("typewriter"),
888
- Type.Literal("scanline"),
889
- Type.Literal("rain"),
890
- Type.Literal("fade"),
891
- Type.Literal("crt"),
892
- Type.Literal("glitch"),
893
- Type.Literal("dissolve"),
894
- ]),
895
- obj.mascotEffect,
896
- ),
897
- };
898
- return Object.values(ui).some((entry) => entry !== undefined) ? ui : undefined;
899
- }
900
-
901
- function parseAgentsConfig(value: unknown): CrewAgentsConfig | undefined {
902
- const obj = asRecord(value);
903
- if (!obj) return undefined;
904
- const overrides: Record<string, AgentOverrideConfig> = {};
905
- if (obj.overrides && typeof obj.overrides === "object" && !Array.isArray(obj.overrides)) {
906
- for (const [name, rawOverride] of Object.entries(obj.overrides as Record<string, unknown>)) {
907
- const parsed = parseAgentOverride(rawOverride);
908
- if (parsed && name.trim()) overrides[name.trim()] = parsed;
909
- }
910
- }
911
- const agents: CrewAgentsConfig = {
912
- disableBuiltins: parseWithSchema(Type.Boolean(), obj.disableBuiltins),
913
- overrides: Object.keys(overrides).length > 0 ? overrides : undefined,
914
- };
915
- return Object.values(agents).some((entry) => entry !== undefined) ? agents : undefined;
916
- }
917
-
918
- function parseToolsConfig(value: unknown): CrewToolsConfig | undefined {
919
- const obj = asRecord(value);
920
- if (!obj) return undefined;
921
- const tools: CrewToolsConfig = {
922
- enableClaudeStyleAliases: parseWithSchema(Type.Boolean(), obj.enableClaudeStyleAliases),
923
- enableSteer: parseWithSchema(Type.Boolean(), obj.enableSteer),
924
- terminateOnForeground: parseWithSchema(Type.Boolean(), obj.terminateOnForeground),
925
- };
926
- return Object.values(tools).some((entry) => entry !== undefined) ? tools : undefined;
927
- }
928
-
929
- function parseTelemetryConfig(value: unknown): CrewTelemetryConfig | undefined {
930
- const obj = asRecord(value);
931
- if (!obj) return undefined;
932
- const telemetry: CrewTelemetryConfig = {
933
- enabled: parseWithSchema(Type.Boolean(), obj.enabled),
934
- };
935
- return Object.values(telemetry).some((entry) => entry !== undefined) ? telemetry : undefined;
936
- }
937
-
938
- function parsePolicyConfig(value: unknown): CrewPolicyConfig | undefined {
939
- const obj = asRecord(value);
940
- if (!obj) return undefined;
941
- const policy: CrewPolicyConfig = {
942
- requireIntentForDestructiveActions: parseWithSchema(Type.Boolean(), obj.requireIntentForDestructiveActions),
943
- disabledCapabilities: parseWithSchema(Type.Array(Type.String()), obj.disabledCapabilities),
944
- };
945
- return Object.values(policy).some((entry) => entry !== undefined) ? policy : undefined;
946
- }
947
-
948
- function parseNotificationsConfig(value: unknown): CrewNotificationsConfig | undefined {
949
- const obj = asRecord(value);
950
- if (!obj) return undefined;
951
- const notifications: CrewNotificationsConfig = {
952
- enabled: parseWithSchema(Type.Boolean(), obj.enabled),
953
- severityFilter: parseWithSchema(
954
- Type.Array(Type.Union([Type.Literal("info"), Type.Literal("warning"), Type.Literal("error"), Type.Literal("critical")])),
955
- obj.severityFilter,
956
- ),
957
- dedupWindowMs: parsePositiveInteger(obj.dedupWindowMs, 24 * 60 * 60 * 1000),
958
- batchWindowMs: parseWithSchema(Type.Integer({ minimum: 0, maximum: 60_000 }), obj.batchWindowMs),
959
- quietHours: parseWithSchema(Type.String({ pattern: "^\\d{2}:\\d{2}-\\d{2}:\\d{2}$" }), obj.quietHours),
960
- sinkRetentionDays: parsePositiveInteger(obj.sinkRetentionDays, 90),
961
- };
962
- return Object.values(notifications).some((entry) => entry !== undefined) ? notifications : undefined;
963
- }
964
-
965
- function parseObservabilityConfig(value: unknown): CrewObservabilityConfig | undefined {
966
- const obj = asRecord(value);
967
- if (!obj) return undefined;
968
- const observability: CrewObservabilityConfig = {
969
- enabled: parseWithSchema(Type.Boolean(), obj.enabled),
970
- pollIntervalMs: parseWithSchema(Type.Integer({ minimum: 1000, maximum: 60_000 }), obj.pollIntervalMs),
971
- metricRetentionDays: parsePositiveInteger(obj.metricRetentionDays, 365),
972
- };
973
- return Object.values(observability).some((entry) => entry !== undefined) ? observability : undefined;
974
- }
975
-
976
- function parseReliabilityConfig(value: unknown): CrewReliabilityConfig | undefined {
977
- const obj = asRecord(value);
978
- if (!obj) return undefined;
979
- const retryObj = asRecord(obj.retryPolicy);
980
- const retryPolicy: CrewRetryPolicyConfig | undefined = retryObj
981
- ? {
982
- maxAttempts: parsePositiveInteger(retryObj.maxAttempts, 10),
983
- backoffMs: parseWithSchema(Type.Integer({ minimum: 100, maximum: 60_000 }), retryObj.backoffMs),
984
- jitterRatio: parseWithSchema(Type.Number({ minimum: 0, maximum: 1 }), retryObj.jitterRatio),
985
- exponentialFactor: parseWithSchema(Type.Number({ minimum: 1, maximum: 5 }), retryObj.exponentialFactor),
986
- retryableErrors: parseStringList(retryObj.retryableErrors),
987
- maxTotalSpawns: parsePositiveInteger(retryObj.maxTotalSpawns),
988
- }
989
- : undefined;
990
- const reliability: CrewReliabilityConfig = {
991
- autoRetry: parseWithSchema(Type.Boolean(), obj.autoRetry),
992
- retryPolicy: retryPolicy && Object.values(retryPolicy).some((entry) => entry !== undefined) ? retryPolicy : undefined,
993
- autoRecover: parseWithSchema(Type.Boolean(), obj.autoRecover),
994
- deadletterThreshold: parsePositiveInteger(obj.deadletterThreshold),
995
- cleanupOrphanedTempDirs: parseWithSchema(Type.Boolean(), obj.cleanupOrphanedTempDirs),
996
- autoRepairIntervalMs: parseWithSchema(Type.Integer({ minimum: 0 }), obj.autoRepairIntervalMs),
997
- forcePreflight: parseWithSchema(Type.Boolean(), obj.forcePreflight),
998
- ambientStatusInjection: parseWithSchema(Type.Boolean(), obj.ambientStatusInjection),
999
- perWriteValidation: parseWithSchema(Type.Boolean(), obj.perWriteValidation),
1000
- scopeModels: parseWithSchema(Type.Boolean(), obj.scopeModels),
1001
- };
1002
- return Object.values(reliability).some((entry) => entry !== undefined) ? reliability : undefined;
1003
- }
1004
-
1005
- function parseOtlpConfig(value: unknown): CrewOtlpConfig | undefined {
1006
- const obj = asRecord(value);
1007
- if (!obj) return undefined;
1008
- const headers: Record<string, string> = Object.create(null);
1009
- const rawHeaders = asRecord(obj.headers);
1010
- if (rawHeaders)
1011
- for (const [key, entry] of Object.entries(rawHeaders)) {
1012
- if (typeof entry !== "string") continue;
1013
- // Prevent prototype pollution via dangerous Object.prototype keys.
1014
- // Case-insensitive check to catch __Proto__, CONSTRUCTOR, etc.
1015
- const lowerKey = key.toLowerCase();
1016
- if (
1017
- lowerKey === "__proto__" ||
1018
- lowerKey === "constructor" ||
1019
- lowerKey === "prototype" ||
1020
- lowerKey === "hasownproperty" ||
1021
- lowerKey === "tostring" ||
1022
- lowerKey === "valueof" ||
1023
- lowerKey === "isprototypeof" ||
1024
- lowerKey === "propertyisenumerable" ||
1025
- lowerKey === "tolocalestring" ||
1026
- lowerKey === "__definegetter__" ||
1027
- lowerKey === "__definesetter__" ||
1028
- lowerKey === "__lookupgetter__" ||
1029
- lowerKey === "__lookupsetter__"
1030
- )
1031
- continue;
1032
- // Validate key format: must start with letter, then alphanumeric/hyphen/underscore.
1033
- // Blocks CRLF, NUL, spaces, shell metacharacters in header keys.
1034
- if (!/^[a-zA-Z][a-zA-Z0-9_-]{0,127}$/.test(key)) continue;
1035
- headers[key] = entry;
1036
- }
1037
- const otlp: CrewOtlpConfig = {
1038
- enabled: parseWithSchema(Type.Boolean(), obj.enabled),
1039
- endpoint: parseWithSchema(Type.String({ minLength: 1 }), obj.endpoint),
1040
- headers: Object.keys(headers).length > 0 ? headers : undefined,
1041
- intervalMs: parseWithSchema(Type.Integer({ minimum: 5000 }), obj.intervalMs),
1042
- };
1043
- return Object.values(otlp).some((entry) => entry !== undefined) ? otlp : undefined;
1044
- }
1045
-
1046
- export function parseConfig(raw: unknown): PiTeamsConfig {
1047
- const obj = asRecord(raw);
1048
- if (!obj) return {};
1049
- return {
1050
- asyncByDefault: parseWithSchema(Type.Boolean(), obj.asyncByDefault),
1051
- executeWorkers: parseWithSchema(Type.Boolean(), obj.executeWorkers),
1052
- notifierIntervalMs: parseWithSchema(Type.Number({ minimum: 1_000 }), obj.notifierIntervalMs),
1053
- requireCleanWorktreeLeader: parseWithSchema(Type.Boolean(), obj.requireCleanWorktreeLeader),
1054
- ignoreMethod: parseWithSchema(Type.Union([Type.Literal("gitignore"), Type.Literal("exclude")]), obj.ignoreMethod),
1055
- autonomous: parseAutonomousConfig(obj.autonomous),
1056
- limits: parseLimitsConfig(obj.limits),
1057
- runtime: parseRuntimeConfig(obj.runtime),
1058
- control: parseControlConfig(obj.control),
1059
- worktree: parseWorktreeConfig(obj.worktree),
1060
- goalWrap: parseGoalWrapConfig(obj.goalWrap),
1061
- agents: parseAgentsConfig(obj.agents),
1062
- tools: parseToolsConfig(obj.tools),
1063
- telemetry: parseTelemetryConfig(obj.telemetry),
1064
- policy: parsePolicyConfig(obj.policy),
1065
- notifications: parseNotificationsConfig(obj.notifications),
1066
- observability: parseObservabilityConfig(obj.observability),
1067
- reliability: parseReliabilityConfig(obj.reliability),
1068
- otlp: parseOtlpConfig(obj.otlp),
1069
- ui: parseUiConfig(obj.ui),
1070
- broker: parseBrokerConfig(obj.broker),
1071
- };
1072
- }
1073
-
1074
- export function parseConfigWithWarnings(raw: unknown): ConfigValidationResult {
1075
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { config: {}, warnings: [] };
1076
- const parsed = parseConfig(raw);
1077
- const warnings = validateConfigWithWarnings(raw as Record<string, unknown>);
1078
- return { config: parsed, warnings };
1079
- }
1080
-
1081
238
  function unsetPath(record: Record<string, unknown>, dottedPath: string): void {
1082
239
  const parts = dottedPath.split(".").filter(Boolean);
1083
240
  if (parts.length === 0) return;
@@ -1219,6 +376,7 @@ export function loadConfig(cwd?: string): LoadedPiTeamsConfig {
1219
376
  // config; defaults fill any missing field. Env `"1"`/`"0"` forces
1220
377
  // the enabled flag even when no broker block is configured.
1221
378
  broker: applyBrokerEnvOverrideAndDefaults(config.broker),
379
+ nesting: applyNestingDefaults(config.nesting),
1222
380
  },
1223
381
  warnings: warnings.length > 0 ? warnings : undefined,
1224
382
  };