claude-code-session-manager 0.111.0 → 0.112.0
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.
- package/.claude-plugin/marketplace.json +2 -2
- package/dist/assets/{AgentLibrary-rBO1daqM.js → AgentLibrary-RwPvEgqm.js} +2 -2
- package/dist/assets/{Button-DsEYRZg0.js → Button-36j3PzYv.js} +1 -1
- package/dist/assets/{DataModel-D8sbvvBC.js → DataModel-DUhANo4l.js} +1 -1
- package/dist/assets/{History-BEHLtxia.js → History-BeZzNjmv.js} +2 -2
- package/dist/assets/{Hooks-CKpvlXrg.js → Hooks-iQ8845Hp.js} +3 -3
- package/dist/assets/{Library-CeF4qh9d.js → Library-DPE1h-1L.js} +6 -6
- package/dist/assets/{ListDetail-DcfmxPFk.js → ListDetail-PStOuQAo.js} +1 -1
- package/dist/assets/{MarkdownEditor-CvK1pyto.js → MarkdownEditor-DPw-N2-m.js} +1 -1
- package/dist/assets/{McpServers-D-h2ihzJ.js → McpServers-CUyRTNep.js} +2 -2
- package/dist/assets/{Memory-BnF89x8v.js → Memory-bZ2xjBGy.js} +3 -3
- package/dist/assets/{Panel-CQY5zano.js → Panel-_VZ_uXNg.js} +1 -1
- package/dist/assets/{Permissions-DLukmmsz.js → Permissions-PPRmfNbK.js} +3 -3
- package/dist/assets/{Plugins-0Pf0OZ4l.js → Plugins-BFcvfvlx.js} +2 -2
- package/dist/assets/{ProvenanceBadge-vC7Tj-JP.js → ProvenanceBadge-B1WUknak.js} +1 -1
- package/dist/assets/RemoteMachines-D5V0lzgW.js +3 -0
- package/dist/assets/{SaveBar-DjijiUb0.js → SaveBar-Dw64FVdM.js} +1 -1
- package/dist/assets/{Scheduler-Cm3EXZvE.js → Scheduler-C8s_pJ3I.js} +9 -9
- package/dist/assets/{ScopeSwitcher-B-P-kSfq.js → ScopeSwitcher-D-nKDMAE.js} +1 -1
- package/dist/assets/{Settings-DYDlp2m_.js → Settings-CQSrR4mO.js} +4 -4
- package/dist/assets/{SkillReferenceGraph-Epv2GJmj.js → SkillReferenceGraph-BbZFMHim.js} +1 -1
- package/dist/assets/{Skills-DHO0N0C2.js → Skills-Bzyrh6EQ.js} +1 -1
- package/dist/assets/SystemPrompt-DP6i3Dx0.js +1 -0
- package/dist/assets/TagLibrary-iip0C6Bl.js +1 -0
- package/dist/assets/{TiptapBody-DAMO3DhO.js → TiptapBody-Cr-hxX8L.js} +1 -1
- package/dist/assets/Toggle-7WpPzcZH.js +1 -0
- package/dist/assets/{ViewTabs-CGX6MAhc.js → ViewTabs-9lQCRwWJ.js} +1 -1
- package/dist/assets/{historyTotals-vgfk8EOL.js → historyTotals-BrFxw5J1.js} +1 -1
- package/dist/assets/{index-CPieAFsl.js → index-CTBpf-26.js} +250 -250
- package/dist/assets/{settingsSchema-D0FxNrTy.js → settingsSchema-Dh5Kl7VO.js} +1 -1
- package/dist/assets/{useAgentsDirWatch-DCu6BNYN.js → useAgentsDirWatch-CMpx0d04.js} +1 -1
- package/dist/assets/{useRemotePeers-D4cdJDyh.js → useRemotePeers-CI2axd-L.js} +1 -1
- package/dist/index.html +1 -1
- package/package.json +3 -2
- package/plugins/CLAUDE.md +5 -8
- package/plugins/session-manager-dev/.claude-plugin/plugin.json +3 -6
- package/plugins/session-manager-dev/skills/builder/1-classify-and-bump/SKILL.md +2 -2
- package/plugins/session-manager-dev/skills/builder/SKILL.md +2 -3
- package/plugins/session-manager-dev/skills/develop/SKILL.md +1 -1
- package/plugins/session-manager-dev/skills/develop/standards.md +3 -3
- package/scripts/README.md +3 -3
- package/scripts/audit-ops-hygiene.cjs +4 -4
- package/scripts/hooks/guard-destructive-git.cjs +4 -4
- package/scripts/hooks/guard-inline-implementation.cjs +1 -1
- package/scripts/hooks/guard-prd-writes.cjs +2 -2
- package/scripts/hooks/lib/guard-destructive-git-policy.cjs +1 -1
- package/scripts/mint-epic.cjs +2 -2
- package/scripts/scheduler-mcp-server.cjs +4 -4
- package/src/main/agentLibrary.cjs +5 -5
- package/src/main/agentsIpc.cjs +76 -0
- package/src/main/build-info.json +4 -4
- package/src/main/chatRunner.cjs +12 -12
- package/src/main/config.cjs +2 -2
- package/src/main/crashDiagnostics.cjs +2 -2
- package/src/main/docEdit.cjs +5 -5
- package/src/main/files.cjs +2 -2
- package/src/main/git.cjs +1 -1
- package/src/main/health.cjs +20 -18
- package/src/main/heapSnapshot.cjs +1 -1
- package/src/main/historyAggregator.cjs +2 -2
- package/src/main/index.cjs +44 -132
- package/src/main/ipcSchemas.cjs +10 -10
- package/src/main/lib/CLAUDE.md +48 -0
- package/src/main/lib/activeSessions.cjs +1 -1
- package/src/main/lib/classifyPromptTicket.cjs +2 -2
- package/src/main/lib/{agentModelResolve.cjs → claude/agentModelResolve.cjs} +7 -7
- package/src/main/lib/{claudeBin.cjs → claude/claudeBin.cjs} +4 -4
- package/src/main/lib/{effectiveModelInfo.cjs → claude/effectiveModelInfo.cjs} +9 -9
- package/src/main/lib/{modelCatalog.cjs → claude/modelCatalog.cjs} +3 -3
- package/src/main/lib/{rateLimitDetect.cjs → claude/rateLimitDetect.cjs} +1 -1
- package/src/main/lib/{rateLimitWindow.cjs → claude/rateLimitWindow.cjs} +1 -1
- package/src/main/lib/{runClaudeP.cjs → claude/runClaudeP.cjs} +1 -1
- package/src/main/lib/credentials.cjs +3 -3
- package/src/main/lib/cwdClassify.cjs +1 -1
- package/src/main/lib/{activeIndexMerge.cjs → epic/activeIndexMerge.cjs} +3 -3
- package/src/main/lib/{activeIndexRebuild.cjs → epic/activeIndexRebuild.cjs} +1 -1
- package/src/main/lib/{delegationReadiness.cjs → epic/delegationReadiness.cjs} +21 -29
- package/src/main/lib/{epicContextDigest.cjs → epic/epicContextDigest.cjs} +1 -1
- package/src/main/lib/{epicDelegationStats.cjs → epic/epicDelegationStats.cjs} +2 -2
- package/src/main/lib/{epicMint.cjs → epic/epicMint.cjs} +11 -11
- package/src/main/lib/{epicSpawnPlan.cjs → epic/epicSpawnPlan.cjs} +3 -3
- package/src/main/lib/{epicStatusMirror.cjs → epic/epicStatusMirror.cjs} +2 -2
- package/src/main/lib/{epicTranscriptDiagnostic.cjs → epic/epicTranscriptDiagnostic.cjs} +2 -2
- package/src/main/lib/{epicTranscriptPath.cjs → epic/epicTranscriptPath.cjs} +2 -2
- package/src/main/lib/{epicValidationHook.cjs → epic/epicValidationHook.cjs} +3 -3
- package/src/main/lib/{epicWorktreeBoot.cjs → epic/epicWorktreeBoot.cjs} +1 -1
- package/src/main/lib/{epicWorktreeMerge.cjs → epic/epicWorktreeMerge.cjs} +3 -3
- package/src/main/lib/{epicWorktreeMint.cjs → epic/epicWorktreeMint.cjs} +3 -3
- package/src/main/lib/{epicWorktreeProjectConfig.cjs → epic/epicWorktreeProjectConfig.cjs} +4 -4
- package/src/main/lib/{promptSessionsCreateEpic.cjs → epic/promptSessionsCreateEpic.cjs} +4 -4
- package/src/main/lib/{crossProjectFeedback.cjs → feedback-remote/crossProjectFeedback.cjs} +7 -7
- package/src/main/lib/{customerFeedbackClient.cjs → feedback-remote/customerFeedbackClient.cjs} +3 -3
- package/src/main/lib/{customerFeedbackInbox.cjs → feedback-remote/customerFeedbackInbox.cjs} +2 -2
- package/src/main/lib/{customerFeedbackIpc.cjs → feedback-remote/customerFeedbackIpc.cjs} +1 -1
- package/src/main/lib/{localAdminHttp.cjs → feedback-remote/localAdminHttp.cjs} +2 -2
- package/src/main/lib/{macroAdminRoutes.cjs → feedback-remote/macroAdminRoutes.cjs} +1 -1
- package/src/main/lib/{projectHomeAdminRoutes.cjs → feedback-remote/projectHomeAdminRoutes.cjs} +4 -4
- package/src/main/lib/{relayClientAuth.cjs → feedback-remote/relayClientAuth.cjs} +2 -2
- package/src/main/lib/{remoteClientSessions.cjs → feedback-remote/remoteClientSessions.cjs} +1 -1
- package/src/main/lib/{gitWorktree.cjs → git/gitWorktree.cjs} +7 -7
- package/src/main/lib/historyRollup.cjs +1 -1
- package/src/main/lib/importReferences.cjs +1 -1
- package/src/main/lib/machineProfile.cjs +1 -1
- package/src/main/lib/openExternalApp.cjs +1 -1
- package/src/main/lib/opsOwnership.cjs +3 -3
- package/src/main/lib/{agentPersonaSchema.cjs → persona-macro/agentPersonaSchema.cjs} +2 -2
- package/src/main/lib/{macroLibrary.cjs → persona-macro/macroLibrary.cjs} +5 -5
- package/src/main/lib/{personaMerge.cjs → persona-macro/personaMerge.cjs} +4 -4
- package/src/main/lib/{prdAdminRoutes.cjs → prd/prdAdminRoutes.cjs} +7 -7
- package/src/main/lib/{prdAgentType.cjs → prd/prdAgentType.cjs} +3 -3
- package/src/main/lib/{prdCreate.cjs → prd/prdCreate.cjs} +12 -12
- package/src/main/lib/{prdDeclaredPaths.cjs → prd/prdDeclaredPaths.cjs} +1 -1
- package/src/main/lib/{prdGateFiles.cjs → prd/prdGateFiles.cjs} +1 -1
- package/src/main/lib/{prdLocations.cjs → prd/prdLocations.cjs} +2 -2
- package/src/main/lib/{prdMigration.cjs → prd/prdMigration.cjs} +3 -3
- package/src/main/lib/prereqs.cjs +2 -2
- package/src/main/lib/{instanceLock.cjs → process/instanceLock.cjs} +4 -11
- package/src/main/lib/{pidAlive.cjs → process/pidAlive.cjs} +1 -1
- package/src/main/lib/{procName.cjs → process/procName.cjs} +2 -2
- package/src/main/lib/{timeoutShim.cjs → process/timeoutShim.cjs} +1 -1
- package/src/main/lib/projectRootResolve.cjs +1 -1
- package/src/main/lib/promptSessionSchema.cjs +1 -1
- package/src/main/lib/{definitionOfDone.cjs → scheduler/definitionOfDone.cjs} +6 -12
- package/src/main/lib/{fixChainDepth.cjs → scheduler/fixChainDepth.cjs} +1 -1
- package/src/main/lib/{jobDirtFilter.cjs → scheduler/jobDirtFilter.cjs} +1 -1
- package/src/main/lib/{jobSupervisorRecord.cjs → scheduler/jobSupervisorRecord.cjs} +1 -1
- package/src/main/lib/{launchFailure.cjs → scheduler/launchFailure.cjs} +2 -2
- package/src/main/lib/{queueStore.cjs → scheduler/queueStore.cjs} +6 -6
- package/src/main/lib/{quietMachineLease.cjs → scheduler/quietMachineLease.cjs} +1 -1
- package/src/main/lib/{rcaReport.cjs → scheduler/rcaReport.cjs} +4 -4
- package/src/main/lib/{reaperHelpers.cjs → scheduler/reaperHelpers.cjs} +3 -3
- package/src/main/lib/{reservationExpiry.cjs → scheduler/reservationExpiry.cjs} +4 -11
- package/src/main/lib/{reviewNotice.cjs → scheduler/reviewNotice.cjs} +1 -1
- package/src/main/lib/{scheduleJobTransitions.cjs → scheduler/scheduleJobTransitions.cjs} +3 -3
- package/src/main/lib/{schedulerBatch.cjs → scheduler/schedulerBatch.cjs} +2 -2
- package/src/main/lib/{schedulerConfig.cjs → scheduler/schedulerConfig.cjs} +1 -1
- package/src/main/lib/{schedulerRuntimeState.cjs → scheduler/schedulerRuntimeState.cjs} +1 -1
- package/src/main/lib/{sessionSlots.cjs → scheduler/sessionSlots.cjs} +2 -2
- package/src/main/lib/{upgradeDrain.cjs → scheduler/upgradeDrain.cjs} +8 -11
- package/src/main/lib/{watchdogHelpers.cjs → scheduler/watchdogHelpers.cjs} +5 -19
- package/src/main/lib/{auditLog.cjs → telemetry/auditLog.cjs} +1 -1
- package/src/main/lib/{opsErrorLog.cjs → telemetry/opsErrorLog.cjs} +4 -4
- package/src/main/lib/{telemetryBacklog.cjs → telemetry/telemetryBacklog.cjs} +4 -4
- package/src/main/lib/{telemetryBoot.cjs → telemetry/telemetryBoot.cjs} +1 -1
- package/src/main/lib/{telemetryClient.cjs → telemetry/telemetryClient.cjs} +4 -4
- package/src/main/lib/{telemetrySettings.cjs → telemetry/telemetrySettings.cjs} +1 -1
- package/src/main/logs.cjs +1 -1
- package/src/main/mcpStatus.cjs +2 -2
- package/src/main/memoryAggregate.cjs +3 -3
- package/src/main/memoryTool.cjs +1 -1
- package/src/main/otel.cjs +2 -2
- package/src/main/pluginInstall.cjs +29 -3
- package/src/main/projectBrief.cjs +6 -6
- package/src/main/projectPages.cjs +1 -1
- package/src/main/promptSessionEvents.cjs +2 -2
- package/src/main/pty.cjs +7 -7
- package/src/main/queueOps.cjs +6 -6
- package/src/main/remoteClient.cjs +4 -4
- package/src/main/remoteClientIpc.cjs +1 -1
- package/src/main/runVerify.cjs +1 -1
- package/src/main/scheduler/CLAUDE.md +26 -0
- package/src/main/scheduler/budget.cjs +576 -0
- package/src/main/scheduler/gitTreeGuard.cjs +672 -0
- package/src/main/scheduler/prdParser.cjs +4 -4
- package/src/main/scheduler/prdPaths.cjs +487 -0
- package/src/main/scheduler/reviewLadder.cjs +1011 -0
- package/src/main/scheduler/starvation.cjs +390 -0
- package/src/main/scheduler.cjs +289 -3311
- package/src/main/seedAgentPersonas.cjs +5 -5
- package/src/main/seedDevPlugin.cjs +70 -3
- package/src/main/seedSchedulerMcp.cjs +2 -2
- package/src/main/supervisor.cjs +5 -5
- package/src/main/telemetryIpc.cjs +51 -0
- package/src/main/transcripts.cjs +3 -3
- package/src/main/updaterIpc.cjs +1 -1
- package/src/main/usage.cjs +1 -1
- package/src/main/watchers.cjs +1 -1
- package/src/main/webRemote.cjs +7 -7
- package/src/preload/api.d.ts +8 -8
- package/src/preload/index.cjs +3 -3
- package/dist/assets/RemoteMachines-CWnKbFHc.js +0 -3
- package/dist/assets/SystemPrompt-DxeNofL9.js +0 -1
- package/dist/assets/TagLibrary-QOAs7ISO.js +0 -1
- package/dist/assets/Toggle-Ba_f7q_m.js +0 -1
- package/plugins/session-manager-dev/skills/blog-for-project-feature/0-select/SKILL.md +0 -39
- package/plugins/session-manager-dev/skills/blog-for-project-feature/1-research/SKILL.md +0 -37
- package/plugins/session-manager-dev/skills/blog-for-project-feature/2-storyboard/SKILL.md +0 -64
- package/plugins/session-manager-dev/skills/blog-for-project-feature/3-capture/SKILL.md +0 -52
- package/plugins/session-manager-dev/skills/blog-for-project-feature/4-draft-copy/SKILL.md +0 -37
- package/plugins/session-manager-dev/skills/blog-for-project-feature/5-illustrate/SKILL.md +0 -50
- package/plugins/session-manager-dev/skills/blog-for-project-feature/6-compose/SKILL.md +0 -51
- package/plugins/session-manager-dev/skills/blog-for-project-feature/7-review/SKILL.md +0 -54
- package/plugins/session-manager-dev/skills/blog-for-project-feature/SKILL.md +0 -144
- package/plugins/session-manager-dev/skills/blog-for-project-feature/feature.config.yaml +0 -90
- package/plugins/session-manager-dev/skills/discover-features/SKILL.md +0 -95
- package/plugins/session-manager-dev/skills/explain-to-me/SKILL.md +0 -205
- package/plugins/session-manager-dev/skills/explain-to-me/assets/style-reference.html +0 -163
- package/plugins/session-manager-dev/skills/find-opportunity/SKILL.md +0 -83
- package/plugins/session-manager-dev/skills/issue-address/0-select/0-fetch-pool/SKILL.md +0 -38
- package/plugins/session-manager-dev/skills/issue-address/0-select/1-reject-fixed/SKILL.md +0 -64
- package/plugins/session-manager-dev/skills/issue-address/0-select/2-reject-claimed/SKILL.md +0 -71
- package/plugins/session-manager-dev/skills/issue-address/0-select/3-rank-impact/SKILL.md +0 -39
- package/plugins/session-manager-dev/skills/issue-address/0-select/SKILL.md +0 -75
- package/plugins/session-manager-dev/skills/issue-address/1-confirm-open/SKILL.md +0 -39
- package/plugins/session-manager-dev/skills/issue-address/2-claim/SKILL.md +0 -57
- package/plugins/session-manager-dev/skills/issue-address/3-reproduce/SKILL.md +0 -40
- package/plugins/session-manager-dev/skills/issue-address/4-fix/SKILL.md +0 -33
- package/plugins/session-manager-dev/skills/issue-address/5-verify/SKILL.md +0 -40
- package/plugins/session-manager-dev/skills/issue-address/SKILL.md +0 -120
- package/plugins/session-manager-dev/skills/local-project-health/SKILL.md +0 -58
- package/plugins/session-manager-dev/skills/memory-sanitation/SKILL.md +0 -147
- package/plugins/session-manager-dev/skills/ops-sweep/SKILL.md +0 -137
- package/plugins/session-manager-dev/skills/pr-review-sweep/0-fetch/SKILL.md +0 -41
- package/plugins/session-manager-dev/skills/pr-review-sweep/1-classify/SKILL.md +0 -56
- package/plugins/session-manager-dev/skills/pr-review-sweep/2-check-fixed/SKILL.md +0 -49
- package/plugins/session-manager-dev/skills/pr-review-sweep/3-queue/SKILL.md +0 -57
- package/plugins/session-manager-dev/skills/pr-review-sweep/4-land-and-resolve/SKILL.md +0 -60
- package/plugins/session-manager-dev/skills/pr-review-sweep/SKILL.md +0 -124
- package/plugins/session-manager-dev/skills/pr-signal/SKILL.md +0 -67
- package/plugins/session-manager-dev/skills/project-status/SKILL.md +0 -243
- package/plugins/session-manager-dev/skills/requesting-code-review/SKILL.md +0 -98
- package/plugins/session-manager-dev/skills/requesting-code-review/code-reviewer.md +0 -146
- /package/src/main/lib/{agentEffortResolve.cjs → claude/agentEffortResolve.cjs} +0 -0
- /package/src/main/lib/{claudeCliCaps.cjs → claude/claudeCliCaps.cjs} +0 -0
- /package/src/main/lib/{usageCircuit.cjs → claude/usageCircuit.cjs} +0 -0
- /package/src/main/lib/{epicSpawnCwd.cjs → epic/epicSpawnCwd.cjs} +0 -0
- /package/src/main/lib/{customerFeedbackAdminRoutes.cjs → feedback-remote/customerFeedbackAdminRoutes.cjs} +0 -0
- /package/src/main/lib/{remoteE2eCrypto.cjs → feedback-remote/remoteE2eCrypto.cjs} +0 -0
- /package/src/main/lib/{branchSweep.cjs → git/branchSweep.cjs} +0 -0
- /package/src/main/lib/{gitExec.cjs → git/gitExec.cjs} +0 -0
- /package/src/main/lib/{jobWorktree.cjs → git/jobWorktree.cjs} +0 -0
- /package/src/main/lib/{jobWorktreeBootLive.cjs → git/jobWorktreeBootLive.cjs} +0 -0
- /package/src/main/lib/{jobWorktreeTerminalOrphanLive.cjs → git/jobWorktreeTerminalOrphanLive.cjs} +0 -0
- /package/src/main/lib/{builtinMacros.cjs → persona-macro/builtinMacros.cjs} +0 -0
- /package/src/main/lib/{personaImportHealth.cjs → persona-macro/personaImportHealth.cjs} +0 -0
- /package/src/main/lib/{shippedPersonaSeeds.cjs → persona-macro/shippedPersonaSeeds.cjs} +0 -0
- /package/src/main/lib/{depSlugResolve.cjs → prd/depSlugResolve.cjs} +0 -0
- /package/src/main/lib/{planValidator.cjs → prd/planValidator.cjs} +0 -0
- /package/src/main/lib/{prdAuthoringSeed.cjs → prd/prdAuthoringSeed.cjs} +0 -0
- /package/src/main/lib/{prdDisposition.cjs → prd/prdDisposition.cjs} +0 -0
- /package/src/main/lib/{prdFrontmatter.cjs → prd/prdFrontmatter.cjs} +0 -0
- /package/src/main/lib/{prdSizing.cjs → prd/prdSizing.cjs} +0 -0
- /package/src/main/lib/{workTypeLibrary.cjs → prd/workTypeLibrary.cjs} +0 -0
- /package/src/main/lib/{childWithLog.cjs → process/childWithLog.cjs} +0 -0
- /package/src/main/lib/{cleanEnv.cjs → process/cleanEnv.cjs} +0 -0
- /package/src/main/lib/{defaultShell.cjs → process/defaultShell.cjs} +0 -0
- /package/src/main/lib/{killTree.cjs → process/killTree.cjs} +0 -0
- /package/src/main/lib/{loginShellPath.cjs → process/loginShellPath.cjs} +0 -0
- /package/src/main/lib/{procIdentity.cjs → process/procIdentity.cjs} +0 -0
- /package/src/main/lib/{singleInstanceGuard.cjs → process/singleInstanceGuard.cjs} +0 -0
- /package/src/main/lib/{smProcNames.cjs → process/smProcNames.cjs} +0 -0
- /package/src/main/lib/{timeoutShimScript.cjs → process/timeoutShimScript.cjs} +0 -0
- /package/src/main/lib/{winSpawn.cjs → process/winSpawn.cjs} +0 -0
- /package/src/main/lib/{adoptedRunSupervisor.cjs → scheduler/adoptedRunSupervisor.cjs} +0 -0
- /package/src/main/lib/{dispatchLoop.cjs → scheduler/dispatchLoop.cjs} +0 -0
- /package/src/main/lib/{dodDrainHook.cjs → scheduler/dodDrainHook.cjs} +0 -0
- /package/src/main/lib/{fixPlanSlug.cjs → scheduler/fixPlanSlug.cjs} +0 -0
- /package/src/main/lib/{gateAuthority.cjs → scheduler/gateAuthority.cjs} +0 -0
- /package/src/main/lib/{landedSinceRun.cjs → scheduler/landedSinceRun.cjs} +0 -0
- /package/src/main/lib/{loadGate.cjs → scheduler/loadGate.cjs} +0 -0
- /package/src/main/lib/{needsReviewLedger.cjs → scheduler/needsReviewLedger.cjs} +0 -0
- /package/src/main/lib/{queueHealth.cjs → scheduler/queueHealth.cjs} +0 -0
- /package/src/main/lib/{queueHistory.cjs → scheduler/queueHistory.cjs} +0 -0
- /package/src/main/lib/{runLogRetention.cjs → scheduler/runLogRetention.cjs} +0 -0
- /package/src/main/lib/{scheduleJobSchema.cjs → scheduler/scheduleJobSchema.cjs} +0 -0
- /package/src/main/lib/{schedulerPaths.cjs → scheduler/schedulerPaths.cjs} +0 -0
- /package/src/main/lib/{terminalRunOutcome.cjs → scheduler/terminalRunOutcome.cjs} +0 -0
- /package/src/main/lib/{validationSentinels.cjs → scheduler/validationSentinels.cjs} +0 -0
- /package/src/main/lib/{crashTelemetry.cjs → telemetry/crashTelemetry.cjs} +0 -0
- /package/src/main/lib/{otlpTraceExporter.cjs → telemetry/otlpTraceExporter.cjs} +0 -0
- /package/src/main/lib/{telemetryConsent.cjs → telemetry/telemetryConsent.cjs} +0 -0
- /package/src/main/lib/{telemetryCounters.cjs → telemetry/telemetryCounters.cjs} +0 -0
- /package/src/main/lib/{atomicFs.cjs → util/atomicFs.cjs} +0 -0
- /package/src/main/lib/{encodeCwd.cjs → util/encodeCwd.cjs} +0 -0
- /package/src/main/lib/{expandHome.cjs → util/expandHome.cjs} +0 -0
- /package/src/main/lib/{extractJson.cjs → util/extractJson.cjs} +0 -0
- /package/src/main/lib/{fileTail.cjs → util/fileTail.cjs} +0 -0
- /package/src/main/lib/{headTailBuffer.cjs → util/headTailBuffer.cjs} +0 -0
- /package/src/main/lib/{kebabCase.cjs → util/kebabCase.cjs} +0 -0
- /package/src/main/lib/{loopDelay.cjs → util/loopDelay.cjs} +0 -0
- /package/src/main/lib/{lruCache.cjs → util/lruCache.cjs} +0 -0
- /package/src/main/lib/{withTimeout.cjs → util/withTimeout.cjs} +0 -0
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import{aJ as Pe,av as ie,aP as xs,ai as $e,ac as le,ag as ee,aU as q,b8 as Le,b6 as pe,aD as f,aa as xe,bf as ms,an as t,b as Ue,I as me,L as mt,q as bs,K as ge,u as ws,Q as vs,d as js,U as ys,aO as Ns,b5 as tt,a_ as ks,a5 as bt,at as Tt,be as Ce,G as Fe,aA as Te,A as st,aN as nt,ad as wt,N as _t,w as Ot,p as Lt,r as Ss,o as at,y as rt,O as $s,f as re,g as H,ae as Ft,b9 as Cs,aC as Ps,aF as qt,bi as Bt,V as Ds,aw as vt,a$ as jt,n as ke,x as yt,aK as Nt,m as Ms,aS as As,X as Rs,v as Ht,b1 as Is,aX as ye,H as Es,C as Ts,ba as _s,aE as Os,T as Ls,bh as Fs,bb as kt,aM as qs}from"./index-CPieAFsl.js";import{f as Bs,a as Hs,s as Gs}from"./historyTotals-vgfk8EOL.js";import{l as Vs}from"./listSkills-C1aWKf0T.js";import{T as Us}from"./Toggle-Ba_f7q_m.js";import"./monaco-editor-BsIlgG7c.js";function Ws(e){const s=new Map(e.map(i=>[i.slug,i])),n=new Map,a=new Set,c=[];function l(i){n.set(i,1),c.push(i);const r=s.get(i);for(const d of(r==null?void 0:r.dependsOn)??[]){if(!s.has(d))continue;const o=n.get(d);if(o===1){const p=c.indexOf(d);for(let u=p;u<c.length;u++)a.add(c[u])}else o===void 0&&l(d)}c.pop(),n.set(i,2)}for(const i of e)n.has(i.slug)||l(i.slug);return a}function Qs(e,s){return(e.dependsOn??[]).map(n=>{const a=s.get(n);return a?{slug:n,status:a.status,missing:!1,needsReview:a.status==="needs_review"}:{slug:n,status:null,missing:!0,needsReview:!1}})}function zs(e,s,n){const a=new Set(e.map(o=>o.slug)),c=new Set;for(const o of e)for(const p of o.dependsOn??[])a.has(p)&&c.add(p);const l=new Map,i=[];for(const o of e){const p=n.has(o.slug)?void 0:(o.dependsOn??[]).find(u=>a.has(u)&&!n.has(u));p?(l.has(p)||l.set(p,[]),l.get(p).push(o)):i.push(o)}const r=(o,p)=>o.slug.localeCompare(p.slug);i.sort(r);for(const o of l.values())o.sort(r);function d(o,p,u){const h=Qs(o,s),g=n.has(o.slug);u.add(o.slug);const x=g?[]:(l.get(o.slug)??[]).filter(w=>!u.has(w.slug)).map(w=>d(w,p+1,u));return u.delete(o.slug),{row:o,depth:p,children:x,blockers:h,blocked:h.some(w=>!w.missing&&w.status!=="completed"),hasNeedsReviewBlocker:h.some(w=>w.needsReview),hasMissingDep:h.some(w=>w.missing),cycle:g,parallelEligible:(o.dependsOn??[]).length===0&&!c.has(o.slug)}}return i.map(o=>d(o,0,new Set))}function Gt(e,s,n){const a=new Map((n??e).map(o=>[o.slug,o])),c=Ws(e),l=[],i=new Map,r=new Map;for(const o of e){const p=Pe(o,s),u=p.epicId??"__none__";i.has(u)||(l.push(u),i.set(u,[]),r.set(u,{epicId:p.epicId,label:p.known&&p.label?p.label:p.epicId?`Epic ${p.epicId.slice(0,12)}…`:"No Epic",known:p.known})),i.get(u).push(o)}const d=l.map(o=>{const p=r.get(o),u=i.get(o),h=zs(u,a,c),g={};for(const x of u){const w=x.status??"unknown";g[w]=(g[w]??0)+1}return{epicId:p.epicId,label:p.label,known:p.known,nodes:h,counts:g,total:u.length}});return d.sort((o,p)=>o.epicId===null?1:p.epicId===null?-1:o.known!==p.known?o.known?-1:1:o.label.localeCompare(p.label)),d}function qe(e){const s=[],n=a=>{s.push(a);for(const c of a.children)n(c)};for(const a of e)n(a);return s}function Ke(e){return String(e??"").replace(/^\d+-/,"")}function _e(e){const s=new Set,n=new Map;for(const a of e){s.add(a.slug);const c=Ke(a.slug),l=n.get(c);l?l.push(a.slug):n.set(c,[a.slug])}return e.map(a=>{const c=a.dependsOn;if(!c||c.length===0)return a;let l=!1;const i=c.map(r=>{if(s.has(r))return r;const d=n.get(Ke(r));return d&&d.length===1?(l=!0,d[0]):r});return l?{...a,dependsOn:i}:a})}const Js=15e4,Ye=e=>e==="completed"||e==="skipped",Se=e=>e==="running"||e==="investigating",Vt=e=>e==="failed"||e==="needs_review"||e==="quarantined",Ks=e=>e==="failed"||e==="needs_review"||e==="quarantined";function Ut(e){const s=Math.max(0,Math.floor(e/1e3)),n=Math.floor(s/3600),a=Math.floor(s%3600/60),c=s%60;return n>0?`${n}h${String(a).padStart(2,"0")}m`:a>0?`${a}m${String(c).padStart(2,"0")}s`:`${c}s`}function Wt(e){if(e<=5e3)return"~now";if(e<6e4)return`~${Math.round(e/1e3)}s`;const s=Math.round(e/6e4);return s<60?`~${s}m`:`~${Math.floor(s/60)}h${String(s%60).padStart(2,"0")}m`}function Qt(e,s){const n=e.estimateMinutes?e.estimateMinutes*6e4:null;return n?`${Math.min(99,Math.floor(s/n*100))}%`:Ut(s)}function Ys(e){let s=0,n=0;for(const a of e)if(a.status==="completed"&&a.startedAt&&a.finishedAt){const c=Date.parse(a.finishedAt)-Date.parse(a.startedAt);c>0&&(s+=c,n++)}return n===0?Js:s/n}function Oe(e){const s=ie(e);return s===null?1/0:Number(s)}function Xe(e,s){const n=Oe(e.slug)-Oe(s.slug);return n!==0&&!Number.isNaN(n)?n:e.slug.localeCompare(s.slug)}function Xs(e){let s=0;for(const n of e.statusHistory??[])n.to==="pending"&&n.from!==null&&s++;return s}function Zs(e){return e.some(n=>Se(n.status))?"active":e.every(n=>Ye(n.status))?"done":e.filter(n=>n.status!=="quarantined").length===0?"draft":"queued"}function en(e,s,n,a){switch(e){case"done":return`${s.doneCount}/${s.rows.length} done`;case"running":return`${s.runningCount} running · ${n}`;case"held":return`${s.heldCount} held`;case"blocked":return`${s.blockedCount+a} blocked`;default:return`${n} ready`}}function tn(e,s){return e._firstNum!==s._firstNum?e._firstNum<s._firstNum?-1:1:e._firstSlug.localeCompare(s._firstSlug)}function sn(e,s){const n=new Map(e.map(l=>[l.row.slug,l.row.slug])),a=l=>{for(;n.get(l)!==l;)n.set(l,n.get(n.get(l))),l=n.get(l);return l};for(const l of e)for(const i of l.row.dependsOn??[])s.has(i)&&n.set(a(l.row.slug),a(i));const c=new Map;for(const l of e){const i=a(l.row.slug),r=c.get(i);r?r.push(l):c.set(i,[l])}return[...c.values()]}function nn(e,s){if(e.length>0&&e.every(n=>!!n.row.planId)){const n=new Map;for(const a of e){const c=n.get(a.row.planId);c?c.push(a):n.set(a.row.planId,[a])}return[...n.values()]}return sn(e,s)}function an(e,s,n,a){const c=[],l=[e];for(a.add(e.row.slug);l.length>0;){const i=l.pop();c.push(i);for(const r of i.row.dependsOn??[])if(n.has(r)&&!a.has(r)){a.add(r);const d=s.get(r);d&&l.push(d)}}return c}function rn(e,s){const n=new Map(e.map(r=>[r.row.slug,r])),a=new Set,c=[],l=e.filter(r=>Ke(r.row.slug).startsWith("validate-")).sort((r,d)=>Xe({slug:r.row.slug},{slug:d.row.slug}));for(const r of l)a.has(r.row.slug)||c.push({nodes:an(r,n,s,a),validateSlug:r.row.slug});const i=e.filter(r=>!a.has(r.row.slug));if(i.length>0){const r=new Set(i.map(d=>d.row.slug));for(const d of nn(i,r))c.push({nodes:d,validateSlug:null})}return c}function ln(e){return e.replace(/^validate[\s:-]*/i,"").trim()}function it(e,s){if(e.length===0)return[];const n=_e(e),a=s.now??Date.now(),c=s.avgDurationMs??Ys(n),l=Math.max(1,s.concurrency??1),i=new Map(n.map(u=>[u.slug,u])),r=u=>u.status==="pending"&&(u.dependsOn??[]).every(h=>i.get(h)===void 0||i.get(h).status==="completed"),d=new Map;n.filter(r).sort(Xe).forEach((u,h)=>d.set(u.slug,h));const o=Gt(n,s.sessions,n),p=[];for(const u of o){const h=qe(u.nodes),g=new Set(h.map(D=>D.row.slug)),x=new Map(h.map(D=>[D.row.slug,D])),w=[];for(const D of rn(h,g)){const k=D.nodes,E=new Set(k.map(N=>N.row.slug)),m=new Map,T=new Set,C=N=>{const S=x.get(N);return(S.row.dependsOn??[]).filter(G=>E.has(G)&&!(S.cycle&&x.get(G).cycle))},P=N=>{const S=m.get(N);if(S!==void 0)return S;if(T.has(N))return 0;T.add(N);let G=0;for(const F of C(N))G=Math.max(G,P(F));return T.delete(N),m.set(N,G+1),G+1};for(const N of k)P(N.row.slug);const O=k.map(N=>{const S=N.row,G=(S.dependsOn??[]).filter(F=>g.has(F));return{slug:S.slug,title:S.title,status:S.status,stage:m.get(S.slug),prdNumber:ie(S.slug),rowKind:"dep",rowTrailing:"",cycle:N.cycle,estimateMinutes:S.estimateMinutes??null,deps:G,crossEpicDeps:(S.dependsOn??[]).filter(F=>!g.has(F)),blockers:N.blockers,job:S}});O.sort(Xe);const K=O.reduce((N,S)=>Math.max(N,S.stage),0),U=new Map;for(const N of O){const S=N.job,G=x.get(N.slug),F=S.status;let W;if(Ye(F)){const b=S.startedAt&&S.finishedAt?Date.parse(S.finishedAt)-Date.parse(S.startedAt):NaN;W={kind:"done",trailing:b>0?Ut(b):"",held:!1,blocked:!1}}else if(Se(F)){const b=S.startedAt?Math.max(0,a-Date.parse(S.startedAt)):null;W={kind:"running",trailing:b===null?"":Qt(S,b),held:!1,blocked:!1}}else if(F==="failed")W={kind:"failed",trailing:"failed",held:!1,blocked:!1};else if(F==="needs_review")W={kind:"review",trailing:"review",held:!1,blocked:!1};else if(F==="quarantined")W={kind:"quarantined",trailing:"quarantined",held:!1,blocked:!1};else{const b=G.blockers.filter(y=>!y.missing&&y.status!=="completed");if(b.length>0){const y=b.some($=>Ks($.status)),M=b[0].slug;W={kind:"dep",trailing:`←${ie(M)??M}`,held:!y,blocked:y}}else if(S.heldReason)W={kind:"gate",trailing:"gate",held:!0,blocked:!1};else{const y=Xs(S),M=d.get(S.slug)??0;W=y>0?{kind:"retry",trailing:`${y} ${y===1?"retry":"retries"}`,held:!1,blocked:!1}:{kind:"eta",trailing:Wt(M*c/l),held:!1,blocked:!1}}}U.set(N.slug,W)}const Q=[];for(let N=1;N<=K;N++){const S=O.filter(_=>_.stage===N),G=S.find(_=>{const X=U.get(_.slug).kind;return _.status==="pending"&&(X==="eta"||X==="retry")});if(G){const _=U.get(G.slug);_.kind="next",_.trailing="next"}let F=0,W=0,b=0,y=0,M=0,$=0;for(const _ of S){const X=U.get(_.slug);_.rowKind=X.kind,_.rowTrailing=X.trailing,Ye(_.status)?F++:Se(_.status)?W++:_.status==="pending"?(M++,X.held&&b++,X.blocked&&y++):Vt(_.status)&&$++}const R=F===S.length?"done":W>0?"running":y+$>0?"blocked":b>0?"held":"pending",L={n:N,rows:S,doneCount:F,runningCount:W,heldCount:b,blockedCount:y};Q.push({...L,state:R,summary:en(R,L,M,$)})}let Y=0;for(const N of O){const S=N.estimateMinutes?N.estimateMinutes*6e4:c;if(N.status==="pending")Y+=S;else if(Se(N.status)){const G=N.job.startedAt?Math.max(0,a-Date.parse(N.job.startedAt)):0;Y+=Math.max(0,S-G)}}const te=O.reduce((N,S)=>Math.min(N,Oe(S.slug)),1/0),se=O.reduce((N,S)=>Math.max(N,Oe(S.slug)),-1/0),z=u.known?xs(u.label).title:u.label,A=D.validateSlug?O.find(N=>N.slug===D.validateSlug):void 0,B=A&&ln(A.title)||z;w.push({epicId:u.epicId,waveIndex:0,index:0,label:B,epicLabel:z,validateSlug:D.validateSlug,width:Q.reduce((N,S)=>Math.max(N,S.rows.length),0),status:Zs(O),prdCount:O.length,stageCount:K,doneCount:Q.reduce((N,S)=>N+S.doneCount,0),runningCount:Q.reduce((N,S)=>N+S.runningCount,0),heldCount:Q.reduce((N,S)=>N+S.heldCount,0),blockedCount:Q.reduce((N,S)=>N+S.blockedCount,0),etaMs:Y/l,stages:Q,_firstNum:te,_lastNum:se,_firstSlug:O[0].slug})}w.sort(tn),w.forEach((D,k)=>{D.waveIndex=k+1});const j=w.filter(D=>D.validateSlug===null);j.forEach((D,k)=>{j.length>1&&(D.label=`${D.label} · plan ${k+1}/${j.length}`)});for(const D of w)p.push(D)}return p.sort((u,h)=>{if(u._lastNum!==h._lastNum)return u._lastNum>h._lastNum?-1:1;const g=(u.epicId??"").localeCompare(h.epicId??"");return g!==0?g:u.waveIndex-h.waveIndex}),p.map(({_firstNum:u,_lastNum:h,_firstSlug:g,...x},w)=>({...x,index:w+1}))}function on(e,s=Date.now()){const n=_e(e),a=new Map(n.map(g=>[g.slug,g])),c=new Date(s).toDateString();let l=0,i=0,r=0,d=0,o=0,p=0,u=0;for(const g of n)g.status==="pending"?(i++,(g.dependsOn??[]).every(w=>a.get(w)===void 0||a.get(w).status==="completed")&&l++):Se(g.status)?u++:g.status==="failed"?r++:g.status==="needs_review"?d++:g.status==="quarantined"?o++:g.status==="completed"&&g.finishedAt&&new Date(Date.parse(g.finishedAt)).toDateString()===c&&p++;let h=null;if(r+d+o>0){for(const g of it(n,{sessions:{},now:s}))for(const x of g.stages)if(x.rows.some(w=>Vt(w.status))){(h===null||x.n<h)&&(h=x.n);break}}return{readyNow:l,totalQueued:i,heldByDeps:i-l,needsYou:r+d+o,needsYouStage:h,failedCount:r,needsReviewCount:d,doneToday:p,inFlight:u}}function dn(e){const s=new Map;for(const d of e.stages)for(const o of d.rows)s.set(o.slug,o);const n=d=>{var o;return((o=s.get(d))==null?void 0:o.cycle)===!0},a=new Map,c=new Set,l=(d,o)=>d.chain.length!==o.chain.length?d.chain.length>o.chain.length:d.est!==o.est?d.est>o.est:d.chain.join("\0")<o.chain.join("\0"),i=d=>{const o=a.get(d);if(o)return o;const p=s.get(d),u=p.estimateMinutes??0;if(c.has(d))return{chain:[d],est:u};c.add(d);let h=null;for(const x of p.deps){if(!s.has(x)||p.cycle&&n(x))continue;const w=i(x);(!h||l(w,h))&&(h=w)}c.delete(d);const g=h?{chain:[...h.chain,d],est:h.est+u}:{chain:[d],est:u};return a.set(d,g),g};let r=null;for(const d of s.keys()){const o=i(d);(!r||l(o,r))&&(r=o)}return r?r.chain:[]}const cn=300*6e4,un={five_hour:"5-hour",session:"5-hour",weekly_all:"weekly",weekly:"weekly"};function pn(e){return un[e]??e.replace(/_/g," ")}function zt({snap:e,now:s,avgDurationMs:n,runningJobs:a}){const{config:c,jobs:l,paused:i,nextReset:r,utilization:d,utilizationWindow:o,effectiveConcurrency:p}=e;let u=0,h=0;for(const k of l)k.status==="pending"?u++:k.status==="completed"&&h++;const g=a.length,x=u+g,w=(p==null?void 0:p.cap)??5;if(g>0){const k=a.reduce((P,O)=>(P.startedAt??"")<(O.startedAt??"")?P:O),E=k.startedAt?s-Date.parse(k.startedAt):0,m=h+g,T=h+x,C=g>1?` · ${g}/${w} parallel`:"";return{kind:"running",line1:`Running ${m}/${T}${C} · ${$e(E)}`,line2:g===1?k.title:a.map(P=>P.title).join(", "),tooltip:a.map(P=>`${P.slug} (g${P.parallelGroup})`).join("; ")}}if(i){const k=i.resumeAt?Date.parse(i.resumeAt)-s:null;return{kind:"paused",line1:{rate_limit:"Paused — tokens exhausted",auth:"Paused — authentication failed",network:"Paused — network unreachable",reset_failure:"Paused — billing data unavailable",manual:"Paused — manual (you paused the queue)"}[i.reason]??`Paused — ${i.reason}`,line2:i.reason==="auth"?"Run `claude` in any terminal to refresh credentials, then Resume":k!==null&&k>0?`auto-resume ${le(Date.parse(i.resumeAt))} (in ${ee(k)})`:i.resumeAt?"resuming…":"no auto-resume scheduled",tooltip:i.resumeAt??"",action:{label:"Resume",onClick:()=>window.api.schedule.resume(),title:"Clear the pause and resume queue immediately"}}}if(x===0)return{kind:"idle",line1:"No work queued",line2:null};const j=c.firePolicy??"when-available";if(j==="manual")return{kind:"manual",line1:`Manual · ${u} pending`,line2:"click Fire next batch now to fire",action:{label:"Fire next batch now",onClick:()=>window.api.schedule.forceTick().then(q.fromOutcome).catch(()=>q.error("Failed to fire batch")),title:"Bypasses the billing-usage poll. Use when the meter is rate-limited or you want immediate progress."}};if(j==="on-reset"){if(!r)return{kind:"on-reset",line1:"On-reset · waiting for billing data",line2:null};const k=Date.parse(r)+c.offsetMinutes*6e4,E=k-s;return{kind:"on-reset",line1:`On-reset · ${u} pending`,line2:E>0?`fires ${le(k)} (in ${ee(E)})`:"firing now…"}}const D=c.utilizationThreshold??90;if(d==null)return{kind:"auto-soon",line1:`Auto · ${u} pending`,line2:"checking token availability…"};if(d>=D){const k=r?Date.parse(r)-s:null,E=o?pn(o):null,m=k===null||Number.isNaN(k)||k>cn,T=k&&k>0?`resets ${le(Date.parse(r))} (in ${ee(k)})`:null;let C;return m?C=`${E??"binding"} window — long hold${T?`, ${T}`:", reset time unknown"}`:C=T?`${E?`${E} window `:""}next ${T}`:"will fire when usage drops",{kind:"auto-throttled",line1:`Auto · throttled (util ${d.toFixed(0)}% ≥ ${D}%)`,line2:C}}return{kind:"auto-soon",line1:`Auto · ${u} pending · util ${d.toFixed(0)}%`,line2:"fires within 2 min (poll cycle)"}}const fn=15e3,hn=new Set(["failed","needs_review","quarantined"]);function St(){var n;const s=Array.from(document.querySelectorAll("[data-job-row]")).find(a=>hn.has(a.dataset.jobStatus??""));(n=s==null?void 0:s.scrollIntoView)==null||n.call(s,{block:"center",behavior:"smooth"})}function gn(e,s){var n;switch(e.kind){case"paused":return`paused: scheduler is paused (${e.reason??"manual"})`;case"launch-blocked":return`launch-blocked: ${e.agentType} jobs can't launch${(n=e.block)!=null&&n.kind?` (${e.block.kind})`:""}`;case"idle":return"idle: 0 pending";case"saturated":{const a=s!=null?`, oldest ${ee(s)}`:"";return`saturated: ${e.totalSlots??"?"} slot(s) busy${a}`}case"blocked":{const a=e.blockedChains.length;return`blocked: ${e.pending} pending, ${e.dispatchable} dispatchable — ${a} chain${a===1?"":"s"} stuck behind a failed/skipped dependency`}case"stalled":return`stalled: no dispatch attempt in ${e.idleMs!=null?ee(e.idleMs):"?"} with ${e.dispatchable} dispatchable`;case"running":default:return`running: ${e.runningCount} in flight, ${e.pending} pending`}}function xn(e){const[s,n]=f.useState(null),a=tt(),c=ks(),l=a&&c;return f.useEffect(()=>{if(!l)return;let i=!0,r=!1,d=!1;const o=()=>{r||(r=!0,window.api.schedule.queueHealth(e).then(u=>{r=!1,d=!1,i&&n(u)},u=>{r=!1,!d&&(d=!0,q.error(`Queue health refresh failed: ${u instanceof Error?u.message:String(u)}`))}))};o();const p=setInterval(o,fn);return()=>{i=!1,clearInterval(p)}},[e,l]),s}const mn={running:{dot:"bg-sage",text:"text-sage-dark"},paused:{dot:"bg-amber-500",text:"text-amber-600"},idle:{dot:"bg-fg-faint",text:"text-fg-faint"}};function bn(e,s,n){return e==="paused"||e==="launch-blocked"?"paused":e==="running"||e==="saturated"?"running":e?"idle":s?"paused":n>0?"running":"idle"}const We="px-2.5 py-1.5 rounded border border-line text-[12.5px] font-medium text-fg-dim hover:text-fg hover:bg-bg-hi disabled:opacity-40 disabled:cursor-not-allowed whitespace-nowrap";function wn(e,s,n,a){var c;if(e==="agent"){const l=((c=a==null?void 0:a.cwd)==null?void 0:c.split("/").filter(Boolean).pop())||"another session",i=a!=null&&a.reason?` — "${a.reason}"`:"",r=s?new Date(s).getTime()-n:null,d=r==null?"":r>0?` — auto-resumes in ${ee(r)}`:" — auto-resume pending";return`Paused by an agent in ${l}${i}${d}. Click Resume to restart now.`}if(e==="auth")return"Scheduler paused: Claude sign-in expired or invalid. Restart the app or re-run `claude login`, then Resume.";if(e==="rate_limit"){if(s){const l=new Date(s).getTime()-n;return l>0?`Paused for rate limit — resumes in ${ee(l)}`:"Paused for rate limit — resume pending"}return"Paused for rate limit"}return e==="network"?"Paused: billing endpoint unreachable for 30+ min.":e==="manual"?"Scheduler paused manually — no new jobs start; running jobs continue. Click Resume to restart.":`Scheduler paused (${e})`}function vn({now:e}){const s=Le(p=>p.snapshot);if(!s)return null;const n=s.paused,a=Object.entries(s.launchBlocks??{}),c=Object.entries(s.launchMitigations??{}),l=(n==null?void 0:n.reason)==="auth"||(n==null?void 0:n.reason)==="network",i="flex items-start gap-3 border-b px-0 py-1.5 text-[12.5px]",r="bg-red-950/10 border-red-700/30 text-red-800",d="bg-amber-400/10 border-amber-600/30 text-amber-700",o="shrink-0 px-2 py-0.5 rounded border border-current/40 hover:bg-white/20 text-[12px] font-medium";return t.jsxs(t.Fragment,{children:[n&&t.jsxs("div",{"data-testid":"pause-banner",className:`${i} ${l?r:d}`,children:[t.jsx("span",{className:"flex-1 leading-snug",children:wn(n.reason,n.resumeAt,e,n.by)}),t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resume(),className:o,children:"Resume"})]}),a.map(([p,u])=>t.jsxs("div",{"data-testid":"launch-block-banner",className:`${i} ${r}`,children:[t.jsxs("div",{className:"flex-1 leading-snug min-w-0",children:[t.jsxs("div",{className:"font-medium",children:["Launches for ",t.jsx("span",{className:"font-mono",children:p})," jobs are failing before any work starts",u.httpStatus?` (HTTP ${u.httpStatus}, ${u.kind})`:` (${u.kind})`,u.exhausted?" — held until the Claude CLI version changes or you press Retry now.":u.until?` — next automatic probe ${new Date(u.until).getTime()>e?`in ${ee(new Date(u.until).getTime()-e)}`:"on the next tick"}.`:"."]}),t.jsx("div",{className:"opacity-80",children:u.hint}),t.jsxs("div",{className:"font-mono text-[11.5px] opacity-70 truncate",title:u.message,children:[u.attempts," failed probe",u.attempts===1?"":"s",u.claudeVersion?` · CLI ${u.claudeVersion}`:"",u.lastSlug?` · last: ${u.lastSlug}`:""," · ",u.message]})]}),t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resume(),className:o,children:"Retry now"})]},`launch-block-${p}`)),c.map(([p,u])=>t.jsx("div",{"data-testid":"launch-mitigation-banner",className:`${i} ${d}`,children:t.jsxs("div",{className:"flex-1 leading-snug min-w-0",children:[t.jsxs("div",{className:"font-medium",children:[t.jsx("span",{className:"font-mono",children:p})," jobs are running in degraded mode"," ","(",t.jsx("span",{className:"font-mono",children:Object.entries(u.env).map(([h,g])=>`${h}=${g}`).join(" ")}),")",u.claudeVersion?` since CLI ${u.claudeVersion}`:"","."]}),t.jsx("div",{className:"opacity-80",children:u.hint})]})},`launch-mitigation-${p}`))]})}function jn({scopeCwd:e,subView:s,onSubView:n,filterText:a,onFilterText:c,planMode:l,onPlanMode:i,planToolsRef:r}){const d=Le($=>$.snapshot),o=pe($=>$.sessions),p=xn(e),[u,h]=f.useState(()=>Date.now()),[g,x]=f.useState("—");f.useEffect(()=>{const $=setInterval(()=>h(Date.now()),3e4);return()=>clearInterval($)},[]),f.useEffect(()=>{let $=!0;return Bs(30).then(R=>{if(!$||!R.ok||!R.data)return;const L=new Date,_=Be=>String(Be).padStart(2,"0"),X=`${L.getFullYear()}-${_(L.getMonth()+1)}-${_(L.getDate())}`;x(Hs(Gs(R.data,{day:X})))}),()=>{$=!1}},[]);const w=f.useMemo(()=>((d==null?void 0:d.jobs)??[]).filter($=>!e||$.cwd===e),[d,e]),j=f.useMemo(()=>on(w,u),[w,u]),D=f.useMemo(()=>{const $=it(w,{sessions:o,now:u}),R=L=>$.filter(_=>_.status===L).length;return{active:R("active"),queued:R("queued"),draft:R("draft")}},[w,o,u]),k=f.useMemo(()=>{const $=new Date(u).toDateString(),R=[];for(const L of w)if(L.status==="completed"&&L.startedAt&&L.finishedAt&&new Date(Date.parse(L.finishedAt)).toDateString()===$){const _=Date.parse(L.finishedAt)-Date.parse(L.startedAt);_>0&&R.push(_)}return R.length?Math.round(R.reduce((L,_)=>L+_,0)/R.length/6e4):null},[w,u]);if(!d)return null;const E=p&&!p.unknown?p.verdict??null:null,m=p&&!p.unknown?p.slots??null:null,T=d.paused,C=bn((E==null?void 0:E.kind)??null,!!T,j.inFlight),P=mn[C],O=w.filter($=>$.status==="pending").length,K=w.filter($=>$.status==="running").length,U=zt({snap:{...d,jobs:w},now:u,avgDurationMs:0,runningJobs:w.filter($=>$.status==="running")}),Q=p!=null&&p.unknown?`Queue health: unknown — ${p.reason??"state unavailable"}`:E?gn(E,(p==null?void 0:p.oldestRunningAgeMs)??null):"queue health loading…",Y=xe(d.lastRunAt?Date.parse(d.lastRunAt):null,u),te=p!=null&&p.lastDispatchAttemptAt?xe(Date.parse(p.lastDispatchAttemptAt),u):"never",se=[Q,U.line1,E?`dispatchable ${E.dispatchable} · needs_review ${E.needsReviewCount}`:null,(p==null?void 0:p.oldestRunningAgeMs)!=null?`oldest running ${ee(p.oldestRunningAgeMs)} (any project)`:null,`last batch fired ${Y} (lastRunAt — advances only when a job launches)`,`last dispatch attempt ${te} (advances on every driver evaluation)`].filter(Boolean).join(`
|
|
2
|
-
`),z=d.utilization,A=d.pollHealth,B=A!=null&&!A.lastPollOk,N=ms(d.utilizationWindow),S=d.nextReset?Date.parse(d.nextReset):null,G=S?S>u?ee(S-u):"soon":"—",F=d.effectiveConcurrency,W=(F==null?void 0:F.cap)??5,b=(F==null?void 0:F.source)==="env",y=d.config.firePolicy??"when-available",M=O===0&&K===0;return t.jsxs("div",{"data-testid":"scheduler-top-bands",className:"shrink-0 px-[18px]",children:[t.jsxs(Ue,{height:40,testId:"queue-health-header",className:"gap-3",children:[t.jsx("h1",{className:"m-0 font-serif text-[21px] font-semibold leading-none tracking-tight text-fg",children:"Scheduler"}),t.jsx("span",{className:"w-px h-[20px] bg-rule-structural","aria-hidden":"true"}),t.jsxs("span",{className:`inline-flex items-center gap-1.5 text-[12.5px] font-medium ${P.text}`,"data-testid":"scheduler-state-word","data-state":C,children:[t.jsx("span",{className:`w-2 h-2 rounded-full ${P.dot}`,"aria-hidden":"true"}),C]}),t.jsxs("span",{className:"font-mono text-[12px] text-fg-faint whitespace-nowrap","data-testid":"scheduler-meta",children:[j.inFlight," in flight · ",j.heldByDeps," held · last batch ",Y]}),t.jsxs(me,{title:se,testId:"scheduler-verdict-info",popoverTestId:"scheduler-info-popover",children:[t.jsx("pre",{className:"m-0 mb-2 whitespace-pre-wrap font-mono text-[11.5px] text-fg-dim",children:se}),mt.scheduler&&t.jsx(bs,{content:mt.scheduler})]}),t.jsxs("span",{className:"ml-auto flex items-center gap-2",children:[t.jsx("button",{type:"button",onClick:()=>window.api.schedule.rescan().then(q.fromOutcome).catch(()=>q.error("Failed to rescan")),title:"Re-scan the prds/ folder. Use when you've added or edited PRDs on disk and want the queue to reflect them immediately.",className:We,children:"Refresh"}),T?t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resume(),title:"Clear the pause and resume queue immediately",className:We,children:"Resume"}):t.jsx("button",{type:"button",onClick:()=>window.api.schedule.pause(),title:"Stop NEW dispatch. Running jobs are not killed.",className:We,children:"Pause"}),t.jsx("button",{type:"button",onClick:()=>window.api.schedule.forceTick().then(q.fromOutcome).catch(()=>q.error("Failed to fire batch")),disabled:M,title:"Bypasses the billing-usage poll. Use when the meter is rate-limited or you want immediate progress.",className:"px-3 py-1.5 rounded bg-accent text-white text-[12.5px] font-semibold whitespace-nowrap disabled:opacity-40 disabled:cursor-not-allowed hover:opacity-90",children:"Fire next batch"})]})]}),t.jsx(vn,{now:u}),t.jsxs(Ue,{height:70,testId:"scheduler-kpi-band",children:[t.jsx(ge,{testId:"kpi-window",label:N?`${N} used`:"Window used",info:B?`Billing poll failing — this reading may be outdated (last good reading ${xe(A.lastPollAt,u)}). Machine-wide ${N??"binding"} window.`:`Share of the machine-wide ${N??"binding"} billing window consumed — the window closest to its limit.`,value:z==null?"—":`${Math.round(z)}%`,sub:`resets in ${G}`,third:t.jsx(ws,{pct:z??0,tone:B?"bg-amber-500":"bg-accent"})}),t.jsx(ge,{testId:"kpi-slots",label:"Slots",info:`Machine-wide session pool (${(m==null?void 0:m.source)==="env"?"SM_SESSION_SLOTS override":"Home tab cap"}), not scoped to this project`,value:m?`${m.inUse}/${m.total}`:"—",sub:"in use",third:m?t.jsx(vs,{filled:m.inUse,total:m.total}):null}),t.jsx(ge,{testId:"kpi-ready",label:"Ready now",info:"Pending rows whose dependsOn chain is fully satisfied right now",value:j.readyNow,sub:`of ${j.totalQueued} queued`,third:`${j.heldByDeps} held by deps`}),j.needsYou>0?t.jsx(ge,{testId:"kpi-needs-you",label:"Needs you",value:t.jsx("button",{type:"button","data-testid":"kpi-needs-you-jump",onClick:St,className:"font-semibold text-accent hover:underline",title:"Scroll to the first failed / needs-review / quarantined row",children:j.needsYou}),sub:t.jsx("button",{type:"button",onClick:St,className:"hover:underline",children:j.needsYouStage!=null?`blocking stage ${j.needsYouStage}`:"need attention"}),third:[j.failedCount>0&&`${j.failedCount} failed`,j.needsReviewCount>0&&`${j.needsReviewCount} needs review`,j.needsYou-j.failedCount-j.needsReviewCount>0&&`${j.needsYou-j.failedCount-j.needsReviewCount} quarantined`].filter(Boolean).join(" · ")}):t.jsx(ge,{testId:"kpi-needs-you",label:"Needs you",value:t.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[15px]",children:[t.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-sage","aria-hidden":"true"}),"all clear"]}),third:"0 failed · 0 needs review"}),t.jsx(ge,{testId:"kpi-done",label:"Done today",value:j.doneToday,sub:k!=null?`avg ${k}m`:"avg —",third:t.jsx("span",{"data-testid":"kpi-done-spend",children:g})}),t.jsx(ge,{testId:"kpi-concurrency",label:"Concurrency",info:"Start-jobs policy, concurrency cap and utilization threshold",infoTestId:"kpi-concurrency-info",infoAlignRight:!0,infoContent:t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-fg",children:"Start jobs"}),t.jsxs("select",{"data-testid":"kpi-fire-policy",value:y,onChange:$=>window.api.schedule.setConfig({firePolicy:$.target.value}),className:"border border-line bg-bg-hi rounded px-1 py-0.5 text-[12px] text-fg-dim",title:"when-available: poll usage and fire when tokens are below threshold. on-reset: fire after each 5h reset. manual: only on Run now.","aria-label":"Start jobs policy",children:[t.jsx("option",{value:"when-available",children:"when available"}),t.jsx("option",{value:"on-reset",children:"only on reset"}),t.jsx("option",{value:"manual",children:"manually"})]})]}),value:t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(ys,{value:W,min:0,max:10,disabled:b,onChange:$=>{Ns($).catch(R=>{q.error(`Could not set session slots: ${R instanceof Error?R.message:String(R)}`)})},title:b?"pinned by SM_SESSION_SLOTS — unset the env var to edit":"Machine-wide claude -p session slots, shared with chat runs"}),b&&t.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-amber-600 bg-amber-400/10 border border-amber-400/30 rounded px-1 py-0",title:"Pinned by SM_SESSION_SLOTS — unset the env var to edit",children:"env"})]}),sub:"at once",third:y==="when-available"?t.jsxs("span",{children:["pause above"," ",t.jsx(js,{value:d.config.utilizationThreshold??90,min:0,max:100,testId:"kpi-threshold",title:"Fire only when 5h utilization is below this percent — click to edit",onCommit:$=>window.api.schedule.setConfig({utilizationThreshold:$})})]}):null})]}),t.jsxs(Ue,{height:30,testId:"scheduler-plans-toolbar",className:"gap-3",children:[t.jsx("span",{className:"text-[10.5px] font-semibold uppercase tracking-wide text-fg-faint",children:"Plans"}),t.jsxs("span",{className:"font-mono text-[12px] text-fg-faint whitespace-nowrap","data-testid":"scheduler-plans-meta",children:[D.active," active · ",D.queued," queued · ",D.draft," draft · ",w.length," PRDs"]}),t.jsxs("span",{className:"ml-auto flex items-center gap-3",children:[t.jsx("span",{ref:r,className:"contents","data-testid":"scheduler-plan-tools"}),t.jsx("input",{type:"text",value:a,onChange:$=>c($.target.value),placeholder:"filter PRDs…","aria-label":"Filter PRDs by title, slug, or project","data-testid":"scheduler-filter-input",className:"w-[180px] bg-bg-hi border border-line rounded px-2 py-0.5 text-[12px] text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint"}),t.jsx("span",{className:"inline-flex border border-line rounded overflow-hidden",role:"group","aria-label":"Plan view mode",children:[["graph","Graph"],["list","List"],["critical","Critical path"]].map(([$,R])=>t.jsx("button",{type:"button","data-testid":`plan-mode-${$}`,"aria-pressed":l===$&&s==="queue",onClick:()=>{i($),n("queue")},className:`px-2 py-0.5 text-[12px] ${l===$&&s==="queue"?"bg-bg-elev font-semibold text-fg":"text-fg-dim hover:text-fg"}`,children:R},$))}),t.jsx("span",{className:"w-px h-[16px] bg-rule-structural","aria-hidden":"true"}),[["prds","PRDs","Authored PRD source files on disk — edit, lint, archive, or queue them."],["history","History","The last 50 completed and failed jobs."],["machine","Machine","Machine-wide config that applies to every project — not this project’s live queue."]].map(([$,R,L])=>t.jsx("button",{type:"button",onClick:()=>n($),"aria-pressed":s===$,title:L,className:`text-[12.5px] ${s===$?"font-semibold text-fg":"text-fg-faint hover:text-fg-dim"}`,children:R},$))]})]})]})}function Jt({options:e,value:s,onChange:n,pillPadding:a="px-3 py-1.5"}){return t.jsx("div",{className:"flex gap-1.5 flex-wrap",children:e.map(c=>{const l=c.value===s;return t.jsxs("button",{type:"button",onClick:()=>n(c.value),className:`rounded-full ${a} text-[12.5px] border transition-colors ${l?"bg-accent text-white border-accent font-semibold":"bg-bg-hi text-fg-dim border-line hover:border-fg-faint font-medium"}`,children:[c.label,c.count!==void 0&&t.jsxs("span",{children:[" ",c.count]})]},c.value)})})}function Kt(e,s=60){const n=e.trim();return n.length<=s?n:`${n.slice(0,s-1)}…`}function yn(e){return qe([e]).filter(s=>s.children.length===0).map(s=>s.row.slug)}function Yt(e){return e.nodes.map(s=>({rootSlug:s.row.slug,label:s.row.title||s.row.slug,terminals:yn(s)}))}function Nn(e){const s=new Map;for(const n of e){const a=Yt(n);n.nodes.forEach((c,l)=>{const i=a.filter((r,d)=>d!==l);for(const r of qe([c]))s.set(r.row.slug,i)})}return s}function Xt({job:e,headChoices:s}){const[n,a]=f.useState(!1),c=f.useCallback((l,i)=>{a(!0),window.api.schedule.setPrdDisposition({slug:e.slug,cwd:e.cwd??void 0,disposition:l,dependsOn:i}).then(q.fromOutcome).catch(()=>q.error("Failed to change disposition")).finally(()=>a(!1))},[e.slug,e.cwd]);return e.disposition!=="append"&&s.length===0?null:t.jsxs("select",{"data-testid":"job-row-disposition-control",disabled:n,value:"",onChange:l=>{const i=l.target.value;if(i==="__new-head__")c("new-head");else if(i){const r=s.find(d=>d.rootSlug===i);r&&c("append",r.terminals)}},className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border border-line/60 rounded px-1.5 py-0.5 cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed",title:"Change this wave's relationship to the rest of the Epic's plan",children:[t.jsx("option",{value:"",disabled:!0,children:"change disposition…"}),e.disposition==="append"&&t.jsx("option",{value:"__new-head__",children:"promote to new head"}),s.map(l=>t.jsxs("option",{value:l.rootSlug,children:["attach behind: ",Kt(l.label,40)]},l.rootSlug))]})}function kn(e,s,n=null){if(s.length===0||e.length===0)return e;const a=new Set,c=new Set;for(const i of e){a.add(i.slug);for(const r of bt(i))c.add(r)}const l=[];for(const i of s)i.archived!==!0||a.has(i.slug)||n&&i.cwd!==n||bt(i).some(r=>c.has(r))&&(a.add(i.slug),l.push({slug:i.slug,title:i.title,cwd:i.cwd,parallelGroup:i.parallelGroup,estimateMinutes:i.estimateMinutes,bodyPreview:"",status:i.archivedStatus??"completed",runId:null,startedAt:null,finishedAt:null,exitCode:null,error:null,dependsOn:i.dependsOn??void 0,sourcePromptId:i.sourcePromptId??null,epicId:i.epicId??null,synthetic:!0}));return l.length===0?e:[...e,...l]}const Sn=[],$n=new Set(["failed","needs_review","quarantined"]);function Cn(e){switch(e.status){case"completed":case"skipped":return"bg-sage";case"running":case"investigating":return"bg-accent";case"failed":return"bg-accent";case"needs_review":return"bg-butter";case"quarantined":return"bg-butter/60";default:return e.rowKind==="eta"||e.rowKind==="next"||e.rowKind==="retry"?"border border-fg-faint bg-transparent":"bg-fg-faint/40"}}function Pn(e){switch(e.status){case"running":case"investigating":return"bg-butter/10";case"failed":return"bg-accent/10";case"needs_review":return"bg-butter/25";default:return""}}function Dn(e){switch(e.rowKind){case"running":case"dep":case"failed":return"text-accent";case"review":return"text-butter font-semibold";default:return"text-fg-faint"}}function Mn({row:e,elapsedMs:s,listIndex:n,onFocused:a,headChoices:c=Sn}){const[l,i]=f.useState(!1),r=e.job,d=s!==null&&e.rowKind==="running"?Qt(r,s):e.rowTrailing,o=e.status==="completed"||e.status==="skipped",p=e.rowKind==="dep"&&e.blockers.some(h=>!h.missing&&h.status!==null&&$n.has(h.status)),u=o||p;return t.jsxs("div",{role:"listitem","data-testid":"prd-row","data-slug":e.slug,className:"border-t border-rule-inner first:border-t-0",children:[t.jsxs("button",{type:"button","data-job-row":!0,"data-job-status":r.status,"data-job-index":n,onClick:()=>i(h=>!h),onFocus:()=>a(n),"aria-expanded":l,"aria-label":`${e.prdNumber?`PRD ${e.prdNumber}, `:""}${r.title}, ${r.status}${d?`, ${d}`:""}`,title:r.title,className:`w-full h-[31px] py-1 px-2 text-left flex items-center gap-1.5 hover:bg-bg/40 focus:outline-none focus:ring-1 focus:ring-accent focus:ring-inset ${Pn(e)}`,children:[t.jsx("span",{"aria-hidden":"true",className:`shrink-0 w-[7px] h-[7px] rounded-full ${Cn(e)}`}),t.jsx("span",{className:"shrink-0 font-mono text-[10.5px] text-fg-faint w-[30px]",children:e.prdNumber?`#${e.prdNumber}`:""}),t.jsx("span",{className:`flex-1 min-w-0 truncate text-[12.5px] leading-tight ${u?"text-fg-faint":"text-fg font-medium"}`,children:r.title}),t.jsx("span",{"data-testid":"prd-row-trailing",className:`shrink-0 font-mono text-[10.5px] ${Dn(e)}`,children:d})]}),l&&t.jsx(An,{row:e,elapsedMs:s,headChoices:c})]})}const Zt=f.memo(Mn);function An({row:e,elapsedMs:s,headChoices:n}){const a=e.job,[c,l]=f.useState(!1),i=pe(g=>g.sessions),r=f.useMemo(()=>Pe(a,i),[a,i]),d=r.known&&r.epicId?i[r.epicId]:null,o=f.useCallback(g=>Tt(g),[]),p="font-mono text-[11.5px] text-fg-dim leading-snug break-words",u="text-[12px] font-semibold bg-transparent border-0 cursor-pointer p-0",h=a.error?a.error.split(`
|
|
3
|
-
`)[0]:null;return t.jsxs("div",{"data-testid":"prd-row-detail",className:"px-3 py-2 bg-bg-elev/50 border-t border-rule-inner flex flex-col gap-1",children:[t.jsxs("div",{className:p,children:[a.status.replace(/_/g," "),a.exitCode!==null&&` · exit ${a.exitCode}`,a.verifierVerdict&&` · ${Ce(a.verifierVerdict)}`,a.startedAt&&` · started ${le(Date.parse(a.startedAt))}`,a.finishedAt&&` · finished ${le(Date.parse(a.finishedAt))}`,s===null&&e.rowTrailing&&e.rowKind==="done"?` · took ${e.rowTrailing}`:""]}),e.cycle&&t.jsxs("div",{className:`${p} text-accent`,"data-testid":"job-row-cycle-warning",children:["⚠ dependsOn cycle — ",e.blockers.map(g=>g.slug).join(" ↔ ")||"self-referencing"]}),!e.cycle&&e.blockers.length>0&&t.jsxs("div",{className:p,"data-testid":"job-row-blockers",children:["depends on ",e.blockers.map(g=>`${g.slug} (${g.missing?"missing":(g.status??"unknown").replace(/_/g," ")})`).join(", ")]}),a.status==="pending"&&a.heldReason&&t.jsxs("div",{className:`${p} text-amber-400/90`,"data-testid":"job-row-held-reason",children:["held · ",a.heldReason]}),h&&t.jsx("div",{className:`${p} text-accent/80`,children:h}),!a.synthetic&&t.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 pt-0.5",children:[d&&t.jsx("button",{type:"button","data-testid":"job-row-prompt-session-link",title:d.goalText,onClick:()=>o(d.id),className:`${u} text-accent hover:text-accent/80`,children:"view epic →"}),a.runId&&t.jsx("button",{type:"button",onClick:()=>l(!0),className:`${u} text-fg-dim hover:text-fg`,children:"view log →"}),a.status==="quarantined"&&t.jsx("button",{type:"button","data-testid":"job-row-adopt-prd",title:"Stamp this PRD's provenance so the scheduler will run it — no unstamped PRD runs automatically.",onClick:()=>{window.api.schedule.adoptPrd(a.slug).then(q.fromOutcome).catch(()=>q.error("Failed to adopt PRD"))},className:`${u} text-accent hover:text-accent/80`,children:"adopt PRD →"}),a.status!=="pending"&&a.status!=="running"&&a.status!=="quarantined"&&t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resetJob(a.slug,a.cwd??void 0),className:`${u} text-fg-dim hover:text-fg`,children:"reset to pending →"}),a.disposition&&(a.status==="pending"||a.status==="quarantined")&&t.jsx(Xt,{job:a,headChoices:n})]}),c&&a.runId&&t.jsx(Fe,{runId:a.runId,slug:a.slug,title:a.title||a.slug,onClose:()=>l(!1)})]})}const ue=190,Rn=7,In=5,En=[],es=e=>e==="completed"||e==="skipped",ts=e=>e==="running"||e==="investigating",ss=e=>e==="failed"||e==="needs_review"||e==="quarantined";function Ae(e){return ts(e.status)?0:ss(e.status)?1:es(e.status)?3:2}const Tn={done:"text-sage",running:"text-accent",held:"text-fg-faint",pending:"text-fg-faint",blocked:"text-butter"},_n={done:"bg-sage",running:"bg-accent",held:"bg-fg-faint/50",pending:"bg-fg-faint/50",blocked:"bg-butter"};function On(e,s){return e.every(n=>es(n.status))?`+${e.length} done`:e.every(n=>n.rowKind==="dep"&&n.blockers.some(a=>!a.missing&&a.status!==null&&ss(a.status)))?`+${e.length} blocked`:`+${e.length} in stage ${s}`}function Ln({stage:e,epicId:s,now:n,hidden:a,indexBySlug:c,headChoicesBySlug:l,onRowFocused:i}){const[r,d]=f.useState(!1),o=f.useMemo(()=>e.rows.filter(m=>!(a.has(m.slug)&&(m.status==="completed"||m.status==="failed"))).map((m,T)=>({r:m,i:T})).sort((m,T)=>Ae(m.r)-Ae(T.r)||m.i-T.i).map(m=>m.r),[e.rows,a]),p=f.useMemo(()=>o.filter(m=>Ae(m)<=1).length,[o]),u=Math.max(e.state==="done"?In:Rn,p),h=r?o:o.slice(0,u),g=r?[]:o.slice(u),x=o.find(m=>m.status==="failed"),w=o.find(m=>m.status==="needs_review"),j=p>0&&(x!==void 0||w!==void 0),D=h.reduce((m,T,C)=>Ae(T)<=1?C:m,-1),k=m=>t.jsx(Zt,{row:m,elapsedMs:ts(m.status)&&m.job.startedAt?n-Date.parse(m.job.startedAt):null,listIndex:c.get(m.slug)??0,onFocused:i,headChoices:l.get(m.slug)??En},m.slug),E="flex-1 min-w-0 truncate h-[24px] text-[11.5px] font-medium text-fg-dim hover:text-fg border border-rule-structural rounded-sm bg-transparent cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed";return t.jsxs("div",{"data-testid":"stage-column","data-stage":e.n,style:{width:ue},className:"shrink-0 border-l border-rule-structural first:border-l-0 flex flex-col self-stretch",children:[t.jsxs("div",{className:"h-[30px] shrink-0 flex items-center gap-1.5 px-2 border-b border-rule-inner","data-testid":"stage-header",children:[t.jsx("span",{"aria-hidden":"true",className:`w-[7px] h-[7px] rounded-full shrink-0 ${_n[e.state]}`}),t.jsxs("span",{className:`text-[10px] font-semibold uppercase tracking-wide ${Tn[e.state]}`,children:["Stage ",e.n]}),e.state==="blocked"&&t.jsx(me,{title:"Rows in this stage are failed / need review / are quarantined, or wait on one that is."}),t.jsx("span",{"data-testid":"stage-summary",className:"ml-auto font-mono text-[10.5px] text-fg-dim truncate",children:e.summary})]}),t.jsx("div",{role:"presentation",children:h.map((m,T)=>t.jsxs("div",{children:[k(m),j&&T===D&&t.jsxs("div",{"data-testid":"stage-attention-actions",className:"flex gap-1.5 px-2 py-1.5 border-t border-rule-inner",children:[x&&t.jsxs("button",{type:"button","data-testid":"stage-retry",title:`Reset ${x.slug} to pending`,onClick:()=>{window.api.schedule.resetJob(x.slug,x.job.cwd??void 0).then(C=>{C.ok||q.error(C.error??`Failed to reset ${x.slug}`)}).catch(()=>q.error(`Failed to reset ${x.slug}`))},className:E,children:["Retry ",x.prdNumber?`#${x.prdNumber}`:x.slug]}),w&&t.jsxs("button",{type:"button","data-testid":"stage-review",disabled:!s,title:s?"Open the authoring Epic — a needs_review PRD is a question routed back to it":"No authoring Epic recorded for this plan",onClick:()=>{s&&Tt(s)},className:E,children:["Review ",w.prdNumber?`#${w.prdNumber}`:w.slug]})]})]},m.slug))}),(g.length>0||r&&o.length>u)&&t.jsx("button",{type:"button","data-testid":"stage-footer","aria-expanded":r,onClick:()=>d(m=>!m),className:"mt-auto h-[26px] border-t border-rule-inner font-mono text-[11px] text-fg-faint hover:text-fg-dim bg-transparent cursor-pointer",children:r?"show less ▴":`${On(g,e.n)} ▾`})]})}const we=6,Qe=4,Ee=4,$t=12,Ct=5,ns=2,Pt=4,Fn={done:"bg-sage",running:"bg-accent",attention:"bg-butter",failed:"bg-red-600",pending:"bg-fg-faint/50"};function qn(e){return e==="completed"||e==="skipped"?"done":e==="running"||e==="investigating"?"running":e==="failed"?"failed":e==="needs_review"||e==="quarantined"?"attention":"pending"}function Bn(e){const s=[],n=[],a=[];let c=Ct;for(const l of e){const i=Math.max(1,Math.ceil(l.rows.length/Ee));n.push(c),a.push(i*we),l.rows.forEach((r,d)=>{s.push({x:c+Math.floor(d/Ee)*we,y:ns+d%Ee*we,tone:qn(r.status),title:`${r.prdNumber?`#${r.prdNumber}`:r.slug} ${r.title} — ${r.status}`})}),c+=i*we+$t}return{dots:s,stageX:n,stageW:a,width:Math.max(0,c-$t)+Ct}}function ve(e,s){return e.findIndex(n=>n.rows.some(a=>s(a.status)))}const Ze=e=>e==="running"||e==="investigating",et=e=>e==="failed"||e==="needs_review"||e==="quarantined";function Hn({stages:e,first:s,perView:n,onSeek:a}){const c=f.useMemo(()=>Bn(e),[e]),l=f.useMemo(()=>ve(e,Ze)>=0,[e]),i=f.useMemo(()=>ve(e,et)>=0,[e]),r=f.useRef(!1),d=e.length,o=Math.min(d-1,s+n-1),p=c.stageX[Math.min(s,d-1)]??0,u=(c.stageX[o]??0)+(c.stageW[o]??0),h=x=>{const w=x.currentTarget.getBoundingClientRect(),j=x.clientX-w.left;let D=0;for(let k=0;k<d;k++)c.stageX[k]<=j&&(D=k);a(Math.max(0,Math.min(d-1,D-Math.floor(n/2))))},g="px-2 h-[20px] text-[11.5px] disabled:opacity-40 disabled:cursor-not-allowed";return t.jsxs("div",{"data-testid":"plan-minimap",className:"h-[28px] flex items-center gap-3 px-3 border-t border-rule-inner",children:[t.jsxs("span",{className:"shrink-0 flex items-center gap-1 text-[10.5px] font-semibold uppercase tracking-wide text-fg-faint",children:["Whole graph",t.jsx(me,{title:"Every PRD in this plan as one dot, grouped by stage. The rust box is the range of stages shown below — drag it to scroll."})]}),t.jsxs("div",{"data-testid":"plan-minimap-dots",role:"presentation",className:"relative shrink min-w-0 overflow-hidden cursor-ew-resize touch-none",style:{width:c.width,height:Ee*we-(we-Qe)+2*ns},onPointerDown:x=>{var w,j;r.current=!0,(j=(w=x.currentTarget).setPointerCapture)==null||j.call(w,x.pointerId),h(x)},onPointerMove:x=>{r.current&&h(x)},onPointerUp:()=>{r.current=!1},onPointerCancel:()=>{r.current=!1},children:[c.dots.map((x,w)=>t.jsx("span",{title:x.title,"data-tone":x.tone,className:`absolute rounded-[1px] ${Fn[x.tone]}`,style:{left:x.x,top:x.y,width:Qe,height:Qe}},w)),t.jsx("span",{"data-testid":"plan-minimap-brush","aria-hidden":"true",className:"absolute top-0 bottom-0 border border-accent bg-accent/10 rounded-[2px] pointer-events-none",style:{left:p-Pt,width:u-p+2*Pt}})]}),t.jsxs("span",{className:"ml-auto shrink-0 font-mono text-[11.5px] text-fg-faint","data-testid":"plan-minimap-range",children:["stages ",Math.min(s+1,d),"–",o+1," of ",d]}),t.jsxs("span",{className:"shrink-0 inline-flex border border-line rounded overflow-hidden",role:"group","aria-label":"Jump the stage window",children:[t.jsx("button",{type:"button","data-testid":"minimap-running",disabled:!l,title:l?"Scroll to the lowest stage with a running PRD":"No stage has a running PRD",onClick:()=>a(ve(e,Ze)),className:`${g} text-fg-dim hover:text-fg`,children:"Running"}),t.jsx("button",{type:"button","data-testid":"minimap-blockers",disabled:!i,title:i?"Scroll to the lowest stage with a failed / needs-review / quarantined PRD":"No stage has a failed, needs-review or quarantined PRD",onClick:()=>a(ve(e,et)),className:`${g} text-fg-dim hover:text-fg border-l border-line`,children:"Blockers"})]})]})}const Gn=148;function Vn({stages:e,onSeek:s}){if(e.length===0)return null;const n=e[0].n,a=e[e.length-1].n;return t.jsxs("div",{"data-testid":"further-stages",style:{width:Gn},className:"shrink-0 border-l border-rule-structural flex flex-col",children:[t.jsxs("div",{className:"h-[30px] shrink-0 flex items-center px-2 border-b border-rule-inner text-[10.5px] font-semibold uppercase tracking-wide text-fg-faint",children:["Stage ",n,"–",a]}),t.jsxs("div",{className:"h-[22px] shrink-0 flex items-center gap-1 px-2 text-[10.5px] font-semibold uppercase tracking-wide text-fg-faint",children:["Further stages",t.jsx(me,{title:"Stages beyond the visible window. Click one to scroll the stage columns to it."})]}),e.map(c=>{const l=c.rows.length===0?0:c.doneCount/c.rows.length*100;return t.jsxs("button",{type:"button","data-testid":"further-stage-row","data-stage":c.n,title:`${c.summary} — scroll to stage ${c.n}`,onClick:()=>s(c.n-1),className:"h-[26px] px-2 flex items-center gap-2 border-t border-rule-inner bg-transparent hover:bg-bg-hi cursor-pointer text-left",children:[t.jsxs("span",{className:"font-mono text-[10.5px] text-fg-dim w-[50px] whitespace-nowrap shrink-0",children:["stage ",c.n]}),t.jsx("span",{role:"progressbar","aria-valuenow":c.doneCount,"aria-valuemin":0,"aria-valuemax":c.rows.length,className:"flex-1 h-[4px] rounded-sm bg-rule-inner overflow-hidden",children:t.jsx("span",{className:"block h-full bg-sage",style:{width:`${l}%`}})})]},c.n)})]})}const Un=[],Wn=e=>e==="running"||e==="investigating";function Qn(e){const s=dn(e),n=new Map,a=new Map;for(const r of e.stages){a.set(r.n,r.rows.length);for(const d of r.rows)n.set(d.slug,d)}const c=new Map;let l=0;const i=[];for(const r of s){const d=n.get(r);l+=d.estimateMinutes??0,c.set(d.stage,(c.get(d.stage)??0)+1),i.push({row:d,totalMinutes:l,othersInStage:0})}for(const r of i)r.othersInStage=(a.get(r.row.stage)??0)-(c.get(r.row.stage)??0);return i}function zn({plan:e,now:s,indexBySlug:n,headChoicesBySlug:a,onRowFocused:c}){const l=f.useMemo(()=>Qn(e),[e]);return t.jsx("div",{"data-testid":"critical-path",className:"border-t border-rule-structural max-w-[640px]",children:l.map(({row:i,totalMinutes:r,othersInStage:d})=>t.jsxs("div",{"data-testid":"critical-entry","data-slug":i.slug,children:[t.jsxs("div",{className:"flex items-start",children:[t.jsx("div",{className:"flex-1 min-w-0",children:t.jsx(Zt,{row:i,elapsedMs:Wn(i.status)&&i.job.startedAt?s-Date.parse(i.job.startedAt):null,listIndex:n.get(i.slug)??0,onFocused:c,headChoices:a.get(i.slug)??Un})}),t.jsxs("span",{"data-testid":"critical-est",className:"shrink-0 h-[31px] px-3 flex items-center gap-2 font-mono text-[11.5px] text-fg-faint border-t border-rule-inner",children:[t.jsx("span",{title:"estimateMinutes",children:i.estimateMinutes?`${i.estimateMinutes}m`:"—"}),t.jsxs("span",{className:"text-fg-dim",title:"Running total along the chain",children:["Σ ",r,"m"]})]})]}),d>0&&t.jsxs("div",{"data-testid":"critical-others",className:"h-[22px] px-3 flex items-center font-mono text-[11.5px] text-fg-faint border-t border-rule-inner",children:["stage ",i.stage," · +",d," not on the critical path"]})]},i.slug))})}const Dt=1,Mt=1350,Jn={active:"border-l-accent",queued:"border-l-rule-structural",done:"border-l-sage",draft:"border-l-fg-faint/40 border-dashed"},Kn={active:{label:"ACTIVE",cls:"bg-accent text-white border border-accent"},queued:{label:"QUEUED",cls:"text-fg-dim border border-fg-faint"},done:{label:"DONE",cls:"text-sage-dark border border-sage"},draft:{label:"DRAFT",cls:"text-fg-faint border border-dashed border-fg-faint"}},Yn=e=>String(e).padStart(2,"0");function Xn({plan:e}){const s=Math.max(1,e.prdCount),n=e.doneCount/s*100,a=e.runningCount/s*100;return t.jsxs("span",{"data-testid":"plan-progress",role:"progressbar","aria-valuenow":e.doneCount,"aria-valuemin":0,"aria-valuemax":e.prdCount,className:"flex w-[160px] h-[5px] rounded-sm overflow-hidden bg-rule-inner shrink-0",children:[t.jsx("span",{className:"h-full bg-sage",style:{width:`${n}%`}}),t.jsx("span",{className:"h-full bg-accent",style:{width:`${a}%`}})]})}function Zn({plan:e,mode:s="graph",now:n,hidden:a,indexBySlug:c,headChoicesBySlug:l,onRowFocused:i,onOpenPrds:r}){var se,z;const[d,o]=f.useState(e.status==="active"||e.status==="queued"),[p,u]=f.useState(!1),h=f.useRef(null),[g,x]=f.useState(0),[w,j]=f.useState(Mt),D=f.useMemo(()=>{const A=ve(e.stages,Ze);return A>=0?A:Math.max(0,ve(e.stages,et))},[e.stages]);f.useLayoutEffect(()=>{if(!d)return;const A=h.current,B=(A==null?void 0:A.clientWidth)||Mt,N=Math.max(0,Math.min(D,e.stageCount-Math.max(1,Math.ceil(B/ue))));A!=null&&A.clientWidth&&j(A.clientWidth),A&&(A.scrollLeft=N*ue),x(N)},[d]);const k=f.useMemo(()=>{let A=null;for(const B of e.stages)for(const N of B.rows){if(!N.job.runId)continue;const S=N.job.finishedAt?Date.parse(N.job.finishedAt):0;(!A||S>A.at)&&(A={runId:N.job.runId,slug:N.slug,title:N.title,at:S})}return A},[e.stages]),E=Te((z=(se=e.stages[0])==null?void 0:se.rows[0])==null?void 0:z.job.cwd)??"—",m=Kn[e.status],T=Math.max(1,Math.ceil(w/ue)),C=Math.max(0,Math.min(g-Dt,e.stageCount)),P=Math.min(e.stageCount,g+T+Dt),O=A=>{const B=Math.max(0,Math.min(e.stageCount-1,A));h.current&&(h.current.scrollLeft=B*ue),x(B)},K=Math.min(e.stageCount,g+T),U=A=>{const B=A.currentTarget,N=Math.floor(B.scrollLeft/ue);N!==g&&x(N),B.clientWidth&&B.clientWidth!==w&&j(B.clientWidth)},Q="h-[24px] px-3 text-[12px] font-medium text-fg border border-rule-structural rounded-sm bg-transparent hover:bg-bg-hi cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed shrink-0",Y=(()=>{switch(e.status){case"active":return t.jsx("button",{type:"button","data-testid":"plan-action",title:"Pauses the WHOLE scheduler (machine-wide) — there is no per-plan pause.",onClick:()=>{window.api.schedule.pause().catch(()=>q.error("Failed to pause the scheduler"))},className:Q,children:"Pause plan"});case"queued":return t.jsx("button",{type:"button","data-testid":"plan-action",title:"Fires the next scheduler batch machine-wide (force tick) — it does not target this plan.",onClick:()=>{window.api.schedule.forceTick().then(q.fromOutcome).catch(()=>q.error("Failed to fire the next batch"))},className:Q,children:"Run now"});case"done":return t.jsx("button",{type:"button","data-testid":"plan-action",disabled:!k,title:k?`Open the run log of ${k.slug}, the plan's last run`:"No run log recorded for this plan",onClick:()=>u(!0),className:Q,children:"View run"});case"draft":return t.jsx("button",{type:"button","data-testid":"plan-action",title:"Open the PRDs sub-view on this plan's first PRD (the PRDs view has no per-Epic filter).",onClick:()=>{var A,B;return r==null?void 0:r(((B=(A=e.stages[0])==null?void 0:A.rows[0])==null?void 0:B.slug)??null)},className:Q,children:"Schedule…"})}})(),te=e.etaMs>0?` · ${Wt(e.etaMs)} left`:"";return t.jsxs("section",{"data-testid":"plan-band","data-epic-id":e.epicId??"","data-plan-status":e.status,className:`border-l-[3px] ${Jn[e.status]} border-b border-rule-structural`,children:[t.jsxs("div",{className:"h-[32px] flex items-center gap-2.5 px-3","data-testid":"plan-header",children:[t.jsx("button",{type:"button","aria-expanded":d,"aria-label":d?"Collapse plan":"Expand plan","data-testid":"plan-toggle",onClick:()=>o(A=>!A),className:"shrink-0 w-[14px] text-[11px] text-fg-faint hover:text-fg bg-transparent border-0 cursor-pointer p-0",children:d?"▾":"▸"}),t.jsx("span",{className:"font-mono text-[11.5px] text-fg-faint shrink-0",children:Yn(e.index)}),t.jsx("span",{className:"font-serif text-[15px] font-bold text-fg truncate shrink-0 max-w-[320px]",title:e.epicLabel!==e.label?`${e.label} — ${e.epicLabel}`:e.label,"data-testid":"plan-label",children:e.label}),t.jsx("span",{"data-testid":"plan-chip",className:`shrink-0 rounded-sm px-1.5 py-[1px] text-[10px] font-bold tracking-wide ${m.cls}`,children:m.label}),t.jsx("span",{"aria-hidden":"true",className:"shrink-0 w-px h-[16px] bg-rule-structural"}),t.jsx("span",{className:"font-mono text-[11.5px] text-fg-faint truncate min-w-0","data-testid":"plan-meta",children:e.validateSlug!=null&&e.epicLabel!==e.label?t.jsxs(t.Fragment,{children:[E," · ",e.epicLabel," · ",e.prdCount," PRD",e.prdCount===1?"":"s"," · ",e.width," wide · ",e.stageCount," stage",e.stageCount===1?"":"s"]}):t.jsxs(t.Fragment,{children:[E," · ",e.prdCount," PRD",e.prdCount===1?"":"s",e.width>1?` · ${e.width} wide`:""," · ",e.stageCount," stage",e.stageCount===1?"":"s"]})}),t.jsx(me,{title:`${e.doneCount} done · ${e.runningCount} running · ${e.heldCount} held · ${e.blockedCount} blocked`}),t.jsxs("span",{className:"ml-auto font-mono text-[11.5px] text-fg-dim shrink-0","data-testid":"plan-progress-label",children:[e.doneCount,"/",e.prdCount,te]}),t.jsx(Xn,{plan:e}),Y]}),d&&s==="critical"&&t.jsx(zn,{plan:e,now:n,indexBySlug:c,headChoicesBySlug:l,onRowFocused:i}),d&&s!=="critical"&&e.status==="active"&&t.jsx(Hn,{stages:e.stages,first:g,perView:T,onSeek:O}),d&&s!=="critical"&&t.jsxs("div",{className:"flex border-t border-rule-structural",children:[t.jsxs("div",{ref:h,"data-testid":"plan-stages",onScroll:U,className:"flex flex-1 min-w-0 overflow-x-auto",children:[C>0&&t.jsx("div",{"aria-hidden":"true",className:"shrink-0",style:{width:C*ue}}),e.stages.slice(C,P).map(A=>t.jsx(Ln,{stage:A,epicId:e.epicId,now:n,hidden:a,indexBySlug:c,headChoicesBySlug:l,onRowFocused:i},A.n)),P<e.stageCount&&t.jsx("div",{"aria-hidden":"true",className:"shrink-0",style:{width:(e.stageCount-P)*ue}})]}),t.jsx(Vn,{stages:e.stages.slice(K),onSeek:O})]}),p&&k&&t.jsx(Fe,{runId:k.runId,slug:k.slug,title:k.title||k.slug,onClose:()=>u(!1)})]})}function ea({page:e,pageSize:s,totalItems:n,onPageChange:a}){if(n<=s)return null;const c=Math.max(1,Math.ceil(n/s)),l=(e-1)*s+1,i=Math.min(e*s,n);return t.jsxs("div",{"data-testid":"plan-pager",className:"flex items-center justify-center gap-3 px-[18px] py-3 font-mono text-[12px] text-fg-faint",children:[t.jsx("button",{type:"button","data-testid":"plan-pager-prev",onClick:()=>a(e-1),disabled:e<=1,className:"px-2 py-1 rounded border border-line bg-bg-hi text-fg-dim hover:text-fg disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer",children:"Prev"}),t.jsxs("span",{"data-testid":"plan-pager-range",children:[l,"–",i," of ",n]}),t.jsx("button",{type:"button","data-testid":"plan-pager-next",onClick:()=>a(e+1),disabled:e>=c,className:"px-2 py-1 rounded border border-line bg-bg-hi text-fg-dim hover:text-fg disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer",children:"Next"})]})}function ta({section:e,children:s}){const[n,a]=f.useState(!0),c=Object.entries(e.counts).map(([l,i])=>`${i} ${l.replace(/_/g," ")}`).join(" · ");return t.jsxs("div",{className:"border-t border-line","data-testid":"backlog-epic-section","data-epic-id":e.epicId??"",children:[t.jsxs("button",{type:"button",onClick:()=>a(l=>!l),className:"w-full flex items-center gap-2.5 px-[18px] py-2.5 bg-bg-elev/60 hover:bg-bg-elev text-left","aria-expanded":n,title:e.label,children:[t.jsx("span",{className:`text-fg-faint inline-flex shrink-0 transition-transform duration-150 ${n?"rotate-90":""}`,"aria-hidden":"true",children:t.jsx(st,{name:"chevron",size:12})}),t.jsx("span",{className:"font-serif text-[14.5px] font-semibold text-fg truncate","data-testid":"backlog-epic-label",children:e.label}),t.jsxs("span",{className:"font-mono text-[11px] text-fg-faint shrink-0",children:[e.total," PRD",e.total===1?"":"s"]}),t.jsx("span",{className:"font-mono text-[11px] text-fg-faint truncate",children:c})]}),n&&s]})}const sa=[],na=[],aa={depth:0,blockers:sa,blocked:!1,hasNeedsReviewBlocker:!1,hasMissingDep:!1,cycle:!1,parallelEligible:!1};function ra(e){return e.missing?`${e.slug} (missing)`:e.needsReview?`${e.slug} (needs review)`:`${e.slug} (${(e.status??"unknown").replace(/_/g," ")})`}function ia(e){return e.missing?"text-accent":e.needsReview?"text-butter font-semibold":e.status==="completed"?"text-sage":"text-amber-400/90"}function la({job:e,eta:s,elapsedMs:n,avgDurationMs:a,listIndex:c,onFocused:l,hold:i,backlog:r=aa,headChoices:d=na}){const[o,p]=f.useState(!1),[u,h]=f.useState(!1),g=pe(P=>P.sessions),x=f.useMemo(()=>Pe(e,g),[e,g]),w=x.known&&x.epicId?g[x.epicId]:null,j=f.useCallback(P=>{nt(P),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"terminal"}))},[]),D=e.status==="running",k=e.status==="failed";let E=null;D&&n!==null?E=`${wt(n)} elapsed`:e.status==="completed"&&e.startedAt&&e.finishedAt?E=`took ${$e(Date.parse(e.finishedAt)-Date.parse(e.startedAt))}`:s&&(E=s);const m=e.error??null,T=k&&m?m.split(`
|
|
4
|
-
`)[0]:e.status==="needs_review"&&e.verifierVerdict
|
|
5
|
-
`)[0],wrap:!0})]}),e.statusHistory&&e.statusHistory.length>0&&t.jsx(re,{label:"History",children:t.jsx("div",{className:"grid gap-1",children:e.statusHistory.map((P,O)=>t.jsxs("div",{className:"font-mono text-xs leading-relaxed",children:[t.jsxs("div",{className:"text-fg",children:[P.from??"(new)"," → ",P.to,t.jsxs("span",{className:"text-fg-faint",children:[" · ",le(Date.parse(P.at))]})]}),P.reason&&t.jsx("div",{className:"text-fg-faint break-words",children:P.reason})]},O))})}),t.jsxs(re,{label:"Timing",children:[t.jsx(H,{k:"started",v:e.startedAt?le(Date.parse(e.startedAt)):"—"}),t.jsx(H,{k:"finished",v:e.finishedAt?le(Date.parse(e.finishedAt)):"—"}),t.jsx(H,{k:"duration",v:e.startedAt&&e.finishedAt?$e(Date.parse(e.finishedAt)-Date.parse(e.startedAt)):D&&n!==null?wt(n):"—"})]}),t.jsxs(re,{label:"Location",children:[t.jsx(H,{k:"group",v:`${e.parallelGroup} · ${e.slug}`}),t.jsx(H,{k:"cwd",v:e.cwd??"—",wrap:!0}),t.jsx(H,{k:"session",v:x.label??x.epicId??"—",wrap:!0}),t.jsx(H,{k:"session id",v:x.epicId??"—",wrap:!0}),t.jsx(H,{k:"prompt id",v:e.sourcePromptId??"—",wrap:!0}),t.jsx(H,{k:"source tab",v:e.sourceTabId??"—",wrap:!0})]}),t.jsx(re,{label:"Actions",children:t.jsxs("div",{className:"flex flex-col gap-1.5 items-start",children:[w&&t.jsx("button",{type:"button","data-testid":"job-row-prompt-session-link",title:w.goalText,onClick:()=>j(w.id),className:"text-[13px] font-semibold text-accent hover:text-accent/80 bg-transparent border-0 cursor-pointer p-0",children:"view epic →"}),e.runId&&t.jsx("button",{type:"button",onClick:()=>h(!0),className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border-0 cursor-pointer p-0",children:"view log →"}),e.status==="quarantined"&&t.jsx("button",{type:"button","data-testid":"job-row-adopt-prd",title:"Stamp this PRD's provenance so the scheduler will run it — no unstamped PRD runs automatically.",onClick:()=>{window.api.schedule.adoptPrd(e.slug).then(q.fromOutcome).catch(()=>q.error("Failed to adopt PRD"))},className:"text-[13px] font-semibold text-accent hover:text-accent/80 bg-transparent border-0 cursor-pointer p-0",children:"adopt PRD →"}),e.status!=="pending"&&e.status!=="running"&&e.status!=="quarantined"&&t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resetJob(e.slug,e.cwd??void 0),className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border-0 cursor-pointer p-0",children:"reset to pending →"}),e.disposition&&(e.status==="pending"||e.status==="quarantined")&&t.jsx(Xt,{job:e,headChoices:d})]})})]}),u&&e.runId&&t.jsx(Fe,{runId:e.runId,slug:e.slug,title:e.title||e.slug,onClose:()=>h(!1)})]})}const oa=f.memo(la);function da({supervisorConfig:e,onSetConfig:s,onBack:n}){const[a,c]=f.useState([]),[l,i]=f.useState(()=>Date.now()),r=tt();f.useEffect(()=>{if(!r)return;window.api.supervisor.getLog().then(c).catch(()=>{}),i(Date.now());const o=setInterval(()=>i(Date.now()),5e3);return()=>clearInterval(o)},[r]);const d={enabled:(e==null?void 0:e.enabled)??!0,intervalMinutes:(e==null?void 0:e.intervalMinutes)??15,maxConcurrentProbes:(e==null?void 0:e.maxConcurrentProbes)??2,probeStaleThresholdMinutes:(e==null?void 0:e.probeStaleThresholdMinutes)??10};return t.jsxs("div",{className:"bg-bg-elev/60",children:[t.jsxs("div",{className:"px-3 py-2 flex items-center gap-2 border-b border-line",children:[t.jsx("button",{type:"button",onClick:n,className:"text-[10px] text-fg-faint hover:text-fg-dim",title:"Back to queue",children:"← queue"}),t.jsx("span",{className:"text-[11px] font-medium text-fg-dim",children:"Supervisor"}),t.jsx("button",{type:"button",onClick:()=>window.api.supervisor.getLog().then(c).catch(()=>{}),className:"ml-auto text-[10px] text-fg-faint hover:text-fg-dim underline",title:"Refresh log",children:"refresh"})]}),t.jsxs("div",{className:"px-3 py-2 space-y-1.5 border-b border-line",children:[t.jsx("div",{className:"text-[9px] text-fg-faint uppercase tracking-wider",children:"Config"}),t.jsxs("div",{className:"flex items-center gap-3 flex-wrap text-[10px] text-fg-faint",children:[t.jsxs("label",{className:"flex items-center gap-1",children:[t.jsx("input",{type:"checkbox",checked:d.enabled,onChange:o=>s({enabled:o.target.checked}),className:"cursor-pointer"}),t.jsx("span",{children:"enabled"})]}),t.jsxs("label",{className:"flex items-center gap-1",title:"How often to check for wedged jobs (minutes)",children:[t.jsx("span",{children:"interval"}),t.jsx("input",{type:"number",min:5,max:60,value:d.intervalMinutes,onChange:o=>s({intervalMinutes:Number(o.target.value)}),className:"w-10 bg-bg border border-line rounded px-1 py-0.5 font-mono"}),t.jsx("span",{children:"min"})]}),t.jsxs("label",{className:"flex items-center gap-1",title:"Max concurrent Opus probes per tick",children:[t.jsx("span",{children:"probes"}),t.jsx("input",{type:"number",min:1,max:5,value:d.maxConcurrentProbes,onChange:o=>s({maxConcurrentProbes:Number(o.target.value)}),className:"w-8 bg-bg border border-line rounded px-1 py-0.5 font-mono"})]}),t.jsxs("label",{className:"flex items-center gap-1",title:"Probe a job only if no JSONL event in this many minutes",children:[t.jsx("span",{children:"stale"}),t.jsx("input",{type:"number",min:5,max:30,value:d.probeStaleThresholdMinutes,onChange:o=>s({probeStaleThresholdMinutes:Number(o.target.value)}),className:"w-8 bg-bg border border-line rounded px-1 py-0.5 font-mono"}),t.jsx("span",{children:"min"})]})]})]}),t.jsxs("div",{className:"px-3 py-2",children:[t.jsxs("div",{className:"text-[9px] text-fg-faint uppercase tracking-wider mb-1",children:["Recent probes (last ",a.length,")"]}),a.length===0?t.jsx("div",{className:"text-[10px] text-fg-faint italic",children:"No probes yet."}):t.jsx("div",{className:"space-y-0.5 max-h-64 overflow-y-auto",children:a.map((o,p)=>t.jsx(ca,{entry:o,now:l},`${o.ts}-${p}`))})]})]})}function ca({entry:e,now:s}){const n=e.action!=="none",a=ee(s-e.ts);return t.jsxs("div",{className:`text-[10px] px-1.5 py-1 rounded font-mono ${n?"bg-red-500/10 border border-red-500/20":"bg-bg/40"}`,title:e.reason,children:[t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsxs("span",{className:"text-fg-faint shrink-0",children:[a," ago"]}),t.jsx("span",{className:`shrink-0 px-1 rounded ${e.verdict==="stuck"?"text-red-400 bg-red-500/10":"text-green-500/70"}`,children:e.verdict}),t.jsx("span",{className:"truncate text-fg-dim",children:e.jobSlug}),n&&t.jsxs("span",{className:"shrink-0 text-red-400",children:[e.action,e.targetPid?` pid=${e.targetPid}`:""]}),e.costUsd!==null&&t.jsxs("span",{className:"shrink-0 text-fg-faint",children:["$",e.costUsd.toFixed(3)]})]}),t.jsx("div",{className:"text-fg-faint truncate mt-0.5",children:e.reason})]})}const ua=[{title:"Start a session",body:"In Sessions, pick an Agent and a Mission, describe the outcome you want, then Approve & start. Its thread writes the PRD files into that session's own folder."},{title:"Queue what it wrote",body:"The PRDs tab lists every file the session produced. Queue one, or the whole session, and they appear here."},{title:"Leave it alone",body:"Jobs start themselves inside your window, pause on rate-limit, and resume at the reset. History records how each ended."}],pa=[{term:"Session",def:"One goal, one Claude session, and the folder of PRDs written to reach it."},{term:"PRD",def:"One markdown file = one job. Authored by the session."},{term:"5-hour window",def:"Your Claude billing window, on a rolling clock."},{term:"Session pool",def:"5 slots shared with terminal and session chats."}];function fa({navigate:e}){return t.jsx("div",{className:"overflow-y-auto h-full",children:t.jsx("div",{className:"px-9 py-6 max-w-[900px] mx-auto",children:t.jsxs("div",{className:"bg-bg-hi border border-line rounded-2xl px-9 py-8",children:[t.jsx("h2",{className:"m-0 font-serif text-[25px] font-semibold text-fg",children:"Nothing to run yet — the scheduler needs a session."}),t.jsx("p",{className:"mt-2 mb-6 text-[14.5px] text-fg-dim leading-relaxed max-w-[580px]",children:"You don't write PRDs here. A session breaks its goal into numbered PRD files, and this page runs them in order. Two steps, once."}),t.jsx("div",{className:"grid grid-cols-3 gap-3.5",children:ua.map((s,n)=>{const a=n===0;return t.jsxs("div",{className:`bg-bg border rounded-xl px-4 py-4 flex flex-col gap-2 ${a?"border-accent shadow-[0_0_0_3px_rgba(184,92,52,.09)]":"border-line"}`,children:[t.jsx("span",{className:`w-6 h-6 rounded-full grid place-items-center font-mono text-[12px] font-semibold ${a?"bg-accent text-white":"bg-bg-elev text-fg-dim"}`,children:n+1}),t.jsx("h3",{className:"m-0 text-[15px] font-semibold text-fg",children:s.title}),t.jsx("p",{className:"m-0 text-[13.5px] text-fg-dim leading-relaxed",children:s.body}),a&&t.jsx("button",{type:"button",onClick:()=>e==null?void 0:e("terminal"),className:"self-start bg-accent text-white rounded-lg px-3.5 py-1.5 text-[13px] font-semibold mt-1",children:"Go to Sessions →"})]},s.title)})}),t.jsx("dl",{className:"flex mt-[22px] pt-4 border-t border-line gap-5 flex-wrap",children:pa.map(({term:s,def:n})=>t.jsxs("div",{className:"flex-1 min-w-[150px]",children:[t.jsx("dt",{className:"text-[13.5px] font-semibold text-fg mb-0.5",children:s}),t.jsx("dd",{className:"m-0 text-[12.5px] text-fg-faint leading-relaxed",children:n})]},s))})]})})})}const ha=5e3;let Re=null,Ne=null;async function At(e){const s=Date.now();return!(e!=null&&e.fresh)&&Re&&s-Re.at<ha?Re.result:Ne||(Ne=(async()=>{try{const n=await window.api.schedule.lintQueue();return Re={result:n,at:Date.now()},n}finally{Ne=null}})(),Ne)}function ga({health:e,jobCount:s,lastRunAt:n,nextReset:a,now:c,onOpenSupervisor:l}){const[i,r]=f.useState(!1),[d,o]=f.useState(null),[p,u]=f.useState(!1),h=`${s}:${n??""}`;f.useEffect(()=>{let C=!0;return u(!0),At().then(P=>{C&&o(P)}).catch(()=>{}).finally(()=>{C&&u(!1)}),()=>{C=!1}},[h]);let g=0,x=0;const w=d?d.reports.filter(C=>C.findings.length>0):[];for(const C of w)for(const P of C.findings)P.severity==="error"?g++:x++;const j=g===0&&x===0,D=d?`graph lint ${g} error${g===1?"":"s"}, ${x} warn${x===1?"":"s"}`:`graph lint ${p?"scanning…":"idle"}`,k=(e==null?void 0:e.consecutiveFailures)??0,m=[e?`${k} poll failure${k===1?"":"s"} in current streak`:null,D].filter(Boolean).join(" · "),T="text-accent hover:underline bg-transparent border-0 p-0 cursor-pointer text-[12px]";return t.jsxs("div",{"data-testid":"scheduler-footer",className:"border-t border-rule-structural",children:[t.jsxs("div",{className:"h-[28px] flex items-center gap-2 px-[18px] font-mono text-[11.5px] text-fg-faint",children:[t.jsx("span",{"data-testid":"footer-summary",className:"truncate",children:m}),t.jsx("button",{type:"button","data-testid":"footer-info","aria-expanded":i,onClick:()=>r(C=>!C),className:"bg-transparent border-0 p-0 cursor-pointer",children:t.jsx(me,{title:"Scheduler poll health and queue-lint findings — click for the full detail"})}),t.jsxs("span",{className:"ml-auto flex items-center gap-3 shrink-0",children:[t.jsxs("span",{"data-testid":"footer-timing",children:[a?t.jsxs("span",{title:`next 5h reset: ${a}`,children:["reset ",ee(Date.parse(a)-c)]}):null,a&&n?" · ":null,n?t.jsxs("span",{title:n,children:["last run ",ee(c-Date.parse(n))," ago"]}):null]}),t.jsx("button",{type:"button","data-testid":"footer-supervisor",onClick:l,title:"Open supervisor log and settings",className:T,children:"supervisor"}),t.jsx("button",{type:"button","data-testid":"footer-folder",onClick:()=>window.api.schedule.openFolder(),className:T,children:"folder"})]})]}),i&&t.jsxs("div",{"data-testid":"footer-detail",className:"px-[18px] pb-2 space-y-2 font-mono text-[12px] text-fg-dim border-t border-rule-inner pt-2",children:[e&&t.jsxs("div",{className:"space-y-0.5",children:[t.jsxs("div",{children:["booted: ",xe(e.bootedAt,c)]}),t.jsxs("div",{children:["last poll: ",xe(e.lastPollAt,c)," · ",e.lastPollOk?"ok":"failed"]}),e.backoffNextAt!==null&&e.backoffNextAt>c&&t.jsxs("div",{children:["retry in: ",ee(e.backoffNextAt-c)]}),e.nextResetCached&&t.jsxs("div",{children:["cached reset: ",le(Date.parse(e.nextResetCached))]}),e.runningJobs.length>0&&t.jsxs("div",{children:["running: ",e.runningJobs.map(C=>`${C.slug}(pid ${C.pid})`).join(", ")]})]}),d&&t.jsxs("div",{className:"space-y-1",children:[j?t.jsxs("div",{className:"text-sage",children:["✓ no issues in ",d.reports.length," PRD",d.reports.length!==1?"s":""]}):w.map(C=>t.jsxs("div",{children:[t.jsx("div",{className:"text-fg-dim truncate",title:C.slug,children:C.slug}),C.findings.map((P,O)=>t.jsxs("div",{className:`pl-3 truncate ${P.severity==="error"?"text-accent/80":"text-butter/90"}`,title:P.snippet,children:[P.severity==="error"?"✗":"⚠"," L",P.line,": ",P.snippet]},`${C.slug}-${O}`))]},C.slug)),t.jsx("button",{type:"button","data-testid":"footer-rerun-lint",onClick:()=>{u(!0),At({fresh:!0}).then(o).catch(()=>{}).finally(()=>u(!1))},className:"text-fg-faint hover:text-fg-dim underline",children:p?"…":"rerun lint"})]})]})]})}const xa=5,ma=1440*60*1e3,Ie=10,ba=["all","running","investigating","pending","completed","skipped","needs_review","failed","quarantined"];async function wa(e){if(!e)return{text:"",status:"all"};const s=await qt(e);return{text:"",status:ba.includes(s.queueFilterStatus)?s.queueFilterStatus:"all"}}function va(e,s){return e?Bt(e,{queueFilterStatus:s.status}):Promise.resolve()}function Rt(e,s){if(s.status==="all"&&!s.text)return e;const n=s.text.toLowerCase();return e.filter(a=>{if(s.status!=="all"&&a.status!==s.status)return!1;if(!n)return!0;const c=Te(a.cwd)??"";return a.title.toLowerCase().includes(n)||a.slug.toLowerCase().includes(n)||c.toLowerCase().includes(n)})}async function ja(e){if(!e)return new Set;const s=await qt(e);return Array.isArray(s.hiddenCompletedSlugs)?new Set(s.hiddenCompletedSlugs.filter(n=>typeof n=="string")):new Set}function ya(e,s){return e?Bt(e,{hiddenCompletedSlugs:[...s]}):Promise.resolve()}function Na({scopeCwd:e=null,navigate:s,filterText:n,planMode:a="graph",onOpenPrds:c,planToolsEl:l=null}){var xt;const i=Le(v=>v.snapshot),r=f.useMemo(()=>!i||!e?i:{...i,jobs:i.jobs.filter(v=>v.cwd===e)},[i,e]),[d,o]=f.useState(null),[p,u]=f.useState(()=>Date.now()),[h,g]=f.useState(new Set),[x,w]=f.useState(!1),[j,D]=f.useState({text:"",status:"all"}),k=f.useMemo(()=>n===void 0?j:{...j,text:n},[j,n]),[E,m]=f.useState(!1),[T,C]=f.useState("queue"),P=f.useRef(null),[O,K]=f.useState(0),[U,Q]=f.useState(""),Y=tt(),te=f.useRef(!1),se=f.useRef(!1),z=f.useRef(h);z.current=h;const A=f.useRef(j);A.current=j,f.useEffect(()=>{let v=!1;return te.current=!1,se.current=!1,ja(e).then(I=>{!v&&!te.current&&g(I)}),wa(e).then(I=>{!v&&!se.current&&D(I)}),()=>{v=!0}},[e]),f.useEffect(()=>(window.api.schedule.health().then(o).catch(()=>{}),window.api.schedule.onState(()=>{window.api.schedule.health().then(o).catch(()=>{})})),[]),f.useEffect(()=>{if(!Y)return;u(Date.now());const v=setInterval(()=>u(Date.now()),1e3);return()=>clearInterval(v)},[Y]);const B=f.useMemo(()=>{if(!r)return 15e4;const v=[];for(const I of r.jobs)if(I.status==="completed"&&I.startedAt&&I.finishedAt){const V=Date.parse(I.finishedAt)-Date.parse(I.startedAt);V>0&&v.push(V)}return v.length===0?15e4:v.reduce((I,V)=>I+V,0)/v.length},[r]),N=f.useRef(new Map);f.useEffect(()=>{if(!r)return;const v=[];for(const I of r.jobs){const V=N.current.get(I.slug);V&&V!==I.status&&v.push(`${I.title}: ${V} → ${I.status}`),N.current.set(I.slug,I.status)}v.length>0&&Q(v.join("; "))},[r]);const S=f.useMemo(()=>{var I;const v=new Map;for(const V of((I=r==null?void 0:r.lastTick)==null?void 0:I.holds)??[])v.set(V.slug,V);return v},[r==null?void 0:r.lastTick]),G=pe(v=>v.sessions),F=f.useMemo(()=>r?Gt(_e(r.jobs),G,i!=null&&i.jobs?_e(i.jobs):void 0):[],[r,G,i]),W=Cs(),b=f.useMemo(()=>r?Rt(kn(r.jobs,W,e),k):[],[r,W,e,k]),y=(xt=r==null?void 0:r.effectiveConcurrency)==null?void 0:xt.cap,M=f.useMemo(()=>a==="list"?[]:it(b,{sessions:G,avgDurationMs:B,concurrency:y}),[a,b,G,B,y]),[$,R]=f.useState(1),L=M.map(v=>`${v.epicId??""}#${v.waveIndex}`).join(",");f.useEffect(()=>{R(1)},[e,k.status,k.text,L]);const _=Math.max(1,Math.ceil(M.length/Ie)),X=Math.min($,_),Be=f.useMemo(()=>M.slice((X-1)*Ie,X*Ie),[M,X]),rs=f.useMemo(()=>{const v=new Map;let I=0;for(const V of M)for(const J of V.stages)for(const ae of J.rows)v.set(ae.slug,I++);return v},[M]),is=f.useMemo(()=>Nn(F),[F]),ls=h,lt=f.useCallback(v=>{var be;const I=(be=P.current)==null?void 0:be.querySelectorAll("[data-job-row]");if(!I||I.length===0)return;const V=Array.from(I),J=V.findIndex(ne=>ne.dataset.jobIndex===String(O)),ae=ne=>{const fe=V[ne];if(!fe)return;const he=Number(fe.dataset.jobIndex);K(he),fe.focus()};v.key==="ArrowDown"?(v.preventDefault(),ae(J===-1?0:Math.min(J+1,V.length-1))):v.key==="ArrowUp"&&(v.preventDefault(),ae(J===-1?V.length-1:Math.max(J-1,0)))},[O]),ot=f.useCallback(v=>{K(v)},[]),dt=f.useCallback(v=>{const I=A.current;se.current=!0,A.current=v,D(v),va(e,v).catch(()=>{A.current===v&&(A.current=I,D(I),q.error("Couldn't save queue filter — reverted."))})},[e]),ct=f.useCallback(v=>{const I=z.current;te.current=!0,z.current=v,g(v),ya(e,v).catch(()=>{z.current===v&&(z.current=I,g(I),q.error("Couldn't save hidden completed jobs — reverted."))})},[e]);if(!r)return null;if(T==="supervisor")return t.jsx(da,{supervisorConfig:r.config.supervisor,onSetConfig:v=>window.api.schedule.setConfig({supervisor:v}),onBack:()=>C("queue")});const{jobs:Z,paused:ut,lastRunAt:os,nextReset:ds,effectiveConcurrency:He}=r;if(Z.length===0)return t.jsx(fa,{navigate:s});const oe={pending:0,running:0,investigating:0,completed:0,needs_review:0,failed:0};for(const v of Z)v.status in oe&&oe[v.status]++;const Ge=Z.filter(v=>v.status==="running"),cs=zt({snap:r,now:p,avgDurationMs:B,runningJobs:Ge}),je=Rt(Z,k),us=ka(je),{inline:De,collapsedCount:Ve}=Sa(je,h,p,x),ps=$a(De,Z,us,B,cs.kind,p),pt=()=>{const v=new Set(h);for(const I of Z)(I.status==="completed"||I.status==="failed")&&v.add(I.slug);ct(v)},ft=async()=>{const v=Z.filter(J=>J.status!=="running").length;if(v===0)return;const I=`Archive ${v} non-running PRD${v===1?"":"s"} and remove from the queue?
|
|
1
|
+
import{aK as Pe,aw as ie,ae as Te,aQ as gs,aj as Ce,ad as le,ah as ee,aV as q,b9 as Fe,b7 as pe,aE as f,ab as xe,bg as xs,ao as t,b as Ue,I as me,L as bt,q as ms,K as ge,u as bs,Q as ws,d as vs,U as js,aP as ys,b6 as st,a$ as Ns,a6 as wt,au as Tt,bf as $e,G as qe,aB as _e,A as nt,aO as at,N as _t,w as Ot,p as Lt,r as ks,o as rt,y as it,O as Ss,f as re,g as H,af as Ft,ba as Cs,aD as $s,aG as qt,bj as Bt,V as Ps,ax as vt,b0 as jt,n as ke,x as yt,aL as Nt,m as Ds,aT as As,X as Ms,v as Ht,b2 as Rs,aY as ye,H as Is,C as Es,bb as Ts,aF as _s,T as Os,bi as Ls,bc as kt,aN as Fs}from"./index-CTBpf-26.js";import{f as qs,a as Bs,s as Hs}from"./historyTotals-BrFxw5J1.js";import{l as Gs}from"./listSkills-C1aWKf0T.js";import{T as Vs}from"./Toggle-7WpPzcZH.js";import"./monaco-editor-BsIlgG7c.js";function Ws(e){const s=new Map(e.map(i=>[i.slug,i])),n=new Map,a=new Set,c=[];function l(i){n.set(i,1),c.push(i);const r=s.get(i);for(const d of(r==null?void 0:r.dependsOn)??[]){if(!s.has(d))continue;const o=n.get(d);if(o===1){const p=c.indexOf(d);for(let u=p;u<c.length;u++)a.add(c[u])}else o===void 0&&l(d)}c.pop(),n.set(i,2)}for(const i of e)n.has(i.slug)||l(i.slug);return a}function Us(e,s){return(e.dependsOn??[]).map(n=>{const a=s.get(n);return a?{slug:n,status:a.status,missing:!1,needsReview:a.status==="needs_review"}:{slug:n,status:null,missing:!0,needsReview:!1}})}function Qs(e,s,n){const a=new Set(e.map(o=>o.slug)),c=new Set;for(const o of e)for(const p of o.dependsOn??[])a.has(p)&&c.add(p);const l=new Map,i=[];for(const o of e){const p=n.has(o.slug)?void 0:(o.dependsOn??[]).find(u=>a.has(u)&&!n.has(u));p?(l.has(p)||l.set(p,[]),l.get(p).push(o)):i.push(o)}const r=(o,p)=>o.slug.localeCompare(p.slug);i.sort(r);for(const o of l.values())o.sort(r);function d(o,p,u){const h=Us(o,s),g=n.has(o.slug);u.add(o.slug);const x=g?[]:(l.get(o.slug)??[]).filter(w=>!u.has(w.slug)).map(w=>d(w,p+1,u));return u.delete(o.slug),{row:o,depth:p,children:x,blockers:h,blocked:h.some(w=>!w.missing&&w.status!=="completed"),hasNeedsReviewBlocker:h.some(w=>w.needsReview),hasMissingDep:h.some(w=>w.missing),cycle:g,parallelEligible:(o.dependsOn??[]).length===0&&!c.has(o.slug)}}return i.map(o=>d(o,0,new Set))}function Gt(e,s,n){const a=new Map((n??e).map(o=>[o.slug,o])),c=Ws(e),l=[],i=new Map,r=new Map;for(const o of e){const p=Pe(o,s),u=p.epicId??"__none__";i.has(u)||(l.push(u),i.set(u,[]),r.set(u,{epicId:p.epicId,label:p.known&&p.label?p.label:p.epicId?`Epic ${p.epicId.slice(0,12)}…`:"No Epic",known:p.known})),i.get(u).push(o)}const d=l.map(o=>{const p=r.get(o),u=i.get(o),h=Qs(u,a,c),g={};for(const x of u){const w=x.status??"unknown";g[w]=(g[w]??0)+1}return{epicId:p.epicId,label:p.label,known:p.known,nodes:h,counts:g,total:u.length}});return d.sort((o,p)=>o.epicId===null?1:p.epicId===null?-1:o.known!==p.known?o.known?-1:1:o.label.localeCompare(p.label)),d}function Be(e){const s=[],n=a=>{s.push(a);for(const c of a.children)n(c)};for(const a of e)n(a);return s}function Je(e){return String(e??"").replace(/^\d+-/,"")}function Oe(e){const s=new Set,n=new Map;for(const a of e){s.add(a.slug);const c=Je(a.slug),l=n.get(c);l?l.push(a.slug):n.set(c,[a.slug])}return e.map(a=>{const c=a.dependsOn;if(!c||c.length===0)return a;let l=!1;const i=c.map(r=>{if(s.has(r))return r;const d=n.get(Je(r));return d&&d.length===1?(l=!0,d[0]):r});return l?{...a,dependsOn:i}:a})}const zs=15e4,Xe=e=>e==="completed"||e==="skipped",Se=e=>e==="running"||e==="investigating",Vt=e=>e==="failed"||e==="needs_review"||e==="quarantined",Ys=e=>e==="failed"||e==="needs_review"||e==="quarantined";function Wt(e){if(e<=5e3)return"~now";if(e<6e4)return`~${Math.round(e/1e3)}s`;const s=Math.round(e/6e4);return s<60?`~${s}m`:`~${Math.floor(s/60)}h${String(s%60).padStart(2,"0")}m`}function Ut(e,s){const n=e.estimateMinutes?e.estimateMinutes*6e4:null;return n?`${Math.min(99,Math.floor(s/n*100))}%`:Te(s)}function Ks(e){let s=0,n=0;for(const a of e)if(a.status==="completed"&&a.startedAt&&a.finishedAt){const c=Date.parse(a.finishedAt)-Date.parse(a.startedAt);c>0&&(s+=c,n++)}return n===0?zs:s/n}function Le(e){const s=ie(e);return s===null?1/0:Number(s)}function Ze(e,s){const n=Le(e.slug)-Le(s.slug);return n!==0&&!Number.isNaN(n)?n:e.slug.localeCompare(s.slug)}function Js(e){let s=0;for(const n of e.statusHistory??[])n.to==="pending"&&n.from!==null&&s++;return s}function Xs(e){return e.some(n=>Se(n.status))?"active":e.every(n=>Xe(n.status))?"done":e.filter(n=>n.status!=="quarantined").length===0?"draft":"queued"}function Zs(e,s,n,a){switch(e){case"done":return`${s.doneCount}/${s.rows.length} done`;case"running":return`${s.runningCount} running · ${n}`;case"held":return`${s.heldCount} held`;case"blocked":return`${s.blockedCount+a} blocked`;default:return`${n} ready`}}function en(e,s){return e._firstNum!==s._firstNum?e._firstNum<s._firstNum?-1:1:e._firstSlug.localeCompare(s._firstSlug)}function tn(e,s){const n=new Map(e.map(l=>[l.row.slug,l.row.slug])),a=l=>{for(;n.get(l)!==l;)n.set(l,n.get(n.get(l))),l=n.get(l);return l};for(const l of e)for(const i of l.row.dependsOn??[])s.has(i)&&n.set(a(l.row.slug),a(i));const c=new Map;for(const l of e){const i=a(l.row.slug),r=c.get(i);r?r.push(l):c.set(i,[l])}return[...c.values()]}function sn(e,s){if(e.length>0&&e.every(n=>!!n.row.planId)){const n=new Map;for(const a of e){const c=n.get(a.row.planId);c?c.push(a):n.set(a.row.planId,[a])}return[...n.values()]}return tn(e,s)}function nn(e,s,n,a){const c=[],l=[e];for(a.add(e.row.slug);l.length>0;){const i=l.pop();c.push(i);for(const r of i.row.dependsOn??[])if(n.has(r)&&!a.has(r)){a.add(r);const d=s.get(r);d&&l.push(d)}}return c}function an(e,s){const n=new Map(e.map(r=>[r.row.slug,r])),a=new Set,c=[],l=e.filter(r=>Je(r.row.slug).startsWith("validate-")).sort((r,d)=>Ze({slug:r.row.slug},{slug:d.row.slug}));for(const r of l)a.has(r.row.slug)||c.push({nodes:nn(r,n,s,a),validateSlug:r.row.slug});const i=e.filter(r=>!a.has(r.row.slug));if(i.length>0){const r=new Set(i.map(d=>d.row.slug));for(const d of sn(i,r))c.push({nodes:d,validateSlug:null})}return c}function rn(e){return e.replace(/^validate[\s:-]*/i,"").trim()}function lt(e,s){if(e.length===0)return[];const n=Oe(e),a=s.now??Date.now(),c=s.avgDurationMs??Ks(n),l=Math.max(1,s.concurrency??1),i=new Map(n.map(u=>[u.slug,u])),r=u=>u.status==="pending"&&(u.dependsOn??[]).every(h=>i.get(h)===void 0||i.get(h).status==="completed"),d=new Map;n.filter(r).sort(Ze).forEach((u,h)=>d.set(u.slug,h));const o=Gt(n,s.sessions,n),p=[];for(const u of o){const h=Be(u.nodes),g=new Set(h.map(D=>D.row.slug)),x=new Map(h.map(D=>[D.row.slug,D])),w=[];for(const D of an(h,g)){const k=D.nodes,E=new Set(k.map(N=>N.row.slug)),m=new Map,T=new Set,$=N=>{const S=x.get(N);return(S.row.dependsOn??[]).filter(G=>E.has(G)&&!(S.cycle&&x.get(G).cycle))},P=N=>{const S=m.get(N);if(S!==void 0)return S;if(T.has(N))return 0;T.add(N);let G=0;for(const F of $(N))G=Math.max(G,P(F));return T.delete(N),m.set(N,G+1),G+1};for(const N of k)P(N.row.slug);const O=k.map(N=>{const S=N.row,G=(S.dependsOn??[]).filter(F=>g.has(F));return{slug:S.slug,title:S.title,status:S.status,stage:m.get(S.slug),prdNumber:ie(S.slug),rowKind:"dep",rowTrailing:"",cycle:N.cycle,estimateMinutes:S.estimateMinutes??null,deps:G,crossEpicDeps:(S.dependsOn??[]).filter(F=>!g.has(F)),blockers:N.blockers,job:S}});O.sort(Ze);const K=O.reduce((N,S)=>Math.max(N,S.stage),0),W=new Map;for(const N of O){const S=N.job,G=x.get(N.slug),F=S.status;let U;if(Xe(F)){const b=S.startedAt&&S.finishedAt?Date.parse(S.finishedAt)-Date.parse(S.startedAt):NaN;U={kind:"done",trailing:b>0?Te(b):"",held:!1,blocked:!1}}else if(Se(F)){const b=S.startedAt?Math.max(0,a-Date.parse(S.startedAt)):null;U={kind:"running",trailing:b===null?"":Ut(S,b),held:!1,blocked:!1}}else if(F==="failed")U={kind:"failed",trailing:"failed",held:!1,blocked:!1};else if(F==="needs_review")U={kind:"review",trailing:"review",held:!1,blocked:!1};else if(F==="quarantined")U={kind:"quarantined",trailing:"quarantined",held:!1,blocked:!1};else{const b=G.blockers.filter(y=>!y.missing&&y.status!=="completed");if(b.length>0){const y=b.some(C=>Ys(C.status)),A=b[0].slug;U={kind:"dep",trailing:`←${ie(A)??A}`,held:!y,blocked:y}}else if(S.heldReason)U={kind:"gate",trailing:"gate",held:!0,blocked:!1};else{const y=Js(S),A=d.get(S.slug)??0;U=y>0?{kind:"retry",trailing:`${y} ${y===1?"retry":"retries"}`,held:!1,blocked:!1}:{kind:"eta",trailing:Wt(A*c/l),held:!1,blocked:!1}}}W.set(N.slug,U)}const Q=[];for(let N=1;N<=K;N++){const S=O.filter(_=>_.stage===N),G=S.find(_=>{const X=W.get(_.slug).kind;return _.status==="pending"&&(X==="eta"||X==="retry")});if(G){const _=W.get(G.slug);_.kind="next",_.trailing="next"}let F=0,U=0,b=0,y=0,A=0,C=0;for(const _ of S){const X=W.get(_.slug);_.rowKind=X.kind,_.rowTrailing=X.trailing,Xe(_.status)?F++:Se(_.status)?U++:_.status==="pending"?(A++,X.held&&b++,X.blocked&&y++):Vt(_.status)&&C++}const R=F===S.length?"done":U>0?"running":y+C>0?"blocked":b>0?"held":"pending",L={n:N,rows:S,doneCount:F,runningCount:U,heldCount:b,blockedCount:y};Q.push({...L,state:R,summary:Zs(R,L,A,C)})}let J=0;for(const N of O){const S=N.estimateMinutes?N.estimateMinutes*6e4:c;if(N.status==="pending")J+=S;else if(Se(N.status)){const G=N.job.startedAt?Math.max(0,a-Date.parse(N.job.startedAt)):0;J+=Math.max(0,S-G)}}const te=O.reduce((N,S)=>Math.min(N,Le(S.slug)),1/0),se=O.reduce((N,S)=>Math.max(N,Le(S.slug)),-1/0),z=u.known?gs(u.label).title:u.label,M=D.validateSlug?O.find(N=>N.slug===D.validateSlug):void 0,B=M&&rn(M.title)||z;w.push({epicId:u.epicId,waveIndex:0,index:0,label:B,epicLabel:z,validateSlug:D.validateSlug,width:Q.reduce((N,S)=>Math.max(N,S.rows.length),0),status:Xs(O),prdCount:O.length,stageCount:K,doneCount:Q.reduce((N,S)=>N+S.doneCount,0),runningCount:Q.reduce((N,S)=>N+S.runningCount,0),heldCount:Q.reduce((N,S)=>N+S.heldCount,0),blockedCount:Q.reduce((N,S)=>N+S.blockedCount,0),etaMs:J/l,stages:Q,_firstNum:te,_lastNum:se,_firstSlug:O[0].slug})}w.sort(en),w.forEach((D,k)=>{D.waveIndex=k+1});const j=w.filter(D=>D.validateSlug===null);j.forEach((D,k)=>{j.length>1&&(D.label=`${D.label} · plan ${k+1}/${j.length}`)});for(const D of w)p.push(D)}return p.sort((u,h)=>{if(u._lastNum!==h._lastNum)return u._lastNum>h._lastNum?-1:1;const g=(u.epicId??"").localeCompare(h.epicId??"");return g!==0?g:u.waveIndex-h.waveIndex}),p.map(({_firstNum:u,_lastNum:h,_firstSlug:g,...x},w)=>({...x,index:w+1}))}function ln(e,s=Date.now()){const n=Oe(e),a=new Map(n.map(g=>[g.slug,g])),c=new Date(s).toDateString();let l=0,i=0,r=0,d=0,o=0,p=0,u=0;for(const g of n)g.status==="pending"?(i++,(g.dependsOn??[]).every(w=>a.get(w)===void 0||a.get(w).status==="completed")&&l++):Se(g.status)?u++:g.status==="failed"?r++:g.status==="needs_review"?d++:g.status==="quarantined"?o++:g.status==="completed"&&g.finishedAt&&new Date(Date.parse(g.finishedAt)).toDateString()===c&&p++;let h=null;if(r+d+o>0){for(const g of lt(n,{sessions:{},now:s}))for(const x of g.stages)if(x.rows.some(w=>Vt(w.status))){(h===null||x.n<h)&&(h=x.n);break}}return{readyNow:l,totalQueued:i,heldByDeps:i-l,needsYou:r+d+o,needsYouStage:h,failedCount:r,needsReviewCount:d,doneToday:p,inFlight:u}}function on(e){const s=new Map;for(const d of e.stages)for(const o of d.rows)s.set(o.slug,o);const n=d=>{var o;return((o=s.get(d))==null?void 0:o.cycle)===!0},a=new Map,c=new Set,l=(d,o)=>d.chain.length!==o.chain.length?d.chain.length>o.chain.length:d.est!==o.est?d.est>o.est:d.chain.join("\0")<o.chain.join("\0"),i=d=>{const o=a.get(d);if(o)return o;const p=s.get(d),u=p.estimateMinutes??0;if(c.has(d))return{chain:[d],est:u};c.add(d);let h=null;for(const x of p.deps){if(!s.has(x)||p.cycle&&n(x))continue;const w=i(x);(!h||l(w,h))&&(h=w)}c.delete(d);const g=h?{chain:[...h.chain,d],est:h.est+u}:{chain:[d],est:u};return a.set(d,g),g};let r=null;for(const d of s.keys()){const o=i(d);(!r||l(o,r))&&(r=o)}return r?r.chain:[]}const dn=300*6e4,cn={five_hour:"5-hour",session:"5-hour",weekly_all:"weekly",weekly:"weekly"};function un(e){return cn[e]??e.replace(/_/g," ")}function Qt({snap:e,now:s,avgDurationMs:n,runningJobs:a}){const{config:c,jobs:l,paused:i,nextReset:r,utilization:d,utilizationWindow:o,effectiveConcurrency:p}=e;let u=0,h=0;for(const k of l)k.status==="pending"?u++:k.status==="completed"&&h++;const g=a.length,x=u+g,w=(p==null?void 0:p.cap)??5;if(g>0){const k=a.reduce((P,O)=>(P.startedAt??"")<(O.startedAt??"")?P:O),E=k.startedAt?s-Date.parse(k.startedAt):0,m=h+g,T=h+x,$=g>1?` · ${g}/${w} parallel`:"";return{kind:"running",line1:`Running ${m}/${T}${$} · ${Ce(E)}`,line2:g===1?k.title:a.map(P=>P.title).join(", "),tooltip:a.map(P=>`${P.slug} (g${P.parallelGroup})`).join("; ")}}if(i){const k=i.resumeAt?Date.parse(i.resumeAt)-s:null;return{kind:"paused",line1:{rate_limit:"Paused — tokens exhausted",auth:"Paused — authentication failed",network:"Paused — network unreachable",reset_failure:"Paused — billing data unavailable",manual:"Paused — manual (you paused the queue)"}[i.reason]??`Paused — ${i.reason}`,line2:i.reason==="auth"?"Run `claude` in any terminal to refresh credentials, then Resume":k!==null&&k>0?`auto-resume ${le(Date.parse(i.resumeAt))} (in ${ee(k)})`:i.resumeAt?"resuming…":"no auto-resume scheduled",tooltip:i.resumeAt??"",action:{label:"Resume",onClick:()=>window.api.schedule.resume(),title:"Clear the pause and resume queue immediately"}}}if(x===0)return{kind:"idle",line1:"No work queued",line2:null};const j=c.firePolicy??"when-available";if(j==="manual")return{kind:"manual",line1:`Manual · ${u} pending`,line2:"click Fire next batch now to fire",action:{label:"Fire next batch now",onClick:()=>window.api.schedule.forceTick().then(q.fromOutcome).catch(()=>q.error("Failed to fire batch")),title:"Bypasses the billing-usage poll. Use when the meter is rate-limited or you want immediate progress."}};if(j==="on-reset"){if(!r)return{kind:"on-reset",line1:"On-reset · waiting for billing data",line2:null};const k=Date.parse(r)+c.offsetMinutes*6e4,E=k-s;return{kind:"on-reset",line1:`On-reset · ${u} pending`,line2:E>0?`fires ${le(k)} (in ${ee(E)})`:"firing now…"}}const D=c.utilizationThreshold??90;if(d==null)return{kind:"auto-soon",line1:`Auto · ${u} pending`,line2:"checking token availability…"};if(d>=D){const k=r?Date.parse(r)-s:null,E=o?un(o):null,m=k===null||Number.isNaN(k)||k>dn,T=k&&k>0?`resets ${le(Date.parse(r))} (in ${ee(k)})`:null;let $;return m?$=`${E??"binding"} window — long hold${T?`, ${T}`:", reset time unknown"}`:$=T?`${E?`${E} window `:""}next ${T}`:"will fire when usage drops",{kind:"auto-throttled",line1:`Auto · throttled (util ${d.toFixed(0)}% ≥ ${D}%)`,line2:$}}return{kind:"auto-soon",line1:`Auto · ${u} pending · util ${d.toFixed(0)}%`,line2:"fires within 2 min (poll cycle)"}}const pn=15e3,fn=new Set(["failed","needs_review","quarantined"]);function St(){var n;const s=Array.from(document.querySelectorAll("[data-job-row]")).find(a=>fn.has(a.dataset.jobStatus??""));(n=s==null?void 0:s.scrollIntoView)==null||n.call(s,{block:"center",behavior:"smooth"})}function hn(e,s){var n;switch(e.kind){case"paused":return`paused: scheduler is paused (${e.reason??"manual"})`;case"launch-blocked":return`launch-blocked: ${e.agentType} jobs can't launch${(n=e.block)!=null&&n.kind?` (${e.block.kind})`:""}`;case"idle":return"idle: 0 pending";case"saturated":{const a=s!=null?`, oldest ${ee(s)}`:"";return`saturated: ${e.totalSlots??"?"} slot(s) busy${a}`}case"blocked":{const a=e.blockedChains.length;return`blocked: ${e.pending} pending, ${e.dispatchable} dispatchable — ${a} chain${a===1?"":"s"} stuck behind a failed/skipped dependency`}case"stalled":return`stalled: no dispatch attempt in ${e.idleMs!=null?ee(e.idleMs):"?"} with ${e.dispatchable} dispatchable`;case"running":default:return`running: ${e.runningCount} in flight, ${e.pending} pending`}}function gn(e){const[s,n]=f.useState(null),a=st(),c=Ns(),l=a&&c;return f.useEffect(()=>{if(!l)return;let i=!0,r=!1,d=!1;const o=()=>{r||(r=!0,window.api.schedule.queueHealth(e).then(u=>{r=!1,d=!1,i&&n(u)},u=>{r=!1,!d&&(d=!0,q.error(`Queue health refresh failed: ${u instanceof Error?u.message:String(u)}`))}))};o();const p=setInterval(o,pn);return()=>{i=!1,clearInterval(p)}},[e,l]),s}const xn={running:{dot:"bg-sage",text:"text-sage-dark"},paused:{dot:"bg-amber-500",text:"text-amber-600"},idle:{dot:"bg-fg-faint",text:"text-fg-faint"}};function mn(e,s,n){return e==="paused"||e==="launch-blocked"?"paused":e==="running"||e==="saturated"?"running":e?"idle":s?"paused":n>0?"running":"idle"}const Qe="px-2.5 py-1.5 rounded border border-line text-[12.5px] font-medium text-fg-dim hover:text-fg hover:bg-bg-hi disabled:opacity-40 disabled:cursor-not-allowed whitespace-nowrap";function bn(e,s,n,a){var c;if(e==="agent"){const l=((c=a==null?void 0:a.cwd)==null?void 0:c.split("/").filter(Boolean).pop())||"another session",i=a!=null&&a.reason?` — "${a.reason}"`:"",r=s?new Date(s).getTime()-n:null,d=r==null?"":r>0?` — auto-resumes in ${ee(r)}`:" — auto-resume pending";return`Paused by an agent in ${l}${i}${d}. Click Resume to restart now.`}if(e==="auth")return"Scheduler paused: Claude sign-in expired or invalid. Restart the app or re-run `claude login`, then Resume.";if(e==="rate_limit"){if(s){const l=new Date(s).getTime()-n;return l>0?`Paused for rate limit — resumes in ${ee(l)}`:"Paused for rate limit — resume pending"}return"Paused for rate limit"}return e==="network"?"Paused: billing endpoint unreachable for 30+ min.":e==="manual"?"Scheduler paused manually — no new jobs start; running jobs continue. Click Resume to restart.":`Scheduler paused (${e})`}function wn({now:e}){const s=Fe(p=>p.snapshot);if(!s)return null;const n=s.paused,a=Object.entries(s.launchBlocks??{}),c=Object.entries(s.launchMitigations??{}),l=(n==null?void 0:n.reason)==="auth"||(n==null?void 0:n.reason)==="network",i="flex items-start gap-3 border-b px-0 py-1.5 text-[12.5px]",r="bg-red-950/10 border-red-700/30 text-red-800",d="bg-amber-400/10 border-amber-600/30 text-amber-700",o="shrink-0 px-2 py-0.5 rounded border border-current/40 hover:bg-white/20 text-[12px] font-medium";return t.jsxs(t.Fragment,{children:[n&&t.jsxs("div",{"data-testid":"pause-banner",className:`${i} ${l?r:d}`,children:[t.jsx("span",{className:"flex-1 leading-snug",children:bn(n.reason,n.resumeAt,e,n.by)}),t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resume(),className:o,children:"Resume"})]}),a.map(([p,u])=>t.jsxs("div",{"data-testid":"launch-block-banner",className:`${i} ${r}`,children:[t.jsxs("div",{className:"flex-1 leading-snug min-w-0",children:[t.jsxs("div",{className:"font-medium",children:["Launches for ",t.jsx("span",{className:"font-mono",children:p})," jobs are failing before any work starts",u.httpStatus?` (HTTP ${u.httpStatus}, ${u.kind})`:` (${u.kind})`,u.exhausted?" — held until the Claude CLI version changes or you press Retry now.":u.until?` — next automatic probe ${new Date(u.until).getTime()>e?`in ${ee(new Date(u.until).getTime()-e)}`:"on the next tick"}.`:"."]}),t.jsx("div",{className:"opacity-80",children:u.hint}),t.jsxs("div",{className:"font-mono text-[11.5px] opacity-70 truncate",title:u.message,children:[u.attempts," failed probe",u.attempts===1?"":"s",u.claudeVersion?` · CLI ${u.claudeVersion}`:"",u.lastSlug?` · last: ${u.lastSlug}`:""," · ",u.message]})]}),t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resume(),className:o,children:"Retry now"})]},`launch-block-${p}`)),c.map(([p,u])=>t.jsx("div",{"data-testid":"launch-mitigation-banner",className:`${i} ${d}`,children:t.jsxs("div",{className:"flex-1 leading-snug min-w-0",children:[t.jsxs("div",{className:"font-medium",children:[t.jsx("span",{className:"font-mono",children:p})," jobs are running in degraded mode"," ","(",t.jsx("span",{className:"font-mono",children:Object.entries(u.env).map(([h,g])=>`${h}=${g}`).join(" ")}),")",u.claudeVersion?` since CLI ${u.claudeVersion}`:"","."]}),t.jsx("div",{className:"opacity-80",children:u.hint})]})},`launch-mitigation-${p}`))]})}function vn({scopeCwd:e,subView:s,onSubView:n,filterText:a,onFilterText:c,planMode:l,onPlanMode:i,planToolsRef:r}){const d=Fe(C=>C.snapshot),o=pe(C=>C.sessions),p=gn(e),[u,h]=f.useState(()=>Date.now()),[g,x]=f.useState("—");f.useEffect(()=>{const C=setInterval(()=>h(Date.now()),3e4);return()=>clearInterval(C)},[]),f.useEffect(()=>{let C=!0;return qs(30).then(R=>{if(!C||!R.ok||!R.data)return;const L=new Date,_=He=>String(He).padStart(2,"0"),X=`${L.getFullYear()}-${_(L.getMonth()+1)}-${_(L.getDate())}`;x(Bs(Hs(R.data,{day:X})))}),()=>{C=!1}},[]);const w=f.useMemo(()=>((d==null?void 0:d.jobs)??[]).filter(C=>!e||C.cwd===e),[d,e]),j=f.useMemo(()=>ln(w,u),[w,u]),D=f.useMemo(()=>{const C=lt(w,{sessions:o,now:u}),R=L=>C.filter(_=>_.status===L).length;return{active:R("active"),queued:R("queued"),draft:R("draft")}},[w,o,u]),k=f.useMemo(()=>{const C=new Date(u).toDateString(),R=[];for(const L of w)if(L.status==="completed"&&L.startedAt&&L.finishedAt&&new Date(Date.parse(L.finishedAt)).toDateString()===C){const _=Date.parse(L.finishedAt)-Date.parse(L.startedAt);_>0&&R.push(_)}return R.length?Math.round(R.reduce((L,_)=>L+_,0)/R.length/6e4):null},[w,u]);if(!d)return null;const E=p&&!p.unknown?p.verdict??null:null,m=p&&!p.unknown?p.slots??null:null,T=d.paused,$=mn((E==null?void 0:E.kind)??null,!!T,j.inFlight),P=xn[$],O=w.filter(C=>C.status==="pending").length,K=w.filter(C=>C.status==="running").length,W=Qt({snap:{...d,jobs:w},now:u,avgDurationMs:0,runningJobs:w.filter(C=>C.status==="running")}),Q=p!=null&&p.unknown?`Queue health: unknown — ${p.reason??"state unavailable"}`:E?hn(E,(p==null?void 0:p.oldestRunningAgeMs)??null):"queue health loading…",J=xe(d.lastRunAt?Date.parse(d.lastRunAt):null,u),te=p!=null&&p.lastDispatchAttemptAt?xe(Date.parse(p.lastDispatchAttemptAt),u):"never",se=[Q,W.line1,E?`dispatchable ${E.dispatchable} · needs_review ${E.needsReviewCount}`:null,(p==null?void 0:p.oldestRunningAgeMs)!=null?`oldest running ${ee(p.oldestRunningAgeMs)} (any project)`:null,`last batch fired ${J} (lastRunAt — advances only when a job launches)`,`last dispatch attempt ${te} (advances on every driver evaluation)`].filter(Boolean).join(`
|
|
2
|
+
`),z=d.utilization,M=d.pollHealth,B=M!=null&&!M.lastPollOk,N=xs(d.utilizationWindow),S=d.nextReset?Date.parse(d.nextReset):null,G=S?S>u?ee(S-u):"soon":"—",F=d.effectiveConcurrency,U=(F==null?void 0:F.cap)??5,b=(F==null?void 0:F.source)==="env",y=d.config.firePolicy??"when-available",A=O===0&&K===0;return t.jsxs("div",{"data-testid":"scheduler-top-bands",className:"shrink-0 px-[18px]",children:[t.jsxs(Ue,{height:40,testId:"queue-health-header",className:"gap-3",children:[t.jsx("h1",{className:"m-0 font-serif text-[21px] font-semibold leading-none tracking-tight text-fg",children:"Scheduler"}),t.jsx("span",{className:"w-px h-[20px] bg-rule-structural","aria-hidden":"true"}),t.jsxs("span",{className:`inline-flex items-center gap-1.5 text-[12.5px] font-medium ${P.text}`,"data-testid":"scheduler-state-word","data-state":$,children:[t.jsx("span",{className:`w-2 h-2 rounded-full ${P.dot}`,"aria-hidden":"true"}),$]}),t.jsxs("span",{className:"font-mono text-[12px] text-fg-faint whitespace-nowrap","data-testid":"scheduler-meta",children:[j.inFlight," in flight · ",j.heldByDeps," held · last batch ",J]}),t.jsxs(me,{title:se,testId:"scheduler-verdict-info",popoverTestId:"scheduler-info-popover",children:[t.jsx("pre",{className:"m-0 mb-2 whitespace-pre-wrap font-mono text-[11.5px] text-fg-dim",children:se}),bt.scheduler&&t.jsx(ms,{content:bt.scheduler})]}),t.jsxs("span",{className:"ml-auto flex items-center gap-2",children:[t.jsx("button",{type:"button",onClick:()=>window.api.schedule.rescan().then(q.fromOutcome).catch(()=>q.error("Failed to rescan")),title:"Re-scan the prds/ folder. Use when you've added or edited PRDs on disk and want the queue to reflect them immediately.",className:Qe,children:"Refresh"}),T?t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resume(),title:"Clear the pause and resume queue immediately",className:Qe,children:"Resume"}):t.jsx("button",{type:"button",onClick:()=>window.api.schedule.pause(),title:"Stop NEW dispatch. Running jobs are not killed.",className:Qe,children:"Pause"}),t.jsx("button",{type:"button",onClick:()=>window.api.schedule.forceTick().then(q.fromOutcome).catch(()=>q.error("Failed to fire batch")),disabled:A,title:"Bypasses the billing-usage poll. Use when the meter is rate-limited or you want immediate progress.",className:"px-3 py-1.5 rounded bg-accent text-white text-[12.5px] font-semibold whitespace-nowrap disabled:opacity-40 disabled:cursor-not-allowed hover:opacity-90",children:"Fire next batch"})]})]}),t.jsx(wn,{now:u}),t.jsxs(Ue,{height:70,testId:"scheduler-kpi-band",children:[t.jsx(ge,{testId:"kpi-window",label:N?`${N} used`:"Window used",info:B?`Billing poll failing — this reading may be outdated (last good reading ${xe(M.lastPollAt,u)}). Machine-wide ${N??"binding"} window.`:`Share of the machine-wide ${N??"binding"} billing window consumed — the window closest to its limit.`,value:z==null?"—":`${Math.round(z)}%`,sub:`resets in ${G}`,third:t.jsx(bs,{pct:z??0,tone:B?"bg-amber-500":"bg-accent"})}),t.jsx(ge,{testId:"kpi-slots",label:"Slots",info:`Machine-wide session pool (${(m==null?void 0:m.source)==="env"?"SM_SESSION_SLOTS override":"Home tab cap"}), not scoped to this project`,value:m?`${m.inUse}/${m.total}`:"—",sub:"in use",third:m?t.jsx(ws,{filled:m.inUse,total:m.total}):null}),t.jsx(ge,{testId:"kpi-ready",label:"Ready now",info:"Pending rows whose dependsOn chain is fully satisfied right now",value:j.readyNow,sub:`of ${j.totalQueued} queued`,third:`${j.heldByDeps} held by deps`}),j.needsYou>0?t.jsx(ge,{testId:"kpi-needs-you",label:"Needs you",value:t.jsx("button",{type:"button","data-testid":"kpi-needs-you-jump",onClick:St,className:"font-semibold text-accent hover:underline",title:"Scroll to the first failed / needs-review / quarantined row",children:j.needsYou}),sub:t.jsx("button",{type:"button",onClick:St,className:"hover:underline",children:j.needsYouStage!=null?`blocking stage ${j.needsYouStage}`:"need attention"}),third:[j.failedCount>0&&`${j.failedCount} failed`,j.needsReviewCount>0&&`${j.needsReviewCount} needs review`,j.needsYou-j.failedCount-j.needsReviewCount>0&&`${j.needsYou-j.failedCount-j.needsReviewCount} quarantined`].filter(Boolean).join(" · ")}):t.jsx(ge,{testId:"kpi-needs-you",label:"Needs you",value:t.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[15px]",children:[t.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-sage","aria-hidden":"true"}),"all clear"]}),third:"0 failed · 0 needs review"}),t.jsx(ge,{testId:"kpi-done",label:"Done today",value:j.doneToday,sub:k!=null?`avg ${k}m`:"avg —",third:t.jsx("span",{"data-testid":"kpi-done-spend",children:g})}),t.jsx(ge,{testId:"kpi-concurrency",label:"Concurrency",info:"Start-jobs policy, concurrency cap and utilization threshold",infoTestId:"kpi-concurrency-info",infoAlignRight:!0,infoContent:t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-fg",children:"Start jobs"}),t.jsxs("select",{"data-testid":"kpi-fire-policy",value:y,onChange:C=>window.api.schedule.setConfig({firePolicy:C.target.value}),className:"border border-line bg-bg-hi rounded px-1 py-0.5 text-[12px] text-fg-dim",title:"when-available: poll usage and fire when tokens are below threshold. on-reset: fire after each 5h reset. manual: only on Run now.","aria-label":"Start jobs policy",children:[t.jsx("option",{value:"when-available",children:"when available"}),t.jsx("option",{value:"on-reset",children:"only on reset"}),t.jsx("option",{value:"manual",children:"manually"})]})]}),value:t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(js,{value:U,min:0,max:10,disabled:b,onChange:C=>{ys(C).catch(R=>{q.error(`Could not set session slots: ${R instanceof Error?R.message:String(R)}`)})},title:b?"pinned by SM_SESSION_SLOTS — unset the env var to edit":"Machine-wide claude -p session slots, shared with chat runs"}),b&&t.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-amber-600 bg-amber-400/10 border border-amber-400/30 rounded px-1 py-0",title:"Pinned by SM_SESSION_SLOTS — unset the env var to edit",children:"env"})]}),sub:"at once",third:y==="when-available"?t.jsxs("span",{children:["pause above"," ",t.jsx(vs,{value:d.config.utilizationThreshold??90,min:0,max:100,testId:"kpi-threshold",title:"Fire only when 5h utilization is below this percent — click to edit",onCommit:C=>window.api.schedule.setConfig({utilizationThreshold:C})})]}):null})]}),t.jsxs(Ue,{height:30,testId:"scheduler-plans-toolbar",className:"gap-3",children:[t.jsx("span",{className:"text-[10.5px] font-semibold uppercase tracking-wide text-fg-faint",children:"Plans"}),t.jsxs("span",{className:"font-mono text-[12px] text-fg-faint whitespace-nowrap","data-testid":"scheduler-plans-meta",children:[D.active," active · ",D.queued," queued · ",D.draft," draft · ",w.length," PRDs"]}),t.jsxs("span",{className:"ml-auto flex items-center gap-3",children:[t.jsx("span",{ref:r,className:"contents","data-testid":"scheduler-plan-tools"}),t.jsx("input",{type:"text",value:a,onChange:C=>c(C.target.value),placeholder:"filter PRDs…","aria-label":"Filter PRDs by title, slug, or project","data-testid":"scheduler-filter-input",className:"w-[180px] bg-bg-hi border border-line rounded px-2 py-0.5 text-[12px] text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint"}),t.jsx("span",{className:"inline-flex border border-line rounded overflow-hidden",role:"group","aria-label":"Plan view mode",children:[["graph","Graph"],["list","List"],["critical","Critical path"]].map(([C,R])=>t.jsx("button",{type:"button","data-testid":`plan-mode-${C}`,"aria-pressed":l===C&&s==="queue",onClick:()=>{i(C),n("queue")},className:`px-2 py-0.5 text-[12px] ${l===C&&s==="queue"?"bg-bg-elev font-semibold text-fg":"text-fg-dim hover:text-fg"}`,children:R},C))}),t.jsx("span",{className:"w-px h-[16px] bg-rule-structural","aria-hidden":"true"}),[["prds","PRDs","Authored PRD source files on disk — edit, lint, archive, or queue them."],["history","History","The last 50 completed and failed jobs."],["machine","Machine","Machine-wide config that applies to every project — not this project’s live queue."]].map(([C,R,L])=>t.jsx("button",{type:"button",onClick:()=>n(C),"aria-pressed":s===C,title:L,className:`text-[12.5px] ${s===C?"font-semibold text-fg":"text-fg-faint hover:text-fg-dim"}`,children:R},C))]})]})]})}function zt({options:e,value:s,onChange:n,pillPadding:a="px-3 py-1.5"}){return t.jsx("div",{className:"flex gap-1.5 flex-wrap",children:e.map(c=>{const l=c.value===s;return t.jsxs("button",{type:"button",onClick:()=>n(c.value),className:`rounded-full ${a} text-[12.5px] border transition-colors ${l?"bg-accent text-white border-accent font-semibold":"bg-bg-hi text-fg-dim border-line hover:border-fg-faint font-medium"}`,children:[c.label,c.count!==void 0&&t.jsxs("span",{children:[" ",c.count]})]},c.value)})})}function Yt(e,s=60){const n=e.trim();return n.length<=s?n:`${n.slice(0,s-1)}…`}function jn(e){return Be([e]).filter(s=>s.children.length===0).map(s=>s.row.slug)}function Kt(e){return e.nodes.map(s=>({rootSlug:s.row.slug,label:s.row.title||s.row.slug,terminals:jn(s)}))}function yn(e){const s=new Map;for(const n of e){const a=Kt(n);n.nodes.forEach((c,l)=>{const i=a.filter((r,d)=>d!==l);for(const r of Be([c]))s.set(r.row.slug,i)})}return s}function Jt({job:e,headChoices:s}){const[n,a]=f.useState(!1),c=f.useCallback((l,i)=>{a(!0),window.api.schedule.setPrdDisposition({slug:e.slug,cwd:e.cwd??void 0,disposition:l,dependsOn:i}).then(q.fromOutcome).catch(()=>q.error("Failed to change disposition")).finally(()=>a(!1))},[e.slug,e.cwd]);return e.disposition!=="append"&&s.length===0?null:t.jsxs("select",{"data-testid":"job-row-disposition-control",disabled:n,value:"",onChange:l=>{const i=l.target.value;if(i==="__new-head__")c("new-head");else if(i){const r=s.find(d=>d.rootSlug===i);r&&c("append",r.terminals)}},className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border border-line/60 rounded px-1.5 py-0.5 cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed",title:"Change this wave's relationship to the rest of the Epic's plan",children:[t.jsx("option",{value:"",disabled:!0,children:"change disposition…"}),e.disposition==="append"&&t.jsx("option",{value:"__new-head__",children:"promote to new head"}),s.map(l=>t.jsxs("option",{value:l.rootSlug,children:["attach behind: ",Yt(l.label,40)]},l.rootSlug))]})}function Nn(e,s,n=null){if(s.length===0||e.length===0)return e;const a=new Set,c=new Set;for(const i of e){a.add(i.slug);for(const r of wt(i))c.add(r)}const l=[];for(const i of s)i.archived!==!0||a.has(i.slug)||n&&i.cwd!==n||wt(i).some(r=>c.has(r))&&(a.add(i.slug),l.push({slug:i.slug,title:i.title,cwd:i.cwd,parallelGroup:i.parallelGroup,estimateMinutes:i.estimateMinutes,bodyPreview:"",status:i.archivedStatus??"completed",runId:null,startedAt:null,finishedAt:null,exitCode:null,error:null,dependsOn:i.dependsOn??void 0,sourcePromptId:i.sourcePromptId??null,epicId:i.epicId??null,synthetic:!0}));return l.length===0?e:[...e,...l]}const kn=[],Sn=new Set(["failed","needs_review","quarantined"]);function Cn(e){switch(e.status){case"completed":case"skipped":return"bg-sage";case"running":case"investigating":return"bg-accent";case"failed":return"bg-accent";case"needs_review":return"bg-butter";case"quarantined":return"bg-butter/60";default:return e.rowKind==="eta"||e.rowKind==="next"||e.rowKind==="retry"?"border border-fg-faint bg-transparent":"bg-fg-faint/40"}}function $n(e){switch(e.status){case"running":case"investigating":return"bg-butter/10";case"failed":return"bg-accent/10";case"needs_review":return"bg-butter/25";default:return""}}function Pn(e){switch(e.rowKind){case"running":case"dep":case"failed":return"text-accent";case"review":return"text-butter font-semibold";default:return"text-fg-faint"}}function Dn({row:e,elapsedMs:s,listIndex:n,onFocused:a,headChoices:c=kn}){const[l,i]=f.useState(!1),r=e.job,d=s!==null&&e.rowKind==="running"?Ut(r,s):e.rowTrailing,o=e.status==="completed"||e.status==="skipped",p=e.rowKind==="dep"&&e.blockers.some(h=>!h.missing&&h.status!==null&&Sn.has(h.status)),u=o||p;return t.jsxs("div",{role:"listitem","data-testid":"prd-row","data-slug":e.slug,className:"border-t border-rule-inner first:border-t-0",children:[t.jsxs("button",{type:"button","data-job-row":!0,"data-job-status":r.status,"data-job-index":n,onClick:()=>i(h=>!h),onFocus:()=>a(n),"aria-expanded":l,"aria-label":`${e.prdNumber?`PRD ${e.prdNumber}, `:""}${r.title}, ${r.status}${d?`, ${d}`:""}`,title:r.title,className:`w-full h-[31px] py-1 px-2 text-left flex items-center gap-1.5 hover:bg-bg/40 focus:outline-none focus:ring-1 focus:ring-accent focus:ring-inset ${$n(e)}`,children:[t.jsx("span",{"aria-hidden":"true",className:`shrink-0 w-[7px] h-[7px] rounded-full ${Cn(e)}`}),t.jsx("span",{className:"shrink-0 font-mono text-[10.5px] text-fg-faint w-[30px]",children:e.prdNumber?`#${e.prdNumber}`:""}),t.jsx("span",{className:`flex-1 min-w-0 truncate text-[12.5px] leading-tight ${u?"text-fg-faint":"text-fg font-medium"}`,children:r.title}),t.jsx("span",{"data-testid":"prd-row-trailing",className:`shrink-0 font-mono text-[10.5px] ${Pn(e)}`,children:d})]}),l&&t.jsx(An,{row:e,elapsedMs:s,headChoices:c})]})}const Xt=f.memo(Dn);function An({row:e,elapsedMs:s,headChoices:n}){const a=e.job,[c,l]=f.useState(!1),i=pe(g=>g.sessions),r=f.useMemo(()=>Pe(a,i),[a,i]),d=r.known&&r.epicId?i[r.epicId]:null,o=f.useCallback(g=>Tt(g),[]),p="font-mono text-[11.5px] text-fg-dim leading-snug break-words",u="text-[12px] font-semibold bg-transparent border-0 cursor-pointer p-0",h=a.error?a.error.split(`
|
|
3
|
+
`)[0]:null;return t.jsxs("div",{"data-testid":"prd-row-detail",className:"px-3 py-2 bg-bg-elev/50 border-t border-rule-inner flex flex-col gap-1",children:[t.jsxs("div",{className:p,children:[a.status.replace(/_/g," "),a.exitCode!==null&&` · exit ${a.exitCode}`,a.verifierVerdict&&` · ${$e(a.verifierVerdict)}`,a.startedAt&&` · started ${le(Date.parse(a.startedAt))}`,a.finishedAt&&` · finished ${le(Date.parse(a.finishedAt))}`,s===null&&e.rowTrailing&&e.rowKind==="done"?` · took ${e.rowTrailing}`:""]}),e.cycle&&t.jsxs("div",{className:`${p} text-accent`,"data-testid":"job-row-cycle-warning",children:["⚠ dependsOn cycle — ",e.blockers.map(g=>g.slug).join(" ↔ ")||"self-referencing"]}),!e.cycle&&e.blockers.length>0&&t.jsxs("div",{className:p,"data-testid":"job-row-blockers",children:["depends on ",e.blockers.map(g=>`${g.slug} (${g.missing?"missing":(g.status??"unknown").replace(/_/g," ")})`).join(", ")]}),a.status==="pending"&&a.heldReason&&t.jsxs("div",{className:`${p} text-amber-400/90`,"data-testid":"job-row-held-reason",children:["held · ",a.heldReason]}),h&&t.jsx("div",{className:`${p} text-accent/80`,children:h}),!a.synthetic&&t.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 pt-0.5",children:[d&&t.jsx("button",{type:"button","data-testid":"job-row-prompt-session-link",title:d.goalText,onClick:()=>o(d.id),className:`${u} text-accent hover:text-accent/80`,children:"view epic →"}),a.runId&&t.jsx("button",{type:"button",onClick:()=>l(!0),className:`${u} text-fg-dim hover:text-fg`,children:"view log →"}),a.status==="quarantined"&&t.jsx("button",{type:"button","data-testid":"job-row-adopt-prd",title:"Stamp this PRD's provenance so the scheduler will run it — no unstamped PRD runs automatically.",onClick:()=>{window.api.schedule.adoptPrd(a.slug).then(q.fromOutcome).catch(()=>q.error("Failed to adopt PRD"))},className:`${u} text-accent hover:text-accent/80`,children:"adopt PRD →"}),a.status!=="pending"&&a.status!=="running"&&a.status!=="quarantined"&&t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resetJob(a.slug,a.cwd??void 0),className:`${u} text-fg-dim hover:text-fg`,children:"reset to pending →"}),a.disposition&&(a.status==="pending"||a.status==="quarantined")&&t.jsx(Jt,{job:a,headChoices:n})]}),c&&a.runId&&t.jsx(qe,{runId:a.runId,slug:a.slug,title:a.title||a.slug,onClose:()=>l(!1)})]})}const ue=190,Mn=7,Rn=5,In=[],Zt=e=>e==="completed"||e==="skipped",es=e=>e==="running"||e==="investigating",ts=e=>e==="failed"||e==="needs_review"||e==="quarantined";function Me(e){return es(e.status)?0:ts(e.status)?1:Zt(e.status)?3:2}const En={done:"text-sage",running:"text-accent",held:"text-fg-faint",pending:"text-fg-faint",blocked:"text-butter"},Tn={done:"bg-sage",running:"bg-accent",held:"bg-fg-faint/50",pending:"bg-fg-faint/50",blocked:"bg-butter"};function _n(e,s){return e.every(n=>Zt(n.status))?`+${e.length} done`:e.every(n=>n.rowKind==="dep"&&n.blockers.some(a=>!a.missing&&a.status!==null&&ts(a.status)))?`+${e.length} blocked`:`+${e.length} in stage ${s}`}function On({stage:e,epicId:s,now:n,hidden:a,indexBySlug:c,headChoicesBySlug:l,onRowFocused:i}){const[r,d]=f.useState(!1),o=f.useMemo(()=>e.rows.filter(m=>!(a.has(m.slug)&&(m.status==="completed"||m.status==="failed"))).map((m,T)=>({r:m,i:T})).sort((m,T)=>Me(m.r)-Me(T.r)||m.i-T.i).map(m=>m.r),[e.rows,a]),p=f.useMemo(()=>o.filter(m=>Me(m)<=1).length,[o]),u=Math.max(e.state==="done"?Rn:Mn,p),h=r?o:o.slice(0,u),g=r?[]:o.slice(u),x=o.find(m=>m.status==="failed"),w=o.find(m=>m.status==="needs_review"),j=p>0&&(x!==void 0||w!==void 0),D=h.reduce((m,T,$)=>Me(T)<=1?$:m,-1),k=m=>t.jsx(Xt,{row:m,elapsedMs:es(m.status)&&m.job.startedAt?n-Date.parse(m.job.startedAt):null,listIndex:c.get(m.slug)??0,onFocused:i,headChoices:l.get(m.slug)??In},m.slug),E="flex-1 min-w-0 truncate h-[24px] text-[11.5px] font-medium text-fg-dim hover:text-fg border border-rule-structural rounded-sm bg-transparent cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed";return t.jsxs("div",{"data-testid":"stage-column","data-stage":e.n,style:{width:ue},className:"shrink-0 border-l border-rule-structural first:border-l-0 flex flex-col self-stretch",children:[t.jsxs("div",{className:"h-[30px] shrink-0 flex items-center gap-1.5 px-2 border-b border-rule-inner","data-testid":"stage-header",children:[t.jsx("span",{"aria-hidden":"true",className:`w-[7px] h-[7px] rounded-full shrink-0 ${Tn[e.state]}`}),t.jsxs("span",{className:`text-[10px] font-semibold uppercase tracking-wide ${En[e.state]}`,children:["Stage ",e.n]}),e.state==="blocked"&&t.jsx(me,{title:"Rows in this stage are failed / need review / are quarantined, or wait on one that is."}),t.jsx("span",{"data-testid":"stage-summary",className:"ml-auto font-mono text-[10.5px] text-fg-dim truncate",children:e.summary})]}),t.jsx("div",{role:"presentation",children:h.map((m,T)=>t.jsxs("div",{children:[k(m),j&&T===D&&t.jsxs("div",{"data-testid":"stage-attention-actions",className:"flex gap-1.5 px-2 py-1.5 border-t border-rule-inner",children:[x&&t.jsxs("button",{type:"button","data-testid":"stage-retry",title:`Reset ${x.slug} to pending`,onClick:()=>{window.api.schedule.resetJob(x.slug,x.job.cwd??void 0).then($=>{$.ok||q.error($.error??`Failed to reset ${x.slug}`)}).catch(()=>q.error(`Failed to reset ${x.slug}`))},className:E,children:["Retry ",x.prdNumber?`#${x.prdNumber}`:x.slug]}),w&&t.jsxs("button",{type:"button","data-testid":"stage-review",disabled:!s,title:s?"Open the authoring Epic — a needs_review PRD is a question routed back to it":"No authoring Epic recorded for this plan",onClick:()=>{s&&Tt(s)},className:E,children:["Review ",w.prdNumber?`#${w.prdNumber}`:w.slug]})]})]},m.slug))}),(g.length>0||r&&o.length>u)&&t.jsx("button",{type:"button","data-testid":"stage-footer","aria-expanded":r,onClick:()=>d(m=>!m),className:"mt-auto h-[26px] border-t border-rule-inner font-mono text-[11px] text-fg-faint hover:text-fg-dim bg-transparent cursor-pointer",children:r?"show less ▴":`${_n(g,e.n)} ▾`})]})}const we=6,ze=4,Ee=4,Ct=12,$t=5,ss=2,Pt=4,Ln={done:"bg-sage",running:"bg-accent",attention:"bg-butter",failed:"bg-red-600",pending:"bg-fg-faint/50"};function Fn(e){return e==="completed"||e==="skipped"?"done":e==="running"||e==="investigating"?"running":e==="failed"?"failed":e==="needs_review"||e==="quarantined"?"attention":"pending"}function qn(e){const s=[],n=[],a=[];let c=$t;for(const l of e){const i=Math.max(1,Math.ceil(l.rows.length/Ee));n.push(c),a.push(i*we),l.rows.forEach((r,d)=>{s.push({x:c+Math.floor(d/Ee)*we,y:ss+d%Ee*we,tone:Fn(r.status),title:`${r.prdNumber?`#${r.prdNumber}`:r.slug} ${r.title} — ${r.status}`})}),c+=i*we+Ct}return{dots:s,stageX:n,stageW:a,width:Math.max(0,c-Ct)+$t}}function ve(e,s){return e.findIndex(n=>n.rows.some(a=>s(a.status)))}const et=e=>e==="running"||e==="investigating",tt=e=>e==="failed"||e==="needs_review"||e==="quarantined";function Bn({stages:e,first:s,perView:n,onSeek:a}){const c=f.useMemo(()=>qn(e),[e]),l=f.useMemo(()=>ve(e,et)>=0,[e]),i=f.useMemo(()=>ve(e,tt)>=0,[e]),r=f.useRef(!1),d=e.length,o=Math.min(d-1,s+n-1),p=c.stageX[Math.min(s,d-1)]??0,u=(c.stageX[o]??0)+(c.stageW[o]??0),h=x=>{const w=x.currentTarget.getBoundingClientRect(),j=x.clientX-w.left;let D=0;for(let k=0;k<d;k++)c.stageX[k]<=j&&(D=k);a(Math.max(0,Math.min(d-1,D-Math.floor(n/2))))},g="px-2 h-[20px] text-[11.5px] disabled:opacity-40 disabled:cursor-not-allowed";return t.jsxs("div",{"data-testid":"plan-minimap",className:"h-[28px] flex items-center gap-3 px-3 border-t border-rule-inner",children:[t.jsxs("span",{className:"shrink-0 flex items-center gap-1 text-[10.5px] font-semibold uppercase tracking-wide text-fg-faint",children:["Whole graph",t.jsx(me,{title:"Every PRD in this plan as one dot, grouped by stage. The rust box is the range of stages shown below — drag it to scroll."})]}),t.jsxs("div",{"data-testid":"plan-minimap-dots",role:"presentation",className:"relative shrink min-w-0 overflow-hidden cursor-ew-resize touch-none",style:{width:c.width,height:Ee*we-(we-ze)+2*ss},onPointerDown:x=>{var w,j;r.current=!0,(j=(w=x.currentTarget).setPointerCapture)==null||j.call(w,x.pointerId),h(x)},onPointerMove:x=>{r.current&&h(x)},onPointerUp:()=>{r.current=!1},onPointerCancel:()=>{r.current=!1},children:[c.dots.map((x,w)=>t.jsx("span",{title:x.title,"data-tone":x.tone,className:`absolute rounded-[1px] ${Ln[x.tone]}`,style:{left:x.x,top:x.y,width:ze,height:ze}},w)),t.jsx("span",{"data-testid":"plan-minimap-brush","aria-hidden":"true",className:"absolute top-0 bottom-0 border border-accent bg-accent/10 rounded-[2px] pointer-events-none",style:{left:p-Pt,width:u-p+2*Pt}})]}),t.jsxs("span",{className:"ml-auto shrink-0 font-mono text-[11.5px] text-fg-faint","data-testid":"plan-minimap-range",children:["stages ",Math.min(s+1,d),"–",o+1," of ",d]}),t.jsxs("span",{className:"shrink-0 inline-flex border border-line rounded overflow-hidden",role:"group","aria-label":"Jump the stage window",children:[t.jsx("button",{type:"button","data-testid":"minimap-running",disabled:!l,title:l?"Scroll to the lowest stage with a running PRD":"No stage has a running PRD",onClick:()=>a(ve(e,et)),className:`${g} text-fg-dim hover:text-fg`,children:"Running"}),t.jsx("button",{type:"button","data-testid":"minimap-blockers",disabled:!i,title:i?"Scroll to the lowest stage with a failed / needs-review / quarantined PRD":"No stage has a failed, needs-review or quarantined PRD",onClick:()=>a(ve(e,tt)),className:`${g} text-fg-dim hover:text-fg border-l border-line`,children:"Blockers"})]})]})}const Hn=148;function Gn({stages:e,onSeek:s}){if(e.length===0)return null;const n=e[0].n,a=e[e.length-1].n;return t.jsxs("div",{"data-testid":"further-stages",style:{width:Hn},className:"shrink-0 border-l border-rule-structural flex flex-col",children:[t.jsxs("div",{className:"h-[30px] shrink-0 flex items-center px-2 border-b border-rule-inner text-[10.5px] font-semibold uppercase tracking-wide text-fg-faint",children:["Stage ",n,"–",a]}),t.jsxs("div",{className:"h-[22px] shrink-0 flex items-center gap-1 px-2 text-[10.5px] font-semibold uppercase tracking-wide text-fg-faint",children:["Further stages",t.jsx(me,{title:"Stages beyond the visible window. Click one to scroll the stage columns to it."})]}),e.map(c=>{const l=c.rows.length===0?0:c.doneCount/c.rows.length*100;return t.jsxs("button",{type:"button","data-testid":"further-stage-row","data-stage":c.n,title:`${c.summary} — scroll to stage ${c.n}`,onClick:()=>s(c.n-1),className:"h-[26px] px-2 flex items-center gap-2 border-t border-rule-inner bg-transparent hover:bg-bg-hi cursor-pointer text-left",children:[t.jsxs("span",{className:"font-mono text-[10.5px] text-fg-dim w-[50px] whitespace-nowrap shrink-0",children:["stage ",c.n]}),t.jsx("span",{role:"progressbar","aria-valuenow":c.doneCount,"aria-valuemin":0,"aria-valuemax":c.rows.length,className:"flex-1 h-[4px] rounded-sm bg-rule-inner overflow-hidden",children:t.jsx("span",{className:"block h-full bg-sage",style:{width:`${l}%`}})})]},c.n)})]})}const Vn=[],Wn=e=>e==="running"||e==="investigating";function Un(e){const s=on(e),n=new Map,a=new Map;for(const r of e.stages){a.set(r.n,r.rows.length);for(const d of r.rows)n.set(d.slug,d)}const c=new Map;let l=0;const i=[];for(const r of s){const d=n.get(r);l+=d.estimateMinutes??0,c.set(d.stage,(c.get(d.stage)??0)+1),i.push({row:d,totalMinutes:l,othersInStage:0})}for(const r of i)r.othersInStage=(a.get(r.row.stage)??0)-(c.get(r.row.stage)??0);return i}function Qn({plan:e,now:s,indexBySlug:n,headChoicesBySlug:a,onRowFocused:c}){const l=f.useMemo(()=>Un(e),[e]);return t.jsx("div",{"data-testid":"critical-path",className:"border-t border-rule-structural max-w-[640px]",children:l.map(({row:i,totalMinutes:r,othersInStage:d})=>t.jsxs("div",{"data-testid":"critical-entry","data-slug":i.slug,children:[t.jsxs("div",{className:"flex items-start",children:[t.jsx("div",{className:"flex-1 min-w-0",children:t.jsx(Xt,{row:i,elapsedMs:Wn(i.status)&&i.job.startedAt?s-Date.parse(i.job.startedAt):null,listIndex:n.get(i.slug)??0,onFocused:c,headChoices:a.get(i.slug)??Vn})}),t.jsxs("span",{"data-testid":"critical-est",className:"shrink-0 h-[31px] px-3 flex items-center gap-2 font-mono text-[11.5px] text-fg-faint border-t border-rule-inner",children:[t.jsx("span",{title:"estimateMinutes",children:i.estimateMinutes?`${i.estimateMinutes}m`:"—"}),t.jsxs("span",{className:"text-fg-dim",title:"Running total along the chain",children:["Σ ",r,"m"]})]})]}),d>0&&t.jsxs("div",{"data-testid":"critical-others",className:"h-[22px] px-3 flex items-center font-mono text-[11.5px] text-fg-faint border-t border-rule-inner",children:["stage ",i.stage," · +",d," not on the critical path"]})]},i.slug))})}const Dt=1,At=1350,zn={active:"border-l-accent",queued:"border-l-rule-structural",done:"border-l-sage",draft:"border-l-fg-faint/40 border-dashed"},Yn={active:{label:"ACTIVE",cls:"bg-accent text-white border border-accent"},queued:{label:"QUEUED",cls:"text-fg-dim border border-fg-faint"},done:{label:"DONE",cls:"text-sage-dark border border-sage"},draft:{label:"DRAFT",cls:"text-fg-faint border border-dashed border-fg-faint"}},Kn=e=>String(e).padStart(2,"0");function Jn({plan:e}){const s=Math.max(1,e.prdCount),n=e.doneCount/s*100,a=e.runningCount/s*100;return t.jsxs("span",{"data-testid":"plan-progress",role:"progressbar","aria-valuenow":e.doneCount,"aria-valuemin":0,"aria-valuemax":e.prdCount,className:"flex w-[160px] h-[5px] rounded-sm overflow-hidden bg-rule-inner shrink-0",children:[t.jsx("span",{className:"h-full bg-sage",style:{width:`${n}%`}}),t.jsx("span",{className:"h-full bg-accent",style:{width:`${a}%`}})]})}function Xn({plan:e,mode:s="graph",now:n,hidden:a,indexBySlug:c,headChoicesBySlug:l,onRowFocused:i,onOpenPrds:r}){var se,z;const[d,o]=f.useState(e.status==="active"||e.status==="queued"),[p,u]=f.useState(!1),h=f.useRef(null),[g,x]=f.useState(0),[w,j]=f.useState(At),D=f.useMemo(()=>{const M=ve(e.stages,et);return M>=0?M:Math.max(0,ve(e.stages,tt))},[e.stages]);f.useLayoutEffect(()=>{if(!d)return;const M=h.current,B=(M==null?void 0:M.clientWidth)||At,N=Math.max(0,Math.min(D,e.stageCount-Math.max(1,Math.ceil(B/ue))));M!=null&&M.clientWidth&&j(M.clientWidth),M&&(M.scrollLeft=N*ue),x(N)},[d]);const k=f.useMemo(()=>{let M=null;for(const B of e.stages)for(const N of B.rows){if(!N.job.runId)continue;const S=N.job.finishedAt?Date.parse(N.job.finishedAt):0;(!M||S>M.at)&&(M={runId:N.job.runId,slug:N.slug,title:N.title,at:S})}return M},[e.stages]),E=_e((z=(se=e.stages[0])==null?void 0:se.rows[0])==null?void 0:z.job.cwd)??"—",m=Yn[e.status],T=Math.max(1,Math.ceil(w/ue)),$=Math.max(0,Math.min(g-Dt,e.stageCount)),P=Math.min(e.stageCount,g+T+Dt),O=M=>{const B=Math.max(0,Math.min(e.stageCount-1,M));h.current&&(h.current.scrollLeft=B*ue),x(B)},K=Math.min(e.stageCount,g+T),W=M=>{const B=M.currentTarget,N=Math.floor(B.scrollLeft/ue);N!==g&&x(N),B.clientWidth&&B.clientWidth!==w&&j(B.clientWidth)},Q="h-[24px] px-3 text-[12px] font-medium text-fg border border-rule-structural rounded-sm bg-transparent hover:bg-bg-hi cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed shrink-0",J=(()=>{switch(e.status){case"active":return t.jsx("button",{type:"button","data-testid":"plan-action",title:"Pauses the WHOLE scheduler (machine-wide) — there is no per-plan pause.",onClick:()=>{window.api.schedule.pause().catch(()=>q.error("Failed to pause the scheduler"))},className:Q,children:"Pause plan"});case"queued":return t.jsx("button",{type:"button","data-testid":"plan-action",title:"Fires the next scheduler batch machine-wide (force tick) — it does not target this plan.",onClick:()=>{window.api.schedule.forceTick().then(q.fromOutcome).catch(()=>q.error("Failed to fire the next batch"))},className:Q,children:"Run now"});case"done":return t.jsx("button",{type:"button","data-testid":"plan-action",disabled:!k,title:k?`Open the run log of ${k.slug}, the plan's last run`:"No run log recorded for this plan",onClick:()=>u(!0),className:Q,children:"View run"});case"draft":return t.jsx("button",{type:"button","data-testid":"plan-action",title:"Open the PRDs sub-view on this plan's first PRD (the PRDs view has no per-Epic filter).",onClick:()=>{var M,B;return r==null?void 0:r(((B=(M=e.stages[0])==null?void 0:M.rows[0])==null?void 0:B.slug)??null)},className:Q,children:"Schedule…"})}})(),te=e.etaMs>0?` · ${Wt(e.etaMs)} left`:"";return t.jsxs("section",{"data-testid":"plan-band","data-epic-id":e.epicId??"","data-plan-status":e.status,className:`border-l-[3px] ${zn[e.status]} border-b border-rule-structural`,children:[t.jsxs("div",{className:"h-[32px] flex items-center gap-2.5 px-3","data-testid":"plan-header",children:[t.jsx("button",{type:"button","aria-expanded":d,"aria-label":d?"Collapse plan":"Expand plan","data-testid":"plan-toggle",onClick:()=>o(M=>!M),className:"shrink-0 w-[14px] text-[11px] text-fg-faint hover:text-fg bg-transparent border-0 cursor-pointer p-0",children:d?"▾":"▸"}),t.jsx("span",{className:"font-mono text-[11.5px] text-fg-faint shrink-0",children:Kn(e.index)}),t.jsx("span",{className:"font-serif text-[15px] font-bold text-fg truncate shrink-0 max-w-[320px]",title:e.epicLabel!==e.label?`${e.label} — ${e.epicLabel}`:e.label,"data-testid":"plan-label",children:e.label}),t.jsx("span",{"data-testid":"plan-chip",className:`shrink-0 rounded-sm px-1.5 py-[1px] text-[10px] font-bold tracking-wide ${m.cls}`,children:m.label}),t.jsx("span",{"aria-hidden":"true",className:"shrink-0 w-px h-[16px] bg-rule-structural"}),t.jsx("span",{className:"font-mono text-[11.5px] text-fg-faint truncate min-w-0","data-testid":"plan-meta",children:e.validateSlug!=null&&e.epicLabel!==e.label?t.jsxs(t.Fragment,{children:[E," · ",e.epicLabel," · ",e.prdCount," PRD",e.prdCount===1?"":"s"," · ",e.width," wide · ",e.stageCount," stage",e.stageCount===1?"":"s"]}):t.jsxs(t.Fragment,{children:[E," · ",e.prdCount," PRD",e.prdCount===1?"":"s",e.width>1?` · ${e.width} wide`:""," · ",e.stageCount," stage",e.stageCount===1?"":"s"]})}),t.jsx(me,{title:`${e.doneCount} done · ${e.runningCount} running · ${e.heldCount} held · ${e.blockedCount} blocked`}),t.jsxs("span",{className:"ml-auto font-mono text-[11.5px] text-fg-dim shrink-0","data-testid":"plan-progress-label",children:[e.doneCount,"/",e.prdCount,te]}),t.jsx(Jn,{plan:e}),J]}),d&&s==="critical"&&t.jsx(Qn,{plan:e,now:n,indexBySlug:c,headChoicesBySlug:l,onRowFocused:i}),d&&s!=="critical"&&e.status==="active"&&t.jsx(Bn,{stages:e.stages,first:g,perView:T,onSeek:O}),d&&s!=="critical"&&t.jsxs("div",{className:"flex border-t border-rule-structural",children:[t.jsxs("div",{ref:h,"data-testid":"plan-stages",onScroll:W,className:"flex flex-1 min-w-0 overflow-x-auto",children:[$>0&&t.jsx("div",{"aria-hidden":"true",className:"shrink-0",style:{width:$*ue}}),e.stages.slice($,P).map(M=>t.jsx(On,{stage:M,epicId:e.epicId,now:n,hidden:a,indexBySlug:c,headChoicesBySlug:l,onRowFocused:i},M.n)),P<e.stageCount&&t.jsx("div",{"aria-hidden":"true",className:"shrink-0",style:{width:(e.stageCount-P)*ue}})]}),t.jsx(Gn,{stages:e.stages.slice(K),onSeek:O})]}),p&&k&&t.jsx(qe,{runId:k.runId,slug:k.slug,title:k.title||k.slug,onClose:()=>u(!1)})]})}function Zn({page:e,pageSize:s,totalItems:n,onPageChange:a}){if(n<=s)return null;const c=Math.max(1,Math.ceil(n/s)),l=(e-1)*s+1,i=Math.min(e*s,n);return t.jsxs("div",{"data-testid":"plan-pager",className:"flex items-center justify-center gap-3 px-[18px] py-3 font-mono text-[12px] text-fg-faint",children:[t.jsx("button",{type:"button","data-testid":"plan-pager-prev",onClick:()=>a(e-1),disabled:e<=1,className:"px-2 py-1 rounded border border-line bg-bg-hi text-fg-dim hover:text-fg disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer",children:"Prev"}),t.jsxs("span",{"data-testid":"plan-pager-range",children:[l,"–",i," of ",n]}),t.jsx("button",{type:"button","data-testid":"plan-pager-next",onClick:()=>a(e+1),disabled:e>=c,className:"px-2 py-1 rounded border border-line bg-bg-hi text-fg-dim hover:text-fg disabled:opacity-40 disabled:cursor-not-allowed cursor-pointer",children:"Next"})]})}function ea({section:e,children:s}){const[n,a]=f.useState(!0),c=Object.entries(e.counts).map(([l,i])=>`${i} ${l.replace(/_/g," ")}`).join(" · ");return t.jsxs("div",{className:"border-t border-line","data-testid":"backlog-epic-section","data-epic-id":e.epicId??"",children:[t.jsxs("button",{type:"button",onClick:()=>a(l=>!l),className:"w-full flex items-center gap-2.5 px-[18px] py-2.5 bg-bg-elev/60 hover:bg-bg-elev text-left","aria-expanded":n,title:e.label,children:[t.jsx("span",{className:`text-fg-faint inline-flex shrink-0 transition-transform duration-150 ${n?"rotate-90":""}`,"aria-hidden":"true",children:t.jsx(nt,{name:"chevron",size:12})}),t.jsx("span",{className:"font-serif text-[14.5px] font-semibold text-fg truncate","data-testid":"backlog-epic-label",children:e.label}),t.jsxs("span",{className:"font-mono text-[11px] text-fg-faint shrink-0",children:[e.total," PRD",e.total===1?"":"s"]}),t.jsx("span",{className:"font-mono text-[11px] text-fg-faint truncate",children:c})]}),n&&s]})}const ta=[],sa=[],na={depth:0,blockers:ta,blocked:!1,hasNeedsReviewBlocker:!1,hasMissingDep:!1,cycle:!1,parallelEligible:!1};function aa(e){return e.missing?`${e.slug} (missing)`:e.needsReview?`${e.slug} (needs review)`:`${e.slug} (${(e.status??"unknown").replace(/_/g," ")})`}function ra(e){return e.missing?"text-accent":e.needsReview?"text-butter font-semibold":e.status==="completed"?"text-sage":"text-amber-400/90"}function ia({job:e,eta:s,elapsedMs:n,avgDurationMs:a,listIndex:c,onFocused:l,hold:i,backlog:r=na,headChoices:d=sa}){const[o,p]=f.useState(!1),[u,h]=f.useState(!1),g=pe(P=>P.sessions),x=f.useMemo(()=>Pe(e,g),[e,g]),w=x.known&&x.epicId?g[x.epicId]:null,j=f.useCallback(P=>{at(P),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"terminal"}))},[]),D=e.status==="running",k=e.status==="failed";let E=null;D&&n!==null?E=`${Te(n)} elapsed`:e.status==="completed"&&e.startedAt&&e.finishedAt?E=`took ${Ce(Date.parse(e.finishedAt)-Date.parse(e.startedAt))}`:s&&(E=s);const m=e.error??null,T=k&&m?m.split(`
|
|
4
|
+
`)[0]:e.status==="needs_review"&&e.verifierVerdict?$e(e.verifierVerdict):null,$=D&&n!==null?Math.min(.99,n/a):0;return t.jsxs("div",{role:"listitem",className:"border-t border-line",children:[t.jsxs("button",{type:"button","data-job-row":!0,"data-job-status":e.status,"data-job-index":c,"data-depth":r.depth,onClick:()=>p(P=>!P),onFocus:()=>l(c),style:r.depth>0?{paddingLeft:18+r.depth*20}:void 0,className:`w-full text-left grid grid-cols-[116px_1fr_auto_auto] items-center gap-4 px-[18px] py-3.5 hover:bg-bg/40 focus:outline-none focus:ring-1 focus:ring-accent focus:ring-inset ${o?"bg-bg-elev/40":""}`,"aria-expanded":o,"aria-label":`${ie(e.slug)?`PRD ${ie(e.slug)}, `:""}${e.title}, ${e.status}${E?`, ${E}`:""}`,title:e.title,children:[t.jsx(_t,{status:e.status}),t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-baseline gap-2 text-[14.5px] font-medium text-fg leading-snug",children:[ie(e.slug)&&t.jsx(Ot,{n:ie(e.slug)}),e.title,t.jsx(Lt,{leaked:e.leakedDescendants}),t.jsx(ks,{count:e.leftoverCount,truncated:e.leftoverPathsTruncated,salvagePatch:e.salvagePatch}),r.parallelEligible&&t.jsx("span",{"data-testid":"job-row-parallel-eligible",title:"No dependsOn, and nothing in this Epic depends on it — can run any time a slot is free",className:"text-[10px] font-semibold uppercase tracking-wide text-sage/90 bg-sage/10 border border-sage/30 rounded px-1.5 py-0.5",children:"parallel"})]}),r.cycle&&t.jsxs("div",{className:"text-[12.5px] mt-0.5 text-accent font-mono","data-testid":"job-row-cycle-warning",children:["⚠ dependsOn cycle — ",r.blockers.map(P=>P.slug).join(" ↔ ")||"self-referencing"]}),!r.cycle&&r.blockers.length>0&&t.jsxs("div",{className:"text-[12.5px] mt-0.5 font-mono","data-testid":"job-row-blockers",children:[t.jsx("span",{className:r.blocked||r.hasMissingDep?"text-amber-400/90":"text-fg-faint",children:r.blocked||r.hasMissingDep?"blocked by ":"depends on "}),r.blockers.map((P,O)=>t.jsxs("span",{className:ra(P),children:[O>0&&", ",aa(P)]},P.slug))]}),T&&t.jsx("div",{className:`text-[12.5px] mt-0.5 ${k?"text-accent/80":"text-fg-faint"}`,children:T}),i&&t.jsx("div",{className:"text-[12.5px] mt-0.5 text-amber-400/90 font-mono","data-testid":"job-row-hold",children:i.dep?t.jsxs(t.Fragment,{children:["held · waiting on ",i.dep," (",i.depStatus,")"]}):t.jsxs(t.Fragment,{children:["held · ",i.reason??"launch blocked"]})}),!i&&e.status==="pending"&&e.heldReason&&t.jsxs("div",{className:"text-[12.5px] mt-0.5 text-amber-400/90 font-mono","data-testid":"job-row-held-reason",children:["held · ",e.heldReason]}),t.jsx(rt,{epicId:x.epicId,label:x.label?Yt(x.label):null,onOpen:j,testId:"job-row-prompt-session-chip",className:"mt-0.5"})]}),t.jsx(it,{cwd:e.cwd}),t.jsxs("span",{className:"inline-flex items-center gap-2.5 font-mono text-xs text-fg-faint shrink-0",children:[t.jsx(Ss,{status:e.status,overrun:e.overrun}),E,t.jsx("span",{className:`text-fg-faint inline-flex transition-transform duration-150 ${o?"rotate-90":""}`,"aria-hidden":"true",children:t.jsx(nt,{name:"chevron",size:14})})]})]}),D&&!o&&t.jsx("div",{className:"h-1 bg-line mx-[18px] mb-3 rounded-full overflow-hidden",children:t.jsx("div",{className:"h-full bg-accent transition-all duration-1000",style:{width:`${Math.max(4,$*100)}%`}})}),o&&t.jsxs("div",{className:"px-[18px] py-5 grid grid-cols-[repeat(auto-fit,minmax(160px,1fr))] gap-5 bg-bg-elev/50 border-t border-line",children:[t.jsxs(re,{label:"Status",children:[t.jsx(H,{k:"result",v:e.exitCode!==null?`exit ${e.exitCode}`:"—"}),t.jsx(H,{k:"state",v:e.status.replace(/_/g," ")}),e.verifierVerdict&&t.jsx(H,{k:"verdict",v:$e(e.verifierVerdict)}),e.leakedDescendants&&e.leakedDescendants.length>0&&t.jsx(H,{k:"leaked",v:Ft(e.leakedDescendants),wrap:!0}),e.leftoverCount!=null&&e.leftoverCount>0&&t.jsx(H,{k:"uncommitted",v:`${e.leftoverCount} file${e.leftoverCount===1?"":"s"}${e.leftoverPathsTruncated?"+":""}: ${(e.leftoverPaths??[]).join(", ")}${e.salvagePatch?` — salvaged to ${e.salvagePatch}`:""}`,wrap:!0}),m&&t.jsx(H,{k:"error",v:m.split(`
|
|
5
|
+
`)[0],wrap:!0})]}),e.statusHistory&&e.statusHistory.length>0&&t.jsx(re,{label:"History",children:t.jsx("div",{className:"grid gap-1",children:e.statusHistory.map((P,O)=>t.jsxs("div",{className:"font-mono text-xs leading-relaxed",children:[t.jsxs("div",{className:"text-fg",children:[P.from??"(new)"," → ",P.to,t.jsxs("span",{className:"text-fg-faint",children:[" · ",le(Date.parse(P.at))]})]}),P.reason&&t.jsx("div",{className:"text-fg-faint break-words",children:P.reason})]},O))})}),t.jsxs(re,{label:"Timing",children:[t.jsx(H,{k:"started",v:e.startedAt?le(Date.parse(e.startedAt)):"—"}),t.jsx(H,{k:"finished",v:e.finishedAt?le(Date.parse(e.finishedAt)):"—"}),t.jsx(H,{k:"duration",v:e.startedAt&&e.finishedAt?Ce(Date.parse(e.finishedAt)-Date.parse(e.startedAt)):D&&n!==null?Te(n):"—"})]}),t.jsxs(re,{label:"Location",children:[t.jsx(H,{k:"group",v:`${e.parallelGroup} · ${e.slug}`}),t.jsx(H,{k:"cwd",v:e.cwd??"—",wrap:!0}),t.jsx(H,{k:"session",v:x.label??x.epicId??"—",wrap:!0}),t.jsx(H,{k:"session id",v:x.epicId??"—",wrap:!0}),t.jsx(H,{k:"prompt id",v:e.sourcePromptId??"—",wrap:!0}),t.jsx(H,{k:"source tab",v:e.sourceTabId??"—",wrap:!0})]}),t.jsx(re,{label:"Actions",children:t.jsxs("div",{className:"flex flex-col gap-1.5 items-start",children:[w&&t.jsx("button",{type:"button","data-testid":"job-row-prompt-session-link",title:w.goalText,onClick:()=>j(w.id),className:"text-[13px] font-semibold text-accent hover:text-accent/80 bg-transparent border-0 cursor-pointer p-0",children:"view epic →"}),e.runId&&t.jsx("button",{type:"button",onClick:()=>h(!0),className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border-0 cursor-pointer p-0",children:"view log →"}),e.status==="quarantined"&&t.jsx("button",{type:"button","data-testid":"job-row-adopt-prd",title:"Stamp this PRD's provenance so the scheduler will run it — no unstamped PRD runs automatically.",onClick:()=>{window.api.schedule.adoptPrd(e.slug).then(q.fromOutcome).catch(()=>q.error("Failed to adopt PRD"))},className:"text-[13px] font-semibold text-accent hover:text-accent/80 bg-transparent border-0 cursor-pointer p-0",children:"adopt PRD →"}),e.status!=="pending"&&e.status!=="running"&&e.status!=="quarantined"&&t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resetJob(e.slug,e.cwd??void 0),className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border-0 cursor-pointer p-0",children:"reset to pending →"}),e.disposition&&(e.status==="pending"||e.status==="quarantined")&&t.jsx(Jt,{job:e,headChoices:d})]})})]}),u&&e.runId&&t.jsx(qe,{runId:e.runId,slug:e.slug,title:e.title||e.slug,onClose:()=>h(!1)})]})}const la=f.memo(ia);function oa({supervisorConfig:e,onSetConfig:s,onBack:n}){const[a,c]=f.useState([]),[l,i]=f.useState(()=>Date.now()),r=st();f.useEffect(()=>{if(!r)return;window.api.supervisor.getLog().then(c).catch(()=>{}),i(Date.now());const o=setInterval(()=>i(Date.now()),5e3);return()=>clearInterval(o)},[r]);const d={enabled:(e==null?void 0:e.enabled)??!0,intervalMinutes:(e==null?void 0:e.intervalMinutes)??15,maxConcurrentProbes:(e==null?void 0:e.maxConcurrentProbes)??2,probeStaleThresholdMinutes:(e==null?void 0:e.probeStaleThresholdMinutes)??10};return t.jsxs("div",{className:"bg-bg-elev/60",children:[t.jsxs("div",{className:"px-3 py-2 flex items-center gap-2 border-b border-line",children:[t.jsx("button",{type:"button",onClick:n,className:"text-[10px] text-fg-faint hover:text-fg-dim",title:"Back to queue",children:"← queue"}),t.jsx("span",{className:"text-[11px] font-medium text-fg-dim",children:"Supervisor"}),t.jsx("button",{type:"button",onClick:()=>window.api.supervisor.getLog().then(c).catch(()=>{}),className:"ml-auto text-[10px] text-fg-faint hover:text-fg-dim underline",title:"Refresh log",children:"refresh"})]}),t.jsxs("div",{className:"px-3 py-2 space-y-1.5 border-b border-line",children:[t.jsx("div",{className:"text-[9px] text-fg-faint uppercase tracking-wider",children:"Config"}),t.jsxs("div",{className:"flex items-center gap-3 flex-wrap text-[10px] text-fg-faint",children:[t.jsxs("label",{className:"flex items-center gap-1",children:[t.jsx("input",{type:"checkbox",checked:d.enabled,onChange:o=>s({enabled:o.target.checked}),className:"cursor-pointer"}),t.jsx("span",{children:"enabled"})]}),t.jsxs("label",{className:"flex items-center gap-1",title:"How often to check for wedged jobs (minutes)",children:[t.jsx("span",{children:"interval"}),t.jsx("input",{type:"number",min:5,max:60,value:d.intervalMinutes,onChange:o=>s({intervalMinutes:Number(o.target.value)}),className:"w-10 bg-bg border border-line rounded px-1 py-0.5 font-mono"}),t.jsx("span",{children:"min"})]}),t.jsxs("label",{className:"flex items-center gap-1",title:"Max concurrent Opus probes per tick",children:[t.jsx("span",{children:"probes"}),t.jsx("input",{type:"number",min:1,max:5,value:d.maxConcurrentProbes,onChange:o=>s({maxConcurrentProbes:Number(o.target.value)}),className:"w-8 bg-bg border border-line rounded px-1 py-0.5 font-mono"})]}),t.jsxs("label",{className:"flex items-center gap-1",title:"Probe a job only if no JSONL event in this many minutes",children:[t.jsx("span",{children:"stale"}),t.jsx("input",{type:"number",min:5,max:30,value:d.probeStaleThresholdMinutes,onChange:o=>s({probeStaleThresholdMinutes:Number(o.target.value)}),className:"w-8 bg-bg border border-line rounded px-1 py-0.5 font-mono"}),t.jsx("span",{children:"min"})]})]})]}),t.jsxs("div",{className:"px-3 py-2",children:[t.jsxs("div",{className:"text-[9px] text-fg-faint uppercase tracking-wider mb-1",children:["Recent probes (last ",a.length,")"]}),a.length===0?t.jsx("div",{className:"text-[10px] text-fg-faint italic",children:"No probes yet."}):t.jsx("div",{className:"space-y-0.5 max-h-64 overflow-y-auto",children:a.map((o,p)=>t.jsx(da,{entry:o,now:l},`${o.ts}-${p}`))})]})]})}function da({entry:e,now:s}){const n=e.action!=="none",a=ee(s-e.ts);return t.jsxs("div",{className:`text-[10px] px-1.5 py-1 rounded font-mono ${n?"bg-red-500/10 border border-red-500/20":"bg-bg/40"}`,title:e.reason,children:[t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsxs("span",{className:"text-fg-faint shrink-0",children:[a," ago"]}),t.jsx("span",{className:`shrink-0 px-1 rounded ${e.verdict==="stuck"?"text-red-400 bg-red-500/10":"text-green-500/70"}`,children:e.verdict}),t.jsx("span",{className:"truncate text-fg-dim",children:e.jobSlug}),n&&t.jsxs("span",{className:"shrink-0 text-red-400",children:[e.action,e.targetPid?` pid=${e.targetPid}`:""]}),e.costUsd!==null&&t.jsxs("span",{className:"shrink-0 text-fg-faint",children:["$",e.costUsd.toFixed(3)]})]}),t.jsx("div",{className:"text-fg-faint truncate mt-0.5",children:e.reason})]})}const ca=[{title:"Start a session",body:"In Sessions, pick an Agent and a Mission, describe the outcome you want, then Approve & start. Its thread writes the PRD files into that session's own folder."},{title:"Queue what it wrote",body:"The PRDs tab lists every file the session produced. Queue one, or the whole session, and they appear here."},{title:"Leave it alone",body:"Jobs start themselves inside your window, pause on rate-limit, and resume at the reset. History records how each ended."}],ua=[{term:"Session",def:"One goal, one Claude session, and the folder of PRDs written to reach it."},{term:"PRD",def:"One markdown file = one job. Authored by the session."},{term:"5-hour window",def:"Your Claude billing window, on a rolling clock."},{term:"Session pool",def:"5 slots shared with terminal and session chats."}];function pa({navigate:e}){return t.jsx("div",{className:"overflow-y-auto h-full",children:t.jsx("div",{className:"px-9 py-6 max-w-[900px] mx-auto",children:t.jsxs("div",{className:"bg-bg-hi border border-line rounded-2xl px-9 py-8",children:[t.jsx("h2",{className:"m-0 font-serif text-[25px] font-semibold text-fg",children:"Nothing to run yet — the scheduler needs a session."}),t.jsx("p",{className:"mt-2 mb-6 text-[14.5px] text-fg-dim leading-relaxed max-w-[580px]",children:"You don't write PRDs here. A session breaks its goal into numbered PRD files, and this page runs them in order. Two steps, once."}),t.jsx("div",{className:"grid grid-cols-3 gap-3.5",children:ca.map((s,n)=>{const a=n===0;return t.jsxs("div",{className:`bg-bg border rounded-xl px-4 py-4 flex flex-col gap-2 ${a?"border-accent shadow-[0_0_0_3px_rgba(184,92,52,.09)]":"border-line"}`,children:[t.jsx("span",{className:`w-6 h-6 rounded-full grid place-items-center font-mono text-[12px] font-semibold ${a?"bg-accent text-white":"bg-bg-elev text-fg-dim"}`,children:n+1}),t.jsx("h3",{className:"m-0 text-[15px] font-semibold text-fg",children:s.title}),t.jsx("p",{className:"m-0 text-[13.5px] text-fg-dim leading-relaxed",children:s.body}),a&&t.jsx("button",{type:"button",onClick:()=>e==null?void 0:e("terminal"),className:"self-start bg-accent text-white rounded-lg px-3.5 py-1.5 text-[13px] font-semibold mt-1",children:"Go to Sessions →"})]},s.title)})}),t.jsx("dl",{className:"flex mt-[22px] pt-4 border-t border-line gap-5 flex-wrap",children:ua.map(({term:s,def:n})=>t.jsxs("div",{className:"flex-1 min-w-[150px]",children:[t.jsx("dt",{className:"text-[13.5px] font-semibold text-fg mb-0.5",children:s}),t.jsx("dd",{className:"m-0 text-[12.5px] text-fg-faint leading-relaxed",children:n})]},s))})]})})})}const fa=5e3;let Re=null,Ne=null;async function Mt(e){const s=Date.now();return!(e!=null&&e.fresh)&&Re&&s-Re.at<fa?Re.result:Ne||(Ne=(async()=>{try{const n=await window.api.schedule.lintQueue();return Re={result:n,at:Date.now()},n}finally{Ne=null}})(),Ne)}function ha({health:e,jobCount:s,lastRunAt:n,nextReset:a,now:c,onOpenSupervisor:l}){const[i,r]=f.useState(!1),[d,o]=f.useState(null),[p,u]=f.useState(!1),h=`${s}:${n??""}`;f.useEffect(()=>{let $=!0;return u(!0),Mt().then(P=>{$&&o(P)}).catch(()=>{}).finally(()=>{$&&u(!1)}),()=>{$=!1}},[h]);let g=0,x=0;const w=d?d.reports.filter($=>$.findings.length>0):[];for(const $ of w)for(const P of $.findings)P.severity==="error"?g++:x++;const j=g===0&&x===0,D=d?`graph lint ${g} error${g===1?"":"s"}, ${x} warn${x===1?"":"s"}`:`graph lint ${p?"scanning…":"idle"}`,k=(e==null?void 0:e.consecutiveFailures)??0,m=[e?`${k} poll failure${k===1?"":"s"} in current streak`:null,D].filter(Boolean).join(" · "),T="text-accent hover:underline bg-transparent border-0 p-0 cursor-pointer text-[12px]";return t.jsxs("div",{"data-testid":"scheduler-footer",className:"border-t border-rule-structural",children:[t.jsxs("div",{className:"h-[28px] flex items-center gap-2 px-[18px] font-mono text-[11.5px] text-fg-faint",children:[t.jsx("span",{"data-testid":"footer-summary",className:"truncate",children:m}),t.jsx("button",{type:"button","data-testid":"footer-info","aria-expanded":i,onClick:()=>r($=>!$),className:"bg-transparent border-0 p-0 cursor-pointer",children:t.jsx(me,{title:"Scheduler poll health and queue-lint findings — click for the full detail"})}),t.jsxs("span",{className:"ml-auto flex items-center gap-3 shrink-0",children:[t.jsxs("span",{"data-testid":"footer-timing",children:[a?t.jsxs("span",{title:`next 5h reset: ${a}`,children:["reset ",ee(Date.parse(a)-c)]}):null,a&&n?" · ":null,n?t.jsxs("span",{title:n,children:["last run ",ee(c-Date.parse(n))," ago"]}):null]}),t.jsx("button",{type:"button","data-testid":"footer-supervisor",onClick:l,title:"Open supervisor log and settings",className:T,children:"supervisor"}),t.jsx("button",{type:"button","data-testid":"footer-folder",onClick:()=>window.api.schedule.openFolder(),className:T,children:"folder"})]})]}),i&&t.jsxs("div",{"data-testid":"footer-detail",className:"px-[18px] pb-2 space-y-2 font-mono text-[12px] text-fg-dim border-t border-rule-inner pt-2",children:[e&&t.jsxs("div",{className:"space-y-0.5",children:[t.jsxs("div",{children:["booted: ",xe(e.bootedAt,c)]}),t.jsxs("div",{children:["last poll: ",xe(e.lastPollAt,c)," · ",e.lastPollOk?"ok":"failed"]}),e.backoffNextAt!==null&&e.backoffNextAt>c&&t.jsxs("div",{children:["retry in: ",ee(e.backoffNextAt-c)]}),e.nextResetCached&&t.jsxs("div",{children:["cached reset: ",le(Date.parse(e.nextResetCached))]}),e.runningJobs.length>0&&t.jsxs("div",{children:["running: ",e.runningJobs.map($=>`${$.slug}(pid ${$.pid})`).join(", ")]})]}),d&&t.jsxs("div",{className:"space-y-1",children:[j?t.jsxs("div",{className:"text-sage",children:["✓ no issues in ",d.reports.length," PRD",d.reports.length!==1?"s":""]}):w.map($=>t.jsxs("div",{children:[t.jsx("div",{className:"text-fg-dim truncate",title:$.slug,children:$.slug}),$.findings.map((P,O)=>t.jsxs("div",{className:`pl-3 truncate ${P.severity==="error"?"text-accent/80":"text-butter/90"}`,title:P.snippet,children:[P.severity==="error"?"✗":"⚠"," L",P.line,": ",P.snippet]},`${$.slug}-${O}`))]},$.slug)),t.jsx("button",{type:"button","data-testid":"footer-rerun-lint",onClick:()=>{u(!0),Mt({fresh:!0}).then(o).catch(()=>{}).finally(()=>u(!1))},className:"text-fg-faint hover:text-fg-dim underline",children:p?"…":"rerun lint"})]})]})]})}const ga=5,xa=1440*60*1e3,Ie=10,ma=["all","running","investigating","pending","completed","skipped","needs_review","failed","quarantined"];async function ba(e){if(!e)return{text:"",status:"all"};const s=await qt(e);return{text:"",status:ma.includes(s.queueFilterStatus)?s.queueFilterStatus:"all"}}function wa(e,s){return e?Bt(e,{queueFilterStatus:s.status}):Promise.resolve()}function Rt(e,s){if(s.status==="all"&&!s.text)return e;const n=s.text.toLowerCase();return e.filter(a=>{if(s.status!=="all"&&a.status!==s.status)return!1;if(!n)return!0;const c=_e(a.cwd)??"";return a.title.toLowerCase().includes(n)||a.slug.toLowerCase().includes(n)||c.toLowerCase().includes(n)})}async function va(e){if(!e)return new Set;const s=await qt(e);return Array.isArray(s.hiddenCompletedSlugs)?new Set(s.hiddenCompletedSlugs.filter(n=>typeof n=="string")):new Set}function ja(e,s){return e?Bt(e,{hiddenCompletedSlugs:[...s]}):Promise.resolve()}function ya({scopeCwd:e=null,navigate:s,filterText:n,planMode:a="graph",onOpenPrds:c,planToolsEl:l=null}){var mt;const i=Fe(v=>v.snapshot),r=f.useMemo(()=>!i||!e?i:{...i,jobs:i.jobs.filter(v=>v.cwd===e)},[i,e]),[d,o]=f.useState(null),[p,u]=f.useState(()=>Date.now()),[h,g]=f.useState(new Set),[x,w]=f.useState(!1),[j,D]=f.useState({text:"",status:"all"}),k=f.useMemo(()=>n===void 0?j:{...j,text:n},[j,n]),[E,m]=f.useState(!1),[T,$]=f.useState("queue"),P=f.useRef(null),[O,K]=f.useState(0),[W,Q]=f.useState(""),J=st(),te=f.useRef(!1),se=f.useRef(!1),z=f.useRef(h);z.current=h;const M=f.useRef(j);M.current=j,f.useEffect(()=>{let v=!1;return te.current=!1,se.current=!1,va(e).then(I=>{!v&&!te.current&&g(I)}),ba(e).then(I=>{!v&&!se.current&&D(I)}),()=>{v=!0}},[e]),f.useEffect(()=>(window.api.schedule.health().then(o).catch(()=>{}),window.api.schedule.onState(()=>{window.api.schedule.health().then(o).catch(()=>{})})),[]),f.useEffect(()=>{if(!J)return;u(Date.now());const v=setInterval(()=>u(Date.now()),1e3);return()=>clearInterval(v)},[J]);const B=f.useMemo(()=>{if(!r)return 15e4;const v=[];for(const I of r.jobs)if(I.status==="completed"&&I.startedAt&&I.finishedAt){const V=Date.parse(I.finishedAt)-Date.parse(I.startedAt);V>0&&v.push(V)}return v.length===0?15e4:v.reduce((I,V)=>I+V,0)/v.length},[r]),N=f.useRef(new Map);f.useEffect(()=>{if(!r)return;const v=[];for(const I of r.jobs){const V=N.current.get(I.slug);V&&V!==I.status&&v.push(`${I.title}: ${V} → ${I.status}`),N.current.set(I.slug,I.status)}v.length>0&&Q(v.join("; "))},[r]);const S=f.useMemo(()=>{var I;const v=new Map;for(const V of((I=r==null?void 0:r.lastTick)==null?void 0:I.holds)??[])v.set(V.slug,V);return v},[r==null?void 0:r.lastTick]),G=pe(v=>v.sessions),F=f.useMemo(()=>r?Gt(Oe(r.jobs),G,i!=null&&i.jobs?Oe(i.jobs):void 0):[],[r,G,i]),U=Cs(),b=f.useMemo(()=>r?Rt(Nn(r.jobs,U,e),k):[],[r,U,e,k]),y=(mt=r==null?void 0:r.effectiveConcurrency)==null?void 0:mt.cap,A=f.useMemo(()=>a==="list"?[]:lt(b,{sessions:G,avgDurationMs:B,concurrency:y}),[a,b,G,B,y]),[C,R]=f.useState(1),L=A.map(v=>`${v.epicId??""}#${v.waveIndex}`).join(",");f.useEffect(()=>{R(1)},[e,k.status,k.text,L]);const _=Math.max(1,Math.ceil(A.length/Ie)),X=Math.min(C,_),He=f.useMemo(()=>A.slice((X-1)*Ie,X*Ie),[A,X]),as=f.useMemo(()=>{const v=new Map;let I=0;for(const V of A)for(const Y of V.stages)for(const ae of Y.rows)v.set(ae.slug,I++);return v},[A]),rs=f.useMemo(()=>yn(F),[F]),is=h,ot=f.useCallback(v=>{var be;const I=(be=P.current)==null?void 0:be.querySelectorAll("[data-job-row]");if(!I||I.length===0)return;const V=Array.from(I),Y=V.findIndex(ne=>ne.dataset.jobIndex===String(O)),ae=ne=>{const fe=V[ne];if(!fe)return;const he=Number(fe.dataset.jobIndex);K(he),fe.focus()};v.key==="ArrowDown"?(v.preventDefault(),ae(Y===-1?0:Math.min(Y+1,V.length-1))):v.key==="ArrowUp"&&(v.preventDefault(),ae(Y===-1?V.length-1:Math.max(Y-1,0)))},[O]),dt=f.useCallback(v=>{K(v)},[]),ct=f.useCallback(v=>{const I=M.current;se.current=!0,M.current=v,D(v),wa(e,v).catch(()=>{M.current===v&&(M.current=I,D(I),q.error("Couldn't save queue filter — reverted."))})},[e]),ut=f.useCallback(v=>{const I=z.current;te.current=!0,z.current=v,g(v),ja(e,v).catch(()=>{z.current===v&&(z.current=I,g(I),q.error("Couldn't save hidden completed jobs — reverted."))})},[e]);if(!r)return null;if(T==="supervisor")return t.jsx(oa,{supervisorConfig:r.config.supervisor,onSetConfig:v=>window.api.schedule.setConfig({supervisor:v}),onBack:()=>$("queue")});const{jobs:Z,paused:pt,lastRunAt:ls,nextReset:os,effectiveConcurrency:Ge}=r;if(Z.length===0)return t.jsx(pa,{navigate:s});const oe={pending:0,running:0,investigating:0,completed:0,needs_review:0,failed:0};for(const v of Z)v.status in oe&&oe[v.status]++;const Ve=Z.filter(v=>v.status==="running"),ds=Qt({snap:r,now:p,avgDurationMs:B,runningJobs:Ve}),je=Rt(Z,k),cs=Na(je),{inline:De,collapsedCount:We}=ka(je,h,p,x),us=Sa(De,Z,cs,B,ds.kind,p),ft=()=>{const v=new Set(h);for(const I of Z)(I.status==="completed"||I.status==="failed")&&v.add(I.slug);ut(v)},ht=async()=>{const v=Z.filter(Y=>Y.status!=="running").length;if(v===0)return;const I=`Archive ${v} non-running PRD${v===1?"":"s"} and remove from the queue?
|
|
6
6
|
|
|
7
|
-
Files are moved to prds-archived/<timestamp>/ and can be restored from disk. Running jobs are kept.`;if(!window.confirm(I))return;const V=await window.api.schedule.clearQueue();V.ok||q.error(`Clear queue failed: ${V.error??"unknown error"}`)},ht=()=>{ct(new Set),w(!1)},gt=a==="list"?De.some(v=>v.status==="completed"):Z.some(v=>(v.status==="completed"||v.status==="skipped")&&!h.has(v.slug)),fs=Z.filter(v=>(v.status==="completed"||v.status==="failed")&&h.has(v.slug)).length,de=a==="list",Me=de?"":"px-[18px] py-2";return t.jsxs("div",{className:"overflow-y-auto h-full",children:[t.jsx("div",{"aria-live":"polite","aria-atomic":"true",className:"sr-only",children:U}),t.jsxs("div",{className:de?"px-9 py-6 max-w-[1100px] mx-auto space-y-4":"",children:[d&&d.consecutiveFailures>5&&d.lastFailureKind==="meter_rate_limited"&&!ut&&!E&&t.jsx("div",{className:Me,children:t.jsxs("div",{className:de?"flex items-center gap-3 px-4 py-3 bg-amber-400/15 border border-amber-400/30 rounded-xl":"flex items-center gap-3 -mx-[18px] px-[18px] py-1 bg-amber-400/15 border-y border-amber-400/30",children:[t.jsx("span",{"aria-hidden":"true",children:"⚠"}),t.jsxs("span",{className:"text-[13.5px] text-amber-400/90",children:[t.jsx("strong",{className:"font-semibold",children:"Usage meter unavailable"})," — last good reading"," ",xe(d.lastPollAt,p),". Firing on a conservative estimate until it recovers."]}),t.jsx("button",{type:"button",onClick:()=>m(!0),className:"ml-auto text-[12px] text-amber-400/70 hover:text-amber-400 shrink-0",title:"Dismiss this banner. The scheduler continues firing normally.",children:"Dismiss"})]})}),de&&Ge.length>0&&(()=>{const v=(He==null?void 0:He.cap)??5,I=Z.filter(V=>V.status==="pending").length;return t.jsxs("div",{className:`flex items-center gap-2 text-[12px] font-mono ${Me}`,children:[t.jsxs("span",{className:"px-2 py-0.5 rounded bg-amber-400/20 text-amber-400 shrink-0",children:[Ge.length,"/",v," running"]}),I>0&&t.jsxs("span",{className:"text-fg-faint",children:["+",I," ready in this group"]})]})})(),de&&Z.length>0&&t.jsx("div",{className:Me,children:t.jsx(Pa,{showText:n===void 0,filter:k,onChange:dt})}),!de&&t.jsxs("div",{"data-testid":"plan-graph",children:[l&&Ps.createPortal(t.jsx(Ca,{jobCount:je.length,counts:oe,filter:k,onFilter:dt,hiddenInGraph:fs,onUnhideAll:ht,hasInlineCompleted:gt,onClearCompleted:pt,onClearQueue:ft,clearQueueDisabled:Z.every(v=>v.status==="running")}),l),M.length===0&&t.jsx("div",{className:"px-[18px] py-6 text-[13px] text-fg-faint italic",children:"no matching jobs"}),t.jsx("div",{ref:P,role:"list","aria-label":"Job queue",onKeyDown:lt,children:Be.map(v=>t.jsx(Zn,{plan:v,mode:a,now:p,hidden:ls,indexBySlug:rs,headChoicesBySlug:is,onRowFocused:ot,onOpenPrds:c},`${v.epicId??"__none__"}#${v.waveIndex}`))}),t.jsx(ea,{page:X,pageSize:Ie,totalItems:M.length,onPageChange:R})]}),de&&t.jsxs("div",{className:"bg-bg-hi border border-line rounded-2xl overflow-hidden",children:[t.jsxs("div",{className:"flex items-center justify-between px-[18px] py-3 bg-bg-elev",children:[t.jsxs("span",{className:"font-serif text-base font-semibold text-fg",children:[je.length," job",je.length!==1?"s":""]}),t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsxs("span",{className:"font-mono text-[12px] text-fg-faint",children:[oe.pending,"p · ",oe.running,"r · ",oe.completed,"d",oe.failed>0&&t.jsxs("span",{className:"text-accent",children:[" · ",oe.failed,"f"]})]}),gt&&t.jsx("button",{type:"button",onClick:pt,className:"text-[12.5px] text-fg-dim hover:text-fg bg-transparent border-0 cursor-pointer font-medium",title:"Hide completed jobs from this view (queue.json unchanged — they remain in history)",children:"Clear completed"}),t.jsx("button",{type:"button",onClick:ft,disabled:Z.every(v=>v.status==="running"),className:"text-[12px] text-accent border border-accent/40 hover:bg-accent/10 rounded-md px-2.5 py-1 cursor-pointer font-medium disabled:opacity-40 disabled:cursor-not-allowed",title:"Archive every non-running PRD (moved to prds-archived/<timestamp>/) and remove them from the queue. Running jobs are kept.",children:"Archive & clear queue…"})]})]}),De.length===0&&Ve===0&&t.jsx("div",{className:"px-[18px] py-6 text-[13px] text-fg-faint italic",children:"no matching jobs"}),t.jsx("div",{ref:P,role:"list","aria-label":"Job queue",onKeyDown:lt,children:(()=>{const v=new Set(De.map(J=>J.slug));let I=0;return F.map(J=>{const ae=Yt(J),be=J.nodes.map(ne=>{const fe=qe([ne]).filter(he=>v.has(he.row.slug)).map(he=>({node:he,listIndex:I++}));return{headRootSlug:ne.row.slug,rows:fe}}).filter(ne=>ne.rows.length>0);return{section:J,heads:be,headChoices:ae}}).filter(J=>J.heads.length>0).map(({section:J,heads:ae,headChoices:be})=>t.jsx(ta,{section:J,children:ae.map(({headRootSlug:ne,rows:fe},he)=>t.jsxs("div",{"data-testid":"backlog-head-group",children:[ae.length>1&&t.jsxs("div",{className:"px-[18px] pt-2.5 pb-1 text-[11px] font-mono uppercase tracking-wide text-fg-faint bg-bg-elev/30 border-t border-line/60","data-testid":"backlog-head-label",children:["Plan ",he+1," of ",ae.length]}),fe.map(({node:ce,listIndex:hs})=>t.jsx(oa,{job:ce.row,backlog:ce,eta:ps.get(ce.row.slug)??null,elapsedMs:ce.row.status==="running"&&ce.row.startedAt?p-Date.parse(ce.row.startedAt):null,avgDurationMs:B,listIndex:hs,hold:S.get(ce.row.slug),onFocused:ot,headChoices:be.filter(gs=>gs.rootSlug!==ne)},ce.row.slug))]},ne))},J.epicId??"__none__"))})()}),Ve>0&&t.jsxs("button",{type:"button",onClick:()=>w(v=>!v),className:"w-full text-left text-[12px] text-fg-faint hover:text-fg-dim px-[18px] py-3 border-t border-line",title:x?"Re-collapse old/cleared completed":"Show all completed (incl. cleared and >24h)",children:[x?"▾":"▸"," ",Ve," more completed",t.jsx("span",{className:"ml-1.5 font-mono text-[11.5px] text-fg-faint",children:"· fresh & capped at 5 shown inline"}),h.size>0&&t.jsx("span",{className:"ml-2 underline",onClick:v=>{v.stopPropagation(),ht()},children:"un-hide"})]})]}),de&&!ut&&t.jsx("div",{className:Me,children:t.jsxs("div",{className:"flex gap-2.5 bg-sage/10 border border-sage/30 rounded-xl px-3.5 py-2.5 text-[13.5px] text-fg-dim leading-relaxed",children:[t.jsx("span",{"aria-hidden":"true",children:"✓"}),t.jsxs("span",{children:[t.jsx("strong",{className:"font-semibold text-fg",children:"Nothing needed from you."})," ","Close the app if you like — jobs keep running, and History shows how each one ended."]})]})})]}),t.jsx(ga,{health:d,jobCount:Z.length,lastRunAt:os,nextReset:ds,now:p,onOpenSupervisor:()=>C("supervisor")})]})}function ka(e){const s=new Map(e.map(l=>[l.slug,l])),n=l=>(l.dependsOn??[]).filter(i=>{var r;return((r=s.get(i))==null?void 0:r.status)!=="completed"}).length,a=e.filter(l=>l.status==="running"||l.status==="pending").sort((l,i)=>n(l)-n(i)||l.slug.localeCompare(i.slug)),c=new Map;return a.forEach((l,i)=>c.set(l.slug,i)),c}function Sa(e,s,n,a){if(a)return{inline:e,collapsedCount:0};const c=e.filter(o=>o.status==="completed").sort((o,p)=>{const u=o.finishedAt?Date.parse(o.finishedAt):0;return(p.finishedAt?Date.parse(p.finishedAt):0)-u}),l=new Set;let i=0;for(const o of c){if(i>=xa)break;s.has(o.slug)||o.finishedAt&&n-Date.parse(o.finishedAt)>ma||(l.add(o.slug),i++)}const r=[];let d=0;for(const o of e){if(o.status==="failed"&&s.has(o.slug)){d++;continue}if(o.status!=="completed"){r.push(o);continue}l.has(o.slug)?r.push(o):d++}return{inline:r,collapsedCount:d}}function $a(e,s,n,a,c,l){const i=new Map;if(c==="paused"||c==="manual"||c==="auto-throttled"){for(const o of e)i.set(o.slug,null);return i}const r=s.find(o=>o.status==="running"&&o.startedAt),d=r!=null&&r.startedAt?l-Date.parse(r.startedAt):0;for(const o of e){if(o.status!=="pending"){i.set(o.slug,null);continue}const p=n.get(o.slug)??0;let u=p*a;p>0&&(u-=Math.min(a,d)),i.set(o.slug,u<=5e3?"~now":`~${$e(u)}`)}return i}const as=[{label:"All",value:"all"},{label:"Running",value:"running"},{label:"Investigating",value:"investigating"},{label:"Pending",value:"pending"},{label:"Completed",value:"completed"},{label:"Skipped",value:"skipped"},{label:"Needs review",value:"needs_review"},{label:"Failed",value:"failed"},{label:"Quarantined",value:"quarantined"}];function Ca({jobCount:e,counts:s,filter:n,onFilter:a,hiddenInGraph:c,onUnhideAll:l,hasInlineCompleted:i,onClearCompleted:r,onClearQueue:d,clearQueueDisabled:o}){const p="block w-full text-left px-2 py-1 text-[12px] hover:bg-bg-hi disabled:opacity-40 disabled:cursor-not-allowed bg-transparent border-0 cursor-pointer";return t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"font-mono text-[11.5px] text-fg-faint whitespace-nowrap","data-testid":"plan-tools-counts",children:[e," job",e!==1?"s":""," · ",s.pending,"p · ",s.running,"r · ",s.completed,"d",s.failed>0&&t.jsxs("span",{className:"text-accent",children:[" · ",s.failed,"f"]})]}),c>0&&t.jsxs("button",{type:"button",onClick:l,className:"text-[12px] text-fg-faint hover:text-fg-dim underline bg-transparent border-0 cursor-pointer whitespace-nowrap",title:"Show the completed/failed jobs hidden by Clear completed",children:[c," hidden · un-hide"]}),t.jsx("select",{"data-testid":"scheduler-status-filter","aria-label":"Filter by status",value:n.status,onChange:u=>a({...n,status:u.target.value}),className:"bg-bg-hi border border-line rounded px-1 py-0.5 text-[12px] text-fg-dim",title:"Filter the plan graph by job status",children:as.map(u=>t.jsx("option",{value:u.value,children:u.value==="all"?"all statuses":u.label.toLowerCase()},u.value))}),t.jsx(me,{title:"Queue actions",testId:"plan-tools-menu",popoverTestId:"plan-tools-menu-popover",alignRight:!0,glyph:"⋯",widthCls:"w-52",children:t.jsxs("div",{className:"-mx-3 -my-2",children:[i&&t.jsx("button",{type:"button",onClick:r,className:`${p} text-fg-dim`,title:"Hide completed jobs from this view (queue.json unchanged — they remain in history)",children:"Clear completed"}),t.jsx("button",{type:"button",onClick:d,disabled:o,className:`${p} text-accent`,title:"Archive every non-running PRD (moved to prds-archived/<timestamp>/) and remove them from the queue. Running jobs are kept.",children:"Archive & clear queue…"})]})})]})}function Pa({filter:e,onChange:s,showText:n}){const a=as;return t.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[n&&t.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-[320px]",children:[t.jsx("span",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-fg-faint inline-flex","aria-hidden":"true",children:t.jsx(st,{name:"search",size:15})}),t.jsx("input",{type:"text",value:e.text,onChange:c=>s({...e,text:c.target.value}),placeholder:"filter jobs…",className:"w-full bg-bg-hi border border-line rounded-xl py-2 pl-9 pr-3 text-[13.5px] text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint","aria-label":"Filter jobs by title, slug, or project"})]}),t.jsx(Jt,{options:a,value:e.status,onChange:c=>s({...e,status:c})})]})}new Set(Ds.map(e=>e.tag).filter(e=>e!=="discussion"));const Da=["title","cwd","estimateMinutes","parallelGroup","sourcePromptId","sourceTabId","tag","agentType","dependsOn","disposition","planId"];function Ma(e,s){return!Array.isArray(e)||!Array.isArray(s)?!1:e.length===s.length&&e.every((n,a)=>n===s[a])}function Aa(e){if(e==null)return"";if(typeof e=="boolean"||typeof e=="number")return String(e);const s=String(e);return s===""||/^(true|false|null|~)$/.test(s)||/^-?\d+(\.\d+)?$/.test(s)||/^\s|\s$/.test(s)||s.startsWith("'")||s.startsWith('"')||s.includes(`
|
|
8
|
-
`)?s.includes("'")?`"${s.replace(/"/g,'\\"')}"`:`'${s}'`:s}function
|
|
7
|
+
Files are moved to prds-archived/<timestamp>/ and can be restored from disk. Running jobs are kept.`;if(!window.confirm(I))return;const V=await window.api.schedule.clearQueue();V.ok||q.error(`Clear queue failed: ${V.error??"unknown error"}`)},gt=()=>{ut(new Set),w(!1)},xt=a==="list"?De.some(v=>v.status==="completed"):Z.some(v=>(v.status==="completed"||v.status==="skipped")&&!h.has(v.slug)),ps=Z.filter(v=>(v.status==="completed"||v.status==="failed")&&h.has(v.slug)).length,de=a==="list",Ae=de?"":"px-[18px] py-2";return t.jsxs("div",{className:"overflow-y-auto h-full",children:[t.jsx("div",{"aria-live":"polite","aria-atomic":"true",className:"sr-only",children:W}),t.jsxs("div",{className:de?"px-9 py-6 max-w-[1100px] mx-auto space-y-4":"",children:[d&&d.consecutiveFailures>5&&d.lastFailureKind==="meter_rate_limited"&&!pt&&!E&&t.jsx("div",{className:Ae,children:t.jsxs("div",{className:de?"flex items-center gap-3 px-4 py-3 bg-amber-400/15 border border-amber-400/30 rounded-xl":"flex items-center gap-3 -mx-[18px] px-[18px] py-1 bg-amber-400/15 border-y border-amber-400/30",children:[t.jsx("span",{"aria-hidden":"true",children:"⚠"}),t.jsxs("span",{className:"text-[13.5px] text-amber-400/90",children:[t.jsx("strong",{className:"font-semibold",children:"Usage meter unavailable"})," — last good reading"," ",xe(d.lastPollAt,p),". Firing on a conservative estimate until it recovers."]}),t.jsx("button",{type:"button",onClick:()=>m(!0),className:"ml-auto text-[12px] text-amber-400/70 hover:text-amber-400 shrink-0",title:"Dismiss this banner. The scheduler continues firing normally.",children:"Dismiss"})]})}),de&&Ve.length>0&&(()=>{const v=(Ge==null?void 0:Ge.cap)??5,I=Z.filter(V=>V.status==="pending").length;return t.jsxs("div",{className:`flex items-center gap-2 text-[12px] font-mono ${Ae}`,children:[t.jsxs("span",{className:"px-2 py-0.5 rounded bg-amber-400/20 text-amber-400 shrink-0",children:[Ve.length,"/",v," running"]}),I>0&&t.jsxs("span",{className:"text-fg-faint",children:["+",I," ready in this group"]})]})})(),de&&Z.length>0&&t.jsx("div",{className:Ae,children:t.jsx($a,{showText:n===void 0,filter:k,onChange:ct})}),!de&&t.jsxs("div",{"data-testid":"plan-graph",children:[l&&$s.createPortal(t.jsx(Ca,{jobCount:je.length,counts:oe,filter:k,onFilter:ct,hiddenInGraph:ps,onUnhideAll:gt,hasInlineCompleted:xt,onClearCompleted:ft,onClearQueue:ht,clearQueueDisabled:Z.every(v=>v.status==="running")}),l),A.length===0&&t.jsx("div",{className:"px-[18px] py-6 text-[13px] text-fg-faint italic",children:"no matching jobs"}),t.jsx("div",{ref:P,role:"list","aria-label":"Job queue",onKeyDown:ot,children:He.map(v=>t.jsx(Xn,{plan:v,mode:a,now:p,hidden:is,indexBySlug:as,headChoicesBySlug:rs,onRowFocused:dt,onOpenPrds:c},`${v.epicId??"__none__"}#${v.waveIndex}`))}),t.jsx(Zn,{page:X,pageSize:Ie,totalItems:A.length,onPageChange:R})]}),de&&t.jsxs("div",{className:"bg-bg-hi border border-line rounded-2xl overflow-hidden",children:[t.jsxs("div",{className:"flex items-center justify-between px-[18px] py-3 bg-bg-elev",children:[t.jsxs("span",{className:"font-serif text-base font-semibold text-fg",children:[je.length," job",je.length!==1?"s":""]}),t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsxs("span",{className:"font-mono text-[12px] text-fg-faint",children:[oe.pending,"p · ",oe.running,"r · ",oe.completed,"d",oe.failed>0&&t.jsxs("span",{className:"text-accent",children:[" · ",oe.failed,"f"]})]}),xt&&t.jsx("button",{type:"button",onClick:ft,className:"text-[12.5px] text-fg-dim hover:text-fg bg-transparent border-0 cursor-pointer font-medium",title:"Hide completed jobs from this view (queue.json unchanged — they remain in history)",children:"Clear completed"}),t.jsx("button",{type:"button",onClick:ht,disabled:Z.every(v=>v.status==="running"),className:"text-[12px] text-accent border border-accent/40 hover:bg-accent/10 rounded-md px-2.5 py-1 cursor-pointer font-medium disabled:opacity-40 disabled:cursor-not-allowed",title:"Archive every non-running PRD (moved to prds-archived/<timestamp>/) and remove them from the queue. Running jobs are kept.",children:"Archive & clear queue…"})]})]}),De.length===0&&We===0&&t.jsx("div",{className:"px-[18px] py-6 text-[13px] text-fg-faint italic",children:"no matching jobs"}),t.jsx("div",{ref:P,role:"list","aria-label":"Job queue",onKeyDown:ot,children:(()=>{const v=new Set(De.map(Y=>Y.slug));let I=0;return F.map(Y=>{const ae=Kt(Y),be=Y.nodes.map(ne=>{const fe=Be([ne]).filter(he=>v.has(he.row.slug)).map(he=>({node:he,listIndex:I++}));return{headRootSlug:ne.row.slug,rows:fe}}).filter(ne=>ne.rows.length>0);return{section:Y,heads:be,headChoices:ae}}).filter(Y=>Y.heads.length>0).map(({section:Y,heads:ae,headChoices:be})=>t.jsx(ea,{section:Y,children:ae.map(({headRootSlug:ne,rows:fe},he)=>t.jsxs("div",{"data-testid":"backlog-head-group",children:[ae.length>1&&t.jsxs("div",{className:"px-[18px] pt-2.5 pb-1 text-[11px] font-mono uppercase tracking-wide text-fg-faint bg-bg-elev/30 border-t border-line/60","data-testid":"backlog-head-label",children:["Plan ",he+1," of ",ae.length]}),fe.map(({node:ce,listIndex:fs})=>t.jsx(la,{job:ce.row,backlog:ce,eta:us.get(ce.row.slug)??null,elapsedMs:ce.row.status==="running"&&ce.row.startedAt?p-Date.parse(ce.row.startedAt):null,avgDurationMs:B,listIndex:fs,hold:S.get(ce.row.slug),onFocused:dt,headChoices:be.filter(hs=>hs.rootSlug!==ne)},ce.row.slug))]},ne))},Y.epicId??"__none__"))})()}),We>0&&t.jsxs("button",{type:"button",onClick:()=>w(v=>!v),className:"w-full text-left text-[12px] text-fg-faint hover:text-fg-dim px-[18px] py-3 border-t border-line",title:x?"Re-collapse old/cleared completed":"Show all completed (incl. cleared and >24h)",children:[x?"▾":"▸"," ",We," more completed",t.jsx("span",{className:"ml-1.5 font-mono text-[11.5px] text-fg-faint",children:"· fresh & capped at 5 shown inline"}),h.size>0&&t.jsx("span",{className:"ml-2 underline",onClick:v=>{v.stopPropagation(),gt()},children:"un-hide"})]})]}),de&&!pt&&t.jsx("div",{className:Ae,children:t.jsxs("div",{className:"flex gap-2.5 bg-sage/10 border border-sage/30 rounded-xl px-3.5 py-2.5 text-[13.5px] text-fg-dim leading-relaxed",children:[t.jsx("span",{"aria-hidden":"true",children:"✓"}),t.jsxs("span",{children:[t.jsx("strong",{className:"font-semibold text-fg",children:"Nothing needed from you."})," ","Close the app if you like — jobs keep running, and History shows how each one ended."]})]})})]}),t.jsx(ha,{health:d,jobCount:Z.length,lastRunAt:ls,nextReset:os,now:p,onOpenSupervisor:()=>$("supervisor")})]})}function Na(e){const s=new Map(e.map(l=>[l.slug,l])),n=l=>(l.dependsOn??[]).filter(i=>{var r;return((r=s.get(i))==null?void 0:r.status)!=="completed"}).length,a=e.filter(l=>l.status==="running"||l.status==="pending").sort((l,i)=>n(l)-n(i)||l.slug.localeCompare(i.slug)),c=new Map;return a.forEach((l,i)=>c.set(l.slug,i)),c}function ka(e,s,n,a){if(a)return{inline:e,collapsedCount:0};const c=e.filter(o=>o.status==="completed").sort((o,p)=>{const u=o.finishedAt?Date.parse(o.finishedAt):0;return(p.finishedAt?Date.parse(p.finishedAt):0)-u}),l=new Set;let i=0;for(const o of c){if(i>=ga)break;s.has(o.slug)||o.finishedAt&&n-Date.parse(o.finishedAt)>xa||(l.add(o.slug),i++)}const r=[];let d=0;for(const o of e){if(o.status==="failed"&&s.has(o.slug)){d++;continue}if(o.status!=="completed"){r.push(o);continue}l.has(o.slug)?r.push(o):d++}return{inline:r,collapsedCount:d}}function Sa(e,s,n,a,c,l){const i=new Map;if(c==="paused"||c==="manual"||c==="auto-throttled"){for(const o of e)i.set(o.slug,null);return i}const r=s.find(o=>o.status==="running"&&o.startedAt),d=r!=null&&r.startedAt?l-Date.parse(r.startedAt):0;for(const o of e){if(o.status!=="pending"){i.set(o.slug,null);continue}const p=n.get(o.slug)??0;let u=p*a;p>0&&(u-=Math.min(a,d)),i.set(o.slug,u<=5e3?"~now":`~${Ce(u)}`)}return i}const ns=[{label:"All",value:"all"},{label:"Running",value:"running"},{label:"Investigating",value:"investigating"},{label:"Pending",value:"pending"},{label:"Completed",value:"completed"},{label:"Skipped",value:"skipped"},{label:"Needs review",value:"needs_review"},{label:"Failed",value:"failed"},{label:"Quarantined",value:"quarantined"}];function Ca({jobCount:e,counts:s,filter:n,onFilter:a,hiddenInGraph:c,onUnhideAll:l,hasInlineCompleted:i,onClearCompleted:r,onClearQueue:d,clearQueueDisabled:o}){const p="block w-full text-left px-2 py-1 text-[12px] hover:bg-bg-hi disabled:opacity-40 disabled:cursor-not-allowed bg-transparent border-0 cursor-pointer";return t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"font-mono text-[11.5px] text-fg-faint whitespace-nowrap","data-testid":"plan-tools-counts",children:[e," job",e!==1?"s":""," · ",s.pending,"p · ",s.running,"r · ",s.completed,"d",s.failed>0&&t.jsxs("span",{className:"text-accent",children:[" · ",s.failed,"f"]})]}),c>0&&t.jsxs("button",{type:"button",onClick:l,className:"text-[12px] text-fg-faint hover:text-fg-dim underline bg-transparent border-0 cursor-pointer whitespace-nowrap",title:"Show the completed/failed jobs hidden by Clear completed",children:[c," hidden · un-hide"]}),t.jsx("select",{"data-testid":"scheduler-status-filter","aria-label":"Filter by status",value:n.status,onChange:u=>a({...n,status:u.target.value}),className:"bg-bg-hi border border-line rounded px-1 py-0.5 text-[12px] text-fg-dim",title:"Filter the plan graph by job status",children:ns.map(u=>t.jsx("option",{value:u.value,children:u.value==="all"?"all statuses":u.label.toLowerCase()},u.value))}),t.jsx(me,{title:"Queue actions",testId:"plan-tools-menu",popoverTestId:"plan-tools-menu-popover",alignRight:!0,glyph:"⋯",widthCls:"w-52",children:t.jsxs("div",{className:"-mx-3 -my-2",children:[i&&t.jsx("button",{type:"button",onClick:r,className:`${p} text-fg-dim`,title:"Hide completed jobs from this view (queue.json unchanged — they remain in history)",children:"Clear completed"}),t.jsx("button",{type:"button",onClick:d,disabled:o,className:`${p} text-accent`,title:"Archive every non-running PRD (moved to prds-archived/<timestamp>/) and remove them from the queue. Running jobs are kept.",children:"Archive & clear queue…"})]})})]})}function $a({filter:e,onChange:s,showText:n}){const a=ns;return t.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[n&&t.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-[320px]",children:[t.jsx("span",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-fg-faint inline-flex","aria-hidden":"true",children:t.jsx(nt,{name:"search",size:15})}),t.jsx("input",{type:"text",value:e.text,onChange:c=>s({...e,text:c.target.value}),placeholder:"filter jobs…",className:"w-full bg-bg-hi border border-line rounded-xl py-2 pl-9 pr-3 text-[13.5px] text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint","aria-label":"Filter jobs by title, slug, or project"})]}),t.jsx(zt,{options:a,value:e.status,onChange:c=>s({...e,status:c})})]})}new Set(Ps.map(e=>e.tag).filter(e=>e!=="discussion"));const Pa=["title","cwd","estimateMinutes","parallelGroup","sourcePromptId","sourceTabId","tag","agentType","dependsOn","disposition","planId"];function Da(e,s){return!Array.isArray(e)||!Array.isArray(s)?!1:e.length===s.length&&e.every((n,a)=>n===s[a])}function Aa(e){if(e==null)return"";if(typeof e=="boolean"||typeof e=="number")return String(e);const s=String(e);return s===""||/^(true|false|null|~)$/.test(s)||/^-?\d+(\.\d+)?$/.test(s)||/^\s|\s$/.test(s)||s.startsWith("'")||s.startsWith('"')||s.includes(`
|
|
8
|
+
`)?s.includes("'")?`"${s.replace(/"/g,'\\"')}"`:`'${s}'`:s}function Ma(e,s){var c;const n=[];for(const l of Pa){const i=e[l];if(i==null||i===""||Array.isArray(i)&&i.length===0)continue;const r=(c=e._raw)==null?void 0:c[l];if(r&&(Array.isArray(i)?Da(r.parsed,i):r.parsed===i)){n.push(r.line);continue}if(typeof i=="number"){n.push(`${l}: ${i}`);continue}if(Array.isArray(i)){n.push(`${l}: [${i.join(", ")}]`);continue}n.push(`${l}: ${Aa(i)}`)}if(e.extras)for(const l of Object.keys(e.extras)){const i=e.extras[l];!i||!i.lines.length||n.push(i.lines.join(`
|
|
9
9
|
`))}return`---
|
|
10
10
|
${n.join(`
|
|
11
11
|
`)}
|
|
12
12
|
---
|
|
13
|
-
${s}`}function
|
|
13
|
+
${s}`}function Ye(e){return e.filter(s=>!s.archived)}function Ra(e){at(e),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"terminal"}))}function Ke({label:e,tip:s,onClick:n,disabled:a,primary:c}){return t.jsx(Ms,{content:s,align:"bottom-center",children:t.jsx("button",{title:s,onClick:n,disabled:a,className:`px-2 py-0.5 text-xs rounded border disabled:opacity-40 disabled:cursor-not-allowed ${c?"text-accent border-accent/50 hover:bg-bg-hi":"text-fg-dim border-line hover:text-fg hover:bg-bg-hi"}`,children:e})})}function Ia({scopeCwd:e=null}){const[s,n]=f.useState([]),[a,c]=f.useState(null),[l,i]=f.useState(null),[r,d]=f.useState(null),[o,p]=f.useState(!1),[u,h]=f.useState(!0),[g,x]=f.useState(new Set),[w,j]=f.useState(!1),[D,k]=f.useState(!1),[E,m]=f.useState(!1),[T,$]=f.useState(null);f.useEffect(()=>{let b=!0;return window.api.schedule.listPrds().then(y=>{b&&(n(Ye(y)),h(!1))}).catch(y=>{b&&(h(!1),q.error(`Scheduler: failed to load PRD list — ${y instanceof Error?y.message:"unknown error"}`))}),()=>{b=!1}},[]);const P=Fe(b=>b.snapshot),O=pe(b=>b.sessions);f.useEffect(()=>{P&&c(P)},[P]);const K=f.useMemo(()=>[...s].filter(b=>!e||b.cwd===e).sort((b,y)=>y.mtimeMs-b.mtimeMs||b.slug.localeCompare(y.slug)),[s,e]);f.useEffect(()=>{const b=As();b&&i(b);const y=A=>i(A.detail);return window.addEventListener("sm:select-prd",y),()=>window.removeEventListener("sm:select-prd",y)},[]);const W=f.useMemo(()=>(a==null?void 0:a.jobs.find(b=>b.slug===l))??null,[a,l]),Q=vt(W);function J(b){var A;const y=(A=s.find(C=>C.slug===b))==null?void 0:A.cwd;return y?`${y}/session-manager-operations/scheduler/prds/${b}.md`:null}f.useEffect(()=>{if(!l)return;const b=J(l);b&&jt.getState().openFile(b)},[l,s]);function te(b){i(b),d(null),p(!1)}function se(){i(null)}async function z(){if(!l)return;if(!(W!=null&&W.runId)){d("no log available (job has not run yet)"),p(y=>!y);return}const b=await window.api.schedule.readLog(W.runId,l);d(b.ok?b.text??"":`error: ${b.error}`),p(y=>!y)}if(u)return t.jsx(ke,{title:"loading PRDs…"});const M=b=>{x(y=>{const A=new Set(y);return A.has(b)?A.delete(b):A.add(b),A})};!(K.length>0&&K.every(b=>g.has(b.slug)))&&K.some(b=>g.has(b.slug));const N=()=>x(new Set);async function S(){try{const b=await window.api.schedule.listPrds();n(Ye(b))}catch{}}async function G(){const b=`new-prd-${Date.now()}`,y=Ma({title:"New PRD",cwd:"",estimateMinutes:60,parallelGroup:99},`## Task
|
|
14
14
|
|
|
15
15
|
Describe the task here.
|
|
16
|
-
`);try{const M=await window.api.schedule.writePrd(b,y);if(!M.ok){q.error(`Failed to create PRD: ${M.error}`);return}const $=await window.api.schedule.listPrds();n(ze($)),te(b)}catch(M){q.error(`Failed to create PRD: ${M instanceof Error?M.message:String(M)}`)}}async function F(){var b;m(!0),C(null);try{const y=[...g],M=await window.api.schedule.archivePrds(y);if(!M.ok)C(M.error??"archive failed");else{const $=((b=M.results)==null?void 0:b.filter(R=>!R.ok))??[];$.length>0&&q.warn(`Archive: ${$.length} of ${M.results.length} PRD${$.length===1?"":"s"} failed to move`),N(),j(!1),await S()}}catch(y){C(y instanceof Error?y.message:String(y))}finally{m(!1)}}async function W(b,y){m(!0),C(null);try{const M=[];for(const R of g){const L={slug:R};b!==null&&(L.parallelGroup=b),y!==null&&(L.estimateMinutes=y),M.push(L)}const $=await window.api.schedule.retagPrds(M);if(!$.ok)C($.error??"retag failed");else{N(),k(!1),await S();for(const R of $.results)if(R.newSlug&&R.newSlug!==R.slug){const L=Y(R.slug),_=Y(R.newSlug);L&&_&&jt.getState().renameOpenFile(L,_)}l&&$.results.some(R=>R.slug===l&&R.newSlug&&R.newSlug!==R.slug)&&i(null)}}catch(M){C(M instanceof Error?M.message:String(M))}finally{m(!1)}}return t.jsxs(t.Fragment,{children:[l?t.jsxs("div",{className:"h-full flex flex-col min-h-0",children:[t.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-line flex-wrap shrink-0",children:[t.jsx("button",{type:"button",onClick:se,className:"text-[11px] text-fg-faint hover:text-fg",children:"← PRDs"}),t.jsx("span",{className:"font-mono text-xs text-fg-dim truncate",children:l}),t.jsx(yt,{status:Q}),t.jsx("div",{className:"flex-1"}),t.jsx(Je,{label:"Reset",tip:"Reset failed job to pending",onClick:()=>{var b;window.api.schedule.resetJob(l,((b=s.find(y=>y.slug===l))==null?void 0:b.cwd)||void 0)},disabled:Q!=="failed"}),t.jsx(Je,{label:"Run now",tip:"Run all pending jobs immediately",onClick:()=>{Nt()}}),t.jsx(Je,{label:o?"Hide log":"Last run log",tip:"Toggle most recent run log",onClick:z})]}),t.jsx("div",{className:"flex-1 min-h-0",children:t.jsx(Ms,{})}),o&&r!==null&&t.jsxs("div",{className:"border-t border-line max-h-64 overflow-auto bg-bg-elev",children:[t.jsxs("div",{className:"px-3 py-1.5 flex items-center gap-2 border-b border-line sticky top-0 bg-bg-elev",children:[t.jsxs("span",{className:"text-[10px] text-fg-faint font-mono",children:["run log",U!=null&&U.runId?` — ${U.runId}`:""]}),t.jsx("button",{onClick:()=>p(!1),className:"ml-auto text-[10px] text-fg-faint hover:text-fg",children:"close"})]}),t.jsx("pre",{className:"p-3 text-[11px] font-mono text-fg-dim whitespace-pre-wrap",children:r})]})]}):t.jsxs("div",{className:"px-6 py-5 overflow-auto",children:[t.jsxs("div",{className:"flex items-start justify-between mb-5 gap-4",children:[t.jsxs("p",{className:"text-[14px] text-fg-dim leading-relaxed max-w-[560px]",children:["PRDs are the source the scheduler runs from. Each one becomes a"," ",t.jsx("code",{className:"font-mono text-[13px]",children:"claude -p"})," job when you queue it. This is where you write and edit the source — to watch a run in progress, use the Queue tab."]}),t.jsx("button",{type:"button",onClick:G,className:"shrink-0 bg-accent text-white rounded-lg px-4 py-[9px] text-[13.5px] font-semibold leading-none",children:"+ New PRD"})]}),g.size>0&&t.jsxs("div",{className:"mb-4 px-4 py-2 bg-bg border border-line rounded-lg flex items-center gap-2",children:[t.jsxs("span",{className:"text-xs text-fg-dim",children:[g.size," selected"]}),t.jsx("div",{className:"flex-1"}),t.jsx("button",{type:"button",onClick:()=>j(!0),className:"text-xs px-3 py-1.5 rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:"Archive…"}),t.jsx("button",{type:"button",onClick:()=>k(!0),className:"text-xs px-3 py-1.5 rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:"Retag…"}),t.jsx("button",{type:"button",onClick:N,className:"text-xs px-3 py-1.5 rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:"Clear"})]}),K.length===0?t.jsx(ke,{title:"no PRDs found"}):t.jsx("div",{className:"grid gap-3",children:K.map(b=>{const y=a==null?void 0:a.jobs.find(_=>_.slug===b.slug),M=vt(y),$=Pe({epicId:b.epicId??(y==null?void 0:y.epicId)??null,sourcePromptId:b.sourcePromptId??(y==null?void 0:y.sourcePromptId)??null,sourceTabId:(y==null?void 0:y.sourceTabId)??null},O),R=(y==null?void 0:y.status)==="running",L=(y==null?void 0:y.status)==="needs_review";return t.jsxs("div",{className:"flex items-stretch bg-bg-elev border border-line rounded-2xl overflow-hidden",children:[t.jsx("label",{className:"flex items-center px-3 cursor-pointer hover:bg-bg-hi",children:t.jsx("input",{type:"checkbox",checked:g.has(b.slug),onChange:()=>A(b.slug),className:"accent-accent w-3.5 h-3.5"})}),t.jsxs("div",{className:"flex-1 min-w-0 py-4 pr-2",children:[t.jsxs("div",{className:"flex items-center gap-2.5 mb-[5px] flex-wrap",children:[ie(b.slug)&&t.jsx(Ot,{n:ie(b.slug)}),t.jsx("button",{type:"button",onClick:()=>te(b.slug),className:"font-serif text-[18px] font-semibold text-fg leading-tight hover:underline text-left",children:b.title||b.slug}),t.jsx(yt,{status:M}),(y==null?void 0:y.status)&&t.jsx("span",{className:"sr-only",children:y.status})]}),t.jsxs("div",{className:"flex items-center gap-4 font-mono text-xs text-fg-faint flex-wrap",children:[t.jsx(rt,{cwd:b.cwd}),t.jsx(at,{epicId:$.epicId,label:$.label,onOpen:Ia}),b.estimateMinutes!=null&&t.jsxs("span",{children:[b.estimateMinutes,"m"]}),t.jsxs("span",{className:"opacity-60",title:"parallelGroup — a unique-per-PRD display hint, never an ordering barrier. dependsOn is the real ordering primitive.",children:["g",b.parallelGroup]}),b.dependsOn&&b.dependsOn.length>0&&t.jsxs("span",{title:`depends on: ${b.dependsOn.join(", ")}`,children:["⛓ ",b.dependsOn.length," dep",b.dependsOn.length===1?"":"s"]}),t.jsxs("span",{children:["edited ",xe(b.mtimeMs,Date.now())]})]}),t.jsx("button",{type:"button",onClick:()=>te(b.slug),className:"mt-1.5 font-mono text-[11px] text-fg-faint hover:text-fg-dim leading-none",children:b.slug}),L&&t.jsxs("div",{className:"mt-3 space-y-2",children:[(y==null?void 0:y.verifierVerdict)&&t.jsxs("div",{className:"text-xs text-fg-faint",children:["verdict: ",t.jsx("span",{className:"font-mono",children:Ce(y.verifierVerdict)})]}),t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resetJob(b.slug,b.cwd||void 0),className:"text-xs px-2.5 py-1 rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:"Re-fire"})]})]}),t.jsx("div",{className:"flex flex-col gap-2 items-stretch px-[18px] py-4",children:t.jsx("button",{type:"button",onClick:()=>{Nt()},disabled:R,className:"bg-fg text-bg rounded-lg px-[18px] py-2 text-[13px] font-semibold whitespace-nowrap disabled:opacity-50",children:R?"Running…":"Queue job"})})]},b.slug)})})]}),t.jsx(Ta,{open:w,count:g.size,busy:E,onClose:()=>j(!1),onConfirm:F}),t.jsx(_a,{open:D,count:g.size,busy:E,onClose:()=>k(!1),onConfirm:W})]})}function Ta({open:e,count:s,busy:n,onClose:a,onConfirm:c}){return t.jsxs(Ht,{open:e,onClose:a,title:"Archive PRDs",children:[t.jsxs("p",{className:"text-xs text-fg-dim",children:["Move ",t.jsx("span",{className:"font-mono",children:s})," PRD",s===1?"":"s"," to"," ",t.jsx("span",{className:"font-mono",children:"prds-archived/<timestamp>/"}),"?"]}),t.jsx("p",{className:"text-[10px] text-fg-faint mt-2",children:"Files are renamed, never deleted. Restore manually from disk if needed."}),t.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[t.jsx("button",{type:"button",onClick:a,disabled:n,className:"px-2 py-1 text-xs border border-line rounded text-fg-dim hover:text-fg disabled:opacity-40",children:"Cancel"}),t.jsx("button",{type:"button",onClick:c,disabled:n||s===0,className:"px-2 py-1 text-xs border border-accent/60 text-accent rounded hover:bg-bg-hi disabled:opacity-40",children:n?"Archiving…":`Archive ${s}`})]})]})}function _a({open:e,count:s,busy:n,onClose:a,onConfirm:c}){const[l,i]=f.useState(""),[r,d]=f.useState(""),[o,p]=f.useState(null);f.useEffect(()=>{e&&(i(""),d(""),p(null))},[e]);function u(){p(null);let h=null,g=null;if(l.trim()){const x=Number(l);if(!Number.isInteger(x)||x<0||x>999){p("parallelGroup must be 0–999");return}h=x}if(r.trim()){const x=Number(r);if(!Number.isInteger(x)||x<=0){p("estimateMinutes must be a positive integer");return}g=x}if(h===null&&g===null){p("set at least one field");return}c(h,g)}return t.jsxs(Ht,{open:e,onClose:a,title:"Retag PRDs",children:[t.jsxs("p",{className:"text-xs text-fg-dim",children:["Update ",t.jsx("span",{className:"font-mono",children:s})," PRD",s===1?"":"s",". Leave a field blank to keep its current value."]}),t.jsxs("p",{className:"text-[10px] text-fg-faint mt-2",children:["Changing parallelGroup on an ",t.jsx("span",{className:"font-mono",children:"NN-kebab"})," slug renames the file. Every change is logged to ",t.jsx("span",{className:"font-mono",children:"retag-log.jsonl"})," so it's reversible."]}),t.jsxs("div",{className:"mt-3 space-y-2",children:[t.jsxs("label",{className:"flex items-center gap-2 text-xs",children:[t.jsx("span",{className:"w-32 text-fg-faint",children:"parallelGroup:"}),t.jsx("input",{type:"number",min:0,max:999,value:l,onChange:h=>i(h.target.value),placeholder:"(unchanged)",className:"flex-1 bg-bg border border-line rounded px-2 py-1 font-mono text-xs"})]}),t.jsxs("label",{className:"flex items-center gap-2 text-xs",children:[t.jsx("span",{className:"w-32 text-fg-faint",children:"estimateMinutes:"}),t.jsx("input",{type:"number",min:1,value:r,onChange:h=>d(h.target.value),placeholder:"(unchanged)",className:"flex-1 bg-bg border border-line rounded px-2 py-1 font-mono text-xs"})]})]}),o&&t.jsx("div",{className:"mt-2 text-[10px] text-red-300",children:o}),t.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[t.jsx("button",{type:"button",onClick:a,disabled:n,className:"px-2 py-1 text-xs border border-line rounded text-fg-dim hover:text-fg disabled:opacity-40",children:"Cancel"}),t.jsx("button",{type:"button",onClick:u,disabled:n||s===0,className:"px-2 py-1 text-xs border border-accent/60 text-accent rounded hover:bg-bg-hi disabled:opacity-40",children:n?"Retagging…":`Retag ${s}`})]})]})}function Oa(e){nt(e),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"terminal"}))}function It(e){return e?e.slice(0,10):""}const La=[{value:"all",label:"All"},{value:"completed",label:"Completed"},{value:"skipped",label:"Skipped"},{value:"failed",label:"Failed"}];function Fa({scopeCwd:e=null}){const[s,n]=f.useState(null),[a,c]=f.useState(!0),[l,i]=f.useState(""),[r,d]=f.useState(""),[o,p]=f.useState(""),[u,h]=f.useState("all");f.useEffect(()=>{c(!0),window.api.schedule.getHistory().then(j=>n(j)).catch(j=>n({ok:!1,jobs:[],error:j instanceof Error?j.message:String(j)})).finally(()=>c(!1))},[]);const g=f.useMemo(()=>{if(!(s!=null&&s.jobs))return[];const j=new Set;for(const D of s.jobs){const k=Te(D.cwd);k&&j.add(k)}return[...j].sort()},[s]),x=f.useMemo(()=>s!=null&&s.jobs?s.jobs.filter(j=>!(e&&j.cwd!==e||u!=="all"&&j.status!==u||l&&Te(j.cwd)!==l||r&&It(j.finishedAt)<r||o&&It(j.finishedAt)>o)):[],[s,u,l,r,o,e]);if(a)return t.jsx(ke,{title:"Loading history…"});if(!(s!=null&&s.ok)||s.error)return t.jsxs("div",{className:"p-4 text-xs text-red-300",children:["Failed to load history: ",(s==null?void 0:s.error)??"unknown error"]});if(s.jobs.length===0)return t.jsx(ke,{title:"No history yet",hint:"Completed and failed jobs appear here."});const w=u!=="all"||!!l||!!r||!!o;return t.jsxs("div",{className:"h-full flex flex-col",children:[t.jsxs("div",{className:"shrink-0 flex items-center gap-2 px-4 py-2.5 border-b border-line flex-wrap",children:[t.jsx(Jt,{options:La,value:u,onChange:h,pillPadding:"px-3 py-1"}),t.jsx("span",{className:"w-px h-4 bg-line mx-1","aria-hidden":"true"}),g.length>0&&t.jsxs("select",{value:l,onChange:j=>i(j.target.value),className:"bg-bg-hi border border-line rounded-lg px-2 py-1 text-[12.5px] text-fg-dim max-w-[12rem] font-medium",children:[t.jsx("option",{value:"",children:"All projects"}),g.map(j=>t.jsx("option",{value:j,children:j},j))]}),t.jsxs("div",{className:"flex items-center gap-1.5 text-[12px] text-fg-faint",children:[t.jsx("span",{children:"from"}),t.jsx("input",{type:"date",value:r,onChange:j=>d(j.target.value),className:"bg-bg-hi border border-line rounded-lg px-2 py-1 text-fg-dim font-mono text-[12px]"})]}),t.jsxs("div",{className:"flex items-center gap-1.5 text-[12px] text-fg-faint",children:[t.jsx("span",{children:"to"}),t.jsx("input",{type:"date",value:o,onChange:j=>p(j.target.value),className:"bg-bg-hi border border-line rounded-lg px-2 py-1 text-fg-dim font-mono text-[12px]"})]}),t.jsxs("span",{className:"text-[12px] text-fg-faint ml-auto font-mono",children:[x.length," / ",s.jobs.length]}),w&&t.jsx("button",{type:"button",onClick:()=>{h("all"),i(""),d(""),p("")},className:"text-[12px] text-fg-faint hover:text-fg-dim underline",children:"clear"})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:x.length===0?t.jsx(ke,{title:"No matches",hint:"Try adjusting the filters."}):t.jsxs("div",{className:"mx-4 my-3 bg-bg-hi border border-line rounded-2xl overflow-hidden",children:[t.jsx("div",{className:"flex items-center px-[18px] py-3 bg-bg-elev",children:t.jsxs("span",{className:"font-serif text-base font-semibold text-fg",children:[x.length," job",x.length!==1?"s":""]})}),x.map(j=>t.jsx(qa,{job:j},`${j.slug}-${j.finishedAt??""}`))]})})]})}function qa({job:e}){const[s,n]=f.useState(!1),[a,c]=f.useState(!1),l=pe(h=>h.sessions),i=f.useMemo(()=>Pe(e,l),[e,l]),r=e.startedAt&&e.finishedAt?Date.parse(e.finishedAt)-Date.parse(e.startedAt):null,d=e.startedAt?new Date(e.startedAt).toLocaleString():"—",o=e.finishedAt?new Date(e.finishedAt).toLocaleString():"—",p=r!==null?$e(r):"—",u=e.exitCode!==null?String(e.exitCode):"—";return t.jsxs("div",{className:"border-t border-line/60",children:[t.jsxs("button",{type:"button",className:`w-full text-left grid items-center gap-4 px-[18px] py-3.5 cursor-pointer transition-colors hover:bg-bg-elev ${s?"bg-bg-elev":"bg-transparent"}`,style:{gridTemplateColumns:"116px 1fr auto auto"},onClick:()=>n(h=>!h),"aria-expanded":s,children:[t.jsx(_t,{status:e.status}),t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-baseline gap-2 text-[14.5px] font-medium text-fg leading-snug text-pretty",children:[e.title,t.jsx(Lt,{leaked:e.leakedDescendants})]}),e.error&&!s&&(e.status==="failed"||e.status==="needs_review")&&t.jsx("div",{className:"text-[12.5px] mt-0.5 text-accent/80 truncate",children:e.error}),i.epicId&&t.jsx("span",{className:"flex mt-0.5",children:t.jsx(at,{epicId:i.epicId,label:i.label,onOpen:Oa})})]}),t.jsx(rt,{cwd:e.cwd}),t.jsxs("span",{className:"inline-flex items-center gap-2.5 font-mono text-xs text-fg-faint whitespace-nowrap",children:[p,t.jsx("span",{className:"inline-flex transition-transform duration-150",style:{transform:s?"rotate(90deg)":"none"},"aria-hidden":"true",children:"›"})]})]}),s&&t.jsxs("div",{className:"grid gap-5 px-[18px] pt-1 pb-5 bg-bg-elev",style:{gridTemplateColumns:"repeat(auto-fit, minmax(160px, 1fr))"},children:[t.jsxs(re,{label:"Status",children:[t.jsx(H,{k:"result",v:u}),t.jsx(H,{k:"state",v:e.status.replace("_"," ")}),e.verifierVerdict&&t.jsx(H,{k:"verifier",v:Ce(e.verifierVerdict)}),e.leakedDescendants&&e.leakedDescendants.length>0&&t.jsx(H,{k:"leaked",v:Ft(e.leakedDescendants),wrap:!0})]}),t.jsxs(re,{label:"Timing",children:[t.jsx(H,{k:"started",v:d}),t.jsx(H,{k:"finished",v:o}),t.jsx(H,{k:"duration",v:p})]}),t.jsxs(re,{label:"Location",children:[t.jsx(H,{k:"group",v:e.parallelGroup!=null?String(e.parallelGroup):"—"}),t.jsx(H,{k:"slug",v:e.slug}),t.jsx(H,{k:"epic",v:i.label??i.epicId??"—",wrap:!0}),e.cwd&&t.jsx(H,{k:"cwd",v:e.cwd,wrap:!0})]}),t.jsx(re,{label:"Actions",children:t.jsxs("div",{className:"flex flex-col gap-2 items-start",children:[e.runId&&t.jsx("button",{type:"button",onClick:h=>{h.stopPropagation(),c(!0)},className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border-0 p-0 cursor-pointer",children:"view log →"}),e.status!=="pending"&&t.jsx("button",{type:"button",onClick:h=>{h.stopPropagation(),window.api.schedule.resetJob(e.slug,e.cwd??void 0)},className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border-0 p-0 cursor-pointer",children:"reset to pending →"}),e.error&&t.jsx("p",{className:"text-[12px] text-accent/90 mt-1 break-words whitespace-pre-wrap max-w-sm m-0",children:e.error})]})})]}),a&&e.runId&&t.jsx(Fe,{runId:e.runId,slug:e.slug,title:e.title||e.slug,onClose:()=>c(!1)})]})}function Ba(e){return e?Object.values(e).reduce((s,n)=>s+(n??[]).reduce((a,c)=>{var l;return a+(((l=c.hooks)==null?void 0:l.length)??0)},0),0):0}function Ha(e){var s,n,a;return e?(((s=e.allow)==null?void 0:s.length)??0)+(((n=e.deny)==null?void 0:n.length)??0)+(((a=e.ask)==null?void 0:a.length)??0):0}function Ga({navigate:e}){const s=Is(),n=ye(m=>m.files),a=ye(m=>m.loadJson),c=ye(m=>m.loadText),l=ye(m=>m.watchFile),i=ye(m=>m.unwatchFile),r=s?Es.resolve("user",s,null):null,d=s?Ts.resolve("user",s,null):null,o=s?`${s}/.claude.json`:null;f.useEffect(()=>{const m=[r,o].filter(Boolean);m.forEach(C=>{n[C]||a(C),l(C)});const T=[d].filter(Boolean);return T.forEach(C=>{n[C]||c(C),l(C)}),()=>{[...m,...T].forEach(C=>i(C))}},[r,d,o]);const[p,u]=f.useState(null);f.useEffect(()=>{if(!s)return;let m=!1;return(async()=>{const{entries:T}=await Vs(`${s}/.claude/skills`);m||u(T.length)})(),()=>{m=!0}},[s]);const h=r?n[r]:null,g=o?n[o]:null,x=d?n[d]:null,w=f.useMemo(()=>{if(!(h!=null&&h.exists)||h.parseError)return null;const m=h.diskData;return m===null||typeof m!="object"||Array.isArray(m)?{}:m},[h]),j=f.useMemo(()=>{if(!(g!=null&&g.exists)||g.parseError)return null;const m=g.diskData;return m===null||typeof m!="object"||Array.isArray(m)?{}:m},[g]),D=h?h.parseError?"invalid JSON":null:"loading…",k=g?g.parseError?"invalid JSON":null:"loading…",E=[{key:"settings",title:"Settings",summary:D??(w?`${Object.keys(w).length} top-level key${Object.keys(w).length===1?"":"s"} configured`:"not configured")},{key:"permissions",title:"Permissions",summary:D??(w?`${Ha(w.permissions)} rule(s) configured`:"not configured")},{key:"hooks",title:"Hooks",summary:D??(w?`${Ba(w.hooks)} hook(s) configured`:"not configured")},{key:"mcp",title:"MCP Servers",summary:k??(j?`${Object.keys(j.mcpServers??{}).length} MCP server(s)`:"not configured")},{key:"system-prompt",title:"System Prompt",summary:x!=null&&x.exists&&x.diskRaw.trim().length>0?`configured (${x.diskRaw.length.toLocaleString()} chars)`:"not set"},{key:"skills",title:"Skills",summary:p===null?"loading…":`${p} skill(s) installed`}];return t.jsxs("section",{className:"border border-line rounded-xl bg-bg-hi px-5 py-4",children:[t.jsx("h2",{className:"m-0 mb-1 font-serif text-[18px] font-semibold text-fg",children:"Global Controls"}),t.jsx("p",{className:"mt-0 mb-3 text-[13px] text-fg-dim leading-relaxed",children:"Machine-wide (user-scope) config state for the tabs that default to global here on Home. Read-only summary — open a card to edit."}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:E.map(m=>t.jsxs("button",{type:"button",onClick:()=>e==null?void 0:e(m.key),className:"text-left border border-line rounded-lg bg-bg px-3 py-2.5 hover:border-accent transition-colors",children:[t.jsx("div",{className:"text-[13px] font-medium text-fg",children:m.title}),t.jsx("div",{className:"mt-0.5 text-[12px] text-fg-dim",children:m.summary})]},m.key))})]})}function Va({navigate:e}){const s=_s(),[n,a]=f.useState(!1),[c,l]=f.useState(!1),[i,r]=f.useState(null);f.useEffect(()=>{let o=!0;return Os().then(p=>{o&&a(p.openToHomeOnLaunch===!0)}),()=>{o=!1}},[]),f.useEffect(()=>{var p,u;let o=!0;return(u=(p=window.api.schedule).worktreeBase)==null||u.call(p).then(h=>{o&&r(h)}).catch(()=>{}),()=>{o=!1}},[]);const d=async o=>{a(o),l(!0);try{await Fs({openToHomeOnLaunch:o})}catch{a(!o),q.error('Failed to save "Open to Home on launch" — try again.')}finally{l(!1)}};return t.jsxs("div",{className:"max-w-[760px] space-y-6",children:[t.jsx(Ga,{navigate:e}),t.jsxs("section",{className:"border border-line rounded-xl bg-bg-hi px-5 py-4",children:[t.jsx("h2",{className:"m-0 mb-1 font-serif text-[18px] font-semibold text-fg",children:"Session pool"}),t.jsxs("p",{className:"mt-0 mb-3 text-[13px] text-fg-dim leading-relaxed",children:["One machine-wide pool of concurrent Claude sessions. Scheduler jobs and Epic chat runs each request a slot before launching; work waits when the pool is full. Adjustable from 0 (pauses new launches) to 10 on the Home tab, default 5 — or pin it with"," ",t.jsx("code",{className:"font-mono text-[12px]",children:"SM_SESSION_SLOTS"})," (clamped 0–10)."]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ls,{total:(s==null?void 0:s.total)??5,inUse:(s==null?void 0:s.inUse)??0,size:"md"}),t.jsx("span",{className:"ml-2 font-mono text-[12.5px] text-fg-faint",children:s?`${s.inUse} / ${s.total} in use`:"loading…"})]}),s&&s.holders.length>0&&t.jsx("ul",{className:"mt-2 mb-0 pl-0 list-none space-y-0.5",children:s.holders.map((o,p)=>t.jsxs("li",{className:"font-mono text-[12px] text-fg-dim",children:[o.owner," ",t.jsxs("span",{className:"text-fg-faint",children:["since ",new Date(o.at).toLocaleTimeString()]})]},p))})]}),t.jsxs("section",{className:"border border-line rounded-xl bg-bg-hi px-5 py-4",children:[t.jsx("h2",{className:"m-0 mb-1 font-serif text-[18px] font-semibold text-fg",children:"Behavior"}),t.jsx("p",{className:"mt-0 mb-3 text-[13px] text-fg-dim leading-relaxed",children:"Cross-project app behavior, independent of any single project's config."}),t.jsx(Us,{checked:n,onChange:d,disabled:c,label:"Open to Home on launch"})]}),t.jsxs("section",{className:"border border-line rounded-xl bg-bg-hi px-5 py-4",children:[t.jsx("h2",{className:"m-0 mb-1 font-serif text-[18px] font-semibold text-fg",children:"On disk"}),t.jsxs("p",{className:"mt-0 mb-2 text-[13px] text-fg-dim leading-relaxed",children:["Global runtime state is deliberately small — everything project-scoped lives inside that project's ",t.jsx("code",{className:"font-mono text-[12px]",children:"session-manager-operations/"})," folder."]}),t.jsxs("ul",{className:"m-0 pl-0 list-none space-y-1 font-mono text-[12px] text-fg-dim",children:[t.jsxs("li",{children:["~/.claude/session-manager/scheduler-machine.json ",t.jsx("span",{className:"text-fg-faint",children:"— policy + pause state"})]}),t.jsxs("li",{"data-testid":"worktree-base-path",children:[i??"…","/session-manager-epic-worktrees/ ",t.jsx("span",{className:"text-fg-faint",children:"— Epic git worktrees (SM_WORKTREE_ROOT overrides)"})]}),t.jsxs("li",{children:["<project>/session-manager-operations/scheduler/state/ ",t.jsx("span",{className:"text-fg-faint",children:"— per-project queue + history"})]}),t.jsxs("li",{children:["<project>/session-manager-operations/scheduler/epics/<epic>/prds/ ",t.jsx("span",{className:"text-fg-faint",children:"— PRD sources, per session"})]})]})]})]})}const Et="sm.schedulerTab.subView";function Ua({navigate:e}={}){var x;const[s,n]=f.useState("graph"),[a,c]=f.useState(""),[l,i]=f.useState(null),[r,d]=f.useState(()=>{const w=localStorage.getItem(Et);return w==="prds"||w==="history"||w==="machine"?w:"queue"}),o=kt(w=>w.tabs),p=kt(w=>w.activeTabId),u=((x=o.find(w=>w.id===p))==null?void 0:x.cwd)??null,h=u;f.useEffect(()=>{u&&(pe.getState().hydrate(u),pe.getState().hydrateArchived(u))},[u]);const g=f.useCallback(w=>{w&&qs(w),d("prds")},[]);return f.useEffect(()=>{localStorage.setItem(Et,r)},[r]),t.jsxs("div",{className:"h-full flex flex-col",children:[t.jsx(jn,{scopeCwd:h,subView:r,onSubView:d,filterText:a,onFilterText:c,planMode:s,onPlanMode:n,planToolsRef:i}),t.jsxs("div",{className:"flex-1 min-h-0",children:[r==="queue"&&t.jsx(Na,{scopeCwd:h,navigate:e,filterText:a,planMode:s,onOpenPrds:g,planToolsEl:l}),r==="prds"&&t.jsx(Ea,{scopeCwd:h}),r==="history"&&t.jsx(Fa,{scopeCwd:h}),r==="machine"&&t.jsx("div",{className:"h-full overflow-y-auto px-9 py-6",children:t.jsx(Va,{navigate:e})})]})]})}const Ya=f.memo(Ua);export{Ya as Scheduler};
|
|
16
|
+
`);try{const A=await window.api.schedule.writePrd(b,y);if(!A.ok){q.error(`Failed to create PRD: ${A.error}`);return}const C=await window.api.schedule.listPrds();n(Ye(C)),te(b)}catch(A){q.error(`Failed to create PRD: ${A instanceof Error?A.message:String(A)}`)}}async function F(){var b;m(!0),$(null);try{const y=[...g],A=await window.api.schedule.archivePrds(y);if(!A.ok)$(A.error??"archive failed");else{const C=((b=A.results)==null?void 0:b.filter(R=>!R.ok))??[];C.length>0&&q.warn(`Archive: ${C.length} of ${A.results.length} PRD${C.length===1?"":"s"} failed to move`),N(),j(!1),await S()}}catch(y){$(y instanceof Error?y.message:String(y))}finally{m(!1)}}async function U(b,y){m(!0),$(null);try{const A=[];for(const R of g){const L={slug:R};b!==null&&(L.parallelGroup=b),y!==null&&(L.estimateMinutes=y),A.push(L)}const C=await window.api.schedule.retagPrds(A);if(!C.ok)$(C.error??"retag failed");else{N(),k(!1),await S();for(const R of C.results)if(R.newSlug&&R.newSlug!==R.slug){const L=J(R.slug),_=J(R.newSlug);L&&_&&jt.getState().renameOpenFile(L,_)}l&&C.results.some(R=>R.slug===l&&R.newSlug&&R.newSlug!==R.slug)&&i(null)}}catch(A){$(A instanceof Error?A.message:String(A))}finally{m(!1)}}return t.jsxs(t.Fragment,{children:[l?t.jsxs("div",{className:"h-full flex flex-col min-h-0",children:[t.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-line flex-wrap shrink-0",children:[t.jsx("button",{type:"button",onClick:se,className:"text-[11px] text-fg-faint hover:text-fg",children:"← PRDs"}),t.jsx("span",{className:"font-mono text-xs text-fg-dim truncate",children:l}),t.jsx(yt,{status:Q}),t.jsx("div",{className:"flex-1"}),t.jsx(Ke,{label:"Reset",tip:"Reset failed job to pending",onClick:()=>{var b;window.api.schedule.resetJob(l,((b=s.find(y=>y.slug===l))==null?void 0:b.cwd)||void 0)},disabled:Q!=="failed"}),t.jsx(Ke,{label:"Run now",tip:"Run all pending jobs immediately",onClick:()=>{Nt()}}),t.jsx(Ke,{label:o?"Hide log":"Last run log",tip:"Toggle most recent run log",onClick:z})]}),t.jsx("div",{className:"flex-1 min-h-0",children:t.jsx(Ds,{})}),o&&r!==null&&t.jsxs("div",{className:"border-t border-line max-h-64 overflow-auto bg-bg-elev",children:[t.jsxs("div",{className:"px-3 py-1.5 flex items-center gap-2 border-b border-line sticky top-0 bg-bg-elev",children:[t.jsxs("span",{className:"text-[10px] text-fg-faint font-mono",children:["run log",W!=null&&W.runId?` — ${W.runId}`:""]}),t.jsx("button",{onClick:()=>p(!1),className:"ml-auto text-[10px] text-fg-faint hover:text-fg",children:"close"})]}),t.jsx("pre",{className:"p-3 text-[11px] font-mono text-fg-dim whitespace-pre-wrap",children:r})]})]}):t.jsxs("div",{className:"px-6 py-5 overflow-auto",children:[t.jsxs("div",{className:"flex items-start justify-between mb-5 gap-4",children:[t.jsxs("p",{className:"text-[14px] text-fg-dim leading-relaxed max-w-[560px]",children:["PRDs are the source the scheduler runs from. Each one becomes a"," ",t.jsx("code",{className:"font-mono text-[13px]",children:"claude -p"})," job when you queue it. This is where you write and edit the source — to watch a run in progress, use the Queue tab."]}),t.jsx("button",{type:"button",onClick:G,className:"shrink-0 bg-accent text-white rounded-lg px-4 py-[9px] text-[13.5px] font-semibold leading-none",children:"+ New PRD"})]}),g.size>0&&t.jsxs("div",{className:"mb-4 px-4 py-2 bg-bg border border-line rounded-lg flex items-center gap-2",children:[t.jsxs("span",{className:"text-xs text-fg-dim",children:[g.size," selected"]}),t.jsx("div",{className:"flex-1"}),t.jsx("button",{type:"button",onClick:()=>j(!0),className:"text-xs px-3 py-1.5 rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:"Archive…"}),t.jsx("button",{type:"button",onClick:()=>k(!0),className:"text-xs px-3 py-1.5 rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:"Retag…"}),t.jsx("button",{type:"button",onClick:N,className:"text-xs px-3 py-1.5 rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:"Clear"})]}),K.length===0?t.jsx(ke,{title:"no PRDs found"}):t.jsx("div",{className:"grid gap-3",children:K.map(b=>{const y=a==null?void 0:a.jobs.find(_=>_.slug===b.slug),A=vt(y),C=Pe({epicId:b.epicId??(y==null?void 0:y.epicId)??null,sourcePromptId:b.sourcePromptId??(y==null?void 0:y.sourcePromptId)??null,sourceTabId:(y==null?void 0:y.sourceTabId)??null},O),R=(y==null?void 0:y.status)==="running",L=(y==null?void 0:y.status)==="needs_review";return t.jsxs("div",{className:"flex items-stretch bg-bg-elev border border-line rounded-2xl overflow-hidden",children:[t.jsx("label",{className:"flex items-center px-3 cursor-pointer hover:bg-bg-hi",children:t.jsx("input",{type:"checkbox",checked:g.has(b.slug),onChange:()=>M(b.slug),className:"accent-accent w-3.5 h-3.5"})}),t.jsxs("div",{className:"flex-1 min-w-0 py-4 pr-2",children:[t.jsxs("div",{className:"flex items-center gap-2.5 mb-[5px] flex-wrap",children:[ie(b.slug)&&t.jsx(Ot,{n:ie(b.slug)}),t.jsx("button",{type:"button",onClick:()=>te(b.slug),className:"font-serif text-[18px] font-semibold text-fg leading-tight hover:underline text-left",children:b.title||b.slug}),t.jsx(yt,{status:A}),(y==null?void 0:y.status)&&t.jsx("span",{className:"sr-only",children:y.status})]}),t.jsxs("div",{className:"flex items-center gap-4 font-mono text-xs text-fg-faint flex-wrap",children:[t.jsx(it,{cwd:b.cwd}),t.jsx(rt,{epicId:C.epicId,label:C.label,onOpen:Ra}),b.estimateMinutes!=null&&t.jsxs("span",{children:[b.estimateMinutes,"m"]}),t.jsxs("span",{className:"opacity-60",title:"parallelGroup — a unique-per-PRD display hint, never an ordering barrier. dependsOn is the real ordering primitive.",children:["g",b.parallelGroup]}),b.dependsOn&&b.dependsOn.length>0&&t.jsxs("span",{title:`depends on: ${b.dependsOn.join(", ")}`,children:["⛓ ",b.dependsOn.length," dep",b.dependsOn.length===1?"":"s"]}),t.jsxs("span",{children:["edited ",xe(b.mtimeMs,Date.now())]})]}),t.jsx("button",{type:"button",onClick:()=>te(b.slug),className:"mt-1.5 font-mono text-[11px] text-fg-faint hover:text-fg-dim leading-none",children:b.slug}),L&&t.jsxs("div",{className:"mt-3 space-y-2",children:[(y==null?void 0:y.verifierVerdict)&&t.jsxs("div",{className:"text-xs text-fg-faint",children:["verdict: ",t.jsx("span",{className:"font-mono",children:$e(y.verifierVerdict)})]}),t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resetJob(b.slug,b.cwd||void 0),className:"text-xs px-2.5 py-1 rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:"Re-fire"})]})]}),t.jsx("div",{className:"flex flex-col gap-2 items-stretch px-[18px] py-4",children:t.jsx("button",{type:"button",onClick:()=>{Nt()},disabled:R,className:"bg-fg text-bg rounded-lg px-[18px] py-2 text-[13px] font-semibold whitespace-nowrap disabled:opacity-50",children:R?"Running…":"Queue job"})})]},b.slug)})})]}),t.jsx(Ea,{open:w,count:g.size,busy:E,onClose:()=>j(!1),onConfirm:F}),t.jsx(Ta,{open:D,count:g.size,busy:E,onClose:()=>k(!1),onConfirm:U})]})}function Ea({open:e,count:s,busy:n,onClose:a,onConfirm:c}){return t.jsxs(Ht,{open:e,onClose:a,title:"Archive PRDs",children:[t.jsxs("p",{className:"text-xs text-fg-dim",children:["Move ",t.jsx("span",{className:"font-mono",children:s})," PRD",s===1?"":"s"," to"," ",t.jsx("span",{className:"font-mono",children:"prds-archived/<timestamp>/"}),"?"]}),t.jsx("p",{className:"text-[10px] text-fg-faint mt-2",children:"Files are renamed, never deleted. Restore manually from disk if needed."}),t.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[t.jsx("button",{type:"button",onClick:a,disabled:n,className:"px-2 py-1 text-xs border border-line rounded text-fg-dim hover:text-fg disabled:opacity-40",children:"Cancel"}),t.jsx("button",{type:"button",onClick:c,disabled:n||s===0,className:"px-2 py-1 text-xs border border-accent/60 text-accent rounded hover:bg-bg-hi disabled:opacity-40",children:n?"Archiving…":`Archive ${s}`})]})]})}function Ta({open:e,count:s,busy:n,onClose:a,onConfirm:c}){const[l,i]=f.useState(""),[r,d]=f.useState(""),[o,p]=f.useState(null);f.useEffect(()=>{e&&(i(""),d(""),p(null))},[e]);function u(){p(null);let h=null,g=null;if(l.trim()){const x=Number(l);if(!Number.isInteger(x)||x<0||x>999){p("parallelGroup must be 0–999");return}h=x}if(r.trim()){const x=Number(r);if(!Number.isInteger(x)||x<=0){p("estimateMinutes must be a positive integer");return}g=x}if(h===null&&g===null){p("set at least one field");return}c(h,g)}return t.jsxs(Ht,{open:e,onClose:a,title:"Retag PRDs",children:[t.jsxs("p",{className:"text-xs text-fg-dim",children:["Update ",t.jsx("span",{className:"font-mono",children:s})," PRD",s===1?"":"s",". Leave a field blank to keep its current value."]}),t.jsxs("p",{className:"text-[10px] text-fg-faint mt-2",children:["Changing parallelGroup on an ",t.jsx("span",{className:"font-mono",children:"NN-kebab"})," slug renames the file. Every change is logged to ",t.jsx("span",{className:"font-mono",children:"retag-log.jsonl"})," so it's reversible."]}),t.jsxs("div",{className:"mt-3 space-y-2",children:[t.jsxs("label",{className:"flex items-center gap-2 text-xs",children:[t.jsx("span",{className:"w-32 text-fg-faint",children:"parallelGroup:"}),t.jsx("input",{type:"number",min:0,max:999,value:l,onChange:h=>i(h.target.value),placeholder:"(unchanged)",className:"flex-1 bg-bg border border-line rounded px-2 py-1 font-mono text-xs"})]}),t.jsxs("label",{className:"flex items-center gap-2 text-xs",children:[t.jsx("span",{className:"w-32 text-fg-faint",children:"estimateMinutes:"}),t.jsx("input",{type:"number",min:1,value:r,onChange:h=>d(h.target.value),placeholder:"(unchanged)",className:"flex-1 bg-bg border border-line rounded px-2 py-1 font-mono text-xs"})]})]}),o&&t.jsx("div",{className:"mt-2 text-[10px] text-red-300",children:o}),t.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[t.jsx("button",{type:"button",onClick:a,disabled:n,className:"px-2 py-1 text-xs border border-line rounded text-fg-dim hover:text-fg disabled:opacity-40",children:"Cancel"}),t.jsx("button",{type:"button",onClick:u,disabled:n||s===0,className:"px-2 py-1 text-xs border border-accent/60 text-accent rounded hover:bg-bg-hi disabled:opacity-40",children:n?"Retagging…":`Retag ${s}`})]})]})}function _a(e){at(e),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"terminal"}))}function It(e){return e?e.slice(0,10):""}const Oa=[{value:"all",label:"All"},{value:"completed",label:"Completed"},{value:"skipped",label:"Skipped"},{value:"failed",label:"Failed"}];function La({scopeCwd:e=null}){const[s,n]=f.useState(null),[a,c]=f.useState(!0),[l,i]=f.useState(""),[r,d]=f.useState(""),[o,p]=f.useState(""),[u,h]=f.useState("all");f.useEffect(()=>{c(!0),window.api.schedule.getHistory().then(j=>n(j)).catch(j=>n({ok:!1,jobs:[],error:j instanceof Error?j.message:String(j)})).finally(()=>c(!1))},[]);const g=f.useMemo(()=>{if(!(s!=null&&s.jobs))return[];const j=new Set;for(const D of s.jobs){const k=_e(D.cwd);k&&j.add(k)}return[...j].sort()},[s]),x=f.useMemo(()=>s!=null&&s.jobs?s.jobs.filter(j=>!(e&&j.cwd!==e||u!=="all"&&j.status!==u||l&&_e(j.cwd)!==l||r&&It(j.finishedAt)<r||o&&It(j.finishedAt)>o)):[],[s,u,l,r,o,e]);if(a)return t.jsx(ke,{title:"Loading history…"});if(!(s!=null&&s.ok)||s.error)return t.jsxs("div",{className:"p-4 text-xs text-red-300",children:["Failed to load history: ",(s==null?void 0:s.error)??"unknown error"]});if(s.jobs.length===0)return t.jsx(ke,{title:"No history yet",hint:"Completed and failed jobs appear here."});const w=u!=="all"||!!l||!!r||!!o;return t.jsxs("div",{className:"h-full flex flex-col",children:[t.jsxs("div",{className:"shrink-0 flex items-center gap-2 px-4 py-2.5 border-b border-line flex-wrap",children:[t.jsx(zt,{options:Oa,value:u,onChange:h,pillPadding:"px-3 py-1"}),t.jsx("span",{className:"w-px h-4 bg-line mx-1","aria-hidden":"true"}),g.length>0&&t.jsxs("select",{value:l,onChange:j=>i(j.target.value),className:"bg-bg-hi border border-line rounded-lg px-2 py-1 text-[12.5px] text-fg-dim max-w-[12rem] font-medium",children:[t.jsx("option",{value:"",children:"All projects"}),g.map(j=>t.jsx("option",{value:j,children:j},j))]}),t.jsxs("div",{className:"flex items-center gap-1.5 text-[12px] text-fg-faint",children:[t.jsx("span",{children:"from"}),t.jsx("input",{type:"date",value:r,onChange:j=>d(j.target.value),className:"bg-bg-hi border border-line rounded-lg px-2 py-1 text-fg-dim font-mono text-[12px]"})]}),t.jsxs("div",{className:"flex items-center gap-1.5 text-[12px] text-fg-faint",children:[t.jsx("span",{children:"to"}),t.jsx("input",{type:"date",value:o,onChange:j=>p(j.target.value),className:"bg-bg-hi border border-line rounded-lg px-2 py-1 text-fg-dim font-mono text-[12px]"})]}),t.jsxs("span",{className:"text-[12px] text-fg-faint ml-auto font-mono",children:[x.length," / ",s.jobs.length]}),w&&t.jsx("button",{type:"button",onClick:()=>{h("all"),i(""),d(""),p("")},className:"text-[12px] text-fg-faint hover:text-fg-dim underline",children:"clear"})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:x.length===0?t.jsx(ke,{title:"No matches",hint:"Try adjusting the filters."}):t.jsxs("div",{className:"mx-4 my-3 bg-bg-hi border border-line rounded-2xl overflow-hidden",children:[t.jsx("div",{className:"flex items-center px-[18px] py-3 bg-bg-elev",children:t.jsxs("span",{className:"font-serif text-base font-semibold text-fg",children:[x.length," job",x.length!==1?"s":""]})}),x.map(j=>t.jsx(Fa,{job:j},`${j.slug}-${j.finishedAt??""}`))]})})]})}function Fa({job:e}){const[s,n]=f.useState(!1),[a,c]=f.useState(!1),l=pe(h=>h.sessions),i=f.useMemo(()=>Pe(e,l),[e,l]),r=e.startedAt&&e.finishedAt?Date.parse(e.finishedAt)-Date.parse(e.startedAt):null,d=e.startedAt?new Date(e.startedAt).toLocaleString():"—",o=e.finishedAt?new Date(e.finishedAt).toLocaleString():"—",p=r!==null?Ce(r):"—",u=e.exitCode!==null?String(e.exitCode):"—";return t.jsxs("div",{className:"border-t border-line/60",children:[t.jsxs("button",{type:"button",className:`w-full text-left grid items-center gap-4 px-[18px] py-3.5 cursor-pointer transition-colors hover:bg-bg-elev ${s?"bg-bg-elev":"bg-transparent"}`,style:{gridTemplateColumns:"116px 1fr auto auto"},onClick:()=>n(h=>!h),"aria-expanded":s,children:[t.jsx(_t,{status:e.status}),t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-baseline gap-2 text-[14.5px] font-medium text-fg leading-snug text-pretty",children:[e.title,t.jsx(Lt,{leaked:e.leakedDescendants})]}),e.error&&!s&&(e.status==="failed"||e.status==="needs_review")&&t.jsx("div",{className:"text-[12.5px] mt-0.5 text-accent/80 truncate",children:e.error}),i.epicId&&t.jsx("span",{className:"flex mt-0.5",children:t.jsx(rt,{epicId:i.epicId,label:i.label,onOpen:_a})})]}),t.jsx(it,{cwd:e.cwd}),t.jsxs("span",{className:"inline-flex items-center gap-2.5 font-mono text-xs text-fg-faint whitespace-nowrap",children:[p,t.jsx("span",{className:"inline-flex transition-transform duration-150",style:{transform:s?"rotate(90deg)":"none"},"aria-hidden":"true",children:"›"})]})]}),s&&t.jsxs("div",{className:"grid gap-5 px-[18px] pt-1 pb-5 bg-bg-elev",style:{gridTemplateColumns:"repeat(auto-fit, minmax(160px, 1fr))"},children:[t.jsxs(re,{label:"Status",children:[t.jsx(H,{k:"result",v:u}),t.jsx(H,{k:"state",v:e.status.replace("_"," ")}),e.verifierVerdict&&t.jsx(H,{k:"verifier",v:$e(e.verifierVerdict)}),e.leakedDescendants&&e.leakedDescendants.length>0&&t.jsx(H,{k:"leaked",v:Ft(e.leakedDescendants),wrap:!0})]}),t.jsxs(re,{label:"Timing",children:[t.jsx(H,{k:"started",v:d}),t.jsx(H,{k:"finished",v:o}),t.jsx(H,{k:"duration",v:p})]}),t.jsxs(re,{label:"Location",children:[t.jsx(H,{k:"group",v:e.parallelGroup!=null?String(e.parallelGroup):"—"}),t.jsx(H,{k:"slug",v:e.slug}),t.jsx(H,{k:"epic",v:i.label??i.epicId??"—",wrap:!0}),e.cwd&&t.jsx(H,{k:"cwd",v:e.cwd,wrap:!0})]}),t.jsx(re,{label:"Actions",children:t.jsxs("div",{className:"flex flex-col gap-2 items-start",children:[e.runId&&t.jsx("button",{type:"button",onClick:h=>{h.stopPropagation(),c(!0)},className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border-0 p-0 cursor-pointer",children:"view log →"}),e.status!=="pending"&&t.jsx("button",{type:"button",onClick:h=>{h.stopPropagation(),window.api.schedule.resetJob(e.slug,e.cwd??void 0)},className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border-0 p-0 cursor-pointer",children:"reset to pending →"}),e.error&&t.jsx("p",{className:"text-[12px] text-accent/90 mt-1 break-words whitespace-pre-wrap max-w-sm m-0",children:e.error})]})})]}),a&&e.runId&&t.jsx(qe,{runId:e.runId,slug:e.slug,title:e.title||e.slug,onClose:()=>c(!1)})]})}function qa(e){return e?Object.values(e).reduce((s,n)=>s+(n??[]).reduce((a,c)=>{var l;return a+(((l=c.hooks)==null?void 0:l.length)??0)},0),0):0}function Ba(e){var s,n,a;return e?(((s=e.allow)==null?void 0:s.length)??0)+(((n=e.deny)==null?void 0:n.length)??0)+(((a=e.ask)==null?void 0:a.length)??0):0}function Ha({navigate:e}){const s=Rs(),n=ye(m=>m.files),a=ye(m=>m.loadJson),c=ye(m=>m.loadText),l=ye(m=>m.watchFile),i=ye(m=>m.unwatchFile),r=s?Is.resolve("user",s,null):null,d=s?Es.resolve("user",s,null):null,o=s?`${s}/.claude.json`:null;f.useEffect(()=>{const m=[r,o].filter(Boolean);m.forEach($=>{n[$]||a($),l($)});const T=[d].filter(Boolean);return T.forEach($=>{n[$]||c($),l($)}),()=>{[...m,...T].forEach($=>i($))}},[r,d,o]);const[p,u]=f.useState(null);f.useEffect(()=>{if(!s)return;let m=!1;return(async()=>{const{entries:T}=await Gs(`${s}/.claude/skills`);m||u(T.length)})(),()=>{m=!0}},[s]);const h=r?n[r]:null,g=o?n[o]:null,x=d?n[d]:null,w=f.useMemo(()=>{if(!(h!=null&&h.exists)||h.parseError)return null;const m=h.diskData;return m===null||typeof m!="object"||Array.isArray(m)?{}:m},[h]),j=f.useMemo(()=>{if(!(g!=null&&g.exists)||g.parseError)return null;const m=g.diskData;return m===null||typeof m!="object"||Array.isArray(m)?{}:m},[g]),D=h?h.parseError?"invalid JSON":null:"loading…",k=g?g.parseError?"invalid JSON":null:"loading…",E=[{key:"settings",title:"Settings",summary:D??(w?`${Object.keys(w).length} top-level key${Object.keys(w).length===1?"":"s"} configured`:"not configured")},{key:"permissions",title:"Permissions",summary:D??(w?`${Ba(w.permissions)} rule(s) configured`:"not configured")},{key:"hooks",title:"Hooks",summary:D??(w?`${qa(w.hooks)} hook(s) configured`:"not configured")},{key:"mcp",title:"MCP Servers",summary:k??(j?`${Object.keys(j.mcpServers??{}).length} MCP server(s)`:"not configured")},{key:"system-prompt",title:"System Prompt",summary:x!=null&&x.exists&&x.diskRaw.trim().length>0?`configured (${x.diskRaw.length.toLocaleString()} chars)`:"not set"},{key:"skills",title:"Skills",summary:p===null?"loading…":`${p} skill(s) installed`}];return t.jsxs("section",{className:"border border-line rounded-xl bg-bg-hi px-5 py-4",children:[t.jsx("h2",{className:"m-0 mb-1 font-serif text-[18px] font-semibold text-fg",children:"Global Controls"}),t.jsx("p",{className:"mt-0 mb-3 text-[13px] text-fg-dim leading-relaxed",children:"Machine-wide (user-scope) config state for the tabs that default to global here on Home. Read-only summary — open a card to edit."}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:E.map(m=>t.jsxs("button",{type:"button",onClick:()=>e==null?void 0:e(m.key),className:"text-left border border-line rounded-lg bg-bg px-3 py-2.5 hover:border-accent transition-colors",children:[t.jsx("div",{className:"text-[13px] font-medium text-fg",children:m.title}),t.jsx("div",{className:"mt-0.5 text-[12px] text-fg-dim",children:m.summary})]},m.key))})]})}function Ga({navigate:e}){const s=Ts(),[n,a]=f.useState(!1),[c,l]=f.useState(!1),[i,r]=f.useState(null);f.useEffect(()=>{let o=!0;return _s().then(p=>{o&&a(p.openToHomeOnLaunch===!0)}),()=>{o=!1}},[]),f.useEffect(()=>{var p,u;let o=!0;return(u=(p=window.api.schedule).worktreeBase)==null||u.call(p).then(h=>{o&&r(h)}).catch(()=>{}),()=>{o=!1}},[]);const d=async o=>{a(o),l(!0);try{await Ls({openToHomeOnLaunch:o})}catch{a(!o),q.error('Failed to save "Open to Home on launch" — try again.')}finally{l(!1)}};return t.jsxs("div",{className:"max-w-[760px] space-y-6",children:[t.jsx(Ha,{navigate:e}),t.jsxs("section",{className:"border border-line rounded-xl bg-bg-hi px-5 py-4",children:[t.jsx("h2",{className:"m-0 mb-1 font-serif text-[18px] font-semibold text-fg",children:"Session pool"}),t.jsxs("p",{className:"mt-0 mb-3 text-[13px] text-fg-dim leading-relaxed",children:["One machine-wide pool of concurrent Claude sessions. Scheduler jobs and Epic chat runs each request a slot before launching; work waits when the pool is full. Adjustable from 0 (pauses new launches) to 10 on the Home tab, default 5 — or pin it with"," ",t.jsx("code",{className:"font-mono text-[12px]",children:"SM_SESSION_SLOTS"})," (clamped 0–10)."]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Os,{total:(s==null?void 0:s.total)??5,inUse:(s==null?void 0:s.inUse)??0,size:"md"}),t.jsx("span",{className:"ml-2 font-mono text-[12.5px] text-fg-faint",children:s?`${s.inUse} / ${s.total} in use`:"loading…"})]}),s&&s.holders.length>0&&t.jsx("ul",{className:"mt-2 mb-0 pl-0 list-none space-y-0.5",children:s.holders.map((o,p)=>t.jsxs("li",{className:"font-mono text-[12px] text-fg-dim",children:[o.owner," ",t.jsxs("span",{className:"text-fg-faint",children:["since ",new Date(o.at).toLocaleTimeString()]})]},p))})]}),t.jsxs("section",{className:"border border-line rounded-xl bg-bg-hi px-5 py-4",children:[t.jsx("h2",{className:"m-0 mb-1 font-serif text-[18px] font-semibold text-fg",children:"Behavior"}),t.jsx("p",{className:"mt-0 mb-3 text-[13px] text-fg-dim leading-relaxed",children:"Cross-project app behavior, independent of any single project's config."}),t.jsx(Vs,{checked:n,onChange:d,disabled:c,label:"Open to Home on launch"})]}),t.jsxs("section",{className:"border border-line rounded-xl bg-bg-hi px-5 py-4",children:[t.jsx("h2",{className:"m-0 mb-1 font-serif text-[18px] font-semibold text-fg",children:"On disk"}),t.jsxs("p",{className:"mt-0 mb-2 text-[13px] text-fg-dim leading-relaxed",children:["Global runtime state is deliberately small — everything project-scoped lives inside that project's ",t.jsx("code",{className:"font-mono text-[12px]",children:"session-manager-operations/"})," folder."]}),t.jsxs("ul",{className:"m-0 pl-0 list-none space-y-1 font-mono text-[12px] text-fg-dim",children:[t.jsxs("li",{children:["~/.claude/session-manager/scheduler-machine.json ",t.jsx("span",{className:"text-fg-faint",children:"— policy + pause state"})]}),t.jsxs("li",{"data-testid":"worktree-base-path",children:[i??"…","/session-manager-epic-worktrees/ ",t.jsx("span",{className:"text-fg-faint",children:"— Epic git worktrees (SM_WORKTREE_ROOT overrides)"})]}),t.jsxs("li",{children:["<project>/session-manager-operations/scheduler/state/ ",t.jsx("span",{className:"text-fg-faint",children:"— per-project queue + history"})]}),t.jsxs("li",{children:["<project>/session-manager-operations/scheduler/epics/<epic>/prds/ ",t.jsx("span",{className:"text-fg-faint",children:"— PRD sources, per session"})]})]})]})]})}const Et="sm.schedulerTab.subView";function Va({navigate:e}={}){var x;const[s,n]=f.useState("graph"),[a,c]=f.useState(""),[l,i]=f.useState(null),[r,d]=f.useState(()=>{const w=localStorage.getItem(Et);return w==="prds"||w==="history"||w==="machine"?w:"queue"}),o=kt(w=>w.tabs),p=kt(w=>w.activeTabId),u=((x=o.find(w=>w.id===p))==null?void 0:x.cwd)??null,h=u;f.useEffect(()=>{u&&(pe.getState().hydrate(u),pe.getState().hydrateArchived(u))},[u]);const g=f.useCallback(w=>{w&&Fs(w),d("prds")},[]);return f.useEffect(()=>{localStorage.setItem(Et,r)},[r]),t.jsxs("div",{className:"h-full flex flex-col",children:[t.jsx(vn,{scopeCwd:h,subView:r,onSubView:d,filterText:a,onFilterText:c,planMode:s,onPlanMode:n,planToolsRef:i}),t.jsxs("div",{className:"flex-1 min-h-0",children:[r==="queue"&&t.jsx(ya,{scopeCwd:h,navigate:e,filterText:a,planMode:s,onOpenPrds:g,planToolsEl:l}),r==="prds"&&t.jsx(Ia,{scopeCwd:h}),r==="history"&&t.jsx(La,{scopeCwd:h}),r==="machine"&&t.jsx("div",{className:"h-full overflow-y-auto px-9 py-6",children:t.jsx(Ga,{navigate:e})})]})]})}const Ka=f.memo(Va);export{Ka as Scheduler};
|