@caupulican/pi-adaptative 0.81.29 → 0.81.30

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 (147) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/bundled-resources/skills/harness-self-adaptation/SKILL.md +327 -0
  3. package/dist/bundled-resources/skills/harness-self-adaptation/references/adaptation-layers.md +89 -0
  4. package/dist/core/agent-session.d.ts +11 -1
  5. package/dist/core/agent-session.d.ts.map +1 -1
  6. package/dist/core/agent-session.js +16 -14
  7. package/dist/core/agent-session.js.map +1 -1
  8. package/dist/core/autonomy/approval-gate.d.ts +1 -1
  9. package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
  10. package/dist/core/autonomy/approval-gate.js +5 -1
  11. package/dist/core/autonomy/approval-gate.js.map +1 -1
  12. package/dist/core/autonomy/lane-tool-surface.d.ts +4 -0
  13. package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
  14. package/dist/core/autonomy/lane-tool-surface.js +31 -4
  15. package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
  16. package/dist/core/autonomy/lane-tracker.d.ts +1 -0
  17. package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
  18. package/dist/core/autonomy/lane-tracker.js +11 -0
  19. package/dist/core/autonomy/lane-tracker.js.map +1 -1
  20. package/dist/core/autonomy/risk-assessment.d.ts.map +1 -1
  21. package/dist/core/autonomy/risk-assessment.js +1 -1
  22. package/dist/core/autonomy/risk-assessment.js.map +1 -1
  23. package/dist/core/background-lane-controller.d.ts +12 -0
  24. package/dist/core/background-lane-controller.d.ts.map +1 -1
  25. package/dist/core/background-lane-controller.js +114 -19
  26. package/dist/core/background-lane-controller.js.map +1 -1
  27. package/dist/core/context/context-artifacts.d.ts.map +1 -1
  28. package/dist/core/context/context-artifacts.js +7 -6
  29. package/dist/core/context/context-artifacts.js.map +1 -1
  30. package/dist/core/context/context-store-retention.d.ts +12 -0
  31. package/dist/core/context/context-store-retention.d.ts.map +1 -0
  32. package/dist/core/context/context-store-retention.js +161 -0
  33. package/dist/core/context/context-store-retention.js.map +1 -0
  34. package/dist/core/context-gc.d.ts.map +1 -1
  35. package/dist/core/context-gc.js +19 -4
  36. package/dist/core/context-gc.js.map +1 -1
  37. package/dist/core/context-pipeline.d.ts +13 -12
  38. package/dist/core/context-pipeline.d.ts.map +1 -1
  39. package/dist/core/context-pipeline.js +128 -33
  40. package/dist/core/context-pipeline.js.map +1 -1
  41. package/dist/core/cost/cost-summary.d.ts +7 -1
  42. package/dist/core/cost/cost-summary.d.ts.map +1 -1
  43. package/dist/core/cost/cost-summary.js +28 -17
  44. package/dist/core/cost/cost-summary.js.map +1 -1
  45. package/dist/core/cost/daily-usage.d.ts +7 -3
  46. package/dist/core/cost/daily-usage.d.ts.map +1 -1
  47. package/dist/core/cost/daily-usage.js +10 -5
  48. package/dist/core/cost/daily-usage.js.map +1 -1
  49. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  50. package/dist/core/delegation/worker-runner.js +25 -9
  51. package/dist/core/delegation/worker-runner.js.map +1 -1
  52. package/dist/core/export-html/template.js +2 -1
  53. package/dist/core/extensions/loader.d.ts.map +1 -1
  54. package/dist/core/extensions/loader.js +52 -2
  55. package/dist/core/extensions/loader.js.map +1 -1
  56. package/dist/core/extensions/runner.d.ts.map +1 -1
  57. package/dist/core/extensions/runner.js +21 -19
  58. package/dist/core/extensions/runner.js.map +1 -1
  59. package/dist/core/extensions/types.d.ts +5 -0
  60. package/dist/core/extensions/types.d.ts.map +1 -1
  61. package/dist/core/extensions/types.js.map +1 -1
  62. package/dist/core/failure-corpus.d.ts.map +1 -1
  63. package/dist/core/failure-corpus.js +36 -13
  64. package/dist/core/failure-corpus.js.map +1 -1
  65. package/dist/core/local-runtime-controller.d.ts.map +1 -1
  66. package/dist/core/local-runtime-controller.js +20 -2
  67. package/dist/core/local-runtime-controller.js.map +1 -1
  68. package/dist/core/memory-controller.d.ts +2 -0
  69. package/dist/core/memory-controller.d.ts.map +1 -1
  70. package/dist/core/memory-controller.js +18 -0
  71. package/dist/core/memory-controller.js.map +1 -1
  72. package/dist/core/models/local-runtime.d.ts.map +1 -1
  73. package/dist/core/models/local-runtime.js +15 -10
  74. package/dist/core/models/local-runtime.js.map +1 -1
  75. package/dist/core/reflection-controller.d.ts +3 -1
  76. package/dist/core/reflection-controller.d.ts.map +1 -1
  77. package/dist/core/reflection-controller.js +8 -5
  78. package/dist/core/reflection-controller.js.map +1 -1
  79. package/dist/core/runtime-builder.d.ts +2 -0
  80. package/dist/core/runtime-builder.d.ts.map +1 -1
  81. package/dist/core/runtime-builder.js.map +1 -1
  82. package/dist/core/sdk.d.ts.map +1 -1
  83. package/dist/core/sdk.js +1 -1
  84. package/dist/core/sdk.js.map +1 -1
  85. package/dist/core/session-analytics.d.ts +13 -7
  86. package/dist/core/session-analytics.d.ts.map +1 -1
  87. package/dist/core/session-analytics.js +155 -112
  88. package/dist/core/session-analytics.js.map +1 -1
  89. package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
  90. package/dist/core/tool-recovery-log-records.js +54 -9
  91. package/dist/core/tool-recovery-log-records.js.map +1 -1
  92. package/dist/core/tool-recovery-logger.d.ts +2 -0
  93. package/dist/core/tool-recovery-logger.d.ts.map +1 -1
  94. package/dist/core/tool-recovery-logger.js +32 -13
  95. package/dist/core/tool-recovery-logger.js.map +1 -1
  96. package/dist/core/tool-recovery-stats.d.ts +15 -0
  97. package/dist/core/tool-recovery-stats.d.ts.map +1 -0
  98. package/dist/core/tool-recovery-stats.js +206 -0
  99. package/dist/core/tool-recovery-stats.js.map +1 -0
  100. package/dist/core/tools/delegate-status.d.ts.map +1 -1
  101. package/dist/core/tools/delegate-status.js +15 -6
  102. package/dist/core/tools/delegate-status.js.map +1 -1
  103. package/dist/core/tools/delegate.d.ts +3 -0
  104. package/dist/core/tools/delegate.d.ts.map +1 -1
  105. package/dist/core/tools/delegate.js +7 -2
  106. package/dist/core/tools/delegate.js.map +1 -1
  107. package/dist/main.d.ts.map +1 -1
  108. package/dist/main.js +1 -1
  109. package/dist/main.js.map +1 -1
  110. package/dist/modes/interactive/components/bash-execution.d.ts +2 -1
  111. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  112. package/dist/modes/interactive/components/bash-execution.js +12 -1
  113. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  114. package/dist/modes/interactive/components/footer.d.ts +1 -0
  115. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  116. package/dist/modes/interactive/components/footer.js +19 -9
  117. package/dist/modes/interactive/components/footer.js.map +1 -1
  118. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  119. package/dist/modes/interactive/components/tool-execution.js +12 -2
  120. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  121. package/dist/modes/interactive/components/tool-panel-registry.d.ts +1 -0
  122. package/dist/modes/interactive/components/tool-panel-registry.d.ts.map +1 -1
  123. package/dist/modes/interactive/components/tool-panel-registry.js +18 -2
  124. package/dist/modes/interactive/components/tool-panel-registry.js.map +1 -1
  125. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  126. package/dist/modes/interactive/interactive-mode.js +9 -3
  127. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  128. package/dist/modes/rpc/jsonl.d.ts.map +1 -1
  129. package/dist/modes/rpc/jsonl.js +9 -28
  130. package/dist/modes/rpc/jsonl.js.map +1 -1
  131. package/dist/utils/streaming-lines.d.ts +20 -0
  132. package/dist/utils/streaming-lines.d.ts.map +1 -0
  133. package/dist/utils/streaming-lines.js +79 -0
  134. package/dist/utils/streaming-lines.js.map +1 -0
  135. package/docs/extensions.md +2 -0
  136. package/docs/index.md +1 -1
  137. package/docs/self-adaptation.md +7 -0
  138. package/docs/settings.md +5 -1
  139. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  140. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  141. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  142. package/examples/extensions/sandbox/package-lock.json +2 -2
  143. package/examples/extensions/sandbox/package.json +1 -1
  144. package/examples/extensions/with-deps/package-lock.json +2 -2
  145. package/examples/extensions/with-deps/package.json +1 -1
  146. package/npm-shrinkwrap.json +12 -12
  147. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"background-lane-controller.d.ts","sourceRoot":"","sources":["../../src/core/background-lane-controller.ts"],"names":[],"mappings":"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","sourcesContent":["/**\n * Background-lane controller: goal auto-continue, the research lane, scout-worker delegation, and\n * the model-fitness probe.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the lane timers, the\n * single-flight guards, the last research-lane skip reason, the live {@link LaneTracker}, and the\n * session-lifetime abort controllers for in-flight research/worker passes. Everything else it needs\n * — the session manager, settings, model registry, live model, capability envelope, the goal\n * continuation LOOP, the isolated-completion primitive, spawned-usage accounting, and the telemetry\n * sink — is reached through narrow deps accessors rather than the whole AgentSession.\n *\n * Drive-loop boundary (deliberate): the idle triggers ({@link scheduleGoalAutoContinueFromIdle},\n * {@link scheduleResearchLaneFromIdle}) are invoked from the session's prompt tail as one-line\n * delegations; goal auto-continue itself only ever asks the session to `continueGoalLoop`, so this\n * controller never touches `prompt()`, the last-assistant-message, retry, or streaming state.\n */\n\nimport path from \"node:path\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { Api, Model, Usage } from \"@caupulican/pi-ai\";\nimport type {\n\tAgentSessionEvent,\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tIsolatedCompletionOptions,\n\tIsolatedCompletionResult,\n\tPromptOptions,\n\tResearchLaneRunOutcome,\n\tWorkerDelegationRunOutcome,\n} from \"./agent-session.ts\";\nimport type { CapabilityEnvelope, EvidenceBundle, WorkerRequest, WorkerResult } from \"./autonomy/contracts.ts\";\nimport { createLaneToolSurface, type LaneToolSurface } from \"./autonomy/lane-tool-surface.ts\";\nimport { type LaneRecord, type LaneStatus, LaneTracker } from \"./autonomy/lane-tracker.ts\";\nimport { safeRealpathSync } from \"./autonomy/path-scope.ts\";\nimport { appendLaneRecordSnapshot, getLaneRecordSnapshots } from \"./autonomy/session-lane-record.ts\";\nimport { composeSubagentSystemPrompt } from \"./autonomy/subagent-prompt.ts\";\nimport { AUTONOMY_TELEMETRY_EVENT_TYPES, type AutonomyTelemetryEvent } from \"./autonomy/telemetry-events.ts\";\nimport { applyWorkerActions, type WorkerAction } from \"./delegation/worker-actions.ts\";\nimport { runWorker } from \"./delegation/worker-runner.ts\";\nimport type { GoalRuntimeSnapshot, GoalRuntimeSnapshotSettings } from \"./goals/goal-runtime-snapshot.ts\";\nimport type { GoalState } from \"./goals/goal-state.ts\";\nimport {\n\tderiveModelCapabilityProfile,\n\ttype ModelCapabilityProfile,\n\tscaleContinuationBudgetsForCapability,\n} from \"./model-capability.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { resolveCliModel } from \"./model-resolver.ts\";\nimport { FitnessStore, type StoredFitnessReport } from \"./models/fitness-store.ts\";\nimport type { NormalizedProfile } from \"./profile-registry.ts\";\nimport { type ModelFitnessReport, runModelFitnessProbe } from \"./research/model-fitness.ts\";\nimport { runResearch } from \"./research/research-runner.ts\";\nimport type { collectWorkspaceSources } from \"./research/workspace-collector.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\nexport function clampLaneMaxUsd(settingsMaxUsd: number, foregroundMaxEstimatedUsd?: number): number {\n\treturn Math.min(settingsMaxUsd, foregroundMaxEstimatedUsd ?? Number.POSITIVE_INFINITY);\n}\n\nexport interface BackgroundLaneControllerDeps {\n\t/** A disposed session must never schedule/persist a lane or continuation. */\n\tisDisposed(): boolean;\n\t/** Child sessions never run the idle research lane (only the top-level session drives autonomy). */\n\tisChildSession(): boolean;\n\t/** This session's id, for lane envelope ids and spawned-usage report ids. */\n\tgetSessionId(): string;\n\t/** The workspace root a lane runs relative to (worker path scope + research source collection). */\n\tgetCwd(): string;\n\t/** Root dir the host-keyed {@link FitnessStore} persists under. */\n\tgetAgentDir(): string;\n\t/** Session log: lane records read/append here and feed lane-history dedupe. */\n\tgetSessionManager(): SessionManager;\n\t/** Autonomy / research-lane / worker-delegation / model-capability settings + the profile registry. */\n\tgetSettingsManager(): SettingsManager;\n\t/** Resolves a configured lane model pattern against configured auth. */\n\tgetModelRegistry(): ModelRegistry;\n\t/** Session-scoped provider/model quota exhaustion guard. */\n\tisModelExhausted(model: Model<Api>): boolean;\n\t/** The session's current model — lanes inherit it unless a lane model is explicitly configured. */\n\tgetModel(): Model<Api> | undefined;\n\t/** Tool/profile gate: delegation is unavailable when the active surface removes `delegate`. */\n\tisDelegateToolActive(): boolean;\n\t/** Foreground cost ceiling — a lane budget is clamped to it, never exceeds it. */\n\tgetCapabilityEnvelope(): CapabilityEnvelope | undefined;\n\t/** Capability profile of the SESSION model (gates background lanes, scales continuation budgets). */\n\tgetModelCapabilityProfile(): ModelCapabilityProfile;\n\t/** Emits a session event (only `warning` from this controller). */\n\temit(event: AgentSessionEvent): void;\n\t/** G3/G8 telemetry sink (codes/ids only — never lane product text). */\n\temitAutonomyTelemetry(event: AutonomyTelemetryEvent): void;\n\t/** Durable goal state, if a goal is active (the research lane's demand source). */\n\tgetGoalStateSnapshot(): GoalState | undefined;\n\t/** Continuation gate + goal state for the idle autosteer scheduler. */\n\tgetGoalRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot;\n\t/** Latest persisted evidence bundle, for research-lane dedupe. */\n\tgetEvidenceBundleSnapshot(): EvidenceBundle | undefined;\n\t/** Persist a research lane's evidence bundle to the session log. */\n\tsaveEvidenceBundleSnapshot(bundle: EvidenceBundle): string;\n\t/** Persist a worker delegation's result snapshot to the session log. */\n\tsaveWorkerResultSnapshot(result: WorkerResult, request?: WorkerRequest): string;\n\t/** Roll a lane's spawned usage into session accounting (idempotent per reportId). */\n\taddSpawnedUsage(\n\t\tusage: Usage,\n\t\topts?: { label?: string; sourceSessionId?: string; reportId?: string },\n\t): string | undefined;\n\t/** Bounded LLM call fully isolated from the main session; lanes may supply a child tool loop. */\n\trunIsolatedCompletion(opts: IsolatedCompletionOptions): Promise<IsolatedCompletionResult>;\n\t/** Drive-loop boundary: the session's bounded goal-continuation loop (owns `prompt()`, not us). */\n\tcontinueGoalLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult>;\n\t/** Best-effort workspace evidence collection (silent-on-failure; [] preserves prior behavior). */\n\tcollectWorkspaceSources: typeof collectWorkspaceSources;\n}\n\nexport class BackgroundLaneController {\n\t/** Pending idle timer that starts bounded goal continuation after the session becomes idle. */\n\tprivate _goalAutoContinueTimer: ReturnType<typeof setTimeout> | undefined;\n\t/** Guards bounded idle autosteer so continuation prompts do not recursively trigger themselves. */\n\tprivate _isGoalAutoContinuing = false;\n\t/** Pending idle timer that starts an autonomous research pass after the session becomes idle. */\n\tprivate _researchLaneTimer: ReturnType<typeof setTimeout> | undefined;\n\t/** Single-flight guard: at most one research pass runs at a time per session. */\n\tprivate _isResearchLaneRunning = false;\n\t/** Why the last idle research-lane evaluation skipped, for /autonomy diagnostics. */\n\tprivate _lastResearchLaneSkipReason: string | undefined;\n\t/** Live lane registry — the real source for AutonomyStatusSnapshot.activeLaneCount. */\n\tprivate readonly _laneTracker = new LaneTracker();\n\t/** Session-lifetime abort for in-flight research passes (same pattern as _reflectionAbort). */\n\tprivate readonly _researchLaneAbort = new AbortController();\n\t/** Session-lifetime abort for in-flight delegated workers. */\n\tprivate readonly _workerDelegationAbort = new AbortController();\n\t/** Session-local de-duplication for fail-closed profile grants that cannot bind to lane tools. */\n\tprivate readonly _warnedUnboundLaneToolGrants = new Set<string>();\n\t/** Every background execution is retained until its terminal result is observed. */\n\tprivate readonly _workerPromises = new Map<string, Promise<WorkerDelegationRunOutcome>>();\n\tprivate readonly _queuedWorkers = new Map<string, { instructions: string; systemPrompt?: string }>();\n\tprivate _workerNotificationTimer: ReturnType<typeof setTimeout> | undefined;\n\tprivate _workersCompletedSinceFlush = 0;\n\tprivate _workersFailedSinceFlush = 0;\n\n\tprivate readonly deps: BackgroundLaneControllerDeps;\n\n\tprivate _scheduleWorkerNotification(): void {\n\t\tif (this._workerNotificationTimer !== undefined) return;\n\t\tthis._workerNotificationTimer = setTimeout(() => {\n\t\t\tthis._workerNotificationTimer = undefined;\n\t\t\tthis.deps.emit({\n\t\t\t\ttype: \"delegate_workers\",\n\t\t\t\tactive: this._laneTracker.getActiveCount(\"worker\"),\n\t\t\t\tcompletedSinceFlush: this._workersCompletedSinceFlush,\n\t\t\t\tfailedSinceFlush: this._workersFailedSinceFlush,\n\t\t\t});\n\t\t\tthis._workersCompletedSinceFlush = 0;\n\t\t\tthis._workersFailedSinceFlush = 0;\n\t\t}, 75);\n\t}\n\n\tprivate _recordWorkerTerminal(status: LaneStatus): void {\n\t\tif (status === \"succeeded\") this._workersCompletedSinceFlush++;\n\t\telse this._workersFailedSinceFlush++;\n\t\tthis._scheduleWorkerNotification();\n\t}\n\n\tconstructor(deps: BackgroundLaneControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/** Live lane records tracked by this process (running and terminal). */\n\tgetLaneRecords(): LaneRecord[] {\n\t\treturn this._laneTracker.getRecords();\n\t}\n\n\t/** Live count of active lanes — the real source for AutonomyStatusSnapshot.activeLaneCount. */\n\tgetActiveLaneCount(): number {\n\t\treturn this._laneTracker.getActiveCount();\n\t}\n\n\t/** Why the last idle research-lane evaluation skipped, for /autonomy diagnostics. */\n\tgetLastResearchLaneSkipReason(): string | undefined {\n\t\treturn this._lastResearchLaneSkipReason;\n\t}\n\n\t/** Abort any in-flight research pass or delegated worker (called on session dispose). */\n\tabortInFlightLanes(): void {\n\t\tthis._researchLaneAbort.abort();\n\t\tthis._workerDelegationAbort.abort();\n\t}\n\n\tclearGoalAutoContinueTimer(): void {\n\t\tif (this._goalAutoContinueTimer !== undefined) {\n\t\t\tclearTimeout(this._goalAutoContinueTimer);\n\t\t\tthis._goalAutoContinueTimer = undefined;\n\t\t}\n\t}\n\n\tscheduleGoalAutoContinueFromIdle(options?: PromptOptions): void {\n\t\tif (options?.autoContinueGoal === false || this._isGoalAutoContinuing || this.deps.isDisposed()) return;\n\n\t\t// Small-window models cannot afford multi-thousand-token continuation prompts per idle turn.\n\t\tif (!this.deps.getModelCapabilityProfile().backgroundLanesEnabled) return;\n\n\t\tconst { maxStallTurns, goalAutoContinue, goalAutoContinueDelayMs } = this.deps\n\t\t\t.getSettingsManager()\n\t\t\t.getAutonomySettings();\n\t\tif (!goalAutoContinue) return;\n\n\t\tconst snapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns });\n\t\tif (snapshot.continuation.action !== \"continue\") return;\n\n\t\tthis.clearGoalAutoContinueTimer();\n\t\tthis._goalAutoContinueTimer = setTimeout(() => {\n\t\t\tthis._goalAutoContinueTimer = undefined;\n\t\t\tvoid this._runScheduledGoalAutoContinue();\n\t\t}, goalAutoContinueDelayMs);\n\n\t\tconst timer = this._goalAutoContinueTimer;\n\t\tif (typeof timer === \"object\" && timer && \"unref\" in timer) {\n\t\t\tconst { unref } = timer as { unref?: () => void };\n\t\t\tunref?.call(timer);\n\t\t}\n\t}\n\n\tprivate async _runScheduledGoalAutoContinue(): Promise<void> {\n\t\tif (this._isGoalAutoContinuing || this.deps.isDisposed()) return;\n\n\t\tconst { maxStallTurns, goalContinueTurns, goalContinueMaxWallClockMinutes, goalAutoContinue } = this.deps\n\t\t\t.getSettingsManager()\n\t\t\t.getAutonomySettings();\n\t\tif (!goalAutoContinue) return;\n\n\t\tconst snapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns });\n\t\tif (snapshot.continuation.action !== \"continue\") return;\n\n\t\t// Lean-window models (16-32k) keep autosteer but at a reduced budget; full passes through.\n\t\tconst scaled = scaleContinuationBudgetsForCapability(this.deps.getModelCapabilityProfile(), {\n\t\t\tmaxTurns: goalContinueTurns,\n\t\t\tmaxWallClockMinutes: goalContinueMaxWallClockMinutes,\n\t\t});\n\n\t\tthis._isGoalAutoContinuing = true;\n\t\ttry {\n\t\t\tawait this.deps.continueGoalLoop({\n\t\t\t\tmaxTurns: scaled.maxTurns,\n\t\t\t\tmaxStallTurns,\n\t\t\t\tmaxWallClockMinutes: scaled.maxWallClockMinutes,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Goal auto-continuation failed: ${message}` });\n\t\t} finally {\n\t\t\tthis._isGoalAutoContinuing = false;\n\t\t}\n\t}\n\n\tclearResearchLaneTimer(): void {\n\t\tif (this._researchLaneTimer !== undefined) {\n\t\t\tclearTimeout(this._researchLaneTimer);\n\t\t\tthis._researchLaneTimer = undefined;\n\t\t}\n\t}\n\n\t/**\n\t * Derive the research demand from durable goal state: an active goal with open requirements,\n\t * deduplicated against the latest persisted bundle so the same requirement set is never\n\t * researched twice (the query is deterministic, so dedupe survives session reload).\n\t */\n\tprivate _buildResearchLaneDemand(): { query: string; context: string; goalId: string } | undefined {\n\t\tconst goal = this.deps.getGoalStateSnapshot();\n\t\tif (!goal || goal.status !== \"active\") {\n\t\t\tthis._lastResearchLaneSkipReason = \"no_active_goal\";\n\t\t\treturn undefined;\n\t\t}\n\t\tconst open = goal.requirements.filter((requirement) => requirement.status === \"open\");\n\t\tif (open.length === 0) {\n\t\t\tthis._lastResearchLaneSkipReason = \"no_open_requirements\";\n\t\t\treturn undefined;\n\t\t}\n\t\tconst query = `goal:${goal.goalId} requirements:${open\n\t\t\t.map((requirement) => requirement.id)\n\t\t\t.sort()\n\t\t\t.join(\",\")}`;\n\t\tif (this.deps.getEvidenceBundleSnapshot()?.query === query) {\n\t\t\tthis._lastResearchLaneSkipReason = \"recent_evidence_sufficient\";\n\t\t\treturn undefined;\n\t\t}\n\t\tconst context = [\n\t\t\t`Goal: ${goal.userGoal}`,\n\t\t\t\"Open requirements:\",\n\t\t\t...open.slice(0, 20).map((requirement) => `- ${requirement.text}`),\n\t\t].join(\"\\n\");\n\t\treturn { query, context, goalId: goal.goalId };\n\t}\n\n\t/**\n\t * Idle trigger for the autonomous research lane (mirrors {@link scheduleGoalAutoContinueFromIdle}).\n\t * All skips are recorded in `_lastResearchLaneSkipReason` and surfaced via diagnostics — the lane\n\t * informs, it never prompts or blocks the foreground.\n\t */\n\tscheduleResearchLaneFromIdle(): void {\n\t\tif (this._isResearchLaneRunning || this.deps.isDisposed() || this.deps.isChildSession()) return;\n\n\t\tconst research = this.deps.getSettingsManager().getResearchLaneSettings();\n\t\tif (!research.enabled) {\n\t\t\tthis._lastResearchLaneSkipReason = \"research_lane_disabled\";\n\t\t\treturn;\n\t\t}\n\t\tconst { mode } = this.deps.getSettingsManager().getAutonomySettings();\n\t\tif (mode === \"off\") {\n\t\t\tthis._lastResearchLaneSkipReason = \"autonomy_mode_off\";\n\t\t\treturn;\n\t\t}\n\t\tconst priorRuns = getLaneRecordSnapshots(this.deps.getSessionManager().getEntries()).filter(\n\t\t\t(record) => record.type === \"research\",\n\t\t).length;\n\t\tif (priorRuns >= research.maxRunsPerSession) {\n\t\t\tthis._lastResearchLaneSkipReason = \"max_runs_reached\";\n\t\t\treturn;\n\t\t}\n\t\tif (!this._buildResearchLaneDemand()) return;\n\t\tconst shipment = this._resolveLaneShipment(research, \"no_research_model\");\n\t\tif (!shipment.ok) {\n\t\t\tthis._lastResearchLaneSkipReason = shipment.skipReason;\n\t\t\treturn;\n\t\t}\n\t\tif (!this._laneCapabilityProfile(shipment.model).backgroundLanesEnabled) {\n\t\t\tthis._lastResearchLaneSkipReason = \"model_research_unsupported\";\n\t\t\treturn;\n\t\t}\n\n\t\tthis.clearResearchLaneTimer();\n\t\tthis._researchLaneTimer = setTimeout(() => {\n\t\t\tthis._researchLaneTimer = undefined;\n\t\t\tvoid this._runScheduledResearchLane();\n\t\t}, research.idleDelayMs);\n\n\t\tconst timer = this._researchLaneTimer;\n\t\tif (typeof timer === \"object\" && timer && \"unref\" in timer) {\n\t\t\tconst { unref } = timer as { unref?: () => void };\n\t\t\tunref?.call(timer);\n\t\t}\n\t}\n\n\tprivate async _runScheduledResearchLane(): Promise<void> {\n\t\tif (this._isResearchLaneRunning || this.deps.isDisposed()) return;\n\n\t\tconst research = this.deps.getSettingsManager().getResearchLaneSettings();\n\t\tconst { mode } = this.deps.getSettingsManager().getAutonomySettings();\n\t\tif (!research.enabled || mode === \"off\") return;\n\n\t\ttry {\n\t\t\tawait this.runResearchLaneOnce();\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Research lane failed: ${message}` });\n\t\t}\n\t}\n\n\t/** Capability profile for a specific lane model (lane budgets scale to the lane model's window). */\n\tprivate _laneCapabilityProfile(model: Model<Api>): ModelCapabilityProfile {\n\t\treturn deriveModelCapabilityProfile({\n\t\t\tcontextWindow: model.contextWindow,\n\t\t\tmode: this.deps.getSettingsManager().getModelCapabilitySettings().mode,\n\t\t});\n\t}\n\n\t/**\n\t * Resolve the model for a background lane. Lanes are shipped BY this session, so they inherit\n\t * the session's own model unless a lane-specific model is explicitly configured — a single-model\n\t * setup (e.g. one local open model) runs its lanes on that same model. An explicitly configured\n\t * pattern that cannot resolve/authenticate is a visible skip, not a silent fallback.\n\t */\n\tresolveLaneModel(configuredPattern: string | undefined): Model<Api> | undefined {\n\t\tif (configuredPattern) {\n\t\t\tconst resolved = resolveCliModel({ cliModel: configuredPattern, modelRegistry: this.deps.getModelRegistry() });\n\t\t\tif (resolved.model && this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) {\n\t\t\t\treturn resolved.model;\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t\treturn this.deps.getModel() ?? undefined;\n\t}\n\n\t/**\n\t * Resolve what a lane ships with. Precedence: explicit lane model setting, then the lane\n\t * profile's model (a shipped profile with a model MUST be obeyed — unresolvable is a visible\n\t * skip, never a fallback), then generic inheritance of the session model.\n\t */\n\tprivate _resolveLaneShipment(\n\t\tlaneSettings: { model?: string; profile?: string },\n\t\tmissingModelReason: string,\n\t): { ok: true; model: Model<Api>; laneProfile?: NormalizedProfile } | { ok: false; skipReason: string } {\n\t\tlet laneProfile: NormalizedProfile | undefined;\n\t\tif (laneSettings.profile) {\n\t\t\tconst profileRef = laneSettings.profile.trim();\n\t\t\tconst registry = this.deps.getSettingsManager().getProfileRegistry();\n\t\t\tlaneProfile =\n\t\t\t\tprofileRef.startsWith(\"./\") || profileRef.startsWith(\"../\")\n\t\t\t\t\t? registry.resolveProfileRef(profileRef, this.deps.getCwd())\n\t\t\t\t\t: registry.getProfile(profileRef);\n\t\t\tif (!laneProfile) {\n\t\t\t\treturn { ok: false, skipReason: \"lane_profile_not_found\" };\n\t\t\t}\n\t\t}\n\n\t\tlet model: Model<Api> | undefined;\n\t\tif (laneSettings.model) {\n\t\t\tmodel = this.resolveLaneModel(laneSettings.model);\n\t\t\tif (!model) return { ok: false, skipReason: missingModelReason };\n\t\t} else if (laneProfile?.model) {\n\t\t\tmodel = this.resolveLaneModel(laneProfile.model);\n\t\t\tif (!model) return { ok: false, skipReason: \"no_lane_profile_model\" };\n\t\t} else {\n\t\t\tmodel = this.deps.getModel() ?? undefined;\n\t\t\tif (!model) return { ok: false, skipReason: missingModelReason };\n\t\t}\n\t\tif (this.deps.isModelExhausted(model)) {\n\t\t\treturn { ok: false, skipReason: `${model.provider}/${model.id} model exhausted: quota` };\n\t\t}\n\t\treturn { ok: true, model, laneProfile };\n\t}\n\n\tprivate _warnUnboundLaneToolGrants(laneProfile: NormalizedProfile | undefined, surface: LaneToolSurface): void {\n\t\tif (!laneProfile || surface.unboundAllowPatterns.length === 0) return;\n\t\tconst warningKey = `${laneProfile.name}\\0${[...surface.unboundAllowPatterns].sort().join(\"\\0\")}`;\n\t\tif (this._warnedUnboundLaneToolGrants.has(warningKey)) return;\n\t\tthis._warnedUnboundLaneToolGrants.add(warningKey);\n\t\tthis.deps.emit({\n\t\t\ttype: \"warning\",\n\t\t\tmessage: `Lane profile '${laneProfile.name}' grants unavailable isolated-lane tools: ${surface.unboundAllowPatterns.join(\", \")}. Only classified lane tools can execute.`,\n\t\t});\n\t}\n\n\t/** Stripped research envelope — never the foreground/architect envelope. */\n\tprivate _buildResearchLaneEnvelope(\n\t\tmaxUsd: number,\n\t\tlaneProfile: NormalizedProfile | undefined,\n\t\tsurface: LaneToolSurface,\n\t): CapabilityEnvelope {\n\t\treturn {\n\t\t\tid: `research-${this.deps.getSessionId()}-${Date.now()}`,\n\t\t\tprofileId: laneProfile?.name,\n\t\t\tcapabilities: [\"research\", \"read_files\", \"memory_read\"],\n\t\t\tallowedTools: [...surface.allowedTools],\n\t\t\tdeniedTools: [...surface.deniedTools],\n\t\t\tallowedPaths: [this.deps.getCwd()],\n\t\t\tmaxEstimatedUsd: clampLaneMaxUsd(maxUsd, this.deps.getCapabilityEnvelope()?.maxEstimatedUsd),\n\t\t\tcreatedAt: new Date().toISOString(),\n\t\t};\n\t}\n\n\t/**\n\t * Run one bounded, read-only research pass and persist its results: evidence bundle snapshot,\n\t * terminal lane record, and spawned-usage cost report (single-hop invariant, idempotent on the\n\t * lane's reportId). Explicit calls (e.g. `/autonomy research`) express user intent and bypass the\n\t * enabled/mode/dedupe gates the idle scheduler enforces; budget and capability gates always apply.\n\t */\n\tasync runResearchLaneOnce(request?: {\n\t\tquery?: string;\n\t\tcontext?: string;\n\t\tgoalId?: string;\n\t}): Promise<ResearchLaneRunOutcome> {\n\t\tif (this._isResearchLaneRunning) {\n\t\t\treturn { started: false, skipReason: \"research_lane_already_running\" };\n\t\t}\n\t\tif (this.deps.isDisposed()) {\n\t\t\treturn { started: false, skipReason: \"session_disposed\" };\n\t\t}\n\n\t\tconst settings = this.deps.getSettingsManager().getResearchLaneSettings();\n\t\tconst demand = request?.query\n\t\t\t? { query: request.query, context: request.context ?? \"\", goalId: request.goalId }\n\t\t\t: this._buildResearchLaneDemand();\n\t\tif (!demand) {\n\t\t\treturn { started: false, skipReason: this._lastResearchLaneSkipReason ?? \"no_research_demand\" };\n\t\t}\n\n\t\tconst shipment = this._resolveLaneShipment(settings, \"no_research_model\");\n\t\tif (!shipment.ok) {\n\t\t\tthis._lastResearchLaneSkipReason = shipment.skipReason;\n\t\t\treturn { started: false, skipReason: shipment.skipReason };\n\t\t}\n\t\tconst { model, laneProfile } = shipment;\n\t\tconst laneCapability = this._laneCapabilityProfile(model);\n\t\tif (!laneCapability.backgroundLanesEnabled) {\n\t\t\tthis._lastResearchLaneSkipReason = \"model_research_unsupported\";\n\t\t\treturn { started: false, skipReason: \"model_research_unsupported\" };\n\t\t}\n\n\t\tthis._isResearchLaneRunning = true;\n\t\tthis._laneTracker.ensureCounterAtLeast(\n\t\t\tgetLaneRecordSnapshots(this.deps.getSessionManager().getEntries()).length + 1,\n\t\t);\n\t\tconst startedRecord = this._laneTracker.start({ type: \"research\", goalId: demand.goalId });\n\t\ttry {\n\t\t\tlet spentUsage: Usage | undefined;\n\t\t\t// Best-effort, pointer-first workspace evidence. Derives search terms from the goal/requirement\n\t\t\t// text (not the identity-key query) and is bounded + silent-on-failure: [] == today's behavior.\n\t\t\tconst workspaceSources = await this.deps.collectWorkspaceSources({\n\t\t\t\tquery: `${demand.context}\\n${demand.query}`,\n\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\tmaxSources: settings.maxSources,\n\t\t\t});\n\t\t\tconst maxUsd = clampLaneMaxUsd(settings.maxUsd, this.deps.getCapabilityEnvelope()?.maxEstimatedUsd);\n\t\t\tconst toolSurface = createLaneToolSurface({ cwd: this.deps.getCwd(), profile: laneProfile });\n\t\t\tthis._warnUnboundLaneToolGrants(laneProfile, toolSurface);\n\t\t\tconst result = await runResearch({\n\t\t\t\tquery: demand.query,\n\t\t\t\tcontext: demand.context,\n\t\t\t\tsources: workspaceSources,\n\t\t\t\tenvelope: this._buildResearchLaneEnvelope(maxUsd, laneProfile, toolSurface),\n\t\t\t\tmaxUsd,\n\t\t\t\tmaxSources: settings.maxSources,\n\t\t\t\tmaxFindings: settings.maxFindings,\n\t\t\t\tmaxWallClockMs: settings.maxWallClockMs,\n\t\t\t\tsignal: this._researchLaneAbort.signal,\n\t\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\t\t// Level-0 core always survives; profile soul and role prompt are the replaceable\n\t\t\t\t\t\t// layers; a settings-provided prompt replaces everything above the core.\n\t\t\t\t\t\tsystemPrompt: composeSubagentSystemPrompt({\n\t\t\t\t\t\t\tsoul: laneProfile?.soul,\n\t\t\t\t\t\t\trolePrompt: systemPrompt,\n\t\t\t\t\t\t\toverride: settings.systemPrompt,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tthinkingLevel: laneProfile?.thinking ?? \"off\",\n\t\t\t\t\t\tmaxTokens: laneCapability.laneMaxOutputTokens,\n\t\t\t\t\t\ttools: toolSurface.tools,\n\t\t\t\t\t\tmaxTurns: 6,\n\t\t\t\t\t\tbeforeToolCall: toolSurface.beforeToolCall,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t// Core/soul/role are all static per configuration — the provider can cache the prefix.\n\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t});\n\t\t\t\t\tspentUsage = completion.usage;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttext: completion.text,\n\t\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t});\n\n\t\t\t// Bug #21 pattern: if the session was disposed while the completion was in flight, do NOT\n\t\t\t// persist evidence/records/usage against the dead session.\n\t\t\tif (this.deps.isDisposed()) {\n\t\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\t\tstatus: \"canceled\",\n\t\t\t\t\treasonCode: \"session_disposed\",\n\t\t\t\t});\n\t\t\t\treturn { started: true, record, result };\n\t\t\t}\n\n\t\t\tlet evidenceEntryId: string | undefined;\n\t\t\tif (result.bundle) {\n\t\t\t\tevidenceEntryId = this.deps.saveEvidenceBundleSnapshot(result.bundle);\n\t\t\t}\n\t\t\tif (spentUsage && (spentUsage.cost.total > 0 || spentUsage.totalTokens > 0)) {\n\t\t\t\tthis.deps.addSpawnedUsage(spentUsage, {\n\t\t\t\t\tlabel: \"research-lane\",\n\t\t\t\t\treportId: `research:${this.deps.getSessionId()}:${startedRecord.laneId}`,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\tstatus: result.status,\n\t\t\t\treasonCode: result.reasonCode,\n\t\t\t\tcostUsd: result.costUsd,\n\t\t\t\tevidenceEntryId,\n\t\t\t});\n\t\t\tif (record) {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), record);\n\t\t\t\t// G3: a research lane's product is an evidence bundle, so its terminal record maps to\n\t\t\t\t// the evidence_bundle event. Lane outcome only (status/reasonCode/cost) — no findings text.\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.evidenceBundle,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tlaneId: record.laneId,\n\t\t\t\t\t\tlaneType: record.type,\n\t\t\t\t\t\tstatus: record.status,\n\t\t\t\t\t\treasonCode: record.reasonCode ?? null,\n\t\t\t\t\t\tcostUsd: record.costUsd ?? null,\n\t\t\t\t\t\thasEvidence: record.evidenceEntryId !== undefined,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn { started: true, record, result };\n\t\t} catch (error) {\n\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\treasonCode: \"research_lane_error\",\n\t\t\t});\n\t\t\tif (record && !this.deps.isDisposed()) {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), record);\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.evidenceBundle,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tlaneId: record.laneId,\n\t\t\t\t\t\tlaneType: record.type,\n\t\t\t\t\t\tstatus: record.status,\n\t\t\t\t\t\treasonCode: record.reasonCode ?? null,\n\t\t\t\t\t\tcostUsd: record.costUsd ?? null,\n\t\t\t\t\t\thasEvidence: record.evidenceEntryId !== undefined,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Research lane failed: ${message}` });\n\t\t\treturn { started: true, record };\n\t\t} finally {\n\t\t\tthis._isResearchLaneRunning = false;\n\t\t}\n\t}\n\n\t/**\n\t * Run one bounded scout-worker delegation: build a WorkerRequest with a stripped read-only\n\t * envelope, execute it as an isolated completion on a cheap lane, validate the result via\n\t * {@link validateWorkerResult} before acceptance, and persist result + lane record + spawned\n\t * usage (idempotent per-lane reportId). Consumed by the `delegate` tool.\n\t */\n\tstartWorkerDelegation(request: {\n\t\tinstructions: string;\n\t\t/** Model-provided replacement for the worker role prompt (the level-0 core always remains). */\n\t\tsystemPrompt?: string;\n\t}): { started: false; skipReason: string } | { started: true; record: LaneRecord } {\n\t\tconst settings = this.deps.getSettingsManager().getWorkerDelegationSettings();\n\t\tconst foreground = this.deps.getModel();\n\t\tconst managedLocal = foreground?.provider === \"ollama\" || foreground?.provider === \"transformers\";\n\t\tif (managedLocal) {\n\t\t\tif (\n\t\t\t\tthis._queuedWorkers.size >= 8 ||\n\t\t\t\tthis._laneTracker.getActiveCount(\"worker\") >= settings.maxConcurrent + 8\n\t\t\t) {\n\t\t\t\treturn { started: false, skipReason: \"worker_delegation_queue_full\" };\n\t\t\t}\n\t\t\tconst record = this._laneTracker.enqueue({ type: \"worker\" });\n\t\t\tthis._queuedWorkers.set(record.laneId, request);\n\t\t\tthis._scheduleWorkerNotification();\n\t\t\treturn { started: true, record };\n\t\t}\n\t\tlet startedRecord: LaneRecord | undefined;\n\t\tconst promise = this.runWorkerDelegationOnce(request, (record) => {\n\t\t\tstartedRecord = record;\n\t\t});\n\t\tif (!startedRecord) {\n\t\t\t// Preparation is synchronous up to the first isolated completion await. A promise that\n\t\t\t// rejected before producing a lane is still observed below, so it cannot become unhandled.\n\t\t\tvoid promise.catch(() => undefined);\n\t\t\treturn { started: false, skipReason: \"worker_not_started\" };\n\t\t}\n\t\tthis._workerPromises.set(startedRecord.laneId, promise);\n\t\tvoid promise.then(\n\t\t\t() => this._workerPromises.delete(startedRecord?.laneId ?? \"\"),\n\t\t\t() => this._workerPromises.delete(startedRecord?.laneId ?? \"\"),\n\t\t);\n\t\treturn { started: true, record: startedRecord };\n\t}\n\n\tasync runWorkerDelegationOnce(\n\t\trequest: {\n\t\t\tinstructions: string;\n\t\t\t/** Model-provided replacement for the worker role prompt (the level-0 core always remains). */\n\t\t\tsystemPrompt?: string;\n\t\t},\n\t\tonStarted?: (record: LaneRecord) => void,\n\t\texistingRecord?: LaneRecord,\n\t): Promise<WorkerDelegationRunOutcome> {\n\t\tconst delegationSettings = this.deps.getSettingsManager().getWorkerDelegationSettings();\n\t\tconst activeWorkers = this._laneTracker.getActiveCount(\"worker\") - (existingRecord ? 1 : 0);\n\t\tif (activeWorkers >= delegationSettings.maxConcurrent) {\n\t\t\treturn { started: false, skipReason: \"worker_delegation_already_running\" };\n\t\t}\n\t\tif (this.deps.isDisposed()) {\n\t\t\treturn { started: false, skipReason: \"session_disposed\" };\n\t\t}\n\t\tconst instructions = request.instructions.trim();\n\t\tif (instructions.length === 0) {\n\t\t\treturn { started: false, skipReason: \"missing_instructions\" };\n\t\t}\n\n\t\tconst settings = delegationSettings;\n\t\tif (!this.deps.isDelegateToolActive()) {\n\t\t\treturn { started: false, skipReason: \"delegate_tool_inactive\" };\n\t\t}\n\t\tif (!settings.enabled) {\n\t\t\treturn { started: false, skipReason: \"worker_delegation_disabled\" };\n\t\t}\n\n\t\tconst shipment = this._resolveLaneShipment(settings, \"no_worker_model\");\n\t\tif (!shipment.ok) {\n\t\t\treturn { started: false, skipReason: shipment.skipReason };\n\t\t}\n\t\tconst { model, laneProfile } = shipment;\n\t\tconst laneCapability = this._laneCapabilityProfile(model);\n\t\tif (!laneCapability.backgroundLanesEnabled) {\n\t\t\treturn { started: false, skipReason: \"model_delegation_unsupported\" };\n\t\t}\n\n\t\tthis._laneTracker.ensureCounterAtLeast(\n\t\t\tgetLaneRecordSnapshots(this.deps.getSessionManager().getEntries()).length + 1,\n\t\t);\n\t\tconst startedRecord = existingRecord ?? this._laneTracker.start({ type: \"worker\" });\n\t\tif (existingRecord) this._laneTracker.markRunning(existingRecord.laneId);\n\t\tonStarted?.(startedRecord);\n\t\tconst maxUsd = Math.min(\n\t\t\tsettings.maxUsd,\n\t\t\tthis.deps.getCapabilityEnvelope()?.maxEstimatedUsd ?? Number.POSITIVE_INFINITY,\n\t\t);\n\t\tconst writeEnabled = settings.writeEnabled && settings.writePaths.length > 0;\n\t\tconst toolSurface = createLaneToolSurface({\n\t\t\tcwd: this.deps.getCwd(),\n\t\t\tprofile: laneProfile,\n\t\t\twriteEnabled,\n\t\t\twritePaths: settings.writePaths,\n\t\t});\n\t\tthis._warnUnboundLaneToolGrants(laneProfile, toolSurface);\n\t\tconst allowedActionOps = new Set<WorkerAction[\"op\"]>(\n\t\t\ttoolSurface.allowedTools.filter((name): name is WorkerAction[\"op\"] => name === \"write\" || name === \"edit\"),\n\t\t);\n\t\tconst writeGranted = writeEnabled && allowedActionOps.size > 0;\n\t\tconst workerRequest: WorkerRequest = {\n\t\t\tid: startedRecord.laneId,\n\t\t\tinstructions,\n\t\t\troute: {\n\t\t\t\ttier: \"cheap\",\n\t\t\t\trisk: writeGranted ? \"scoped-write\" : \"read-only\",\n\t\t\t\tconfidence: 1,\n\t\t\t\treasonCode: \"scout_worker\",\n\t\t\t\treasons: [writeGranted ? \"Path-scoped worker delegation\" : \"Read-only scout delegation\"],\n\t\t\t},\n\t\t\tenvelope: {\n\t\t\t\tid: `worker-${this.deps.getSessionId()}-${startedRecord.laneId}`,\n\t\t\t\tprofileId: laneProfile?.name,\n\t\t\t\t// write_files requires BOTH the opt-in AND an explicit non-empty path scope —\n\t\t\t\t// an unscoped write grant is refused here, not discovered at validation time.\n\t\t\t\tcapabilities: writeGranted ? [\"read_files\", \"write_files\"] : [\"read_files\"],\n\t\t\t\t...(writeGranted ? { allowedPaths: [...settings.writePaths] } : {}),\n\t\t\t\tallowedTools: [...toolSurface.allowedTools],\n\t\t\t\tdeniedTools: [...toolSurface.deniedTools],\n\t\t\t\tmaxEstimatedUsd: maxUsd,\n\t\t\t\tcreatedAt: new Date().toISOString(),\n\t\t\t},\n\t\t\tmaxEstimatedUsd: maxUsd,\n\t\t\tcreatedAt: new Date().toISOString(),\n\t\t};\n\t\t// G8: worker delegation START. Routing/scope codes + budget only — never the instructions text.\n\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.workerRequest,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tpayload: {\n\t\t\t\tid: workerRequest.id,\n\t\t\t\ttier: workerRequest.route.tier,\n\t\t\t\tcapabilities: [...workerRequest.envelope.capabilities],\n\t\t\t\tmaxEstimatedUsd: workerRequest.maxEstimatedUsd ?? null,\n\t\t\t},\n\t\t});\n\t\tconst usageReportId = `worker:${this.deps.getSessionId()}:${startedRecord.laneId}`;\n\n\t\ttry {\n\t\t\tlet spentUsage: Usage | undefined;\n\t\t\tconst toolChangedFiles = new Set<string>();\n\t\t\tconst toolIssues = new Set<string>();\n\t\t\tconst outcome = await runWorker({\n\t\t\t\trequest: workerRequest,\n\t\t\t\tmaxUsd,\n\t\t\t\tmaxWallClockMs: settings.maxWallClockMs,\n\t\t\t\tusageReportId,\n\t\t\t\tgetChangedFiles: () => [...toolChangedFiles],\n\t\t\t\tsignal: this._workerDelegationAbort.signal,\n\t\t\t\t// Parent validation must use the same relative-path baseline the runner reports in.\n\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\t// Write lane (G2): runner-side action application through the envelope path scope.\n\t\t\t\tapplyActions: workerRequest.envelope.capabilities.includes(\"write_files\")\n\t\t\t\t\t? (actions) => {\n\t\t\t\t\t\t\tconst permitted = actions.filter((action) => allowedActionOps.has(action.op));\n\t\t\t\t\t\t\tconst applied = applyWorkerActions({\n\t\t\t\t\t\t\t\tactions: permitted,\n\t\t\t\t\t\t\t\tenvelope: workerRequest.envelope,\n\t\t\t\t\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t...applied,\n\t\t\t\t\t\t\t\trefused: [\n\t\t\t\t\t\t\t\t\t...actions\n\t\t\t\t\t\t\t\t\t\t.filter((action) => !allowedActionOps.has(action.op))\n\t\t\t\t\t\t\t\t\t\t.map((action) => ({\n\t\t\t\t\t\t\t\t\t\t\tpath: action.path,\n\t\t\t\t\t\t\t\t\t\t\treason: `${action.op} is not granted by the lane profile`,\n\t\t\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t\t\t...applied.refused,\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\t\t// Level-0 core always survives. A model-provided prompt (delegate tool) is the most\n\t\t\t\t\t\t// specific override, then the settings-level prompt, then profile soul + role prompt.\n\t\t\t\t\t\tsystemPrompt: composeSubagentSystemPrompt({\n\t\t\t\t\t\t\tsoul: laneProfile?.soul,\n\t\t\t\t\t\t\trolePrompt: systemPrompt,\n\t\t\t\t\t\t\toverride: request.systemPrompt ?? settings.systemPrompt,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tthinkingLevel: laneProfile?.thinking ?? \"off\",\n\t\t\t\t\t\tmaxTokens: laneCapability.laneMaxOutputTokens,\n\t\t\t\t\t\ttools: toolSurface.tools,\n\t\t\t\t\t\tmaxTurns: 6,\n\t\t\t\t\t\tbeforeToolCall: async (context, toolSignal) => {\n\t\t\t\t\t\t\tconst decision = await toolSurface.beforeToolCall(context, toolSignal);\n\t\t\t\t\t\t\tif (decision?.block) {\n\t\t\t\t\t\t\t\ttoolIssues.add(`${context.toolCall.name} blocked: ${decision.reason ?? \"capability denied\"}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn decision;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tafterToolCall: async ({ toolCall, args, isError }) => {\n\t\t\t\t\t\t\t// This hook runs only for a validated, gate-approved tool that actually entered\n\t\t\t\t\t\t\t// execution. Record a direct mutation target before inspecting `isError`: write/edit\n\t\t\t\t\t\t\t// may have changed disk and then observed cancellation, timeout, or a late I/O error.\n\t\t\t\t\t\t\t// Pre-gate/profile/path refusals never reach afterToolCall, so they remain unreported.\n\t\t\t\t\t\t\tif (toolCall.name === \"write\" || toolCall.name === \"edit\") {\n\t\t\t\t\t\t\t\tif (args && typeof args === \"object\" && !Array.isArray(args)) {\n\t\t\t\t\t\t\t\t\tconst rawPath = (args as Record<string, unknown>).path;\n\t\t\t\t\t\t\t\t\tif (typeof rawPath === \"string\" && rawPath.length > 0) {\n\t\t\t\t\t\t\t\t\t\tconst absolutePath = path.isAbsolute(rawPath)\n\t\t\t\t\t\t\t\t\t\t\t? path.resolve(rawPath)\n\t\t\t\t\t\t\t\t\t\t\t: path.resolve(this.deps.getCwd(), rawPath);\n\t\t\t\t\t\t\t\t\t\tlet canonicalPath = absolutePath;\n\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\tcanonicalPath = safeRealpathSync(absolutePath);\n\t\t\t\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t\t\t\t// Execution was attempted; preserve conservative accounting with the lexical path.\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\ttoolChangedFiles.add(path.relative(this.deps.getCwd(), canonicalPath));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (isError) {\n\t\t\t\t\t\t\t\ttoolIssues.add(`${toolCall.name} failed during isolated execution`);\n\t\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t// Core/soul/role are all static per configuration — the provider can cache the prefix.\n\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t});\n\t\t\t\t\tspentUsage = completion.usage;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttext: completion.text,\n\t\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t\t\tchangedFiles: [...toolChangedFiles],\n\t\t\t\t\t\tblockers: [...toolIssues],\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t});\n\n\t\t\t// Bug #21 pattern: never persist against a disposed session.\n\t\t\tif (this.deps.isDisposed()) {\n\t\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\t\tstatus: \"canceled\",\n\t\t\t\t\treasonCode: \"session_disposed\",\n\t\t\t\t});\n\t\t\t\tif (record) this._recordWorkerTerminal(record.status);\n\t\t\t\treturn { started: true, record, outcome };\n\t\t\t}\n\n\t\t\tthis.deps.saveWorkerResultSnapshot(outcome.result, workerRequest);\n\t\t\tif (spentUsage && (spentUsage.cost.total > 0 || spentUsage.totalTokens > 0)) {\n\t\t\t\tthis.deps.addSpawnedUsage(spentUsage, { label: \"worker-delegation\", reportId: usageReportId });\n\t\t\t}\n\n\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\tstatus: outcome.laneStatus,\n\t\t\t\treasonCode: outcome.reasonCode,\n\t\t\t\tcostUsd: outcome.costUsd,\n\t\t\t});\n\t\t\tif (record) {\n\t\t\t\tthis._recordWorkerTerminal(record.status);\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), record);\n\t\t\t\t// G3: worker lane terminal record -> worker_result event. Lane outcome only\n\t\t\t\t// (status/reasonCode/cost) — never the worker's summary/changed-file text.\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.workerResult,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tlaneId: record.laneId,\n\t\t\t\t\t\tlaneType: record.type,\n\t\t\t\t\t\tstatus: record.status,\n\t\t\t\t\t\treasonCode: record.reasonCode ?? null,\n\t\t\t\t\t\tcostUsd: record.costUsd ?? null,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn { started: true, record, outcome };\n\t\t} catch (error) {\n\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\treasonCode: \"worker_delegation_error\",\n\t\t\t});\n\t\t\tif (record) this._recordWorkerTerminal(record.status);\n\t\t\tif (record && !this.deps.isDisposed()) {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), record);\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.workerResult,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tlaneId: record.laneId,\n\t\t\t\t\t\tlaneType: record.type,\n\t\t\t\t\t\tstatus: record.status,\n\t\t\t\t\t\treasonCode: record.reasonCode ?? null,\n\t\t\t\t\t\tcostUsd: record.costUsd ?? null,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Worker delegation failed: ${message}` });\n\t\t\treturn { started: true, record };\n\t\t} finally {\n\t\t}\n\t}\n\n\t/**\n\t * Probe a candidate model against the subagent contracts (research/worker/judge/search/\n\t * tool-call surfaces) via {@link runModelFitnessProbe}. The model must resolve and\n\t * authenticate; every probe call runs as an isolated completion on that model, and probe\n\t * spend is reported through spawned-usage accounting.\n\t */\n\tasync runModelFitness(args: {\n\t\tmodel: string;\n\t\ttrials?: number;\n\t}): Promise<{ started: true; model: string; report: ModelFitnessReport } | { started: false; skipReason: string }> {\n\t\tif (this.deps.isDisposed()) return { started: false, skipReason: \"session_disposed\" };\n\t\tconst resolved = this.resolveLaneModel(args.model.trim() || undefined);\n\t\tif (!resolved) return { started: false, skipReason: \"model_unresolved_or_unauthenticated\" };\n\t\tconst capability = this._laneCapabilityProfile(resolved);\n\n\t\tconst spent: Usage = {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t};\n\t\tconst report = await runModelFitnessProbe({\n\t\t\ttrials: args.trials,\n\t\t\tsignal: this._researchLaneAbort.signal,\n\t\t\tcapacityProbe:\n\t\t\t\tresolved.provider === \"ollama\" && resolved.contextWindow > 0\n\t\t\t\t\t? { registeredContextWindow: resolved.contextWindow }\n\t\t\t\t\t: undefined,\n\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\tconst callStarted = Date.now();\n\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\tsystemPrompt,\n\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\tmodel: resolved,\n\t\t\t\t\tthinkingLevel: \"off\",\n\t\t\t\t\tmaxTokens: capability.laneMaxOutputTokens,\n\t\t\t\t\tsignal,\n\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t});\n\t\t\t\tconst callMs = Date.now() - callStarted;\n\t\t\t\tspent.input += completion.usage.input;\n\t\t\t\tspent.output += completion.usage.output;\n\t\t\t\tspent.cacheRead += completion.usage.cacheRead;\n\t\t\t\tspent.cacheWrite += completion.usage.cacheWrite;\n\t\t\t\tspent.totalTokens += completion.usage.totalTokens;\n\t\t\t\tspent.cost.input += completion.usage.cost.input;\n\t\t\t\tspent.cost.output += completion.usage.cost.output;\n\t\t\t\tspent.cost.cacheRead += completion.usage.cost.cacheRead;\n\t\t\t\tspent.cost.cacheWrite += completion.usage.cost.cacheWrite;\n\t\t\t\tspent.cost.total += completion.usage.cost.total;\n\t\t\t\treturn {\n\t\t\t\t\ttext: completion.text,\n\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t\t// Wall-clock fallback for tok/s: providers don't expose pure eval time, so the\n\t\t\t\t\t// measured call time stands in — slightly conservative (includes network/queue).\n\t\t\t\t\toutputTokens: completion.usage.output,\n\t\t\t\t\tevalMs: callMs,\n\t\t\t\t};\n\t\t\t},\n\t\t});\n\t\tif (!this.deps.isDisposed() && (spent.cost.total > 0 || spent.totalTokens > 0)) {\n\t\t\tthis.deps.addSpawnedUsage(spent, { label: \"model-fitness\" });\n\t\t}\n\t\tconst modelRef = `${resolved.provider}/${resolved.id}`;\n\t\t// Fitness is a property of a model ON a host — persist the report host-keyed so role\n\t\t// assignments stay per-machine (a model can await better hardware without being forgotten).\n\t\t// Best-effort: a disk problem must not fail the probe itself.\n\t\ttry {\n\t\t\tif (!this.deps.isDisposed()) {\n\t\t\t\tFitnessStore.forAgentDir(this.deps.getAgentDir()).save(modelRef, report);\n\t\t\t}\n\t\t} catch {\n\t\t\t// best-effort persistence\n\t\t}\n\t\treturn { started: true, model: modelRef, report };\n\t}\n\n\t/** Start queued local workers at the owner session's foreground-idle boundary. */\n\tdrainQueuedWorkerDelegations(): void {\n\t\tfor (const [laneId, request] of [...this._queuedWorkers]) {\n\t\t\tif (\n\t\t\t\tthis._laneTracker.getActiveCount(\"worker\") >\n\t\t\t\tthis.deps.getSettingsManager().getWorkerDelegationSettings().maxConcurrent\n\t\t\t)\n\t\t\t\tbreak;\n\t\t\tconst record = this._laneTracker.getRecords().find((candidate) => candidate.laneId === laneId);\n\t\t\tif (!record) {\n\t\t\t\tthis._queuedWorkers.delete(laneId);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis._queuedWorkers.delete(laneId);\n\t\t\tconst promise = this.runWorkerDelegationOnce(request, undefined, record);\n\t\t\tthis._workerPromises.set(laneId, promise);\n\t\t\tvoid promise.then(\n\t\t\t\t(outcome) => {\n\t\t\t\t\tif (!outcome.started) {\n\t\t\t\t\t\tconst terminal = this._laneTracker.complete(laneId, {\n\t\t\t\t\t\t\tstatus: \"canceled\",\n\t\t\t\t\t\t\treasonCode: outcome.skipReason,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (terminal) this._recordWorkerTerminal(terminal.status);\n\t\t\t\t\t}\n\t\t\t\t\tthis._workerPromises.delete(laneId);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tconst terminal = this._laneTracker.complete(laneId, {\n\t\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\t\treasonCode: \"worker_background_error\",\n\t\t\t\t\t});\n\t\t\t\t\tif (terminal) this._recordWorkerTerminal(terminal.status);\n\t\t\t\t\tthis._workerPromises.delete(laneId);\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t}\n\n\t/** Fitness reports persisted for THIS host (measured evidence for architect/profile decisions). */\n\tgetStoredFitnessReports(): StoredFitnessReport[] {\n\t\ttry {\n\t\t\treturn FitnessStore.forAgentDir(this.deps.getAgentDir()).getForHost();\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"background-lane-controller.d.ts","sourceRoot":"","sources":["../../src/core/background-lane-controller.ts"],"names":[],"mappings":"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","sourcesContent":["/**\n * Background-lane controller: goal auto-continue, the research lane, scout-worker delegation, and\n * the model-fitness probe.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the lane timers, the\n * single-flight guards, the last research-lane skip reason, the live {@link LaneTracker}, and the\n * session-lifetime abort controllers for in-flight research/worker passes. Everything else it needs\n * — the session manager, settings, model registry, live model, capability envelope, the goal\n * continuation LOOP, the isolated-completion primitive, spawned-usage accounting, and the telemetry\n * sink — is reached through narrow deps accessors rather than the whole AgentSession.\n *\n * Drive-loop boundary (deliberate): the idle triggers ({@link scheduleGoalAutoContinueFromIdle},\n * {@link scheduleResearchLaneFromIdle}) are invoked from the session's prompt tail as one-line\n * delegations; goal auto-continue itself only ever asks the session to `continueGoalLoop`, so this\n * controller never touches `prompt()`, the last-assistant-message, retry, or streaming state.\n */\n\nimport path from \"node:path\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { Api, Model, Usage } from \"@caupulican/pi-ai\";\nimport type {\n\tAgentSessionEvent,\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tIsolatedCompletionOptions,\n\tIsolatedCompletionResult,\n\tPromptOptions,\n\tResearchLaneRunOutcome,\n\tWorkerDelegationRunOutcome,\n} from \"./agent-session.ts\";\nimport type { CapabilityEnvelope, EvidenceBundle, WorkerRequest, WorkerResult } from \"./autonomy/contracts.ts\";\nimport { createLaneToolSurface, type LaneToolSurface } from \"./autonomy/lane-tool-surface.ts\";\nimport { type LaneRecord, type LaneTerminalStatus, LaneTracker } from \"./autonomy/lane-tracker.ts\";\nimport { safeRealpathSync } from \"./autonomy/path-scope.ts\";\nimport { appendLaneRecordSnapshot, getLaneRecordSnapshots } from \"./autonomy/session-lane-record.ts\";\nimport { composeSubagentSystemPrompt } from \"./autonomy/subagent-prompt.ts\";\nimport { AUTONOMY_TELEMETRY_EVENT_TYPES, type AutonomyTelemetryEvent } from \"./autonomy/telemetry-events.ts\";\nimport { applyWorkerActions, type WorkerAction } from \"./delegation/worker-actions.ts\";\nimport { runWorker } from \"./delegation/worker-runner.ts\";\nimport type { GoalRuntimeSnapshot, GoalRuntimeSnapshotSettings } from \"./goals/goal-runtime-snapshot.ts\";\nimport type { GoalState } from \"./goals/goal-state.ts\";\nimport {\n\tderiveModelCapabilityProfile,\n\ttype ModelCapabilityProfile,\n\tscaleContinuationBudgetsForCapability,\n} from \"./model-capability.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { resolveCliModel } from \"./model-resolver.ts\";\nimport { FitnessStore, type StoredFitnessReport } from \"./models/fitness-store.ts\";\nimport type { NormalizedProfile } from \"./profile-registry.ts\";\nimport { type ModelFitnessReport, runModelFitnessProbe } from \"./research/model-fitness.ts\";\nimport { runResearch } from \"./research/research-runner.ts\";\nimport type { collectWorkspaceSources } from \"./research/workspace-collector.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\nexport function clampLaneMaxUsd(settingsMaxUsd: number, foregroundMaxEstimatedUsd?: number): number {\n\treturn Math.min(settingsMaxUsd, foregroundMaxEstimatedUsd ?? Number.POSITIVE_INFINITY);\n}\n\nexport function getPrivateLaneDeniedPaths(cwd: string, agentDir: string): string[] {\n\treturn [\n\t\t\"auth.json\",\n\t\t\"MEMORY.md\",\n\t\t\"USER.md\",\n\t\t\"settings.json\",\n\t\t\"models.json\",\n\t\t\"trust.json\",\n\t\t\"sessions\",\n\t\t\"state\",\n\t\t\"context-artifacts\",\n\t\t\"context-gc\",\n\t]\n\t\t.map((entry) => path.join(agentDir, entry))\n\t\t.concat(path.join(cwd, \".pi\", \"settings.json\"));\n}\n\nexport function isLocalExecutionModel(model: Pick<Model<Api>, \"provider\" | \"baseUrl\">): boolean {\n\tif (model.provider === \"ollama\" || model.provider === \"transformers\" || model.provider === \"llama-cpp\") {\n\t\treturn true;\n\t}\n\ttry {\n\t\tconst hostname = new URL(model.baseUrl).hostname.toLowerCase();\n\t\treturn hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname === \"::1\" || hostname === \"[::1]\";\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport interface BackgroundLaneControllerDeps {\n\t/** A disposed session must never schedule/persist a lane or continuation. */\n\tisDisposed(): boolean;\n\t/** Child sessions never run the idle research lane (only the top-level session drives autonomy). */\n\tisChildSession(): boolean;\n\t/** This session's id, for lane envelope ids and spawned-usage report ids. */\n\tgetSessionId(): string;\n\t/** The workspace root a lane runs relative to (worker path scope + research source collection). */\n\tgetCwd(): string;\n\t/** Root dir the host-keyed {@link FitnessStore} persists under. */\n\tgetAgentDir(): string;\n\t/** Session log: lane records read/append here and feed lane-history dedupe. */\n\tgetSessionManager(): SessionManager;\n\t/** Autonomy / research-lane / worker-delegation / model-capability settings + the profile registry. */\n\tgetSettingsManager(): SettingsManager;\n\t/** Resolves a configured lane model pattern against configured auth. */\n\tgetModelRegistry(): ModelRegistry;\n\t/** Session-scoped provider/model quota exhaustion guard. */\n\tisModelExhausted(model: Model<Api>): boolean;\n\t/** The session's current model — lanes inherit it unless a lane model is explicitly configured. */\n\tgetModel(): Model<Api> | undefined;\n\t/** Tool/profile gate: delegation is unavailable when the active surface removes `delegate`. */\n\tisDelegateToolActive(): boolean;\n\t/** Foreground cost ceiling — a lane budget is clamped to it, never exceeds it. */\n\tgetCapabilityEnvelope(): CapabilityEnvelope | undefined;\n\t/** Capability profile of the SESSION model (gates background lanes, scales continuation budgets). */\n\tgetModelCapabilityProfile(): ModelCapabilityProfile;\n\t/** Emits a session event (only `warning` from this controller). */\n\temit(event: AgentSessionEvent): void;\n\t/** G3/G8 telemetry sink (codes/ids only — never lane product text). */\n\temitAutonomyTelemetry(event: AutonomyTelemetryEvent): void;\n\t/** Durable goal state, if a goal is active (the research lane's demand source). */\n\tgetGoalStateSnapshot(): GoalState | undefined;\n\t/** Continuation gate + goal state for the idle autosteer scheduler. */\n\tgetGoalRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot;\n\t/** Latest persisted evidence bundle, for research-lane dedupe. */\n\tgetEvidenceBundleSnapshot(): EvidenceBundle | undefined;\n\t/** Persist a research lane's evidence bundle to the session log. */\n\tsaveEvidenceBundleSnapshot(bundle: EvidenceBundle): string;\n\t/** Persist a worker delegation's result snapshot to the session log. */\n\tsaveWorkerResultSnapshot(result: WorkerResult, request?: WorkerRequest): string;\n\t/** Bounded, source-labeled memory retrieval for an orchestrator-authorized worker. */\n\treadMemoryForLane(query: string): Promise<string>;\n\t/** Roll a lane's spawned usage into session accounting (idempotent per reportId). */\n\taddSpawnedUsage(\n\t\tusage: Usage,\n\t\topts?: { label?: string; sourceSessionId?: string; reportId?: string },\n\t): string | undefined;\n\t/** Bounded LLM call fully isolated from the main session; lanes may supply a child tool loop. */\n\trunIsolatedCompletion(opts: IsolatedCompletionOptions): Promise<IsolatedCompletionResult>;\n\t/** Drive-loop boundary: the session's bounded goal-continuation loop (owns `prompt()`, not us). */\n\tcontinueGoalLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult>;\n\t/** Best-effort workspace evidence collection (silent-on-failure; [] preserves prior behavior). */\n\tcollectWorkspaceSources: typeof collectWorkspaceSources;\n}\n\nexport class BackgroundLaneController {\n\t/** Pending idle timer that starts bounded goal continuation after the session becomes idle. */\n\tprivate _goalAutoContinueTimer: ReturnType<typeof setTimeout> | undefined;\n\t/** Guards bounded idle autosteer so continuation prompts do not recursively trigger themselves. */\n\tprivate _isGoalAutoContinuing = false;\n\t/** Pending idle timer that starts an autonomous research pass after the session becomes idle. */\n\tprivate _researchLaneTimer: ReturnType<typeof setTimeout> | undefined;\n\t/** Single-flight guard: at most one research pass runs at a time per session. */\n\tprivate _isResearchLaneRunning = false;\n\t/** Why the last idle research-lane evaluation skipped, for /autonomy diagnostics. */\n\tprivate _lastResearchLaneSkipReason: string | undefined;\n\t/** Live lane registry — the real source for AutonomyStatusSnapshot.activeLaneCount. */\n\tprivate readonly _laneTracker = new LaneTracker();\n\tprivate _laneHistorySeeded = false;\n\tprivate _persistedResearchRunCount = 0;\n\t/** Session-lifetime abort for in-flight research passes (same pattern as _reflectionAbort). */\n\tprivate readonly _researchLaneAbort = new AbortController();\n\t/** Session-lifetime abort for in-flight delegated workers. */\n\tprivate readonly _workerDelegationAbort = new AbortController();\n\t/** Session-local de-duplication for fail-closed profile grants that cannot bind to lane tools. */\n\tprivate readonly _warnedUnboundLaneToolGrants = new Set<string>();\n\t/** Every background execution is retained until its terminal result is observed. */\n\tprivate readonly _workerPromises = new Map<string, Promise<WorkerDelegationRunOutcome>>();\n\tprivate readonly _queuedWorkers = new Map<\n\t\tstring,\n\t\t{ instructions: string; systemPrompt?: string; memoryRead?: boolean }\n\t>();\n\tprivate _workerNotificationTimer: ReturnType<typeof setTimeout> | undefined;\n\tprivate _workersCompletedSinceFlush = 0;\n\tprivate _workersFailedSinceFlush = 0;\n\tprivate readonly _workerTerminalSinceFlush: Array<{\n\t\tlaneId: string;\n\t\tstatus: LaneTerminalStatus;\n\t\treasonCode?: string;\n\t}> = [];\n\n\tprivate readonly deps: BackgroundLaneControllerDeps;\n\n\tprivate _scheduleWorkerNotification(): void {\n\t\tif (this._workerNotificationTimer !== undefined) return;\n\t\tthis._workerNotificationTimer = setTimeout(() => {\n\t\t\tthis._workerNotificationTimer = undefined;\n\t\t\tconst queued = this._laneTracker\n\t\t\t\t.getRecords()\n\t\t\t\t.filter((record) => record.type === \"worker\" && record.status === \"queued\").length;\n\t\t\tconst running = this._laneTracker.getRunningCount(\"worker\");\n\t\t\tthis.deps.emit({\n\t\t\t\ttype: \"delegate_workers\",\n\t\t\t\tactive: queued + running,\n\t\t\t\tqueued,\n\t\t\t\trunning,\n\t\t\t\tcompletedSinceFlush: this._workersCompletedSinceFlush,\n\t\t\t\tfailedSinceFlush: this._workersFailedSinceFlush,\n\t\t\t\tterminalSinceFlush: this._workerTerminalSinceFlush.splice(0),\n\t\t\t});\n\t\t\tthis._workersCompletedSinceFlush = 0;\n\t\t\tthis._workersFailedSinceFlush = 0;\n\t\t}, 75);\n\t\tconst timer = this._workerNotificationTimer;\n\t\tif (typeof timer === \"object\" && timer && \"unref\" in timer) timer.unref();\n\t}\n\n\tprivate _recordWorkerTerminal(record: LaneRecord): void {\n\t\tif (record.status === \"queued\" || record.status === \"running\") return;\n\t\tif (record.status === \"succeeded\") this._workersCompletedSinceFlush++;\n\t\telse this._workersFailedSinceFlush++;\n\t\tthis._workerTerminalSinceFlush.push({\n\t\t\tlaneId: record.laneId,\n\t\t\tstatus: record.status,\n\t\t\t...(record.reasonCode ? { reasonCode: record.reasonCode } : {}),\n\t\t});\n\t\tthis._scheduleWorkerNotification();\n\t}\n\n\tconstructor(deps: BackgroundLaneControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tprivate _seedLaneHistory(): void {\n\t\tif (this._laneHistorySeeded) return;\n\t\tconst records = getLaneRecordSnapshots(this.deps.getSessionManager().getEntries());\n\t\tthis._laneTracker.ensureCounterAtLeast(records.length + 1);\n\t\tthis._persistedResearchRunCount = records.filter((record) => record.type === \"research\").length;\n\t\tthis._laneHistorySeeded = true;\n\t}\n\n\t/** Live lane records tracked by this process (running and terminal). */\n\tgetLaneRecords(): LaneRecord[] {\n\t\treturn this._laneTracker.getRecords();\n\t}\n\n\t/** Live count of active lanes — the real source for AutonomyStatusSnapshot.activeLaneCount. */\n\tgetActiveLaneCount(): number {\n\t\treturn this._laneTracker.getActiveCount();\n\t}\n\n\t/** Why the last idle research-lane evaluation skipped, for /autonomy diagnostics. */\n\tgetLastResearchLaneSkipReason(): string | undefined {\n\t\treturn this._lastResearchLaneSkipReason;\n\t}\n\n\t/** Abort any in-flight research pass or delegated worker (called on session dispose). */\n\tabortInFlightLanes(): void {\n\t\tthis._researchLaneAbort.abort();\n\t\tthis._workerDelegationAbort.abort();\n\t\tif (this._workerNotificationTimer !== undefined) {\n\t\t\tclearTimeout(this._workerNotificationTimer);\n\t\t\tthis._workerNotificationTimer = undefined;\n\t\t}\n\t}\n\n\tclearGoalAutoContinueTimer(): void {\n\t\tif (this._goalAutoContinueTimer !== undefined) {\n\t\t\tclearTimeout(this._goalAutoContinueTimer);\n\t\t\tthis._goalAutoContinueTimer = undefined;\n\t\t}\n\t}\n\n\tscheduleGoalAutoContinueFromIdle(options?: PromptOptions): void {\n\t\tif (options?.autoContinueGoal === false || this._isGoalAutoContinuing || this.deps.isDisposed()) return;\n\n\t\t// Small-window models cannot afford multi-thousand-token continuation prompts per idle turn.\n\t\tif (!this.deps.getModelCapabilityProfile().backgroundLanesEnabled) return;\n\n\t\tconst { maxStallTurns, goalAutoContinue, goalAutoContinueDelayMs } = this.deps\n\t\t\t.getSettingsManager()\n\t\t\t.getAutonomySettings();\n\t\tif (!goalAutoContinue) return;\n\n\t\tconst snapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns });\n\t\tif (snapshot.continuation.action !== \"continue\") return;\n\n\t\tthis.clearGoalAutoContinueTimer();\n\t\tthis._goalAutoContinueTimer = setTimeout(() => {\n\t\t\tthis._goalAutoContinueTimer = undefined;\n\t\t\tvoid this._runScheduledGoalAutoContinue();\n\t\t}, goalAutoContinueDelayMs);\n\n\t\tconst timer = this._goalAutoContinueTimer;\n\t\tif (typeof timer === \"object\" && timer && \"unref\" in timer) {\n\t\t\tconst { unref } = timer as { unref?: () => void };\n\t\t\tunref?.call(timer);\n\t\t}\n\t}\n\n\tprivate async _runScheduledGoalAutoContinue(): Promise<void> {\n\t\tif (this._isGoalAutoContinuing || this.deps.isDisposed()) return;\n\n\t\tconst { maxStallTurns, goalContinueTurns, goalContinueMaxWallClockMinutes, goalAutoContinue } = this.deps\n\t\t\t.getSettingsManager()\n\t\t\t.getAutonomySettings();\n\t\tif (!goalAutoContinue) return;\n\n\t\tconst snapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns });\n\t\tif (snapshot.continuation.action !== \"continue\") return;\n\n\t\t// Lean-window models (16-32k) keep autosteer but at a reduced budget; full passes through.\n\t\tconst scaled = scaleContinuationBudgetsForCapability(this.deps.getModelCapabilityProfile(), {\n\t\t\tmaxTurns: goalContinueTurns,\n\t\t\tmaxWallClockMinutes: goalContinueMaxWallClockMinutes,\n\t\t});\n\n\t\tthis._isGoalAutoContinuing = true;\n\t\ttry {\n\t\t\tawait this.deps.continueGoalLoop({\n\t\t\t\tmaxTurns: scaled.maxTurns,\n\t\t\t\tmaxStallTurns,\n\t\t\t\tmaxWallClockMinutes: scaled.maxWallClockMinutes,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Goal auto-continuation failed: ${message}` });\n\t\t} finally {\n\t\t\tthis._isGoalAutoContinuing = false;\n\t\t}\n\t}\n\n\tclearResearchLaneTimer(): void {\n\t\tif (this._researchLaneTimer !== undefined) {\n\t\t\tclearTimeout(this._researchLaneTimer);\n\t\t\tthis._researchLaneTimer = undefined;\n\t\t}\n\t}\n\n\t/**\n\t * Derive the research demand from durable goal state: an active goal with open requirements,\n\t * deduplicated against the latest persisted bundle so the same requirement set is never\n\t * researched twice (the query is deterministic, so dedupe survives session reload).\n\t */\n\tprivate _buildResearchLaneDemand(): { query: string; context: string; goalId: string } | undefined {\n\t\tconst goal = this.deps.getGoalStateSnapshot();\n\t\tif (!goal || goal.status !== \"active\") {\n\t\t\tthis._lastResearchLaneSkipReason = \"no_active_goal\";\n\t\t\treturn undefined;\n\t\t}\n\t\tconst open = goal.requirements.filter((requirement) => requirement.status === \"open\");\n\t\tif (open.length === 0) {\n\t\t\tthis._lastResearchLaneSkipReason = \"no_open_requirements\";\n\t\t\treturn undefined;\n\t\t}\n\t\tconst query = `goal:${goal.goalId} requirements:${open\n\t\t\t.map((requirement) => requirement.id)\n\t\t\t.sort()\n\t\t\t.join(\",\")}`;\n\t\tif (this.deps.getEvidenceBundleSnapshot()?.query === query) {\n\t\t\tthis._lastResearchLaneSkipReason = \"recent_evidence_sufficient\";\n\t\t\treturn undefined;\n\t\t}\n\t\tconst context = [\n\t\t\t`Goal: ${goal.userGoal}`,\n\t\t\t\"Open requirements:\",\n\t\t\t...open.slice(0, 20).map((requirement) => `- ${requirement.text}`),\n\t\t].join(\"\\n\");\n\t\treturn { query, context, goalId: goal.goalId };\n\t}\n\n\t/**\n\t * Idle trigger for the autonomous research lane (mirrors {@link scheduleGoalAutoContinueFromIdle}).\n\t * All skips are recorded in `_lastResearchLaneSkipReason` and surfaced via diagnostics — the lane\n\t * informs, it never prompts or blocks the foreground.\n\t */\n\tscheduleResearchLaneFromIdle(): void {\n\t\tif (this._isResearchLaneRunning || this.deps.isDisposed() || this.deps.isChildSession()) return;\n\n\t\tconst research = this.deps.getSettingsManager().getResearchLaneSettings();\n\t\tif (!research.enabled) {\n\t\t\tthis._lastResearchLaneSkipReason = \"research_lane_disabled\";\n\t\t\treturn;\n\t\t}\n\t\tconst { mode } = this.deps.getSettingsManager().getAutonomySettings();\n\t\tif (mode === \"off\") {\n\t\t\tthis._lastResearchLaneSkipReason = \"autonomy_mode_off\";\n\t\t\treturn;\n\t\t}\n\t\tthis._seedLaneHistory();\n\t\tif (this._persistedResearchRunCount >= research.maxRunsPerSession) {\n\t\t\tthis._lastResearchLaneSkipReason = \"max_runs_reached\";\n\t\t\treturn;\n\t\t}\n\t\tif (!this._buildResearchLaneDemand()) return;\n\t\tconst shipment = this._resolveLaneShipment(research, \"no_research_model\");\n\t\tif (!shipment.ok) {\n\t\t\tthis._lastResearchLaneSkipReason = shipment.skipReason;\n\t\t\treturn;\n\t\t}\n\t\tif (!this._laneCapabilityProfile(shipment.model).backgroundLanesEnabled) {\n\t\t\tthis._lastResearchLaneSkipReason = \"model_research_unsupported\";\n\t\t\treturn;\n\t\t}\n\n\t\tthis.clearResearchLaneTimer();\n\t\tthis._researchLaneTimer = setTimeout(() => {\n\t\t\tthis._researchLaneTimer = undefined;\n\t\t\tvoid this._runScheduledResearchLane();\n\t\t}, research.idleDelayMs);\n\n\t\tconst timer = this._researchLaneTimer;\n\t\tif (typeof timer === \"object\" && timer && \"unref\" in timer) {\n\t\t\tconst { unref } = timer as { unref?: () => void };\n\t\t\tunref?.call(timer);\n\t\t}\n\t}\n\n\tprivate async _runScheduledResearchLane(): Promise<void> {\n\t\tif (this._isResearchLaneRunning || this.deps.isDisposed()) return;\n\n\t\tconst research = this.deps.getSettingsManager().getResearchLaneSettings();\n\t\tconst { mode } = this.deps.getSettingsManager().getAutonomySettings();\n\t\tif (!research.enabled || mode === \"off\") return;\n\n\t\ttry {\n\t\t\tawait this.runResearchLaneOnce();\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Research lane failed: ${message}` });\n\t\t}\n\t}\n\n\t/** Capability profile for a specific lane model (lane budgets scale to the lane model's window). */\n\tprivate _laneCapabilityProfile(model: Model<Api>): ModelCapabilityProfile {\n\t\treturn deriveModelCapabilityProfile({\n\t\t\tcontextWindow: model.contextWindow,\n\t\t\tmode: this.deps.getSettingsManager().getModelCapabilitySettings().mode,\n\t\t});\n\t}\n\n\t/**\n\t * Resolve the model for a background lane. Lanes are shipped BY this session, so they inherit\n\t * the session's own model unless a lane-specific model is explicitly configured — a single-model\n\t * setup (e.g. one local open model) runs its lanes on that same model. An explicitly configured\n\t * pattern that cannot resolve/authenticate is a visible skip, not a silent fallback.\n\t */\n\tresolveLaneModel(configuredPattern: string | undefined): Model<Api> | undefined {\n\t\tif (configuredPattern) {\n\t\t\tconst resolved = resolveCliModel({ cliModel: configuredPattern, modelRegistry: this.deps.getModelRegistry() });\n\t\t\tif (resolved.model && this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) {\n\t\t\t\treturn resolved.model;\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t\treturn this.deps.getModel() ?? undefined;\n\t}\n\n\t/**\n\t * Resolve what a lane ships with. Precedence: explicit lane model setting, then the lane\n\t * profile's model (a shipped profile with a model MUST be obeyed — unresolvable is a visible\n\t * skip, never a fallback), then generic inheritance of the session model.\n\t */\n\tprivate _resolveLaneShipment(\n\t\tlaneSettings: { model?: string; profile?: string },\n\t\tmissingModelReason: string,\n\t): { ok: true; model: Model<Api>; laneProfile?: NormalizedProfile } | { ok: false; skipReason: string } {\n\t\tlet laneProfile: NormalizedProfile | undefined;\n\t\tif (laneSettings.profile) {\n\t\t\tconst profileRef = laneSettings.profile.trim();\n\t\t\tconst registry = this.deps.getSettingsManager().getProfileRegistry();\n\t\t\tlaneProfile =\n\t\t\t\tprofileRef.startsWith(\"./\") || profileRef.startsWith(\"../\")\n\t\t\t\t\t? registry.resolveProfileRef(profileRef, this.deps.getCwd())\n\t\t\t\t\t: registry.getProfile(profileRef);\n\t\t\tif (!laneProfile) {\n\t\t\t\treturn { ok: false, skipReason: \"lane_profile_not_found\" };\n\t\t\t}\n\t\t}\n\n\t\tlet model: Model<Api> | undefined;\n\t\tif (laneSettings.model) {\n\t\t\tmodel = this.resolveLaneModel(laneSettings.model);\n\t\t\tif (!model) return { ok: false, skipReason: missingModelReason };\n\t\t} else if (laneProfile?.model) {\n\t\t\tmodel = this.resolveLaneModel(laneProfile.model);\n\t\t\tif (!model) return { ok: false, skipReason: \"no_lane_profile_model\" };\n\t\t} else {\n\t\t\tmodel = this.deps.getModel() ?? undefined;\n\t\t\tif (!model) return { ok: false, skipReason: missingModelReason };\n\t\t}\n\t\tif (this.deps.isModelExhausted(model)) {\n\t\t\treturn { ok: false, skipReason: `${model.provider}/${model.id} model exhausted: quota` };\n\t\t}\n\t\treturn { ok: true, model, laneProfile };\n\t}\n\n\tprivate _warnUnboundLaneToolGrants(laneProfile: NormalizedProfile | undefined, surface: LaneToolSurface): void {\n\t\tif (!laneProfile || surface.unboundAllowPatterns.length === 0) return;\n\t\tconst warningKey = `${laneProfile.name}\\0${[...surface.unboundAllowPatterns].sort().join(\"\\0\")}`;\n\t\tif (this._warnedUnboundLaneToolGrants.has(warningKey)) return;\n\t\tthis._warnedUnboundLaneToolGrants.add(warningKey);\n\t\tthis.deps.emit({\n\t\t\ttype: \"warning\",\n\t\t\tmessage: `Lane profile '${laneProfile.name}' grants unavailable isolated-lane tools: ${surface.unboundAllowPatterns.join(\", \")}. Only classified lane tools can execute.`,\n\t\t});\n\t}\n\n\t/** Stripped research envelope — never the foreground/architect envelope. */\n\tprivate _buildResearchLaneEnvelope(\n\t\tmaxUsd: number,\n\t\tlaneProfile: NormalizedProfile | undefined,\n\t\tsurface: LaneToolSurface,\n\t): CapabilityEnvelope {\n\t\treturn {\n\t\t\tid: `research-${this.deps.getSessionId()}-${Date.now()}`,\n\t\t\tprofileId: laneProfile?.name,\n\t\t\tcapabilities: [\"research\", \"read_files\", \"memory_read\"],\n\t\t\tallowedTools: [...surface.allowedTools],\n\t\t\tdeniedTools: [...surface.deniedTools],\n\t\t\tallowedPaths: [this.deps.getCwd()],\n\t\t\tdeniedPaths: getPrivateLaneDeniedPaths(this.deps.getCwd(), this.deps.getAgentDir()),\n\t\t\tmaxEstimatedUsd: clampLaneMaxUsd(maxUsd, this.deps.getCapabilityEnvelope()?.maxEstimatedUsd),\n\t\t\tcreatedAt: new Date().toISOString(),\n\t\t};\n\t}\n\n\t/**\n\t * Run one bounded, read-only research pass and persist its results: evidence bundle snapshot,\n\t * terminal lane record, and spawned-usage cost report (single-hop invariant, idempotent on the\n\t * lane's reportId). Explicit calls (e.g. `/autonomy research`) express user intent and bypass the\n\t * enabled/mode/dedupe gates the idle scheduler enforces; budget and capability gates always apply.\n\t */\n\tasync runResearchLaneOnce(request?: {\n\t\tquery?: string;\n\t\tcontext?: string;\n\t\tgoalId?: string;\n\t}): Promise<ResearchLaneRunOutcome> {\n\t\tif (this._isResearchLaneRunning) {\n\t\t\treturn { started: false, skipReason: \"research_lane_already_running\" };\n\t\t}\n\t\tif (this.deps.isDisposed()) {\n\t\t\treturn { started: false, skipReason: \"session_disposed\" };\n\t\t}\n\n\t\tconst settings = this.deps.getSettingsManager().getResearchLaneSettings();\n\t\tconst demand = request?.query\n\t\t\t? { query: request.query, context: request.context ?? \"\", goalId: request.goalId }\n\t\t\t: this._buildResearchLaneDemand();\n\t\tif (!demand) {\n\t\t\treturn { started: false, skipReason: this._lastResearchLaneSkipReason ?? \"no_research_demand\" };\n\t\t}\n\n\t\tconst shipment = this._resolveLaneShipment(settings, \"no_research_model\");\n\t\tif (!shipment.ok) {\n\t\t\tthis._lastResearchLaneSkipReason = shipment.skipReason;\n\t\t\treturn { started: false, skipReason: shipment.skipReason };\n\t\t}\n\t\tconst { model, laneProfile } = shipment;\n\t\tconst laneCapability = this._laneCapabilityProfile(model);\n\t\tif (!laneCapability.backgroundLanesEnabled) {\n\t\t\tthis._lastResearchLaneSkipReason = \"model_research_unsupported\";\n\t\t\treturn { started: false, skipReason: \"model_research_unsupported\" };\n\t\t}\n\n\t\tthis._isResearchLaneRunning = true;\n\t\tthis._seedLaneHistory();\n\t\tconst startedRecord = this._laneTracker.start({ type: \"research\", goalId: demand.goalId });\n\t\tthis._persistedResearchRunCount++;\n\t\ttry {\n\t\t\tlet spentUsage: Usage | undefined;\n\t\t\t// Best-effort, pointer-first workspace evidence. Derives search terms from the goal/requirement\n\t\t\t// text (not the identity-key query) and is bounded + silent-on-failure: [] == today's behavior.\n\t\t\tconst workspaceSources = await this.deps.collectWorkspaceSources({\n\t\t\t\tquery: `${demand.context}\\n${demand.query}`,\n\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\tmaxSources: settings.maxSources,\n\t\t\t});\n\t\t\tconst maxUsd = clampLaneMaxUsd(settings.maxUsd, this.deps.getCapabilityEnvelope()?.maxEstimatedUsd);\n\t\t\tconst toolSurface = createLaneToolSurface({\n\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\tprofile: laneProfile,\n\t\t\t\tdeniedPaths: getPrivateLaneDeniedPaths(this.deps.getCwd(), this.deps.getAgentDir()),\n\t\t\t});\n\t\t\tthis._warnUnboundLaneToolGrants(laneProfile, toolSurface);\n\t\t\tconst result = await runResearch({\n\t\t\t\tquery: demand.query,\n\t\t\t\tcontext: demand.context,\n\t\t\t\tsources: workspaceSources,\n\t\t\t\tenvelope: this._buildResearchLaneEnvelope(maxUsd, laneProfile, toolSurface),\n\t\t\t\tmaxUsd,\n\t\t\t\tmaxSources: settings.maxSources,\n\t\t\t\tmaxFindings: settings.maxFindings,\n\t\t\t\tmaxWallClockMs: settings.maxWallClockMs,\n\t\t\t\tsignal: this._researchLaneAbort.signal,\n\t\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\t\t// Level-0 core always survives; profile soul and role prompt are the replaceable\n\t\t\t\t\t\t// layers; a settings-provided prompt replaces everything above the core.\n\t\t\t\t\t\tsystemPrompt: composeSubagentSystemPrompt({\n\t\t\t\t\t\t\tsoul: laneProfile?.soul,\n\t\t\t\t\t\t\trolePrompt: systemPrompt,\n\t\t\t\t\t\t\toverride: settings.systemPrompt,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tthinkingLevel: laneProfile?.thinking ?? \"off\",\n\t\t\t\t\t\tmaxTokens: laneCapability.laneMaxOutputTokens,\n\t\t\t\t\t\ttools: toolSurface.tools,\n\t\t\t\t\t\tmaxTurns: 6,\n\t\t\t\t\t\tbeforeToolCall: toolSurface.beforeToolCall,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t// Core/soul/role are all static per configuration — the provider can cache the prefix.\n\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t});\n\t\t\t\t\tspentUsage = completion.usage;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttext: completion.text,\n\t\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t});\n\n\t\t\t// Bug #21 pattern: if the session was disposed while the completion was in flight, do NOT\n\t\t\t// persist evidence/records/usage against the dead session.\n\t\t\tif (this.deps.isDisposed()) {\n\t\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\t\tstatus: \"canceled\",\n\t\t\t\t\treasonCode: \"session_disposed\",\n\t\t\t\t});\n\t\t\t\treturn { started: true, record, result };\n\t\t\t}\n\n\t\t\tlet evidenceEntryId: string | undefined;\n\t\t\tif (result.bundle) {\n\t\t\t\tevidenceEntryId = this.deps.saveEvidenceBundleSnapshot(result.bundle);\n\t\t\t}\n\t\t\tif (spentUsage && (spentUsage.cost.total > 0 || spentUsage.totalTokens > 0)) {\n\t\t\t\tthis.deps.addSpawnedUsage(spentUsage, {\n\t\t\t\t\tlabel: \"research-lane\",\n\t\t\t\t\treportId: `research:${this.deps.getSessionId()}:${startedRecord.laneId}`,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\tstatus: result.status,\n\t\t\t\treasonCode: result.reasonCode,\n\t\t\t\tcostUsd: result.costUsd,\n\t\t\t\tevidenceEntryId,\n\t\t\t});\n\t\t\tif (record) {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), record);\n\t\t\t\t// G3: a research lane's product is an evidence bundle, so its terminal record maps to\n\t\t\t\t// the evidence_bundle event. Lane outcome only (status/reasonCode/cost) — no findings text.\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.evidenceBundle,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tlaneId: record.laneId,\n\t\t\t\t\t\tlaneType: record.type,\n\t\t\t\t\t\tstatus: record.status,\n\t\t\t\t\t\treasonCode: record.reasonCode ?? null,\n\t\t\t\t\t\tcostUsd: record.costUsd ?? null,\n\t\t\t\t\t\thasEvidence: record.evidenceEntryId !== undefined,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn { started: true, record, result };\n\t\t} catch (error) {\n\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\treasonCode: \"research_lane_error\",\n\t\t\t});\n\t\t\tif (record && !this.deps.isDisposed()) {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), record);\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.evidenceBundle,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tlaneId: record.laneId,\n\t\t\t\t\t\tlaneType: record.type,\n\t\t\t\t\t\tstatus: record.status,\n\t\t\t\t\t\treasonCode: record.reasonCode ?? null,\n\t\t\t\t\t\tcostUsd: record.costUsd ?? null,\n\t\t\t\t\t\thasEvidence: record.evidenceEntryId !== undefined,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Research lane failed: ${message}` });\n\t\t\treturn { started: true, record };\n\t\t} finally {\n\t\t\tthis._isResearchLaneRunning = false;\n\t\t}\n\t}\n\n\t/**\n\t * Run one bounded scout-worker delegation: build a WorkerRequest with a stripped read-only\n\t * envelope, execute it as an isolated completion on a cheap lane, validate the result via\n\t * {@link validateWorkerResult} before acceptance, and persist result + lane record + spawned\n\t * usage (idempotent per-lane reportId). Consumed by the `delegate` tool.\n\t */\n\tstartWorkerDelegation(request: {\n\t\tinstructions: string;\n\t\t/** Model-provided replacement for the worker role prompt (the level-0 core always remains). */\n\t\tsystemPrompt?: string;\n\t\t/** Orchestrator-requested read-only memory access; the lane profile may still deny it. */\n\t\tmemoryRead?: boolean;\n\t}): { started: false; skipReason: string } | { started: true; record: LaneRecord } {\n\t\tconst settings = this.deps.getSettingsManager().getWorkerDelegationSettings();\n\t\tif (this.deps.isDisposed()) return { started: false, skipReason: \"session_disposed\" };\n\t\tif (request.instructions.trim().length === 0) return { started: false, skipReason: \"missing_instructions\" };\n\t\tif (!this.deps.isDelegateToolActive()) return { started: false, skipReason: \"delegate_tool_inactive\" };\n\t\tif (!settings.enabled) return { started: false, skipReason: \"worker_delegation_disabled\" };\n\t\tconst shipment = this._resolveLaneShipment(settings, \"no_worker_model\");\n\t\tif (!shipment.ok) return { started: false, skipReason: shipment.skipReason };\n\t\tif (!this._laneCapabilityProfile(shipment.model).backgroundLanesEnabled) {\n\t\t\treturn { started: false, skipReason: \"model_delegation_unsupported\" };\n\t\t}\n\n\t\tconst foreground = this.deps.getModel();\n\t\tconst contendsWithLocalForeground =\n\t\t\tforeground !== undefined && isLocalExecutionModel(foreground) && isLocalExecutionModel(shipment.model);\n\t\tif (contendsWithLocalForeground) {\n\t\t\tif (\n\t\t\t\tthis._queuedWorkers.size >= 8 ||\n\t\t\t\tthis._laneTracker.getActiveCount(\"worker\") >= settings.maxConcurrent + 8\n\t\t\t) {\n\t\t\t\treturn { started: false, skipReason: \"worker_delegation_queue_full\" };\n\t\t\t}\n\t\t\tconst record = this._laneTracker.enqueue({ type: \"worker\" });\n\t\t\tthis._queuedWorkers.set(record.laneId, request);\n\t\t\tthis._scheduleWorkerNotification();\n\t\t\treturn { started: true, record };\n\t\t}\n\t\tif (this._laneTracker.getRunningCount(\"worker\") >= settings.maxConcurrent) {\n\t\t\treturn { started: false, skipReason: \"worker_delegation_already_running\" };\n\t\t}\n\t\tlet startedRecord: LaneRecord | undefined;\n\t\tconst promise = this.runWorkerDelegationOnce(request, (record) => {\n\t\t\tstartedRecord = record;\n\t\t});\n\t\tif (!startedRecord) {\n\t\t\t// Preparation is synchronous up to the first isolated completion await. A promise that\n\t\t\t// rejected before producing a lane is still observed below, so it cannot become unhandled.\n\t\t\tvoid promise.catch(() => undefined);\n\t\t\treturn { started: false, skipReason: \"worker_not_started\" };\n\t\t}\n\t\tthis._workerPromises.set(startedRecord.laneId, promise);\n\t\tvoid promise.then(\n\t\t\t() => this._workerPromises.delete(startedRecord?.laneId ?? \"\"),\n\t\t\t() => this._workerPromises.delete(startedRecord?.laneId ?? \"\"),\n\t\t);\n\t\treturn { started: true, record: startedRecord };\n\t}\n\n\tasync runWorkerDelegationOnce(\n\t\trequest: {\n\t\t\tinstructions: string;\n\t\t\t/** Model-provided replacement for the worker role prompt (the level-0 core always remains). */\n\t\t\tsystemPrompt?: string;\n\t\t\t/** Orchestrator-requested read-only memory access; the lane profile may still deny it. */\n\t\t\tmemoryRead?: boolean;\n\t\t},\n\t\tonStarted?: (record: LaneRecord) => void,\n\t\texistingRecord?: LaneRecord,\n\t): Promise<WorkerDelegationRunOutcome> {\n\t\tconst delegationSettings = this.deps.getSettingsManager().getWorkerDelegationSettings();\n\t\tconst runningWorkers = this._laneTracker.getRunningCount(\"worker\");\n\t\tif (runningWorkers >= delegationSettings.maxConcurrent) {\n\t\t\treturn { started: false, skipReason: \"worker_delegation_already_running\" };\n\t\t}\n\t\tif (this.deps.isDisposed()) {\n\t\t\treturn { started: false, skipReason: \"session_disposed\" };\n\t\t}\n\t\tconst instructions = request.instructions.trim();\n\t\tif (instructions.length === 0) {\n\t\t\treturn { started: false, skipReason: \"missing_instructions\" };\n\t\t}\n\n\t\tconst settings = delegationSettings;\n\t\tif (!this.deps.isDelegateToolActive()) {\n\t\t\treturn { started: false, skipReason: \"delegate_tool_inactive\" };\n\t\t}\n\t\tif (!settings.enabled) {\n\t\t\treturn { started: false, skipReason: \"worker_delegation_disabled\" };\n\t\t}\n\n\t\tconst shipment = this._resolveLaneShipment(settings, \"no_worker_model\");\n\t\tif (!shipment.ok) {\n\t\t\treturn { started: false, skipReason: shipment.skipReason };\n\t\t}\n\t\tconst { model, laneProfile } = shipment;\n\t\tconst laneCapability = this._laneCapabilityProfile(model);\n\t\tif (!laneCapability.backgroundLanesEnabled) {\n\t\t\treturn { started: false, skipReason: \"model_delegation_unsupported\" };\n\t\t}\n\n\t\tthis._seedLaneHistory();\n\t\tconst startedRecord = existingRecord ?? this._laneTracker.start({ type: \"worker\" });\n\t\tif (existingRecord) this._laneTracker.markRunning(existingRecord.laneId);\n\t\tonStarted?.(startedRecord);\n\t\tconst maxUsd = Math.min(\n\t\t\tsettings.maxUsd,\n\t\t\tthis.deps.getCapabilityEnvelope()?.maxEstimatedUsd ?? Number.POSITIVE_INFINITY,\n\t\t);\n\t\tconst writeEnabled = settings.writeEnabled && settings.writePaths.length > 0;\n\t\tconst toolSurface = createLaneToolSurface({\n\t\t\tcwd: this.deps.getCwd(),\n\t\t\tprofile: laneProfile,\n\t\t\tdeniedPaths: getPrivateLaneDeniedPaths(this.deps.getCwd(), this.deps.getAgentDir()),\n\t\t\treadMemory: request.memoryRead ? (query) => this.deps.readMemoryForLane(query) : undefined,\n\t\t\twriteEnabled,\n\t\t\twritePaths: settings.writePaths,\n\t\t});\n\t\tthis._warnUnboundLaneToolGrants(laneProfile, toolSurface);\n\t\tconst allowedActionOps = new Set<WorkerAction[\"op\"]>(\n\t\t\ttoolSurface.allowedTools.filter((name): name is WorkerAction[\"op\"] => name === \"write\" || name === \"edit\"),\n\t\t);\n\t\tconst writeGranted = writeEnabled && allowedActionOps.size > 0;\n\t\tconst memoryReadGranted = request.memoryRead === true && toolSurface.allowedTools.includes(\"memory\");\n\t\tconst workerRequest: WorkerRequest = {\n\t\t\tid: startedRecord.laneId,\n\t\t\tinstructions,\n\t\t\troute: {\n\t\t\t\ttier: \"cheap\",\n\t\t\t\trisk: writeGranted ? \"scoped-write\" : \"read-only\",\n\t\t\t\tconfidence: 1,\n\t\t\t\treasonCode: \"scout_worker\",\n\t\t\t\treasons: [writeGranted ? \"Path-scoped worker delegation\" : \"Read-only scout delegation\"],\n\t\t\t},\n\t\t\tenvelope: {\n\t\t\t\tid: `worker-${this.deps.getSessionId()}-${startedRecord.laneId}`,\n\t\t\t\tprofileId: laneProfile?.name,\n\t\t\t\t// write_files requires BOTH the opt-in AND an explicit non-empty path scope —\n\t\t\t\t// an unscoped write grant is refused here, not discovered at validation time.\n\t\t\t\tcapabilities: [\n\t\t\t\t\t\"read_files\",\n\t\t\t\t\t...(memoryReadGranted ? ([\"memory_read\"] as const) : []),\n\t\t\t\t\t...(writeGranted ? ([\"write_files\"] as const) : []),\n\t\t\t\t],\n\t\t\t\t...(writeGranted ? { allowedPaths: [...settings.writePaths] } : {}),\n\t\t\t\tdeniedPaths: getPrivateLaneDeniedPaths(this.deps.getCwd(), this.deps.getAgentDir()),\n\t\t\t\tallowedTools: [...toolSurface.allowedTools],\n\t\t\t\tdeniedTools: [...toolSurface.deniedTools],\n\t\t\t\tmaxEstimatedUsd: maxUsd,\n\t\t\t\tcreatedAt: new Date().toISOString(),\n\t\t\t},\n\t\t\tmaxEstimatedUsd: maxUsd,\n\t\t\tcreatedAt: new Date().toISOString(),\n\t\t};\n\t\t// G8: worker delegation START. Routing/scope codes + budget only — never the instructions text.\n\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.workerRequest,\n\t\t\ttimestamp: new Date().toISOString(),\n\t\t\tpayload: {\n\t\t\t\tid: workerRequest.id,\n\t\t\t\ttier: workerRequest.route.tier,\n\t\t\t\tcapabilities: [...workerRequest.envelope.capabilities],\n\t\t\t\tmaxEstimatedUsd: workerRequest.maxEstimatedUsd ?? null,\n\t\t\t},\n\t\t});\n\t\tconst usageReportId = `worker:${this.deps.getSessionId()}:${startedRecord.laneId}`;\n\n\t\ttry {\n\t\t\tlet spentUsage: Usage | undefined;\n\t\t\tconst toolChangedFiles = new Set<string>();\n\t\t\tconst toolIssues = new Set<string>();\n\t\t\tconst outcome = await runWorker({\n\t\t\t\trequest: workerRequest,\n\t\t\t\tmaxUsd,\n\t\t\t\tmaxWallClockMs: settings.maxWallClockMs,\n\t\t\t\tusageReportId,\n\t\t\t\tgetChangedFiles: () => [...toolChangedFiles],\n\t\t\t\tsignal: this._workerDelegationAbort.signal,\n\t\t\t\t// Parent validation must use the same relative-path baseline the runner reports in.\n\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\t// Write lane (G2): runner-side action application through the envelope path scope.\n\t\t\t\tapplyActions: workerRequest.envelope.capabilities.includes(\"write_files\")\n\t\t\t\t\t? (actions) => {\n\t\t\t\t\t\t\tconst permitted = actions.filter((action) => allowedActionOps.has(action.op));\n\t\t\t\t\t\t\tconst applied = applyWorkerActions({\n\t\t\t\t\t\t\t\tactions: permitted,\n\t\t\t\t\t\t\t\tenvelope: workerRequest.envelope,\n\t\t\t\t\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t...applied,\n\t\t\t\t\t\t\t\trefused: [\n\t\t\t\t\t\t\t\t\t...actions\n\t\t\t\t\t\t\t\t\t\t.filter((action) => !allowedActionOps.has(action.op))\n\t\t\t\t\t\t\t\t\t\t.map((action) => ({\n\t\t\t\t\t\t\t\t\t\t\tpath: action.path,\n\t\t\t\t\t\t\t\t\t\t\treason: `${action.op} is not granted by the lane profile`,\n\t\t\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t\t\t...applied.refused,\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\t\t// Level-0 core always survives. A model-provided prompt (delegate tool) is the most\n\t\t\t\t\t\t// specific override, then the settings-level prompt, then profile soul + role prompt.\n\t\t\t\t\t\tsystemPrompt: composeSubagentSystemPrompt({\n\t\t\t\t\t\t\tsoul: laneProfile?.soul,\n\t\t\t\t\t\t\trolePrompt: systemPrompt,\n\t\t\t\t\t\t\toverride: request.systemPrompt ?? settings.systemPrompt,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tthinkingLevel: laneProfile?.thinking ?? \"off\",\n\t\t\t\t\t\tmaxTokens: laneCapability.laneMaxOutputTokens,\n\t\t\t\t\t\ttools: toolSurface.tools,\n\t\t\t\t\t\tmaxTurns: 6,\n\t\t\t\t\t\tbeforeToolCall: async (context, toolSignal) => {\n\t\t\t\t\t\t\tconst decision = await toolSurface.beforeToolCall(context, toolSignal);\n\t\t\t\t\t\t\tif (decision?.block) {\n\t\t\t\t\t\t\t\ttoolIssues.add(`${context.toolCall.name} blocked: ${decision.reason ?? \"capability denied\"}`);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn decision;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tafterToolCall: async ({ toolCall, args, isError }) => {\n\t\t\t\t\t\t\t// This hook runs only for a validated, gate-approved tool that actually entered\n\t\t\t\t\t\t\t// execution. Record a direct mutation target before inspecting `isError`: write/edit\n\t\t\t\t\t\t\t// may have changed disk and then observed cancellation, timeout, or a late I/O error.\n\t\t\t\t\t\t\t// Pre-gate/profile/path refusals never reach afterToolCall, so they remain unreported.\n\t\t\t\t\t\t\tif (toolCall.name === \"write\" || toolCall.name === \"edit\") {\n\t\t\t\t\t\t\t\tif (args && typeof args === \"object\" && !Array.isArray(args)) {\n\t\t\t\t\t\t\t\t\tconst rawPath = (args as Record<string, unknown>).path;\n\t\t\t\t\t\t\t\t\tif (typeof rawPath === \"string\" && rawPath.length > 0) {\n\t\t\t\t\t\t\t\t\t\tconst absolutePath = path.isAbsolute(rawPath)\n\t\t\t\t\t\t\t\t\t\t\t? path.resolve(rawPath)\n\t\t\t\t\t\t\t\t\t\t\t: path.resolve(this.deps.getCwd(), rawPath);\n\t\t\t\t\t\t\t\t\t\tlet canonicalPath = absolutePath;\n\t\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\t\tcanonicalPath = safeRealpathSync(absolutePath);\n\t\t\t\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t\t\t\t// Execution was attempted; preserve conservative accounting with the lexical path.\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\ttoolChangedFiles.add(path.relative(this.deps.getCwd(), canonicalPath));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (isError) {\n\t\t\t\t\t\t\t\ttoolIssues.add(`${toolCall.name} failed during isolated execution`);\n\t\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t},\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t// Core/soul/role are all static per configuration — the provider can cache the prefix.\n\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t});\n\t\t\t\t\tspentUsage = completion.usage;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttext: completion.text,\n\t\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t\t\tchangedFiles: [...toolChangedFiles],\n\t\t\t\t\t\tblockers: [...toolIssues],\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t});\n\n\t\t\t// Bug #21 pattern: never persist against a disposed session.\n\t\t\tif (this.deps.isDisposed()) {\n\t\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\t\tstatus: \"canceled\",\n\t\t\t\t\treasonCode: \"session_disposed\",\n\t\t\t\t});\n\t\t\t\tif (record) this._recordWorkerTerminal(record);\n\t\t\t\treturn { started: true, record, outcome };\n\t\t\t}\n\n\t\t\tthis.deps.saveWorkerResultSnapshot(outcome.result, workerRequest);\n\t\t\tif (spentUsage && (spentUsage.cost.total > 0 || spentUsage.totalTokens > 0)) {\n\t\t\t\tthis.deps.addSpawnedUsage(spentUsage, { label: \"worker-delegation\", reportId: usageReportId });\n\t\t\t}\n\n\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\tstatus: outcome.laneStatus,\n\t\t\t\treasonCode: outcome.reasonCode,\n\t\t\t\tcostUsd: outcome.costUsd,\n\t\t\t});\n\t\t\tif (record) {\n\t\t\t\tthis._recordWorkerTerminal(record);\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), record);\n\t\t\t\t// G3: worker lane terminal record -> worker_result event. Lane outcome only\n\t\t\t\t// (status/reasonCode/cost) — never the worker's summary/changed-file text.\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.workerResult,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tlaneId: record.laneId,\n\t\t\t\t\t\tlaneType: record.type,\n\t\t\t\t\t\tstatus: record.status,\n\t\t\t\t\t\treasonCode: record.reasonCode ?? null,\n\t\t\t\t\t\tcostUsd: record.costUsd ?? null,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn { started: true, record, outcome };\n\t\t} catch (error) {\n\t\t\tconst record = this._laneTracker.complete(startedRecord.laneId, {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\treasonCode: \"worker_delegation_error\",\n\t\t\t});\n\t\t\tif (record) this._recordWorkerTerminal(record);\n\t\t\tif (record && !this.deps.isDisposed()) {\n\t\t\t\tappendLaneRecordSnapshot(this.deps.getSessionManager(), record);\n\t\t\t\tthis.deps.emitAutonomyTelemetry({\n\t\t\t\t\ttype: AUTONOMY_TELEMETRY_EVENT_TYPES.workerResult,\n\t\t\t\t\ttimestamp: new Date().toISOString(),\n\t\t\t\t\tpayload: {\n\t\t\t\t\t\tlaneId: record.laneId,\n\t\t\t\t\t\tlaneType: record.type,\n\t\t\t\t\t\tstatus: record.status,\n\t\t\t\t\t\treasonCode: record.reasonCode ?? null,\n\t\t\t\t\t\tcostUsd: record.costUsd ?? null,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tthis.deps.emit({ type: \"warning\", message: `Worker delegation failed: ${message}` });\n\t\t\treturn { started: true, record };\n\t\t} finally {\n\t\t}\n\t}\n\n\t/**\n\t * Probe a candidate model against the subagent contracts (research/worker/judge/search/\n\t * tool-call surfaces) via {@link runModelFitnessProbe}. The model must resolve and\n\t * authenticate; every probe call runs as an isolated completion on that model, and probe\n\t * spend is reported through spawned-usage accounting.\n\t */\n\tasync runModelFitness(args: {\n\t\tmodel: string;\n\t\ttrials?: number;\n\t}): Promise<{ started: true; model: string; report: ModelFitnessReport } | { started: false; skipReason: string }> {\n\t\tif (this.deps.isDisposed()) return { started: false, skipReason: \"session_disposed\" };\n\t\tconst resolved = this.resolveLaneModel(args.model.trim() || undefined);\n\t\tif (!resolved) return { started: false, skipReason: \"model_unresolved_or_unauthenticated\" };\n\t\tconst capability = this._laneCapabilityProfile(resolved);\n\n\t\tconst spent: Usage = {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t};\n\t\tconst report = await runModelFitnessProbe({\n\t\t\ttrials: args.trials,\n\t\t\tsignal: this._researchLaneAbort.signal,\n\t\t\tcapacityProbe:\n\t\t\t\tresolved.provider === \"ollama\" && resolved.contextWindow > 0\n\t\t\t\t\t? { registeredContextWindow: resolved.contextWindow }\n\t\t\t\t\t: undefined,\n\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\tconst callStarted = Date.now();\n\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\tsystemPrompt,\n\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\tmodel: resolved,\n\t\t\t\t\tthinkingLevel: \"off\",\n\t\t\t\t\tmaxTokens: capability.laneMaxOutputTokens,\n\t\t\t\t\tsignal,\n\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t});\n\t\t\t\tconst callMs = Date.now() - callStarted;\n\t\t\t\tspent.input += completion.usage.input;\n\t\t\t\tspent.output += completion.usage.output;\n\t\t\t\tspent.cacheRead += completion.usage.cacheRead;\n\t\t\t\tspent.cacheWrite += completion.usage.cacheWrite;\n\t\t\t\tspent.totalTokens += completion.usage.totalTokens;\n\t\t\t\tspent.cost.input += completion.usage.cost.input;\n\t\t\t\tspent.cost.output += completion.usage.cost.output;\n\t\t\t\tspent.cost.cacheRead += completion.usage.cost.cacheRead;\n\t\t\t\tspent.cost.cacheWrite += completion.usage.cost.cacheWrite;\n\t\t\t\tspent.cost.total += completion.usage.cost.total;\n\t\t\t\treturn {\n\t\t\t\t\ttext: completion.text,\n\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t\t// Wall-clock fallback for tok/s: providers don't expose pure eval time, so the\n\t\t\t\t\t// measured call time stands in — slightly conservative (includes network/queue).\n\t\t\t\t\toutputTokens: completion.usage.output,\n\t\t\t\t\tevalMs: callMs,\n\t\t\t\t};\n\t\t\t},\n\t\t});\n\t\tif (!this.deps.isDisposed() && (spent.cost.total > 0 || spent.totalTokens > 0)) {\n\t\t\tthis.deps.addSpawnedUsage(spent, { label: \"model-fitness\" });\n\t\t}\n\t\tconst modelRef = `${resolved.provider}/${resolved.id}`;\n\t\t// Fitness is a property of a model ON a host — persist the report host-keyed so role\n\t\t// assignments stay per-machine (a model can await better hardware without being forgotten).\n\t\t// Best-effort: a disk problem must not fail the probe itself.\n\t\ttry {\n\t\t\tif (!this.deps.isDisposed()) {\n\t\t\t\tFitnessStore.forAgentDir(this.deps.getAgentDir()).save(modelRef, report);\n\t\t\t}\n\t\t} catch {\n\t\t\t// best-effort persistence\n\t\t}\n\t\treturn { started: true, model: modelRef, report };\n\t}\n\n\t/** Start queued local workers at the owner session's foreground-idle boundary. */\n\tdrainQueuedWorkerDelegations(): void {\n\t\tfor (const [laneId, request] of [...this._queuedWorkers]) {\n\t\t\tif (\n\t\t\t\tthis._laneTracker.getRunningCount(\"worker\") >=\n\t\t\t\tthis.deps.getSettingsManager().getWorkerDelegationSettings().maxConcurrent\n\t\t\t)\n\t\t\t\tbreak;\n\t\t\tconst record = this._laneTracker.getRecords().find((candidate) => candidate.laneId === laneId);\n\t\t\tif (!record) {\n\t\t\t\tthis._queuedWorkers.delete(laneId);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis._queuedWorkers.delete(laneId);\n\t\t\tconst promise = this.runWorkerDelegationOnce(request, undefined, record);\n\t\t\tthis._workerPromises.set(laneId, promise);\n\t\t\tvoid promise.then(\n\t\t\t\t(outcome) => {\n\t\t\t\t\tif (!outcome.started) {\n\t\t\t\t\t\tconst terminal = this._laneTracker.complete(laneId, {\n\t\t\t\t\t\t\tstatus: \"canceled\",\n\t\t\t\t\t\t\treasonCode: outcome.skipReason,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (terminal) this._recordWorkerTerminal(terminal);\n\t\t\t\t\t}\n\t\t\t\t\tthis._workerPromises.delete(laneId);\n\t\t\t\t\tif (!this.deps.isDisposed()) this.drainQueuedWorkerDelegations();\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tconst terminal = this._laneTracker.complete(laneId, {\n\t\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\t\treasonCode: \"worker_background_error\",\n\t\t\t\t\t});\n\t\t\t\t\tif (terminal) this._recordWorkerTerminal(terminal);\n\t\t\t\t\tthis._workerPromises.delete(laneId);\n\t\t\t\t\tif (!this.deps.isDisposed()) this.drainQueuedWorkerDelegations();\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t}\n\n\t/** Fitness reports persisted for THIS host (measured evidence for architect/profile decisions). */\n\tgetStoredFitnessReports(): StoredFitnessReport[] {\n\t\ttry {\n\t\t\treturn FitnessStore.forAgentDir(this.deps.getAgentDir()).getForHost();\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n}\n"]}
@@ -31,6 +31,34 @@ import { runResearch } from "./research/research-runner.js";
31
31
  export function clampLaneMaxUsd(settingsMaxUsd, foregroundMaxEstimatedUsd) {
32
32
  return Math.min(settingsMaxUsd, foregroundMaxEstimatedUsd ?? Number.POSITIVE_INFINITY);
33
33
  }
34
+ export function getPrivateLaneDeniedPaths(cwd, agentDir) {
35
+ return [
36
+ "auth.json",
37
+ "MEMORY.md",
38
+ "USER.md",
39
+ "settings.json",
40
+ "models.json",
41
+ "trust.json",
42
+ "sessions",
43
+ "state",
44
+ "context-artifacts",
45
+ "context-gc",
46
+ ]
47
+ .map((entry) => path.join(agentDir, entry))
48
+ .concat(path.join(cwd, ".pi", "settings.json"));
49
+ }
50
+ export function isLocalExecutionModel(model) {
51
+ if (model.provider === "ollama" || model.provider === "transformers" || model.provider === "llama-cpp") {
52
+ return true;
53
+ }
54
+ try {
55
+ const hostname = new URL(model.baseUrl).hostname.toLowerCase();
56
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "[::1]";
57
+ }
58
+ catch {
59
+ return false;
60
+ }
61
+ }
34
62
  export class BackgroundLaneController {
35
63
  /** Pending idle timer that starts bounded goal continuation after the session becomes idle. */
36
64
  _goalAutoContinueTimer;
@@ -44,6 +72,8 @@ export class BackgroundLaneController {
44
72
  _lastResearchLaneSkipReason;
45
73
  /** Live lane registry — the real source for AutonomyStatusSnapshot.activeLaneCount. */
46
74
  _laneTracker = new LaneTracker();
75
+ _laneHistorySeeded = false;
76
+ _persistedResearchRunCount = 0;
47
77
  /** Session-lifetime abort for in-flight research passes (same pattern as _reflectionAbort). */
48
78
  _researchLaneAbort = new AbortController();
49
79
  /** Session-lifetime abort for in-flight delegated workers. */
@@ -56,32 +86,58 @@ export class BackgroundLaneController {
56
86
  _workerNotificationTimer;
57
87
  _workersCompletedSinceFlush = 0;
58
88
  _workersFailedSinceFlush = 0;
89
+ _workerTerminalSinceFlush = [];
59
90
  deps;
60
91
  _scheduleWorkerNotification() {
61
92
  if (this._workerNotificationTimer !== undefined)
62
93
  return;
63
94
  this._workerNotificationTimer = setTimeout(() => {
64
95
  this._workerNotificationTimer = undefined;
96
+ const queued = this._laneTracker
97
+ .getRecords()
98
+ .filter((record) => record.type === "worker" && record.status === "queued").length;
99
+ const running = this._laneTracker.getRunningCount("worker");
65
100
  this.deps.emit({
66
101
  type: "delegate_workers",
67
- active: this._laneTracker.getActiveCount("worker"),
102
+ active: queued + running,
103
+ queued,
104
+ running,
68
105
  completedSinceFlush: this._workersCompletedSinceFlush,
69
106
  failedSinceFlush: this._workersFailedSinceFlush,
107
+ terminalSinceFlush: this._workerTerminalSinceFlush.splice(0),
70
108
  });
71
109
  this._workersCompletedSinceFlush = 0;
72
110
  this._workersFailedSinceFlush = 0;
73
111
  }, 75);
112
+ const timer = this._workerNotificationTimer;
113
+ if (typeof timer === "object" && timer && "unref" in timer)
114
+ timer.unref();
74
115
  }
75
- _recordWorkerTerminal(status) {
76
- if (status === "succeeded")
116
+ _recordWorkerTerminal(record) {
117
+ if (record.status === "queued" || record.status === "running")
118
+ return;
119
+ if (record.status === "succeeded")
77
120
  this._workersCompletedSinceFlush++;
78
121
  else
79
122
  this._workersFailedSinceFlush++;
123
+ this._workerTerminalSinceFlush.push({
124
+ laneId: record.laneId,
125
+ status: record.status,
126
+ ...(record.reasonCode ? { reasonCode: record.reasonCode } : {}),
127
+ });
80
128
  this._scheduleWorkerNotification();
81
129
  }
82
130
  constructor(deps) {
83
131
  this.deps = deps;
84
132
  }
133
+ _seedLaneHistory() {
134
+ if (this._laneHistorySeeded)
135
+ return;
136
+ const records = getLaneRecordSnapshots(this.deps.getSessionManager().getEntries());
137
+ this._laneTracker.ensureCounterAtLeast(records.length + 1);
138
+ this._persistedResearchRunCount = records.filter((record) => record.type === "research").length;
139
+ this._laneHistorySeeded = true;
140
+ }
85
141
  /** Live lane records tracked by this process (running and terminal). */
86
142
  getLaneRecords() {
87
143
  return this._laneTracker.getRecords();
@@ -98,6 +154,10 @@ export class BackgroundLaneController {
98
154
  abortInFlightLanes() {
99
155
  this._researchLaneAbort.abort();
100
156
  this._workerDelegationAbort.abort();
157
+ if (this._workerNotificationTimer !== undefined) {
158
+ clearTimeout(this._workerNotificationTimer);
159
+ this._workerNotificationTimer = undefined;
160
+ }
101
161
  }
102
162
  clearGoalAutoContinueTimer() {
103
163
  if (this._goalAutoContinueTimer !== undefined) {
@@ -217,8 +277,8 @@ export class BackgroundLaneController {
217
277
  this._lastResearchLaneSkipReason = "autonomy_mode_off";
218
278
  return;
219
279
  }
220
- const priorRuns = getLaneRecordSnapshots(this.deps.getSessionManager().getEntries()).filter((record) => record.type === "research").length;
221
- if (priorRuns >= research.maxRunsPerSession) {
280
+ this._seedLaneHistory();
281
+ if (this._persistedResearchRunCount >= research.maxRunsPerSession) {
222
282
  this._lastResearchLaneSkipReason = "max_runs_reached";
223
283
  return;
224
284
  }
@@ -342,6 +402,7 @@ export class BackgroundLaneController {
342
402
  allowedTools: [...surface.allowedTools],
343
403
  deniedTools: [...surface.deniedTools],
344
404
  allowedPaths: [this.deps.getCwd()],
405
+ deniedPaths: getPrivateLaneDeniedPaths(this.deps.getCwd(), this.deps.getAgentDir()),
345
406
  maxEstimatedUsd: clampLaneMaxUsd(maxUsd, this.deps.getCapabilityEnvelope()?.maxEstimatedUsd),
346
407
  createdAt: new Date().toISOString(),
347
408
  };
@@ -378,8 +439,9 @@ export class BackgroundLaneController {
378
439
  return { started: false, skipReason: "model_research_unsupported" };
379
440
  }
380
441
  this._isResearchLaneRunning = true;
381
- this._laneTracker.ensureCounterAtLeast(getLaneRecordSnapshots(this.deps.getSessionManager().getEntries()).length + 1);
442
+ this._seedLaneHistory();
382
443
  const startedRecord = this._laneTracker.start({ type: "research", goalId: demand.goalId });
444
+ this._persistedResearchRunCount++;
383
445
  try {
384
446
  let spentUsage;
385
447
  // Best-effort, pointer-first workspace evidence. Derives search terms from the goal/requirement
@@ -390,7 +452,11 @@ export class BackgroundLaneController {
390
452
  maxSources: settings.maxSources,
391
453
  });
392
454
  const maxUsd = clampLaneMaxUsd(settings.maxUsd, this.deps.getCapabilityEnvelope()?.maxEstimatedUsd);
393
- const toolSurface = createLaneToolSurface({ cwd: this.deps.getCwd(), profile: laneProfile });
455
+ const toolSurface = createLaneToolSurface({
456
+ cwd: this.deps.getCwd(),
457
+ profile: laneProfile,
458
+ deniedPaths: getPrivateLaneDeniedPaths(this.deps.getCwd(), this.deps.getAgentDir()),
459
+ });
394
460
  this._warnUnboundLaneToolGrants(laneProfile, toolSurface);
395
461
  const result = await runResearch({
396
462
  query: demand.query,
@@ -510,9 +576,23 @@ export class BackgroundLaneController {
510
576
  */
511
577
  startWorkerDelegation(request) {
512
578
  const settings = this.deps.getSettingsManager().getWorkerDelegationSettings();
579
+ if (this.deps.isDisposed())
580
+ return { started: false, skipReason: "session_disposed" };
581
+ if (request.instructions.trim().length === 0)
582
+ return { started: false, skipReason: "missing_instructions" };
583
+ if (!this.deps.isDelegateToolActive())
584
+ return { started: false, skipReason: "delegate_tool_inactive" };
585
+ if (!settings.enabled)
586
+ return { started: false, skipReason: "worker_delegation_disabled" };
587
+ const shipment = this._resolveLaneShipment(settings, "no_worker_model");
588
+ if (!shipment.ok)
589
+ return { started: false, skipReason: shipment.skipReason };
590
+ if (!this._laneCapabilityProfile(shipment.model).backgroundLanesEnabled) {
591
+ return { started: false, skipReason: "model_delegation_unsupported" };
592
+ }
513
593
  const foreground = this.deps.getModel();
514
- const managedLocal = foreground?.provider === "ollama" || foreground?.provider === "transformers";
515
- if (managedLocal) {
594
+ const contendsWithLocalForeground = foreground !== undefined && isLocalExecutionModel(foreground) && isLocalExecutionModel(shipment.model);
595
+ if (contendsWithLocalForeground) {
516
596
  if (this._queuedWorkers.size >= 8 ||
517
597
  this._laneTracker.getActiveCount("worker") >= settings.maxConcurrent + 8) {
518
598
  return { started: false, skipReason: "worker_delegation_queue_full" };
@@ -522,6 +602,9 @@ export class BackgroundLaneController {
522
602
  this._scheduleWorkerNotification();
523
603
  return { started: true, record };
524
604
  }
605
+ if (this._laneTracker.getRunningCount("worker") >= settings.maxConcurrent) {
606
+ return { started: false, skipReason: "worker_delegation_already_running" };
607
+ }
525
608
  let startedRecord;
526
609
  const promise = this.runWorkerDelegationOnce(request, (record) => {
527
610
  startedRecord = record;
@@ -538,8 +621,8 @@ export class BackgroundLaneController {
538
621
  }
539
622
  async runWorkerDelegationOnce(request, onStarted, existingRecord) {
540
623
  const delegationSettings = this.deps.getSettingsManager().getWorkerDelegationSettings();
541
- const activeWorkers = this._laneTracker.getActiveCount("worker") - (existingRecord ? 1 : 0);
542
- if (activeWorkers >= delegationSettings.maxConcurrent) {
624
+ const runningWorkers = this._laneTracker.getRunningCount("worker");
625
+ if (runningWorkers >= delegationSettings.maxConcurrent) {
543
626
  return { started: false, skipReason: "worker_delegation_already_running" };
544
627
  }
545
628
  if (this.deps.isDisposed()) {
@@ -565,7 +648,7 @@ export class BackgroundLaneController {
565
648
  if (!laneCapability.backgroundLanesEnabled) {
566
649
  return { started: false, skipReason: "model_delegation_unsupported" };
567
650
  }
568
- this._laneTracker.ensureCounterAtLeast(getLaneRecordSnapshots(this.deps.getSessionManager().getEntries()).length + 1);
651
+ this._seedLaneHistory();
569
652
  const startedRecord = existingRecord ?? this._laneTracker.start({ type: "worker" });
570
653
  if (existingRecord)
571
654
  this._laneTracker.markRunning(existingRecord.laneId);
@@ -575,12 +658,15 @@ export class BackgroundLaneController {
575
658
  const toolSurface = createLaneToolSurface({
576
659
  cwd: this.deps.getCwd(),
577
660
  profile: laneProfile,
661
+ deniedPaths: getPrivateLaneDeniedPaths(this.deps.getCwd(), this.deps.getAgentDir()),
662
+ readMemory: request.memoryRead ? (query) => this.deps.readMemoryForLane(query) : undefined,
578
663
  writeEnabled,
579
664
  writePaths: settings.writePaths,
580
665
  });
581
666
  this._warnUnboundLaneToolGrants(laneProfile, toolSurface);
582
667
  const allowedActionOps = new Set(toolSurface.allowedTools.filter((name) => name === "write" || name === "edit"));
583
668
  const writeGranted = writeEnabled && allowedActionOps.size > 0;
669
+ const memoryReadGranted = request.memoryRead === true && toolSurface.allowedTools.includes("memory");
584
670
  const workerRequest = {
585
671
  id: startedRecord.laneId,
586
672
  instructions,
@@ -596,8 +682,13 @@ export class BackgroundLaneController {
596
682
  profileId: laneProfile?.name,
597
683
  // write_files requires BOTH the opt-in AND an explicit non-empty path scope —
598
684
  // an unscoped write grant is refused here, not discovered at validation time.
599
- capabilities: writeGranted ? ["read_files", "write_files"] : ["read_files"],
685
+ capabilities: [
686
+ "read_files",
687
+ ...(memoryReadGranted ? ["memory_read"] : []),
688
+ ...(writeGranted ? ["write_files"] : []),
689
+ ],
600
690
  ...(writeGranted ? { allowedPaths: [...settings.writePaths] } : {}),
691
+ deniedPaths: getPrivateLaneDeniedPaths(this.deps.getCwd(), this.deps.getAgentDir()),
601
692
  allowedTools: [...toolSurface.allowedTools],
602
693
  deniedTools: [...toolSurface.deniedTools],
603
694
  maxEstimatedUsd: maxUsd,
@@ -726,7 +817,7 @@ export class BackgroundLaneController {
726
817
  reasonCode: "session_disposed",
727
818
  });
728
819
  if (record)
729
- this._recordWorkerTerminal(record.status);
820
+ this._recordWorkerTerminal(record);
730
821
  return { started: true, record, outcome };
731
822
  }
732
823
  this.deps.saveWorkerResultSnapshot(outcome.result, workerRequest);
@@ -739,7 +830,7 @@ export class BackgroundLaneController {
739
830
  costUsd: outcome.costUsd,
740
831
  });
741
832
  if (record) {
742
- this._recordWorkerTerminal(record.status);
833
+ this._recordWorkerTerminal(record);
743
834
  appendLaneRecordSnapshot(this.deps.getSessionManager(), record);
744
835
  // G3: worker lane terminal record -> worker_result event. Lane outcome only
745
836
  // (status/reasonCode/cost) — never the worker's summary/changed-file text.
@@ -763,7 +854,7 @@ export class BackgroundLaneController {
763
854
  reasonCode: "worker_delegation_error",
764
855
  });
765
856
  if (record)
766
- this._recordWorkerTerminal(record.status);
857
+ this._recordWorkerTerminal(record);
767
858
  if (record && !this.deps.isDisposed()) {
768
859
  appendLaneRecordSnapshot(this.deps.getSessionManager(), record);
769
860
  this.deps.emitAutonomyTelemetry({
@@ -865,7 +956,7 @@ export class BackgroundLaneController {
865
956
  /** Start queued local workers at the owner session's foreground-idle boundary. */
866
957
  drainQueuedWorkerDelegations() {
867
958
  for (const [laneId, request] of [...this._queuedWorkers]) {
868
- if (this._laneTracker.getActiveCount("worker") >
959
+ if (this._laneTracker.getRunningCount("worker") >=
869
960
  this.deps.getSettingsManager().getWorkerDelegationSettings().maxConcurrent)
870
961
  break;
871
962
  const record = this._laneTracker.getRecords().find((candidate) => candidate.laneId === laneId);
@@ -883,17 +974,21 @@ export class BackgroundLaneController {
883
974
  reasonCode: outcome.skipReason,
884
975
  });
885
976
  if (terminal)
886
- this._recordWorkerTerminal(terminal.status);
977
+ this._recordWorkerTerminal(terminal);
887
978
  }
888
979
  this._workerPromises.delete(laneId);
980
+ if (!this.deps.isDisposed())
981
+ this.drainQueuedWorkerDelegations();
889
982
  }, () => {
890
983
  const terminal = this._laneTracker.complete(laneId, {
891
984
  status: "failed",
892
985
  reasonCode: "worker_background_error",
893
986
  });
894
987
  if (terminal)
895
- this._recordWorkerTerminal(terminal.status);
988
+ this._recordWorkerTerminal(terminal);
896
989
  this._workerPromises.delete(laneId);
990
+ if (!this.deps.isDisposed())
991
+ this.drainQueuedWorkerDelegations();
897
992
  });
898
993
  }
899
994
  }