toolroll 0.9.137 → 0.9.138
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/CHANGELOG.md +9 -0
- package/dist/build-review.js +2 -2
- package/dist/operate.js +5 -5
- package/package.json +1 -1
package/dist/operate.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{fetchLocalSkillBundle}from"./plugin-bundle-source.js";import{installSkillBundle,listSkillBundles,removeSkillBundle,rollbackSkillBundle,sweepSkillBundleUpdates}from"./skill-library.js";import{FLEXIBLE_CANDIDATE_FIXED,FLEXIBLE_FILED_PREFIX,flexibleMergeRefusal}from"./agent-thread/guards.js";import{readPiConfiguredModels}from"./agent-thread/providers.js";import{executeTaskHandoff}from"./agent-handoff.js";import{CARD_HELP,configHelp,FLOWS_HELP,LEAD_HELP,MODELS_HELP}from"./cli-help.js";import{legacyLiveLogPath,liveLogPath,liveSubLogPath}from"./live.js";import{parseLiveRecords}from"./live-records.js";import{clearResolvedAgentRequests,fileAgentRequest,listAgentRequests,resolveAgentRequest,waitForAgentRequest}from"./agent-requests.js";import{readStoredGeminiStatus,refreshSubscriptions}from"./subscription-usage.js";import{liveCommandsShown}from"./live-detail.js";import{directChatArmedPass,flexibleArmedPass,flexibleSavedWords,flexibleUncommittedFiles,saveFlexibleBranch}from"./agent-thread/ship.js";import{closeFlexibleThread,flexibleShipNeedsFor,flexibleThreadRecords,flexibleThreadShipTerms,flexibleThreadTitleOf,latestFlexibleShip,removeFlexibleThreadCopy,shipFlexibleThread,stopFlexibleThreadsEverywhere}from"./agent-thread/session.js";import{CARD_SOURCES}from"./card-catalog.js";import{runCardCommand}from"./card-cli.js";import{CARD_PANEL_VALUE_FLAGS,isPanelCardCliInvocation,runPanelCardCommand}from"./panels.js";import{mintSecret}from"./secret-mint.js";import{ACP_AGENTS,ACP_PROVIDER_IDS,isAcpProvider,isKeyedProvider,ownSignInOf}from"./acp-agents.js";import{resolveAcpAgentForRunner,runnerPathOf}from"./acp-inspect.js";import{runAcpChecks}from"./acp-check.js";import{verifyLaunch}from"./acp-attest.js";import{notificationClaimHeld,claimNotifications,finalizeNotification,notificationCommandEnv,notificationDestination}from"./notification-delivery.js";import{adapterPolicy}from"./server/route-policy.js";import{UNSENT_REPLY_MS}from"./telegram.js";import{checkPublicCommand}from"./public-check.js";import{leadNameOf}from"./lead-identity.js";import{modelName,quickLeadModel}from"./lead-route.js";import{maybeTriggerRepair}from"./dispose.js";import{CHECK_LEVEL_HINTS,CHECK_LEVEL_WORDS,isCheckLevel,liveQuickCommand,projectCheckLevel,quickVerifyKey,setProjectCheckLevel,setTaskCheckLevel,suggestQuickCommand}from"./check-levels.js";import{fileAddTestsTask,requestFollowUpChecks,runFollowUpCheck,runWaitingChecks}from"./result-follow-ups.js";import{runBatchChecks}from"./batch-checks.js";import{BATCH_HINT,BATCH_WINDOW_MS,projectBatchChecks,setProjectBatchChecks}from"./batch-policy.js";import{buildReviewPass}from"./build-review.js";import{buildReviewLines,buildReviewOf}from"./review-switch.js";import{steerDestinationWords,steerStandingOf,steerStandingWords}from"./steer-status.js";import{utcMinute}from"./when.js";import{parseProtectedPaths,rulesSummary}from"./approval-policy.js";import{evidencePack,exportDay,ledgerExportChunks,standaloneEvidenceHtml}from"./evidence-pack.js";import{matchesOutsideCheckpoint}from"./ledger-chain.js";import{CLEANUP_CHOICES,bytesWords,cleanupWords,diskBytes,idleCleanupWords,idleWords,parseCleanup,parseIdle,storageReport}from"./storage.js";import{removeStaleTestTemp,tempRoots,testTempFolders}from"./test-temp.js";import{storageSweepSupervisor}from"./storage-sweep-process.js";import{idleStorageSweep,sweepSchedule,sweepScheduleWords}from"./storage-sweep-schedule.js";import{lastSweep,saveSweep,sweepDetails,sweepWords as storageSweepWords}from"./storage-sweep.js";import{removeShared,sharedDepsRoot,sharedUse,unusedShared}from"./shared-deps.js";import{cleanLandedBacklog,gitOf,landedBacklog,reconcileLanded,BACKLOG_DAYS}from"./landed-cleanup.js";import{accessOf,applyTidy,approverStandsNow,withinLens,familyRepoOf,releaseFactsFor,runTidy,tidyDays,tidyDigest,tidyGroups,tidyPreview,TIDY_DEFAULT_DAYS,TIDY_PASS_LIMIT}from"./tidy.js";import{personProof}from"./person-proof.js";import{RemoteMains}from"./remote-main.js";import{checkoutPlan,cleanCheckouts,discardCheckout,finishedCheckouts,slimKeptCheckouts,whyWords}from"./checkout-cleanup.js";import{closeOutCheckouts,closeOutRuns,stoppedWords}from"./run-closeout.js";import{proveFinishedRunsStopped,proveRunStopped}from"./stop-proof.js";import{LIFECYCLE_RETENTION_DAYS,NOTIFICATION_RETENTION_WORDS,notificationLifecyclePreview}from"./notification-retention.js";import{MIN_DAYS,RETENTION_KINDS,countWords,dailyRetention,isRetentionKind,lastSweepAt,parsePeriod,periodLabel,periodWords,retentionPlan,sweepWords}from"./retention.js";import{checkPolicy,parseList,policyParts}from"./policy.js";import{billingOf,budgetHoldWords,budgetLabel,budgetStates,monthNamed,monthOf,spendCsv,spendItems,subagentNames,usd as spendUsd}from"./spend.js";import{buildExport,exportSummary,exportZip,writeExportFolder}from"./export.js";import{startBudgetAlerts}from"./budget-alerts.js";import{runTokensCommand}from"./tokens-cli.js";import{startTokenNotices}from"./token-notices.js";import{liftAuthPause,openAuthPauses,signInGate,signInWords,startSignInProbes}from"./provider-auth.js";import{createConnectionChecker}from"./provider-connection.js";import{agentsSignedOutLines,checkIntegrations,integrationsBrokenLine,integrationsNow,renderIntegrations}from"./integrations.js";import{buildHandoff,handoffLines,loginAccount,runOnboard}from"./agent-onboard.js";import{autoSelectFirstRunDefault,detectFirstRunAgents,formatFirstRunAgentsTable}from"./first-run-detect.js";import{backupFiles,backupFolderOf,backupOwner,backupNow,restoreDatabase,startBackups}from"./backup.js";import{startLiveBackups}from"./live-backup.js";import{pushLimitSink}from"./provider-limits.js";import{filingSizing,installFilingSizer,ownerSizer,refineFiledSizing,setTaskSizing,settleSizings,taskSizingSetting}from"./task-sizing.js";import{tierLines,tierReport}from"./tier-report.js";import{savingsLines,savingsReportOrError}from"./route-savings.js";import{limitsView}from"./settings-data.js";import{codexSignedInNow,startCodexLimits}from"./codex-limits.js";import{packageVersion,startMonitoring,targetOf}from"./monitoring.js";import{origin,readMonitoring}from"./monitoring-settings.js";import{logEvent}from"./log.js";import{FLOW_EVERY_MS,flowHousekeeping,moveCards,moveCardsAfter}from"./flow-cadence.js";import{NO_YOUIYOUX_PASS,youiyouxOnboardLine}from"./youiyoux-intake.js";import{readHooksBase,scheduleFromWords}from"./flow-triggers.js";import{sendSubagentSummaries}from"./subagent-admin.js";import{runRequestedUndos,sendSubagentWeeklies}from"./subagent-week.js";import{refreshConnections}from"./mcp-connect.js";import{releaseCheckPurposeFor,releaseTermsFor}from"./release-carry.js";import{approveReleaseCard,journalMatchesPlane,releaseApprovalCard,releaseCardLines,releaseTaskOf,waitingJournals}from"./release-approval.js";import{journalFile}from"./release.js";import{refreshTrustedMains,settleReleaseChecks}from"./nightly-check.js";import{refreshCodeMaps}from"./code-map-build.js";import{sweepDeliveries}from"./code-map-admission.js";import{runMapCommand}from"./code-map-cli.js";import{githubNightlyRepos,readGithubNightlies}from"./nightly-github.js";import{exec as releaseExec,githubReads}from"./release-adapters.js";import{releaseTools}from"./release-git.js";import{SECRETS_FIRST,startToolSecrets,toolSecretStorage}from"./project-tools.js";import{followDiscord}from"./discord.js";import{followTeams}from"./teams.js";import{followSlack}from"./slack.js";import{validateScopeText}from"./task-text.js";import{runMemoryCommand}from"./memory-cli.js";import{runFlakyCommand}from"./flaky-cli.js";import{backfillMemoryUse}from"./memory-use.js";import{scheduledTidy}from"./memory-tidy.js";import{CI_READ_EVERY_MS,ciCursorKey,ciRepositoriesOf,observeCiAttempts}from"./flaky-ci.js";import{runKnowledgeApply,runKnowledgeCommand}from"./knowledge-cli.js";import{FLOWS_VALUE_FLAGS,runFlowsCommand}from"./flows-cli.js";import{approvalSummaryFor,approvalSummaryOf,describeScope,summaryContextOf,summaryLines}from"./approval-summary.js";import{runAssignmentCommand}from"./assignment-adapters.js";import{applyProjectProfile,runProjectCommand}from"./project-cli.js";import{passwordFreeOwner,passwordFreeShell,passwordFreeShellWords,proveTaskBuildsStopped,pullRequestLines,runLocalCompletion,runLocalRevision,runTaskMergeCommand,runTaskOutcomeCommand}from"./task-outcome-cli.js";import{applyPendingAgentChanges,planAgainAsLocalOwner,requestPlanAsLocalOwner,retryAsLocalOwner}from"./local-owner-acts.js";import{withTaskAlias}from"./task-aliases.js";import{checklistLines,landedNowOf,mergeChecklistOf}from"./merge-checklist.js";import{landedRowsOf}from"./landed-rows.js";import{taskReviewBrief,renderReviewBrief}from"./task-review-brief.js";import{homedir,hostname}from"node:os";import{basename,dirname,isAbsolute,join,resolve}from"node:path";import{CHECK_RECOVERY_HELD,readCheckRecoveryHoldsForTaskRef}from"./check-recovery-hold.js";import{currentRuntime,driftWords,releaseStalledUpdate,serviceDriftHere,waitingUpdate}from"./toolroll-update.js";import{dur}from"./design/kit.js";import{requeueEligibility,checkoutIdle,setCheckoutIdle,leadQuickAnswersOn,setLeadQuickAnswers,openStore,openStoreReadOnly,openStoreNoMigrate,initLocalMode,localModeCandidate,consoleServingNow,consoleComponent,consoleRowForPort,openConsoleRows,enrollOwnerPassword,installationCreatedBy,laptopPortOf,recordLaptopPort,localModeOf,localOwnerBinding,archiveTaskFamily,restoreTaskFamily,shipChecksForTask,elapsedSeconds,CONCURRENT_WRITER_WAIT_MS,isDatabaseBusy,briefly,databasePath,BUILT_IN,parseCapabilityKey,verifiedAuthor,isDigestTime,predecessorWatches,RESULT_SCREENSHOTS,reportLifecycle,beatLifecycle}from"./store.js";import{createHash,randomBytes,randomInt,randomUUID}from"node:crypto";import{claimInstance,clearInstance,instanceRunDir,openInstanceSocket,prepareRunDir,proveLiveConsole}from"./console-instance.js";import{backgroundOff,backgroundOn,backgroundShow,laptopStatus,laptopStop,restartOwnBuilder}from"./laptop-background.js";import{authorizePlanUnderMode}from"./plan-auto.js";import{ghDispatchAdapter,mirrorTaskId,syncPass}from"./sync.js";import{LIVE_FILE_BOUND,LIVE_RETAIN_MS,sweepLiveLogs}from"./live.js";import{addRepos,removeRepos,updateRepos,loadRepos,loadProjectRegistry,updateProjectRegistry,registryRemovals}from"./repos.js";import{deleteProject,holdingsWords,projectHoldings,projectRunning,PROJECT_RECOVERY_DELETE_MESSAGE}from"./project-delete.js";import{pushPass}from"./push.js";import{chmodSync,closeSync,constants as fsConstants,existsSync,fstatSync,fsyncSync,mkdirSync,openSync,readFileSync,readSync,realpathSync,renameSync,unlinkSync,writeSync,writeFileSync}from"node:fs";import{BRANCH_PREFIX,envValue,existingOrFirst,taskBranches}from"./names.js";import{claimActor,currentActor,withActor}from"./actor.js";import{parseLeadToken}from"./api-tokens.js";import{MAX_NETWORK_HOSTS,normalizeHost}from"./egress.js";import{isWritesMode,writesWords}from"./writes-mode.js";import{linuxFenceAvailable,macosFenceAvailable}from"./agent-fence.js";import{parseMachLookup,parseReadDeny,readDenyWords}from"./project-sandbox.js";import{LOCAL_POLICY}from"./surface.js";import{handoffWords,land,landedLine,landingBranchOf,landingWords,publishesThroughPullRequests,PULL_REQUESTS_INSTEAD,readLanding,runPendingLocalLands}from"./local-landing.js";import{catchUpMergeOf,catchUpRevision,recordCatchUp}from"./revision-catch-up.js";import{asLocalOwner,currentLocalOwner,localActNow,LOCAL_OWNER_LAPSED,LOCAL_MODE_CONFINES,localModeOn,localOwnerRefusal,localOwnerRequested}from"./local-owner.js";import{CHECK_ACCESS_WARNINGS,checkAccessRunsAs,checkAccessWords,isCheckAccess,signInHostsMissing,signInsUnavailableWords,widerThan}from"./check-access.js";import{CLI_PASSWORD_SOURCE,withPasswordSource}from"./sign-in-guard.js";import{ledgerSpent,NO_SAFE_OPENER,openSignInLink,platformOpener}from"./sign-in-page.js";import{admissionRecorded,admitProject,commandLineActor}from"./project-admission.js";import{leadClaim,leadSay,noteLeadWork}from"./lead-voice.js";import{createConnection as createNetConnection,createServer as createNetServer}from"node:net";import{fileURLToPath}from"node:url";import{superviseController}from"./controller-supervisor.js";import{buildIdentity,memoryChannel,RoleGenerations,roleMessage}from"./up-processes.js";import{checkedEnvelopeJson as envelopeJson}from"./contracts/cli.js";import{auditCommand}from"./audit-cli.js";import{closedQuestionWords,hasDisguisedText,validateNote}from"./decision.js";import{readVerifiedArtifact,readVerifiedReport,storeEvidence}from"./evidence.js";import{contractChangesOf,decodePlanContractRecord,describeContractChanges,encodePlannerSource,plannerSourceOf}from"./planner-source.js";function planContractLines(store,evidenceRoot,taskId){const ref=store.lookupRef(taskId);if(ref===null||ref.plan!=="drafted")return[];const artifact=store.latestPlanContractArtifact(ref.id);if(artifact===null)return[];let record;try{const verified=readVerifiedArtifact(evidenceRoot,artifact);if(!verified.ok)return[` filed contract: record does not verify — ${verified.problem} (run ${artifact.run})`];record=decodePlanContractRecord(verified.content)}catch{return[` filed contract: record could not be read (run ${artifact.run})`]}if(record===null)return[` filed contract: record is not the JSON it was sealed as (run ${artifact.run})`];const scope=store.getScope(taskId),stale=scope!==null&&contractChangesOf(record.proposed,scope).length>0?" (the scope was edited after this draft)":"";return record.filed===null?[` filed contract: none — the planner drafted every term from the title and repository${stale}`]:record.changes.length===0?[` filed contract: preserved exactly by the plan — approval binds the terms you filed${stale}`]:[` filed contract: AMENDED by the plan — ${record.changes.length} change${record.changes.length===1?"":"s"}; approval binds the amended terms${stale}`,` why: ${record.amendment??"(the planner stated no reason)"}`,...describeContractChanges(record.changes).map(line=>` ${line}`)]}import{verdictWords as proofVerdictWords,manualReviewCriterionOf,matrixWords,plainReasonWords,semanticCoverage,coverageWords}from"./proof.js";import{probeRepo}from"./probe.js";import{agentlessFirstRun,buildersFor,diagnoseTaskDispatch,diagnosisIsDispatchable,NO_AGENT_TITLE,scopeApprovedForDispatch}from"./dispatch.js";import{createDecisionServer,SIGN_IN_LINK_MS}from"./serve.js";import{warmWorkspaceRenderer}from"./workspace-ssr.js";import{readTailnetNames}from"./tailnet.js";import{daemonLaunchCommand,daemonStatus,installReplacingLegacy,installedLegacyDaemon,planDaemon,uninstallDaemon,awaitFreshHeartbeat}from"./daemon.js";import{bridgePass,clearBotToken,createTransport,followBridge,hashPairingCode,loadBotToken,mintPairingCode,networkFence,networkFenceLine,redactToken,saveBotToken,PAIRING_TTL_MS,TOKEN_ENV,telegramHookSecret,telegramPushUrl}from"./telegram.js";import{projectIdentities}from"./project-identity.js";import{lookIdentities}from"./folder-look.js";import{scanRepo}from"./capscan.js";import{computeGaps,describeCapability}from"./gaps.js";import{ask as promptAsk,askHidden as promptHidden,confirm as promptConfirm,interactive as promptInteractive,underAgent}from"./prompt.js";import{runLeadCli,answerContextLines}from"./lead-cli.js";import{liveTerminalWanted,processTerminal}from"./lead-cli-live.js";import{confirmCoordinatorProposal,dismissCoordinatorProposal}from"./lead-doors.js";import{verifyApproverByPassword as approverByPassword,verifyApproverStanding}from"./principal.js";import{activeRemote,REMOTE_MESSAGES,REMOTE_REFUSED_FLAGS,REMOTE_SCOPES,RemoteRefusal,remoteAllows,remoteLensOf,remoteProjectOf,remoteRowOf,remoteSecret,reproveRemote,withRemote}from"./operate-remote.js";import{projectAuthority}from"./project-access.js";import{authorizedProject,canonicalProject,projectName,resolveCeiling}from"./project.js";import{tally,spendLine}from"./summary.js";import{describePublicationGrant,observeChecks,publishPass,sweepMerges}from"./publish.js";import{checkPublishing,publishingOf,savePublishing,followPullRequests,newestPullRequestOf}from"./pull-request-flow.js";import{starterOf,startersFor,switchOnStarter}from"./flow-starters.js";import{acquire,acquireIfReady,heartbeat,release,reap,currentClaim,DEFAULT_LEASE_MS,SYNC_MAX_AGE_MS,finalize}from"./claim.js";import{moveTask}from"./task-moves.js";import{disposeBuildOutcome,holdStaleApproval,regateTask}from"./dispose.js";import{proposeGrant,describeGrant,describeWithheld,permits,MUTATION_CLASSES,DEFAULT_MUTATIONS}from"./grant.js";import{builtIn,guarded}from"./backend.js";import{register,authenticate,heartbeat as heartbeatRunner,isAlive,recoverDead,recoveredAnything,acquireWatchLeaseAuthed,renewWatchLeaseAuthed,addRunnerReposAuthed,removeRunnerRepoAuthed,registerRunnerIfIdle,retireRunnerIfCurrent,drainRunnerIfCurrent,drainOf,RUNNER_HEARTBEAT_MS,MAX_WATCH_LEASE_MS,normalizeRunnerName,validRunnerName,canonicalRepos,RUNNER_NAME_MAX,RUNNER_CAPACITY_MAX,parseRunnerCapacity,hashToken as hashRunnerToken}from"./runner.js";import{processIdentityProblem}from"./process-identity.js";import{openAddress}from"./browser-open.js";import{credentialDigest,recordedHolderProvedGone,processGone,processStart,readRunnerProcessRecord,runnerProcessFile,sealRunnerProcessRecord,writeRunnerProcessRecord}from"./runner-process.js";import{stopProcessTree}from"./process-tree.js";import{mintCoordinator,revokeCoordinator,listCoordinators}from"./coordinator.js";import{serveMcp}from"./mcp.js";import{createInterface}from"node:readline";import{hashPassword}from"./scope.js";import{noticeDueOnce,CONTAINMENT_NOTICE_FACT,passwordResetRefusal,resetAccountPassword}from"./store.js";import{propose,approve,addApprover,authenticateAccount,authenticateApprover as passwordApprover,approvalOf,hashToken as hashApproverToken,modeFilingCoverage,acceptanceLinesToInput,parseAcceptanceCriteria,splitAcceptanceRubric,rubricIsPlaceholder,isCommitSha,credentialProof,rememberedLogin,personApprovalOf}from"./scope.js";import{CHAT_APPROVE_ALL,presetTerms,modeTermsJson,modeDigestOf,modeTermsFromJson,modeWords,MODE_MAX_DAYS}from"./modes.js";import{WorktreePool}from"./worktree.js";import{baseStandingWords,freshBaseFor,taskBaseOf}from"./task-base.js";import{requestTaskStop,resumeTaskStop,taskControlOf}from"./task-control.js";import{worktreeAdoptionNotice}from"./worktree-notices.js";import{workIndexPage,workIndexTask,WorkIndexCursorError}from"./work-index.js";import{readExecutorOf}from"./read-executor.js";import{parseWorkView}from"./workspace-projection.js";import{taskWorkSummaryOf}from"./work-summary.js";import{assignmentOf,assignmentBrief,syncAssignmentHandoffs,localCompletionRefusal}from"./assignment.js";import{completedByOf}from"./task-status.js";import{createScheduledFlow,describeSchedule,parseSchedule}from"./flow-schedule.js";import{fileTaskProposal,validateTaskText}from"./proposal.js";import{TEMPLATES,templateByName}from"./templates.js";import{isDirectChatProvider,isSubscriptionChatProvider,priceOf,PRICED_MODELS}from"./converse.js";import{clearFallbackChain,dispatchEntryOf,entryMovesOnWords,entryWords,fallbackSettingOf,parseEntry,reconcileWalks,setFallbackChain,setPaidGrant}from"./fallback.js";import{resolvePhaseAgent,resolveScopeProfile,resolveRouteCandidates,routeOfTask,INSTALLATION_SCOPE}from"./agentconfig.js";import{applyModelChoices}from"./model-choices.js";import{isTaskSize,legOf,projectRoute,readinessRefuses,routeDigestOf,routeWords,TASK_SIZES,PHASES as ROUTE_PHASES}from"./phase-routing.js";import{routeWorkerModel}from"./model-routing.js";import{observeProviderReadiness,reportProviderReadinessAuthed}from"./runner.js";import{retryVanishedWhenStopped}from"./vanished-retry.js";import{requestMissingRechecks}from"./check-only.js";import{checkRepairOfRun,resumeParkedRepairs,startCheckRepair}from"./check-repair.js";import{capturesCommand,evidenceCommand,failingFirstCommand,findingCommand,handoverCommand}from"./follow-through-cli.js";import{recordBuilderWish}from"./builder-restart.js";import{expireFastStarts,fastAcceptance,fastRefusalWords,fastStartBuild,keepGrownChange,prepareFastStart}from"./fast-start.js";import{fastTermsLines}from"./fast-terms.js";import{resumeAllowedReleases}from"./release-next.js";import{RELEASE_CHECK_WAIT,runningReleaseCheck}from"./release-quiet.js";import{closeStillRestarting,noteRestarted,noteStillRestarting,STILL_RESTARTING_AFTER_MS}from"./builder-notice.js";import{sweepOrphanedReleases}from"./release-resume.js";import{fileGithubItem,readGithubItem}from"./github-import.js";import{runRelease}from"./release.js";import{releaseAdapters}from"./release-adapters.js";import{eligibleModelChangeTasks,proposeNetworkChanges,rerouteReplyWords,rerouteWaitingTasks,routeChangeOf,routeLegacyPlans}from"./route-change.js";import{ownerMode}from"./owner-mode.js";import{installModeNow,sessionStandsIn}from"./install-mode.js";import{parseDemoUrl,projectDemoUrl,saveProjectDemo}from"./project-demo.js";import{effectiveConcurrency,maySlotTake,parseProjectConcurrency,PROJECT_CONCURRENCY_DEFAULT,ProjectPasses,projectConcurrency,saveProjectConcurrency,savedProjectConcurrency}from"./project-concurrency.js";import{activeWebhookTargets,webhookPass,LEGACY_WEBHOOK_WARNING,loadWebhookTargets,effectivePrimary,isMessagingChannel,loadConsoleUrl,phoneOrigin,readUpConsoleUrl,saveConsoleUrl,savePrimary,UP_CONSOLE_FILE}from"./webhooks.js";import{auditOf,inspectionOf,isProviderId,MONEY_CAPABILITIES,PROVIDER_IDS,validModelId,validateSpec,ALL_CREDENTIAL_ENV}from"./provider.js";import{attestProvider,attestationOf,versionInRange}from"./attest.js";import{build,proveApprovedProfile}from"./builder.js";import{plan as planTask}from"./planner.js";import{attachTmux,elapsedWords,openInTmux,PEEK_TAIL_LINES,runPeek,snapshotLiveRuns}from"./peek-cli.js";import{scout as scoutTask}from"./scout.js";import{profileDigestOf}from"./scope.js";import{PROVIDER_KEY_ENV,clearProviderKey,keyStatus,readAuthMode,readAuthModeStrict,readProviderKey,saveProviderKey,setAuthMode,verifyProviderKey,verdictWords}from"./keys.js";import{forgetOpenRouterKey,saveOpenRouterKey}from"./openrouter-key.js";import{run,terminateLiveProviders,liveProviderCount,run as execRun}from"./exec.js";import{hardenedGit,lazyFetchSafeGit,noLazyFetch,PARTIAL_CLONE_REFUSAL}from"./teardown-git.js";import{installedGitFloorProblem}from"./git-floor.js";import{noticeGitIncidents}from"./git-incident.js";import{containmentNotice,containmentStatus,currentContainment,describeContainment,resolveContainment}from"./containment.js";import{readPulls}from"./pulls.js";import{startMaintenance,busyRetryAfter}from"./maintenance.js";import{WakePoker,wakeHubFor}from"./wake-hub.js";import{livePin,modelWatchPass}from"./model-catalog.js";import{runModelsCommand}from"./models-cli.js";import{ALL_PROJECTS,chatApprovalSettings,chatApprovalWords,setChatApproval}from"./chat-approval.js";import{updateAdmissionPaused,UPDATE_PAUSED}from"./update-gate.js";import{abortablePause}from"./chat-follow.js";import{endAfterExitProof,watchdogVerdict}from"./shutdown-proof.js";import{loopEndRecovery,relaunchAdmission,relaunchDelayMs,LOOP_STABLE_MS,RELAUNCH_WAIT_WORDS}from"./loop-recovery.js";import{beads}from"./beads.js";import{githubIssues}from"./issues.js";import{installationStatus,renderInstallationStatus,renderTaskWait,repairStaleStatuses,taskWaitSnapshot}from"./lead-status.js";import{latestRelease,newerRelease,notifySecurityRelease,notifyVersionLive,recordRunnerVersion,startUpdateChecks,updateLine}from"./releases.js";import{installMethod}from"./install-method.js";import{PACKAGE_VERSION}from"./version.js";import{machineActing}from"./scope.js";import{enableFlexible,FLEXIBLE_LAPSE_WORDS,FLEXIBLE_LEVEL_WORDS,FLEXIBLE_UNAVAILABLE,flexibleAvailable,flexibleSetting,flexibleStanding,flexibleTermsWords,isFlexibleLevel,lowerFlexible,proposedFlexibleTerms,setFlexibleSetting,turnFlexibleOff}from"./agent-thread/guards.js";import{flexibleSignInStatus,looksLikeClaudeCredential,recheckFlexibleSignIn,removeFlexibleSignIn,saveFlexibleSignIn,setupTokenFromPaste,signInCheckWords,statusCheck,tidyFlexibleSignIns}from"./agent-thread/sign-in.js";import{reevaluateResultRecords}from"./route-results.js";import{holdRuleOff,routeRulesPass,taskEvidenceWords}from"./route-rules.js";import{ruleHoldOf}from"./route-store.js";import{wasInterrupted}from"./run-ending.js";import{loginFileOf,migrateLegacyLogin,removeStaleSavedLogin,savedLoginFile,writableLoginFile}from"./login-secrets.js";import{runWords}from"./needs-you.js";export const EXIT={ok:0,failed:1,usage:2,refused:3};const STATES=["queued","running","done","failed","cancelled"];export const TASK_ADD_HELP=`toolroll task add "<title>" [options]
|
|
1
|
+
import{fetchLocalSkillBundle}from"./plugin-bundle-source.js";import{installSkillBundle,listSkillBundles,removeSkillBundle,rollbackSkillBundle,sweepSkillBundleUpdates}from"./skill-library.js";import{FLEXIBLE_CANDIDATE_FIXED,FLEXIBLE_FILED_PREFIX,flexibleMergeRefusal}from"./agent-thread/guards.js";import{readPiConfiguredModels}from"./agent-thread/providers.js";import{executeTaskHandoff}from"./agent-handoff.js";import{CARD_HELP,configHelp,FLOWS_HELP,LEAD_HELP,MODELS_HELP}from"./cli-help.js";import{legacyLiveLogPath,liveLogPath,liveSubLogPath}from"./live.js";import{parseLiveRecords}from"./live-records.js";import{clearResolvedAgentRequests,fileAgentRequest,listAgentRequests,resolveAgentRequest,waitForAgentRequest}from"./agent-requests.js";import{readStoredGeminiStatus,refreshSubscriptions}from"./subscription-usage.js";import{liveCommandsShown}from"./live-detail.js";import{directChatArmedPass,flexibleArmedPass,flexibleSavedWords,flexibleUncommittedFiles,saveFlexibleBranch}from"./agent-thread/ship.js";import{closeFlexibleThread,flexibleShipNeedsFor,flexibleThreadRecords,flexibleThreadShipTerms,flexibleThreadTitleOf,latestFlexibleShip,removeFlexibleThreadCopy,shipFlexibleThread,stopFlexibleThreadsEverywhere}from"./agent-thread/session.js";import{CARD_SOURCES}from"./card-catalog.js";import{runCardCommand}from"./card-cli.js";import{CARD_PANEL_VALUE_FLAGS,isPanelCardCliInvocation,runPanelCardCommand}from"./panels.js";import{mintSecret}from"./secret-mint.js";import{ACP_AGENTS,ACP_PROVIDER_IDS,isAcpProvider,isKeyedProvider,ownSignInOf}from"./acp-agents.js";import{resolveAcpAgentForRunner,runnerPathOf}from"./acp-inspect.js";import{runAcpChecks}from"./acp-check.js";import{verifyLaunch}from"./acp-attest.js";import{notificationClaimHeld,claimNotifications,finalizeNotification,notificationCommandEnv,notificationDestination}from"./notification-delivery.js";import{adapterPolicy}from"./server/route-policy.js";import{UNSENT_REPLY_MS}from"./telegram.js";import{checkPublicCommand}from"./public-check.js";import{leadNameOf}from"./lead-identity.js";import{modelName,quickLeadModel}from"./lead-route.js";import{maybeTriggerRepair}from"./dispose.js";import{CHECK_LEVEL_HINTS,CHECK_LEVEL_WORDS,isCheckLevel,liveQuickCommand,projectCheckLevel,quickVerifyKey,setProjectCheckLevel,setTaskCheckLevel,suggestQuickCommand}from"./check-levels.js";import{fileAddTestsTask,requestFollowUpChecks,runFollowUpCheck,runWaitingChecks}from"./result-follow-ups.js";import{runBatchChecks}from"./batch-checks.js";import{BATCH_HINT,BATCH_WINDOW_MS,projectBatchChecks,setProjectBatchChecks}from"./batch-policy.js";import{buildReviewPass,REVIEW_BEAT_MS,REVIEW_SLOTS,startReviewSlots}from"./build-review.js";import{buildReviewLines,buildReviewOf}from"./review-switch.js";import{steerDestinationWords,steerStandingOf,steerStandingWords}from"./steer-status.js";import{utcMinute}from"./when.js";import{parseProtectedPaths,rulesSummary}from"./approval-policy.js";import{evidencePack,exportDay,ledgerExportChunks,standaloneEvidenceHtml}from"./evidence-pack.js";import{matchesOutsideCheckpoint}from"./ledger-chain.js";import{CLEANUP_CHOICES,bytesWords,cleanupWords,diskBytes,idleCleanupWords,idleWords,parseCleanup,parseIdle,storageReport}from"./storage.js";import{removeStaleTestTemp,tempRoots,testTempFolders}from"./test-temp.js";import{storageSweepSupervisor}from"./storage-sweep-process.js";import{idleStorageSweep,sweepSchedule,sweepScheduleWords}from"./storage-sweep-schedule.js";import{lastSweep,saveSweep,sweepDetails,sweepWords as storageSweepWords}from"./storage-sweep.js";import{removeShared,sharedDepsRoot,sharedUse,unusedShared}from"./shared-deps.js";import{cleanLandedBacklog,gitOf,landedBacklog,reconcileLanded,BACKLOG_DAYS}from"./landed-cleanup.js";import{accessOf,applyTidy,approverStandsNow,withinLens,familyRepoOf,releaseFactsFor,runTidy,tidyDays,tidyDigest,tidyGroups,tidyPreview,TIDY_DEFAULT_DAYS,TIDY_PASS_LIMIT}from"./tidy.js";import{personProof}from"./person-proof.js";import{RemoteMains}from"./remote-main.js";import{checkoutPlan,cleanCheckouts,discardCheckout,finishedCheckouts,slimKeptCheckouts,whyWords}from"./checkout-cleanup.js";import{closeOutCheckouts,closeOutRuns,stoppedWords}from"./run-closeout.js";import{proveFinishedRunsStopped,proveRunStopped}from"./stop-proof.js";import{LIFECYCLE_RETENTION_DAYS,NOTIFICATION_RETENTION_WORDS,notificationLifecyclePreview}from"./notification-retention.js";import{MIN_DAYS,RETENTION_KINDS,countWords,dailyRetention,isRetentionKind,lastSweepAt,parsePeriod,periodLabel,periodWords,retentionPlan,sweepWords}from"./retention.js";import{checkPolicy,parseList,policyParts}from"./policy.js";import{billingOf,budgetHoldWords,budgetLabel,budgetStates,monthNamed,monthOf,spendCsv,spendItems,subagentNames,usd as spendUsd}from"./spend.js";import{buildExport,exportSummary,exportZip,writeExportFolder}from"./export.js";import{startBudgetAlerts}from"./budget-alerts.js";import{runTokensCommand}from"./tokens-cli.js";import{startTokenNotices}from"./token-notices.js";import{liftAuthPause,openAuthPauses,signInGate,signInWords,startSignInProbes}from"./provider-auth.js";import{createConnectionChecker}from"./provider-connection.js";import{agentsSignedOutLines,checkIntegrations,integrationsBrokenLine,integrationsNow,renderIntegrations}from"./integrations.js";import{buildHandoff,handoffLines,loginAccount,runOnboard}from"./agent-onboard.js";import{autoSelectFirstRunDefault,detectFirstRunAgents,formatFirstRunAgentsTable}from"./first-run-detect.js";import{backupFiles,backupFolderOf,backupOwner,backupNow,restoreDatabase,startBackups}from"./backup.js";import{startLiveBackups}from"./live-backup.js";import{pushLimitSink}from"./provider-limits.js";import{filingSizing,installFilingSizer,ownerSizer,refineFiledSizing,setTaskSizing,settleSizings,taskSizingSetting}from"./task-sizing.js";import{tierLines,tierReport}from"./tier-report.js";import{savingsLines,savingsReportOrError}from"./route-savings.js";import{limitsView}from"./settings-data.js";import{codexSignedInNow,startCodexLimits}from"./codex-limits.js";import{packageVersion,startMonitoring,targetOf}from"./monitoring.js";import{origin,readMonitoring}from"./monitoring-settings.js";import{logEvent}from"./log.js";import{FLOW_EVERY_MS,flowHousekeeping,moveCards,moveCardsAfter}from"./flow-cadence.js";import{NO_YOUIYOUX_PASS,youiyouxOnboardLine}from"./youiyoux-intake.js";import{readHooksBase,scheduleFromWords}from"./flow-triggers.js";import{sendSubagentSummaries}from"./subagent-admin.js";import{runRequestedUndos,sendSubagentWeeklies}from"./subagent-week.js";import{refreshConnections}from"./mcp-connect.js";import{releaseCheckPurposeFor,releaseTermsFor}from"./release-carry.js";import{approveReleaseCard,journalMatchesPlane,releaseApprovalCard,releaseCardLines,releaseTaskOf,waitingJournals}from"./release-approval.js";import{journalFile}from"./release.js";import{refreshTrustedMains,settleReleaseChecks}from"./nightly-check.js";import{refreshCodeMaps}from"./code-map-build.js";import{sweepDeliveries}from"./code-map-admission.js";import{runMapCommand}from"./code-map-cli.js";import{githubNightlyRepos,readGithubNightlies}from"./nightly-github.js";import{exec as releaseExec,githubReads}from"./release-adapters.js";import{releaseTools}from"./release-git.js";import{SECRETS_FIRST,startToolSecrets,toolSecretStorage}from"./project-tools.js";import{followDiscord}from"./discord.js";import{followTeams}from"./teams.js";import{followSlack}from"./slack.js";import{validateScopeText}from"./task-text.js";import{runMemoryCommand}from"./memory-cli.js";import{runFlakyCommand}from"./flaky-cli.js";import{backfillMemoryUse}from"./memory-use.js";import{scheduledTidy}from"./memory-tidy.js";import{CI_READ_EVERY_MS,ciCursorKey,ciRepositoriesOf,observeCiAttempts}from"./flaky-ci.js";import{runKnowledgeApply,runKnowledgeCommand}from"./knowledge-cli.js";import{FLOWS_VALUE_FLAGS,runFlowsCommand}from"./flows-cli.js";import{approvalSummaryFor,approvalSummaryOf,describeScope,summaryContextOf,summaryLines}from"./approval-summary.js";import{runAssignmentCommand}from"./assignment-adapters.js";import{applyProjectProfile,runProjectCommand}from"./project-cli.js";import{passwordFreeOwner,passwordFreeShell,passwordFreeShellWords,proveTaskBuildsStopped,pullRequestLines,runLocalCompletion,runLocalRevision,runTaskMergeCommand,runTaskOutcomeCommand}from"./task-outcome-cli.js";import{applyPendingAgentChanges,planAgainAsLocalOwner,requestPlanAsLocalOwner,retryAsLocalOwner}from"./local-owner-acts.js";import{withTaskAlias}from"./task-aliases.js";import{checklistLines,landedNowOf,mergeChecklistOf}from"./merge-checklist.js";import{landedRowsOf}from"./landed-rows.js";import{taskReviewBrief,renderReviewBrief}from"./task-review-brief.js";import{homedir,hostname}from"node:os";import{basename,dirname,isAbsolute,join,resolve}from"node:path";import{CHECK_RECOVERY_HELD,readCheckRecoveryHoldsForTaskRef}from"./check-recovery-hold.js";import{currentRuntime,driftWords,releaseStalledUpdate,serviceDriftHere,waitingUpdate}from"./toolroll-update.js";import{dur}from"./design/kit.js";import{requeueEligibility,checkoutIdle,setCheckoutIdle,leadQuickAnswersOn,setLeadQuickAnswers,openStore,openStoreReadOnly,openStoreNoMigrate,initLocalMode,localModeCandidate,consoleServingNow,consoleComponent,consoleRowForPort,openConsoleRows,enrollOwnerPassword,installationCreatedBy,laptopPortOf,recordLaptopPort,localModeOf,localOwnerBinding,archiveTaskFamily,restoreTaskFamily,shipChecksForTask,elapsedSeconds,CONCURRENT_WRITER_WAIT_MS,isDatabaseBusy,briefly,databasePath,BUILT_IN,parseCapabilityKey,verifiedAuthor,isDigestTime,predecessorWatches,RESULT_SCREENSHOTS,reportLifecycle,beatLifecycle}from"./store.js";import{createHash,randomBytes,randomInt,randomUUID}from"node:crypto";import{claimInstance,clearInstance,instanceRunDir,openInstanceSocket,prepareRunDir,proveLiveConsole}from"./console-instance.js";import{backgroundOff,backgroundOn,backgroundShow,laptopStatus,laptopStop,restartOwnBuilder}from"./laptop-background.js";import{authorizePlanUnderMode}from"./plan-auto.js";import{ghDispatchAdapter,mirrorTaskId,syncPass}from"./sync.js";import{LIVE_FILE_BOUND,LIVE_RETAIN_MS,sweepLiveLogs}from"./live.js";import{addRepos,removeRepos,updateRepos,loadRepos,loadProjectRegistry,updateProjectRegistry,registryRemovals}from"./repos.js";import{deleteProject,holdingsWords,projectHoldings,projectRunning,PROJECT_RECOVERY_DELETE_MESSAGE}from"./project-delete.js";import{pushPass}from"./push.js";import{chmodSync,closeSync,constants as fsConstants,existsSync,fstatSync,fsyncSync,mkdirSync,openSync,readFileSync,readSync,realpathSync,renameSync,unlinkSync,writeSync,writeFileSync}from"node:fs";import{BRANCH_PREFIX,envValue,existingOrFirst,taskBranches}from"./names.js";import{claimActor,currentActor,withActor}from"./actor.js";import{parseLeadToken}from"./api-tokens.js";import{MAX_NETWORK_HOSTS,normalizeHost}from"./egress.js";import{isWritesMode,writesWords}from"./writes-mode.js";import{linuxFenceAvailable,macosFenceAvailable}from"./agent-fence.js";import{parseMachLookup,parseReadDeny,readDenyWords}from"./project-sandbox.js";import{LOCAL_POLICY}from"./surface.js";import{handoffWords,land,landedLine,landingBranchOf,landingWords,publishesThroughPullRequests,PULL_REQUESTS_INSTEAD,readLanding,runPendingLocalLands}from"./local-landing.js";import{catchUpMergeOf,catchUpRevision,recordCatchUp}from"./revision-catch-up.js";import{asLocalOwner,currentLocalOwner,localActNow,LOCAL_OWNER_LAPSED,LOCAL_MODE_CONFINES,localModeOn,localOwnerRefusal,localOwnerRequested}from"./local-owner.js";import{CHECK_ACCESS_WARNINGS,checkAccessRunsAs,checkAccessWords,isCheckAccess,signInHostsMissing,signInsUnavailableWords,widerThan}from"./check-access.js";import{CLI_PASSWORD_SOURCE,withPasswordSource}from"./sign-in-guard.js";import{ledgerSpent,NO_SAFE_OPENER,openSignInLink,platformOpener}from"./sign-in-page.js";import{admissionRecorded,admitProject,commandLineActor}from"./project-admission.js";import{leadClaim,leadSay,noteLeadWork}from"./lead-voice.js";import{createConnection as createNetConnection,createServer as createNetServer}from"node:net";import{fileURLToPath}from"node:url";import{superviseController}from"./controller-supervisor.js";import{buildIdentity,memoryChannel,RoleGenerations,roleMessage}from"./up-processes.js";import{checkedEnvelopeJson as envelopeJson}from"./contracts/cli.js";import{auditCommand}from"./audit-cli.js";import{closedQuestionWords,hasDisguisedText,validateNote}from"./decision.js";import{readVerifiedArtifact,readVerifiedReport,storeEvidence}from"./evidence.js";import{contractChangesOf,decodePlanContractRecord,describeContractChanges,encodePlannerSource,plannerSourceOf}from"./planner-source.js";function planContractLines(store,evidenceRoot,taskId){const ref=store.lookupRef(taskId);if(ref===null||ref.plan!=="drafted")return[];const artifact=store.latestPlanContractArtifact(ref.id);if(artifact===null)return[];let record;try{const verified=readVerifiedArtifact(evidenceRoot,artifact);if(!verified.ok)return[` filed contract: record does not verify — ${verified.problem} (run ${artifact.run})`];record=decodePlanContractRecord(verified.content)}catch{return[` filed contract: record could not be read (run ${artifact.run})`]}if(record===null)return[` filed contract: record is not the JSON it was sealed as (run ${artifact.run})`];const scope=store.getScope(taskId),stale=scope!==null&&contractChangesOf(record.proposed,scope).length>0?" (the scope was edited after this draft)":"";return record.filed===null?[` filed contract: none — the planner drafted every term from the title and repository${stale}`]:record.changes.length===0?[` filed contract: preserved exactly by the plan — approval binds the terms you filed${stale}`]:[` filed contract: AMENDED by the plan — ${record.changes.length} change${record.changes.length===1?"":"s"}; approval binds the amended terms${stale}`,` why: ${record.amendment??"(the planner stated no reason)"}`,...describeContractChanges(record.changes).map(line=>` ${line}`)]}import{verdictWords as proofVerdictWords,manualReviewCriterionOf,matrixWords,plainReasonWords,semanticCoverage,coverageWords}from"./proof.js";import{probeRepo}from"./probe.js";import{agentlessFirstRun,buildersFor,diagnoseTaskDispatch,diagnosisIsDispatchable,NO_AGENT_TITLE,scopeApprovedForDispatch}from"./dispatch.js";import{createDecisionServer,SIGN_IN_LINK_MS}from"./serve.js";import{warmWorkspaceRenderer}from"./workspace-ssr.js";import{readTailnetNames}from"./tailnet.js";import{daemonLaunchCommand,daemonStatus,installReplacingLegacy,installedLegacyDaemon,planDaemon,uninstallDaemon,awaitFreshHeartbeat}from"./daemon.js";import{bridgePass,clearBotToken,createTransport,followBridge,hashPairingCode,loadBotToken,mintPairingCode,networkFence,networkFenceLine,redactToken,saveBotToken,PAIRING_TTL_MS,TOKEN_ENV,telegramHookSecret,telegramPushUrl}from"./telegram.js";import{projectIdentities}from"./project-identity.js";import{lookIdentities}from"./folder-look.js";import{scanRepo}from"./capscan.js";import{computeGaps,describeCapability}from"./gaps.js";import{ask as promptAsk,askHidden as promptHidden,confirm as promptConfirm,interactive as promptInteractive,underAgent}from"./prompt.js";import{runLeadCli,answerContextLines}from"./lead-cli.js";import{liveTerminalWanted,processTerminal}from"./lead-cli-live.js";import{confirmCoordinatorProposal,dismissCoordinatorProposal}from"./lead-doors.js";import{verifyApproverByPassword as approverByPassword,verifyApproverStanding}from"./principal.js";import{activeRemote,REMOTE_MESSAGES,REMOTE_REFUSED_FLAGS,REMOTE_SCOPES,RemoteRefusal,remoteAllows,remoteLensOf,remoteProjectOf,remoteRowOf,remoteSecret,reproveRemote,withRemote}from"./operate-remote.js";import{projectAuthority}from"./project-access.js";import{authorizedProject,canonicalProject,projectName,resolveCeiling}from"./project.js";import{tally,spendLine}from"./summary.js";import{describePublicationGrant,observeChecks,publishPass,sweepMerges}from"./publish.js";import{checkPublishing,publishingOf,savePublishing,followPullRequests,newestPullRequestOf}from"./pull-request-flow.js";import{starterOf,startersFor,switchOnStarter}from"./flow-starters.js";import{acquire,acquireIfReady,heartbeat,release,reap,currentClaim,DEFAULT_LEASE_MS,SYNC_MAX_AGE_MS,finalize}from"./claim.js";import{moveTask}from"./task-moves.js";import{disposeBuildOutcome,holdStaleApproval,regateTask}from"./dispose.js";import{proposeGrant,describeGrant,describeWithheld,permits,MUTATION_CLASSES,DEFAULT_MUTATIONS}from"./grant.js";import{builtIn,guarded}from"./backend.js";import{register,authenticate,heartbeat as heartbeatRunner,isAlive,recoverDead,recoveredAnything,acquireWatchLeaseAuthed,renewWatchLeaseAuthed,addRunnerReposAuthed,removeRunnerRepoAuthed,registerRunnerIfIdle,retireRunnerIfCurrent,drainRunnerIfCurrent,drainOf,RUNNER_HEARTBEAT_MS,MAX_WATCH_LEASE_MS,normalizeRunnerName,validRunnerName,canonicalRepos,RUNNER_NAME_MAX,RUNNER_CAPACITY_MAX,parseRunnerCapacity,hashToken as hashRunnerToken}from"./runner.js";import{processIdentityProblem}from"./process-identity.js";import{openAddress}from"./browser-open.js";import{credentialDigest,recordedHolderProvedGone,processGone,processStart,readRunnerProcessRecord,runnerProcessFile,sealRunnerProcessRecord,writeRunnerProcessRecord}from"./runner-process.js";import{stopProcessTree}from"./process-tree.js";import{mintCoordinator,revokeCoordinator,listCoordinators}from"./coordinator.js";import{serveMcp}from"./mcp.js";import{createInterface}from"node:readline";import{hashPassword}from"./scope.js";import{noticeDueOnce,CONTAINMENT_NOTICE_FACT,passwordResetRefusal,resetAccountPassword}from"./store.js";import{propose,approve,addApprover,authenticateAccount,authenticateApprover as passwordApprover,approvalOf,hashToken as hashApproverToken,modeFilingCoverage,acceptanceLinesToInput,parseAcceptanceCriteria,splitAcceptanceRubric,rubricIsPlaceholder,isCommitSha,credentialProof,rememberedLogin,personApprovalOf}from"./scope.js";import{CHAT_APPROVE_ALL,presetTerms,modeTermsJson,modeDigestOf,modeTermsFromJson,modeWords,MODE_MAX_DAYS}from"./modes.js";import{WorktreePool}from"./worktree.js";import{baseStandingWords,freshBaseFor,taskBaseOf}from"./task-base.js";import{requestTaskStop,resumeTaskStop,taskControlOf}from"./task-control.js";import{worktreeAdoptionNotice}from"./worktree-notices.js";import{workIndexPage,workIndexTask,WorkIndexCursorError}from"./work-index.js";import{readExecutorOf}from"./read-executor.js";import{parseWorkView}from"./workspace-projection.js";import{taskWorkSummaryOf}from"./work-summary.js";import{assignmentOf,assignmentBrief,syncAssignmentHandoffs,localCompletionRefusal}from"./assignment.js";import{completedByOf}from"./task-status.js";import{createScheduledFlow,describeSchedule,parseSchedule}from"./flow-schedule.js";import{fileTaskProposal,validateTaskText}from"./proposal.js";import{TEMPLATES,templateByName}from"./templates.js";import{isDirectChatProvider,isSubscriptionChatProvider,priceOf,PRICED_MODELS}from"./converse.js";import{clearFallbackChain,dispatchEntryOf,entryMovesOnWords,entryWords,fallbackSettingOf,parseEntry,reconcileWalks,setFallbackChain,setPaidGrant}from"./fallback.js";import{resolvePhaseAgent,resolveScopeProfile,resolveRouteCandidates,routeOfTask,INSTALLATION_SCOPE}from"./agentconfig.js";import{applyModelChoices}from"./model-choices.js";import{isTaskSize,legOf,projectRoute,readinessRefuses,routeDigestOf,routeWords,TASK_SIZES,PHASES as ROUTE_PHASES}from"./phase-routing.js";import{routeWorkerModel}from"./model-routing.js";import{observeProviderReadiness,reportProviderReadinessAuthed}from"./runner.js";import{retryVanishedWhenStopped}from"./vanished-retry.js";import{requestMissingRechecks}from"./check-only.js";import{checkRepairOfRun,resumeParkedRepairs,startCheckRepair}from"./check-repair.js";import{capturesCommand,evidenceCommand,failingFirstCommand,findingCommand,handoverCommand}from"./follow-through-cli.js";import{recordBuilderWish}from"./builder-restart.js";import{expireFastStarts,fastAcceptance,fastRefusalWords,fastStartBuild,keepGrownChange,prepareFastStart}from"./fast-start.js";import{fastTermsLines}from"./fast-terms.js";import{resumeAllowedReleases}from"./release-next.js";import{RELEASE_CHECK_WAIT,runningReleaseCheck}from"./release-quiet.js";import{closeStillRestarting,noteRestarted,noteStillRestarting,STILL_RESTARTING_AFTER_MS}from"./builder-notice.js";import{sweepOrphanedReleases}from"./release-resume.js";import{fileGithubItem,readGithubItem}from"./github-import.js";import{runRelease}from"./release.js";import{releaseAdapters}from"./release-adapters.js";import{eligibleModelChangeTasks,proposeNetworkChanges,rerouteReplyWords,rerouteWaitingTasks,routeChangeOf,routeLegacyPlans}from"./route-change.js";import{ownerMode}from"./owner-mode.js";import{installModeNow,sessionStandsIn}from"./install-mode.js";import{parseDemoUrl,projectDemoUrl,saveProjectDemo}from"./project-demo.js";import{effectiveConcurrency,maySlotTake,parseProjectConcurrency,PROJECT_CONCURRENCY_DEFAULT,ProjectPasses,projectConcurrency,saveProjectConcurrency,savedProjectConcurrency}from"./project-concurrency.js";import{activeWebhookTargets,webhookPass,LEGACY_WEBHOOK_WARNING,loadWebhookTargets,effectivePrimary,isMessagingChannel,loadConsoleUrl,phoneOrigin,readUpConsoleUrl,saveConsoleUrl,savePrimary,UP_CONSOLE_FILE}from"./webhooks.js";import{auditOf,inspectionOf,isProviderId,MONEY_CAPABILITIES,PROVIDER_IDS,validModelId,validateSpec,ALL_CREDENTIAL_ENV}from"./provider.js";import{attestProvider,attestationOf,versionInRange}from"./attest.js";import{build,proveApprovedProfile}from"./builder.js";import{plan as planTask}from"./planner.js";import{attachTmux,elapsedWords,openInTmux,PEEK_TAIL_LINES,runPeek,snapshotLiveRuns}from"./peek-cli.js";import{scout as scoutTask}from"./scout.js";import{profileDigestOf}from"./scope.js";import{PROVIDER_KEY_ENV,clearProviderKey,keyStatus,readAuthMode,readAuthModeStrict,readProviderKey,saveProviderKey,setAuthMode,verifyProviderKey,verdictWords}from"./keys.js";import{forgetOpenRouterKey,saveOpenRouterKey}from"./openrouter-key.js";import{run,terminateLiveProviders,liveProviderCount,run as execRun}from"./exec.js";import{hardenedGit,lazyFetchSafeGit,noLazyFetch,PARTIAL_CLONE_REFUSAL}from"./teardown-git.js";import{installedGitFloorProblem}from"./git-floor.js";import{noticeGitIncidents}from"./git-incident.js";import{containmentNotice,containmentStatus,currentContainment,describeContainment,resolveContainment}from"./containment.js";import{readPulls}from"./pulls.js";import{startMaintenance,busyRetryAfter}from"./maintenance.js";import{WakePoker,wakeHubFor}from"./wake-hub.js";import{livePin,modelWatchPass}from"./model-catalog.js";import{runModelsCommand}from"./models-cli.js";import{ALL_PROJECTS,chatApprovalSettings,chatApprovalWords,setChatApproval}from"./chat-approval.js";import{updateAdmissionPaused,UPDATE_PAUSED}from"./update-gate.js";import{abortablePause}from"./chat-follow.js";import{endAfterExitProof,watchdogVerdict}from"./shutdown-proof.js";import{loopEndRecovery,relaunchAdmission,relaunchDelayMs,LOOP_STABLE_MS,RELAUNCH_WAIT_WORDS}from"./loop-recovery.js";import{beads}from"./beads.js";import{githubIssues}from"./issues.js";import{installationStatus,renderInstallationStatus,renderTaskWait,repairStaleStatuses,taskWaitSnapshot}from"./lead-status.js";import{latestRelease,newerRelease,notifySecurityRelease,notifyVersionLive,recordRunnerVersion,startUpdateChecks,updateLine}from"./releases.js";import{installMethod}from"./install-method.js";import{PACKAGE_VERSION}from"./version.js";import{machineActing}from"./scope.js";import{enableFlexible,FLEXIBLE_LAPSE_WORDS,FLEXIBLE_LEVEL_WORDS,FLEXIBLE_UNAVAILABLE,flexibleAvailable,flexibleSetting,flexibleStanding,flexibleTermsWords,isFlexibleLevel,lowerFlexible,proposedFlexibleTerms,setFlexibleSetting,turnFlexibleOff}from"./agent-thread/guards.js";import{flexibleSignInStatus,looksLikeClaudeCredential,recheckFlexibleSignIn,removeFlexibleSignIn,saveFlexibleSignIn,setupTokenFromPaste,signInCheckWords,statusCheck,tidyFlexibleSignIns}from"./agent-thread/sign-in.js";import{reevaluateResultRecords}from"./route-results.js";import{holdRuleOff,routeRulesPass,taskEvidenceWords}from"./route-rules.js";import{ruleHoldOf}from"./route-store.js";import{wasInterrupted}from"./run-ending.js";import{loginFileOf,migrateLegacyLogin,removeStaleSavedLogin,savedLoginFile,writableLoginFile}from"./login-secrets.js";import{runWords}from"./needs-you.js";export const EXIT={ok:0,failed:1,usage:2,refused:3};const STATES=["queued","running","done","failed","cancelled"];export const TASK_ADD_HELP=`toolroll task add "<title>" [options]
|
|
2
2
|
|
|
3
3
|
--goal <text> what the task should accomplish (--body is an alias)
|
|
4
4
|
--plan request a plan before coding
|
|
@@ -471,11 +471,11 @@ Exit codes
|
|
|
471
471
|
0 it happened 2 bad usage
|
|
472
472
|
1 something broke 3 ran fine, the answer is no`,TASK_ACTIONS=["add","new","keep","list","show","log","send","handoff","attach","wait","state","block","unblock","next","steer","pause","continue","assign","reopen","scope","approve","hold","unhold","require","requeue","regate","plan","review","accept","repair","route","stop","resume","complete","revise","merge","ask","checks","add-tests","archive","restore","tidy","ship","ready","handover","before-after","failing-first","land"],PUBLISH_ACTIONS=["setup","grant","revoke","status","unblock","rearm","merge","refire"],CONFIG_ACTIONS=["show","set","clear"],APPROVER_ACTIONS=["list","add"],PEOPLE_ACTIONS=["list","invite","projects","revoke"],KEYS_ACTIONS=["status","set","clear","verify","auth"],SECRET_VALUE_FLAGS=new Set(["token","password"]),OPERATE_VALUE_FLAGS=new Set(["key","db","runner","ttl","state","flow","on","reason","until","id","backend","build","from","allow","selector","paths","credentials","repo","token","capacity","agents","goal","not","touches","acceptance","candidate","by","digest","terms","as","branch","pool","base","model","turns","max","cap","probe","kind","expires","cmd","since","repair-model","choose","choice","claim","revision","note","max-open-decisions","name","days","publication","auto-approve","review-auto","port","host","allow-host","for","tick-every","bridge-every","reconcile-every","incarnation","say","ceiling-usd","cap-usd","incident","into","case","k","world","deny","abandon","token-file","bin","poll","github","remote","head-prefix","password","not-requester","protect","protect-paths","checkpoint","out","from","to","month","usd","person","subagent","teammate","providers","models","tools","project-root","schedule","ceiling","require","provider","plan-model","plan-provider","public-url","editor","command","timeout-seconds","setup-digest","stop-grace","title","name","every","lines","label","reviewers","limit","role","key-file","weekly-usd","daily-turns","per-hour","token-file","budget-usd","build-usd","sync-max-age","merge-method","phase","tier","clear-phase","size","risky","run","containment","agent","path","line","action","from-review","from-check","task","starter","template","steps","about","language","timeout-minutes","body","description","zone","option","except","token-env","after","repair-max-attempts","consumer","batch","feedback","source","view","cursor","why","supersedes","decision","sessions","timeout","replaced-by","replaces","quick","level","checks","task","access","projects","overlap","token-name","request","read-deny","mach","default","release","despite"]),OPERATE_BOOLEAN_FLAGS=new Set(["plan","just-code","finish","preview","diagnostic","keep","no-carry","from-main","full-check","rehearsal","json","yes","all","brief","local","history","latest-watch","dry-run","file","clear","follow","ready","all-tasks","inbound-only","help","undo","anyone","allow-dispatch","allow-merge","merge-delete-branch","no-open","single-process","laptop","web","remove","no-verify","no-follow","end","report","off","tmux","self-heal","plan-auto","chat-approve","full-access","repair-auto","review-retry-auto","no-local","html","csv","alerts-only","open","allowlist","allow-paid","no-paid","zip","saved","pull-request","checked","landed","verbose","revoke","anyway","also","reroute","password-stdin","now","preview","apply","no-check","check","wait","live","sub","list"]);const PROJECT_NETWORK_VALUE_FLAGS=new Set(["remove","local"]);export function parseOperateArgs(argv,ownValues=new Set){const positional=[],flags=new Map,repoList=[],wantsValue=new Set([...OPERATE_VALUE_FLAGS,...ownValues]),booleans=new Set([...OPERATE_BOOLEAN_FLAGS].filter(name=>!ownValues.has(name)));for(let index=0;index<argv.length;index++){const argument=argv[index];if(!argument.startsWith("--")){if(argument==="-h"){flags.set("help",!0);continue}if(argument==="-f"){flags.set("follow",!0);continue}positional.push(argument);continue}const equals=argument.indexOf("="),name=argument.slice(2,equals===-1?void 0:equals);if(booleans.has(name)){if(equals!==-1)return{error:`--${name} does not take a value`};flags.set(name,!0);continue}if(!wantsValue.has(name))return{error:`unknown option --${name} — add --help to any queue command for the whole surface`};const value=equals===-1?argv[++index]:argument.slice(equals+1),namesFlag=one=>{const flag2=one.slice(2).split("=")[0];return booleans.has(flag2)||wantsValue.has(flag2)};if(value===void 0||equals===-1&&value.startsWith("--")&&(!SECRET_VALUE_FLAGS.has(name)||namesFlag(value)))return{error:`--${name} needs a value`};if(flags.set(name,name==="param"&&typeof flags.get(name)=="string"?`${flags.get(name)}
|
|
473
473
|
${value}`:value),name==="repo")for(const one of value.split(",").map(part=>part.trim()).filter(part=>part!==""))repoList.push(one)}return{positional,flags,repoList}}export async function runOperate(command,argv,write,options={}){return command==="task"&&(argv=withTaskAlias(["task",...argv]).slice(1)),withPasswordSource(CLI_PASSWORD_SOURCE,()=>rememberedLogin.run({login:null},()=>runOperateLocal(command,argv,write,options)))}async function runOperateLocal(command,argv,write,options={}){const parsed=parseOperateArgs(argv,ownValueFlags(command,argv));if("error"in parsed)return fail(write,argv.includes("--json"),command,"usage",parsed.error,EXIT.usage);const{positional,flags}=parsed,json=flags.has("json");if(flags.has("help")){const helpText=command==="task"&&(positional.length===0||positional[0]==="add")?positional[0]==="add"?TASK_ADD_HELP:TASK_HELP:command==="plugin"?`toolroll plugin list | install <github-url|folder> | update [id] | rollback <id> | remove <id> | validate <folder>
|
|
474
|
-
Add --json for a machine-readable envelope.`:command==="flows"?FLOWS_HELP:command==="lead"?LEAD_HELP:command==="card"?CARD_HELP:command==="config"?configHelp(PROVIDER_IDS):command==="models"?MODELS_HELP:OPERATE_HELP;return write(json?envelopeJson({ok:!0,command:"help",help:helpText}):helpText),EXIT.ok}if(localOwnerRequested()&&localOwnerRowAct(command,positional,flags)===null)return fail(write,json,command,"refused","Set a password, or sign in with your password, to do this.",EXIT.refused);const file=text(flags,"db")??options.databaseFile??databasePath(process.env,homedir()),now=options.now??new Date;try{applyProjectProfile(command,positional,flags,file)}catch(error){return fail(write,json,command,"configuration",describe(error),EXIT.refused)}try{const containment=resolveContainment(text(flags,"containment"));if(!containment.ok)return fail(write,json,command,"usage",containment.problem,EXIT.usage)}catch(error){return fail(write,json,command,"usage",describe(error),EXIT.usage)}if(command==="mcp")return mcpCommand(file,flags,write,json);if(command==="serve"&&positional[0]==="check-public")return checkPublicCommand(flags,{write,json,envelope:envelopeJson,...options.publicProbe===void 0?{}:{probe:options.publicProbe}});if(command==="restore")return restoreCommand(file,positional,flags,write,json,now);if(command==="plugin"&&positional[0]==="validate")return positional.length!==2?fail(write,json,"plugin validate","usage","toolroll plugin validate <folder>",EXIT.usage):validatePluginCommand(file,positional[1],write,json);let store;try{const laptop=command==="up"&&flags.has("laptop")&&options.upRole===void 0;store=options.openDatabase!==void 0?options.openDatabase(file):openStore(file,laptop?{createdBy:"laptop"}:{})}catch(error){return databaseFailure(write,json,command,file,error)}if(file!==":memory:"&&startToolSecrets(store,file,()=>new Date,{eager:SECRETS_FIRST.has(command)}),localOwnerRequested()||shellActsAsLocalOwner(store,command,positional,flags,options)){const admitted=localOwnerCommand(store,command,positional,flags);if(!admitted.ok)return store.close(),fail(write,json,command,"refused",admitted.message,EXIT.refused);try{return await dispatchOn(command,positional,flags,parsed.repoList,{store,write,json,file,now},options,run2=>asLocalOwner(admitted.principal,run2))}finally{store.close()}}const presentedFlag=text(flags,"token"),flagLead=presentedFlag!==void 0&&parseLeadToken(presentedFlag)!==null,envLead=envValue(process.env,"LEAD_TOKEN"),presented=flagLead?presentedFlag:LEAD_COMMANDS.has(command)&&envLead!==void 0&&envLead!==""?envLead:void 0;let actor=null;if(presented!==void 0){if(!LEAD_COMMANDS.has(command))return store.close(),fail(write,json,command,"usage",`A lead token works for ${[...LEAD_COMMANDS].filter(one=>one!=="lead").join(", ")}. Use your own sign-in for ${command}.`,EXIT.usage);const lead=store.leadFor(presented);if(lead===null)return store.close(),fail(write,json,command,"unauthenticated","That lead token is not valid (revoked, replaced, or its owner can no longer approve). The owner mints a new one with: toolroll lead token",EXIT.refused);flagLead&&flags.delete("token"),actor={account:lead.owner,lead:!0}}try{return await dispatchOn(command,positional,flags,parsed.repoList,{store,write,json,file,now,...actor===null?{}:{leadToken:presented}},options,run2=>LEAD_COMMANDS.has(command)?withActor(actor,run2):run2())}finally{store.close()}}async function dispatchOn(command,positional,flags,repoList,base,options,enter){const{store,write,json,file,now}=base,dropLimitSink=pushLimitSink(reading=>store.recordProviderLimits(reading,new Date)),sizer=options.filingSizer??(process.env.VITEST!==void 0||envValue(process.env,"NO_TASK_CLASSIFIER")!==void 0||store.isDemo()?null:ownerSizer()),dropSizer=sizer===null?()=>{}:installFilingSizer(sizer),clock=options.now===void 0?()=>new Date:()=>now;try{return await enter(()=>dispatch(command,positional,flags,{...base.leadToken===void 0?{}:{leadToken:base.leadToken},store,write,json,repoList,now,clock,evidenceRoot:join(dirname(file),"evidence"),databaseFile:file,...injectedSeams(options),telegramTokenFile:join(dirname(file),"telegram-token"),...upNeedsOneProcess(options)?{upOneProcess:!0}:{},...activeRemote()===null?{}:{principal:activeRemote()}}))}catch(error){return error instanceof RemoteRefusal?fail(write,json,command,error.reason,error.message,EXIT.refused):isDatabaseBusy(error)?databaseFailure(write,json,command,file,error):fail(write,json,command,"failed",describe(error),EXIT.failed)}finally{await settleSizings(),dropSizer(),dropLimitSink()}}export async function runOperateAs(argv,opts){const{principal,store,write}=opts,source=opts.source==="mcp"?"mcp":"api",options=opts.options??{},now=options.now??new Date;argv=[...withTaskAlias(argv)];const[root="",...rest]=argv,json=rest.includes("--json");let invocation=root,tokenName=null;const tool=source==="mcp"&&typeof opts.tool=="string"&&/^[a-z][a-z0-9_]{0,40}$/.test(opts.tool)?opts.tool:null,record=(outcome,repo,taskId,why)=>{store.recordAction({at:(options.now??new Date).toISOString(),actor:principal.account,repo,taskId,runId:null,action:`remote command: ${invocation===""?"(none)":invocation}`.slice(0,200),outcome,source,detail:`token ${tokenName??principal.tokenId}${why===null?"":` · ${why}`}${tool===null?"":` · tool ${tool}`}`})},refuse=(reason,message,repo=null,taskId=null)=>(record("refused",repo,taskId,reason),fail(write,json,invocation===""?"remote":invocation,reason,message,EXIT.refused)),proved=reproveRemote(store,principal,now);if(!proved.ok)return refuse("unauthenticated",REMOTE_MESSAGES.stale);tokenName=proved.tokenName;const firstFlag=rest.findIndex(one=>one.startsWith("-")),row=remoteRowOf(root,firstFlag===-1?rest:rest.slice(0,firstFlag));if(row===null)return refuse("not-remote",REMOTE_MESSAGES.unknown);if(invocation=row.invocation,row.remote==="step-up")return refuse("step-up",REMOTE_MESSAGES["step-up"]);const scope=REMOTE_SCOPES.get(row.invocation);if(row.remote!=="yes"||scope===void 0)return refuse("not-remote",REMOTE_MESSAGES.no);const parsed=parseOperateArgs(rest,ownValueFlags(root,rest));if("error"in parsed)return refuse("usage",parsed.error);if(remoteRowOf(root,parsed.positional)?.invocation!==row.invocation)return refuse("not-remote",REMOTE_MESSAGES.unknown);if(!adapterPolicy({caller:"bearer",capability:proved.scope,token:!0},row.mutation!=="none"?"act":"read").ok||proved.scope==="read"&&row.mutation!=="none")return refuse("read-only",REMOTE_MESSAGES.read);if([...parsed.flags.keys()].some(name=>REMOTE_REFUSED_FLAGS.has(name)))return refuse("usage",REMOTE_MESSAGES.credential);const allows=repo=>remoteAllows(store,principal,repo),project=remoteProjectOf(store,{allows},scope,parsed.positional,parsed.repoList,row.invocation,parsed.flags,opts.files??{});if(!project.ok)return refuse(project.reason,project.message);if(!adapterPolicy({caller:"bearer",capability:proved.scope,token:!0},void 0,source2=>source2==="adapter"&&(project.repo===null||allows(project.repo))).ok)return refuse("forbidden",REMOTE_MESSAGES.no);const key=text(parsed.flags,"key");key!==void 0&&row.invocation!=="task revise"&&parsed.flags.set("key",`remote:${createHash("sha256").update(JSON.stringify([principal.account,row.invocation,project.repo,project.taskId,key])).digest("hex")}`);const file=store.databaseFile()??options.databaseFile;if(file===void 0)return refuse("failed","The server's database has no file.",project.repo,project.taskId);let filed=null;const run2=Object.freeze({account:principal.account,scope:proved.scope,tokenName:proved.tokenName,source,secret:remoteSecret(),allows,lens:remoteLensOf(store,scope,allows),noteTask:taskId=>{filed=taskId},files:Object.freeze({...opts.files})});record("requested",project.repo,project.taskId,null);let code;try{code=await withRemote(run2,()=>dispatchOn(root,parsed.positional,parsed.flags,parsed.repoList,{store,write,json,file,now},options,go=>withActor({account:principal.account,lead:!1},()=>projectAuthority.run({actor:principal.account,repo:project.repo},go))))}catch(error){throw record("failed",project.repo,filed??project.taskId,null),error}return record(code===EXIT.ok?"done":code===EXIT.refused?"refused":code===EXIT.usage?"usage":"failed",project.repo,filed??project.taskId,null),code}function remoteFile(remote,path){if(Object.prototype.hasOwnProperty.call(remote.files,path))return remote.files[path];throw new RemoteRefusal("usage",REMOTE_MESSAGES.files)}const LEAD_COMMANDS=new Set(["plugin","task","assignment","status","ready","brief","peek","check-progress","notifications","lead"]),SEAMS=["tempRoots","desktopIdentity","inferProjectFromCwd","additionalProjectRepos","agentRunner","gitRunner","telegramTransport","telegramEnv","publishExec","dispatchAdapter","flowTriggerIo","flowStepIo","flowEveryMs","watchHeartbeatMs","loopRelaunchMs","platform","fenceAvailable","flowFetch","integrationIo","shouldStop","leadSeams","waitSleep","releaseIo","installBin","onboardSeams","upSeams","laptopSeams","easySeams","upRole","folderLook","underAgent"];function registryPathOf(context){return join(dirname(context.databaseFile),"repos.json")}function telegramReadProjects(context){return async()=>{const loaded=await loadProjectRegistry(registryPathOf(context));if("error"in loaded)throw new Error("project registry unavailable");return loaded.repos}}function telegramCanDeliver(context,token){return()=>loadBotToken(process.env,context.telegramTokenFile)?.token===token&&effectivePrimary(process.env,dirname(context.databaseFile),!0).channel==="telegram"}function telegramConversation(context,options={}){return{evidenceRoot:context.evidenceRoot,...context.leadSeams?.subscriptionRunner===void 0?{}:{subscriptionRunner:context.leadSeams.subscriptionRunner},phoneOrigin:()=>phoneOrigin(process.env,dirname(context.databaseFile),{serverOrigin:options.serverOrigin??null})}}function noteBaseStanding(store,runId,standing,main,now){if(standing==null)return;const commits=count=>`${count} commit${count===1?"":"s"}`;if(standing.moved!==null)store.addRunNote(runId,"Toolroll",`Started from current ${main} (${standing.main.slice(0,8)}). The branch had no commits or changes of its own and was ${commits(standing.moved.behind)} behind at ${standing.moved.from.slice(0,8)}.`,now);else if(standing.kept!==null&&standing.behind>0){const why=standing.kept==="has commits"?"it has commits of its own":standing.kept==="has changes"?"it has uncommitted changes":"its checkout is not on the task branch";store.addRunNote(runId,"Toolroll",`Based on an older ${main}: ${standing.head.slice(0,8)} is ${commits(standing.behind)} behind. It was not moved because ${why}.`,now)}}function revisionSourceHead(store,evidenceRoot,taskRef,revisionOf){const source=store.revisionSourceOf(taskRef),sourceRun=source===null?null:store.getRun(source.sourceRun);if(source===null||sourceRun===null||store.externalIdFor(sourceRun.taskRef)!==revisionOf||sourceRun.headRevision===null)return{ok:!1,problem:"the revision source has no matching sealed head"};try{const verified=readVerifiedArtifact(evidenceRoot,source.briefArtifact),brief=verified.ok?JSON.parse(verified.content.toString("utf8")):null;return brief===null||brief.head!==sourceRun.headRevision||brief.sourceScopeDigest!==sourceRun.scopeDigest?{ok:!1,problem:"the revision brief no longer binds the source head and scope"}:{ok:!0,head:sourceRun.headRevision}}catch{return{ok:!1,problem:"the revision source brief cannot be verified"}}}async function dispatch(command,positional,flags,context){const handler=Object.prototype.hasOwnProperty.call(COMMANDS,command)?COMMANDS[command]:void 0;return handler===void 0?fail(context.write,context.json,command,"usage",`unknown command \`${command}\``,EXIT.usage):handler(positional,flags,context)}function openBackend(name,store,repo){return name===BUILT_IN?builtIn(store):name==="beads"?guarded(beads({repo}),{store,repo}):name==="github-issues"?guarded(githubIssues({repo}),{store,repo}):null}function repoFrom(flags){if(activeRemote()!==null&&text(flags,"repo")===void 0)throw new RemoteRefusal("unknown-project",REMOTE_MESSAGES.project);return resolve(text(flags,"repo")??process.cwd())}async function readyCommand(flags,context){const{store,write,json,now}=context,backendName=text(flags,"backend")??BUILT_IN;if(backendName!==BUILT_IN){const repo=repoFrom(flags),backend=openBackend(backendName,store,repo);if(backend===null)return fail(write,json,"ready","usage",`no backend \`${backendName}\``,EXIT.usage);const result=await backend.listReady();if(!result.ok)return fail(write,json,"ready",result.reason,result.message,EXIT.failed);const tasks=result.value;if(json)return write(envelopeJson({ok:tasks.length>0,command:"ready",...tasks.length>0?{}:{reason:"empty",message:"nothing is ready to dispatch"},backend:backendName,count:tasks.length,tasks})),tasks.length>0?EXIT.ok:EXIT.refused;if(tasks.length===0)return write(`Nothing is ready in ${backendName}.`),EXIT.refused;write(`${tasks.length} ready in ${backendName}:`);for(const task of tasks)write(` ${task.id} ${task.title}`);return EXIT.ok}const lens=context.principal?.lens??null,ready=store.listReady(now).filter(ref=>lens===null||ref.repo!==null&&lens.includes(ref.repo)),described=ready.map(ref=>describeRef(store,ref,now)),dispatchableCount=described.filter(one=>diagnosisIsDispatchable(one.dispatch)).length,pauses=openAuthPauses(store);if(json)return write(envelopeJson({ok:ready.length>0,command:"ready",...ready.length>0?{}:{reason:"empty",message:"nothing is task-locally ready"},count:ready.length,dispatchableCount,signIn:pauses.map(one=>({provider:one.provider,message:signInWords(one),since:one.openedAt})),tasks:described})),ready.length>0?EXIT.ok:EXIT.refused;for(const one of pauses)write(signInWords(one));if(ready.length===0)return write("Nothing is ready to dispatch."),EXIT.refused;write(`${ready.length} task-local candidate${ready.length===1?"":"s"} (${dispatchableCount} can dispatch with the fleet as it stands):`);for(const ref of ready){const task=store.getTask(ref.externalId),diagnosis=diagnoseTaskDispatch(store,ref.externalId,now);write(` ${ref.externalId} ${task===null?"":task.title}${ref.assignedRunner===null?"":` (reserved for ${ref.assignedRunner})`}${diagnosis===null?"":` — ${diagnosis.code==="signed-out"?diagnosis.summary:diagnosis.summary.toLowerCase()}`}`)}return EXIT.ok}function describeRef(store,ref,now){const task=store.getTask(ref.externalId);return{id:ref.externalId,ref:ref.id,backend:ref.backend,title:task?.title??null,state:task?.state??null,reservedFor:ref.assignedRunner??null,claim:currentClaim(store,ref.id,now),dispatch:diagnoseTaskDispatch(store,ref.externalId,now)}}function claimCommand(positional,flags,context){const{store,write,json,now}=context,id=positional[0],runner=text(flags,"runner");if(id===void 0)return fail(write,json,"claim","usage","which task? `toolroll claim <id> --runner <name> --token <token>`",EXIT.usage);if(runner===void 0)return fail(write,json,"claim","usage","--runner names who is taking it",EXIT.usage);const token=text(flags,"token");if(token===void 0)return fail(write,json,"claim","usage","--token proves the runner is who it says",EXIT.usage);const auth=authenticate(store,runner,token);if(!auth.ok)return fail(write,json,"claim",auth.reason,describeAuth(auth.reason,runner),EXIT.refused);const backend=text(flags,"backend")??BUILT_IN;if(backend===BUILT_IN&&store.getTask(id)===null)return fail(write,json,"claim","unknown-task",`no task \`${id}\``,EXIT.refused);const ttl=readTtl(flags);if(ttl===null)return fail(write,json,"claim","usage","--ttl takes whole seconds",EXIT.usage);if(backend!==BUILT_IN){const repo=resolve(text(flags,"repo")??process.cwd()),verdict=permits(store.grantFor(repo,backend),{repo,backend,mutation:"transition",origin:store.originOf(backend,id)});if(!verdict.ok)return fail(write,json,"claim",verdict.reason,verdict.message,EXIT.refused)}const ref=store.refFor(backend,id),result=claimAndMarkRunning(store,backend,id,ref.id,runner,{now,token,ttlMs:ttl,mutation:mutationFrom(flags,now)});return result.ok?succeed(write,json,"claim",{lease:result.claim,reclaimed:result.reclaimed},()=>[`Claimed ${id} as ${runner}.`,` lease ${result.claim.leaseId}`,` expires ${result.claim.expiresAt}`]):result.reason==="reserved"?fail(write,json,"claim","reserved",`${id} is reserved for ${result.reservedFor} — only that worker takes it`,EXIT.refused,{reservedFor:result.reservedFor}):result.reason==="external"?fail(write,json,"claim","external",{"stale-mirror":"this tracker item has not been seen recently — run `toolroll sync` first","external-closed":"the tracker closed this — reopen it first, or leave it be","dispatch-revoked":"this tracker's building permission was revoked or narrowed","plane-blocked":"this tracker's plane marker could not be verified — building is paused"}[result.detail]??"external work is not dispatchable right now",EXIT.refused,{detail:result.detail}):result.reason==="mode-ended"?fail(write,json,"claim","mode-ended",result.message,EXIT.refused):result.reason==="unauthenticated"?fail(write,json,"claim","unauthenticated",describeAuth(result.detail,runner),EXIT.refused):result.reason==="unplaced"?fail(write,json,"claim","unplaced","this task has no repository — preserve its history and file a replacement with `task add <title> --repo <path>`, then approve the new scope",EXIT.refused):result.reason==="unauthorized-repo"?fail(write,json,"claim","unauthorized-repo",`this runner is not bound to ${result.repo} — \`runner bind\` adds it`,EXIT.refused):result.reason==="coordinator-filed"?fail(write,json,"claim","coordinator-filed","a coordinator filed this — nothing runs until the operator signs its scope",EXIT.refused):result.reason==="sweep-limit"?fail(write,json,"claim","sweep-limit",`its sweep already has ${result.limit} running at once — it starts when one finishes`,EXIT.refused,{sweep:result.sweep,limit:result.limit}):result.reason==="watch-custody"?fail(write,json,"claim","watch-custody","This worker no longer holds the project; restart the watch",EXIT.refused):result.reason==="archived"?fail(write,json,"claim","archived",`${id} is put away — restore it with \`toolroll task restore ${id}\` first`,EXIT.refused):result.reason==="draining"?fail(write,json,"claim","draining",`Toolroll is restarting (draining): ${runner} takes no new work until it is back (by ${result.until})`,EXIT.refused,{until:result.until}):result.reason==="closed"?fail(write,json,"claim","closed",closedClaimWords(store,id,result.state,now),EXIT.refused,{state:result.state}):result.reason==="no-task"?fail(write,json,"claim","no-task",`no task \`${id}\``,EXIT.refused):fail(write,json,"claim",result.reason,`held by ${result.by} until ${result.until}`,EXIT.refused,{holder:result.by,until:result.until})}function leaseCommand(command,positional,flags,context){const{store,write,json,now}=context,name=command==="release"?"worker release":command,lease=positional[0];if(lease===void 0)return fail(write,json,name,"usage",`which lease? \`toolroll ${name} <lease>\``,EXIT.usage);const ttl=readTtl(flags);if(ttl===null)return fail(write,json,name,"usage","--ttl takes whole seconds",EXIT.usage);const result=command==="heartbeat"?heartbeat(store,lease,now,ttl):releaseToQueue(store,lease,now);if(!result.ok){if(result.reason==="closed")return fail(write,json,name,"closed",`this lease ran out and its task is ${result.state} now, so it can't be renewed; stop rather than retry`,EXIT.refused,{state:result.state});const message=result.reason==="fenced"?"superseded — another runner holds this task now; stop rather than retry":"no such lease";return fail(write,json,name,result.reason,message,EXIT.refused)}return succeed(write,json,name,{lease:result.claim},()=>[command==="heartbeat"?`Still yours until ${result.claim.expiresAt}.`:`Released ${result.claim.leaseId}.`])}function reapCommand(context){const{store,write,json,now}=context,reaped=reap(store,now);if(json)return write(envelopeJson({ok:!0,command:"reap",count:reaped.length,released:reaped})),EXIT.ok;if(reaped.length===0)return write("No leases had run out."),EXIT.ok;write(`Released ${reaped.length}:`);for(const claim of reaped)write(` ${claim.leaseId} held by ${claim.runner}`);return EXIT.ok}async function runnerCommand(positional,flags,context){const{store,write,json,now}=context,[action,name]=positional;if(action==="list"||action===void 0){const runners=store.listRunners().map(one=>({...one,alive:isAlive(one,now)}));if(json)return write(envelopeJson({ok:!0,command:"runner list",count:runners.length,runners})),EXIT.ok;if(runners.length===0)return write("No runners registered."),write(" toolroll runner register <name>"),EXIT.ok;for(const one of runners)write(` ${one.name} ${one.alive?"alive":"not answering"} last heard ${one.heartbeatAt}`);return EXIT.ok}if(action==="register"){if(name===void 0)return fail(write,json,"runner register","usage","a runner needs a name",EXIT.usage);const capacity=Number(text(flags,"capacity")??"1");if(!Number.isInteger(capacity)||capacity<1)return fail(write,json,"runner register","usage","--capacity is a whole number of tasks",EXIT.usage);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,"runner register","usage","`runner register <name> --repo <path> --as <you> --token <t>` — adding a builder is an approver's act",EXIT.usage);const authenticated=credentialApprover(store,acting.name,acting.token);if(!authenticated.ok)return fail(write,json,"runner register",authenticated.reason,describeApproveFailure(authenticated.reason,name),EXIT.refused);const repos=context.repoList??[];if(repos.length===0)return fail(write,json,"runner register","usage","--repo names at least one repository this runner may build — authority binds at the mint",EXIT.usage);const tokenFile=text(flags,"token-file");if(tokenFile!==void 0&&existsSync(tokenFile))return fail(write,json,"runner register","token-file-exists",`${tokenFile} already exists — remove it first if that worker is gone, or name another file`,EXIT.refused);const{runner,token,reclaimed}=register(store,{name,host:hostname(),capacity,repos,now,mutation:mutationFrom(flags,now)});if(tokenFile!==void 0)try{writeFileSync(tokenFile,`${token}
|
|
474
|
+
Add --json for a machine-readable envelope.`:command==="flows"?FLOWS_HELP:command==="lead"?LEAD_HELP:command==="card"?CARD_HELP:command==="config"?configHelp(PROVIDER_IDS):command==="models"?MODELS_HELP:OPERATE_HELP;return write(json?envelopeJson({ok:!0,command:"help",help:helpText}):helpText),EXIT.ok}if(localOwnerRequested()&&localOwnerRowAct(command,positional,flags)===null)return fail(write,json,command,"refused","Set a password, or sign in with your password, to do this.",EXIT.refused);const file=text(flags,"db")??options.databaseFile??databasePath(process.env,homedir()),now=options.now??new Date;try{applyProjectProfile(command,positional,flags,file)}catch(error){return fail(write,json,command,"configuration",describe(error),EXIT.refused)}try{const containment=resolveContainment(text(flags,"containment"));if(!containment.ok)return fail(write,json,command,"usage",containment.problem,EXIT.usage)}catch(error){return fail(write,json,command,"usage",describe(error),EXIT.usage)}if(command==="mcp")return mcpCommand(file,flags,write,json);if(command==="serve"&&positional[0]==="check-public")return checkPublicCommand(flags,{write,json,envelope:envelopeJson,...options.publicProbe===void 0?{}:{probe:options.publicProbe}});if(command==="restore")return restoreCommand(file,positional,flags,write,json,now);if(command==="plugin"&&positional[0]==="validate")return positional.length!==2?fail(write,json,"plugin validate","usage","toolroll plugin validate <folder>",EXIT.usage):validatePluginCommand(file,positional[1],write,json);let store;try{const laptop=command==="up"&&flags.has("laptop")&&options.upRole===void 0;store=options.openDatabase!==void 0?options.openDatabase(file):openStore(file,laptop?{createdBy:"laptop"}:{})}catch(error){return databaseFailure(write,json,command,file,error)}if(file!==":memory:"&&startToolSecrets(store,file,()=>new Date,{eager:SECRETS_FIRST.has(command)}),localOwnerRequested()||shellActsAsLocalOwner(store,command,positional,flags,options)){const admitted=localOwnerCommand(store,command,positional,flags);if(!admitted.ok)return store.close(),fail(write,json,command,"refused",admitted.message,EXIT.refused);try{return await dispatchOn(command,positional,flags,parsed.repoList,{store,write,json,file,now},options,run2=>asLocalOwner(admitted.principal,run2))}finally{store.close()}}const presentedFlag=text(flags,"token"),flagLead=presentedFlag!==void 0&&parseLeadToken(presentedFlag)!==null,envLead=envValue(process.env,"LEAD_TOKEN"),presented=flagLead?presentedFlag:LEAD_COMMANDS.has(command)&&envLead!==void 0&&envLead!==""?envLead:void 0;let actor=null;if(presented!==void 0){if(!LEAD_COMMANDS.has(command))return store.close(),fail(write,json,command,"usage",`A lead token works for ${[...LEAD_COMMANDS].filter(one=>one!=="lead").join(", ")}. Use your own sign-in for ${command}.`,EXIT.usage);const lead=store.leadFor(presented);if(lead===null)return store.close(),fail(write,json,command,"unauthenticated","That lead token is not valid (revoked, replaced, or its owner can no longer approve). The owner mints a new one with: toolroll lead token",EXIT.refused);flagLead&&flags.delete("token"),actor={account:lead.owner,lead:!0}}try{return await dispatchOn(command,positional,flags,parsed.repoList,{store,write,json,file,now,...actor===null?{}:{leadToken:presented}},options,run2=>LEAD_COMMANDS.has(command)?withActor(actor,run2):run2())}finally{store.close()}}async function dispatchOn(command,positional,flags,repoList,base,options,enter){const{store,write,json,file,now}=base,dropLimitSink=pushLimitSink(reading=>store.recordProviderLimits(reading,new Date)),sizer=options.filingSizer??(process.env.VITEST!==void 0||envValue(process.env,"NO_TASK_CLASSIFIER")!==void 0||store.isDemo()?null:ownerSizer()),dropSizer=sizer===null?()=>{}:installFilingSizer(sizer),clock=options.now===void 0?()=>new Date:()=>now;try{return await enter(()=>dispatch(command,positional,flags,{...base.leadToken===void 0?{}:{leadToken:base.leadToken},store,write,json,repoList,now,clock,evidenceRoot:join(dirname(file),"evidence"),databaseFile:file,...injectedSeams(options),telegramTokenFile:join(dirname(file),"telegram-token"),...upNeedsOneProcess(options)?{upOneProcess:!0}:{},...activeRemote()===null?{}:{principal:activeRemote()}}))}catch(error){return error instanceof RemoteRefusal?fail(write,json,command,error.reason,error.message,EXIT.refused):isDatabaseBusy(error)?databaseFailure(write,json,command,file,error):fail(write,json,command,"failed",describe(error),EXIT.failed)}finally{await settleSizings(),dropSizer(),dropLimitSink()}}export async function runOperateAs(argv,opts){const{principal,store,write}=opts,source=opts.source==="mcp"?"mcp":"api",options=opts.options??{},now=options.now??new Date;argv=[...withTaskAlias(argv)];const[root="",...rest]=argv,json=rest.includes("--json");let invocation=root,tokenName=null;const tool=source==="mcp"&&typeof opts.tool=="string"&&/^[a-z][a-z0-9_]{0,40}$/.test(opts.tool)?opts.tool:null,record=(outcome,repo,taskId,why)=>{store.recordAction({at:(options.now??new Date).toISOString(),actor:principal.account,repo,taskId,runId:null,action:`remote command: ${invocation===""?"(none)":invocation}`.slice(0,200),outcome,source,detail:`token ${tokenName??principal.tokenId}${why===null?"":` · ${why}`}${tool===null?"":` · tool ${tool}`}`})},refuse=(reason,message,repo=null,taskId=null)=>(record("refused",repo,taskId,reason),fail(write,json,invocation===""?"remote":invocation,reason,message,EXIT.refused)),proved=reproveRemote(store,principal,now);if(!proved.ok)return refuse("unauthenticated",REMOTE_MESSAGES.stale);tokenName=proved.tokenName;const firstFlag=rest.findIndex(one=>one.startsWith("-")),row=remoteRowOf(root,firstFlag===-1?rest:rest.slice(0,firstFlag));if(row===null)return refuse("not-remote",REMOTE_MESSAGES.unknown);if(invocation=row.invocation,row.remote==="step-up")return refuse("step-up",REMOTE_MESSAGES["step-up"]);const scope=REMOTE_SCOPES.get(row.invocation);if(row.remote!=="yes"||scope===void 0)return refuse("not-remote",REMOTE_MESSAGES.no);const parsed=parseOperateArgs(rest,ownValueFlags(root,rest));if("error"in parsed)return refuse("usage",parsed.error);if(remoteRowOf(root,parsed.positional)?.invocation!==row.invocation)return refuse("not-remote",REMOTE_MESSAGES.unknown);if(!adapterPolicy({caller:"bearer",capability:proved.scope,token:!0},row.mutation!=="none"?"act":"read").ok||proved.scope==="read"&&row.mutation!=="none")return refuse("read-only",REMOTE_MESSAGES.read);if([...parsed.flags.keys()].some(name=>REMOTE_REFUSED_FLAGS.has(name)))return refuse("usage",REMOTE_MESSAGES.credential);const allows=repo=>remoteAllows(store,principal,repo),project=remoteProjectOf(store,{allows},scope,parsed.positional,parsed.repoList,row.invocation,parsed.flags,opts.files??{});if(!project.ok)return refuse(project.reason,project.message);if(!adapterPolicy({caller:"bearer",capability:proved.scope,token:!0},void 0,source2=>source2==="adapter"&&(project.repo===null||allows(project.repo))).ok)return refuse("forbidden",REMOTE_MESSAGES.no);const key=text(parsed.flags,"key");key!==void 0&&row.invocation!=="task revise"&&parsed.flags.set("key",`remote:${createHash("sha256").update(JSON.stringify([principal.account,row.invocation,project.repo,project.taskId,key])).digest("hex")}`);const file=store.databaseFile()??options.databaseFile;if(file===void 0)return refuse("failed","The server's database has no file.",project.repo,project.taskId);let filed=null;const run2=Object.freeze({account:principal.account,scope:proved.scope,tokenName:proved.tokenName,source,secret:remoteSecret(),allows,lens:remoteLensOf(store,scope,allows),noteTask:taskId=>{filed=taskId},files:Object.freeze({...opts.files})});record("requested",project.repo,project.taskId,null);let code;try{code=await withRemote(run2,()=>dispatchOn(root,parsed.positional,parsed.flags,parsed.repoList,{store,write,json,file,now},options,go=>withActor({account:principal.account,lead:!1},()=>projectAuthority.run({actor:principal.account,repo:project.repo},go))))}catch(error){throw record("failed",project.repo,filed??project.taskId,null),error}return record(code===EXIT.ok?"done":code===EXIT.refused?"refused":code===EXIT.usage?"usage":"failed",project.repo,filed??project.taskId,null),code}function remoteFile(remote,path){if(Object.prototype.hasOwnProperty.call(remote.files,path))return remote.files[path];throw new RemoteRefusal("usage",REMOTE_MESSAGES.files)}const LEAD_COMMANDS=new Set(["plugin","task","assignment","status","ready","brief","peek","check-progress","notifications","lead"]),SEAMS=["tempRoots","desktopIdentity","inferProjectFromCwd","additionalProjectRepos","agentRunner","gitRunner","telegramTransport","telegramEnv","publishExec","dispatchAdapter","flowTriggerIo","flowStepIo","flowEveryMs","reviewEveryMs","watchHeartbeatMs","loopRelaunchMs","platform","fenceAvailable","flowFetch","integrationIo","shouldStop","leadSeams","waitSleep","releaseIo","installBin","onboardSeams","upSeams","laptopSeams","easySeams","upRole","folderLook","underAgent"];function registryPathOf(context){return join(dirname(context.databaseFile),"repos.json")}function telegramReadProjects(context){return async()=>{const loaded=await loadProjectRegistry(registryPathOf(context));if("error"in loaded)throw new Error("project registry unavailable");return loaded.repos}}function telegramCanDeliver(context,token){return()=>loadBotToken(process.env,context.telegramTokenFile)?.token===token&&effectivePrimary(process.env,dirname(context.databaseFile),!0).channel==="telegram"}function telegramConversation(context,options={}){return{evidenceRoot:context.evidenceRoot,...context.leadSeams?.subscriptionRunner===void 0?{}:{subscriptionRunner:context.leadSeams.subscriptionRunner},phoneOrigin:()=>phoneOrigin(process.env,dirname(context.databaseFile),{serverOrigin:options.serverOrigin??null})}}function noteBaseStanding(store,runId,standing,main,now){if(standing==null)return;const commits=count=>`${count} commit${count===1?"":"s"}`;if(standing.moved!==null)store.addRunNote(runId,"Toolroll",`Started from current ${main} (${standing.main.slice(0,8)}). The branch had no commits or changes of its own and was ${commits(standing.moved.behind)} behind at ${standing.moved.from.slice(0,8)}.`,now);else if(standing.kept!==null&&standing.behind>0){const why=standing.kept==="has commits"?"it has commits of its own":standing.kept==="has changes"?"it has uncommitted changes":"its checkout is not on the task branch";store.addRunNote(runId,"Toolroll",`Based on an older ${main}: ${standing.head.slice(0,8)} is ${commits(standing.behind)} behind. It was not moved because ${why}.`,now)}}function revisionSourceHead(store,evidenceRoot,taskRef,revisionOf){const source=store.revisionSourceOf(taskRef),sourceRun=source===null?null:store.getRun(source.sourceRun);if(source===null||sourceRun===null||store.externalIdFor(sourceRun.taskRef)!==revisionOf||sourceRun.headRevision===null)return{ok:!1,problem:"the revision source has no matching sealed head"};try{const verified=readVerifiedArtifact(evidenceRoot,source.briefArtifact),brief=verified.ok?JSON.parse(verified.content.toString("utf8")):null;return brief===null||brief.head!==sourceRun.headRevision||brief.sourceScopeDigest!==sourceRun.scopeDigest?{ok:!1,problem:"the revision brief no longer binds the source head and scope"}:{ok:!0,head:sourceRun.headRevision}}catch{return{ok:!1,problem:"the revision source brief cannot be verified"}}}async function dispatch(command,positional,flags,context){const handler=Object.prototype.hasOwnProperty.call(COMMANDS,command)?COMMANDS[command]:void 0;return handler===void 0?fail(context.write,context.json,command,"usage",`unknown command \`${command}\``,EXIT.usage):handler(positional,flags,context)}function openBackend(name,store,repo){return name===BUILT_IN?builtIn(store):name==="beads"?guarded(beads({repo}),{store,repo}):name==="github-issues"?guarded(githubIssues({repo}),{store,repo}):null}function repoFrom(flags){if(activeRemote()!==null&&text(flags,"repo")===void 0)throw new RemoteRefusal("unknown-project",REMOTE_MESSAGES.project);return resolve(text(flags,"repo")??process.cwd())}async function readyCommand(flags,context){const{store,write,json,now}=context,backendName=text(flags,"backend")??BUILT_IN;if(backendName!==BUILT_IN){const repo=repoFrom(flags),backend=openBackend(backendName,store,repo);if(backend===null)return fail(write,json,"ready","usage",`no backend \`${backendName}\``,EXIT.usage);const result=await backend.listReady();if(!result.ok)return fail(write,json,"ready",result.reason,result.message,EXIT.failed);const tasks=result.value;if(json)return write(envelopeJson({ok:tasks.length>0,command:"ready",...tasks.length>0?{}:{reason:"empty",message:"nothing is ready to dispatch"},backend:backendName,count:tasks.length,tasks})),tasks.length>0?EXIT.ok:EXIT.refused;if(tasks.length===0)return write(`Nothing is ready in ${backendName}.`),EXIT.refused;write(`${tasks.length} ready in ${backendName}:`);for(const task of tasks)write(` ${task.id} ${task.title}`);return EXIT.ok}const lens=context.principal?.lens??null,ready=store.listReady(now).filter(ref=>lens===null||ref.repo!==null&&lens.includes(ref.repo)),described=ready.map(ref=>describeRef(store,ref,now)),dispatchableCount=described.filter(one=>diagnosisIsDispatchable(one.dispatch)).length,pauses=openAuthPauses(store);if(json)return write(envelopeJson({ok:ready.length>0,command:"ready",...ready.length>0?{}:{reason:"empty",message:"nothing is task-locally ready"},count:ready.length,dispatchableCount,signIn:pauses.map(one=>({provider:one.provider,message:signInWords(one),since:one.openedAt})),tasks:described})),ready.length>0?EXIT.ok:EXIT.refused;for(const one of pauses)write(signInWords(one));if(ready.length===0)return write("Nothing is ready to dispatch."),EXIT.refused;write(`${ready.length} task-local candidate${ready.length===1?"":"s"} (${dispatchableCount} can dispatch with the fleet as it stands):`);for(const ref of ready){const task=store.getTask(ref.externalId),diagnosis=diagnoseTaskDispatch(store,ref.externalId,now);write(` ${ref.externalId} ${task===null?"":task.title}${ref.assignedRunner===null?"":` (reserved for ${ref.assignedRunner})`}${diagnosis===null?"":` — ${diagnosis.code==="signed-out"?diagnosis.summary:diagnosis.summary.toLowerCase()}`}`)}return EXIT.ok}function describeRef(store,ref,now){const task=store.getTask(ref.externalId);return{id:ref.externalId,ref:ref.id,backend:ref.backend,title:task?.title??null,state:task?.state??null,reservedFor:ref.assignedRunner??null,claim:currentClaim(store,ref.id,now),dispatch:diagnoseTaskDispatch(store,ref.externalId,now)}}function claimCommand(positional,flags,context){const{store,write,json,now}=context,id=positional[0],runner=text(flags,"runner");if(id===void 0)return fail(write,json,"claim","usage","which task? `toolroll claim <id> --runner <name> --token <token>`",EXIT.usage);if(runner===void 0)return fail(write,json,"claim","usage","--runner names who is taking it",EXIT.usage);const token=text(flags,"token");if(token===void 0)return fail(write,json,"claim","usage","--token proves the runner is who it says",EXIT.usage);const auth=authenticate(store,runner,token);if(!auth.ok)return fail(write,json,"claim",auth.reason,describeAuth(auth.reason,runner),EXIT.refused);const backend=text(flags,"backend")??BUILT_IN;if(backend===BUILT_IN&&store.getTask(id)===null)return fail(write,json,"claim","unknown-task",`no task \`${id}\``,EXIT.refused);const ttl=readTtl(flags);if(ttl===null)return fail(write,json,"claim","usage","--ttl takes whole seconds",EXIT.usage);if(backend!==BUILT_IN){const repo=resolve(text(flags,"repo")??process.cwd()),verdict=permits(store.grantFor(repo,backend),{repo,backend,mutation:"transition",origin:store.originOf(backend,id)});if(!verdict.ok)return fail(write,json,"claim",verdict.reason,verdict.message,EXIT.refused)}const ref=store.refFor(backend,id),result=claimAndMarkRunning(store,backend,id,ref.id,runner,{now,token,ttlMs:ttl,mutation:mutationFrom(flags,now)});return result.ok?succeed(write,json,"claim",{lease:result.claim,reclaimed:result.reclaimed},()=>[`Claimed ${id} as ${runner}.`,` lease ${result.claim.leaseId}`,` expires ${result.claim.expiresAt}`]):result.reason==="reserved"?fail(write,json,"claim","reserved",`${id} is reserved for ${result.reservedFor} — only that worker takes it`,EXIT.refused,{reservedFor:result.reservedFor}):result.reason==="external"?fail(write,json,"claim","external",{"stale-mirror":"this tracker item has not been seen recently — run `toolroll sync` first","external-closed":"the tracker closed this — reopen it first, or leave it be","dispatch-revoked":"this tracker's building permission was revoked or narrowed","plane-blocked":"this tracker's plane marker could not be verified — building is paused"}[result.detail]??"external work is not dispatchable right now",EXIT.refused,{detail:result.detail}):result.reason==="mode-ended"?fail(write,json,"claim","mode-ended",result.message,EXIT.refused):result.reason==="unauthenticated"?fail(write,json,"claim","unauthenticated",describeAuth(result.detail,runner),EXIT.refused):result.reason==="unplaced"?fail(write,json,"claim","unplaced","this task has no repository — preserve its history and file a replacement with `task add <title> --repo <path>`, then approve the new scope",EXIT.refused):result.reason==="unauthorized-repo"?fail(write,json,"claim","unauthorized-repo",`this runner is not bound to ${result.repo} — \`runner bind\` adds it`,EXIT.refused):result.reason==="coordinator-filed"?fail(write,json,"claim","coordinator-filed","a coordinator filed this — nothing runs until the operator signs its scope",EXIT.refused):result.reason==="sweep-limit"?fail(write,json,"claim","sweep-limit",`its sweep already has ${result.limit} running at once — it starts when one finishes`,EXIT.refused,{sweep:result.sweep,limit:result.limit}):result.reason==="watch-custody"?fail(write,json,"claim","watch-custody","This worker no longer holds the project; restart the watch",EXIT.refused):result.reason==="archived"?fail(write,json,"claim","archived",`${id} is put away — restore it with \`toolroll task restore ${id}\` first`,EXIT.refused):result.reason==="draining"?fail(write,json,"claim","draining",`Toolroll is restarting (draining): ${runner} takes no new work until it is back (by ${result.until})`,EXIT.refused,{until:result.until}):result.reason==="closed"?fail(write,json,"claim","closed",closedClaimWords(store,id,result.state,now),EXIT.refused,{state:result.state}):result.reason==="no-task"?fail(write,json,"claim","no-task",`no task \`${id}\``,EXIT.refused):fail(write,json,"claim",result.reason,`held by ${result.by} until ${result.until}`,EXIT.refused,{holder:result.by,until:result.until})}function leaseCommand(command,positional,flags,context){const{store,write,json,now}=context,name=command==="release"?"worker release":command,lease=positional[0];if(lease===void 0)return fail(write,json,name,"usage",`which lease? \`toolroll ${name} <lease>\``,EXIT.usage);const ttl=readTtl(flags);if(ttl===null)return fail(write,json,name,"usage","--ttl takes whole seconds",EXIT.usage);const result=command==="heartbeat"?heartbeat(store,lease,now,ttl):releaseToQueue(store,lease,now);if(!result.ok){if(result.reason==="closed")return fail(write,json,name,"closed",`this lease ran out and its task is ${result.state} now, so it can't be renewed; stop rather than retry`,EXIT.refused,{state:result.state});const message=result.reason==="fenced"?"superseded — another runner holds this task now; stop rather than retry":"no such lease";return fail(write,json,name,result.reason,message,EXIT.refused)}return succeed(write,json,name,{lease:result.claim},()=>[command==="heartbeat"?`Still yours until ${result.claim.expiresAt}.`:`Released ${result.claim.leaseId}.`])}function reapCommand(context){const{store,write,json,now}=context,reaped=reap(store,now);if(json)return write(envelopeJson({ok:!0,command:"reap",count:reaped.length,released:reaped})),EXIT.ok;if(reaped.length===0)return write("No leases had run out."),EXIT.ok;write(`Released ${reaped.length}:`);for(const claim of reaped)write(` ${claim.leaseId} held by ${claim.runner}`);return EXIT.ok}async function runnerCommand(positional,flags,context){const{store,write,json,now}=context,[action,name]=positional;if(action==="list"||action===void 0){const runners=store.listRunners().map(one=>({...one,alive:isAlive(one,now)}));if(json)return write(envelopeJson({ok:!0,command:"runner list",count:runners.length,runners})),EXIT.ok;if(runners.length===0)return write("No runners registered."),write(" toolroll runner register <name>"),EXIT.ok;for(const one of runners)write(` ${one.name} ${one.alive?"alive":"not answering"} last heard ${one.heartbeatAt}`);return EXIT.ok}if(action==="register"){if(name===void 0)return fail(write,json,"runner register","usage","a runner needs a name",EXIT.usage);const capacity=Number(text(flags,"capacity")??"1");if(!Number.isInteger(capacity)||capacity<1)return fail(write,json,"runner register","usage","--capacity is a whole number of tasks",EXIT.usage);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,"runner register","usage","`runner register <name> --repo <path> --as <you> --token <t>` — adding a builder is an approver's act",EXIT.usage);const authenticated=credentialApprover(store,acting.name,acting.token);if(!authenticated.ok)return fail(write,json,"runner register",authenticated.reason,describeApproveFailure(authenticated.reason,name),EXIT.refused);const repos=context.repoList??[];if(repos.length===0)return fail(write,json,"runner register","usage","--repo names at least one repository this runner may build — authority binds at the mint",EXIT.usage);const tokenFile=text(flags,"token-file");if(tokenFile!==void 0&&existsSync(tokenFile))return fail(write,json,"runner register","token-file-exists",`${tokenFile} already exists — remove it first if that worker is gone, or name another file`,EXIT.refused);const{runner,token,reclaimed}=register(store,{name,host:hostname(),capacity,repos,now,mutation:mutationFrom(flags,now)});if(tokenFile!==void 0)try{writeFileSync(tokenFile,`${token}
|
|
475
475
|
`,{mode:384,flag:"wx"}),chmodSync(tokenFile,384)}catch(error){return fail(write,json,"runner register","token-file",`registered ${runner.name}, but the token could not be written to ${tokenFile} (${describe(error)}) — register again with a writable path`,EXIT.failed,{runner,reclaimed})}return succeed(write,json,"runner register",{runner,...tokenFile===void 0?{token}:{tokenFile},reclaimed},()=>[`Registered ${runner.name} on ${runner.host}, capacity ${runner.capacity}.`,"",...tokenFile===void 0?[` token ${token}`,"","That token is shown once and is not stored — only a hash of it is."]:[` token written to ${tokenFile} (owner-only) — \`toolroll watch --runner ${runner.name} --token-file ${tokenFile} --repo <path>\` uses it.`,"","The token is not stored anywhere else — only a hash of it is."],"If it is lost, register again to mint a new one.",...reclaimed===null?[]:["",`A previous ${runner.name} was still holding work; it has been taken back:`,...reclaimed.claims.map(lease=>` claim ${lease}`),...reclaimed.worktrees.map(path=>` worktree ${path} (unverified)`)]])}if(action==="heartbeat"){const token=text(flags,"token");if(name===void 0||token===void 0)return fail(write,json,"runner heartbeat","usage","`runner heartbeat <name> --token <token>`",EXIT.usage);const result=heartbeatRunner(store,name,token,now);return result.ok?succeed(write,json,"runner heartbeat",{runner:result.runner},()=>[`${name} checked in.`]):fail(write,json,"runner heartbeat",result.reason,describeAuth(result.reason,name),EXIT.refused)}if(action==="reap"){const recovered=recoverDead(store,now).filter(recoveredAnything);if(json)return write(envelopeJson({ok:!0,command:"runner reap",recovered})),EXIT.ok;if(recovered.length===0)return write("Every runner is answering, or held nothing."),EXIT.ok;for(const one of recovered){write(`${one.runner} is not answering — took back:`);for(const lease of one.claims)write(` claim ${lease}`);for(const id of one.runs)write(` run #${id} (finished as interrupted)`);for(const id of one.requeued)write(` task ${id} (requeued)`);for(const path of one.worktrees)write(` worktree ${path} (unverified)`)}return EXIT.ok}if(action==="retire"){if(name===void 0)return fail(write,json,"runner retire","usage","which runner?",EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);return acting===null||!verified?.ok?refuseApprover(context,"runner retire",verified,"`runner retire <name> --as <you> --token <t>` — retiring a builder is an approver's act",name):store.retireRunner(name,now,mutationFrom(flags,now))?succeed(write,json,"runner retire",{name},()=>[`${name} is retired.`]):fail(write,json,"runner retire","unknown",`no runner \`${name}\``,EXIT.refused)}if(action==="bind"){if(name===void 0)return fail(write,json,"runner bind","usage","which runner?",EXIT.usage);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,"runner bind","usage","`runner bind <name> --repo <path> --as <you> --token <t>` — choosing a builder's projects is an approver's act",EXIT.usage);const authenticated=credentialApprover(store,acting.name,acting.token);if(!authenticated.ok)return fail(write,json,"runner bind",authenticated.reason,describeApproveFailure(authenticated.reason,name),EXIT.refused);const repos=context.repoList??[];if(repos.length===0)return fail(write,json,"runner bind","usage","--repo names at least one repository",EXIT.usage);const bound=store.bindRunnerRepos(name,canonicalRepos(repos),now);return bound.ok?succeed(write,json,"runner bind",{name,repos:bound.repos},()=>[`${name} may build in:`,...bound.repos.map(one=>` ${one}`)]):fail(write,json,"runner bind",bound.reason,describeAuth(bound.reason,name),EXIT.refused)}if(action==="capacity"){const given=positional[2];if(name===void 0||given===void 0||positional.length>3)return fail(write,json,"runner capacity","usage","`runner capacity <name> <n> --as <you> --token <t>`",EXIT.usage);const capacity=parseRunnerCapacity(given,{allowZero:!0});if(capacity===null)return fail(write,json,"runner capacity","usage",`capacity is a whole number of tasks, 0 to ${RUNNER_CAPACITY_MAX}; 0 stops new builds`,EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok||!store.isInstanceOperator(acting.name))return fail(write,json,"runner capacity","refused","An instance operator changes a worker's capacity: pass --as and --token (or use the remembered login).",EXIT.refused);const changed=store.setRunnerCapacity(name,capacity,acting.name,now);if(!changed.ok)return fail(write,json,"runner capacity",changed.reason,changed.reason==="retired"?`${name} is retired`:`no runner \`${name}\``,EXIT.refused);const running=store.liveClaimCount(name,now);return changed.after===0?succeed(write,json,"runner capacity",{name,before:changed.before,after:changed.after,running},()=>[`${name} takes no new builds. ${running===0?"Nothing is running.":`${running} running task(s) will finish.`}`,`Resume with: toolroll runner capacity ${name} <1-${RUNNER_CAPACITY_MAX}>`]):succeed(write,json,"runner capacity",{name,before:changed.before,after:changed.after,running},()=>[changed.before===changed.after?`${name} already runs up to ${changed.after} at once.`:`${name} now runs up to ${changed.after} at once (was ${changed.before}).`,...running>changed.after?[`It is running ${running} now; those carry on, and it takes nothing new until fewer than ${changed.after} are running.`]:[]])}return fail(write,json,"runner","usage",`unknown \`runner ${action}\` — try list, register, bind, capacity, heartbeat, reap, retire`,EXIT.usage)}async function coordinatorCommand(positional,flags,context){const{store,write,json,now}=context,[action,name]=positional;if(action==="list"||action===void 0){const rows=listCoordinators(store);if(json)return write(envelopeJson({ok:!0,command:"coordinator list",coordinators:rows})),EXIT.ok;if(rows.length===0)return write("No coordinators. `toolroll coordinator mint <name> --repo <path> --as <you> --token <t>`"),EXIT.ok;for(const one of rows){const state=one.revokedAt===null?`${one.perHour}/h`:"revoked";write(` ${one.name}#${one.cid.slice(0,4)} ${state} ${one.repos.join(", ")} last filed ${one.lastFiledAt??"never"}`)}return EXIT.ok}if(action==="mint"){if(name===void 0)return fail(write,json,"coordinator mint","usage","a coordinator needs a name",EXIT.usage);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,"coordinator mint","usage","`coordinator mint <name> --repo <path> --as <you> --token <t>` — minting your lead's credential is an approver's act",EXIT.usage);const authenticated=credentialApprover(store,acting.name,acting.token);if(!authenticated.ok)return fail(write,json,"coordinator mint",authenticated.reason,describeApproveFailure(authenticated.reason,name),EXIT.refused);const repos=context.repoList??[];if(repos.length===0)return fail(write,json,"coordinator mint","usage","--repo names at least one repository this coordinator may file into",EXIT.usage);const perHourGiven=text(flags,"per-hour"),perHour=perHourGiven===void 0?void 0:Number(perHourGiven),daysGiven=text(flags,"days"),days=daysGiven===void 0?void 0:Number(daysGiven),made=mintCoordinator(store,{name,repos,...perHour===void 0?{}:{perHour},...days===void 0?{}:{days},by:acting.name,now});if(!made.ok){const said={"bad-name":"a coordinator name is 1-32 characters of a-z, 0-9, and dashes","name-taken":`a live coordinator already answers to \`${name}\` — revoke it first, or pick another name`,"bad-rate":"--per-hour is a whole number from 1 to 60, and --days from 1 to 365","no-repos":"--repo names at least one repository"};return fail(write,json,"coordinator mint",made.reason,said[made.reason]??made.reason,made.reason==="name-taken"?EXIT.refused:EXIT.usage)}return succeed(write,json,"coordinator mint",{cid:made.cid,token:made.token,repos:made.repos},()=>[`Minted ${name}#${made.cid.slice(0,4)} — may file into:`,...made.repos.map(one=>` ${one}`),"",` token ${made.token}`,"",`It expires in ${days??90} days: mint a new one before then.`,"That token is shown once and is not stored — only a hash of it is.","Give it to the MCP server via a 0600 token file or TOOLROLL_COORDINATOR."])}if(action==="revoke"){if(name===void 0)return fail(write,json,"coordinator revoke","usage","which coordinator? (`coordinator list` shows cids)",EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"coordinator revoke",verified,"`coordinator revoke <cid> --as <you> --token <t>` — revoking is an approver's act",name);const revoked=revokeCoordinator(store,name,acting.name,now);if(!revoked.ok){const said=revoked.reason==="unknown"?`no coordinator \`${name}\` — \`coordinator list\` shows cids`:"already revoked";return fail(write,json,"coordinator revoke",revoked.reason,said,EXIT.refused)}return succeed(write,json,"coordinator revoke",{cid:name},()=>[`${name} is revoked — its filings stand, its token does not.`])}return fail(write,json,"coordinator","usage",`unknown \`coordinator ${action}\` — try list, mint, revoke`,EXIT.usage)}async function mcpCommand(file,flags,write,json){const said=message=>(json?write(envelopeJson({ok:!1,command:"mcp",reason:"refused",message})):process.stderr.write(`${message}
|
|
476
476
|
`),EXIT.refused),fromFile=text(flags,"token-file"),fromEnv=envValue(process.env,"COORDINATOR");if(fromFile!==void 0&&fromEnv!==void 0&&fromEnv!=="")return said("both --token-file and TOOLROLL_COORDINATOR are set — pick one");let token;if(fromFile!==void 0){let fd;try{fd=openSync(fromFile,fsConstants.O_RDONLY|fsConstants.O_NOFOLLOW|fsConstants.O_NONBLOCK)}catch{return said(`${fromFile}: cannot open (missing, or a symlink — the token file must be the real file)`)}try{const stat=fstatSync(fd);if(!stat.isFile())return said(`${fromFile}: not a regular file`);if(stat.uid!==process.getuid?.())return said(`${fromFile}: owned by somebody else`);if((stat.mode&4095)!==384)return said(`${fromFile}: mode must be exactly 0600 — special bits included`);if(stat.size>4096)return said(`${fromFile}: too large for a token file`);const buffer=Buffer.alloc(4096),read=readSync(fd,buffer,0,4096,0);token=buffer.subarray(0,read).toString("utf8").trim()}finally{closeSync(fd)}}else if(fromEnv!==void 0&&fromEnv!=="")token=fromEnv.trim();else return said("no credential — pass --token-file <path> (0600) or set TOOLROLL_COORDINATOR");process.umask?.(63);const door=openStoreNoMigrate(file);if(!door.ok)return said(door.message);const store=door.store;startToolSecrets(store,file,()=>new Date,{eager:!1});for(const suffix of["","-wal","-shm"])try{chmodSync(`${file}${suffix}`,384)}catch{}try{chmodSync(dirname(file),448)}catch{}if(store.isDemo())return store.close(),said("demo console — no gateway");let enrolled=null;try{const loaded=await loadRepos(registryPathOf({databaseFile:file}));"error"in loaded||(enrolled=loaded.repos)}catch{enrolled=null}return await new Promise(resolvePromise=>{let lineHandler=()=>{},eofHandler=()=>{};const reader=createInterface({input:process.stdin,terminal:!1});reader.on("line",line=>lineHandler(line)),reader.on("close",()=>eofHandler());const outcome=serveMcp(store,token,{onLine:handler=>{lineHandler=handler},onEof:handler=>{eofHandler=handler},write:line=>process.stdout.write(`${line}
|
|
477
477
|
`),log:line=>process.stderr.write(`${line}
|
|
478
|
-
`),exit:code=>{reader.close(),store.close(),resolvePromise(code)}},void 0,enrolled,join(dirname(file),"evidence"));outcome.ok||(reader.close(),store.close(),resolvePromise(said(outcome.message)))})}function describeAuth(reason,name){return reason==="unknown"?`no runner \`${name}\` — register it first`:reason==="retired"?`${name} has been retired`:reason==="expired"?`${name}'s token expired a year after it registered — register it again`:"that token does not match"}async function buildCommand(positional,flags,context){const{store,write,json,now}=context,demoFence=refuseDemo(context,"build");if(demoFence!==null)return demoFence;const id=positional[0];if(id!==void 0&&store.mirrorByTask(id)!==null)return fail(write,json,"build","external-task","external work dispatches through tick/watch — the completion gate lives there",EXIT.refused);const runner=text(flags,"runner"),token=text(flags,"token"),branch=text(flags,"branch");if(id===void 0||runner===void 0||token===void 0||branch===void 0)return fail(write,json,"build","usage","`toolroll build <id> --runner <name> --token <t> --branch <b> --repo <path>`",EXIT.usage);const auth=authenticate(store,runner,token);if(!auth.ok)return fail(write,json,"build",auth.reason,describeAuth(auth.reason,runner),EXIT.refused);const repo=repoFrom(flags);if(!auth.runner.repos.includes(canonicalProject(repo)??resolve(repo)))return fail(write,json,"build","unauthorized-repo",`${runner} is not bound to ${repo} — \`runner bind\` adds it`,EXIT.refused);if(store.getTask(id)===null)return fail(write,json,"build","unknown-task",`No task ${id}.`,EXIT.refused);const pool=text(flags,"pool")??join(dirname(databasePath(process.env,homedir())),"worktrees"),ref=store.refFor(BUILT_IN,id),worktrees=new WorktreePool(store,{root:pool}),leased=await worktrees.lease({repo,branch,runner,taskRef:ref.id,now,...text(flags,"base")===void 0?{}:{base:text(flags,"base")}});if(!leased.ok)return fail(write,json,"build",leased.reason,leased.message,EXIT.refused);const held=currentClaim(store,ref.id,now),standaloneModel=text(flags,"model"),authority=store.routeAuthorityFor(ref.id,"builder",{provider:"claude",model:standaloneModel??null});if(authority!==null&&!authority.ok)return await worktrees.release(leased.worktree.path,now),fail(write,json,"build","admission-refused",`${id}: ${authority.problem}`,EXIT.refused);const standaloneMode=readAuthModeStrict(authority===null?"claude":authority.stamp.provider);if(!standaloneMode.ok)return await worktrees.release(leased.worktree.path,now),fail(write,json,"build","auth-mode",`${id}: ${standaloneMode.problem}`,EXIT.refused);const standaloneProvider=authority===null?"claude":authority.stamp.provider,standaloneHold=store.budgetGate(now)({...store.budgetSubject(ref.id),agents:[{provider:standaloneProvider,billing:standaloneMode.mode==="api-key"?"api-key":billingOf(standaloneProvider,store.handle)}]});if(standaloneHold.over!==null)return await worktrees.release(leased.worktree.path,now),fail(write,json,"build","budget",`${id}: ${budgetHoldWords(standaloneHold,monthOf(now).name)}`,EXIT.refused);let runId;try{runId=store.startRun({taskRef:ref.id,leaseId:held?.leaseId??"unclaimed",runner,branch,worktree:leased.worktree.path,...authority===null?{}:{provider:authority.stamp.provider,route:authority.stamp},...standaloneModel===void 0?{}:{model:standaloneModel},now})}catch(error){return await worktrees.release(leased.worktree.path,now),fail(write,json,"build","admission-refused",error instanceof Error?error.message:String(error),EXIT.refused)}const result=await build(store,{taskId:id,taskRef:ref.id,runner,...held===null?{}:{leaseId:held.leaseId},runnerToken:token,runId,evidenceRoot:context.evidenceRoot,worktree:leased.worktree.path,branch,now,clock:context.clock,...text(flags,"model")===void 0?{}:{model:text(flags,"model")},...text(flags,"repair-model")===void 0?{}:{repairModel:text(flags,"repair-model")},...text(flags,"turns")===void 0?{}:{maxTurns:Number(text(flags,"turns"))},...context.agentRunner===void 0?{}:{agent:context.agentRunner},...context.gitRunner===void 0?{}:{git:context.gitRunner}}),handedBack=await worktrees.release(leased.worktree.path,now),disposition=disposeBuildOutcome({store,policy:"standalone",leaseId:held?.leaseId,runId,taskId:id,taskRef:ref.id,runner,repo,branch,origin:ref.origin,provider:"claude",model:text(flags,"model")??null,worktreePath:leased.worktree.path,clock:context.clock},result);if(result.ok&&result.parked!==void 0)return disposition.kind!=="parked"?fail(write,json,"build","fenced",`${id} parked, but the lease was gone before the decision could be sealed`,EXIT.refused,{worktree:leased.worktree.path}):succeed(write,json,"build",{parked:!0,decision:disposition.decisionId,worktree:leased.worktree.path},()=>[`${id} parked a decision instead of guessing.`,` decision ${disposition.decisionId} — \`toolroll decide ${disposition.decisionId}\``,` worktree ${leased.worktree.path} (work in progress preserved)`]);if(!result.ok){const broke=result.reason==="agent"||result.reason==="agent-reported"||result.reason==="no-op"||result.reason==="no-handoff"||result.reason==="moved-head"||result.reason==="timeout"||result.reason==="git"||result.reason==="malformed-decision";return fail(write,json,"build",result.reason,result.message,broke?EXIT.failed:EXIT.refused,{worktree:leased.worktree.path})}return succeed(write,json,"build",{...result,worktree:leased.worktree.path,clean:handedBack.ok},()=>[result.committed?`Built ${id} and committed to ${branch}.`:`${id}: no change needed — the agent said so and the tree agrees.`,` worktree ${leased.worktree.path}`,"",result.summary,"","Nothing has been pushed. Look at the branch before it goes anywhere."])}function flowIoOf(context,pool,git,base){const dir=dirname(context.databaseFile);return{triggers:{gh:context.flowTriggerIo?.gh??run,fetch:context.flowTriggerIo?.fetch??fetch,dir:context.flowTriggerIo?.dir??dir,shell:context.flowTriggerIo?.shell??context.flowStepIo?.shell??run,scratch:context.flowTriggerIo?.scratch??context.flowStepIo?.scratch??join(pool,"flow-checks"),...context.flowTriggerIo?.mail===void 0?{}:{mail:context.flowTriggerIo.mail}},replies:{fetch:context.flowTriggerIo?.fetch??fetch,dir:context.flowTriggerIo?.dir??dir,...context.flowTriggerIo?.mail===void 0?{}:{mail:context.flowTriggerIo.mail}},steps:{gh:context.flowStepIo?.gh??run,git:context.flowStepIo?.git??(git===run?hardenedGit(run):git),shell:context.flowStepIo?.shell??run,fetch:context.flowStepIo?.fetch??fetch,dir:context.flowStepIo?.dir??dir,scratch:context.flowStepIo?.scratch??join(pool,"flow-checks"),base,...context.evidenceRoot===void 0?{}:{evidenceRoot:context.evidenceRoot}},...context.evidenceRoot===void 0?{}:{evidenceRoot:context.evidenceRoot},youiyouxGit:gitOf(context.gitRunner)}}async function tickCommand(flags,context){const{store,write,json,clock}=context,demoFence=refuseDemo(context,"tick");if(demoFence!==null)return demoFence;const runner=text(flags,"runner"),token=text(flags,"token");if(runner===void 0||token===void 0)return fail(write,json,"tick","usage","`toolroll tick --runner <name> --token <t> --repo <path> [--max <n>] [--base <ref>]`",EXIT.usage);const auth=heartbeatRunner(store,runner,token,clock());if(!auth.ok)return fail(write,json,"tick",auth.reason,describeAuth(auth.reason,runner),EXIT.refused);if(updateAdmissionPaused(store.raw()))return fail(write,json,"tick","updating",UPDATE_PAUSED,EXIT.refused);const maxGiven=text(flags,"max"),maxAsked=maxGiven===void 0?1:Number(maxGiven);if(!Number.isInteger(maxAsked)||maxAsked<=0)return fail(write,json,"tick","usage","--max takes a whole number of tasks",EXIT.usage);const max=flags.has("yield-builds")?0:maxAsked,buildsOnly=flags.has("builds-only"),syncAgeGiven=text(flags,"sync-max-age"),syncMaxAgeMs=syncAgeGiven===void 0?SYNC_MAX_AGE_MS:Number(syncAgeGiven)*1e3;if(!Number.isInteger(syncMaxAgeMs)||syncMaxAgeMs<=0)return fail(write,json,"tick","usage","--sync-max-age takes whole seconds",EXIT.usage);const repo=repoFrom(flags);if(!auth.runner.repos.includes(canonicalProject(repo)??resolve(repo)))return fail(write,json,"tick","unauthorized-repo",`${runner} is not bound to ${repo} — \`runner bind\` adds it`,EXIT.refused);const pool=text(flags,"pool")??join(dirname(databasePath(process.env,homedir())),"worktrees"),model=text(flags,"model"),repairModel=text(flags,"repair-model"),providerFlag=text(flags,"provider"),planModel=text(flags,"plan-model"),planProvider=text(flags,"plan-provider"),turns=text(flags,"turns"),leaseTtlMs=DEFAULT_LEASE_MS,git=context.gitRunner??run,worktrees=new WorktreePool(store,{root:pool,...context.gitRunner===void 0?{}:{runner:context.gitRunner}}),watchOwner=text(flags,"incarnation");watchOwner!==void 0&&!buildsOnly&&await runAcpChecks({store,runner,token,pool:worktrees,clock,watch:{repo:canonicalProject(repo)??resolve(repo),owner:watchOwner},progress:line=>{json||write(line)}});let base=text(flags,"base");if(base===void 0){const head=await git("git",["symbolic-ref","--short","-q","HEAD"],{cwd:repo});if(head.code!==0||head.stdout.trim()==="")return fail(write,json,"tick","git",`${repo} has no branch checked out — say --base explicitly`,EXIT.refused);base=head.stdout.trim()}await probeRepo(store,repo,runner,clock()),applyPendingAgentChanges(store,clock());const housekeeping=buildsOnly?null:await flowHousekeeping(store,repo,clock,flowIoOf(context,pool,git,base),()=>context.shouldStop?.()===!0||context.shouldPauseAdmission?.()===!0),triggerPass=housekeeping?.triggers??{added:0,checked:0,problems:[]},replyPass=housekeeping?.replies??{read:0,taken:0,problem:null},stepPass=housekeeping?.steps??{ran:0,problems:[]},flowPass=housekeeping?.flows??{moved:0,filed:[],problems:[]};if(!buildsOnly)try{sendSubagentSummaries(store,repo,clock()),sendSubagentWeeklies(store,repo,clock())}catch(error){flowPass.problems.push(`subagent summaries: ${error instanceof Error?error.message:"could not send"}`)}if(!buildsOnly&&context.shouldStop?.()!==!0)try{await runRequestedUndos(store,{},clock())}catch(error){flowPass.problems.push(`subagent undo: ${error instanceof Error?error.message:"could not run"}`)}if(!buildsOnly&&context.shouldStop?.()!==!0)try{flowPass.problems.push(...(await refreshConnections(store,[repo],clock(),context.flowStepIo?.fetch===void 0?{}:{fetcher:context.flowStepIo.fetch})).problems)}catch(error){flowPass.problems.push(`tool sign-ins: ${error instanceof Error?error.message:"could not renew"}`)}let settled=0;const settleFinished=()=>{const finished=dispatched.slice(settled).filter(one=>one.outcome!=="skipped").map(one=>one.id);if(settled=dispatched.length,finished.length===0)return;const after=moveCardsAfter(store,repo,finished,clock(),context.evidenceRoot);flowPass.moved+=after.moved,flowPass.filed.push(...after.filed),flowPass.problems.push(...after.problems)};store.sweepCeremonyNonces(clock());let budgetGate=null;const budgetHold=(taskRef,agents)=>(budgetGate??=store.budgetGate(clock()))({...store.budgetSubject(taskRef),agents}),budgetWords=hold=>budgetHoldWords(hold,monthOf(clock()).name),policyHold=agents=>{for(const agent of agents)if("profile"in agent){const verdict=store.runPolicy(agent.profile);if(!verdict.ok)return verdict.message}else{const refused=agent.session!==void 0?store.sessionPolicyRefusal(agent.provider,agent.model,agent.session):store.agentPolicyRefusal(agent.provider,agent.model);if(refused!==null)return refused}return null},ready=store.listReady(clock(),runner),considered=ready.length,dispatched=[];reconcileWalks(store,clock());const MIRROR_WORDS={"stale-mirror":"its tracker has not been synced recently — `toolroll sync` restores freshness","external-closed":"the tracker closed it — reopen it there, then `toolroll task reopen`","dispatch-revoked":"the tracker's building permission was revoked or narrowed","plane-blocked":"the tracker's plane marker could not be verified — building is paused"};for(const skippedMirror of store.ineligibleMirrors(repo,clock(),syncMaxAgeMs))dispatched.push({id:skippedMirror.taskId,outcome:"skipped",reason:skippedMirror.why}),store.enqueueNotification({source:{taskRef:store.lookupRef(skippedMirror.taskId)?.id??-1},dedupeKey:`mirror:${skippedMirror.taskId}:${skippedMirror.why}`,kind:"external-skipped",subject:`${skippedMirror.taskId} cannot dispatch`,body:MIRROR_WORDS[skippedMirror.why]??"the tracker item is not dispatchable right now"},clock());let built=0,parked=0,broke=0;const attestedThisPass=new Map;let untakenTrial=null;for(const ref of ready){if(settleFinished(),untakenTrial?.giveBack(),untakenTrial=null,built>=max)continue;if(context.shouldStop?.()===!0||context.shouldPauseAdmission?.()===!0)break;const id=ref.externalId;if(ref.repo!==null&&ref.repo!==repo){dispatched.push({id,outcome:"skipped",reason:"other-repo"});continue}const scopeApproved=scopeApprovedForDispatch(store,ref.id,clock()),wantsPlan=ref.plan==="requested"&&!scopeApproved,wantsScout=ref.deliverable==="report"&&scopeApproved;if(!wantsPlan&&!scopeApproved){dispatched.push({id,outcome:"skipped",reason:"unapproved"});continue}const agentless=agentlessFirstRun(store,ref,wantsPlan,[runner]);if(agentless!==null){dispatched.push({id,outcome:"skipped",reason:"signed-out",detail:agentless.words});continue}const taskRoute=routeOfTask(store,id,ref,clock());if(taskRoute!==null&&taskRoute.kind==="unreadable"){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:taskRoute.problem});continue}const route=taskRoute!==null&&taskRoute.kind==="route"?taskRoute:null;if(wantsPlan&&route!==null&&route.source==="proposed"){const working=store.workingPlanRouteOf(id);if(!working.ok){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:`${id}: ${working.problem}`});continue}}const planLeg=route===null?null:legOf(route.route,"plan"),fallback=route!==null&&route.source==="approved"&&!wantsPlan&&!wantsScout?dispatchEntryOf(store,ref.id,id,clock()):null;if(fallback!==null&&"problem"in fallback){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:`${id}: ${fallback.problem}`});continue}const sealedBuildLeg=route!==null&&route.source==="approved"?fallback!==null?{provider:fallback.entry.profile.provider,model:fallback.entry.profile.model,chosen:"fallback"}:legOf(route.route,"build"):null;if(wantsPlan&&planLeg!==null&&(planProvider!==void 0||planModel!==void 0||providerFlag!==void 0||model!==void 0)){const flaggedProvider=planProvider??providerFlag,flaggedModel=planModel??model;if(flaggedProvider!==void 0&&flaggedProvider!==planLeg.provider||flaggedModel!==void 0&&flaggedModel!==planLeg.model){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:`the pass flags name ${flaggedProvider??planLeg.provider}${flaggedModel===void 0?"":` · ${flaggedModel}`} but ${id}'s planner is ${planLeg.provider} · ${planLeg.model} — flags cannot reroute a task; override the plan phase with \`task route\``});continue}}const resolution=wantsPlan?planLeg!==null?resolvePhaseAgent(store,"plan",repo,{provider:planLeg.provider,model:planLeg.model}):resolvePhaseAgent(store,"plan",repo,{provider:ref.planProvider??planProvider??providerFlag,model:ref.planProvider!==null?ref.planModel??void 0:planModel??model}):sealedBuildLeg!==null?resolvePhaseAgent(store,"build",repo,{provider:sealedBuildLeg.provider,model:sealedBuildLeg.model},ref):resolvePhaseAgent(store,"build",repo,{provider:providerFlag,model},ref);if(!resolution.ok){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:resolution.problem});continue}const routedDecision=!wantsPlan&&sealedBuildLeg===null&&route===null&&store.getScope(id)?.approvedProfile==null&&resolution.source!=="pinned"&&resolution.source!=="flag"?routeWorkerModel(store,{taskKind:ref.sizing?.size==="small"?"simple-fix":"multi-file-build",provider:resolution.spec.provider,fallbackModel:resolution.spec.model,now:clock()}):null,spec=routedDecision!==null&&routedDecision.steppedDown?{provider:resolution.spec.provider,model:routedDecision.model}:resolution.spec,brokenMode=readAuthModeStrict(spec.provider);if(!brokenMode.ok){dispatched.push({id,outcome:"skipped",reason:"auth-mode",detail:brokenMode.problem});continue}const gate=signInGate(store,[spec.provider],clock(),ref.id);if(gate.waiting!==null){dispatched.push({id,outcome:"skipped",reason:"signed-out",detail:signInWords(gate.waiting)});continue}untakenTrial=gate;const governingLeg=wantsPlan?planLeg:sealedBuildLeg;if(governingLeg!==null&&(spec.provider!==governingLeg.provider||spec.model!==governingLeg.model)){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:`${id}: the ${wantsPlan?"plan":"build"} leg names ${governingLeg.provider} · ${governingLeg.model} but resolution produced ${spec.provider} · ${spec.model??"(no model)"} — nothing substitutes`});continue}const routeStamp=phase=>{if(governingLeg===null||route===null||phase==="plan"&&route.source==="live"){const legacy=store.routeAuthorityFor(ref.id,phase==="plan"?"planner":"builder",{provider:spec.provider,model:spec.model});return legacy!==null&&legacy.ok?legacy.stamp:null}return{routeDigest:routeDigestOf(route.route),phase,provider:spec.provider,model:spec.model,chosen:governingLeg.chosen}};if(!wantsPlan&&!wantsScout&&route===null){const legacyStamp=routeStamp("build");if(legacyStamp!==null&&(legacyStamp.provider!==spec.provider||legacyStamp.model!==spec.model)){const message=`${id}: the sealed profile builds on ${legacyStamp.provider} · ${legacyStamp.model??"(no model)"} but today's routing resolved ${spec.provider} · ${spec.model??"(no model)"} — nothing runs on it (stale-approval)`;holdStaleApproval(store,{taskRef:ref.id,taskId:id,message},clock()),dispatched.push({id,outcome:"skipped",reason:"stale-approval",detail:message});continue}}if(!wantsPlan&&!wantsScout){const ruleHeld=ruleHoldOf(store,id);if(ruleHeld!==null){holdRuleOff(store,ref.id,ruleHeld.model,clock()),dispatched.push({id,outcome:"skipped",reason:"rule-switched-off",detail:`${id}: results for ${ruleHeld.model} dropped after this was approved — approve it again or re-file it`});continue}}{const unavailable=store.runnerReadinessOf(runner,spec.provider);if(unavailable!==null&&readinessRefuses(unavailable,fallback?.entry.authMode??(brokenMode.ok?brokenMode.mode:"subscription"))){const observed=`${unavailable.provider} is reported unavailable on ${runner} (${unavailable.reason}; observed ${unavailable.observedAt})`;dispatched.push({id,outcome:"skipped",reason:"provider-unavailable",detail:`${observed} — nothing substitutes for a routed provider: override the phase with \`task route\` or restore the provider and report readiness again`});continue}}const skipProviders=wantsPlan||fallback!==null?[spec.provider]:[store.getScope(id)?.approvedProfile?.provider].filter(one=>one!=null);let unattestedLane=null;for(const candidate of new Set(skipProviders)){if(isAcpProvider(candidate)){const checked=store.acpAttestationFor(candidate,runner),verified=checked===null?null:verifyLaunch(checked.launch);if(checked===null){unattestedLane=`${ACP_AGENTS[candidate].name} isn't checked on ${runner} — run \`toolroll agents check ${candidate}\` there`;break}if(verified!==null&&!verified.ok){unattestedLane=verified.problem;break}continue}if(attestationOf(candidate)===null)continue;let verdict=attestedThisPass.get(candidate);if(verdict===void 0&&(verdict=await attestProvider(candidate,inspectionOf(candidate).binary),attestedThisPass.set(candidate,verdict)),verdict!==null&&!verdict.ok){unattestedLane=verdict.problem;break}}if(unattestedLane!==null){dispatched.push({id,outcome:"skipped",reason:"provider-unattested",detail:unattestedLane});continue}{const sealed=wantsPlan||wantsScout?null:fallback?.entry.profile??store.getScope(id)?.approvedProfile??null,refused=policyHold([sealed!==null?{profile:sealed}:{provider:spec.provider,model:spec.model,...wantsPlan?{session:"planning"}:wantsScout?{session:"scouting"}:{}}]);if(refused!==null){dispatched.push({id,outcome:"skipped",reason:"policy",detail:refused});continue}}const sealedModel=store.getScope(id)?.approvedProfile?.model??null,budgeted=budgetHold(ref.id,fallback?.paid===!0?[{provider:spec.provider,billing:"api-key"}]:[...new Set([spec.provider,...skipProviders])].map(provider=>isAcpProvider(provider)||provider==="pi"?store.agentFor(provider,provider===spec.provider?spec.model??sealedModel:sealedModel,runner):store.agentsFor([provider])[0]));if(budgeted.over!==null){dispatched.push({id,outcome:"skipped",reason:"budget",detail:budgetWords(budgeted)});continue}if(!wantsPlan&&runningReleaseCheck(store,clock(),ref.id)!==null){dispatched.push({id,outcome:"skipped",reason:"release-check",detail:RELEASE_CHECK_WAIT});continue}if(repo!==null){const railed=store.reserveModeRail(repo,1,clock());if(!railed.ok){dispatched.push({id,outcome:"skipped",reason:railed.rail,detail:railed.detail});continue}}const claimed=acquireIfReady(store,ref.id,runner,{...wantsPlan?{dispatchRole:"planner"}:wantsScout?{dispatchRole:"scout"}:{},now:clock(),token,ttlMs:leaseTtlMs,syncMaxAgeMs,repo,provider:spec.provider,...spec.model===null?{}:{model:spec.model},...fallback!==null?{authMode:fallback.entry.authMode}:brokenMode.ok&&(brokenMode.mode==="api-key"||brokenMode.mode==="subscription")?{authMode:brokenMode.mode}:{},...text(flags,"incarnation")===void 0?{}:{incarnation:text(flags,"incarnation")}});if(claimed.ok&&(untakenTrial=null),!claimed.ok){if(claimed.reason==="capability"&&"message"in claimed){const key=/needs (\S+)/.exec(claimed.message)?.[1],parsed=key===void 0?null:parseCapabilityKey(key);if(parsed!==null){const home=ref.repo??repo;store.enqueueNotification({source:{taskRef:ref.id},dedupeKey:`gap:${home}:${parsed.kind}:${parsed.name}`,kind:"gap",pushClass:"attention",link:"/caps",subject:`${key} blocks work in ${home}`,body:`${id} (and possibly others) cannot dispatch: ${claimed.message}. \`toolroll gaps --repo ${home}\``},clock())}}dispatched.push({id,outcome:"skipped",reason:claimed.reason,..."message"in claimed&&claimed.reason==="capability"?{detail:claimed.message}:{}});continue}const lease=claimed.claim.leaseId;if(wantsPlan){const answers=store.answeredDecisionsFor(id).map(one=>({question:one.question,choice:one.choice??"",note:one.note})),sourced=plannerSourceOf(store,context.evidenceRoot,id,answers);if(!sourced.ok){release(store,lease,clock()),dispatched.push({id,outcome:"skipped",reason:`planner-source-${sourced.reason}`,detail:sourced.message});continue}const planBranch=await existingOrFirst([`toolroll-plan/${id}`,`standing-orders-plan/${id}`],async one=>(await git("git",["rev-parse","--verify","--quiet",`refs/heads/${one}`],{cwd:repo})).code===0),revised=ref.revisionOf===null?null:revisionSourceHead(store,context.evidenceRoot,ref.id,ref.revisionOf);if(revised!==null&&!revised.ok){release(store,lease,clock()),dispatched.push({id,outcome:"skipped",reason:"revision-brief",detail:revised.problem});continue}const planLeased=await worktrees.lease({repo,branch:planBranch,runner,taskRef:ref.id,now:clock(),base:revised?.head??base,reuseBranch:!0,reclaim:{evidenceRoot:context.evidenceRoot},...freshBaseFor(store,id,planBranch,base)});if(!planLeased.ok){release(store,lease,clock()),dispatched.push({id,outcome:"failed",reason:planLeased.reason}),broke++;continue}const planStamp=routeStamp("plan"),planRunId=store.startRun({taskRef:ref.id,leaseId:lease,runner,role:"planner",provider:spec.provider,branch:planBranch,worktree:planLeased.worktree.path,...spec.model===null?{}:{model:spec.model},now:clock(),...planStamp===null?{}:{route:planStamp}});noteBaseStanding(store,planRunId,planLeased.base,base,clock());let sourceArtifact;try{sourceArtifact=storeEvidence(store,context.evidenceRoot,planRunId,"plan-contract","planner-source.json",encodePlannerSource(sourced.source),`planner source ${sourced.source.sourceDigest.slice(0,12)} — the filed request quoted into the brief, recorded before spend (${sourced.bytes} bytes)`,clock(),{captureStatus:"ok"})}catch(error){await worktrees.release(planLeased.worktree.path,clock());const unrecorded=finalize(store,lease,{kind:"plan-failure",runId:planRunId,taskId:id,failure:"failure",message:`the planner's source could not be recorded: ${error instanceof Error?error.message:String(error)}`,now:clock()});dispatched.push({id,outcome:"failed",reason:"evidence"}),unrecorded.ok||release(store,lease,clock()),broke++;continue}store.stampRun(planRunId,{scopeDigest:sourced.source.contract.scope?.digest??""}),budgetGate=null;const outcome=await planTask(store,{...budgeted.remainingMicrousd===null?{}:{maxBudgetUsd:Math.max(1,budgeted.remainingMicrousd)/1e6},taskId:id,taskTitle:store.getTask(id)?.title??id,taskRef:ref.id,runner,leaseId:lease,runnerToken:token,runId:planRunId,worktree:planLeased.worktree.path,branch:planBranch,now:clock(),clock,onProviderSpawn:pid=>{worktrees.recordProviderOccupancy(planLeased.worktree.path,runner,pid,planLeased.worktree.leaseEpoch)},evidenceRoot:context.evidenceRoot,answers,source:sourced.source,provider:spec.provider,...spec.model===null?{}:{model:spec.model},...context.agentRunner===void 0?{}:{agent:context.agentRunner},...context.gitRunner===void 0?{}:{git:context.gitRunner}});if(await worktrees.release(planLeased.worktree.path,clock()),outcome.ok&&"parked"in outcome){const sealed=finalize(store,lease,{kind:"park",runId:planRunId,taskId:id,decision:outcome.parked.decision,artifactIds:outcome.parked.artifactIds,repairRunId:outcome.parked.repairRunId,now:clock()});sealed.ok?(store.resetPlanStrikes(ref.id),dispatched.push({id,outcome:"parked",reason:`decision:${sealed.decisionId}`}),parked++):sealed.reason==="stopped"?dispatched.push({id,outcome:"stopped",reason:`stop:${planRunId}`}):(dispatched.push({id,outcome:"failed",reason:"fenced"}),broke++);continue}if(outcome.ok){const sealed=finalize(store,lease,{kind:"plan",runId:planRunId,taskId:id,plan:outcome.drafted.plan,artifact:outcome.drafted.artifact,repairRunId:outcome.drafted.repairRunId,source:sourced.source,sourceArtifact,evidenceRoot:context.evidenceRoot,now:clock()});sealed.ok?(store.clearQuota(runner,spec.provider,spec.model??""),dispatched.push({id,outcome:"planned",...sealed.changes===0?{}:{detail:`${sealed.changes} contract change${sealed.changes===1?"":"s"} proposed${sealed.amendment===null?"":" with an amendment"}`}})):sealed.reason==="stale-source"||sealed.reason==="source-invalid"?dispatched.push({id,outcome:"skipped",reason:sealed.reason,detail:sealed.detail}):sealed.reason==="stopped"?dispatched.push({id,outcome:"stopped",reason:`stop:${planRunId}`}):(dispatched.push({id,outcome:"failed",reason:"fenced"}),broke++);continue}const sealedFailure=finalize(store,lease,{kind:"plan-failure",runId:planRunId,taskId:id,failure:outcome.kind,...outcome.kind==="malformed"?{malformed:outcome.reason==="malformed-decision"?"decision":"plan"}:{},message:outcome.message,code:outcome.reason,...outcome.kind==="malformed"&&outcome.problems!==void 0?{problems:outcome.problems.map(problem=>problem.message)}:{},...outcome.agentSaid===void 0?{}:{agentSaid:outcome.agentSaid},now:clock()});if(!sealedFailure.ok&&sealedFailure.reason==="stopped"){dispatched.push({id,outcome:"stopped",reason:`stop:${planRunId}`});continue}dispatched.push({id,outcome:"failed",reason:outcome.reason}),sealedFailure.ok||release(store,lease,clock()),broke++;continue}if(wantsScout){const scoutBranch=`toolroll-scout/${id}/${randomBytes(4).toString("hex")}`,scopeRow=store.getScope(id),proof=proveApprovedProfile(scopeRow,{provider:spec.provider,model:spec.model??void 0,maxTurns:void 0,timeoutMs:void 0,skipPermissions:!1});if(!proof.ok){release(store,lease,clock()),dispatched.push({id,outcome:"skipped",reason:"stale-approval",detail:proof.message});continue}const scoutLeased=await worktrees.lease({repo,branch:scoutBranch,runner,taskRef:ref.id,now:clock(),base});if(!scoutLeased.ok){release(store,lease,clock()),dispatched.push({id,outcome:"failed",reason:scoutLeased.reason}),broke++;continue}const scoutStamp=routeStamp("build")??{routeDigest:`profile:${profileDigestOf(proof.effective.profile)}`,phase:"build",provider:spec.provider,model:proof.effective.model,chosen:"legacy"},scoutRunId=store.startRun({taskRef:ref.id,leaseId:lease,runner,role:"scout",provider:spec.provider,branch:scoutBranch,worktree:scoutLeased.worktree.path,model:proof.effective.model,now:clock(),route:scoutStamp});store.stampRun(scoutRunId,{scopeDigest:scopeRow?.approvedDigest??"",profileDigest:profileDigestOf(proof.effective.profile)});const scoutAnswers=store.answeredDecisionsFor(id,6).map(one=>({question:one.question,choice:one.choice??"",note:one.note}));budgetGate=null;const scouted=await scoutTask(store,{...budgeted.remainingMicrousd===null?{}:{maxBudgetUsd:Math.max(1,budgeted.remainingMicrousd)/1e6},taskId:id,taskTitle:store.getTask(id)?.title??id,goal:scopeRow?.goal??"",outOfScope:scopeRow?.outOfScope??null,taskRef:ref.id,runner,leaseId:lease,runnerToken:token,runId:scoutRunId,worktree:scoutLeased.worktree.path,branch:scoutBranch,now:clock(),clock,onProviderSpawn:pid=>{worktrees.recordProviderOccupancy(scoutLeased.worktree.path,runner,pid,scoutLeased.worktree.leaseEpoch)},evidenceRoot:context.evidenceRoot,answers:scoutAnswers,demoUrl:projectDemoUrl(context.databaseFile,repo),provider:spec.provider,model:proof.effective.model,...proof.effective.maxTurns===void 0?{}:{maxTurns:proof.effective.maxTurns},timeoutMs:proof.effective.timeoutMs,...context.agentRunner===void 0?{}:{agent:context.agentRunner},...context.gitRunner===void 0?{}:{git:context.gitRunner}});await worktrees.release(scoutLeased.worktree.path,clock());const discarded=await worktrees.discard(scoutLeased.worktree.path,clock()),leftover=discarded.ok?{}:{detail:`checkout kept: ${discarded.message}`};if(scouted.ok&&"parked"in scouted){const sealed=finalize(store,lease,{kind:"park",runId:scoutRunId,taskId:id,decision:scouted.parked.decision,artifactIds:scouted.parked.artifactIds,now:clock()});sealed.ok?(dispatched.push({id,outcome:"parked",reason:`decision:${sealed.decisionId}`,...leftover}),parked++):(dispatched.push({id,outcome:"failed",reason:"fenced",...leftover}),broke++);continue}if(scouted.ok){const sealed=finalize(store,lease,{kind:"scout",runId:scoutRunId,taskId:id,report:scouted.reported.report,artifact:scouted.reported.artifact,now:clock()});sealed.ok?(store.clearQuota(runner,spec.provider,spec.model??""),dispatched.push({id,outcome:"reported",...leftover})):sealed.reason==="stopped"?dispatched.push({id,outcome:"stopped",reason:`stop:${scoutRunId}`,...leftover}):(dispatched.push({id,outcome:"failed",reason:"fenced",...leftover}),broke++);continue}const sealedFailure=finalize(store,lease,{kind:"scout-failure",runId:scoutRunId,taskId:id,failure:scouted.kind,...scouted.kind==="malformed"?{malformed:scouted.reason==="malformed-decision"?"decision":"report"}:{},message:scouted.message,now:clock()});if(!sealedFailure.ok&&sealedFailure.reason==="stopped"){dispatched.push({id,outcome:"stopped",reason:`stop:${scoutRunId}`,...leftover});continue}dispatched.push({id,outcome:"failed",reason:scouted.reason,...leftover}),sealedFailure.ok||release(store,lease,clock()),broke++;continue}const branch=await existingOrFirst(taskBranches(id),async one=>(await git("git",["rev-parse","--verify","--quiet",`refs/heads/${one}`],{cwd:repo})).code===0),exists=await git("git",["rev-parse","--verify","--quiet",`refs/heads/${branch}`],{cwd:repo});let buildBase=base,caughtUp=null;if(ref.revisionOf!==null){const source=revisionSourceHead(store,context.evidenceRoot,ref.id,ref.revisionOf);let problem=source.ok?null:source.problem;if(source.ok)if(exists.code!==0&&text(flags,"base")===void 0){if(buildBase=source.head,!publishesThroughPullRequests(store,repo)){const onto=landingBranchOf(store,repo,base),result2=await catchUpRevision(hardenedGit(git,"build",{repo}),repo,source.head,onto,id,clock());caughtUp={head:source.head,onto,result:result2},result2.kind==="merged"&&(buildBase=result2.commit)}}else{const descendant=exists.code===0?branch:base,ancestry=await lazyFetchSafeGit(git)("git",[...noLazyFetch(),"-c","protocol.allow=never","--no-replace-objects","merge-base","--is-ancestor",source.head,descendant],{cwd:repo});if(ancestry.code!==0)problem=ancestry.stderr.includes(PARTIAL_CLONE_REFUSAL)?PARTIAL_CLONE_REFUSAL:"the requested revision base does not contain its source head";else if(exists.code===0&&store.latestBranchBaseMove(ref.id,branch)===null&&store.firstBuilderBase(ref.id,branch)===null&&!publishesThroughPullRequests(store,repo)){const tip=exists.stdout.trim(),main=await catchUpMergeOf(hardenedGit(git,"build",{repo}),repo,tip,source.head,landingBranchOf(store,repo,base));main!==null&&store.recordBranchBaseMove(ref.id,branch,tip,main,clock())}}if(problem!==null){release(store,lease,clock()),dispatched.push({id,outcome:"skipped",reason:"revision-brief",detail:problem});continue}}const leased=await worktrees.lease({repo,branch,runner,taskRef:ref.id,now:clock(),...exists.code===0?{}:{base:buildBase},reclaim:{evidenceRoot:context.evidenceRoot},...exists.code===0?freshBaseFor(store,id,branch,base):{}});if(caughtUp!==null&&caughtUp.result.kind==="merged"){const merged=caughtUp.result,at=leased.ok&&leased.created?await hardenedGit(git,"build",{repo})("git",["rev-parse","--verify","-q",`refs/heads/${branch}^{commit}`],{cwd:repo}):null;if(at!==null&&at.code===0&&at.stdout.trim()===merged.commit)store.recordBranchBaseMove(ref.id,branch,merged.commit,merged.main,clock());else if(leased.ok&&leased.created){await worktrees.release(leased.worktree.path,clock()),release(store,lease,clock()),dispatched.push({id,outcome:"failed",reason:"git",detail:"Toolroll couldn't confirm the new branch stands at its merge of main; it tries again."}),broke++;continue}else caughtUp={...caughtUp,result:{kind:"unavailable"}}}if(!leased.ok){release(store,lease,clock()),dispatched.push({id,outcome:"failed",reason:leased.reason}),broke++;continue}const buildStamp=routeStamp("build");let runId;try{if(leased.resumedFromRun!==void 0){if(buildStamp===null)throw new Error(`${id}: the recovered attempt presents no build authority`);const admittedRecovered=store.admitRecoveredBuilder({taskRef:ref.id,leaseId:lease,runner,branch,worktree:leased.worktree.path,provider:spec.provider,...spec.model===null?{}:{model:spec.model},recoveredFrom:leased.resumedFromRun,now:clock(),route:buildStamp});if(!admittedRecovered.ok)throw new Error(admittedRecovered.problem);runId=admittedRecovered.runId}else runId=store.startRun({taskRef:ref.id,leaseId:lease,runner,branch,worktree:leased.worktree.path,provider:spec.provider,...spec.model===null?{}:{model:spec.model},now:clock(),...buildStamp===null?{}:{route:buildStamp}})}catch(error){await worktrees.release(leased.worktree.path,clock()),release(store,lease,clock()),dispatched.push({id,outcome:"skipped",reason:"admission-refused",detail:error instanceof Error?error.message:String(error)});continue}noteBaseStanding(store,runId,leased.base,base,clock()),caughtUp!==null&&leased.created&&recordCatchUp(store,{repo,taskId:id,runId,branch,head:caughtUp.head,onto:caughtUp.onto},caughtUp.result,clock()),leased.resumedFromRun!==void 0&&store.addRunNote(runId,"Toolroll",`Recovered the ${leased.recoveryKind==="completed"?"completed source draft":"work-in-progress draft"} from interrupted attempt #${leased.resumedFromRun}. This fresh attempt is reviewing and verifying it; the safety patch is retained.`,clock());const scopeBudget=store.getScope(id)?.budgetMicrousd??null,backstop=store.getSpendDefaults()?.buildPerRunMicrousd??null,budgetLeft=budgeted.remainingMicrousd!==null&&MONEY_CAPABILITIES[spec.provider].nativeDollarCapFlag!==null?Math.max(1,budgeted.remainingMicrousd):null,capMicrousd=[scopeBudget,backstop,budgetLeft].reduce((least,one)=>one===null?least:least===null?one:Math.min(least,one),null);if(capMicrousd!==null&&MONEY_CAPABILITIES[spec.provider].nativeDollarCapFlag===null){store.finishRun(runId,{outcome:"refused",reason:"budget-unenforceable",now:clock()}),release(store,lease,clock()),await worktrees.release(leased.worktree.path,clock()),dispatched.push({id,outcome:"skipped",reason:"budget-unenforceable"});continue}budgetGate=null;const result=await build(store,{taskId:id,taskRef:ref.id,runner,leaseId:lease,runnerToken:token,runId,evidenceRoot:context.evidenceRoot,worktree:leased.worktree.path,branch,now:clock(),clock,...capMicrousd===null?{}:{maxBudgetUsd:capMicrousd/1e6},onProviderSpawn:pid=>{worktrees.recordProviderOccupancy(leased.worktree.path,runner,pid,leased.worktree.leaseEpoch)},provider:spec.provider,...spec.model===null?{}:{model:spec.model},...repairModel===void 0?{}:{repairModel},...turns===void 0?{}:{maxTurns:Number(turns)},...context.agentRunner===void 0?{}:{agent:context.agentRunner},...context.gitRunner===void 0?{}:{git:context.gitRunner},...context.shouldStop===void 0?{}:{shouldStop:context.shouldStop},...leased.resumedFromRun===void 0?{}:{recoveredDraftRun:leased.resumedFromRun},...leased.recoveryKind===void 0?{}:{recoveredDraftKind:leased.recoveryKind}});await worktrees.release(leased.worktree.path,clock());const disposition=disposeBuildOutcome({store,policy:"tick",leaseId:lease,runId,taskId:id,taskRef:ref.id,runner,repo,branch,origin:ref.origin,provider:spec.provider,model:spec.model,worktreePath:leased.worktree.path,evidenceRoot:context.evidenceRoot,clock},result);switch(disposition.kind){case"parked":dispatched.push({id,outcome:"parked",reason:`decision:${disposition.decisionId}`,worktree:leased.worktree.path}),parked++;break;case"park-fenced":dispatched.push({id,outcome:"failed",reason:"fenced",worktree:leased.worktree.path}),broke++;break;case"disowned":dispatched.push({id,outcome:"failed",reason:"external-closed",branch,worktree:leased.worktree.path}),broke++;break;case"built":dispatched.push({id,outcome:"built",committed:disposition.committed,branch,worktree:leased.worktree.path}),built++;break;case"built-fenced":dispatched.push({id,outcome:"failed",reason:"fenced",branch,worktree:leased.worktree.path}),broke++;break;case"skipped":dispatched.push({id,outcome:"skipped",reason:disposition.reason});break;case"fenced":dispatched.push({id,outcome:"failed",reason:"fenced",worktree:leased.worktree.path}),broke++;break;case"malformed":dispatched.push({id,outcome:"failed",reason:disposition.sealed?"malformed-decision":"fenced",worktree:leased.worktree.path}),broke++;break;case"failed":dispatched.push({id,outcome:"failed",reason:disposition.sealed?disposition.disposition==="auth-expired"?"auth-expired — requeued, sign-in needed":disposition.disposition==="fallback"?"out of plan — moved to the next approved agent":`${disposition.failureClass}${disposition.disposition==="backoff"?` — retry ${disposition.strikes}/3`:disposition.disposition==="stalled"?" — stalled":disposition.closedState!==null?` — the task was already ${disposition.closedState}, so it stays ${disposition.closedState}`:""}`:"fenced",...result.ok?{}:{detail:result.message.slice(0,200)},worktree:leased.worktree.path}),disposition.sealed&&disposition.disposition==="fallback"||broke++;break;case"recorded":break;case"stopped":dispatched.push({id,outcome:"stopped",reason:`stop:${disposition.stopRun}`,branch,worktree:leased.worktree.path});break;case"handed-back":dispatched.push({id,outcome:"stopped",reason:"service-stop",detail:result.ok?"":result.message.slice(0,200),branch,worktree:leased.worktree.path});break;case"invariant":dispatched.push({id,outcome:"failed",reason:disposition.reason}),broke++;break}}if(untakenTrial?.giveBack(),!buildsOnly&&authenticate(store,runner,token).ok){const reviewed=await buildReviewPass(store,{runner,token,repos:auth.runner.repos,clock,root:context.evidenceRoot,...text(flags,"incarnation")===void 0?{}:{watchIncarnation:text(flags,"incarnation")},...context.agentRunner===void 0?{}:{agent:context.agentRunner},shouldStop:()=>context.shouldStop?.()===!0||context.shouldPauseAdmission?.()===!0});for(const one of reviewed)dispatched.push({id:`review of run ${one.run}`,outcome:one.outcome==="not-reviewed"?"not-reviewed":"reviewed",reason:one.detail})}buildsOnly||syncAssignmentHandoffs(store,clock(),auth.runner.repos,context.evidenceRoot),settleFinished();const replied=replyPass.taken>0||replyPass.problem!==null,requestPass=housekeeping?.youiyoux??NO_YOUIYOUX_PASS,requested=requestPass.filed+requestPass.copied+requestPass.decided+requestPass.problems.length>0,flows=flowPass.moved+flowPass.filed.length+flowPass.problems.length+triggerPass.added+triggerPass.problems.length+stepPass.ran+stepPass.problems.length===0&&!replied&&!requested?{}:{flows:{...flowPass,...triggerPass.added+triggerPass.problems.length===0?{}:{triggers:triggerPass},...requested?{youiyoux:requestPass}:{},...stepPass.ran+stepPass.problems.length===0?{}:{steps:stepPass},...replied?{replies:replyPass}:{}}},summary=()=>{const lines=[`Considered ${considered}, built ${built}, parked ${parked}, broke ${broke}.`];for(const entry of dispatched){const detail=entry.outcome==="built"?entry.committed===!0?`committed to ${entry.branch}`:"no changes reported; see the result's proof status":entry.outcome==="parked"?`${entry.reason} — \`toolroll decide\``:entry.reason??"";lines.push(` ${entry.id.padEnd(24)} ${entry.outcome} ${detail}`.trimEnd())}return built>0&&lines.push("","Nothing has been pushed. Look at the branches before they go anywhere."),parked>0&&lines.push("",`${parked} decision${parked===1?"":"s"} waiting — \`toolroll decide\`, or \`toolroll brief\`.`),lines};return broke>0?fail(write,json,"tick","build-failed",`${broke} of ${dispatched.length} dispatched tasks broke`,EXIT.failed,{considered,dispatched}):built>0||parked>0||dispatched.some(one=>one.outcome==="planned"||one.outcome==="reported"||one.outcome==="reviewed"||one.outcome==="not-reviewed")?succeed(write,json,"tick",{considered,dispatched,...flows},summary):considered===0?fail(write,json,"tick","empty","nothing is ready",EXIT.refused,{considered,dispatched,...flows}):fail(write,json,"tick","nothing-dispatched","everything ready is waiting on a person or held by somebody else",EXIT.refused,{considered,dispatched,...flows})}async function reconcileCommand(flags,context){const{store,write,json,clock}=context,demoFence=refuseDemo(context,"reconcile");if(demoFence!==null)return demoFence;const repo=repoFrom(flags),pool=text(flags,"pool")??join(dirname(databasePath(process.env,homedir())),"worktrees"),syncReports=[];for(const dispatchGrant of store.listGrants().filter(one=>one.dispatch===!0&&one.remoteRepo!=null&&one.repo===repo))syncReports.push(await syncPass(store,dispatchGrant,context.dispatchAdapter??ghDispatchAdapter(),clock));for(const report of syncReports)report.outcome==="failed"||report.outcome==="blocked"?store.enqueueEpisode(`sync:${report.remoteRepo}`,{source:{project:repo},kind:"sync-failed",pushClass:"attention",link:"/system",subject:`syncing ${report.remoteRepo} ${report.outcome==="blocked"?"is blocked":"failed"}`,body:`${report.detail??"the pass did not finish"} — external work keeps its last verified state and stops dispatching past its freshness window.`},clock().toISOString(),clock()):store.resolveEpisodes(`sync:${report.remoteRepo}`,clock());const recovered=recoverDead(store,clock()),closedRuns=await closeOutRuns(store,clock,{repo});store.recordFinishedRunExits(clock()),store.settleUnspawnedWitnesses(clock()),await proveFinishedRunsStopped(store,clock),store.settleQuiescentStops(clock()),applyPendingAgentChanges(store,clock()),retryVanishedWhenStopped(store,clock()),expireFastStarts(store,clock()),routeLegacyPlans(store,clock());try{releaseStalledUpdate(dirname(context.databaseFile),clock())}catch{}for(const one of recovered){for(const leaseId of one.claims)store.enqueueNotification({source:{taskRef:Number(store.handle.prepare("SELECT task_ref FROM claim WHERE lease_id = ?").get(leaseId)?.task_ref??-1)},dedupeKey:`recover:${leaseId}`,kind:"runner-recovered",subject:`${one.runner} went dead holding work`,body:`Its claims were requeued and its worktrees handed back unverified. Lease ${leaseId}.`},clock());for(const runId of one.runs)store.enqueueNotification({source:{run:runId},dedupeKey:`recover-run:${runId}`,kind:"runner-recovered",subject:`${one.runner} went dead mid-attempt`,body:`Run #${runId} was still open with no live lease; it is now finished as interrupted. Check this task's current state in the console.`,link:`/r/${runId}`},clock())}const reaped=reap(store,clock()),liveSwept=sweepLiveLogs(store,context.evidenceRoot,clock());try{store.sweepRunActivity(clock(),LIVE_RETAIN_MS,LIVE_FILE_BOUND)}catch{}const worktrees=new WorktreePool(store,{root:pool,...context.gitRunner===void 0?{}:{runner:context.gitRunner}}),adoption=await worktrees.adopt(repo,clock());if(adoption.ok){const now=clock(),notice=worktreeAdoptionNotice(repo,adoption.adopted,now);notice!==null&&store.enqueueNotification(notice,now)}if(!adoption.ok)return fail(write,json,"reconcile","git",adoption.message,EXIT.failed,{recovered,reaped:reaped.map(claim=>claim.leaseId)});let landed={completed:[],steps:[]};const remotes=new RemoteMains(store,context.gitRunner,context.evidenceRoot);try{landed=await reconcileLanded(store,worktrees,gitOf(context.gitRunner),remotes,repo,context.evidenceRoot,clock)}catch{}finally{remotes.close()}const landedGone=landed.steps.filter(one=>one.outcome==="removed");let tidied=[];try{tidied=runTidy(store,clock(),releaseFactsFor(context.databaseFile),TIDY_PASS_LIMIT,{principal:"operator",repos:[repo],includeUnplaced:!1})}catch{}try{reevaluateResultRecords(store,canonicalProject(repo)??resolve(repo),context.evidenceRoot,clock())}catch{}try{routeRulesPass(store,canonicalProject(repo)??resolve(repo),clock())}catch{}const closedCheckouts=await closeOutCheckouts(store,clock,finishedCheckouts(store,clock(),repo)),pruned=await cleanCheckouts(store,worktrees,clock,{manual:!1,actor:"worker",repo}),slimmed=await slimKeptCheckouts(store,worktrees,clock,{actor:"worker",repo});let retention=null;try{retention=dailyRetention(store,context.evidenceRoot,clock())}catch{retention=null}const retained=retention===null?[]:retention.counts.filter(one=>one.count>0);let storageSwept=null;if(context.sweepOwner!==void 0)try{storageSwept=idleStorageSweep(store,{databaseFile:context.databaseFile,pool:worktrees,tempRoots:context.tempRoots??tempRoots(),owner:context.sweepOwner},clock)}catch{storageSwept=null}const swept=storageSwept===null?[]:storageSwept.parts.filter(one=>one.count>0),nothing=retained.length===0&&swept.length===0&&recovered.length===0&&reaped.length===0&&adoption.adopted.length===0&&adoption.forgotten.length===0&&pruned.removed.length===0&&closedRuns.length===0&&closedCheckouts.length===0&&slimmed.slimmed.length===0&&landed.completed.length===0&&landedGone.length===0&&tidied.length===0&&liveSwept.removed.length===0;return succeed(write,json,"reconcile",{recovered,reaped:reaped.map(claim=>claim.leaseId),adopted:adoption.adopted,forgotten:adoption.forgotten,checkoutsRemoved:pruned.removed.map(one=>one.path),checkoutsKept:pruned.kept,processesStopped:[...closedRuns.map(one=>({run:one.runId,pids:one.done.stopped.map(row=>row.pid)})),...closedCheckouts.map(one=>({checkout:one.path,pids:one.done.stopped.map(row=>row.pid)}))],checkoutsSlimmed:slimmed.slimmed.map(one=>one.path),landed:{completed:landed.completed,steps:landed.steps},tidied:tidied.map(one=>({id:one.taskId,rule:one.rule,reason:one.reason})),liveViewsSwept:liveSwept.removed.length,retention:retention===null?null:{counts:retention.counts,freedBytes:retention.freed},storageSweep:storageSwept},()=>nothing?["Nothing to reconcile. Everything is where it should be."]:[...recovered.map(one=>`Recovered ${one.runner}: ${one.claims.length} claim(s) requeued, ${one.worktrees.length} worktree(s) handed back unverified.`),...reaped.length===0?[]:[`Reaped ${reaped.length} expired lease(s).`],...adoption.adopted.map(path=>`Adopted ${path} — released, unverified, somebody should look.`),...adoption.forgotten.map(path=>`Forgot ${path} — its directory is gone.`),...pruned.removed.length===0?[]:[`Removed ${pruned.removed.length} finished task checkout(s), about ${bytesWords(pruned.freed)}; their branches stay.`],...closedRuns.map(one=>`Run #${one.runId} ended; stopped ${stoppedWords(one.done)}.`),...closedCheckouts.map(one=>`${one.path}: its task finished; stopped ${stoppedWords(one.done)}.`),...landed.completed.length===0?[]:[`Marked ${landed.completed.length} landed result(s) complete: ${landed.completed.join(", ")}.`],...tidied.length===0?[]:[`Put away ${tidied.length} old task(s): ${tidied.map(one=>one.taskId).join(", ")}.`],...landedGone.length===0?[]:[`Removed landed work: ${landedGone.filter(one=>one.kind==="checkout").length} checkout(s), ${landedGone.filter(one=>one.kind==="branch").length} local branch(es).`],...slimmed.slimmed.length===0?[]:[`Dropped dependencies and build output from ${slimmed.slimmed.length} kept checkout(s), about ${bytesWords(slimmed.slimmed.reduce((sum,one)=>sum+one.bytes,0))}.`],...liveSwept.removed.length===0?[]:[`Cleared ${liveSwept.removed.length} finished live view(s).`],...retention===null||retained.length===0?[]:[`Retention removed ${sweepWords(retention.counts,retention.freed)}.`],...storageSwept===null||swept.length===0?[]:[`Storage sweep: ${storageSweepWords(storageSwept.parts)}`]])}function gapsCommand(flags,context){const{store,write,json,clock}=context,repo=repoFrom(flags),gaps=computeGaps(store,repo,clock());if(json)return write(envelopeJson({ok:!0,command:"gaps",repo,gaps})),gaps.length===0?EXIT.ok:EXIT.refused;if(gaps.length===0)return write(`No gaps for ${repo}. Everything recorded is verified.`),EXIT.ok;for(const gap of gaps){const freed=gap.unblocks.length>0?`fills → ${gap.unblocks.length} task(s) start: ${gap.unblocks.join(", ")}`:gap.alsoBlocks.length>0?`part of what holds: ${gap.alsoBlocks.join(", ")}`:"nothing queued needs it yet";write(` ${gap.key.padEnd(28)} ${gap.state}`),write(` ${freed}`),write(` verify: ${gap.verify}`),write(` ${gap.instructions}`)}return EXIT.refused}async function briefCommand(flags,context){const{store,write,json,clock}=context,repo=repoFrom(flags),episode=flags.has("latest-watch")?store.latestWatchEpisode(repo):null;if(flags.has("latest-watch")&&episode===null)return fail(write,json,"brief","no-watch","no watch episode recorded for this repo yet — run `toolroll watch` first",EXIT.refused);const since=episode?.startedAt??text(flags,"since")??new Date(clock().getTime()-1440*6e4).toISOString();let runs=store.runsSince(since);episode!==null&&(runs=runs.filter(one=>one.runner===episode.runner&&(episode.endedAt===null||one.startedAt<=episode.endedAt)));const{built,failed,refused,cutDown,invoked,measured,spend,tokens}=tally(runs),gaps=computeGaps(store,repo,clock()),pending=store.pendingForAttention(),decisions=store.listDecisions("unanswered"),incidents=store.openIncidents(),stranded=store.strandedTasks();let review;if(flags.has("local"))review={state:"not-read",why:"--local, the network was not asked"};else{const read=await readPulls(repo);review=read.problems.length>0&&read.pulls.length===0?{state:"not-read",why:read.problems[0]??"unreadable"}:{state:"read",pulls:read.pulls.map(one=>({number:one.number,title:one.title}))}}if(json)return write(envelopeJson({ok:!0,command:"brief",repo,since,episode,tally:{built,failed,refused,cutDown},economics:{invocations:invoked.length,measured:measured.length,costUsd:spend,tokens},gaps,review,outboxPending:pending.length,decide:decisions,incidents,stranded})),EXIT.ok;const lines=[`toolroll — the report ─ ${repo}`];episode!==null&&lines.push(` episode watch #${episode.id} on ${episode.runner} · ${episode.startedAt} → ${episode.endedAt??"never ended — it is running, or it died without saying"}`),lines.push(` runs ${built.length} built · ${failed.length} failed · ${refused.length} refused${cutDown.length>0?` · ${cutDown.length} cut down mid-flight`:""}`);const proofVerdicts=store.proofVerdictsFor(built.map(one=>one.id));for(const one of built){const verdict=proofVerdicts.get(one.id),accepted=verdict!==void 0&&store.proofAcceptance(one.id)!==null,proofNote=verdict===void 0||accepted||verdict.verdict!=="short"&&verdict.verdict!=="refuted"?"":` — ${proofVerdictWords(verdict.verdict,verdict.reasons).word}`;lines.push(` ${one.taskId.padEnd(20)} ${one.committed===!0?`committed to ${one.branch}`:"changed nothing, which is a real answer"}${proofNote}`)}for(const one of failed)lines.push(` ${one.taskId.padEnd(20)} failed: ${one.reason??"?"}${one.worktree===null?"":` — work kept in ${one.worktree}`}`);for(const one of cutDown)lines.push(` ${one.taskId.padEnd(20)} never finished — the process died with it; \`task show ${one.taskId}\``);if(lines.push(` spend ${spendLine({built,failed,refused,cutDown,invoked,measured,spend,tokens})}`),gaps.length>0){const best=gaps[0];lines.push(` ▸ BLOCKED ${gaps.length} gap(s)${best.unblocks.length>0?` — filling ${best.key} starts ${best.unblocks.length} task(s)`:""}`);for(const gap of gaps)lines.push(` ${gap.key.padEnd(28)} ${gap.state}`);lines.push(` → toolroll gaps --repo ${repo}`)}if(lines.push(review.state==="read"?` ▸ REVIEW ${review.pulls.length} PR(s)${review.pulls.length>0?"":" — nothing waits"}`:` ▸ REVIEW not read — ${review.why}`),review.state==="read")for(const pull of review.pulls)lines.push(` #${pull.number} ${pull.title}`);if(pending.length>0&&lines.push(` ▸ OUTBOX ${pending.length} undelivered — toolroll outbox list`),decisions.length>0){const overdue=decisions.filter(one=>one.state==="expired").length;lines.push(` ▸ DECIDE ${decisions.length} waiting${overdue>0?` (${overdue} overdue)`:""} — toolroll decide`);for(const one of decisions)lines.push(` ${String(one.id).padEnd(4)} ${one.taskId.padEnd(20)} ${one.question}`)}else lines.push(" ▸ DECIDE nothing waits on you");if(stranded.length>0){lines.push(` ▸ STRANDED ${stranded.length} task(s) behind failed blockers — they will never become ready on their own`);for(const one of stranded)lines.push(` ${one.id.padEnd(20)} waits on ${one.blockedBy.join(", ")} — \`toolroll task requeue ${one.blockedBy[0]}\``)}if(incidents.length>0){lines.push(` ▸ INCIDENTS ${incidents.length} unresolved — these do not age out`);for(const incident of incidents)lines.push(` ${incident.taskId.padEnd(20)} ${incident.kind} since ${incident.createdAt} — read run ${incident.run}'s evidence, then \`toolroll incident resolve ${incident.id}\``)}return write(lines.join(`
|
|
478
|
+
`),exit:code=>{reader.close(),store.close(),resolvePromise(code)}},void 0,enrolled,join(dirname(file),"evidence"));outcome.ok||(reader.close(),store.close(),resolvePromise(said(outcome.message)))})}function describeAuth(reason,name){return reason==="unknown"?`no runner \`${name}\` — register it first`:reason==="retired"?`${name} has been retired`:reason==="expired"?`${name}'s token expired a year after it registered — register it again`:"that token does not match"}async function buildCommand(positional,flags,context){const{store,write,json,now}=context,demoFence=refuseDemo(context,"build");if(demoFence!==null)return demoFence;const id=positional[0];if(id!==void 0&&store.mirrorByTask(id)!==null)return fail(write,json,"build","external-task","external work dispatches through tick/watch — the completion gate lives there",EXIT.refused);const runner=text(flags,"runner"),token=text(flags,"token"),branch=text(flags,"branch");if(id===void 0||runner===void 0||token===void 0||branch===void 0)return fail(write,json,"build","usage","`toolroll build <id> --runner <name> --token <t> --branch <b> --repo <path>`",EXIT.usage);const auth=authenticate(store,runner,token);if(!auth.ok)return fail(write,json,"build",auth.reason,describeAuth(auth.reason,runner),EXIT.refused);const repo=repoFrom(flags);if(!auth.runner.repos.includes(canonicalProject(repo)??resolve(repo)))return fail(write,json,"build","unauthorized-repo",`${runner} is not bound to ${repo} — \`runner bind\` adds it`,EXIT.refused);if(store.getTask(id)===null)return fail(write,json,"build","unknown-task",`No task ${id}.`,EXIT.refused);const pool=text(flags,"pool")??join(dirname(databasePath(process.env,homedir())),"worktrees"),ref=store.refFor(BUILT_IN,id),worktrees=new WorktreePool(store,{root:pool}),leased=await worktrees.lease({repo,branch,runner,taskRef:ref.id,now,...text(flags,"base")===void 0?{}:{base:text(flags,"base")}});if(!leased.ok)return fail(write,json,"build",leased.reason,leased.message,EXIT.refused);const held=currentClaim(store,ref.id,now),standaloneModel=text(flags,"model"),authority=store.routeAuthorityFor(ref.id,"builder",{provider:"claude",model:standaloneModel??null});if(authority!==null&&!authority.ok)return await worktrees.release(leased.worktree.path,now),fail(write,json,"build","admission-refused",`${id}: ${authority.problem}`,EXIT.refused);const standaloneMode=readAuthModeStrict(authority===null?"claude":authority.stamp.provider);if(!standaloneMode.ok)return await worktrees.release(leased.worktree.path,now),fail(write,json,"build","auth-mode",`${id}: ${standaloneMode.problem}`,EXIT.refused);const standaloneProvider=authority===null?"claude":authority.stamp.provider,standaloneHold=store.budgetGate(now)({...store.budgetSubject(ref.id),agents:[{provider:standaloneProvider,billing:standaloneMode.mode==="api-key"?"api-key":billingOf(standaloneProvider,store.handle)}]});if(standaloneHold.over!==null)return await worktrees.release(leased.worktree.path,now),fail(write,json,"build","budget",`${id}: ${budgetHoldWords(standaloneHold,monthOf(now).name)}`,EXIT.refused);let runId;try{runId=store.startRun({taskRef:ref.id,leaseId:held?.leaseId??"unclaimed",runner,branch,worktree:leased.worktree.path,...authority===null?{}:{provider:authority.stamp.provider,route:authority.stamp},...standaloneModel===void 0?{}:{model:standaloneModel},now})}catch(error){return await worktrees.release(leased.worktree.path,now),fail(write,json,"build","admission-refused",error instanceof Error?error.message:String(error),EXIT.refused)}const result=await build(store,{taskId:id,taskRef:ref.id,runner,...held===null?{}:{leaseId:held.leaseId},runnerToken:token,runId,evidenceRoot:context.evidenceRoot,worktree:leased.worktree.path,branch,now,clock:context.clock,...text(flags,"model")===void 0?{}:{model:text(flags,"model")},...text(flags,"repair-model")===void 0?{}:{repairModel:text(flags,"repair-model")},...text(flags,"turns")===void 0?{}:{maxTurns:Number(text(flags,"turns"))},...context.agentRunner===void 0?{}:{agent:context.agentRunner},...context.gitRunner===void 0?{}:{git:context.gitRunner}}),handedBack=await worktrees.release(leased.worktree.path,now),disposition=disposeBuildOutcome({store,policy:"standalone",leaseId:held?.leaseId,runId,taskId:id,taskRef:ref.id,runner,repo,branch,origin:ref.origin,provider:"claude",model:text(flags,"model")??null,worktreePath:leased.worktree.path,clock:context.clock},result);if(result.ok&&result.parked!==void 0)return disposition.kind!=="parked"?fail(write,json,"build","fenced",`${id} parked, but the lease was gone before the decision could be sealed`,EXIT.refused,{worktree:leased.worktree.path}):succeed(write,json,"build",{parked:!0,decision:disposition.decisionId,worktree:leased.worktree.path},()=>[`${id} parked a decision instead of guessing.`,` decision ${disposition.decisionId} — \`toolroll decide ${disposition.decisionId}\``,` worktree ${leased.worktree.path} (work in progress preserved)`]);if(!result.ok){const broke=result.reason==="agent"||result.reason==="agent-reported"||result.reason==="no-op"||result.reason==="no-handoff"||result.reason==="moved-head"||result.reason==="timeout"||result.reason==="git"||result.reason==="malformed-decision";return fail(write,json,"build",result.reason,result.message,broke?EXIT.failed:EXIT.refused,{worktree:leased.worktree.path})}return succeed(write,json,"build",{...result,worktree:leased.worktree.path,clean:handedBack.ok},()=>[result.committed?`Built ${id} and committed to ${branch}.`:`${id}: no change needed — the agent said so and the tree agrees.`,` worktree ${leased.worktree.path}`,"",result.summary,"","Nothing has been pushed. Look at the branch before it goes anywhere."])}function flowIoOf(context,pool,git,base){const dir=dirname(context.databaseFile);return{triggers:{gh:context.flowTriggerIo?.gh??run,fetch:context.flowTriggerIo?.fetch??fetch,dir:context.flowTriggerIo?.dir??dir,shell:context.flowTriggerIo?.shell??context.flowStepIo?.shell??run,scratch:context.flowTriggerIo?.scratch??context.flowStepIo?.scratch??join(pool,"flow-checks"),...context.flowTriggerIo?.mail===void 0?{}:{mail:context.flowTriggerIo.mail}},replies:{fetch:context.flowTriggerIo?.fetch??fetch,dir:context.flowTriggerIo?.dir??dir,...context.flowTriggerIo?.mail===void 0?{}:{mail:context.flowTriggerIo.mail}},steps:{gh:context.flowStepIo?.gh??run,git:context.flowStepIo?.git??(git===run?hardenedGit(run):git),shell:context.flowStepIo?.shell??run,fetch:context.flowStepIo?.fetch??fetch,dir:context.flowStepIo?.dir??dir,scratch:context.flowStepIo?.scratch??join(pool,"flow-checks"),base,...context.evidenceRoot===void 0?{}:{evidenceRoot:context.evidenceRoot}},...context.evidenceRoot===void 0?{}:{evidenceRoot:context.evidenceRoot},youiyouxGit:gitOf(context.gitRunner)}}async function tickCommand(flags,context){const{store,write,json,clock}=context,demoFence=refuseDemo(context,"tick");if(demoFence!==null)return demoFence;const runner=text(flags,"runner"),token=text(flags,"token");if(runner===void 0||token===void 0)return fail(write,json,"tick","usage","`toolroll tick --runner <name> --token <t> --repo <path> [--max <n>] [--base <ref>]`",EXIT.usage);const auth=heartbeatRunner(store,runner,token,clock());if(!auth.ok)return fail(write,json,"tick",auth.reason,describeAuth(auth.reason,runner),EXIT.refused);if(updateAdmissionPaused(store.raw()))return fail(write,json,"tick","updating",UPDATE_PAUSED,EXIT.refused);const maxGiven=text(flags,"max"),maxAsked=maxGiven===void 0?1:Number(maxGiven);if(!Number.isInteger(maxAsked)||maxAsked<=0)return fail(write,json,"tick","usage","--max takes a whole number of tasks",EXIT.usage);const housekeepingOnly=flags.has("housekeeping-only"),max=flags.has("yield-builds")||housekeepingOnly?0:maxAsked,buildsOnly=flags.has("builds-only"),syncAgeGiven=text(flags,"sync-max-age"),syncMaxAgeMs=syncAgeGiven===void 0?SYNC_MAX_AGE_MS:Number(syncAgeGiven)*1e3;if(!Number.isInteger(syncMaxAgeMs)||syncMaxAgeMs<=0)return fail(write,json,"tick","usage","--sync-max-age takes whole seconds",EXIT.usage);const repo=repoFrom(flags);if(!auth.runner.repos.includes(canonicalProject(repo)??resolve(repo)))return fail(write,json,"tick","unauthorized-repo",`${runner} is not bound to ${repo} — \`runner bind\` adds it`,EXIT.refused);const pool=text(flags,"pool")??join(dirname(databasePath(process.env,homedir())),"worktrees"),model=text(flags,"model"),repairModel=text(flags,"repair-model"),providerFlag=text(flags,"provider"),planModel=text(flags,"plan-model"),planProvider=text(flags,"plan-provider"),turns=text(flags,"turns"),leaseTtlMs=DEFAULT_LEASE_MS,git=context.gitRunner??run,worktrees=new WorktreePool(store,{root:pool,...context.gitRunner===void 0?{}:{runner:context.gitRunner}}),watchOwner=text(flags,"incarnation");watchOwner!==void 0&&!buildsOnly&&await runAcpChecks({store,runner,token,pool:worktrees,clock,watch:{repo:canonicalProject(repo)??resolve(repo),owner:watchOwner},progress:line=>{json||write(line)}});let base=text(flags,"base");if(base===void 0){const head=await git("git",["symbolic-ref","--short","-q","HEAD"],{cwd:repo});if(head.code!==0||head.stdout.trim()==="")return fail(write,json,"tick","git",`${repo} has no branch checked out — say --base explicitly`,EXIT.refused);base=head.stdout.trim()}await probeRepo(store,repo,runner,clock()),applyPendingAgentChanges(store,clock());const housekeeping=buildsOnly?null:await flowHousekeeping(store,repo,clock,flowIoOf(context,pool,git,base),()=>context.shouldStop?.()===!0||context.shouldPauseAdmission?.()===!0),triggerPass=housekeeping?.triggers??{added:0,checked:0,problems:[]},replyPass=housekeeping?.replies??{read:0,taken:0,problem:null},stepPass=housekeeping?.steps??{ran:0,problems:[]},flowPass=housekeeping?.flows??{moved:0,filed:[],problems:[]};if(!buildsOnly)try{sendSubagentSummaries(store,repo,clock()),sendSubagentWeeklies(store,repo,clock())}catch(error){flowPass.problems.push(`subagent summaries: ${error instanceof Error?error.message:"could not send"}`)}if(!buildsOnly&&context.shouldStop?.()!==!0)try{await runRequestedUndos(store,{},clock())}catch(error){flowPass.problems.push(`subagent undo: ${error instanceof Error?error.message:"could not run"}`)}if(!buildsOnly&&context.shouldStop?.()!==!0)try{flowPass.problems.push(...(await refreshConnections(store,[repo],clock(),context.flowStepIo?.fetch===void 0?{}:{fetcher:context.flowStepIo.fetch})).problems)}catch(error){flowPass.problems.push(`tool sign-ins: ${error instanceof Error?error.message:"could not renew"}`)}let settled=0;const settleFinished=()=>{const finished=dispatched.slice(settled).filter(one=>one.outcome!=="skipped").map(one=>one.id);if(settled=dispatched.length,finished.length===0)return;const after=moveCardsAfter(store,repo,finished,clock(),context.evidenceRoot);flowPass.moved+=after.moved,flowPass.filed.push(...after.filed),flowPass.problems.push(...after.problems)};store.sweepCeremonyNonces(clock());let budgetGate=null;const budgetHold=(taskRef,agents)=>(budgetGate??=store.budgetGate(clock()))({...store.budgetSubject(taskRef),agents}),budgetWords=hold=>budgetHoldWords(hold,monthOf(clock()).name),policyHold=agents=>{for(const agent of agents)if("profile"in agent){const verdict=store.runPolicy(agent.profile);if(!verdict.ok)return verdict.message}else{const refused=agent.session!==void 0?store.sessionPolicyRefusal(agent.provider,agent.model,agent.session):store.agentPolicyRefusal(agent.provider,agent.model);if(refused!==null)return refused}return null},ready=store.listReady(clock(),runner),considered=ready.length,dispatched=[];reconcileWalks(store,clock());const MIRROR_WORDS={"stale-mirror":"its tracker has not been synced recently — `toolroll sync` restores freshness","external-closed":"the tracker closed it — reopen it there, then `toolroll task reopen`","dispatch-revoked":"the tracker's building permission was revoked or narrowed","plane-blocked":"the tracker's plane marker could not be verified — building is paused"};for(const skippedMirror of store.ineligibleMirrors(repo,clock(),syncMaxAgeMs))dispatched.push({id:skippedMirror.taskId,outcome:"skipped",reason:skippedMirror.why}),store.enqueueNotification({source:{taskRef:store.lookupRef(skippedMirror.taskId)?.id??-1},dedupeKey:`mirror:${skippedMirror.taskId}:${skippedMirror.why}`,kind:"external-skipped",subject:`${skippedMirror.taskId} cannot dispatch`,body:MIRROR_WORDS[skippedMirror.why]??"the tracker item is not dispatchable right now"},clock());let built=0,parked=0,broke=0;const attestedThisPass=new Map;let untakenTrial=null;for(const ref of ready){if(settleFinished(),untakenTrial?.giveBack(),untakenTrial=null,built>=max)continue;if(context.shouldStop?.()===!0||context.shouldPauseAdmission?.()===!0)break;const id=ref.externalId;if(ref.repo!==null&&ref.repo!==repo){dispatched.push({id,outcome:"skipped",reason:"other-repo"});continue}const scopeApproved=scopeApprovedForDispatch(store,ref.id,clock()),wantsPlan=ref.plan==="requested"&&!scopeApproved,wantsScout=ref.deliverable==="report"&&scopeApproved;if(!wantsPlan&&!scopeApproved){dispatched.push({id,outcome:"skipped",reason:"unapproved"});continue}const agentless=agentlessFirstRun(store,ref,wantsPlan,[runner]);if(agentless!==null){dispatched.push({id,outcome:"skipped",reason:"signed-out",detail:agentless.words});continue}const taskRoute=routeOfTask(store,id,ref,clock());if(taskRoute!==null&&taskRoute.kind==="unreadable"){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:taskRoute.problem});continue}const route=taskRoute!==null&&taskRoute.kind==="route"?taskRoute:null;if(wantsPlan&&route!==null&&route.source==="proposed"){const working=store.workingPlanRouteOf(id);if(!working.ok){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:`${id}: ${working.problem}`});continue}}const planLeg=route===null?null:legOf(route.route,"plan"),fallback=route!==null&&route.source==="approved"&&!wantsPlan&&!wantsScout?dispatchEntryOf(store,ref.id,id,clock()):null;if(fallback!==null&&"problem"in fallback){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:`${id}: ${fallback.problem}`});continue}const sealedBuildLeg=route!==null&&route.source==="approved"?fallback!==null?{provider:fallback.entry.profile.provider,model:fallback.entry.profile.model,chosen:"fallback"}:legOf(route.route,"build"):null;if(wantsPlan&&planLeg!==null&&(planProvider!==void 0||planModel!==void 0||providerFlag!==void 0||model!==void 0)){const flaggedProvider=planProvider??providerFlag,flaggedModel=planModel??model;if(flaggedProvider!==void 0&&flaggedProvider!==planLeg.provider||flaggedModel!==void 0&&flaggedModel!==planLeg.model){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:`the pass flags name ${flaggedProvider??planLeg.provider}${flaggedModel===void 0?"":` · ${flaggedModel}`} but ${id}'s planner is ${planLeg.provider} · ${planLeg.model} — flags cannot reroute a task; override the plan phase with \`task route\``});continue}}const resolution=wantsPlan?planLeg!==null?resolvePhaseAgent(store,"plan",repo,{provider:planLeg.provider,model:planLeg.model}):resolvePhaseAgent(store,"plan",repo,{provider:ref.planProvider??planProvider??providerFlag,model:ref.planProvider!==null?ref.planModel??void 0:planModel??model}):sealedBuildLeg!==null?resolvePhaseAgent(store,"build",repo,{provider:sealedBuildLeg.provider,model:sealedBuildLeg.model},ref):resolvePhaseAgent(store,"build",repo,{provider:providerFlag,model},ref);if(!resolution.ok){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:resolution.problem});continue}const routedDecision=!wantsPlan&&sealedBuildLeg===null&&route===null&&store.getScope(id)?.approvedProfile==null&&resolution.source!=="pinned"&&resolution.source!=="flag"?routeWorkerModel(store,{taskKind:ref.sizing?.size==="small"?"simple-fix":"multi-file-build",provider:resolution.spec.provider,fallbackModel:resolution.spec.model,now:clock()}):null,spec=routedDecision!==null&&routedDecision.steppedDown?{provider:resolution.spec.provider,model:routedDecision.model}:resolution.spec,brokenMode=readAuthModeStrict(spec.provider);if(!brokenMode.ok){dispatched.push({id,outcome:"skipped",reason:"auth-mode",detail:brokenMode.problem});continue}const gate=signInGate(store,[spec.provider],clock(),ref.id);if(gate.waiting!==null){dispatched.push({id,outcome:"skipped",reason:"signed-out",detail:signInWords(gate.waiting)});continue}untakenTrial=gate;const governingLeg=wantsPlan?planLeg:sealedBuildLeg;if(governingLeg!==null&&(spec.provider!==governingLeg.provider||spec.model!==governingLeg.model)){dispatched.push({id,outcome:"skipped",reason:"agent-config",detail:`${id}: the ${wantsPlan?"plan":"build"} leg names ${governingLeg.provider} · ${governingLeg.model} but resolution produced ${spec.provider} · ${spec.model??"(no model)"} — nothing substitutes`});continue}const routeStamp=phase=>{if(governingLeg===null||route===null||phase==="plan"&&route.source==="live"){const legacy=store.routeAuthorityFor(ref.id,phase==="plan"?"planner":"builder",{provider:spec.provider,model:spec.model});return legacy!==null&&legacy.ok?legacy.stamp:null}return{routeDigest:routeDigestOf(route.route),phase,provider:spec.provider,model:spec.model,chosen:governingLeg.chosen}};if(!wantsPlan&&!wantsScout&&route===null){const legacyStamp=routeStamp("build");if(legacyStamp!==null&&(legacyStamp.provider!==spec.provider||legacyStamp.model!==spec.model)){const message=`${id}: the sealed profile builds on ${legacyStamp.provider} · ${legacyStamp.model??"(no model)"} but today's routing resolved ${spec.provider} · ${spec.model??"(no model)"} — nothing runs on it (stale-approval)`;holdStaleApproval(store,{taskRef:ref.id,taskId:id,message},clock()),dispatched.push({id,outcome:"skipped",reason:"stale-approval",detail:message});continue}}if(!wantsPlan&&!wantsScout){const ruleHeld=ruleHoldOf(store,id);if(ruleHeld!==null){holdRuleOff(store,ref.id,ruleHeld.model,clock()),dispatched.push({id,outcome:"skipped",reason:"rule-switched-off",detail:`${id}: results for ${ruleHeld.model} dropped after this was approved — approve it again or re-file it`});continue}}{const unavailable=store.runnerReadinessOf(runner,spec.provider);if(unavailable!==null&&readinessRefuses(unavailable,fallback?.entry.authMode??(brokenMode.ok?brokenMode.mode:"subscription"))){const observed=`${unavailable.provider} is reported unavailable on ${runner} (${unavailable.reason}; observed ${unavailable.observedAt})`;dispatched.push({id,outcome:"skipped",reason:"provider-unavailable",detail:`${observed} — nothing substitutes for a routed provider: override the phase with \`task route\` or restore the provider and report readiness again`});continue}}const skipProviders=wantsPlan||fallback!==null?[spec.provider]:[store.getScope(id)?.approvedProfile?.provider].filter(one=>one!=null);let unattestedLane=null;for(const candidate of new Set(skipProviders)){if(isAcpProvider(candidate)){const checked=store.acpAttestationFor(candidate,runner),verified=checked===null?null:verifyLaunch(checked.launch);if(checked===null){unattestedLane=`${ACP_AGENTS[candidate].name} isn't checked on ${runner} — run \`toolroll agents check ${candidate}\` there`;break}if(verified!==null&&!verified.ok){unattestedLane=verified.problem;break}continue}if(attestationOf(candidate)===null)continue;let verdict=attestedThisPass.get(candidate);if(verdict===void 0&&(verdict=await attestProvider(candidate,inspectionOf(candidate).binary),attestedThisPass.set(candidate,verdict)),verdict!==null&&!verdict.ok){unattestedLane=verdict.problem;break}}if(unattestedLane!==null){dispatched.push({id,outcome:"skipped",reason:"provider-unattested",detail:unattestedLane});continue}{const sealed=wantsPlan||wantsScout?null:fallback?.entry.profile??store.getScope(id)?.approvedProfile??null,refused=policyHold([sealed!==null?{profile:sealed}:{provider:spec.provider,model:spec.model,...wantsPlan?{session:"planning"}:wantsScout?{session:"scouting"}:{}}]);if(refused!==null){dispatched.push({id,outcome:"skipped",reason:"policy",detail:refused});continue}}const sealedModel=store.getScope(id)?.approvedProfile?.model??null,budgeted=budgetHold(ref.id,fallback?.paid===!0?[{provider:spec.provider,billing:"api-key"}]:[...new Set([spec.provider,...skipProviders])].map(provider=>isAcpProvider(provider)||provider==="pi"?store.agentFor(provider,provider===spec.provider?spec.model??sealedModel:sealedModel,runner):store.agentsFor([provider])[0]));if(budgeted.over!==null){dispatched.push({id,outcome:"skipped",reason:"budget",detail:budgetWords(budgeted)});continue}if(!wantsPlan&&runningReleaseCheck(store,clock(),ref.id)!==null){dispatched.push({id,outcome:"skipped",reason:"release-check",detail:RELEASE_CHECK_WAIT});continue}if(repo!==null){const railed=store.reserveModeRail(repo,1,clock());if(!railed.ok){dispatched.push({id,outcome:"skipped",reason:railed.rail,detail:railed.detail});continue}}const claimed=acquireIfReady(store,ref.id,runner,{...wantsPlan?{dispatchRole:"planner"}:wantsScout?{dispatchRole:"scout"}:{},now:clock(),token,ttlMs:leaseTtlMs,syncMaxAgeMs,repo,provider:spec.provider,...spec.model===null?{}:{model:spec.model},...fallback!==null?{authMode:fallback.entry.authMode}:brokenMode.ok&&(brokenMode.mode==="api-key"||brokenMode.mode==="subscription")?{authMode:brokenMode.mode}:{},...text(flags,"incarnation")===void 0?{}:{incarnation:text(flags,"incarnation")}});if(claimed.ok&&(untakenTrial=null),!claimed.ok){if(claimed.reason==="capability"&&"message"in claimed){const key=/needs (\S+)/.exec(claimed.message)?.[1],parsed=key===void 0?null:parseCapabilityKey(key);if(parsed!==null){const home=ref.repo??repo;store.enqueueNotification({source:{taskRef:ref.id},dedupeKey:`gap:${home}:${parsed.kind}:${parsed.name}`,kind:"gap",pushClass:"attention",link:"/caps",subject:`${key} blocks work in ${home}`,body:`${id} (and possibly others) cannot dispatch: ${claimed.message}. \`toolroll gaps --repo ${home}\``},clock())}}dispatched.push({id,outcome:"skipped",reason:claimed.reason,..."message"in claimed&&claimed.reason==="capability"?{detail:claimed.message}:{}});continue}const lease=claimed.claim.leaseId;if(wantsPlan){const answers=store.answeredDecisionsFor(id).map(one=>({question:one.question,choice:one.choice??"",note:one.note})),sourced=plannerSourceOf(store,context.evidenceRoot,id,answers);if(!sourced.ok){release(store,lease,clock()),dispatched.push({id,outcome:"skipped",reason:`planner-source-${sourced.reason}`,detail:sourced.message});continue}const planBranch=await existingOrFirst([`toolroll-plan/${id}`,`standing-orders-plan/${id}`],async one=>(await git("git",["rev-parse","--verify","--quiet",`refs/heads/${one}`],{cwd:repo})).code===0),revised=ref.revisionOf===null?null:revisionSourceHead(store,context.evidenceRoot,ref.id,ref.revisionOf);if(revised!==null&&!revised.ok){release(store,lease,clock()),dispatched.push({id,outcome:"skipped",reason:"revision-brief",detail:revised.problem});continue}const planLeased=await worktrees.lease({repo,branch:planBranch,runner,taskRef:ref.id,now:clock(),base:revised?.head??base,reuseBranch:!0,reclaim:{evidenceRoot:context.evidenceRoot},...freshBaseFor(store,id,planBranch,base)});if(!planLeased.ok){release(store,lease,clock()),dispatched.push({id,outcome:"failed",reason:planLeased.reason}),broke++;continue}const planStamp=routeStamp("plan"),planRunId=store.startRun({taskRef:ref.id,leaseId:lease,runner,role:"planner",provider:spec.provider,branch:planBranch,worktree:planLeased.worktree.path,...spec.model===null?{}:{model:spec.model},now:clock(),...planStamp===null?{}:{route:planStamp}});noteBaseStanding(store,planRunId,planLeased.base,base,clock());let sourceArtifact;try{sourceArtifact=storeEvidence(store,context.evidenceRoot,planRunId,"plan-contract","planner-source.json",encodePlannerSource(sourced.source),`planner source ${sourced.source.sourceDigest.slice(0,12)} — the filed request quoted into the brief, recorded before spend (${sourced.bytes} bytes)`,clock(),{captureStatus:"ok"})}catch(error){await worktrees.release(planLeased.worktree.path,clock());const unrecorded=finalize(store,lease,{kind:"plan-failure",runId:planRunId,taskId:id,failure:"failure",message:`the planner's source could not be recorded: ${error instanceof Error?error.message:String(error)}`,now:clock()});dispatched.push({id,outcome:"failed",reason:"evidence"}),unrecorded.ok||release(store,lease,clock()),broke++;continue}store.stampRun(planRunId,{scopeDigest:sourced.source.contract.scope?.digest??""}),budgetGate=null;const outcome=await planTask(store,{...budgeted.remainingMicrousd===null?{}:{maxBudgetUsd:Math.max(1,budgeted.remainingMicrousd)/1e6},taskId:id,taskTitle:store.getTask(id)?.title??id,taskRef:ref.id,runner,leaseId:lease,runnerToken:token,runId:planRunId,worktree:planLeased.worktree.path,branch:planBranch,now:clock(),clock,onProviderSpawn:pid=>{worktrees.recordProviderOccupancy(planLeased.worktree.path,runner,pid,planLeased.worktree.leaseEpoch)},evidenceRoot:context.evidenceRoot,answers,source:sourced.source,provider:spec.provider,...spec.model===null?{}:{model:spec.model},...context.agentRunner===void 0?{}:{agent:context.agentRunner},...context.gitRunner===void 0?{}:{git:context.gitRunner}});if(await worktrees.release(planLeased.worktree.path,clock()),outcome.ok&&"parked"in outcome){const sealed=finalize(store,lease,{kind:"park",runId:planRunId,taskId:id,decision:outcome.parked.decision,artifactIds:outcome.parked.artifactIds,repairRunId:outcome.parked.repairRunId,now:clock()});sealed.ok?(store.resetPlanStrikes(ref.id),dispatched.push({id,outcome:"parked",reason:`decision:${sealed.decisionId}`}),parked++):sealed.reason==="stopped"?dispatched.push({id,outcome:"stopped",reason:`stop:${planRunId}`}):(dispatched.push({id,outcome:"failed",reason:"fenced"}),broke++);continue}if(outcome.ok){const sealed=finalize(store,lease,{kind:"plan",runId:planRunId,taskId:id,plan:outcome.drafted.plan,artifact:outcome.drafted.artifact,repairRunId:outcome.drafted.repairRunId,source:sourced.source,sourceArtifact,evidenceRoot:context.evidenceRoot,now:clock()});sealed.ok?(store.clearQuota(runner,spec.provider,spec.model??""),dispatched.push({id,outcome:"planned",...sealed.changes===0?{}:{detail:`${sealed.changes} contract change${sealed.changes===1?"":"s"} proposed${sealed.amendment===null?"":" with an amendment"}`}})):sealed.reason==="stale-source"||sealed.reason==="source-invalid"?dispatched.push({id,outcome:"skipped",reason:sealed.reason,detail:sealed.detail}):sealed.reason==="stopped"?dispatched.push({id,outcome:"stopped",reason:`stop:${planRunId}`}):(dispatched.push({id,outcome:"failed",reason:"fenced"}),broke++);continue}const sealedFailure=finalize(store,lease,{kind:"plan-failure",runId:planRunId,taskId:id,failure:outcome.kind,...outcome.kind==="malformed"?{malformed:outcome.reason==="malformed-decision"?"decision":"plan"}:{},message:outcome.message,code:outcome.reason,...outcome.kind==="malformed"&&outcome.problems!==void 0?{problems:outcome.problems.map(problem=>problem.message)}:{},...outcome.agentSaid===void 0?{}:{agentSaid:outcome.agentSaid},now:clock()});if(!sealedFailure.ok&&sealedFailure.reason==="stopped"){dispatched.push({id,outcome:"stopped",reason:`stop:${planRunId}`});continue}dispatched.push({id,outcome:"failed",reason:outcome.reason}),sealedFailure.ok||release(store,lease,clock()),broke++;continue}if(wantsScout){const scoutBranch=`toolroll-scout/${id}/${randomBytes(4).toString("hex")}`,scopeRow=store.getScope(id),proof=proveApprovedProfile(scopeRow,{provider:spec.provider,model:spec.model??void 0,maxTurns:void 0,timeoutMs:void 0,skipPermissions:!1});if(!proof.ok){release(store,lease,clock()),dispatched.push({id,outcome:"skipped",reason:"stale-approval",detail:proof.message});continue}const scoutLeased=await worktrees.lease({repo,branch:scoutBranch,runner,taskRef:ref.id,now:clock(),base});if(!scoutLeased.ok){release(store,lease,clock()),dispatched.push({id,outcome:"failed",reason:scoutLeased.reason}),broke++;continue}const scoutStamp=routeStamp("build")??{routeDigest:`profile:${profileDigestOf(proof.effective.profile)}`,phase:"build",provider:spec.provider,model:proof.effective.model,chosen:"legacy"},scoutRunId=store.startRun({taskRef:ref.id,leaseId:lease,runner,role:"scout",provider:spec.provider,branch:scoutBranch,worktree:scoutLeased.worktree.path,model:proof.effective.model,now:clock(),route:scoutStamp});store.stampRun(scoutRunId,{scopeDigest:scopeRow?.approvedDigest??"",profileDigest:profileDigestOf(proof.effective.profile)});const scoutAnswers=store.answeredDecisionsFor(id,6).map(one=>({question:one.question,choice:one.choice??"",note:one.note}));budgetGate=null;const scouted=await scoutTask(store,{...budgeted.remainingMicrousd===null?{}:{maxBudgetUsd:Math.max(1,budgeted.remainingMicrousd)/1e6},taskId:id,taskTitle:store.getTask(id)?.title??id,goal:scopeRow?.goal??"",outOfScope:scopeRow?.outOfScope??null,taskRef:ref.id,runner,leaseId:lease,runnerToken:token,runId:scoutRunId,worktree:scoutLeased.worktree.path,branch:scoutBranch,now:clock(),clock,onProviderSpawn:pid=>{worktrees.recordProviderOccupancy(scoutLeased.worktree.path,runner,pid,scoutLeased.worktree.leaseEpoch)},evidenceRoot:context.evidenceRoot,answers:scoutAnswers,demoUrl:projectDemoUrl(context.databaseFile,repo),provider:spec.provider,model:proof.effective.model,...proof.effective.maxTurns===void 0?{}:{maxTurns:proof.effective.maxTurns},timeoutMs:proof.effective.timeoutMs,...context.agentRunner===void 0?{}:{agent:context.agentRunner},...context.gitRunner===void 0?{}:{git:context.gitRunner}});await worktrees.release(scoutLeased.worktree.path,clock());const discarded=await worktrees.discard(scoutLeased.worktree.path,clock()),leftover=discarded.ok?{}:{detail:`checkout kept: ${discarded.message}`};if(scouted.ok&&"parked"in scouted){const sealed=finalize(store,lease,{kind:"park",runId:scoutRunId,taskId:id,decision:scouted.parked.decision,artifactIds:scouted.parked.artifactIds,now:clock()});sealed.ok?(dispatched.push({id,outcome:"parked",reason:`decision:${sealed.decisionId}`,...leftover}),parked++):(dispatched.push({id,outcome:"failed",reason:"fenced",...leftover}),broke++);continue}if(scouted.ok){const sealed=finalize(store,lease,{kind:"scout",runId:scoutRunId,taskId:id,report:scouted.reported.report,artifact:scouted.reported.artifact,now:clock()});sealed.ok?(store.clearQuota(runner,spec.provider,spec.model??""),dispatched.push({id,outcome:"reported",...leftover})):sealed.reason==="stopped"?dispatched.push({id,outcome:"stopped",reason:`stop:${scoutRunId}`,...leftover}):(dispatched.push({id,outcome:"failed",reason:"fenced",...leftover}),broke++);continue}const sealedFailure=finalize(store,lease,{kind:"scout-failure",runId:scoutRunId,taskId:id,failure:scouted.kind,...scouted.kind==="malformed"?{malformed:scouted.reason==="malformed-decision"?"decision":"report"}:{},message:scouted.message,now:clock()});if(!sealedFailure.ok&&sealedFailure.reason==="stopped"){dispatched.push({id,outcome:"stopped",reason:`stop:${scoutRunId}`,...leftover});continue}dispatched.push({id,outcome:"failed",reason:scouted.reason,...leftover}),sealedFailure.ok||release(store,lease,clock()),broke++;continue}const branch=await existingOrFirst(taskBranches(id),async one=>(await git("git",["rev-parse","--verify","--quiet",`refs/heads/${one}`],{cwd:repo})).code===0),exists=await git("git",["rev-parse","--verify","--quiet",`refs/heads/${branch}`],{cwd:repo});let buildBase=base,caughtUp=null;if(ref.revisionOf!==null){const source=revisionSourceHead(store,context.evidenceRoot,ref.id,ref.revisionOf);let problem=source.ok?null:source.problem;if(source.ok)if(exists.code!==0&&text(flags,"base")===void 0){if(buildBase=source.head,!publishesThroughPullRequests(store,repo)){const onto=landingBranchOf(store,repo,base),result2=await catchUpRevision(hardenedGit(git,"build",{repo}),repo,source.head,onto,id,clock());caughtUp={head:source.head,onto,result:result2},result2.kind==="merged"&&(buildBase=result2.commit)}}else{const descendant=exists.code===0?branch:base,ancestry=await lazyFetchSafeGit(git)("git",[...noLazyFetch(),"-c","protocol.allow=never","--no-replace-objects","merge-base","--is-ancestor",source.head,descendant],{cwd:repo});if(ancestry.code!==0)problem=ancestry.stderr.includes(PARTIAL_CLONE_REFUSAL)?PARTIAL_CLONE_REFUSAL:"the requested revision base does not contain its source head";else if(exists.code===0&&store.latestBranchBaseMove(ref.id,branch)===null&&store.firstBuilderBase(ref.id,branch)===null&&!publishesThroughPullRequests(store,repo)){const tip=exists.stdout.trim(),main=await catchUpMergeOf(hardenedGit(git,"build",{repo}),repo,tip,source.head,landingBranchOf(store,repo,base));main!==null&&store.recordBranchBaseMove(ref.id,branch,tip,main,clock())}}if(problem!==null){release(store,lease,clock()),dispatched.push({id,outcome:"skipped",reason:"revision-brief",detail:problem});continue}}const leased=await worktrees.lease({repo,branch,runner,taskRef:ref.id,now:clock(),...exists.code===0?{}:{base:buildBase},reclaim:{evidenceRoot:context.evidenceRoot},...exists.code===0?freshBaseFor(store,id,branch,base):{}});if(caughtUp!==null&&caughtUp.result.kind==="merged"){const merged=caughtUp.result,at=leased.ok&&leased.created?await hardenedGit(git,"build",{repo})("git",["rev-parse","--verify","-q",`refs/heads/${branch}^{commit}`],{cwd:repo}):null;if(at!==null&&at.code===0&&at.stdout.trim()===merged.commit)store.recordBranchBaseMove(ref.id,branch,merged.commit,merged.main,clock());else if(leased.ok&&leased.created){await worktrees.release(leased.worktree.path,clock()),release(store,lease,clock()),dispatched.push({id,outcome:"failed",reason:"git",detail:"Toolroll couldn't confirm the new branch stands at its merge of main; it tries again."}),broke++;continue}else caughtUp={...caughtUp,result:{kind:"unavailable"}}}if(!leased.ok){release(store,lease,clock()),dispatched.push({id,outcome:"failed",reason:leased.reason}),broke++;continue}const buildStamp=routeStamp("build");let runId;try{if(leased.resumedFromRun!==void 0){if(buildStamp===null)throw new Error(`${id}: the recovered attempt presents no build authority`);const admittedRecovered=store.admitRecoveredBuilder({taskRef:ref.id,leaseId:lease,runner,branch,worktree:leased.worktree.path,provider:spec.provider,...spec.model===null?{}:{model:spec.model},recoveredFrom:leased.resumedFromRun,now:clock(),route:buildStamp});if(!admittedRecovered.ok)throw new Error(admittedRecovered.problem);runId=admittedRecovered.runId}else runId=store.startRun({taskRef:ref.id,leaseId:lease,runner,branch,worktree:leased.worktree.path,provider:spec.provider,...spec.model===null?{}:{model:spec.model},now:clock(),...buildStamp===null?{}:{route:buildStamp}})}catch(error){await worktrees.release(leased.worktree.path,clock()),release(store,lease,clock()),dispatched.push({id,outcome:"skipped",reason:"admission-refused",detail:error instanceof Error?error.message:String(error)});continue}noteBaseStanding(store,runId,leased.base,base,clock()),caughtUp!==null&&leased.created&&recordCatchUp(store,{repo,taskId:id,runId,branch,head:caughtUp.head,onto:caughtUp.onto},caughtUp.result,clock()),leased.resumedFromRun!==void 0&&store.addRunNote(runId,"Toolroll",`Recovered the ${leased.recoveryKind==="completed"?"completed source draft":"work-in-progress draft"} from interrupted attempt #${leased.resumedFromRun}. This fresh attempt is reviewing and verifying it; the safety patch is retained.`,clock());const scopeBudget=store.getScope(id)?.budgetMicrousd??null,backstop=store.getSpendDefaults()?.buildPerRunMicrousd??null,budgetLeft=budgeted.remainingMicrousd!==null&&MONEY_CAPABILITIES[spec.provider].nativeDollarCapFlag!==null?Math.max(1,budgeted.remainingMicrousd):null,capMicrousd=[scopeBudget,backstop,budgetLeft].reduce((least,one)=>one===null?least:least===null?one:Math.min(least,one),null);if(capMicrousd!==null&&MONEY_CAPABILITIES[spec.provider].nativeDollarCapFlag===null){store.finishRun(runId,{outcome:"refused",reason:"budget-unenforceable",now:clock()}),release(store,lease,clock()),await worktrees.release(leased.worktree.path,clock()),dispatched.push({id,outcome:"skipped",reason:"budget-unenforceable"});continue}budgetGate=null;const result=await build(store,{taskId:id,taskRef:ref.id,runner,leaseId:lease,runnerToken:token,runId,evidenceRoot:context.evidenceRoot,worktree:leased.worktree.path,branch,now:clock(),clock,...capMicrousd===null?{}:{maxBudgetUsd:capMicrousd/1e6},onProviderSpawn:pid=>{worktrees.recordProviderOccupancy(leased.worktree.path,runner,pid,leased.worktree.leaseEpoch)},provider:spec.provider,...spec.model===null?{}:{model:spec.model},...repairModel===void 0?{}:{repairModel},...turns===void 0?{}:{maxTurns:Number(turns)},...context.agentRunner===void 0?{}:{agent:context.agentRunner},...context.gitRunner===void 0?{}:{git:context.gitRunner},...context.shouldStop===void 0?{}:{shouldStop:context.shouldStop},...leased.resumedFromRun===void 0?{}:{recoveredDraftRun:leased.resumedFromRun},...leased.recoveryKind===void 0?{}:{recoveredDraftKind:leased.recoveryKind}});await worktrees.release(leased.worktree.path,clock());const disposition=disposeBuildOutcome({store,policy:"tick",leaseId:lease,runId,taskId:id,taskRef:ref.id,runner,repo,branch,origin:ref.origin,provider:spec.provider,model:spec.model,worktreePath:leased.worktree.path,evidenceRoot:context.evidenceRoot,clock},result);switch(disposition.kind){case"parked":dispatched.push({id,outcome:"parked",reason:`decision:${disposition.decisionId}`,worktree:leased.worktree.path}),parked++;break;case"park-fenced":dispatched.push({id,outcome:"failed",reason:"fenced",worktree:leased.worktree.path}),broke++;break;case"disowned":dispatched.push({id,outcome:"failed",reason:"external-closed",branch,worktree:leased.worktree.path}),broke++;break;case"built":dispatched.push({id,outcome:"built",committed:disposition.committed,branch,worktree:leased.worktree.path}),built++;break;case"built-fenced":dispatched.push({id,outcome:"failed",reason:"fenced",branch,worktree:leased.worktree.path}),broke++;break;case"skipped":dispatched.push({id,outcome:"skipped",reason:disposition.reason});break;case"fenced":dispatched.push({id,outcome:"failed",reason:"fenced",worktree:leased.worktree.path}),broke++;break;case"malformed":dispatched.push({id,outcome:"failed",reason:disposition.sealed?"malformed-decision":"fenced",worktree:leased.worktree.path}),broke++;break;case"failed":dispatched.push({id,outcome:"failed",reason:disposition.sealed?disposition.disposition==="auth-expired"?"auth-expired — requeued, sign-in needed":disposition.disposition==="fallback"?"out of plan — moved to the next approved agent":`${disposition.failureClass}${disposition.disposition==="backoff"?` — retry ${disposition.strikes}/3`:disposition.disposition==="stalled"?" — stalled":disposition.closedState!==null?` — the task was already ${disposition.closedState}, so it stays ${disposition.closedState}`:""}`:"fenced",...result.ok?{}:{detail:result.message.slice(0,200)},worktree:leased.worktree.path}),disposition.sealed&&disposition.disposition==="fallback"||broke++;break;case"recorded":break;case"stopped":dispatched.push({id,outcome:"stopped",reason:`stop:${disposition.stopRun}`,branch,worktree:leased.worktree.path});break;case"handed-back":dispatched.push({id,outcome:"stopped",reason:"service-stop",detail:result.ok?"":result.message.slice(0,200),branch,worktree:leased.worktree.path});break;case"invariant":dispatched.push({id,outcome:"failed",reason:disposition.reason}),broke++;break}}if(untakenTrial?.giveBack(),!buildsOnly&&!housekeepingOnly&&authenticate(store,runner,token).ok){const reviewed=await buildReviewPass(store,{runner,token,repos:auth.runner.repos,clock,root:context.evidenceRoot,...text(flags,"incarnation")===void 0?{}:{watchIncarnation:text(flags,"incarnation")},...context.agentRunner===void 0?{}:{agent:context.agentRunner},shouldStop:()=>context.shouldStop?.()===!0||context.shouldPauseAdmission?.()===!0});for(const one of reviewed)dispatched.push({id:`review of run ${one.run}`,outcome:one.outcome==="not-reviewed"?"not-reviewed":"reviewed",reason:one.detail})}!buildsOnly&&!housekeepingOnly&&syncAssignmentHandoffs(store,clock(),auth.runner.repos,context.evidenceRoot),settleFinished();const replied=replyPass.taken>0||replyPass.problem!==null,requestPass=housekeeping?.youiyoux??NO_YOUIYOUX_PASS,requested=requestPass.filed+requestPass.copied+requestPass.decided+requestPass.problems.length>0,flows=flowPass.moved+flowPass.filed.length+flowPass.problems.length+triggerPass.added+triggerPass.problems.length+stepPass.ran+stepPass.problems.length===0&&!replied&&!requested?{}:{flows:{...flowPass,...triggerPass.added+triggerPass.problems.length===0?{}:{triggers:triggerPass},...requested?{youiyoux:requestPass}:{},...stepPass.ran+stepPass.problems.length===0?{}:{steps:stepPass},...replied?{replies:replyPass}:{}}},summary=()=>{const lines=[`Considered ${considered}, built ${built}, parked ${parked}, broke ${broke}.`];for(const entry of dispatched){const detail=entry.outcome==="built"?entry.committed===!0?`committed to ${entry.branch}`:"no changes reported; see the result's proof status":entry.outcome==="parked"?`${entry.reason} — \`toolroll decide\``:entry.reason??"";lines.push(` ${entry.id.padEnd(24)} ${entry.outcome} ${detail}`.trimEnd())}return built>0&&lines.push("","Nothing has been pushed. Look at the branches before they go anywhere."),parked>0&&lines.push("",`${parked} decision${parked===1?"":"s"} waiting — \`toolroll decide\`, or \`toolroll brief\`.`),lines};return broke>0?fail(write,json,"tick","build-failed",`${broke} of ${dispatched.length} dispatched tasks broke`,EXIT.failed,{considered,dispatched}):built>0||parked>0||dispatched.some(one=>one.outcome==="planned"||one.outcome==="reported"||one.outcome==="reviewed"||one.outcome==="not-reviewed")?succeed(write,json,"tick",{considered,dispatched,...flows},summary):considered===0?fail(write,json,"tick","empty","nothing is ready",EXIT.refused,{considered,dispatched,...flows}):fail(write,json,"tick","nothing-dispatched","everything ready is waiting on a person or held by somebody else",EXIT.refused,{considered,dispatched,...flows})}async function reconcileCommand(flags,context){const{store,write,json,clock}=context,demoFence=refuseDemo(context,"reconcile");if(demoFence!==null)return demoFence;const repo=repoFrom(flags),pool=text(flags,"pool")??join(dirname(databasePath(process.env,homedir())),"worktrees"),syncReports=[];for(const dispatchGrant of store.listGrants().filter(one=>one.dispatch===!0&&one.remoteRepo!=null&&one.repo===repo))syncReports.push(await syncPass(store,dispatchGrant,context.dispatchAdapter??ghDispatchAdapter(),clock));for(const report of syncReports)report.outcome==="failed"||report.outcome==="blocked"?store.enqueueEpisode(`sync:${report.remoteRepo}`,{source:{project:repo},kind:"sync-failed",pushClass:"attention",link:"/system",subject:`syncing ${report.remoteRepo} ${report.outcome==="blocked"?"is blocked":"failed"}`,body:`${report.detail??"the pass did not finish"} — external work keeps its last verified state and stops dispatching past its freshness window.`},clock().toISOString(),clock()):store.resolveEpisodes(`sync:${report.remoteRepo}`,clock());const recovered=recoverDead(store,clock()),closedRuns=await closeOutRuns(store,clock,{repo});store.recordFinishedRunExits(clock()),store.settleUnspawnedWitnesses(clock()),await proveFinishedRunsStopped(store,clock),store.settleQuiescentStops(clock()),applyPendingAgentChanges(store,clock()),retryVanishedWhenStopped(store,clock()),expireFastStarts(store,clock()),routeLegacyPlans(store,clock());try{releaseStalledUpdate(dirname(context.databaseFile),clock())}catch{}for(const one of recovered){for(const leaseId of one.claims)store.enqueueNotification({source:{taskRef:Number(store.handle.prepare("SELECT task_ref FROM claim WHERE lease_id = ?").get(leaseId)?.task_ref??-1)},dedupeKey:`recover:${leaseId}`,kind:"runner-recovered",subject:`${one.runner} went dead holding work`,body:`Its claims were requeued and its worktrees handed back unverified. Lease ${leaseId}.`},clock());for(const runId of one.runs)store.enqueueNotification({source:{run:runId},dedupeKey:`recover-run:${runId}`,kind:"runner-recovered",subject:`${one.runner} went dead mid-attempt`,body:`Run #${runId} was still open with no live lease; it is now finished as interrupted. Check this task's current state in the console.`,link:`/r/${runId}`},clock())}const reaped=reap(store,clock()),liveSwept=sweepLiveLogs(store,context.evidenceRoot,clock());try{store.sweepRunActivity(clock(),LIVE_RETAIN_MS,LIVE_FILE_BOUND)}catch{}const worktrees=new WorktreePool(store,{root:pool,...context.gitRunner===void 0?{}:{runner:context.gitRunner}}),adoption=await worktrees.adopt(repo,clock());if(adoption.ok){const now=clock(),notice=worktreeAdoptionNotice(repo,adoption.adopted,now);notice!==null&&store.enqueueNotification(notice,now)}if(!adoption.ok)return fail(write,json,"reconcile","git",adoption.message,EXIT.failed,{recovered,reaped:reaped.map(claim=>claim.leaseId)});let landed={completed:[],steps:[]};const remotes=new RemoteMains(store,context.gitRunner,context.evidenceRoot);try{landed=await reconcileLanded(store,worktrees,gitOf(context.gitRunner),remotes,repo,context.evidenceRoot,clock)}catch{}finally{remotes.close()}const landedGone=landed.steps.filter(one=>one.outcome==="removed");let tidied=[];try{tidied=runTidy(store,clock(),releaseFactsFor(context.databaseFile),TIDY_PASS_LIMIT,{principal:"operator",repos:[repo],includeUnplaced:!1})}catch{}try{reevaluateResultRecords(store,canonicalProject(repo)??resolve(repo),context.evidenceRoot,clock())}catch{}try{routeRulesPass(store,canonicalProject(repo)??resolve(repo),clock())}catch{}const closedCheckouts=await closeOutCheckouts(store,clock,finishedCheckouts(store,clock(),repo)),pruned=await cleanCheckouts(store,worktrees,clock,{manual:!1,actor:"worker",repo}),slimmed=await slimKeptCheckouts(store,worktrees,clock,{actor:"worker",repo});let retention=null;try{retention=dailyRetention(store,context.evidenceRoot,clock())}catch{retention=null}const retained=retention===null?[]:retention.counts.filter(one=>one.count>0);let storageSwept=null;if(context.sweepOwner!==void 0)try{storageSwept=idleStorageSweep(store,{databaseFile:context.databaseFile,pool:worktrees,tempRoots:context.tempRoots??tempRoots(),owner:context.sweepOwner},clock)}catch{storageSwept=null}const swept=storageSwept===null?[]:storageSwept.parts.filter(one=>one.count>0),nothing=retained.length===0&&swept.length===0&&recovered.length===0&&reaped.length===0&&adoption.adopted.length===0&&adoption.forgotten.length===0&&pruned.removed.length===0&&closedRuns.length===0&&closedCheckouts.length===0&&slimmed.slimmed.length===0&&landed.completed.length===0&&landedGone.length===0&&tidied.length===0&&liveSwept.removed.length===0;return succeed(write,json,"reconcile",{recovered,reaped:reaped.map(claim=>claim.leaseId),adopted:adoption.adopted,forgotten:adoption.forgotten,checkoutsRemoved:pruned.removed.map(one=>one.path),checkoutsKept:pruned.kept,processesStopped:[...closedRuns.map(one=>({run:one.runId,pids:one.done.stopped.map(row=>row.pid)})),...closedCheckouts.map(one=>({checkout:one.path,pids:one.done.stopped.map(row=>row.pid)}))],checkoutsSlimmed:slimmed.slimmed.map(one=>one.path),landed:{completed:landed.completed,steps:landed.steps},tidied:tidied.map(one=>({id:one.taskId,rule:one.rule,reason:one.reason})),liveViewsSwept:liveSwept.removed.length,retention:retention===null?null:{counts:retention.counts,freedBytes:retention.freed},storageSweep:storageSwept},()=>nothing?["Nothing to reconcile. Everything is where it should be."]:[...recovered.map(one=>`Recovered ${one.runner}: ${one.claims.length} claim(s) requeued, ${one.worktrees.length} worktree(s) handed back unverified.`),...reaped.length===0?[]:[`Reaped ${reaped.length} expired lease(s).`],...adoption.adopted.map(path=>`Adopted ${path} — released, unverified, somebody should look.`),...adoption.forgotten.map(path=>`Forgot ${path} — its directory is gone.`),...pruned.removed.length===0?[]:[`Removed ${pruned.removed.length} finished task checkout(s), about ${bytesWords(pruned.freed)}; their branches stay.`],...closedRuns.map(one=>`Run #${one.runId} ended; stopped ${stoppedWords(one.done)}.`),...closedCheckouts.map(one=>`${one.path}: its task finished; stopped ${stoppedWords(one.done)}.`),...landed.completed.length===0?[]:[`Marked ${landed.completed.length} landed result(s) complete: ${landed.completed.join(", ")}.`],...tidied.length===0?[]:[`Put away ${tidied.length} old task(s): ${tidied.map(one=>one.taskId).join(", ")}.`],...landedGone.length===0?[]:[`Removed landed work: ${landedGone.filter(one=>one.kind==="checkout").length} checkout(s), ${landedGone.filter(one=>one.kind==="branch").length} local branch(es).`],...slimmed.slimmed.length===0?[]:[`Dropped dependencies and build output from ${slimmed.slimmed.length} kept checkout(s), about ${bytesWords(slimmed.slimmed.reduce((sum,one)=>sum+one.bytes,0))}.`],...liveSwept.removed.length===0?[]:[`Cleared ${liveSwept.removed.length} finished live view(s).`],...retention===null||retained.length===0?[]:[`Retention removed ${sweepWords(retention.counts,retention.freed)}.`],...storageSwept===null||swept.length===0?[]:[`Storage sweep: ${storageSweepWords(storageSwept.parts)}`]])}function gapsCommand(flags,context){const{store,write,json,clock}=context,repo=repoFrom(flags),gaps=computeGaps(store,repo,clock());if(json)return write(envelopeJson({ok:!0,command:"gaps",repo,gaps})),gaps.length===0?EXIT.ok:EXIT.refused;if(gaps.length===0)return write(`No gaps for ${repo}. Everything recorded is verified.`),EXIT.ok;for(const gap of gaps){const freed=gap.unblocks.length>0?`fills → ${gap.unblocks.length} task(s) start: ${gap.unblocks.join(", ")}`:gap.alsoBlocks.length>0?`part of what holds: ${gap.alsoBlocks.join(", ")}`:"nothing queued needs it yet";write(` ${gap.key.padEnd(28)} ${gap.state}`),write(` ${freed}`),write(` verify: ${gap.verify}`),write(` ${gap.instructions}`)}return EXIT.refused}async function briefCommand(flags,context){const{store,write,json,clock}=context,repo=repoFrom(flags),episode=flags.has("latest-watch")?store.latestWatchEpisode(repo):null;if(flags.has("latest-watch")&&episode===null)return fail(write,json,"brief","no-watch","no watch episode recorded for this repo yet — run `toolroll watch` first",EXIT.refused);const since=episode?.startedAt??text(flags,"since")??new Date(clock().getTime()-1440*6e4).toISOString();let runs=store.runsSince(since);episode!==null&&(runs=runs.filter(one=>one.runner===episode.runner&&(episode.endedAt===null||one.startedAt<=episode.endedAt)));const{built,failed,refused,cutDown,invoked,measured,spend,tokens}=tally(runs),gaps=computeGaps(store,repo,clock()),pending=store.pendingForAttention(),decisions=store.listDecisions("unanswered"),incidents=store.openIncidents(),stranded=store.strandedTasks();let review;if(flags.has("local"))review={state:"not-read",why:"--local, the network was not asked"};else{const read=await readPulls(repo);review=read.problems.length>0&&read.pulls.length===0?{state:"not-read",why:read.problems[0]??"unreadable"}:{state:"read",pulls:read.pulls.map(one=>({number:one.number,title:one.title}))}}if(json)return write(envelopeJson({ok:!0,command:"brief",repo,since,episode,tally:{built,failed,refused,cutDown},economics:{invocations:invoked.length,measured:measured.length,costUsd:spend,tokens},gaps,review,outboxPending:pending.length,decide:decisions,incidents,stranded})),EXIT.ok;const lines=[`toolroll — the report ─ ${repo}`];episode!==null&&lines.push(` episode watch #${episode.id} on ${episode.runner} · ${episode.startedAt} → ${episode.endedAt??"never ended — it is running, or it died without saying"}`),lines.push(` runs ${built.length} built · ${failed.length} failed · ${refused.length} refused${cutDown.length>0?` · ${cutDown.length} cut down mid-flight`:""}`);const proofVerdicts=store.proofVerdictsFor(built.map(one=>one.id));for(const one of built){const verdict=proofVerdicts.get(one.id),accepted=verdict!==void 0&&store.proofAcceptance(one.id)!==null,proofNote=verdict===void 0||accepted||verdict.verdict!=="short"&&verdict.verdict!=="refuted"?"":` — ${proofVerdictWords(verdict.verdict,verdict.reasons).word}`;lines.push(` ${one.taskId.padEnd(20)} ${one.committed===!0?`committed to ${one.branch}`:"changed nothing, which is a real answer"}${proofNote}`)}for(const one of failed)lines.push(` ${one.taskId.padEnd(20)} failed: ${one.reason??"?"}${one.worktree===null?"":` — work kept in ${one.worktree}`}`);for(const one of cutDown)lines.push(` ${one.taskId.padEnd(20)} never finished — the process died with it; \`task show ${one.taskId}\``);if(lines.push(` spend ${spendLine({built,failed,refused,cutDown,invoked,measured,spend,tokens})}`),gaps.length>0){const best=gaps[0];lines.push(` ▸ BLOCKED ${gaps.length} gap(s)${best.unblocks.length>0?` — filling ${best.key} starts ${best.unblocks.length} task(s)`:""}`);for(const gap of gaps)lines.push(` ${gap.key.padEnd(28)} ${gap.state}`);lines.push(` → toolroll gaps --repo ${repo}`)}if(lines.push(review.state==="read"?` ▸ REVIEW ${review.pulls.length} PR(s)${review.pulls.length>0?"":" — nothing waits"}`:` ▸ REVIEW not read — ${review.why}`),review.state==="read")for(const pull of review.pulls)lines.push(` #${pull.number} ${pull.title}`);if(pending.length>0&&lines.push(` ▸ OUTBOX ${pending.length} undelivered — toolroll outbox list`),decisions.length>0){const overdue=decisions.filter(one=>one.state==="expired").length;lines.push(` ▸ DECIDE ${decisions.length} waiting${overdue>0?` (${overdue} overdue)`:""} — toolroll decide`);for(const one of decisions)lines.push(` ${String(one.id).padEnd(4)} ${one.taskId.padEnd(20)} ${one.question}`)}else lines.push(" ▸ DECIDE nothing waits on you");if(stranded.length>0){lines.push(` ▸ STRANDED ${stranded.length} task(s) behind failed blockers — they will never become ready on their own`);for(const one of stranded)lines.push(` ${one.id.padEnd(20)} waits on ${one.blockedBy.join(", ")} — \`toolroll task requeue ${one.blockedBy[0]}\``)}if(incidents.length>0){lines.push(` ▸ INCIDENTS ${incidents.length} unresolved — these do not age out`);for(const incident of incidents)lines.push(` ${incident.taskId.padEnd(20)} ${incident.kind} since ${incident.createdAt} — read run ${incident.run}'s evidence, then \`toolroll incident resolve ${incident.id}\``)}return write(lines.join(`
|
|
479
479
|
`)),EXIT.ok}async function decideCommand(positional,flags,context){const{store,write,json,clock}=context;store.expireOverdueDecisions(clock());const[idText]=positional;if(idText===void 0){const waiting=store.listDecisions("unanswered");if(json)return write(envelopeJson({ok:!0,command:"decide",waiting})),waiting.length===0?EXIT.ok:EXIT.refused;if(waiting.length===0)return write("Nothing waits on you. No decisions were parked."),EXIT.ok;for(const one of waiting){const overdue=one.state==="expired"?" OVERDUE":"";write(` ${String(one.id).padEnd(4)} ${one.taskId.padEnd(20)} ${one.question}${overdue}`),write(` options: ${one.options.map(option=>option.id).join(" · ")} recommended: ${one.recommendation}`)}return write(""),write(" → toolroll decide <id> the whole screen"),write(" → toolroll decide <id> --choose <option> --as <you> --token <t>"),EXIT.refused}const id=Number(idText);if(!Number.isInteger(id)||id<=0)return fail(write,json,"decide","usage","`toolroll decide [<id>] [--choose <option>]`",EXIT.usage);const decision=store.getDecision(id);if(decision===null)return fail(write,json,"decide","unknown-decision",`no decision ${id}`,EXIT.refused);const choice=text(flags,"choose");if(choice===void 0){const evidence=store.evidenceFor(id),run2=store.getRun(decision.run),taskId=run2===null?"?":store.externalIdFor(run2.taskRef)??"?";if(json)return write(envelopeJson({ok:!0,command:"decide",decision,taskId,evidence})),EXIT.ok;write(`${taskId} — ${decision.supersededReason!==null?"CLOSED":decision.state.toUpperCase()}${decision.deadline===null?"":` · deadline ${decision.deadline}`}`),write(""),write(` ${decision.recap}`),write(""),write(` ${decision.question}`),write("");for(const option of decision.options){const marks=[option.id===decision.recommendation?"recommended":"",option.reversible?"reversible":"IRREVERSIBLE"].filter(mark=>mark!=="").join(" · ");write(` [${option.id}] ${option.label} (${marks})`),write(` ${option.consequence}`)}if(decision.state==="answered"&&(write(""),write(decision.supersededReason!==null?` ${closedQuestionWords(decision.supersededReason)} (${decision.answeredAt})`:` answered: ${decision.choice} by ${decision.answeredBy} at ${decision.answeredAt}${decision.note===null?"":` — ${decision.note}`}`)),evidence.length>0){write("");for(const artifact of evidence)write(` evidence ${artifact.kind.padEnd(14)} ${artifact.key}${artifact.truncated?" (truncated)":""}`)}return decision.state!=="answered"&&(write(""),write(` → toolroll decide ${id} --choose <option> --as <you> --token <t>`)),EXIT.ok}const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"decide",verified,"answering takes `--as <you> --token <t>` — who decided is recorded, not asserted",String(id));const{name:asWho}=acting,note=text(flags,"note"),answered=store.answerDecision({id,choice,by:asWho,via:"cli",...note===void 0?{}:{note}},clock(),mutationFrom(flags,clock()));if(!answered.ok){const why=answered.reason==="bad-option"?`"${choice}" is not one of this decision's options — \`toolroll decide ${id}\` shows them`:answered.reason==="already-answered"?`decision ${id} was already answered differently — "decided" is not negotiable; park a new task if the answer must change`:answered.reason==="closed"?`decision ${id}: ${closedQuestionWords(store.getDecision(id)?.supersededReason??"cancelled")} Nothing to answer.`:answered.reason==="bad-note"?"the note is too long or carries control characters":`no decision ${id}`;return fail(write,json,"decide",answered.reason,why,EXIT.refused)}return succeed(write,json,"decide",{decision:answered.decision,duplicate:answered.duplicate===!0},()=>answered.duplicate===!0?[`Decision ${id} was already answered with ${choice} — nothing changed.`]:[`Decided: ${choice} for decision ${id}, as ${asWho}.`,"The task returns to the ready set; the next tick resumes it with your answer in hand."])}export async function startConsole(options){const{context}=options,rehearsal=options.rehearsal===!0;rehearsal||noticeGitIncidents(context.store,context.clock);const identities=projectIdentities(context.folderLook),server=createDecisionServer({identities,store:context.store,backgroundChecks:!rehearsal,...rehearsal?{rehearsal:!0}:{},...context.desktopIdentity===void 0?{}:{desktopIdentity:context.desktopIdentity},...context.additionalProjectRepos===void 0||options.currentRepos===void 0?{}:{additionalProjectRepos:options.currentRepos},evidenceRoot:context.evidenceRoot,clock:context.clock,telegramTokenFile:context.telegramTokenFile,configDir:dirname(context.databaseFile),browserAssetCache:join(dirname(context.databaseFile),"browser-assets"),...options.localRunner===void 0?{}:{localRunner:options.localRunner},poolRoot:options.poolRoot,...options.allowedHosts===void 0?{}:{allowedHosts:options.allowedHosts},tailnetNames:rehearsal?(async()=>[]):context.tailnetNames??(()=>readTailnetNames()),leadByDefault:!0,...options.setupCode===void 0?{}:{setupCode:options.setupCode},...options.repos===void 0?{}:{repos:options.repos},...options.projectRoots===void 0?{}:{projectRoots:options.projectRoots},...options.currentRepos===void 0?{}:{currentRepos:options.currentRepos},...options.admittedRepos===void 0?{}:{admittedRepos:options.admittedRepos},...options.publicUrl===void 0?{}:{publicUrl:options.publicUrl},...options.registryPath===void 0?{}:{registryPath:options.registryPath},...options.upConsole===void 0?{}:{upConsole:options.upConsole},...options.editorLinks===void 0?{}:{editorLinks:options.editorLinks},...options.instanceSecret===void 0?{}:{instanceSecret:options.instanceSecret},...options.draining===void 0?{}:{draining:options.draining},...options.keyEpoch===void 0?{}:{keyEpoch:options.keyEpoch},browserKey:!0});await new Promise((resolve2,reject)=>{server.once("error",reject),server.listen(options.port,options.host,()=>resolve2())}).catch(error=>{throw new Error(`could not listen on ${options.host}:${options.port} — ${describe(error)}`)});const bound=server.address(),port=typeof bound=="object"&&bound!==null?bound.port:options.port,shown=options.host==="0.0.0.0"||options.host==="::"?"localhost":options.host;if(setImmediate(warmWorkspaceRenderer),rehearsal)return{server,port,url:`http://${shown}:${port}/`};consoleIdentitiesInBackground(identities,[...options.repos??[],...options.projectRoots??[],...context.store.listProjects().map(one=>one.path),...context.store.knownRepos()]);const stopMonitoring=startMonitoring({store:context.store,settings:()=>readMonitoring(dirname(context.databaseFile)),instance:options.publicUrl??hostname(),version:packageVersion()}),signIns=createConnectionChecker({store:context.store}),besideConsole=[stopMonitoring,startBudgetAlerts(context.store),startTokenNotices(context.store),startSignInProbes(context.store,signIns),startBackups(context.store,context.databaseFile),startCodexLimits(context.store,()=>codexSignedInNow(signIns)),startUpdateChecks(context.store,dirname(context.databaseFile),PACKAGE_VERSION,installMethod(context.installBin).updateCommand,context.releaseIo??{})];return server.on("close",()=>{for(const stop of besideConsole)stop()}),{server,port,url:`http://${shown}:${port}/`}}async function serveCommand(flags,context){const{store,write,json}=context,portGiven=text(flags,"port"),port=Number(portGiven??4180),rehearsal=flags.get("rehearsal")===!0;if(portGiven!==void 0&&(!Number.isInteger(port)||port<(rehearsal?0:1)||port>=65536))return fail(write,json,"serve","usage","--port is a whole number under 65536",EXIT.usage);const host=text(flags,"host")??"127.0.0.1";if(rehearsal&&(host!=="127.0.0.1"||["allow-host","public-url","runner","editor","repo","project-root"].some(one=>flags.has(one))))return fail(write,json,"serve","usage","--rehearsal serves 127.0.0.1 only, with no --allow-host, --public-url, --runner, --editor, --repo or --project-root",EXIT.usage);const allow=text(flags,"allow-host"),repoFlag=text(flags,"repo"),rootFlag=text(flags,"project-root"),localRunner=text(flags,"runner"),poolRoot=text(flags,"pool")??join(dirname(context.databaseFile),"worktrees"),publicUrl=text(flags,"public-url"),editor=text(flags,"editor");if(editor!==void 0&&editor!=="vscode")return fail(write,json,"serve","usage","--editor supports: vscode",EXIT.usage);if(editor!==void 0&&localRunner===void 0)return fail(write,json,"serve","usage","--editor needs --runner <name> — links bind to the worktrees this machine's runner owns",EXIT.usage);const setupCode=store.listApprovers().length===0?String(randomInt(1e5,1e6)):void 0,console_=await startConsole({context,host,port,...rehearsal?{rehearsal:!0}:{},...setupCode===void 0?{}:{setupCode},...localRunner===void 0?{}:{localRunner},...publicUrl===void 0?{}:{publicUrl},...editor===void 0?{}:{editorLinks:"vscode"},registryPath:registryPathOf(context),poolRoot,...allow===void 0?{}:{allowedHosts:allow.split(",")},...repoFlag===void 0?{}:{repos:repoFlag.split(",").map(one=>one.trim()).filter(one=>one!=="")},...rootFlag===void 0?{}:{projectRoots:rootFlag.split(",").map(one=>one.trim()).filter(one=>one!=="")}}),server=console_.server,actual=console_.port,serveLifecycle=serveConsoleLifecycle(store,host,actual,context.clock);return serveLifecycle===null?(await closeServedConsole(server),fail(write,json,"serve","lifecycle","Toolroll couldn't record that this console is running, so it didn't start. Check the database, then run it again.",EXIT.refused)):(json?write(envelopeJson({ok:!0,command:"serve",host,port:actual,...setupCode===void 0?{}:{setupCode}})):setupCode!==void 0?(write(`The console is on http://${host}:${actual}/`),write(`No account yet. Open http://${host==="0.0.0.0"?"localhost":host}:${actual}/login and enter setup code ${setupCode} to create the first one.`),write("Plain HTTP: keep it on localhost or a tailnet, and put TLS in front for anything else."),write("Ctrl-C stops it.")):(write(`The console is on http://${host}:${actual}/ — sign in with your username and password.`),write("Plain HTTP: keep it on localhost or a tailnet, and put TLS in front for anything else."),write("Ctrl-C stops it.")),await new Promise(resolve2=>{const stop=()=>server.close(()=>resolve2());process.once("SIGINT",stop),process.once("SIGTERM",stop)}),serveLifecycle(),EXIT.ok)}async function requeueTask(positional,flags,context){const{store,write,json,clock}=context,[id]=positional;if(id===void 0)return fail(write,json,"task requeue","usage","`toolroll task requeue <id> --as <you> --token <t>`",EXIT.usage);const passwordFree=passwordFreeRefusal(store,flags,"r",context.principal!==void 0);if(passwordFree!==null)return fail(write,json,"task requeue","local-owner",passwordFree,EXIT.refused);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"task requeue",verified,"requeueing takes `--as <you> --token <t>` — who overrode the stall is recorded, not asserted",id);const{name:asWho}=acting,result=store.requeueTask(id,asWho,clock());if(!result.ok){const why={"unknown-task":`no task ${id}`,"not-stalled":`${id} has nothing to rerun: it is queued or running, or it finished without a rejected result`,claimed:`a runner holds ${id} right now — wait for the attempt to end, or stop it`,"accepted-result":`${id}'s last result was accepted; change it through a revision, not a rerun`,published:`${id}'s last result is published; revise it through its pull request`,moved:`${id} changed since its page was read; read it again`,stale:`${id} changed since its page was read; read it again`,archived:`${id} is put away — restore it with \`toolroll task restore ${id}\` first`};return fail(write,json,"task requeue",result.reason,why[result.reason],EXIT.refused)}return succeed(write,json,"task requeue",{id,resolvedIncidents:result.resolvedIncidents,rejectedRun:result.rejectedRun},()=>[result.rejectedRun!==null?`${id} is queued again: attempt #${result.rejectedRun} was not accepted, so the next attempt continues on the same branch under the current scope. Re-scope first if the candidate changed.`:`${id} is queued again${result.resolvedIncidents>0?`, ${result.resolvedIncidents} incident(s) resolved`:""}. Strikes cleared; the next pass may take it.`])}async function regateTaskCommand(positional,flags,context){const{store,write,json,clock}=context,[id]=positional;if(id===void 0)return fail(write,json,"task regate","usage","`toolroll task regate <id> --as <you> --token <t>`",EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"task regate",verified,"rerunning the check takes `--as <you> --token <t>` — the rerun scope is approved in your name",id);const result=regateTask(store,id,clock(),{kind:"operator",name:acting.name,token:acting.token});return result.ok?succeed(write,json,"task regate",{id,run:result.run,head:result.head},()=>[`${id} is queued again: the approved check runs on commit ${result.head.slice(0,7)}, the same files attempt #${result.run} checked, with no agent. A fresh review follows.`]):fail(write,json,"task regate",result.reason,result.message,EXIT.refused)}async function planTaskCommand(positional,flags,context){const{store,write,json,clock}=context,[id]=positional;if(id===void 0)return fail(write,json,"task plan","usage","`toolroll task plan <id> --as <you> --token <t>`",EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"task plan",verified,"planning takes `--as <you> --token <t>` — it dispatches an agent that spends",id);if(store.getTask(id)===null)return fail(write,json,"task plan","refused",`no task ${id}`,EXIT.refused);const ref=store.refFor(BUILT_IN,id),pinProvider=text(flags,"provider"),pinModel=text(flags,"model");if(pinProvider!==void 0){if(!isProviderId(pinProvider))return fail(write,json,"task plan","usage",`unknown provider \`${pinProvider}\``,EXIT.usage);if(pinModel===void 0||pinModel==="")return fail(write,json,"task plan","usage","a plan pin names an exact --model with --provider — approvals bind exact routing",EXIT.usage);const valid=validateSpec({provider:pinProvider,model:pinModel});if(!valid.ok)return fail(write,json,"task plan","invalid",valid.problem,EXIT.usage);if(!store.setPlanPins(ref.id,pinProvider,pinModel,clock()).ok)return fail(write,json,"task plan","refused","a planner holds this task right now — the pin would reroute a live spend",EXIT.refused)}else if(pinModel!==void 0)return fail(write,json,"task plan","usage","--model rides --provider for a plan pin",EXIT.usage);const result=store.requestPlan(ref.id,clock());if(!result.ok)return fail(write,json,"task plan","refused",result.reason,EXIT.refused);const autoPlan=authorizePlanUnderMode(store,id,acting.name,clock());return succeed(write,json,"task plan",{id,autoPlan,...pinProvider===void 0?{}:{planProvider:pinProvider,planModel:pinModel??null}},()=>[`${id} will be planned before it is built: the next pass dispatches a planner${pinProvider===void 0?"":` on ${pinProvider}${pinModel===void 0?"":` · ${pinModel}`}`}.`,autoPlan?"An unchanged, verified plan can auto-approve under your signed mode. Amendments and questions still wait for you.":"Its questions reach you like any decision; its plan lands as a scope for you to edit and approve."])}async function reviewTaskCommand(positional,flags,context){const{store,write,json}=context;if(flags.has("brief")){const allowed=new Set(["brief","all","run","json","db","as","token"]);for(const name of flags.keys())if(!allowed.has(name))return fail(write,json,"task review","usage",`--${name} is not a task review --brief option.`,EXIT.usage);const task=positional[0],selected=flags.get("run");if(positional.length!==1||!task||task.length>64||/[\x00-\x1f\x7f]/.test(task)||selected!==void 0&&(typeof selected!="string"||!/^[1-9]\d*$/.test(selected)||!Number.isSafeInteger(Number(selected))))return fail(write,json,"task review","usage","Use toolroll task review <task> --brief [--run <id>] [--all] [--json].",EXIT.usage);let viewer=currentActor()?.account??null;if(viewer===null&&(flags.has("as")||flags.has("token"))){const acting=await askCredentials(flags,context);if(acting===null||!authenticateApprover(store,acting.name,acting.token).ok)return fail(write,json,"task review","unauthenticated","That sign-in is not valid.",EXIT.refused);viewer=acting.name}const repos=viewer===null?null:store.knownRepos().filter(repo=>store.accountCanAccess(viewer,repo)),result=taskReviewBrief(store,task,context.evidenceRoot,context.now,{principal:"operator",repos,includeUnplaced:viewer===null},{...selected===void 0?{}:{run:Number(selected)},all:flags.has("all"),secrets:[context.leadToken??"",text(flags,"token")??""]});return result.ok?succeed(write,json,"task review",{brief:result.brief},()=>renderReviewBrief(result.brief)):fail(write,json,"task review",result.reason,result.message,EXIT.refused)}if(flags.has("run")||flags.has("all"))return fail(write,json,"task review","usage","--run and --all require --brief.",EXIT.usage);const[runText]=positional,runId=Number(runText??"");if(runText===void 0||!Number.isInteger(runId)||runId<1)return fail(write,json,"task review","usage","`toolroll task review <run-id>`",EXIT.usage);const review=buildReviewOf(store,runId);return review!==null?succeed(write,json,"task review",{run:runId,review},()=>[`Run ${runId}`,...buildReviewLines(review)]):fail(write,json,"task review","model-review-retired",`Run ${runId} has no automatic review. Manual review requests have been removed; a project's builds are reviewed automatically when its switch is on (\`toolroll review on --repo <path>\`). Inspect the saved work and checks, then give feedback or request a revision.`,EXIT.refused)}async function incidentCommand(positional,flags,context){const{store,write,json,clock}=context,[action,idText]=positional;if(action===void 0||action==="list"){const incidents=store.openIncidents();if(json)return write(envelopeJson({ok:!0,command:"incident list",incidents})),incidents.length===0?EXIT.ok:EXIT.refused;if(incidents.length===0)return write("No unresolved incidents."),EXIT.ok;for(const incident of incidents)write(` ${String(incident.id).padEnd(4)} ${incident.taskId.padEnd(20)} ${incident.kind} since ${incident.createdAt} run ${incident.run}`);return write(""),write(" → toolroll incident resolve <id> --as <you> --token <t>"),EXIT.refused}if(action!=="resolve")return fail(write,json,"incident","usage","`toolroll incident [list|resolve <id>]`",EXIT.usage);const id=Number(idText);if(!Number.isInteger(id)||id<=0)return fail(write,json,"incident resolve","usage","`toolroll incident resolve <id> --as <you> --token <t>`",EXIT.usage);const passwordFree=passwordFreeRefusal(store,flags,"r",context.principal!==void 0);if(passwordFree!==null)return fail(write,json,"incident resolve","local-owner",passwordFree,EXIT.refused);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"incident resolve",verified,"resolving takes `--as <you> --token <t>` — who looked is recorded, not asserted",String(id));const{name:asWho}=acting;return store.resolveIncident(id,asWho,clock())?succeed(write,json,"incident resolve",{id,by:asWho},()=>[`Resolved incident ${id}, as ${asWho}. The task's hold is lifted; the next tick may take it.`]):fail(write,json,"incident resolve","unknown-or-resolved",`no unresolved incident ${id}`,EXIT.refused)}async function webhookCommand(positional,_flags,context){const{write,json}=context,dir=dirname(context.databaseFile),[action,which,value]=positional,telegramConfigured=loadBotToken(process.env,context.telegramTokenFile)!==null;if(action===void 0||action==="status"){const consoleUrl=loadConsoleUrl(process.env,dir),primary=effectivePrimary(process.env,dir,telegramConfigured);if(json)return write(envelopeJson({ok:!0,command:"webhook status",configured:primary.configured,primary:primary.channel,implicit:primary.implicit,consoleUrl})),EXIT.ok;write(`Messaging${primary.configured.length===0?": nothing configured":""}`);for(const channel of primary.configured)write(` ${channel.padEnd(8)} connected${channel===primary.channel?" ← receives alerts":" (silent — not primary)"}`);return primary.implicit&&primary.channel!==null&&(write(` ! several services are connected and none was chosen — ${primary.channel} receives alerts by default.`),write(" Choose: toolroll webhook primary telegram|slack|discord")),write(` links ${consoleUrl??"NOT SET — messages will carry no console link; toolroll webhook set console-url http://host:port"}`),EXIT.ok}if(action==="primary")return which===void 0||!isMessagingChannel(which)?fail(write,json,"webhook primary","usage","primary is one of telegram, slack, discord",EXIT.usage):effectivePrimary(process.env,dir,telegramConfigured).configured.includes(which)?(savePrimary(dir,which),succeed(write,json,"webhook primary",{primary:which},()=>[`Alerts now go to ${which}. ${which==="telegram"?"Buttons and replies work there as always.":"Telegram (if configured) still accepts taps and replies — it just stops sending alerts."}`])):fail(write,json,"webhook primary","unconfigured",`${which} is not configured — set it up first, then choose it`,EXIT.refused);if(action!=="set"||which!=="console-url"||value===void 0)return fail(write,json,"webhook","usage","`toolroll webhook [status|primary <service>|set console-url <url>]`",EXIT.usage);const saved=saveConsoleUrl(dir,value);return saved.ok?succeed(write,json,"webhook set",{which},()=>[`Console links will open ${value.replace(/\/+$/,"")}.`]):fail(write,json,"webhook set","invalid",saved.message,EXIT.usage)}function resumeProviderCommand(positional,flags,context){const{store,write,json}=context,command="providers resume",provider=positional[0];if(provider===void 0||!isProviderId(provider)||positional.length>1)return fail(write,json,command,"usage",`Use \`toolroll providers resume <${PROVIDER_IDS.join("|")}>\`.`,EXIT.usage);const who=text(flags,"as")??process.env.USER??"operator",lifted=liftAuthPause(store,provider,"person",who,context.clock());return lifted===null?succeed(write,json,command,{provider,resumed:0,paused:!1},()=>[`${provider} is not paused.`]):succeed(write,json,command,{provider,resumed:lifted.resumed,paused:!1},()=>[`${provider} resumed — ${lifted.resumed} ${lifted.resumed===1?"task":"tasks"} can start again.`])}async function providersCommand(flags,context){const{store,write,json}=context,probe=context.gitRunner??run,configured=new Map;for(const scope of[INSTALLATION_SCOPE])for(const row of store.listPhaseConfig(scope))configured.set(row.provider,[...configured.get(row.provider)??[],row.phase]);const probed=await Promise.all(PROVIDER_IDS.map(async id=>{const facts=inspectionOf(id);if(isAcpProvider(id)){const seen=resolveAcpAgentForRunner(id),version2={code:seen.found?0:127,stdout:seen.found?seen.package?.version??"":"",stderr:"",notFound:!seen.found,timedOut:!1};return{id,facts,version:version2,installed:seen.found,identity:seen.found?`not checked on this computer — run \`toolroll agents check ${id}\``:null}}const version=await probe(facts.binary,["--version"],{timeoutMs:5e3,omitEnv:ALL_CREDENTIAL_ENV}),installed=version.code===0&&!version.notFound;let identity=null;if(installed&&facts.identityProbe!==null){const asked=await probe(facts.binary,[...facts.identityProbe],{timeoutMs:5e3,omitEnv:ALL_CREDENTIAL_ENV});identity=asked.code===0?asked.stdout.trim().split(`
|
|
480
480
|
`)[0]??null:"not logged in"}return{id,facts,version,installed,identity}})),report=[];for(const{id,facts,version,installed,identity}of probed){const lastSuccess=store.providerLastSuccess(id),keyPresent=facts.requiresEnv===null?null:(process.env[facts.requiresEnv]??"")!=="",installedVersion=installed?version.stdout.trim().split(`
|
|
481
481
|
`)[0]??"":null;report.push({provider:id,binary:facts.binary,installed,version:installedVersion,identity,lastSuccessfulRun:lastSuccess,...keyPresent===null?{}:{keyPresent,keyEnv:facts.requiresEnv},measuresCost:facts.measuresCost,configuredPhases:configured.get(id)??[],audit:auditOf(id),...attestationOf(id)===null?{}:{attestation:{...attestationOf(id),installedInRange:installed&&versionInRange(version.stdout.trim().split(`
|
|
@@ -488,7 +488,7 @@ Add --json for a machine-readable envelope.`:command==="flows"?FLOWS_HELP:comman
|
|
|
488
488
|
${quick.command}
|
|
489
489
|
timeout ${Math.round(quick.timeoutMs/1e3)}s · digest ${quick.digest} · approved by ${quick.approvedBy}`):level.level==="quick"&&write(`No quick command yet, so Quick runs the full check.${suggestion===null?"":` Suggested from the project's scripts:
|
|
490
490
|
toolroll verify set --repo ${repo} --quick "${suggestion}"`}`),EXIT.ok)}if(action==="level"){if(repo===void 0)return fail(write,json,"verify level","usage","which repo? --repo <path>",EXIT.usage);const wanted=positional[1];if(!isCheckLevel(wanted))return fail(write,json,"verify level","usage","`toolroll verify level quick|full|off --repo <path> --as <you> --token <t>`",EXIT.usage);if(passwordFreeInstall(store,flags,context.principal!==void 0))return fail(write,json,"verify level","local-owner","Changing a check needs a password. Run `toolroll password set` first.",EXIT.refused);const acting2=await askCredentials(flags,context);if(acting2===null)return fail(write,json,"verify level","usage","changing a project's checks takes `--as <you> --token <t>`",EXIT.usage);const authenticated=authenticateApprover(store,acting2.name,acting2.token,repo);if(!authenticated.ok)return fail(write,json,"verify level",authenticated.reason,describeApproveFailure(authenticated.reason,repo),EXIT.refused);const changed=setProjectCheckLevel(store,repo,wanted,acting2.name,clock()),runsFull=wanted==="quick"&&liveQuickCommand(store,repo)===null;return succeed(write,json,"verify level",{repo,level:wanted,before:changed.before,changed:changed.changed},()=>[`${repo}: checks are ${CHECK_LEVEL_WORDS[wanted]}${changed.changed?` (was ${CHECK_LEVEL_WORDS[changed.before]})`:""}. ${CHECK_LEVEL_HINTS[wanted]}`,...runsFull?[`No quick command is approved yet, so builds run the full check. Approve one with \`toolroll verify set --repo ${repo} --quick "<cmd>"\`.`]:[],...wanted!=="full"?["The full check still runs when a pull request opens, and Merge waits for it unless a person merges anyway."]:[]])}if(action!=="set"&&action!=="clear")return fail(write,json,"verify","usage","`toolroll verify [show|level quick|full|off|set --command <cmd>|--quick <cmd> [--timeout-seconds <n>] [--self-heal --setup-digest <shown>] --yes|clear [--level quick]] --repo <path> --as <you> --token <t>`",EXIT.usage);const quickValue=text(flags,"quick"),quickClear=action==="clear"&&text(flags,"level")==="quick",grantKey=repo===void 0?void 0:quickValue!==void 0||quickClear?quickVerifyKey(repo):repo;if(repo===void 0)return fail(write,json,`verify ${action}`,"usage","which repo? --repo <path>",EXIT.usage);if(passwordFreeInstall(store,flags,context.principal!==void 0))return fail(write,json,`verify ${action}`,"local-owner",`${action==="set"?"Setting":"Clearing"} a check needs a password. Run \`toolroll password set\` first.`,EXIT.refused);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,`verify ${action}`,verified,"an approved verification command runs unattended after every future build — changing it takes `--as <you> --token <t>`",repo);if(action==="clear"){legacy!==null&&!quickClear&&store.clearVerifyCommand(legacy,acting.name,clock());const cleared=store.clearVerifyCommand(grantKey,acting.name,clock())||legacy!==null&&!quickClear;return quickClear?succeed(write,json,"verify clear",{repo,cleared,level:"quick"},()=>[cleared?`Cleared the quick command — Quick builds of ${repo} run the full check now.`:`No quick command was set for ${repo}.`]):succeed(write,json,"verify clear",{repo,cleared},()=>[cleared?`Cleared — builds of ${repo} land "attested" at best now; nothing re-runs.`:`Nothing was set for ${repo}.`])}const command=quickValue??text(flags,"command");if(quickValue!==void 0&&text(flags,"command")!==void 0)return fail(write,json,"verify set","usage",'give the quick command with --quick "<cmd>" or the full one with --command, not both',EXIT.usage);if(quickValue!==void 0&&flags.get("self-heal")===!0)return fail(write,json,"verify set","usage","--self-heal applies to the full command only",EXIT.usage);if(command===void 0||command.trim()==="")return fail(write,json,"verify set","usage","--command <cmd> is what the plane re-runs after every commit",EXIT.usage);if(command.length>2e3||hasDisguisedText(command))return fail(write,json,"verify set","invalid","the command must be under 2000 characters with no control or bidi characters",EXIT.usage);if(/([A-Za-z0-9_-]*(?:token|secret|password|passwd|apikey|api_key|authorization|bearer|credential)[A-Za-z0-9_-]*\s*[=:]\s*)(?![$"']?\$)\S+/i.test(command)||/\/\/[^\s/@]+:[^\s/@]+@/.test(command))return fail(write,json,"verify set","credential-shaped","the command appears to embed a credential — reference an environment variable the runner exports (e.g. $NPM_TOKEN) instead of a literal value",EXIT.usage);const timeoutSeconds=Number(text(flags,"timeout-seconds")??"300");if(!Number.isInteger(timeoutSeconds)||timeoutSeconds<1||timeoutSeconds>3600)return fail(write,json,"verify set","invalid","--timeout-seconds is 1..3600",EXIT.usage);const selfHeal=flags.get("self-heal")===!0,expectedSetupDigest=text(flags,"setup-digest");if(!selfHeal&&expectedSetupDigest!==void 0)return fail(write,json,"verify set","usage","--setup-digest is only valid with --self-heal",EXIT.usage);const recoverySetup=selfHeal?store.liveWorktreeSetup(repo):null;if(selfHeal&&recoverySetup===null)return fail(write,json,"verify set","setup-required","self-healing needs an approved project setup first — set the exact preparation command, then approve verification again with --self-heal",EXIT.refused);if(flags.get("yes")!==!0){if(json)return write(envelopeJson({ok:!1,command:"verify set",reason:"unconfirmed",repo,...quickValue===void 0?{}:{level:"quick"},verifyCommand:command,timeoutSeconds,selfHeal,recoverySetup:recoverySetup===null?null:{command:recoverySetup.command,digest:recoverySetup.digest}})),EXIT.refused;for(const line of["The terms, exactly:",` repo ${repo}`,` command ${command}`,` timeout ${timeoutSeconds}s`,"",quickValue===void 0?"Every FUTURE build of this repo re-runs this command unattended,":"Every FUTURE Quick build of this repo runs this command unattended,","once, right after it commits — under an ALLOWLISTED environment","(PATH, HOME, locale, temp — no credentials). A pass lands the",'build "verified"; a failure lands it "refuted", never blocked.',...recoverySetup===null?[]:["","Self-healing, exactly: if this check cannot start because a","required project executable is unavailable, Toolroll may replay",`the approved setup \`${recoverySetup.command}\` (digest ${recoverySetup.digest}) once,`,"then retry this exact check once. It stops if custody changes,","setup fails, or setup changes tracked files after the commit."],recoverySetup===null?"Re-run with --yes to approve.":`Re-run with --setup-digest ${recoverySetup.digest} --yes to approve.`])write(line);return EXIT.refused}if(selfHeal&&expectedSetupDigest===void 0)return fail(write,json,"verify set","setup-digest-required",`confirm self-healing with --setup-digest ${recoverySetup?.digest} exactly as previewed`,EXIT.refused);if(selfHeal&&expectedSetupDigest!==recoverySetup?.digest)return fail(write,json,"verify set","stale-approval",`the approved setup changed after preview — expected ${expectedSetupDigest}, current ${recoverySetup?.digest}; preview verification again before approving`,EXIT.refused);const saved=store.setVerifyCommand({repo:grantKey,command,timeoutMs:timeoutSeconds*1e3,approvedBy:acting.name,recoverySetupDigest:recoverySetup?.digest??null},clock());return quickValue!==void 0?succeed(write,json,"verify set",{repo,level:"quick",digest:saved.digest,timeoutSeconds},()=>[`Approved the quick check: Quick builds of ${repo} run \`${command}\` (digest ${saved.digest}, ${timeoutSeconds}s) right after commit.`]):succeed(write,json,"verify set",{repo,digest:saved.digest,timeoutSeconds,selfHeal},()=>[`Approved: builds of ${repo} re-run \`${command}\` (digest ${saved.digest}, ${timeoutSeconds}s) right after commit${selfHeal?"; a missing required project executable gets one bounded approved-setup recovery":""}.`])}const GITHUB_REPO_SHAPE=/^[A-Za-z0-9_.-]{1,80}\/[A-Za-z0-9_.-]{1,100}$/,LABEL_SHAPE=/^[A-Za-z0-9][A-Za-z0-9:_. -]{0,49}$/;function intakeTaskId(github,issueNumber){const suffix=`-${issueNumber}`;return`ghi-${github.replace(/[^A-Za-z0-9._-]+/g,"-")}`.slice(0,64-suffix.length)+suffix}async function intakeCommand(positional,flags,context){const{store,write,json}=context,clock=context.clock??(()=>new Date),gh=context.gitRunner??run,action=positional[0]??"show",repo=repoFrom(flags);if(action==="pr-comments"||action==="preview"||action==="run"){const demoFence=refuseDemo(context,`intake ${action}`);if(demoFence!==null)return demoFence}if(action==="show"){const grant2=store.liveIntakeGrant(repo);return json?(write(envelopeJson({ok:!0,command:"intake show",repo,grant:grant2})),EXIT.ok):(write(grant2===null?`No intake grant for ${repo}. Nothing on GitHub becomes a proposal here.`:`${repo} intakes GitHub issues from ${grant2.github} labeled "${grant2.label}"${grant2.reviewers===null?"":`; PR comments from: ${grant2.reviewers.join(", ")}`} — granted by ${grant2.approvedBy} at ${grant2.approvedAt}.`),EXIT.ok)}if(action==="grant"||action==="clear"){const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,`intake ${action}`,verified,"an intake grant is standing authority — it takes `--as <you> --token <t>`",repo);if(action==="clear"){const cleared=store.clearIntakeGrant(repo,acting.name,clock());return succeed(write,json,"intake clear",{repo,cleared},()=>[cleared?`Revoked — nothing on GitHub becomes a proposal for ${repo} now.`:`Nothing was granted for ${repo}.`])}const github=text(flags,"github"),label=text(flags,"label");if(github===void 0||!GITHUB_REPO_SHAPE.test(github))return fail(write,json,"intake grant","usage","--github <owner/name> names the repository on GitHub",EXIT.usage);if(label===void 0||!LABEL_SHAPE.test(label))return fail(write,json,"intake grant","usage","--label <label> names the exact label that nominates an issue",EXIT.usage);const reviewersRaw=text(flags,"reviewers"),reviewers=reviewersRaw===void 0?null:reviewersRaw.split(",").map(one=>one.trim()).filter(one=>/^[A-Za-z0-9-]{1,39}$/.test(one));if(flags.get("yes")!==!0){if(json)return write(envelopeJson({ok:!1,command:"intake grant",reason:"unconfirmed",repo,github,label,reviewers})),EXIT.refused;for(const line of["The terms, exactly:",` local repo ${repo}`,` github ${github}`,` label ${label}`,` pr comments ${reviewers===null||reviewers.length===0?"nobody's — PR-comment intake stays off":`from ${reviewers.join(", ")} only`}`,"","Open issues carrying exactly this label become LOCAL, UNAPPROVED task","proposals when `toolroll intake run` passes. Nothing builds","without a scope you approve; nothing on GitHub is ever written to.","Re-run with --yes to grant."])write(line);return EXIT.refused}const granted=store.setIntakeGrant({repo,github,label,reviewers,approvedBy:acting.name},clock());return succeed(write,json,"intake grant",{repo,github,label,reviewers:granted.reviewers},()=>[`Granted: issues in ${github} labeled "${label}" become unapproved proposals for ${repo}.`])}if(action!=="preview"&&action!=="run"&&action!=="pr-comments")return fail(write,json,"intake","usage","`toolroll intake [show|grant|clear|preview|run|pr-comments] --repo <path> …`",EXIT.usage);const grant=store.liveIntakeGrant(repo);if(grant===null)return fail(write,json,`intake ${action}`,"no-grant",`no intake grant for ${repo} — \`toolroll intake grant\` states the terms`,EXIT.refused);if(action==="pr-comments"){if(grant.reviewers===null||grant.reviewers.length===0)return fail(write,json,"intake pr-comments","no-reviewers","the grant names no reviewers — `intake grant --reviewers <logins>` is the authority for this",EXIT.refused);const publications=store.openedPublications().filter(one=>one.prNumber!==null&&store.refForId(one.taskRef)?.repo===repo&&one.githubRepo===grant.github);let ingested=0,duplicates=0,refused=0;const skippedPrs=[];for(const publication of publications){const pr=publication.prNumber,terminal=store.artifactsFor(publication.run).find(one=>one.kind==="terminal-diff");if(terminal===void 0){skippedPrs.push({pr,reason:"no terminal diff to bind comments to"});continue}const proven=readVerifiedArtifact(context.evidenceRoot,terminal);if(!proven.ok){skippedPrs.push({pr,reason:`the terminal diff no longer verifies — ${proven.problem}`});continue}const asked2=await gh("gh",["api","--paginate",`repos/${grant.github}/pulls/${pr}/comments`],{timeoutMs:6e4});if(asked2.code!==0){skippedPrs.push({pr,reason:"github unreachable"});continue}let remote;try{remote=JSON.parse(asked2.stdout)}catch{skippedPrs.push({pr,reason:"github answered without its promised JSON"});continue}if(!Array.isArray(remote)){skippedPrs.push({pr,reason:"github answered with JSON that is not the promised array"});continue}for(const comment of remote){const login=String(comment.user?.login??"");if(!grant.reviewers.some(one=>one.toLowerCase()===login.toLowerCase()))continue;const id=Number(comment.id);if(!Number.isInteger(id)||id<=0)continue;const body=validateNote(String(comment.body??""));if(!body.ok){refused+=1;continue}const rawPath=String(comment.path??""),lineRaw=comment.line??comment.original_line,line=typeof lineRaw=="number"&&Number.isInteger(lineRaw)&&lineRaw>0?lineRaw:null;store.addDiffComment({artifactId:terminal.id,runId:publication.run,path:rawPath!==""&&rawPath.length<=300&&!hasDisguisedText(rawPath)?rawPath:null,line,note:body.note,author:`github:${login}`,sourceKey:`gh:${grant.github}:${id}`},clock())===null?duplicates+=1:ingested+=1}}return succeed(write,json,"intake pr-comments",{repo,prs:publications.length,ingested,duplicates,refused,skippedPrs},()=>[`${ingested} comment(s) ingested across ${publications.length} PR(s)${duplicates>0?`, ${duplicates} already known`:""}${refused>0?`, ${refused} refused by the validator`:""}.`,...skippedPrs.map(one=>` PR #${one.pr} skipped: ${one.reason}`),ingested>0?"Seal them into revision tasks from each build's page — every revision takes its own approval.":""])}const limit=Math.min(Math.max(Number(text(flags,"limit")??"50"),1),200),asked=await gh("gh",["issue","list","--repo",grant.github,"--label",grant.label,"--state","open","--limit",String(limit),"--json","number,title,updatedAt"],{timeoutMs:2e4});if(asked.code!==0)return fail(write,json,`intake ${action}`,"github-unreachable",`gh could not list ${grant.github}: ${(asked.stderr.split(`
|
|
491
|
-
`)[0]??"").slice(0,200)}`,EXIT.failed);let issues;try{issues=JSON.parse(asked.stdout)}catch{return fail(write,json,`intake ${action}`,"github-unreadable","gh answered, but not with the JSON it promised",EXIT.failed)}const candidates=issues.filter(issue=>Number.isInteger(issue.number)&&issue.number>0).map(issue=>{const id=intakeTaskId(grant.github,issue.number),title=String(issue.title??""),clean=title.length>0&&title.length<=180&&!hasDisguisedText(title);return{id,number:issue.number,title,clean,exists:store.getTask(id)!==null}});if(action==="preview"){if(json)return write(envelopeJson({ok:!0,command:"intake preview",repo,github:grant.github,label:grant.label,candidates})),EXIT.ok;if(candidates.length===0)return write(`Nothing open in ${grant.github} carries "${grant.label}".`),EXIT.ok;write(`Would intake from ${grant.github} ("${grant.label}"):`);for(const one of candidates)write(` #${one.number} ${one.exists?"already here as":one.clean?"→":"REFUSED (title carries control characters)"} ${one.id}${one.clean?` — ${one.title}`:""}`);return write("Nothing was created. `toolroll intake run` makes the proposals."),EXIT.ok}const created=[],skipped=[];for(const one of candidates){if(one.exists)continue;if(!one.clean){skipped.push({id:one.id,reason:"title-refused"});continue}const made=store.transact(()=>{const filed=fileTaskProposal(store,{id:one.id,title:`GH#${one.number}: ${one.title}`,repo,goal:`Imported from GitHub issue #${one.number} in ${grant.github} (label "${grant.label}"). Only the title was imported — read the issue at https://github.com/${grant.github}/issues/${one.number} for full context, then edit and approve this scope before anything builds.`,acceptance:[{id:"c1",statement:"The linked GitHub issue's request is read and addressed.",how:null,evidence:["manual-review"]}],filedVia:"intake"},clock());if(!filed.ok)return filed;const established=store.establishMirror({localTaskId:filed.id,backend:"github-issues",remoteRepo:grant.github,remoteId:String(one.number),provenance:"intake",intakeGrant:grant.id,establishedBy:"intake"},clock());if(!established.ok&&established.reason!=="duplicate")throw new Error(`mirror not established: ${established.reason}`);return filed});made.ok?created.push(made.id):skipped.push({id:one.id,reason:made.reason})}return succeed(write,json,"intake run",{repo,github:grant.github,label:grant.label,created,skipped},()=>[`${created.length} proposal(s) created${skipped.length>0?`, ${skipped.length} skipped`:""} — each awaits its own scope approval.`,...created.map(one=>` ${one}`),...skipped.map(one=>` skipped ${one.id}: ${one.reason}`)])}function templateCommand(positional,flags,context){const{store,write,json,clock}=context,[action,name]=positional;if(action===void 0||action==="list"){if(json)return write(envelopeJson({ok:!0,command:"template list",templates:TEMPLATES.map(one=>({name:one.name,kind:one.kind,purpose:one.purpose}))})),EXIT.ok;write("Templates — common work you edit to fit. Nothing a template"),write("files is approved; recipes only show existing ceremonies."),write("");for(const one of TEMPLATES)write(` ${one.name.padEnd(16)} ${one.kind.padEnd(9)} ${one.purpose}`);return write(""),write("`toolroll template show <name>` · `template apply <name> --repo <path>`"),EXIT.ok}if(action!=="show"&&action!=="apply")return fail(write,json,`template ${action}`,"usage","`toolroll template list | show <name> | apply <name> --repo <path> [--file]`",EXIT.usage);if(name===void 0)return fail(write,json,`template ${action}`,"usage","which template? `toolroll template list` names them",EXIT.usage);const template=templateByName(name);if(template===null)return fail(write,json,`template ${action}`,"unknown",`no template named ${name} — \`toolroll template list\``,EXIT.refused);if(action==="show"){if(json)return write(envelopeJson({ok:!0,command:"template show",template})),EXIT.ok;if(write(`${template.name} — ${template.purpose}`),template.kind==="recipe"){write(""),write(`This one is a recipe, not an application: ${template.why}`);for(const step of template.steps)write(""),write(` ${step.say}`),write(` ${step.run}`);return EXIT.ok}write(""),template.kind==="task"?(write(" files one task (unapproved until you approve its scope)"),write(` title ${template.title}`)):(write(" makes a scheduled flow (nothing repeats until you turn the schedule on)"),write(` name ${template.title}`),write(` schedule ${template.schedule}`)),write(` goal ${template.goal}`),template.outOfScope!==null&&write(` not ${template.outOfScope}`),template.touches.length>0&&write(` touches ${template.touches.join(", ")}`),write(""),write("You will probably edit:");for(const hint of template.edit)write(` - ${hint}`);return write(""),write(`\`toolroll template apply ${template.name} --repo <path>\` previews the exact filing.`),EXIT.ok}if(template.kind==="recipe")return fail(write,json,"template apply","recipe",`${template.name} cannot be applied: ${template.why} \`toolroll template show ${template.name}\` walks the ceremonies.`,EXIT.refused);const repoGiven=text(flags,"repo");if(repoGiven===void 0)return fail(write,json,"template apply","usage","which repository? --repo <path> — a template never guesses where work lands",EXIT.usage);const goal=text(flags,"goal")??template.goal,outOfScope=text(flags,"not")??template.outOfScope,touches=text(flags,"touches")===void 0?template.touches:(text(flags,"touches")??"").split(",").map(one=>one.trim()).filter(one=>one!=="");if(template.kind==="task"){const title=text(flags,"title")??template.title,draft={kind:"task",title,repo:canonicalProject(repoGiven)??resolve(repoGiven),goal,outOfScope,touches,filedVia:`template:${template.name}`};if(!flags.has("file"))return json?(write(envelopeJson({ok:!1,command:"template apply",reason:"unconfirmed",draft})),3):(write("Would file, exactly (edit with --title/--goal/--not/--touches):"),write(""),write(` task ${draft.title}`),write(` repo ${draft.repo}`),write(` goal ${draft.goal}`),draft.outOfScope!==null&&write(` not ${draft.outOfScope}`),draft.touches.length>0&&write(` touches ${draft.touches.join(", ")}`),write(""),write("Nothing was filed. Re-run with --file to file it — UNAPPROVED either way."),3);const made2=fileTaskProposal(store,{title,repo:repoGiven,goal,outOfScope,touches,acceptance:template.acceptance,filedVia:`template:${template.name}`},clock());if(!made2.ok)return fail(write,json,"template apply",made2.reason,made2.message,made2.reason==="duplicate"?EXIT.refused:EXIT.usage);const filedLink=consoleLinkFor(context,`/t/${encodeURIComponent(made2.id)}`);return succeed(write,json,"template apply",{filed:"task",id:made2.id,approved:!1,...filedLink===null?{}:{links:{task:filedLink}}},()=>[`Filed ${made2.id} from template ${template.name}.`,"","UNAPPROVED — NO AUTHORITY GRANTED. It builds only after you approve its scope:",` toolroll task show ${made2.id}`,...filedLink===null?[]:[` ${filedLink}`]])}const flowName=text(flags,"name")??template.title,scheduleGiven=text(flags,"schedule")??template.schedule,schedule=parseSchedule(scheduleGiven)!==null?scheduleGiven:scheduleFromWords(scheduleGiven)??scheduleGiven,ceilingGiven=text(flags,"ceiling"),costCeilingUsd=ceilingGiven===void 0?template.costCeilingUsd:Number(ceilingGiven),repo=canonicalProject(repoGiven)??resolve(repoGiven),terms={goal,outOfScope,touches,requirements:template.requirements,acceptance:template.acceptance,budgetPerRunMicrousd:null,costCeilingUsd};if(!flags.has("file")){const draft={kind:"scheduled flow",name:flowName,repo,schedule,...terms,filedVia:`template:${template.name}`};if(json)return write(envelopeJson({ok:!1,command:"template apply",reason:"unconfirmed",draft})),3;const readable=parseSchedule(schedule);return write("Would make this scheduled flow (edit with --name/--goal/--not/--touches/--schedule/--ceiling):"),write(""),write(` flow ${draft.name}`),write(` repo ${draft.repo}`),write(` schedule ${readable===null?schedule:describeSchedule(readable)}`),write(` goal ${draft.goal}`),draft.outOfScope!==null&&write(` not ${draft.outOfScope}`),draft.touches.length>0&&write(` touches ${draft.touches.join(", ")}`),draft.costCeilingUsd!==null&&write(` ceiling $${draft.costCeilingUsd} every 7 days`),write(""),write("Nothing was made. Re-run with --file to make it. Nothing repeats until you turn the schedule on."),3}const made=createScheduledFlow(store,{repo,name:flowName,stem:template.name,schedule,terms,by:context.principal?.account??"toolroll",filedBy:context.principal?.account??null},clock());if(!made.ok)return fail(write,json,"template apply","bad-terms",made.message,EXIT.usage);const flowLink=consoleLinkFor(context,`/flows/${made.flow}`);return succeed(write,json,"template apply",{filed:"scheduled flow",flow:made.flow,trigger:made.trigger,on:!1,...flowLink===null?{}:{links:{flow:flowLink}}},()=>[`Made ${flowName}, flow #${made.flow}, from template ${template.name}.`,"","Nothing repeats until you turn the schedule on; each run then waits for approval under the project's rules:",` toolroll flows trigger resume ${made.flow} ${made.trigger}`,...flowLink===null?[]:[` ${flowLink}`]])}function readTokenFile(path){if(path!==void 0)try{const raw=readFileSync(path,"utf8").trim();return raw===""?void 0:raw}catch{return}}async function daemonCommand(positional,flags,context){const{store,write,json}=context,demoFence=refuseDemo(context,"daemon");if(demoFence!==null)return demoFence;const[action="status"]=positional,repo=repoFrom(flags),configDir=dirname(context.telegramTokenFile),supervise=context.gitRunner??run,binFlag=text(flags,"bin"),resolveBin=async()=>{const direct=daemonLaunchCommand({execPath:process.execPath,...process.argv[1]===void 0?{}:{entry:resolve(process.argv[1])},...binFlag===void 0?{}:{explicitBin:resolve(binFlag)}});if(direct!==null)return direct;const found=await supervise("sh",["-lc","command -v toolroll || command -v standing-orders"]);return found.code===0&&found.stdout.trim()!==""?{bin:process.execPath,binArgs:[found.stdout.trim()]}:null};if(action==="install"){const runnerName=text(flags,"runner"),inlineToken=text(flags,"token"),tokenPath=text(flags,"token-file");if(inlineToken!==void 0&&tokenPath!==void 0)return fail(write,json,"daemon install","usage","choose one credential source: --token or --token-file",EXIT.usage);const token=inlineToken??readTokenFile(tokenPath);if(runnerName===void 0||token===void 0)return fail(write,json,"daemon install","usage","`toolroll daemon install --runner <name> (--token <t> | --token-file <path>) --repo <path>` (plus any watch flags to bake in)",EXIT.usage);const auth=authenticate(store,runnerName,token);if(!auth.ok)return fail(write,json,"daemon install",auth.reason,describeAuth(auth.reason,runnerName),EXIT.refused);const heartbeatBefore=store.getRunner(runnerName)?.runner.heartbeatAt??null,located=await resolveBin();if(located===null)return fail(write,json,"daemon install","no-bin","`toolroll` is not on the PATH the service would use — run `toolroll link` first, or pass --bin <absolute path>",EXIT.refused);const watchFlags=[];for(const name of["pool","model","repair-model","provider","plan-model","plan-provider","max","turns","tick-every","bridge-every","reconcile-every","containment"]){const value=text(flags,name);value!==void 0&&watchFlags.push(`--${name}`,value)}watchFlags.includes("--containment")||watchFlags.push("--containment",currentContainment().policy);const plan2=planDaemon({platform:process.platform,bin:located.bin,binArgs:located.binArgs,runner:runnerName,repo,configDir,watchFlags});if("error"in plan2)return fail(write,json,"daemon install","unsupported",plan2.error,EXIT.refused);const legacy2=installedLegacyDaemon({platform:process.platform,bin:located.bin,binArgs:located.binArgs,runner:runnerName,repo,configDir,watchFlags});if(flags.has("dry-run"))return json?(write(envelopeJson({ok:!0,command:"daemon install",dryRun:!0,plan:plan2,replaces:legacy2?.label??null})),EXIT.ok):(write(`Would write ${plan2.unitPath}:`),write(""),write(plan2.unitContent),write(`Token (0600): ${plan2.tokenFile} · logs: ${plan2.logPath}`),legacy2!==null&&write(`Would stop and remove ${legacy2.label} (${legacy2.unitPath}), the same watch under its older name.`),write("Nothing was written. Re-run without --dry-run to install."),EXIT.ok);const installed=await installReplacingLegacy(plan2,token,legacy2,supervise);if(!installed.ok)return fail(write,json,"daemon install","supervisor",installed.message,EXIT.failed);const readySince=legacy2===null?heartbeatBefore:store.getRunner(runnerName)?.runner.heartbeatAt??null,started=await daemonStatus(plan2,supervise);if(started.state!=="running")return fail(write,json,"daemon install","not-running",`the service was installed but did not stay running (${started.detail}) — read ${plan2.logPath}; no work will be claimed until this is fixed`,EXIT.failed);const liveRunner=(await awaitFreshHeartbeat(store,runnerName,installed.action==="running"&&legacy2===null?null:readySince)).ok?store.getRunner(runnerName)?.runner??null:null;if(liveRunner===null){const macHint=process.platform==="darwin"&&repo.startsWith(join(homedir(),"Documents"))?" macOS may be blocking background access to Documents; grant the Node executable Full Disk Access, move the repository outside a protected folder, or keep `toolroll up` running from your terminal.":"";return fail(write,json,"daemon install","not-ready",`the supervisor has a process, but ${runnerName} never reached its worker heartbeat.${macHint} Read ${plan2.logPath}; no work will be claimed until the heartbeat appears`,EXIT.failed)}return succeed(write,json,"daemon install",{label:plan2.label,unit:plan2.unitPath,logs:plan2.logPath,state:started.state,pid:started.pid,heartbeatAt:liveRunner.heartbeatAt,action:installed.action,changed:installed.changed,replaced:legacy2?.label??null,containment:containmentStatus(currentContainment())},()=>[installed.action==="running"?`${plan2.label} was already running under this exact definition; left alone.`:installed.action==="reloaded"?`Reloaded ${plan2.label} under its changed definition.`:`Installed and started ${plan2.label}.`,...legacy2===null?[]:[` replaced ${legacy2.label} (stopped and removed)`],` verified ${started.detail}`,` worker ${runnerName} answered at ${liveRunner.heartbeatAt}`,` unit ${plan2.unitPath}`,` token ${plan2.tokenFile} (0600 — the unit never carries it)`,` logs ${plan2.logPath}`,"","It survives reboots and restarts itself after crashes; watch's","incarnation recovery makes those restarts safe. `toolroll daemon","status` to check on it, `daemon uninstall` to take it back off."])}const planArgs={platform:process.platform,bin:binFlag??"toolroll",binArgs:[],runner:text(flags,"runner")??"runner",repo,configDir,watchFlags:[]},current=planDaemon(planArgs);if("error"in current)return fail(write,json,`daemon ${action}`,"unsupported",current.error,EXIT.refused);const legacy=installedLegacyDaemon(planArgs),plan=legacy!==null&&!existsSync(current.unitPath)?legacy:current;if(action==="status"){const state=await daemonStatus(plan,supervise),containment=currentContainment();return json?(write(envelopeJson({ok:!0,command:"daemon status",...state,label:plan.label,logs:plan.logPath,containment:containmentStatus(containment)})),state.state==="running"?EXIT.ok:EXIT.refused):(write(`${plan.label}: ${state.detail}`),write(` logs ${plan.logPath}`),write(` ${describeContainment(containment)}`),state.state==="not-installed"&&write(" → toolroll daemon install --runner <name> --token <t> --repo <path>"),state.state==="disabled"&&write(" → the service is disabled: `toolroll daemon install` re-enables and loads it"),state.state==="running"?EXIT.ok:EXIT.refused)}if(action==="uninstall"){const gone=await uninstallDaemon(current,supervise),legacyGone=legacy===null?null:await uninstallDaemon(legacy,supervise);return succeed(write,json,"daemon uninstall",{removed:gone.existed||legacyGone?.existed===!0},()=>[...gone.existed||legacyGone===null?[gone.existed?`Stopped and removed ${current.label}.`:`${current.label} was not installed; nothing to remove.`]:[],...legacyGone===null?[]:[`Stopped and removed ${legacy.label}.`]])}return action==="logs"?succeed(write,json,"daemon logs",{logs:plan.logPath},()=>[plan.logPath,` → tail -f ${plan.logPath}`]):fail(write,json,"daemon","usage","`toolroll daemon [install|status|uninstall|logs]`",EXIT.usage)}const WATCH_LEASE_MS=MAX_WATCH_LEASE_MS,WATCH_HEARTBEAT_MS=RUNNER_HEARTBEAT_MS;function startTelegramFollower(args){const{context,progress,label}=args,source=loadBotToken(process.env,context.telegramTokenFile);if(source===null)return null;const fence=networkFence(context.telegramEnv??(context.telegramTransport===void 0?process.env:{}));if(fence!==null)return progress(networkFenceLine(fence)),null;const transport=context.telegramTransport??createTransport(source.token),pushUrl=telegramPushUrl(readHooksBase(dirname(context.databaseFile)));return followBridge(context.store,{push:pushUrl===null?null:{url:pushUrl,secret:telegramHookSecret(dirname(context.databaseFile),!0)},readProjects:telegramReadProjects(context),canDeliver:telegramCanDeliver(context,source.token),conversation:telegramConversation(context,args.publicUrl===void 0?{}:{serverOrigin:args.publicUrl}),botId:source.botId,transport,signal:args.signal,...args.owner===void 0?{}:{owner:args.owner},onCycle:cycle=>{progress(`${label} sent ${cycle.sent}, answered ${cycle.answered}, paired ${cycle.paired}`+((cycle.statusReplies??0)>0?`, status replies ${cycle.statusReplies}`:"")+((cycle.chatQueued??0)>0?`, chat received ${cycle.chatQueued}`:"")+((cycle.chatAnswered??0)>0?`, chat replied ${cycle.chatAnswered}`:"")+((cycle.chatConfirmed??0)>0?`, chat confirmed ${cycle.chatConfirmed}`:"")+(cycle.problems.length>0?` — ${cycle.problems.length} problem(s): ${cycle.problems[0].slice(0,200)}`:""))}}).catch(error=>(progress(`${args.died.prefix}the telegram follower died — ${describe(error)}; ${args.died.next}`),null))}const TELEGRAM_STOP_WAIT_MS=5e3,CLEANUP_SLOW_MS=3e4,SHUTDOWN_DEADLINE_MS=6e4,WORKER_ALIVE_EVERY_MS=5e3,WORKER_SILENCE_MS=6e4;let staleStatusesRepaired=!1;async function runWatchLoop(args){const{context,flags,runner,token,repo,progress}=args,{store}=context;noticeGitIncidents(store,context.clock);const tickEveryMs=Number(text(flags,"tick-every")??6e4),bridgeEveryMs=Number(text(flags,"bridge-every")??45e3),reconcileEveryMs=Number(text(flags,"reconcile-every")??5*6e4),runFor=text(flags,"for")===void 0?null:Number(text(flags,"for"));if(!Number.isSafeInteger(reconcileEveryMs)||reconcileEveryMs<1||reconcileEveryMs>2147483647)throw new Error("--reconcile-every must be an integer from 1 to 2147483647 milliseconds");const incarnation=`${runFor===null?"toolroll-service:":""}${randomUUID()}`;let lease=acquireWatchLeaseAuthed(store,{runner,token,repo,owner:incarnation,ttlMs:WATCH_LEASE_MS},new Date);const waitUntil=Date.now()+(args.leaseWaitMs??0);let saidWaiting=!1;const waitStopping=args.leaseWaitStopping??args.isStopping;for(;!lease.ok&&lease.reason==="watch-busy"&&Date.now()<waitUntil&&!waitStopping();)saidWaiting||progress(`watch: ${repo} is still held by the previous worker until ${lease.until??"its lease lapses"}; taking it over then`),saidWaiting=!0,await new Promise(resolve2=>setTimeout(resolve2,1e3)),lease=acquireWatchLeaseAuthed(store,{runner,token,repo,owner:incarnation,ttlMs:WATCH_LEASE_MS},new Date);if(!lease.ok)return{ok:!1,reason:"watch-busy",detail:lease.reason==="watch-busy"?`another watch holds ${runner} on ${repo} until ${lease.until} — one watch per runner and repo; cron ticks may coexist, watches may not`:describeAuth(lease.reason,runner),ticks:0,built:0,broke:0};lease.superseded!==null&&lease.recovered>0&&progress(`Recovered ${lease.recovered} claim(s) from the previous watch (${lease.superseded.slice(0,8)}…) before dispatching anything.`);for(const line of args.containmentLines?.(currentContainment())??[`watch: ${describeContainment(currentContainment())}`])progress(line);store.startWatchEpisode({repo,runner,incarnation},new Date);try{notifyVersionLive(store,dirname(context.databaseFile),PACKAGE_VERSION,new Date)}catch{}if(recordRunnerVersion(dirname(context.databaseFile),runner,PACKAGE_VERSION,new Date),args.onReady?.(),!staleStatusesRepaired){staleStatusesRepaired=!0;const repaired=repairStaleStatuses(store,new Date);repaired.exitsRecorded>0&&progress(`watch: recorded ${repaired.exitsRecorded} finished process exit(s) left open by an earlier version`)}let leaseLost=!1,leaseLostReason=null,custodyUnknown=!1;const followController=new AbortController,hub=wakeHubFor(store,read=>briefly(store,read)),wakes=new WakePoker;args.onFollowController?.(followController);let failed=!1,failure;const fail2=error=>{failed||(failure=error),failed=!0,wakes.poke()},stopping=()=>args.isStopping()||leaseLost||failed,heartbeatEveryMs=context.watchHeartbeatMs??WATCH_HEARTBEAT_MS;let heartbeatTimer=null,heartbeatStopped=!1,busyBeats=0;const scheduleBeat=ms=>{heartbeatStopped||(heartbeatTimer=setTimeout(beat,ms),heartbeatTimer.unref?.())};function beat(){if(heartbeatTimer=null,heartbeatStopped||leaseLost)return;let answer=null,problem=null;try{answer=briefly(store,()=>renewWatchLeaseAuthed(store,{runner,token,repo,owner:incarnation,ttlMs:WATCH_LEASE_MS},new Date))}catch(error){if(isDatabaseBusy(error)){busyBeats++,custodyUnknown||progress(`watch: ${runner} on ${repo}: the database is busy, so this worker can't prove it still holds the project yet — no new work starts until it can`),custodyUnknown=!0,scheduleBeat(Math.min(heartbeatEveryMs,1e3*2**Math.min(busyBeats-1,4)));return}problem=`renewal could not be proved: ${describe(error)}`}if(answer!==null&&answer.ok){busyBeats=0,answer.lateMs>0&&progress(`watch: renewal late by ${Math.max(1,Math.round(answer.lateMs/1e3))}s — this worker still holds ${repo}; carrying on`),custodyUnknown&&(custodyUnknown=!1,progress(`watch: ${runner} on ${repo}: proved it still holds the project — new work may start again`),wakes.poke()),scheduleBeat(heartbeatEveryMs);return}leaseLostReason=answer===null?"error":answer.reason,leaseLost=!0,followController.abort(),wakes.poke(),progress(`watch: ${runner} on ${repo}: ${problem??renewalRefusedWords(answer.reason)} — stopping without admitting more work`)}scheduleBeat(heartbeatEveryMs);const stopHeartbeat=()=>{heartbeatStopped=!0,heartbeatTimer!==null&&clearTimeout(heartbeatTimer),heartbeatTimer=null};let cleanupStage=null,lastPassAt=null;args.health?.(()=>({repo,leaseLive:!leaseLost&&!custodyUnknown&&cleanupStage===null,lastPassAt,stopping:stopping(),cleanup:cleanupStage}));const serviceBridge=args.serviceBridge===!0,follower=serviceBridge?null:startTelegramFollower({context,publicUrl:text(flags,"public-url"),signal:followController.signal,progress,label:"watch: bridge",died:{prefix:"watch: ",next:"taps wait for the next watch"}}),slackFollower=superviseChatFollower("Slack",followController.signal,progress,()=>followSlack({store,dir:dirname(context.databaseFile),signal:followController.signal,readProjects:telegramReadProjects(context),evidenceRoot:context.evidenceRoot,...context.leadSeams?.subscriptionRunner?{subscriptionRunner:context.leadSeams.subscriptionRunner}:{},origin:()=>phoneOrigin(process.env,dirname(context.databaseFile),{serverOrigin:text(flags,"public-url")??null}),notifications:()=>effectivePrimary(process.env,dirname(context.databaseFile),loadBotToken(process.env,context.telegramTokenFile)!==null).channel==="slack"})),teamsFollower=superviseChatFollower("Teams",followController.signal,progress,()=>followTeams({store,dir:dirname(context.databaseFile),signal:followController.signal,readProjects:telegramReadProjects(context),evidenceRoot:context.evidenceRoot,...context.leadSeams?.subscriptionRunner?{subscriptionRunner:context.leadSeams.subscriptionRunner}:{},origin:()=>phoneOrigin(process.env,dirname(context.databaseFile),{serverOrigin:text(flags,"public-url")??null}),notifications:()=>effectivePrimary(process.env,dirname(context.databaseFile),loadBotToken(process.env,context.telegramTokenFile)!==null).channel==="teams"})),discordFollower=superviseChatFollower("Discord",followController.signal,progress,()=>followDiscord({store,dir:dirname(context.databaseFile),signal:followController.signal,readProjects:telegramReadProjects(context),evidenceRoot:context.evidenceRoot,...context.leadSeams?.subscriptionRunner?{subscriptionRunner:context.leadSeams.subscriptionRunner}:{},origin:()=>phoneOrigin(process.env,dirname(context.databaseFile),{serverOrigin:text(flags,"public-url")??null}),notifications:()=>effectivePrimary(process.env,dirname(context.databaseFile),loadBotToken(process.env,context.telegramTokenFile)!==null).channel==="discord"})),quiet=[],sink=line=>quiet.push(line),passFlags=(extra={})=>{const copy=new Map(flags);copy.set("json",!0),copy.set("incarnation",incarnation);for(const[key,value]of Object.entries(extra))copy.set(key,value);return copy};let reconciliationReady=!1,reconciliationFailure=null,reconciliationBusy=!1;const paused=()=>custodyUnknown||!reconciliationReady||updateAdmissionPaused(store.raw())||context.shouldPauseAdmission?.()===!0,admissionStopped=()=>stopping()||paused(),quietContext={...context,write:sink,json:!0,shouldStop:stopping,shouldPauseAdmission:paused},startedAt=Date.now(),deadline=runFor===null?null:startedAt+runFor;let lastTick=0,lastBridge=0,ticks=0,built=0,brokeCount=0;const sweepOwner={},maintenance=startMaintenance({intervalMs:reconcileEveryMs,onStop:()=>storageSweepSupervisor(context.databaseFile).stop(sweepOwner),shouldStop:stopping,onError:error=>{reconciliationReady=!1;const detail=describe(error);detail!==reconciliationFailure&&progress(`watch: reconciliation failed — ${detail}; new work is paused until a recovery pass succeeds`),reconciliationFailure=detail,reconciliationBusy=busyFailure(error)},retryAfter:(error,failuresInARow)=>busyRetryAfter(busyFailure(error),failuresInARow),run:async()=>{const maintenanceLines=[],maintenanceContext={...quietContext,...runFor===null?{sweepOwner}:{},write:line=>maintenanceLines.push(line)};if(runFor!==null&&delete maintenanceContext.sweepOwner,await reconcileCommand(passFlags(),maintenanceContext)!==EXIT.ok)throw new Error(maintenanceLines.join(" "));reconciliationFailure!==null&&progress("watch: reconciliation recovered — new work may resume");const recovered=!reconciliationReady;if(reconciliationFailure=null,reconciliationReady=!0,recovered&&wakes.poke(),!stopping()){try{const shipped=await flexibleArmedPass(store,{root:context.evidenceRoot,...context.publishExec===void 0?{}:{exec:context.publishExec}});shipped.ok&&shipped.merged>0&&progress(`watch: merged ${shipped.merged} Flexible result(s) whose checks passed`),shipped.ok&&shipped.cancelled>0&&progress(`watch: stopped ${shipped.cancelled} Flexible merge(s) whose terms no longer held`)}catch(error){progress(`watch: the Flexible ship pass failed — ${describe(error)}; retrying on its next interval`)}try{const dcShipped=await directChatArmedPass(store,{root:context.evidenceRoot,...context.publishExec===void 0?{}:{exec:context.publishExec}});dcShipped.merged>0&&progress(`watch: merged ${dcShipped.merged} Direct Chat result(s) whose checks passed`),dcShipped.cancelled>0&&progress(`watch: stopped ${dcShipped.cancelled} Direct Chat merge(s) whose terms no longer held`)}catch(error){progress(`watch: the Direct Chat ship pass failed — ${describe(error)}; retrying on its next interval`)}}if(!stopping()&&store.openedPublications().length>0)try{const checks=await observeChecks(store,context.publishExec===void 0?{}:{exec:context.publishExec});checks.failing>0&&progress(`watch: CI is red on ${checks.failing} published PR(s) — the outbox has it`);const followed=await followPullRequests(store,checks.seen,{evidenceRoot:context.evidenceRoot,...context.publishExec===void 0?{}:{exec:context.publishExec}});followed.revisions>0&&progress(`watch: filed ${followed.revisions} CI revision(s)`),followed.merged>0&&progress(`watch: merged ${followed.merged} pull request(s) whose checks passed`)}catch(error){progress(`watch: CI observation failed — ${describe(error)}; retrying on its next interval`)}}}),followUpChecks=startMaintenance({intervalMs:5e3,shouldStop:stopping,onError:error=>progress(`watch: a follow-up check failed to run — ${describe(error)}; it is recorded on the result`),run:async()=>{if(store.isDemo())return;const batched=await runBatchChecks(store,context.evidenceRoot,{now:context.clock,shouldStop:stopping});batched>0&&progress(`watch: settled ${batched} batch-checked result(s)`),context.agentRunner===void 0&&resumeHeldReleases(store,dirname(context.databaseFile),context.clock()),context.agentRunner===void 0&&context.databaseFile!==":memory:"&&sweepOrphanedReleases(store,context.databaseFile,dirname(context.databaseFile),context.clock()).then(resumed=>{for(const one of resumed)progress(`watch: ${basename(one.file,".json")}: continued the release by itself — ${one.why}`)}),requestMissingRechecks(store,context.evidenceRoot,context.clock()),resumeParkedRepairs(store,context.evidenceRoot,context.clock());const ran=await runWaitingChecks(store,context.evidenceRoot,{now:context.clock,shouldStop:stopping});ran>0&&progress(`watch: ran ${ran} follow-up check(s)`);const pendingLand=await runPendingLocalLands(store,context.clock(),{root:context.evidenceRoot,...context.gitRunner===void 0?{}:{git:context.gitRunner}});pendingLand.landed.length>0&&progress(`watch: landed ${pendingLand.landed.length} queued local task(s)`),await refreshTrustedMains(store,context.evidenceRoot,context.clock(),context.gitRunner);const settledChecks=settleReleaseChecks(store,context.evidenceRoot,context.clock());settledChecks>0&&progress(`watch: settled ${settledChecks} release check(s)`),context.agentRunner===void 0&&await refreshGithubNightlies(store,context.clock),context.agentRunner===void 0&&await refreshLearning(store,context.clock),ran+batched>0&&moveCards(store,repo,context.clock(),context.evidenceRoot)}}),codeMapChecks=startMaintenance({intervalMs:6e4,shouldStop:stopping,onError:error=>progress(`watch: a code map check failed — ${describe(error)}; it tries again`),run:async()=>{store.isDemo()||context.agentRunner!==void 0||(await refreshCodeMaps(store,{scratch:join(context.evidenceRoot,".code-map"),clock:context.clock}),sweepDeliveries(store))}}),flowEveryMs=context.flowEveryMs??FLOW_EVERY_MS,flowPool=text(flags,"pool")??join(dirname(databasePath(process.env,homedir())),"worktrees"),flowGit=context.gitRunner??run,flowsDid=(moved,filed,did)=>{moved+filed!==0&&(store.bumpWake(),progress(`watch: ${did}`))},flowMoves=startMaintenance({intervalMs:flowEveryMs,shouldStop:stopping,onError:error=>progress(`watch: flow cards couldn't move — ${describe(error)}; they try again shortly`),run:async()=>{if(paused())return;const moved=moveCards(store,repo,context.clock(),context.evidenceRoot);flowsDid(moved.moved,moved.filed.length,`moved ${moved.moved} flow card(s), filed ${moved.filed.length} task(s)`)}}),flowSteps=startMaintenance({intervalMs:flowEveryMs,shouldStop:stopping,onError:error=>progress(`watch: a flow pass failed — ${describe(error)}; it runs again shortly`),run:async()=>{if(paused())return;let base=text(flags,"base");if(base===void 0){const head=await flowGit("git",["symbolic-ref","--short","-q","HEAD"],{cwd:repo});if(head.code!==0||head.stdout.trim()==="")return;base=head.stdout.trim()}const pass=await flowHousekeeping(store,repo,context.clock,flowIoOf(context,flowPool,flowGit,base),admissionStopped);flowsDid(pass.flows.moved+pass.triggers.added+pass.steps.ran+pass.replies.taken,pass.flows.filed.length+pass.youiyoux.filed,`flow pass — ${pass.triggers.added} card(s) added, ${pass.youiyoux.filed} youiyoux request(s) filed, ${pass.replies.taken} reply(ies) taken, ${pass.steps.ran} step(s) run, ${pass.flows.moved} moved`)}}),modelWatch=startMaintenance({intervalMs:15*6e4,shouldStop:stopping,onError:error=>progress(`watch: the model check failed — ${describe(error)}; it retries later`),run:async()=>{await modelWatchPass(store,context.clock())&&progress("watch: checked models and CLI versions")}}),leaveServiceBeats=joinServiceBeats({context,progress,ciReady:()=>!admissionStopped(),stopping}),passes=args.passes??new ProjectPasses,slotFacts=yieldingSince=>{const now=new Date,found=store.getRunner(runner),bound=new Set(found?.runner.repos??[repo]),saved=savedProjectConcurrency(context.databaseFile);return{repo,capacity:found?.runner.capacity??1,running:store.liveClaimCountsByRepo(runner,now),limitOf:one=>saved.get(one)??PROJECT_CONCURRENCY_DEFAULT,waiting:new Set(store.listReady(now,runner).map(one=>one.repo).filter(one=>one!==null&&bound.has(one))),yieldingSince,passes}},lanes=[],buildLane=async index=>{const laneLines=[],laneContext={...quietContext,write:line=>laneLines.push(line)};let yieldingSince=null,yieldingTo=null;for(;!stopping()&&(deadline===null||Date.now()<deadline);){const seqBefore=store.wakeSeq();let broke=!1;if(!paused()){const facts=slotFacts(yieldingSince),answer=index<effectiveConcurrency(facts.limitOf(repo),facts.capacity)?maySlotTake(facts):null;if(answer!==null&&answer.take){yieldingSince=null,yieldingTo=null,laneLines.length=0;let code=EXIT.failed;try{code=await tickCommand(passFlags({"builds-only":"1"}),laneContext)}catch(error){laneLines.push(JSON.stringify({dispatched:[{id:"?",outcome:"failed",reason:"lane",detail:describe(error)}]}))}if(passes.passed(repo),code===EXIT.ok){built++,progress(`watch: build ${index+1} did work (${new Date().toISOString()})`);continue}code===EXIT.failed&&(brokeCount++,broke=!0,progress(`watch: build ${index+1} — ${brokenWords(laneLines)}`))}else answer!==null&&!answer.take&&answer.why==="fair-share"?(yieldingSince===null&&(yieldingSince=passes.stamp(),store.bumpWake()),yieldingTo=answer.to??null):(yieldingSince=null,yieldingTo=null)}if(!broke&&store.wakeSeq()!==seqBefore)continue;const seqIdle=store.wakeSeq(),dozeUntil=Math.min(Date.now()+tickEveryMs,deadline??Number.MAX_SAFE_INTEGER),theirTurnEnded=()=>yieldingTo!==null&&yieldingSince!==null&&passes.lastPass(yieldingTo)>yieldingSince;await hub.changed({baseline:seqIdle,deadline:dozeUntil,until:()=>stopping()||theirTurnEnded(),poker:wakes})}},ensureLanes=()=>{const facts=slotFacts(null),wanted=effectiveConcurrency(facts.limitOf(repo),facts.capacity);for(;lanes.length+1<wanted&&!stopping();)lanes.push(buildLane(lanes.length+1).catch(fail2))};let firstLaneYieldingSince=null,firstLaneYieldingTo=null;try{for(await maintenance.runNow();!stopping()&&(deadline===null||Date.now()<deadline);){if(paused()){await hub.changed({baseline:store.wakeSeq(),deadline:Date.now()+1e3,until:stopping,poker:wakes});continue}ensureLanes();const share=maySlotTake(slotFacts(firstLaneYieldingSince)),yieldBuilds=!share.take&&share.why!=="capacity";!share.take&&share.why==="fair-share"?(firstLaneYieldingSince===null&&(firstLaneYieldingSince=passes.stamp(),store.bumpWake()),firstLaneYieldingTo=share.to??null):(firstLaneYieldingSince=null,firstLaneYieldingTo=null);const seqBefore=store.wakeSeq(),now=Date.now();let tickDidWork=!1,tickBroke=!1;{lastTick=now,quiet.length=0,store.expireOverdueDecisions(new Date);const code=await tickCommand(passFlags(yieldBuilds?{"yield-builds":"1"}:{}),quietContext);passes.passed(repo),ticks++,lastPassAt=new Date().toISOString(),code===EXIT.ok?(tickDidWork=!0,built++,progress(`watch: pass ${ticks} did work (${new Date().toISOString()})`)):code===EXIT.failed&&(brokeCount++,tickBroke=!0,progress(`watch: pass ${ticks} — ${brokenWords(quiet)}`))}try{store.sealLedger()}catch(error){progress(`watch: the ledger chain could not be sealed this pass (${error instanceof Error?error.message:String(error)})`)}if(!admissionStopped()&&store.pendingPublications().length>0){const published=await publishPass(store,{repo,evidenceRoot:context.evidenceRoot,...context.publishExec===void 0?{}:{exec:context.publishExec}});published.pushed+published.opened+published.adopted+published.failed>0&&progress(`watch: published — pushed ${published.pushed}, opened ${published.opened}, adopted ${published.adopted}`+(published.failed>0?`, gave up on ${published.failed}`:""))}if(follower===null&&now-lastBridge>=bridgeEveryMs){lastBridge=now;const source=serviceBridge?null:loadBotToken(process.env,context.telegramTokenFile),dir=dirname(context.databaseFile),primary=effectivePrimary(process.env,dir,source!==null);source!==null&&(quiet.length=0,await bridgeCommand(["telegram"],passFlags(primary.channel==="telegram"?{}:{"inbound-only":"1"}),quietContext))}if(tickDidWork||!tickBroke&&store.wakeSeq()!==seqBefore)continue;const idleUntil=Math.min(lastTick+tickEveryMs,lastBridge+bridgeEveryMs,deadline??Number.MAX_SAFE_INTEGER)-Date.now(),seqIdle=store.wakeSeq(),dozeUntil=Date.now()+Math.max(idleUntil,0),theirTurnEnded=()=>firstLaneYieldingTo!==null&&firstLaneYieldingSince!==null&&passes.lastPass(firstLaneYieldingTo)>firstLaneYieldingSince;await hub.changed({baseline:seqIdle,deadline:dozeUntil,until:()=>stopping()||theirTurnEnded(),poker:wakes})}}catch(error){fail2(error)}finally{const step=async(name,work)=>{cleanupStage=name;const slow=setTimeout(()=>progress(`watch: stopping is still waiting on ${name}`),CLEANUP_SLOW_MS);slow.unref?.();try{await work()}finally{clearTimeout(slow)}};await step("its builds",()=>Promise.all(lanes)),await step("reconciliation",()=>maintenance.stop()),await step("follow-up checks",()=>followUpChecks.stop()),await step("the code map check",()=>codeMapChecks.stop()),await step("flow moves",()=>flowMoves.stop()),await step("flow steps",()=>flowSteps.stop()),await step("the model check",()=>modelWatch.stop()),await step("deliveries and fast CI",()=>leaveServiceBeats()),stopHeartbeat(),followController.abort(),follower!==null&&await step("the Telegram follower",()=>follower),await step("the Slack follower",()=>slackFollower),await step("the Teams follower",()=>teamsFollower),await step("the Discord follower",()=>discordFollower),cleanupStage="releasing the project",store.endWatchEpisode(incarnation,{ticks,built,broke:brokeCount},new Date),store.releaseWatchLease(runner,repo,incarnation,new Date),cleanupStage=null}if(failed)throw failure;return leaseLost?{ok:!1,reason:"lease-lost",lost:leaseLostReason??"error",detail:`the watch lease for ${runner} on ${repo} stopped renewing — ${renewalRefusedWords(leaseLostReason??"error")}`,ticks,built,broke:brokeCount}:reconciliationFailure!==null?{ok:!1,reason:"reconciliation-failed",detail:reconciliationFailure,ticks,built,broke:brokeCount,busy:reconciliationBusy}:{ok:!0,ticks,built,broke:brokeCount,incarnation}}function brokenWords(lines){try{const failed=(JSON.parse(lines[lines.length-1]??"").dispatched??[]).filter(one=>one.outcome==="failed");return failed.length===0?"a pass broke something — the run records have it":`${failed.slice(0,3).map(one=>`${one.id} failed (${one.reason??"?"}${one.detail===void 0?"":`: ${one.detail}`})`).join("; ")}${failed.length>3?`; and ${failed.length-3} more`:""}`}catch{return"a pass broke something — the run records have it"}}async function watchCommand(flags,context){const{store,write,json}=context,demoFence=refuseDemo(context,"watch");if(demoFence!==null)return demoFence;const runner=text(flags,"runner"),token=text(flags,"token")??readTokenFile(text(flags,"token-file"));if(runner===void 0||token===void 0)return fail(write,json,"watch","usage","`toolroll watch --runner <name> --token <t>|--token-file <path> --repo <path> [--for <ms>]`",EXIT.usage);flags.set("token",token);const auth=authenticate(store,runner,token);if(!auth.ok)return fail(write,json,"watch",auth.reason,describeAuth(auth.reason,runner),EXIT.refused);const repo=repoFrom(flags),progress=longCommandProgress(write,json);let stopping=!1,graceTimer,followAbort=null;const stopGraceMs=Number(text(flags,"stop-grace")??3e4),hardStop=()=>{const terminated=terminateLiveProviders();terminated>0&&progress(`Hard stop: ${terminated} provider process group(s) terminated. Their work is saved and kept in each checkout, and each task continues from it; fences keep late output out of every commit. Run \`toolroll\` again to continue.`)},dropSignals=onStopSignals(()=>{if(stopping){hardStop();return}stopping=!0,followAbort?.abort(),wakeHubFor(context.store,read=>briefly(context.store,read)).poke(),graceTimer=setTimeout(hardStop,stopGraceMs)}),startedAt=Date.now();let result;try{result=await runWatchLoop({flags,context,runner,token,repo,progress,isStopping:()=>stopping||context.shouldStop?.()===!0,onFollowController:controller=>{followAbort=controller}})}finally{graceTimer!==void 0&&clearTimeout(graceTimer),dropSignals()}return result.ok?succeed(write,json,"watch",{ticks:result.ticks,built:result.built,broke:result.broke,incarnation:result.incarnation},()=>[`Watched ${repo} for ${Math.round((Date.now()-startedAt)/1e3)}s: ${result.ticks} pass(es), ${result.built} with work, ${result.broke} broke.`,"The lease is handed back; cron or the next watch may take it."]):fail(write,json,"watch",result.reason,result.detail,result.reason==="reconciliation-failed"||result.reason==="loop-failed"?EXIT.failed:EXIT.refused,{ticks:result.ticks,built:result.built,broke:result.broke})}const UP_LOGIN_FILE="up-login.txt";export function writeLoginFileDurably(path,name,password){const fd=openSync(path,fsConstants.O_WRONLY|fsConstants.O_CREAT|fsConstants.O_EXCL,384);try{writeSync(fd,`${name} ${password}
|
|
491
|
+
`)[0]??"").slice(0,200)}`,EXIT.failed);let issues;try{issues=JSON.parse(asked.stdout)}catch{return fail(write,json,`intake ${action}`,"github-unreadable","gh answered, but not with the JSON it promised",EXIT.failed)}const candidates=issues.filter(issue=>Number.isInteger(issue.number)&&issue.number>0).map(issue=>{const id=intakeTaskId(grant.github,issue.number),title=String(issue.title??""),clean=title.length>0&&title.length<=180&&!hasDisguisedText(title);return{id,number:issue.number,title,clean,exists:store.getTask(id)!==null}});if(action==="preview"){if(json)return write(envelopeJson({ok:!0,command:"intake preview",repo,github:grant.github,label:grant.label,candidates})),EXIT.ok;if(candidates.length===0)return write(`Nothing open in ${grant.github} carries "${grant.label}".`),EXIT.ok;write(`Would intake from ${grant.github} ("${grant.label}"):`);for(const one of candidates)write(` #${one.number} ${one.exists?"already here as":one.clean?"→":"REFUSED (title carries control characters)"} ${one.id}${one.clean?` — ${one.title}`:""}`);return write("Nothing was created. `toolroll intake run` makes the proposals."),EXIT.ok}const created=[],skipped=[];for(const one of candidates){if(one.exists)continue;if(!one.clean){skipped.push({id:one.id,reason:"title-refused"});continue}const made=store.transact(()=>{const filed=fileTaskProposal(store,{id:one.id,title:`GH#${one.number}: ${one.title}`,repo,goal:`Imported from GitHub issue #${one.number} in ${grant.github} (label "${grant.label}"). Only the title was imported — read the issue at https://github.com/${grant.github}/issues/${one.number} for full context, then edit and approve this scope before anything builds.`,acceptance:[{id:"c1",statement:"The linked GitHub issue's request is read and addressed.",how:null,evidence:["manual-review"]}],filedVia:"intake"},clock());if(!filed.ok)return filed;const established=store.establishMirror({localTaskId:filed.id,backend:"github-issues",remoteRepo:grant.github,remoteId:String(one.number),provenance:"intake",intakeGrant:grant.id,establishedBy:"intake"},clock());if(!established.ok&&established.reason!=="duplicate")throw new Error(`mirror not established: ${established.reason}`);return filed});made.ok?created.push(made.id):skipped.push({id:one.id,reason:made.reason})}return succeed(write,json,"intake run",{repo,github:grant.github,label:grant.label,created,skipped},()=>[`${created.length} proposal(s) created${skipped.length>0?`, ${skipped.length} skipped`:""} — each awaits its own scope approval.`,...created.map(one=>` ${one}`),...skipped.map(one=>` skipped ${one.id}: ${one.reason}`)])}function templateCommand(positional,flags,context){const{store,write,json,clock}=context,[action,name]=positional;if(action===void 0||action==="list"){if(json)return write(envelopeJson({ok:!0,command:"template list",templates:TEMPLATES.map(one=>({name:one.name,kind:one.kind,purpose:one.purpose}))})),EXIT.ok;write("Templates — common work you edit to fit. Nothing a template"),write("files is approved; recipes only show existing ceremonies."),write("");for(const one of TEMPLATES)write(` ${one.name.padEnd(16)} ${one.kind.padEnd(9)} ${one.purpose}`);return write(""),write("`toolroll template show <name>` · `template apply <name> --repo <path>`"),EXIT.ok}if(action!=="show"&&action!=="apply")return fail(write,json,`template ${action}`,"usage","`toolroll template list | show <name> | apply <name> --repo <path> [--file]`",EXIT.usage);if(name===void 0)return fail(write,json,`template ${action}`,"usage","which template? `toolroll template list` names them",EXIT.usage);const template=templateByName(name);if(template===null)return fail(write,json,`template ${action}`,"unknown",`no template named ${name} — \`toolroll template list\``,EXIT.refused);if(action==="show"){if(json)return write(envelopeJson({ok:!0,command:"template show",template})),EXIT.ok;if(write(`${template.name} — ${template.purpose}`),template.kind==="recipe"){write(""),write(`This one is a recipe, not an application: ${template.why}`);for(const step of template.steps)write(""),write(` ${step.say}`),write(` ${step.run}`);return EXIT.ok}write(""),template.kind==="task"?(write(" files one task (unapproved until you approve its scope)"),write(` title ${template.title}`)):(write(" makes a scheduled flow (nothing repeats until you turn the schedule on)"),write(` name ${template.title}`),write(` schedule ${template.schedule}`)),write(` goal ${template.goal}`),template.outOfScope!==null&&write(` not ${template.outOfScope}`),template.touches.length>0&&write(` touches ${template.touches.join(", ")}`),write(""),write("You will probably edit:");for(const hint of template.edit)write(` - ${hint}`);return write(""),write(`\`toolroll template apply ${template.name} --repo <path>\` previews the exact filing.`),EXIT.ok}if(template.kind==="recipe")return fail(write,json,"template apply","recipe",`${template.name} cannot be applied: ${template.why} \`toolroll template show ${template.name}\` walks the ceremonies.`,EXIT.refused);const repoGiven=text(flags,"repo");if(repoGiven===void 0)return fail(write,json,"template apply","usage","which repository? --repo <path> — a template never guesses where work lands",EXIT.usage);const goal=text(flags,"goal")??template.goal,outOfScope=text(flags,"not")??template.outOfScope,touches=text(flags,"touches")===void 0?template.touches:(text(flags,"touches")??"").split(",").map(one=>one.trim()).filter(one=>one!=="");if(template.kind==="task"){const title=text(flags,"title")??template.title,draft={kind:"task",title,repo:canonicalProject(repoGiven)??resolve(repoGiven),goal,outOfScope,touches,filedVia:`template:${template.name}`};if(!flags.has("file"))return json?(write(envelopeJson({ok:!1,command:"template apply",reason:"unconfirmed",draft})),3):(write("Would file, exactly (edit with --title/--goal/--not/--touches):"),write(""),write(` task ${draft.title}`),write(` repo ${draft.repo}`),write(` goal ${draft.goal}`),draft.outOfScope!==null&&write(` not ${draft.outOfScope}`),draft.touches.length>0&&write(` touches ${draft.touches.join(", ")}`),write(""),write("Nothing was filed. Re-run with --file to file it — UNAPPROVED either way."),3);const made2=fileTaskProposal(store,{title,repo:repoGiven,goal,outOfScope,touches,acceptance:template.acceptance,filedVia:`template:${template.name}`},clock());if(!made2.ok)return fail(write,json,"template apply",made2.reason,made2.message,made2.reason==="duplicate"?EXIT.refused:EXIT.usage);const filedLink=consoleLinkFor(context,`/t/${encodeURIComponent(made2.id)}`);return succeed(write,json,"template apply",{filed:"task",id:made2.id,approved:!1,...filedLink===null?{}:{links:{task:filedLink}}},()=>[`Filed ${made2.id} from template ${template.name}.`,"","UNAPPROVED — NO AUTHORITY GRANTED. It builds only after you approve its scope:",` toolroll task show ${made2.id}`,...filedLink===null?[]:[` ${filedLink}`]])}const flowName=text(flags,"name")??template.title,scheduleGiven=text(flags,"schedule")??template.schedule,schedule=parseSchedule(scheduleGiven)!==null?scheduleGiven:scheduleFromWords(scheduleGiven)??scheduleGiven,ceilingGiven=text(flags,"ceiling"),costCeilingUsd=ceilingGiven===void 0?template.costCeilingUsd:Number(ceilingGiven),repo=canonicalProject(repoGiven)??resolve(repoGiven),terms={goal,outOfScope,touches,requirements:template.requirements,acceptance:template.acceptance,budgetPerRunMicrousd:null,costCeilingUsd};if(!flags.has("file")){const draft={kind:"scheduled flow",name:flowName,repo,schedule,...terms,filedVia:`template:${template.name}`};if(json)return write(envelopeJson({ok:!1,command:"template apply",reason:"unconfirmed",draft})),3;const readable=parseSchedule(schedule);return write("Would make this scheduled flow (edit with --name/--goal/--not/--touches/--schedule/--ceiling):"),write(""),write(` flow ${draft.name}`),write(` repo ${draft.repo}`),write(` schedule ${readable===null?schedule:describeSchedule(readable)}`),write(` goal ${draft.goal}`),draft.outOfScope!==null&&write(` not ${draft.outOfScope}`),draft.touches.length>0&&write(` touches ${draft.touches.join(", ")}`),draft.costCeilingUsd!==null&&write(` ceiling $${draft.costCeilingUsd} every 7 days`),write(""),write("Nothing was made. Re-run with --file to make it. Nothing repeats until you turn the schedule on."),3}const made=createScheduledFlow(store,{repo,name:flowName,stem:template.name,schedule,terms,by:context.principal?.account??"toolroll",filedBy:context.principal?.account??null},clock());if(!made.ok)return fail(write,json,"template apply","bad-terms",made.message,EXIT.usage);const flowLink=consoleLinkFor(context,`/flows/${made.flow}`);return succeed(write,json,"template apply",{filed:"scheduled flow",flow:made.flow,trigger:made.trigger,on:!1,...flowLink===null?{}:{links:{flow:flowLink}}},()=>[`Made ${flowName}, flow #${made.flow}, from template ${template.name}.`,"","Nothing repeats until you turn the schedule on; each run then waits for approval under the project's rules:",` toolroll flows trigger resume ${made.flow} ${made.trigger}`,...flowLink===null?[]:[` ${flowLink}`]])}function readTokenFile(path){if(path!==void 0)try{const raw=readFileSync(path,"utf8").trim();return raw===""?void 0:raw}catch{return}}async function daemonCommand(positional,flags,context){const{store,write,json}=context,demoFence=refuseDemo(context,"daemon");if(demoFence!==null)return demoFence;const[action="status"]=positional,repo=repoFrom(flags),configDir=dirname(context.telegramTokenFile),supervise=context.gitRunner??run,binFlag=text(flags,"bin"),resolveBin=async()=>{const direct=daemonLaunchCommand({execPath:process.execPath,...process.argv[1]===void 0?{}:{entry:resolve(process.argv[1])},...binFlag===void 0?{}:{explicitBin:resolve(binFlag)}});if(direct!==null)return direct;const found=await supervise("sh",["-lc","command -v toolroll || command -v standing-orders"]);return found.code===0&&found.stdout.trim()!==""?{bin:process.execPath,binArgs:[found.stdout.trim()]}:null};if(action==="install"){const runnerName=text(flags,"runner"),inlineToken=text(flags,"token"),tokenPath=text(flags,"token-file");if(inlineToken!==void 0&&tokenPath!==void 0)return fail(write,json,"daemon install","usage","choose one credential source: --token or --token-file",EXIT.usage);const token=inlineToken??readTokenFile(tokenPath);if(runnerName===void 0||token===void 0)return fail(write,json,"daemon install","usage","`toolroll daemon install --runner <name> (--token <t> | --token-file <path>) --repo <path>` (plus any watch flags to bake in)",EXIT.usage);const auth=authenticate(store,runnerName,token);if(!auth.ok)return fail(write,json,"daemon install",auth.reason,describeAuth(auth.reason,runnerName),EXIT.refused);const heartbeatBefore=store.getRunner(runnerName)?.runner.heartbeatAt??null,located=await resolveBin();if(located===null)return fail(write,json,"daemon install","no-bin","`toolroll` is not on the PATH the service would use — run `toolroll link` first, or pass --bin <absolute path>",EXIT.refused);const watchFlags=[];for(const name of["pool","model","repair-model","provider","plan-model","plan-provider","max","turns","tick-every","bridge-every","reconcile-every","containment"]){const value=text(flags,name);value!==void 0&&watchFlags.push(`--${name}`,value)}watchFlags.includes("--containment")||watchFlags.push("--containment",currentContainment().policy);const plan2=planDaemon({platform:process.platform,bin:located.bin,binArgs:located.binArgs,runner:runnerName,repo,configDir,watchFlags});if("error"in plan2)return fail(write,json,"daemon install","unsupported",plan2.error,EXIT.refused);const legacy2=installedLegacyDaemon({platform:process.platform,bin:located.bin,binArgs:located.binArgs,runner:runnerName,repo,configDir,watchFlags});if(flags.has("dry-run"))return json?(write(envelopeJson({ok:!0,command:"daemon install",dryRun:!0,plan:plan2,replaces:legacy2?.label??null})),EXIT.ok):(write(`Would write ${plan2.unitPath}:`),write(""),write(plan2.unitContent),write(`Token (0600): ${plan2.tokenFile} · logs: ${plan2.logPath}`),legacy2!==null&&write(`Would stop and remove ${legacy2.label} (${legacy2.unitPath}), the same watch under its older name.`),write("Nothing was written. Re-run without --dry-run to install."),EXIT.ok);const installed=await installReplacingLegacy(plan2,token,legacy2,supervise);if(!installed.ok)return fail(write,json,"daemon install","supervisor",installed.message,EXIT.failed);const readySince=legacy2===null?heartbeatBefore:store.getRunner(runnerName)?.runner.heartbeatAt??null,started=await daemonStatus(plan2,supervise);if(started.state!=="running")return fail(write,json,"daemon install","not-running",`the service was installed but did not stay running (${started.detail}) — read ${plan2.logPath}; no work will be claimed until this is fixed`,EXIT.failed);const liveRunner=(await awaitFreshHeartbeat(store,runnerName,installed.action==="running"&&legacy2===null?null:readySince)).ok?store.getRunner(runnerName)?.runner??null:null;if(liveRunner===null){const macHint=process.platform==="darwin"&&repo.startsWith(join(homedir(),"Documents"))?" macOS may be blocking background access to Documents; grant the Node executable Full Disk Access, move the repository outside a protected folder, or keep `toolroll up` running from your terminal.":"";return fail(write,json,"daemon install","not-ready",`the supervisor has a process, but ${runnerName} never reached its worker heartbeat.${macHint} Read ${plan2.logPath}; no work will be claimed until the heartbeat appears`,EXIT.failed)}return succeed(write,json,"daemon install",{label:plan2.label,unit:plan2.unitPath,logs:plan2.logPath,state:started.state,pid:started.pid,heartbeatAt:liveRunner.heartbeatAt,action:installed.action,changed:installed.changed,replaced:legacy2?.label??null,containment:containmentStatus(currentContainment())},()=>[installed.action==="running"?`${plan2.label} was already running under this exact definition; left alone.`:installed.action==="reloaded"?`Reloaded ${plan2.label} under its changed definition.`:`Installed and started ${plan2.label}.`,...legacy2===null?[]:[` replaced ${legacy2.label} (stopped and removed)`],` verified ${started.detail}`,` worker ${runnerName} answered at ${liveRunner.heartbeatAt}`,` unit ${plan2.unitPath}`,` token ${plan2.tokenFile} (0600 — the unit never carries it)`,` logs ${plan2.logPath}`,"","It survives reboots and restarts itself after crashes; watch's","incarnation recovery makes those restarts safe. `toolroll daemon","status` to check on it, `daemon uninstall` to take it back off."])}const planArgs={platform:process.platform,bin:binFlag??"toolroll",binArgs:[],runner:text(flags,"runner")??"runner",repo,configDir,watchFlags:[]},current=planDaemon(planArgs);if("error"in current)return fail(write,json,`daemon ${action}`,"unsupported",current.error,EXIT.refused);const legacy=installedLegacyDaemon(planArgs),plan=legacy!==null&&!existsSync(current.unitPath)?legacy:current;if(action==="status"){const state=await daemonStatus(plan,supervise),containment=currentContainment();return json?(write(envelopeJson({ok:!0,command:"daemon status",...state,label:plan.label,logs:plan.logPath,containment:containmentStatus(containment)})),state.state==="running"?EXIT.ok:EXIT.refused):(write(`${plan.label}: ${state.detail}`),write(` logs ${plan.logPath}`),write(` ${describeContainment(containment)}`),state.state==="not-installed"&&write(" → toolroll daemon install --runner <name> --token <t> --repo <path>"),state.state==="disabled"&&write(" → the service is disabled: `toolroll daemon install` re-enables and loads it"),state.state==="running"?EXIT.ok:EXIT.refused)}if(action==="uninstall"){const gone=await uninstallDaemon(current,supervise),legacyGone=legacy===null?null:await uninstallDaemon(legacy,supervise);return succeed(write,json,"daemon uninstall",{removed:gone.existed||legacyGone?.existed===!0},()=>[...gone.existed||legacyGone===null?[gone.existed?`Stopped and removed ${current.label}.`:`${current.label} was not installed; nothing to remove.`]:[],...legacyGone===null?[]:[`Stopped and removed ${legacy.label}.`]])}return action==="logs"?succeed(write,json,"daemon logs",{logs:plan.logPath},()=>[plan.logPath,` → tail -f ${plan.logPath}`]):fail(write,json,"daemon","usage","`toolroll daemon [install|status|uninstall|logs]`",EXIT.usage)}const WATCH_LEASE_MS=MAX_WATCH_LEASE_MS,WATCH_HEARTBEAT_MS=RUNNER_HEARTBEAT_MS;function startTelegramFollower(args){const{context,progress,label}=args,source=loadBotToken(process.env,context.telegramTokenFile);if(source===null)return null;const fence=networkFence(context.telegramEnv??(context.telegramTransport===void 0?process.env:{}));if(fence!==null)return progress(networkFenceLine(fence)),null;const transport=context.telegramTransport??createTransport(source.token),pushUrl=telegramPushUrl(readHooksBase(dirname(context.databaseFile)));return followBridge(context.store,{push:pushUrl===null?null:{url:pushUrl,secret:telegramHookSecret(dirname(context.databaseFile),!0)},readProjects:telegramReadProjects(context),canDeliver:telegramCanDeliver(context,source.token),conversation:telegramConversation(context,args.publicUrl===void 0?{}:{serverOrigin:args.publicUrl}),botId:source.botId,transport,signal:args.signal,...args.owner===void 0?{}:{owner:args.owner},onCycle:cycle=>{progress(`${label} sent ${cycle.sent}, answered ${cycle.answered}, paired ${cycle.paired}`+((cycle.statusReplies??0)>0?`, status replies ${cycle.statusReplies}`:"")+((cycle.chatQueued??0)>0?`, chat received ${cycle.chatQueued}`:"")+((cycle.chatAnswered??0)>0?`, chat replied ${cycle.chatAnswered}`:"")+((cycle.chatConfirmed??0)>0?`, chat confirmed ${cycle.chatConfirmed}`:"")+(cycle.problems.length>0?` — ${cycle.problems.length} problem(s): ${cycle.problems[0].slice(0,200)}`:""))}}).catch(error=>(progress(`${args.died.prefix}the telegram follower died — ${describe(error)}; ${args.died.next}`),null))}const TELEGRAM_STOP_WAIT_MS=5e3,CLEANUP_SLOW_MS=3e4,SHUTDOWN_DEADLINE_MS=6e4,WORKER_ALIVE_EVERY_MS=5e3,WORKER_SILENCE_MS=6e4;let staleStatusesRepaired=!1;async function runWatchLoop(args){const{context,flags,runner,token,repo,progress}=args,{store}=context;noticeGitIncidents(store,context.clock);const tickEveryMs=Number(text(flags,"tick-every")??6e4),bridgeEveryMs=Number(text(flags,"bridge-every")??45e3),reconcileEveryMs=Number(text(flags,"reconcile-every")??5*6e4),runFor=text(flags,"for")===void 0?null:Number(text(flags,"for"));if(!Number.isSafeInteger(reconcileEveryMs)||reconcileEveryMs<1||reconcileEveryMs>2147483647)throw new Error("--reconcile-every must be an integer from 1 to 2147483647 milliseconds");const incarnation=`${runFor===null?"toolroll-service:":""}${randomUUID()}`;let lease=acquireWatchLeaseAuthed(store,{runner,token,repo,owner:incarnation,ttlMs:WATCH_LEASE_MS},new Date);const waitUntil=Date.now()+(args.leaseWaitMs??0);let saidWaiting=!1;const waitStopping=args.leaseWaitStopping??args.isStopping;for(;!lease.ok&&lease.reason==="watch-busy"&&Date.now()<waitUntil&&!waitStopping();)saidWaiting||progress(`watch: ${repo} is still held by the previous worker until ${lease.until??"its lease lapses"}; taking it over then`),saidWaiting=!0,await new Promise(resolve2=>setTimeout(resolve2,1e3)),lease=acquireWatchLeaseAuthed(store,{runner,token,repo,owner:incarnation,ttlMs:WATCH_LEASE_MS},new Date);if(!lease.ok)return{ok:!1,reason:"watch-busy",detail:lease.reason==="watch-busy"?`another watch holds ${runner} on ${repo} until ${lease.until} — one watch per runner and repo; cron ticks may coexist, watches may not`:describeAuth(lease.reason,runner),ticks:0,built:0,broke:0};lease.superseded!==null&&lease.recovered>0&&progress(`Recovered ${lease.recovered} claim(s) from the previous watch (${lease.superseded.slice(0,8)}…) before dispatching anything.`);for(const line of args.containmentLines?.(currentContainment())??[`watch: ${describeContainment(currentContainment())}`])progress(line);store.startWatchEpisode({repo,runner,incarnation},new Date);try{notifyVersionLive(store,dirname(context.databaseFile),PACKAGE_VERSION,new Date)}catch{}if(recordRunnerVersion(dirname(context.databaseFile),runner,PACKAGE_VERSION,new Date),args.onReady?.(),!staleStatusesRepaired){staleStatusesRepaired=!0;const repaired=repairStaleStatuses(store,new Date);repaired.exitsRecorded>0&&progress(`watch: recorded ${repaired.exitsRecorded} finished process exit(s) left open by an earlier version`)}let leaseLost=!1,leaseLostReason=null,custodyUnknown=!1;const followController=new AbortController,hub=wakeHubFor(store,read=>briefly(store,read)),wakes=new WakePoker;args.onFollowController?.(followController);let failed=!1,failure;const fail2=error=>{failed||(failure=error),failed=!0,wakes.poke()},stopping=()=>args.isStopping()||leaseLost||failed,heartbeatEveryMs=context.watchHeartbeatMs??WATCH_HEARTBEAT_MS;let heartbeatTimer=null,heartbeatStopped=!1,busyBeats=0;const scheduleBeat=ms=>{heartbeatStopped||(heartbeatTimer=setTimeout(beat,ms),heartbeatTimer.unref?.())};function beat(){if(heartbeatTimer=null,heartbeatStopped||leaseLost)return;let answer=null,problem=null;try{answer=briefly(store,()=>renewWatchLeaseAuthed(store,{runner,token,repo,owner:incarnation,ttlMs:WATCH_LEASE_MS},new Date))}catch(error){if(isDatabaseBusy(error)){busyBeats++,custodyUnknown||progress(`watch: ${runner} on ${repo}: the database is busy, so this worker can't prove it still holds the project yet — no new work starts until it can`),custodyUnknown=!0,scheduleBeat(Math.min(heartbeatEveryMs,1e3*2**Math.min(busyBeats-1,4)));return}problem=`renewal could not be proved: ${describe(error)}`}if(answer!==null&&answer.ok){busyBeats=0,answer.lateMs>0&&progress(`watch: renewal late by ${Math.max(1,Math.round(answer.lateMs/1e3))}s — this worker still holds ${repo}; carrying on`),custodyUnknown&&(custodyUnknown=!1,progress(`watch: ${runner} on ${repo}: proved it still holds the project — new work may start again`),wakes.poke()),scheduleBeat(heartbeatEveryMs);return}leaseLostReason=answer===null?"error":answer.reason,leaseLost=!0,followController.abort(),wakes.poke(),progress(`watch: ${runner} on ${repo}: ${problem??renewalRefusedWords(answer.reason)} — stopping without admitting more work`)}scheduleBeat(heartbeatEveryMs);const stopHeartbeat=()=>{heartbeatStopped=!0,heartbeatTimer!==null&&clearTimeout(heartbeatTimer),heartbeatTimer=null};let cleanupStage=null,lastPassAt=null;args.health?.(()=>({repo,leaseLive:!leaseLost&&!custodyUnknown&&cleanupStage===null,lastPassAt,stopping:stopping(),cleanup:cleanupStage}));const serviceBridge=args.serviceBridge===!0,follower=serviceBridge?null:startTelegramFollower({context,publicUrl:text(flags,"public-url"),signal:followController.signal,progress,label:"watch: bridge",died:{prefix:"watch: ",next:"taps wait for the next watch"}}),slackFollower=superviseChatFollower("Slack",followController.signal,progress,()=>followSlack({store,dir:dirname(context.databaseFile),signal:followController.signal,readProjects:telegramReadProjects(context),evidenceRoot:context.evidenceRoot,...context.leadSeams?.subscriptionRunner?{subscriptionRunner:context.leadSeams.subscriptionRunner}:{},origin:()=>phoneOrigin(process.env,dirname(context.databaseFile),{serverOrigin:text(flags,"public-url")??null}),notifications:()=>effectivePrimary(process.env,dirname(context.databaseFile),loadBotToken(process.env,context.telegramTokenFile)!==null).channel==="slack"})),teamsFollower=superviseChatFollower("Teams",followController.signal,progress,()=>followTeams({store,dir:dirname(context.databaseFile),signal:followController.signal,readProjects:telegramReadProjects(context),evidenceRoot:context.evidenceRoot,...context.leadSeams?.subscriptionRunner?{subscriptionRunner:context.leadSeams.subscriptionRunner}:{},origin:()=>phoneOrigin(process.env,dirname(context.databaseFile),{serverOrigin:text(flags,"public-url")??null}),notifications:()=>effectivePrimary(process.env,dirname(context.databaseFile),loadBotToken(process.env,context.telegramTokenFile)!==null).channel==="teams"})),discordFollower=superviseChatFollower("Discord",followController.signal,progress,()=>followDiscord({store,dir:dirname(context.databaseFile),signal:followController.signal,readProjects:telegramReadProjects(context),evidenceRoot:context.evidenceRoot,...context.leadSeams?.subscriptionRunner?{subscriptionRunner:context.leadSeams.subscriptionRunner}:{},origin:()=>phoneOrigin(process.env,dirname(context.databaseFile),{serverOrigin:text(flags,"public-url")??null}),notifications:()=>effectivePrimary(process.env,dirname(context.databaseFile),loadBotToken(process.env,context.telegramTokenFile)!==null).channel==="discord"})),quiet=[],sink=line=>quiet.push(line),passFlags=(extra={})=>{const copy=new Map(flags);copy.set("json",!0),copy.set("incarnation",incarnation);for(const[key,value]of Object.entries(extra))copy.set(key,value);return copy};let reconciliationReady=!1,reconciliationFailure=null,reconciliationBusy=!1;const paused=()=>custodyUnknown||!reconciliationReady||updateAdmissionPaused(store.raw())||context.shouldPauseAdmission?.()===!0,admissionStopped=()=>stopping()||paused(),quietContext={...context,write:sink,json:!0,shouldStop:stopping,shouldPauseAdmission:paused},startedAt=Date.now(),deadline=runFor===null?null:startedAt+runFor;let lastTick=0,lastBridge=0,ticks=0,built=0,brokeCount=0;const sweepOwner={},maintenance=startMaintenance({intervalMs:reconcileEveryMs,onStop:()=>storageSweepSupervisor(context.databaseFile).stop(sweepOwner),shouldStop:stopping,onError:error=>{reconciliationReady=!1;const detail=describe(error);detail!==reconciliationFailure&&progress(`watch: reconciliation failed — ${detail}; new work is paused until a recovery pass succeeds`),reconciliationFailure=detail,reconciliationBusy=busyFailure(error)},retryAfter:(error,failuresInARow)=>busyRetryAfter(busyFailure(error),failuresInARow),run:async()=>{const maintenanceLines=[],maintenanceContext={...quietContext,...runFor===null?{sweepOwner}:{},write:line=>maintenanceLines.push(line)};if(runFor!==null&&delete maintenanceContext.sweepOwner,await reconcileCommand(passFlags(),maintenanceContext)!==EXIT.ok)throw new Error(maintenanceLines.join(" "));reconciliationFailure!==null&&progress("watch: reconciliation recovered — new work may resume");const recovered=!reconciliationReady;if(reconciliationFailure=null,reconciliationReady=!0,recovered&&wakes.poke(),!stopping()){try{const shipped=await flexibleArmedPass(store,{root:context.evidenceRoot,...context.publishExec===void 0?{}:{exec:context.publishExec}});shipped.ok&&shipped.merged>0&&progress(`watch: merged ${shipped.merged} Flexible result(s) whose checks passed`),shipped.ok&&shipped.cancelled>0&&progress(`watch: stopped ${shipped.cancelled} Flexible merge(s) whose terms no longer held`)}catch(error){progress(`watch: the Flexible ship pass failed — ${describe(error)}; retrying on its next interval`)}try{const dcShipped=await directChatArmedPass(store,{root:context.evidenceRoot,...context.publishExec===void 0?{}:{exec:context.publishExec}});dcShipped.merged>0&&progress(`watch: merged ${dcShipped.merged} Direct Chat result(s) whose checks passed`),dcShipped.cancelled>0&&progress(`watch: stopped ${dcShipped.cancelled} Direct Chat merge(s) whose terms no longer held`)}catch(error){progress(`watch: the Direct Chat ship pass failed — ${describe(error)}; retrying on its next interval`)}}if(!stopping()&&store.openedPublications().length>0)try{const checks=await observeChecks(store,context.publishExec===void 0?{}:{exec:context.publishExec});checks.failing>0&&progress(`watch: CI is red on ${checks.failing} published PR(s) — the outbox has it`);const followed=await followPullRequests(store,checks.seen,{evidenceRoot:context.evidenceRoot,...context.publishExec===void 0?{}:{exec:context.publishExec}});followed.revisions>0&&progress(`watch: filed ${followed.revisions} CI revision(s)`),followed.merged>0&&progress(`watch: merged ${followed.merged} pull request(s) whose checks passed`)}catch(error){progress(`watch: CI observation failed — ${describe(error)}; retrying on its next interval`)}}}),followUpChecks=startMaintenance({intervalMs:5e3,shouldStop:stopping,onError:error=>progress(`watch: a follow-up check failed to run — ${describe(error)}; it is recorded on the result`),run:async()=>{if(store.isDemo())return;const batched=await runBatchChecks(store,context.evidenceRoot,{now:context.clock,shouldStop:stopping});batched>0&&progress(`watch: settled ${batched} batch-checked result(s)`),context.agentRunner===void 0&&resumeHeldReleases(store,dirname(context.databaseFile),context.clock()),context.agentRunner===void 0&&context.databaseFile!==":memory:"&&sweepOrphanedReleases(store,context.databaseFile,dirname(context.databaseFile),context.clock()).then(resumed=>{for(const one of resumed)progress(`watch: ${basename(one.file,".json")}: continued the release by itself — ${one.why}`)}),requestMissingRechecks(store,context.evidenceRoot,context.clock()),resumeParkedRepairs(store,context.evidenceRoot,context.clock());const ran=await runWaitingChecks(store,context.evidenceRoot,{now:context.clock,shouldStop:stopping});ran>0&&progress(`watch: ran ${ran} follow-up check(s)`);const pendingLand=await runPendingLocalLands(store,context.clock(),{root:context.evidenceRoot,...context.gitRunner===void 0?{}:{git:context.gitRunner}});pendingLand.landed.length>0&&progress(`watch: landed ${pendingLand.landed.length} queued local task(s)`),await refreshTrustedMains(store,context.evidenceRoot,context.clock(),context.gitRunner);const settledChecks=settleReleaseChecks(store,context.evidenceRoot,context.clock());settledChecks>0&&progress(`watch: settled ${settledChecks} release check(s)`),context.agentRunner===void 0&&await refreshGithubNightlies(store,context.clock),context.agentRunner===void 0&&await refreshLearning(store,context.clock),ran+batched>0&&moveCards(store,repo,context.clock(),context.evidenceRoot)}}),reviewEveryMs=context.reviewEveryMs??REVIEW_BEAT_MS,canonicalRepo=canonicalProject(repo)??resolve(repo),reviewSlots=startReviewSlots(store,{slots:REVIEW_SLOTS,onReport:report=>progress(`watch: review of run ${report.run} — ${report.outcome} (${report.detail})`),onSlotFree:()=>{stopping()||reviewBeat.runNow()}}),reviewBeat=startMaintenance({intervalMs:reviewEveryMs,shouldStop:stopping,onError:error=>progress(`watch: the review pass failed — ${describe(error)}; retrying on its next beat`),retryAfter:(error,failuresInARow)=>busyRetryAfter(busyFailure(error),failuresInARow),run:async()=>{if(paused())return;store.expireOverdueDecisions(context.clock());const auth=authenticate(store,runner,token);if(auth.ok){const reviewRepos=auth.runner.repos.includes(canonicalRepo)?[canonicalRepo]:[];reviewSlots.start({runner,token,repos:reviewRepos,root:context.evidenceRoot,clock:context.clock,watchIncarnation:incarnation,...context.agentRunner===void 0?{}:{agent:context.agentRunner},shouldStop:admissionStopped}),syncAssignmentHandoffs(store,context.clock(),auth.runner.repos,context.evidenceRoot)}}}),publishBeat=startMaintenance({intervalMs:reviewEveryMs,shouldStop:stopping,onError:error=>progress(`watch: the publish pass failed — ${describe(error)}; retrying on its next beat`),retryAfter:(error,failuresInARow)=>busyRetryAfter(busyFailure(error),failuresInARow),run:async()=>{if(!paused()&&!admissionStopped()&&store.pendingPublications().length>0){const published=await publishPass(store,{repo,evidenceRoot:context.evidenceRoot,...context.publishExec===void 0?{}:{exec:context.publishExec}});published.pushed+published.opened+published.adopted+published.failed>0&&progress(`watch: published — pushed ${published.pushed}, opened ${published.opened}, adopted ${published.adopted}`+(published.failed>0?`, gave up on ${published.failed}`:""))}}}),codeMapChecks=startMaintenance({intervalMs:6e4,shouldStop:stopping,onError:error=>progress(`watch: a code map check failed — ${describe(error)}; it tries again`),run:async()=>{store.isDemo()||context.agentRunner!==void 0||(await refreshCodeMaps(store,{scratch:join(context.evidenceRoot,".code-map"),clock:context.clock}),sweepDeliveries(store))}}),flowEveryMs=context.flowEveryMs??FLOW_EVERY_MS,flowPool=text(flags,"pool")??join(dirname(databasePath(process.env,homedir())),"worktrees"),flowGit=context.gitRunner??run,flowsDid=(moved,filed,did)=>{moved+filed!==0&&(store.bumpWake(),progress(`watch: ${did}`))},flowMoves=startMaintenance({intervalMs:flowEveryMs,shouldStop:stopping,onError:error=>progress(`watch: flow cards couldn't move — ${describe(error)}; they try again shortly`),run:async()=>{if(paused())return;const moved=moveCards(store,repo,context.clock(),context.evidenceRoot);flowsDid(moved.moved,moved.filed.length,`moved ${moved.moved} flow card(s), filed ${moved.filed.length} task(s)`)}}),flowSteps=startMaintenance({intervalMs:flowEveryMs,shouldStop:stopping,onError:error=>progress(`watch: a flow pass failed — ${describe(error)}; it runs again shortly`),run:async()=>{if(paused())return;let base=text(flags,"base");if(base===void 0){const head=await flowGit("git",["symbolic-ref","--short","-q","HEAD"],{cwd:repo});if(head.code!==0||head.stdout.trim()==="")return;base=head.stdout.trim()}const pass=await flowHousekeeping(store,repo,context.clock,flowIoOf(context,flowPool,flowGit,base),admissionStopped);flowsDid(pass.flows.moved+pass.triggers.added+pass.steps.ran+pass.replies.taken,pass.flows.filed.length+pass.youiyoux.filed,`flow pass — ${pass.triggers.added} card(s) added, ${pass.youiyoux.filed} youiyoux request(s) filed, ${pass.replies.taken} reply(ies) taken, ${pass.steps.ran} step(s) run, ${pass.flows.moved} moved`)}}),modelWatch=startMaintenance({intervalMs:15*6e4,shouldStop:stopping,onError:error=>progress(`watch: the model check failed — ${describe(error)}; it retries later`),run:async()=>{await modelWatchPass(store,context.clock())&&progress("watch: checked models and CLI versions")}}),leaveServiceBeats=joinServiceBeats({context,progress,ciReady:()=>!admissionStopped(),stopping}),passes=args.passes??new ProjectPasses,slotFacts=yieldingSince=>{const now=new Date,found=store.getRunner(runner),bound=new Set(found?.runner.repos??[repo]),saved=savedProjectConcurrency(context.databaseFile);return{repo,capacity:found?.runner.capacity??1,running:store.liveClaimCountsByRepo(runner,now),limitOf:one=>saved.get(one)??PROJECT_CONCURRENCY_DEFAULT,waiting:new Set(store.listReady(now,runner).map(one=>one.repo).filter(one=>one!==null&&bound.has(one))),yieldingSince,passes}},lanes=[],buildLane=async index=>{const laneLines=[],laneContext={...quietContext,write:line=>laneLines.push(line)};let yieldingSince=null,yieldingTo=null;for(;!stopping()&&(deadline===null||Date.now()<deadline);){const seqBefore=store.wakeSeq();let broke=!1;if(!paused()){const facts=slotFacts(yieldingSince),answer=index<effectiveConcurrency(facts.limitOf(repo),facts.capacity)?maySlotTake(facts):null;if(answer!==null&&answer.take){yieldingSince=null,yieldingTo=null,laneLines.length=0;let code=EXIT.failed;try{code=await tickCommand(passFlags({"builds-only":"1"}),laneContext)}catch(error){laneLines.push(JSON.stringify({dispatched:[{id:"?",outcome:"failed",reason:"lane",detail:describe(error)}]}))}if(passes.passed(repo),code===EXIT.ok){built++,reviewBeat.runNow(),publishBeat.runNow(),progress(`watch: build ${index+1} did work (${new Date().toISOString()})`);continue}code===EXIT.failed&&(brokeCount++,broke=!0,progress(`watch: build ${index+1} — ${brokenWords(laneLines)}`))}else answer!==null&&!answer.take&&answer.why==="fair-share"?(yieldingSince===null&&(yieldingSince=passes.stamp(),store.bumpWake()),yieldingTo=answer.to??null):(yieldingSince=null,yieldingTo=null)}if(!broke&&store.wakeSeq()!==seqBefore)continue;const seqIdle=store.wakeSeq(),dozeUntil=Math.min(Date.now()+tickEveryMs,deadline??Number.MAX_SAFE_INTEGER),theirTurnEnded=()=>yieldingTo!==null&&yieldingSince!==null&&passes.lastPass(yieldingTo)>yieldingSince;await hub.changed({baseline:seqIdle,deadline:dozeUntil,until:()=>stopping()||theirTurnEnded(),poker:wakes})}},ensureLanes=()=>{const facts=slotFacts(null),wanted=effectiveConcurrency(facts.limitOf(repo),facts.capacity);for(;lanes.length<wanted&&!stopping();)lanes.push(buildLane(lanes.length).catch(fail2))};try{for(await maintenance.runNow();!stopping()&&(deadline===null||Date.now()<deadline);){if(paused()){await hub.changed({baseline:store.wakeSeq(),deadline:Date.now()+1e3,until:stopping,poker:wakes});continue}ensureLanes();const seqBefore=store.wakeSeq(),now=Date.now();reviewBeat.runNow(),publishBeat.runNow();let tickBroke=!1;{lastTick=now,quiet.length=0;const code=await tickCommand(passFlags({"housekeeping-only":"1"}),quietContext);ticks++,lastPassAt=new Date().toISOString(),code===EXIT.failed&&(brokeCount++,tickBroke=!0,progress(`watch: pass ${ticks} — ${brokenWords(quiet)}`))}try{store.sealLedger()}catch(error){progress(`watch: the ledger chain could not be sealed this pass (${error instanceof Error?error.message:String(error)})`)}if(follower===null&&now-lastBridge>=bridgeEveryMs){lastBridge=now;const source=serviceBridge?null:loadBotToken(process.env,context.telegramTokenFile),dir=dirname(context.databaseFile),primary=effectivePrimary(process.env,dir,source!==null);source!==null&&(quiet.length=0,await bridgeCommand(["telegram"],passFlags(primary.channel==="telegram"?{}:{"inbound-only":"1"}),quietContext))}if(!tickBroke&&store.wakeSeq()!==seqBefore)continue;const idleUntil=Math.min(lastTick+tickEveryMs,lastBridge+bridgeEveryMs,deadline??Number.MAX_SAFE_INTEGER)-Date.now(),seqIdle=store.wakeSeq(),dozeUntil=Date.now()+Math.max(idleUntil,0);await hub.changed({baseline:seqIdle,deadline:dozeUntil,until:stopping,poker:wakes})}}catch(error){fail2(error)}finally{const step=async(name,work)=>{cleanupStage=name;const slow=setTimeout(()=>progress(`watch: stopping is still waiting on ${name}`),CLEANUP_SLOW_MS);slow.unref?.();try{await work()}finally{clearTimeout(slow)}};await step("its builds",()=>Promise.all(lanes)),await step("its reviews",async()=>{await reviewBeat.stop(),await reviewSlots.drain();try{const last=authenticate(store,runner,token);last.ok&&syncAssignmentHandoffs(store,context.clock(),last.runner.repos,context.evidenceRoot)}catch(error){progress(`watch: the last handoff sync failed — ${describe(error)}; the next pass sends it`)}}),await step("publishing",()=>publishBeat.stop()),await step("reconciliation",()=>maintenance.stop()),await step("follow-up checks",()=>followUpChecks.stop()),await step("the code map check",()=>codeMapChecks.stop()),await step("flow moves",()=>flowMoves.stop()),await step("flow steps",()=>flowSteps.stop()),await step("the model check",()=>modelWatch.stop()),await step("deliveries and fast CI",()=>leaveServiceBeats()),stopHeartbeat(),followController.abort(),follower!==null&&await step("the Telegram follower",()=>follower),await step("the Slack follower",()=>slackFollower),await step("the Teams follower",()=>teamsFollower),await step("the Discord follower",()=>discordFollower),cleanupStage="releasing the project",store.endWatchEpisode(incarnation,{ticks,built,broke:brokeCount},new Date),store.releaseWatchLease(runner,repo,incarnation,new Date),cleanupStage=null}if(failed)throw failure;return leaseLost?{ok:!1,reason:"lease-lost",lost:leaseLostReason??"error",detail:`the watch lease for ${runner} on ${repo} stopped renewing — ${renewalRefusedWords(leaseLostReason??"error")}`,ticks,built,broke:brokeCount}:reconciliationFailure!==null?{ok:!1,reason:"reconciliation-failed",detail:reconciliationFailure,ticks,built,broke:brokeCount,busy:reconciliationBusy}:{ok:!0,ticks,built,broke:brokeCount,incarnation}}function brokenWords(lines){try{const failed=(JSON.parse(lines[lines.length-1]??"").dispatched??[]).filter(one=>one.outcome==="failed");return failed.length===0?"a pass broke something — the run records have it":`${failed.slice(0,3).map(one=>`${one.id} failed (${one.reason??"?"}${one.detail===void 0?"":`: ${one.detail}`})`).join("; ")}${failed.length>3?`; and ${failed.length-3} more`:""}`}catch{return"a pass broke something — the run records have it"}}async function watchCommand(flags,context){const{store,write,json}=context,demoFence=refuseDemo(context,"watch");if(demoFence!==null)return demoFence;const runner=text(flags,"runner"),token=text(flags,"token")??readTokenFile(text(flags,"token-file"));if(runner===void 0||token===void 0)return fail(write,json,"watch","usage","`toolroll watch --runner <name> --token <t>|--token-file <path> --repo <path> [--for <ms>]`",EXIT.usage);flags.set("token",token);const auth=authenticate(store,runner,token);if(!auth.ok)return fail(write,json,"watch",auth.reason,describeAuth(auth.reason,runner),EXIT.refused);const repo=repoFrom(flags),progress=longCommandProgress(write,json);let stopping=!1,graceTimer,followAbort=null;const stopGraceMs=Number(text(flags,"stop-grace")??3e4),hardStop=()=>{const terminated=terminateLiveProviders();terminated>0&&progress(`Hard stop: ${terminated} provider process group(s) terminated. Their work is saved and kept in each checkout, and each task continues from it; fences keep late output out of every commit. Run \`toolroll\` again to continue.`)},dropSignals=onStopSignals(()=>{if(stopping){hardStop();return}stopping=!0,followAbort?.abort(),wakeHubFor(context.store,read=>briefly(context.store,read)).poke(),graceTimer=setTimeout(hardStop,stopGraceMs)}),startedAt=Date.now();let result;try{result=await runWatchLoop({flags,context,runner,token,repo,progress,isStopping:()=>stopping||context.shouldStop?.()===!0,onFollowController:controller=>{followAbort=controller}})}finally{graceTimer!==void 0&&clearTimeout(graceTimer),dropSignals()}return result.ok?succeed(write,json,"watch",{ticks:result.ticks,built:result.built,broke:result.broke,incarnation:result.incarnation},()=>[`Watched ${repo} for ${Math.round((Date.now()-startedAt)/1e3)}s: ${result.ticks} pass(es), ${result.built} with work, ${result.broke} broke.`,"The lease is handed back; cron or the next watch may take it."]):fail(write,json,"watch",result.reason,result.detail,result.reason==="reconciliation-failed"||result.reason==="loop-failed"?EXIT.failed:EXIT.refused,{ticks:result.ticks,built:result.built,broke:result.broke})}const UP_LOGIN_FILE="up-login.txt";export function writeLoginFileDurably(path,name,password){const fd=openSync(path,fsConstants.O_WRONLY|fsConstants.O_CREAT|fsConstants.O_EXCL,384);try{writeSync(fd,`${name} ${password}
|
|
492
492
|
`),fsyncSync(fd)}finally{closeSync(fd)}const dir=openSync(dirname(path),fsConstants.O_RDONLY);try{fsyncSync(dir)}catch{}finally{closeSync(dir)}}function readLoginFile(path){if(activeRemote()!==null)throw new RemoteRefusal("unauthenticated",REMOTE_MESSAGES.credential);try{const raw=readFileSync(path,"utf8").trim(),cut=raw.indexOf(" ");if(cut<=0)return null;const name=raw.slice(0,cut),password=raw.slice(cut+1);return name===""||password===""?null:{name,password}}catch{return null}}async function resolveUpApprover(context,flags,canPrompt){const{store,clock}=context,stateDir=dirname(context.databaseFile),notes=[],local=localOwnerBinding(store);if(local!==null)return{approver:local.account,approvers:[local.account],verified:!1,passwordFile:null,mintedPassword:null,notes,startAuthority:"local"};const migration=migrateLegacyLogin(stateDir);migration.kind==="moved"?notes.push(`moved your saved login into ${migration.to} (owner-only, kept from agents)`):migration.kind==="both"?notes.push(`${migration.from} was left in place: ${migration.to} already holds a different login, and that one is used`):(migration.kind==="refused"||migration.kind==="failed")&¬es.push(`your saved login stays at ${migration.from} for now: ${migration.reason}`);let loginFile=savedLoginFile(stateDir);const asFlag=text(flags,"as");let names=store.listApprovers().map(one=>one.name);if(names.length===0){const orphan=readLoginFile(loginFile);if(orphan!==null){if(store.bootstrapApproverIfNone(orphan.name,hashApproverToken(orphan.password),clock()).ok)return notes.push(`adopted the login from ${UP_LOGIN_FILE} — a previous start was interrupted before it finished`),{approver:orphan.name,approvers:[orphan.name],verified:!0,passwordFile:loginFile,mintedPassword:null,notes,startAuthority:"full"};names=store.listApprovers().map(one=>one.name)}else{const name=asFlag??process.env.USER??process.env.USERNAME??"operator",password=mintSecret(12);try{loginFile=writableLoginFile(stateDir),writeLoginFileDurably(loginFile,name,password)}catch(error){return{refusal:`could not create ${loginFileOf(stateDir)} (${describe(error)}) — if a file is already there, another \`up\` may be starting; wait a moment, your login will be in it`}}if(store.bootstrapApproverIfNone(name,hashApproverToken(password),clock()).ok)return{approver:name,approvers:[name],verified:!0,passwordFile:loginFile,mintedPassword:password,notes,startAuthority:"full"};if(authenticateApprover(store,name,password).ok)return{approver:name,approvers:store.listApprovers().map(one=>one.name),verified:!0,passwordFile:loginFile,mintedPassword:null,notes,startAuthority:"full"};try{unlinkSync(loginFile)}catch{}names=store.listApprovers().map(one=>one.name)}}let fileLogin=null;const present=readLoginFile(loginFile);present!==null&&(authenticateApprover(store,present.name,present.password).ok?fileLogin=present:notes.push(`${UP_LOGIN_FILE} no longer matches any login — it is stale; your current password is the one you know`));let selected=null;if(asFlag!==void 0){if(!names.includes(asFlag))return{refusal:`no approver named \`${asFlag}\` — known: ${names.join(", ")}`};selected=asFlag}else names.length===1&&(selected=names[0]);let verified=!1,passwordFile=null;if(selected!==null&&fileLogin!==null&&fileLogin.name===selected)verified=!0,passwordFile=loginFile;else if(selected!==null&&canPrompt){const{askHidden:askHidden2}=await import("./prompt.js");let remembered=null;for(let attempt=1;attempt<=3&&!verified;attempt+=1){const typed=await askHidden2(`password for ${selected} (${attempt}/3): `);typed!==""&&authenticateApprover(store,selected,typed).ok&&(verified=!0,remembered=typed)}if(verified&&remembered!==null&&readLoginFile(loginFile)===null)try{loginFile=writableLoginFile(stateDir),writeLoginFileDurably(loginFile,selected,remembered),passwordFile=loginFile,notes.push(`remembered your login on this machine in ${loginFile} (owner-only) — the next \`up\` asks for nothing`)}catch{notes.push(`could not save your login in ${loginFileOf(stateDir)} — the next \`up\` will ask again`)}verified||notes.push(`could not verify ${selected}'s password — the console will still ask at login. If it is lost: another approver can add you (\`approver add\`), or restore the database/${UP_LOGIN_FILE}.`)}return{approver:selected,approvers:names,verified,passwordFile,mintedPassword:null,notes,startAuthority:verified?"full":"none"}}export function openBrowser(url){return openAddress(url)}function recordUpConsoleUrl(dir,url,now){try{const file=join(dir,UP_CONSOLE_FILE),temporary=`${file}.${process.pid}.tmp`;writeFileSync(temporary,`${JSON.stringify({url,at:now.toISOString()})}
|
|
493
493
|
`,{mode:384}),renameSync(temporary,file)}catch{}}function onboardLogin(store,loginFile){const names=store.listApprovers().map(one=>one.name),saved=readLoginFile(loginFile);return names.length===0?saved===null?null:{account:saved.name,file:loginFile}:saved!==null&&authenticateApprover(store,saved.name,saved.password).ok?{account:saved.name,file:loginFile}:{account:names.length===1?names[0]:null,file:null}}async function onboardCommand(flags,context){const{store,write,json,clock}=context,seams=context.onboardSeams??{},portGiven=text(flags,"port"),port=Number(portGiven??4180);if(portGiven!==void 0&&(!Number.isInteger(port)||port<1||port>=65536))return fail(write,json,"onboard","usage","--port is a whole number under 65536",EXIT.usage);const served=portGiven===void 0?readUpConsoleUrl(dirname(context.databaseFile)):null,home=seams.home??homedir(),env=seams.env??process.env,loginFile=savedLoginFile(dirname(context.databaseFile)),gitRun=context.gitRunner??((file,args,opts)=>run(file,[...args],{...opts?.cwd===void 0?{}:{cwd:opts.cwd},timeoutMs:1e4})),registryPath=registryPathOf(context),checker=createConnectionChecker({home,env,store:context.store}),code=await runOnboard({write,json,yes:flag(flags,"yes"),remove:flag(flags,"remove"),agentFlag:text(flags,"agent"),url:served??`http://127.0.0.1:${port}`,login:onboardLogin(store,loginFile),home,worktrees:join(dirname(context.databaseFile),"worktrees"),env,version:PACKAGE_VERSION,cwd:seams.cwd??process.cwd(),interactive:seams.interactive??(interactive()&&!underAgent(env)),confirm:seams.confirm??(async question=>/^y(es)?$/i.test(await ask(`${question} `))),findRepo:seams.findRepo??(async cwd=>{const top=await gitRun("git",["rev-parse","--show-toplevel"],{cwd}),topPath=top.code===0?canonicalProject(top.stdout.trim()):null;if(topPath===null)return null;const common=await gitRun("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd}),commonDir=common.code===0?common.stdout.trim():"",main=basename(commonDir)===".git"?canonicalProject(dirname(commonDir)):null;return{top:topPath,main:main??topPath}}),enrolled:async repo=>{const registry=await loadProjectRegistry(registryPath);return!("error"in registry)&®istry.repos.includes(repo)},enroll:async repo=>{const actor=commandLineActor(store,{databaseFile:context.databaseFile});if("ok"in actor)return{ok:!1,message:actor.message};const before=await loadProjectRegistry(registryPath),admitted=await admitProject(store,{registryFile:registryPath,path:repo,actor,now:clock()});return admitted.ok?{ok:!0,added:"error"in before||!before.repos.includes(admitted.repo)}:{ok:!1,message:admitted.message}},checkConnection:seams.checkConnection??(agent=>checker(agent)),pullRequests:seams.pullRequests??(async repo=>{const publishing=publishingOf(store,repo);if(publishing.on)return`on for ${publishing.githubRepo} into ${publishing.base}`;const checked=await checkPublishing(repo,context.publishExec===void 0?{}:{exec:context.publishExec});return checked.ok?`off: turn on with toolroll publish setup --repo ${repo} --yes (asks your password), or in Settings → Projects`:`off: ${checked.message}`}),youiyoux:seams.youiyoux??(async repo=>youiyouxOnboardLine(store,repo)),starterFlag:text(flags,"starter"),starters:{list:async repo=>{const views=startersFor(store,repo);return store.listApprovers().length>0?views:views.map(one=>({...one,blocked:one.blocked??"Needs your account first: run toolroll up, then onboard again."}))},switchOn:async(repo,id)=>{const owner=onboardLogin(store,loginFile)?.account??store.listApprovers()[0]?.name??null,starter=starterOf(id);return owner===null||starter===null?{ok:!1,said:"Needs your account first: run toolroll up, then onboard again."}:switchOnStarter(store,starter,repo,owner,clock(),dirname(context.databaseFile))}}});if(!json){const line=integrationsBrokenLine(await savedIntegrations(context).catch(()=>[]));line!==null&&write(line)}return code}async function upCommand(flags,context){const{store,write,json,clock}=context;if(context.upRole!==void 0)return upRoleCommand(context,context.upRole);const demoFence=refuseDemo(context,"up");if(demoFence!==null)return demoFence;const portGiven=text(flags,"port");let port=Number(portGiven??4180);if(portGiven!==void 0&&(!Number.isInteger(port)||port<1||port>=65536))return fail(write,json,"up","usage","--port is a whole number under 65536",EXIT.usage);const editorGiven=text(flags,"editor");if(editorGiven!==void 0&&editorGiven!=="vscode")return fail(write,json,"up","usage","--editor supports: vscode",EXIT.usage);const forGiven=text(flags,"for");if(forGiven!==void 0&&(!Number.isInteger(Number(forGiven))||Number(forGiven)<=0))return fail(write,json,"up","usage","--for takes a positive whole number of milliseconds",EXIT.usage);const capacityGiven=text(flags,"capacity"),capacityFlag=capacityGiven===void 0?null:parseRunnerCapacity(capacityGiven);if(capacityGiven!==void 0&&capacityFlag===null)return fail(write,json,"up","usage",`--capacity is a whole number of tasks, 1 to ${RUNNER_CAPACITY_MAX}`,EXIT.usage);const runnerFlag=text(flags,"runner");if(runnerFlag!==void 0&&!validRunnerName(runnerFlag))return fail(write,json,"up","usage",`a worker name is 1–${RUNNER_NAME_MAX} characters with no control characters`,EXIT.usage);const hostFlag=text(flags,"host")??"127.0.0.1";if(!/^[A-Za-z0-9.:-]{1,253}$/.test(hostFlag))return fail(write,json,"up","usage","--host is an address or a name",EXIT.usage);const allowFlag=text(flags,"allow-host"),publicUrlFlag=text(flags,"public-url"),laptop=flags.has("laptop");if(laptop&&(!["127.0.0.1","localhost","::1"].includes(hostFlag)||allowFlag!==void 0||publicUrlFlag!==void 0))return fail(write,json,"up","usage","--laptop serves this computer only: leave out --host, --allow-host and --public-url",EXIT.usage);const progress=longCommandProgress(write,json),registryPath=registryPathOf(context),removalsAtStart=registryRemovals(registryPath),loadedRegistry=await loadProjectRegistry(registryPath);if("error"in loadedRegistry)return fail(write,json,"up","registry",loadedRegistry.error,EXIT.refused);const gitRun=context.gitRunner??((file,args,opts)=>run(file,[...args],{...opts?.cwd===void 0?{}:{cwd:opts.cwd},timeoutMs:1e4})),rootInputs=(text(flags,"project-root")??"").split(",").map(one=>one.trim()).filter(one=>one!==""),explicitRoots=[];for(const input of rootInputs){const canonical=canonicalProject(input);if(canonical===null)return fail(write,json,"up","project-root",`${input} is not a directory this machine can use`,EXIT.refused);explicitRoots.includes(canonical)||explicitRoots.push(canonical)}const projectRoots=[...resolveCeiling([],addRepos(loadedRegistry.roots,explicitRoots)).ceiling.roots],rootNotSaved=explicitRoots.length>0?". The projects folder wasn't saved, because this Toolroll didn't start: stop the one already running, then start it again with --project-root":"",repos=[],proveRepo=async input=>(await upProveSaved(gitRun,input))?.root??null,deferredRepos=[],deferredGenerations={},repoLines={};for(const input of loadedRegistry.repos){const root=await proveRepo(input);root===null?(progress(`saved project unavailable — skipped ${input}; it connects when it's back`),deferredRepos.push(input),deferredGenerations[input]=removalsAtStart===null?-1:removalsAtStart[input]??0):(repos.includes(root)||repos.push(root),(repoLines[root]??=[]).push(input))}const explicitRepos=context.repoList??[],pinnedRepos=new Set;if(explicitRepos.length>0)for(const input of explicitRepos){const root=await proveRepo(input);if(root===null)return fail(write,json,"up","not-a-repository",`${input} is not inside a git repository — choose a repository, set a projects folder once with \`--project-root <dir>\`, or try the sandbox with \`toolroll demo\``,EXIT.refused);repos.includes(root)||repos.push(root),pinnedRepos.add(root)}else if(context.inferProjectFromCwd!==!1){const cwdRepo=await proveRepo(process.cwd());cwdRepo!==null&&!repos.includes(cwdRepo)&&repos.push(cwdRepo),cwdRepo!==null&&pinnedRepos.add(cwdRepo)}if(repos.length===0&&projectRoots.length===0&&deferredRepos.length===0){const fallback=laptop?upLaptopProjectsRoot(context.upSeams?.home??homedir()):null;if(fallback===null)return fail(write,json,"up","no-projects","choose where your projects live once: `toolroll up --project-root <dir>`",EXIT.refused);projectRoots.push(fallback)}if(!(!json&&!flags.has("verbose")&&(context.upSeams?.terminal??process.stdout.isTTY===!0)&&!underAgent(context.upSeams?.env??process.env))){for(const repo of repos)progress(`repository ${repo}`);for(const root of projectRoots)progress(`projects ${root}`)}const localCaller=upLocalInitCaller(context,flags),localInstall=laptop&&(localModeOf(store)?.enabled===!0||personMayInitLocalMode(localCaller)&&localModeCandidate(store)),candidates=laptop&&portGiven===void 0?upLaptopPortCandidates(store,context.upSeams?.laptopPorts,localInstall):[port];let probe=createNetServer(),reserved=!1;for(const candidate of candidates){if(candidate!==candidates[0]&&consoleRowForPort(store,candidate)!==null)break;if(candidate!==candidates[0]&&candidate===candidates[1]){let ours=null;try{ours=await proveLiveConsole(context.databaseFile,store,packageVersion())}catch{ours=null}if(ours?.ok===!0)return fail(write,json,"up","already-running",`Toolroll is already running at ${ours.url}${rootNotSaved}`,EXIT.refused);if(ours===null||ours.state!=="none")break;const serving=consoleServingNow(store,clock(),await consolesProvenDown(store,clock()));if(serving!==null)return fail(write,json,"up","already-running",`${serving.port===null?"Toolroll's console is already serving this database":`Toolroll is already running at http://127.0.0.1:${serving.port}`}${rootNotSaved}`,EXIT.refused)}if(probe=createNetServer(),port=candidate,reserved=await new Promise(resolveProbe=>{probe.once("error",()=>resolveProbe(!1)),probe.listen(candidate,"127.0.0.1",()=>resolveProbe(!0))}),reserved||consoleRowForPort(store,candidate)!==null)break}if(reserved&&laptop&&portGiven===void 0&&candidates.length>1&&(recordLaptopPort(store,port,new Date),port!==candidates[0]&&progress(`port ${candidates[0]} is in use by another program, so Toolroll uses ${port} on this computer`)),!reserved)return consoleRowForPort(store,port)?.state==="draining"?fail(write,json,"up","port-busy",`Toolroll is restarting (draining): the console on port ${port} is stopping — try again in a few seconds${rootNotSaved}`,EXIT.refused):fail(write,json,"up","port-busy",`port ${port} is taken — another \`up\` or \`serve\` may already be running; stop it, or pick a different --port${rootNotSaved}`,EXIT.refused);const agentRunning=underAgent(context.upSeams?.env??process.env),canPrompt=!json&&!agentRunning&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0;let runnerName="",runnerToken="",approver=null;try{flags.has("laptop")&&(await upLaptopLocalMode(context,text(flags,"as"),localCaller)).ok&&progress("local mode is on: this computer's browser signs in without a password");const approverPlan=await resolveUpApprover(context,flags,canPrompt);if("refusal"in approverPlan)return fail(write,json,"up","login",approverPlan.refusal,EXIT.refused);approver=approverPlan;for(const note of approverPlan.notes)progress(note);if(approverPlan.startAuthority==="none")return fail(write,json,"up","login",`${approverPlan.approver}'s password could not be verified — a runner only registers under a proven operator. Type it correctly, restore ${UP_LOGIN_FILE}, or have another approver re-add you.`,EXIT.refused);const base=runnerFlag??normalizeRunnerName(hostname());let doorAnswer=null;for(let attempt=1;attempt<=5;attempt+=1){const suffix=attempt===1?"":`-${attempt}`,name=attempt===1?base:`${base.slice(0,RUNNER_NAME_MAX-suffix.length)}${suffix}`,tryRegister=()=>registerRunnerIfIdle(store,{name,host:hostname(),repos,now:clock(),previousGone:holder=>recordedHolderProvedGone(runnerProcessFile(context.databaseFile,name),holder,hostname())});let answer=tryRegister();const drainWaitUntil=Date.now()+2*6e4;let saidDraining=!1;for(;!answer.ok&&answer.reason==="runner-draining"&&Date.now()<drainWaitUntil;)saidDraining||progress(`${answer.detail}; waiting for it to stop`),saidDraining=!0,await new Promise(resolveWait=>setTimeout(resolveWait,1e3)),answer=tryRegister();if(answer.ok){if(runnerName=name,runnerToken=answer.token,answer.signedOff!==null&&progress(`signed off the previous ${name}: its processes had already exited`),answer.recoveredRuns>0&&progress(`recovered ${answer.recoveredRuns} interrupted attempt(s) left by the previous ${name}`),!recordRunnerProcess(context.databaseFile,{runner:answer.runner,credentialHash:hashRunnerToken(answer.token)},"up",process.pid)){retireRunnerIfCurrent(store,runnerName,runnerToken,clock());const identity=processIdentityProblem();return fail(write,json,"up","runner-alive",`The worker process record could not be saved${identity===null?"":` (${identity})`}; nothing started`,EXIT.refused)}recordBuilderWish(store,"running","up",packageVersion(),clock()),doorAnswer=answer;break}if(doorAnswer=answer,runnerFlag!==void 0||answer.reason==="runner-draining")break}if(runnerName===""){const detail=doorAnswer!==null&&!doorAnswer.ok?doorAnswer.detail:"no worker name could be taken";return doorAnswer!==null&&!doorAnswer.ok&&doorAnswer.reason==="runner-draining"?fail(write,json,"up","runner-alive",`${detail}, and it hasn't yet — try again shortly`,EXIT.refused):fail(write,json,"up","runner-alive",`${detail} — that worker looks alive; stop the other \`up\` or watch, or name a different worker with --runner`,EXIT.refused)}{const enrolled=await updateProjectRegistry(registryPath,current=>({repos:addRepos(current.repos,repos),roots:addRepos(current.roots,projectRoots)}));if(!enrolled.ok)return retireRunnerIfCurrent(store,runnerName,runnerToken,clock()),fail(write,json,"up","registry",`${enrolled.message} — nothing started`,EXIT.refused)}if(capacityFlag!==null){const changed=store.setRunnerCapacity(runnerName,capacityFlag,approverPlan.approver??"operator",clock());changed.ok&&changed.before!==changed.after&&progress(`${runnerName} now runs up to ${changed.after} task(s) at once (was ${changed.before})`)}}finally{await new Promise(done=>probe.close(()=>done()))}const pool=join(dirname(context.databaseFile),"worktrees"),split=!flags.has("single-process")&&context.upOneProcess!==!0,build2=upBuildIdentity(),containmentFlag=text(flags,"containment")??null,stopGraceMs=Number(text(flags,"stop-grace")??3e4);let stopping=!1,fatal=null,runTimer,resolveStopped=()=>{};const stopped=new Promise(resolveStop=>resolveStopped=resolveStop);let currentRepos=[...repos],consoleRole=null,workerRole=null,resolveForced=()=>{};const forced=new Promise(resolveForce=>resolveForced=resolveForce);let forceTimer;const stopDeadlineMs=Math.max(1,stopGraceMs)+2e4,stop=()=>{if(stopping){workerRole?.hardStop();return}stopping=!0,resolveStopped();try{runnerName!==""&&drainRunnerIfCurrent(store,runnerName,runnerToken,clock(),new Date(clock().getTime()+stopDeadlineMs))}catch{}forceTimer=setTimeout(()=>{fatal??=`stopping took longer than ${Math.round(stopDeadlineMs/1e3)} s; its console and worker were stopped outright`,workerRole?.kill(),consoleRole?.kill(),resolveForced()},stopDeadlineMs),forceTimer.unref?.(),consoleRole?.send({type:"stopping"}),workerRole?.stop()},dropStopSignals=onStopSignals(stop);let parentGone=!1;const parentAtStart=process.ppid,parentWatch=context.upSeams===void 0&&parentAtStart>1?setInterval(()=>{process.ppid===parentAtStart||parentGone||(parentGone=!0,progress("the process that started Toolroll is gone; stopping"),stop())},1e3):void 0;parentWatch?.unref?.();const onDisconnect=()=>{parentGone||(parentGone=!0,progress("the process that started Toolroll closed its channel; stopping"),stop())};context.upSeams===void 0&&process.channel!==void 0&&process.channel!==null&&process.once("disconnect",onDisconnect);const labelled=split&&(json||flags.has("verbose")||!(context.upSeams?.terminal??process.stdout.isTTY===!0)),roleLine=role=>line=>progress(labelled?`[${role}] ${line}`:line),dropSignals=()=>{dropStopSignals(),process.removeListener("disconnect",onDisconnect),parentWatch!==void 0&&clearInterval(parentWatch)},consoleConfig={host:hostFlag,port,allowedHosts:allowFlag===void 0?null:allowFlag.split(",").map(one=>one.trim()).filter(one=>one!==""),publicUrl:publicUrlFlag??null,localRunner:runnerName,poolRoot:pool,repos:[...repos],projectRoots,registryPath,editor:editorGiven!==void 0,startAuthority:approver?.startAuthority??"none"},pendingLinks=new Map;let linkRequests=0;const roleSpawned=(role,pid)=>{const held=store.getRunner(runnerName);return held!==null&&held.credentialHash===hashRunnerToken(runnerToken)&&recordRunnerProcess(context.databaseFile,held,role,pid)};consoleRole=startUpRole({role:"console",split,context,build:build2,shutdownMs:15e3,onSpawned:pid=>roleSpawned("console",pid),start:()=>({type:"start",role:"console",databaseFile:context.databaseFile,containment:containmentFlag,build:build2,config:{...consoleConfig,repos:[...currentRepos]}}),onMessage:message=>{message.type==="log"?roleLine("console")(message.line):message.type==="sign-in-link"&&(pendingLinks.get(message.id)?.(message.link),pendingLinks.delete(message.id))},onReady:(_,again)=>{again&&(roleLine("console")("started again"),consoleRole?.send({type:"repos",repos:[...currentRepos]}))},onEnded:(detail,restarting)=>{restarting?roleLine("console")(`${detail}; starting it again`):stopping||(fatal=detail,stop())}});const consoleReady=await consoleRole.ready;if(!consoleReady.ok)return dropSignals(),retireRunnerIfCurrent(store,runnerName,runnerToken,clock()),consoleReady.reason==="port-busy"?fail(write,json,"up","port-busy",`${consoleReady.detail} — the port was taken while starting; try again`,EXIT.refused):fail(write,json,"up","failed",`the console could not start (${consoleReady.detail}) — nothing was left running`,EXIT.failed);const url=consoleReady.url;if(!stopping){workerRole=startUpRole({role:"worker",split,context,build:build2,onSpawned:pid=>roleSpawned("worker",pid),shutdownMs:Math.max(1,stopGraceMs)+15e3,watchdog:{graceMs:stopGraceMs,say:line=>roleLine("worker")(line),...context.upSeams?.watchdogSilenceMs===void 0?{}:{silenceMs:context.upSeams.watchdogSilenceMs},paused:()=>briefly(store,()=>{if(updateAdmissionPaused(store.raw()))return!0;const own=store.getRunner(runnerName)?.runner;return own!==void 0&&drainOf(store,own,clock())!==null})},start:generation=>({type:"start",role:"worker",databaseFile:context.databaseFile,containment:containmentFlag,build:build2,config:{runner:runnerName,token:runnerToken,repos:generation===1?[...repos]:[...currentRepos],pinnedRepos:[...pinnedRepos],projectRoots,registryPath,pool,deferredRepos:[...deferredRepos],deferredGenerations:{...deferredGenerations},repoLines,forMs:forGiven===void 0?null:Number(forGiven),publicUrl:publicUrlFlag??null,stopGraceMs,verbose:flags.has("verbose"),terminal:context.upSeams?.terminal??process.stdout.isTTY===!0,leaseWaitMs:split?WATCH_LEASE_MS+15e3:0}}),onMessage:message=>{if(message.type==="log")roleLine("worker")(message.line);else if(message.type==="deferred"){const narrowed=upNarrowDeferred(deferredRepos,message.repos);deferredRepos.length=0,deferredRepos.push(...narrowed)}else if(message.type==="repos"){const bound=new Set(store.getRunner(runnerName)?.runner.repos??[]);currentRepos=message.repos.filter(repo=>bound.has(repo)),consoleRole?.send({type:"repos",repos:[...currentRepos]})}},onReady:(_,again)=>{again&&roleLine("worker")("started again: its builds and checks continue")},onEnded:(detail,restarting)=>{if(restarting&&authenticate(store,runnerName,runnerToken).ok){roleLine("worker")(`${detail}; starting it again — its interrupted builds are recovered first`);return}stopping||(fatal=restarting?`the builder identity changed (${detail})`:detail,stop())}});const workerReady=await workerRole.ready;!workerReady.ok&&fatal===null&&(fatal=workerReady.detail,stop())}const runnerHeartbeat=setInterval(()=>{let beat;try{beat=briefly(store,()=>heartbeatRunner(store,runnerName,runnerToken,clock()))}catch(error){if(isDatabaseBusy(error)||stopping)return;fatal=`the builder's heartbeat could not be recorded (${describe(error)})`,stop();return}!beat.ok&&!stopping&&(fatal=`the builder identity changed (${beat.reason})`,stop())},RUNNER_HEARTBEAT_MS);runnerHeartbeat.unref?.();let removeSignInPageNow=()=>{};const approverPlan2=approver,terminal=!agentRunning&&(context.upSeams?.terminal??process.stdout.isTTY===!0),upHandoff=buildHandoff({url,login:{account:approverPlan2.passwordFile===null?approverPlan2.approver:loginAccount(approverPlan2.passwordFile)??approverPlan2.approver,file:approverPlan2.passwordFile}});recordUpConsoleUrl(dirname(context.databaseFile),url,clock());let firstRunDetection=null;if(fatal===null&&!stopping&&store.firstSuccessAt(clock())===null&&!store.isDemo()&&(firstRunDetection=await(context.upSeams?.detectFirstRun??(()=>detectFirstRunAgents({env:context.upSeams?.env??process.env,home:context.upSeams?.home??homedir()})))().catch(()=>null),firstRunDetection!==null&&autoSelectFirstRunDefault(store,firstRunDetection,clock())),fatal===null&&!stopping)if(json)write(envelopeJson({ok:!0,command:"up",url,repos,runner:runnerName,approver:approverPlan2.approver,approvers:approverPlan2.approvers,approverVerified:approverPlan2.verified,...approverPlan2.passwordFile===null?{}:{passwordFile:approverPlan2.passwordFile},handoff:upHandoff,...firstRunDetection===null?{}:{detectedAgents:{recommendedDefault:firstRunDetection.recommendedDefault,readinessSummary:firstRunDetection.readinessSummary,ready:firstRunDetection.readyAgents.map(one=>one.id)}}}));else if(terminal){const account=approverPlan2.approver,localStart=approverPlan2.startAuthority==="local",request=upLinkRequest(approverPlan2.startAuthority,account),pageParent=instanceRunDir(context.databaseFile),hasOpener=platformOpener(context.upSeams?.signInPlatform)!==null,canOpen=hasOpener&&prepareRunDir(pageParent)===null,linkExpiresAt=Date.now()+SIGN_IN_LINK_MS,link=request===null||flags.has("no-open")||!canOpen?null:await new Promise(resolveLink=>{const id=++linkRequests,timer=setTimeout(()=>{pendingLinks.delete(id),resolveLink(null)},1e4);pendingLinks.set(id,value=>{clearTimeout(timer),resolveLink(value)}),consoleRole?.send({type:"sign-in-link",id,...request})}),saved=approverPlan2.passwordFile===null?null:resolve(approverPlan2.passwordFile),showCommand=saved===null?null:`cat -- '${saved.replaceAll("'","'\\''")}'`,signInWords2=account===null?`sign in as one of ${approverPlan2.approvers.join(", ")}`:showCommand===null?`sign in as ${account} with your password`:`sign in as ${account}`,opened=link===null?!1:await(async()=>{const outcome=localStart?"local link":"one-time link",page=await openSignInLink(new URL(link,url).toString(),{parent:pageParent,spent:ledgerSpent(store,outcome,localStart?null:account),expiresAt:linkExpiresAt,...context.upSeams?.signInOpener===void 0?{}:{opener:context.upSeams.signInOpener},...context.upSeams?.signInPlatform===void 0?{}:{platform:context.upSeams.signInPlatform}});return removeSignInPageNow=page.stop,page.opened})();if(write(""),write(`Toolroll is on ${url}`),localStart?opened?(write("Opening it in your browser now, already signed in."),write("If it doesn't open, stop it with Ctrl-C and run the same command again.")):flags.has("no-open")?write("To sign in from this computer's browser, run the same command again without --no-open."):write(hasOpener?"Your browser didn't open. Stop it with Ctrl-C and run the same command again.":`${NO_SAFE_OPENER.charAt(0).toUpperCase()}${NO_SAFE_OPENER.slice(1)}.`):opened?(write("Opening it in your browser now, already signed in."),write(`If it doesn't open, go to that address and ${signInWords2}.`)):write(`${signInWords2.charAt(0).toUpperCase()}${signInWords2.slice(1)}.`),showCommand!==null&&write(`Your password: run \`${showCommand}\``),opened||write("Ctrl-C stops it."),firstRunDetection!==null){write("");for(const line of formatFirstRunAgentsTable(firstRunDetection))write(line)}}else{write("");for(const line of handoffLines(upHandoff,{local:approverPlan2.startAuthority==="local"}))write(line);write("Run `toolroll onboard` inside a repository to add it and install the Toolroll skill for your agent.")}forGiven!==void 0&&!stopping&&(runTimer=setTimeout(stop,Number(forGiven)),runTimer.unref?.()),await stopped,removeSignInPageNow(),workerRole!==null&&await Promise.race([workerRole.done,forced]),clearInterval(runnerHeartbeat),runTimer!==void 0&&clearTimeout(runTimer),dropSignals(),retireRunnerIfCurrent(store,runnerName,runnerToken,clock()),consoleRole.stop();const closed=await Promise.race([consoleRole.done,forced.then(()=>({problem:null}))]);return forceTimer!==void 0&&clearTimeout(forceTimer),parentGone&&setTimeout(()=>process.exit(fatal===null?EXIT.ok:EXIT.failed),1e3).unref?.(),closed.problem!==null&&fatal===null&&(fatal=closed.problem),fatal!==null?(process.stderr.write(`up: ${fatal}
|
|
494
494
|
`),EXIT.failed):(progress(flags.has("laptop")?"Toolroll stopped. Run `toolroll` to start it again.":"Toolroll stopped. Run `toolroll up` anywhere on this machine to start it again with every saved project."),EXIT.ok)}function digestWords(everyMs){return everyMs%36e5===0?`${everyMs/36e5}h`:`${Math.round(everyMs/6e4)}m`}async function bridgeCommand(positional,flags,context){const{store,write,json,clock}=context,demoFence=refuseDemo(context,"bridge");if(demoFence!==null)return demoFence;const[channel,action]=positional;if(channel!=="telegram")return fail(write,json,"bridge","usage","`toolroll bridge telegram [pair|unpair|token|status|digest|retry]`",EXIT.usage);if(action==="retry"){const retried=store.retryTelegramReplies(null,clock());return succeed(write,json,"bridge retry",{retried},()=>[retried===0?"No unsent Telegram replies.":`Sending ${retried} Telegram ${retried===1?"reply":"replies"} again on the next bridge pass.`])}if(action==="token"){const value=positional[2];if(flags.has("clear")){const removed=clearBotToken(context.telegramTokenFile);return succeed(write,json,"bridge token",{cleared:removed},()=>[removed?"Token file removed.":"There was no token file to remove."])}if(value===void 0)return fail(write,json,"bridge token","usage","`toolroll bridge telegram token <bot-token>` (from @BotFather), or --clear",EXIT.usage);const saved=saveBotToken(context.telegramTokenFile,value);return saved.ok?succeed(write,json,"bridge token",{saved:!0,file:context.telegramTokenFile},()=>[`Saved (owner-only) to ${context.telegramTokenFile}.`,`${TOKEN_ENV} in the environment would take precedence over it.`]):fail(write,json,"bridge token","bad-token",saved.message,EXIT.refused)}if(action==="digest"){const every=text(flags,"every");if(flags.has("off"))return store.setTelegramDigest(null,"cli",clock()),succeed(write,json,"bridge digest",{everyMs:null},()=>["Digest off — every fact pages as it lands."]);if(every===void 0){const current=store.telegramDigest(),held=store.countRoutinePending();return succeed(write,json,"bridge digest",{...current,held},()=>[current.everyMs===null?"Digest off — every fact pages as it lands. `bridge telegram digest --every 2h` turns it on.":`Digest every ${digestWords(current.everyMs)}; ${held} routine fact(s) held; next no earlier than ${current.lastSentAt===null?"the next bridge pass":new Date(new Date(current.lastSentAt).getTime()+current.everyMs).toISOString()}.`])}const parsed=/^([1-9][0-9]{0,3})(m|h)$/.exec(every);if(parsed===null)return fail(write,json,"bridge digest","usage","--every takes minutes or hours: 30m, 2h, 24h — or --off",EXIT.usage);const everyMs=Number(parsed[1])*(parsed[2]==="h"?36e5:6e4);return everyMs<5*6e4||everyMs>168*36e5?fail(write,json,"bridge digest","usage","the digest cadence is between 5 minutes and 7 days",EXIT.usage):(store.setTelegramDigest(everyMs,"cli",clock()),succeed(write,json,"bridge digest",{everyMs},()=>[`Digest every ${digestWords(everyMs)}. Routine facts are held and sent together; decisions and anything that needs you now still page at once.`]))}const source=loadBotToken(process.env,context.telegramTokenFile);if(action==="status"){const bindings=source===null?[]:store.liveTelegramBindings(source.botId),binding=bindings[0]??null,pending=store.listNotifications("pending").length,digest=store.telegramDigest();return json?(write(envelopeJson({ok:!0,command:"bridge status",token:source===null?null:{source:source.source,botId:source.botId,redacted:redactToken(source.token)},paired:binding!==null,approver:binding?.approver??null,people:bindings.map(one=>one.approver),outboxPending:pending,digest:{everyMs:digest.everyMs,lastSentAt:digest.lastSentAt,held:digest.everyMs===null?0:store.countRoutinePending()}})),EXIT.ok):(write(source===null?`No bot token. Set ${TOKEN_ENV}, run \`toolroll bridge telegram token <t>\`, or use the serve settings card.`:`Token ${redactToken(source.token)} (${source.source}), bot ${source.botId}.`),write(binding===null?"No chat is paired.":`Paired: ${bindings.length===1?`chat answers as ${binding.approver}`:`${bindings.length} chats answer as ${bindings.map(one=>one.approver).join(", ")}`}.`),write(`Outbox pending: ${pending}.`),write(digest.everyMs===null?"Digest off.":`Digest every ${digestWords(digest.everyMs)}; ${store.countRoutinePending()} routine fact(s) held.`),EXIT.ok)}if(action==="pair"||action==="unpair"){const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,`bridge ${action}`,"usage","`--as <you> --token <your password>` — pairing hands your authority to a chat, so it takes your credential",EXIT.usage);const{name:asWho,token}=acting,authenticated=action==="pair"?credentialApprover(store,asWho,token):authenticateApprover(store,asWho,token);if(!authenticated.ok)return fail(write,json,`bridge ${action}`,authenticated.reason,describeApproveFailure(authenticated.reason,asWho),EXIT.refused);if(action==="unpair"){if(source===null)return fail(write,json,"bridge unpair","no-token","no bot token, so no bot to unpair",EXIT.refused);const revoked=store.unpairTelegram(source.botId,asWho,clock());return succeed(write,json,"bridge unpair",{revoked},()=>[revoked?"Unpaired. Every outstanding button from that chat is dead. Rotate the bot token with @BotFather if it may have leaked.":"Nothing was paired."])}const code=mintPairingCode();return store.createTelegramPairing({codeHash:hashPairingCode(code),approver:asWho,by:asWho,ttlMs:PAIRING_TTL_MS},clock()),succeed(write,json,"bridge pair",{code,expiresInMs:PAIRING_TTL_MS},()=>["From your phone, send your bot this message within 10 minutes:","",` /pair ${code}`,"","The next bridge pass completes it. The code works once, in a private","chat only, and the chat will answer as you — treat it accordingly."])}if(action!==void 0)return fail(write,json,"bridge","usage","`toolroll bridge telegram [pair|unpair|token|status]`",EXIT.usage);if(source===null)return fail(write,json,"bridge","no-token",`no bot token — set ${TOKEN_ENV}, run \`toolroll bridge telegram token <t>\`, or use the serve settings card`,EXIT.refused);const fenced=networkFence(context.telegramEnv??(context.telegramTransport===void 0?process.env:{}));if(fenced!==null)return fail(write,json,"bridge","network-fenced",networkFenceLine(fenced),EXIT.refused);const transport=context.telegramTransport??createTransport(source.token);if(flags.has("follow")){const controller=new AbortController,dropSignals=onStopSignals(()=>controller.abort()),runFor=text(flags,"for"),timer=runFor===void 0?null:setTimeout(()=>controller.abort(),Number(runFor));timer?.unref?.();const fence=context.shouldStop===void 0?null:setInterval(()=>{context.shouldStop?.()===!0&&controller.abort()},50);fence?.unref?.(),json||write(`Following bot ${source.botId} — taps apply as they arrive. Ctrl-C stops it.`);try{const report2=await followBridge(store,{readProjects:telegramReadProjects(context),canDeliver:telegramCanDeliver(context,source.token),conversation:telegramConversation(context),...flags.has("inbound-only")?{deliver:!1}:{},botId:source.botId,transport,signal:controller.signal,clock,...text(flags,"poll")===void 0?{}:{pollSeconds:Number(text(flags,"poll"))},onCycle:cycle=>{json||write(`bridge: sent ${cycle.sent}, answered ${cycle.answered}, paired ${cycle.paired}`+((cycle.statusReplies??0)>0?`, status replies ${cycle.statusReplies}`:"")+(cycle.problems.length>0?` — ${cycle.problems.length} problem(s): ${cycle.problems[0].slice(0,200)}`:""))}});return succeed(write,json,"bridge follow",{report:report2},()=>[`Followed for ${report2.cycles} cycle(s): sent ${report2.sent}, answered ${report2.answered}, paired ${report2.paired}, ignored ${report2.ignored}, status replies ${report2.statusReplies??0}.`,...report2.problems.slice(-5).map(problem=>` problem: ${problem}`)])}finally{timer!==null&&clearTimeout(timer),fence!==null&&clearInterval(fence),dropSignals()}}const passed=await bridgePass(store,{readProjects:telegramReadProjects(context),canDeliver:telegramCanDeliver(context,source.token),conversation:telegramConversation(context),botId:source.botId,transport,clock,...flags.has("inbound-only")?{deliver:!1}:{}});if(!passed.ok)return fail(write,json,"bridge",passed.reason,passed.message,EXIT.refused);const{report}=passed,broke=report.problems.length>0,idle=report.sent===0&&report.answered===0&&report.paired===0&&(report.statusReplies??0)===0&&(report.chatQueued??0)===0&&(report.chatAnswered??0)===0&&(report.chatRefused??0)===0&&(report.chatConfirmed??0)===0,lines=()=>[`Sent ${report.sent}, answered ${report.answered}, paired ${report.paired}, ignored ${report.ignored}, status replies ${report.statusReplies??0}, chat received ${report.chatQueued??0}, chat replied ${report.chatAnswered??0}, chat confirmed ${report.chatConfirmed??0}.`,...report.backlog?["Telegram still holds more updates than one pass's budget — run it again."]:[],...report.problems.map(problem=>` problem: ${problem}`)];return broke?fail(write,json,"bridge","telegram-transport",lines().join(`
|
|
@@ -502,7 +502,7 @@ Add --json for a machine-readable envelope.`:command==="flows"?FLOWS_HELP:comman
|
|
|
502
502
|
`;return writeOut(context,command,text(flags,"out"),content,{task:pack.task.id,digest:pack.digest,chainOk:pack.ledger.chain.ok},`Evidence pack for ${pack.task.id} (${pack.ledger.entries.length} ledger entries, chain ${pack.ledger.chain.ok?"verified":"BROKEN"}).`,flags.has("html")?{html:content}:{pack})}async function ledgerCommand(positional,flags,context){const[action,...extra]=positional,command=`ledger ${action??""}`.trim(),allowed=new Set(action==="verify"?["checkpoint","db","json"]:action==="checkpoint"?["as","token","token-file","token-env","db","json"]:["from","to","out","db","json"]);for(const name of flags.keys())if(!allowed.has(name))return fail(context.write,context.json,command,"usage",`--${name} is not a ${command} option.`,EXIT.usage);if(extra.length>0||action!=="verify"&&action!=="checkpoint"&&action!=="export")return fail(context.write,context.json,command,"usage","Use ledger verify, ledger checkpoint or ledger export --from <day> --to <day>.",EXIT.usage);const store=context.store;if(action==="verify"){const report=store.ledgerChain({full:!0}),copied=text(flags,"checkpoint"),outside=copied===void 0?null:matchesOutsideCheckpoint(store.handle,copied),inside=store.ledgerCheckpoints(1)[0]??null,ok=report.ok&&(outside===null||outside.ok),lines=[report.ok?`Chain verified: ${report.entries} entries through #${report.through??0}, head ${report.head}.`:`Chain BROKEN: ${report.problem?.what??"it doesn't verify"}.`,...report.checkpoints>0&&report.ok?[`All ${report.checkpoints} checkpoints kept here still match${inside===null?"":`; the latest is ${inside.through}:${inside.hash}`}.`]:[],...outside===null?[]:[outside.what]];return context.write(context.json?envelopeJson({ok,command,chain:report,outside}):lines.join(`
|
|
503
503
|
`)),ok?EXIT.ok:EXIT.failed}if(action==="checkpoint"){const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok||!store.isInstanceOperator(acting.name))return fail(context.write,context.json,command,"refused","An instance operator makes checkpoints: pass --as and --token (or use the remembered login).",EXIT.refused);const made=store.ledgerCheckpoint(acting.name,context.clock());return made===null?fail(context.write,context.json,command,"empty","The ledger has no entries yet.",EXIT.refused):"problem"in made?fail(context.write,context.json,command,"broken",`No checkpoint: the chain doesn't verify (${made.problem}).`,EXIT.failed):succeed(context.write,context.json,command,{through:made.through,hash:made.hash,checkpoint:`${made.through}:${made.hash}`},()=>[`${made.through}:${made.hash}`,"Copy this somewhere outside this machine; ledger verify --checkpoint <it> proves nothing before it was rewritten."])}const from=exportDay(text(flags,"from")??null),last=exportDay(text(flags,"to")??null);if(from===null||last===null)return fail(context.write,context.json,command,"usage","Use ledger export --from <YYYY-MM-DD> --to <YYYY-MM-DD> [--out <file>].",EXIT.usage);const to=new Date(Date.parse(last)+864e5).toISOString();if(to<=from)return fail(context.write,context.json,command,"usage","--to is on or after --from.",EXIT.usage);const who="command line",content=[...ledgerExportChunks(store,{from,to},{repos:null,instance:!0},{principal:"operator",repos:null,includeUnplaced:!0},who,context.clock(),context.evidenceRoot)].join(""),bundle=JSON.parse(content);return store.recordAction({at:context.clock().toISOString(),actor:who,repo:null,taskId:null,runId:null,action:"ledger exported",outcome:"exported",source:"access",detail:`${from.slice(0,10)} to ${last.slice(0,10)} · ${bundle.entries.length} entries · ${bundle.packs.length} evidence packs`}),writeOut(context,command,text(flags,"out"),`${content}
|
|
504
504
|
`,{entries:bundle.entries.length,packs:bundle.packs.length,chainOk:bundle.chain.ok},`${bundle.entries.length} ledger entries and ${bundle.packs.length} evidence packs (chain ${bundle.chain.ok?"verified":"BROKEN"}).`,{export:bundle})}function succeed(write,json,command,data,lines){return write(json?envelopeJson({ok:!0,command,...data}):lines().join(`
|
|
505
|
-
`)),EXIT.ok}function fail(write,json,command,reason,message,code,extra={}){return write(json?envelopeJson({ok:!1,command,reason,message,...extra}):message),code}function text(flags,name){const value=flags.get(name);return typeof value=="string"?value:void 0}function flag(flags,name){return flags.get(name)===!0||flags.get(name)==="true"}function consoleLinkFor(context,path){const base=loadConsoleUrl(process.env,dirname(context.databaseFile));return base===null?null:`${base}${path}`}function refuseDemo(context,command){return context.store.isDemo()?fail(context.write,context.json,command,"demo-database","this database is a demo sandbox — it never spends money or touches a remote; point this command at a real database",EXIT.refused):null}function readTtl(flags){const given=text(flags,"ttl");if(given===void 0)return DEFAULT_LEASE_MS;const seconds=Number(given);return!Number.isInteger(seconds)||seconds<=0?null:seconds*1e3}function mutationFrom(flags,now){const key=text(flags,"key");return key===void 0?{at:now}:{idempotencyKey:key,at:now}}function slug(title,now){const words=title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").split("-").filter(Boolean).slice(0,4).join("-"),stamp=now.toISOString().slice(11,19).replace(/:/g,"");return words===""?`task-${stamp}`:`${words}-${stamp}`}function describe(error){return error instanceof Error?error.message:String(error)}function databaseFailure(write,json,command,file,error){return isDatabaseBusy(error)?fail(write,json,command,"database-busy",`The database ${file} stayed busy for ${CONCURRENT_WRITER_WAIT_MS/1e3} seconds. Wait for the other Toolroll process to finish, then try again.`,EXIT.failed):fail(write,json,command,"database",describe(error),EXIT.failed)}function refuseApprover(context,command,verified,usage,subject){if(verified===null)return fail(context.write,context.json,command,"usage",usage,EXIT.usage);const reason=verified.ok?"":verified.reason;return fail(context.write,context.json,command,reason,describeApproveFailure(reason,subject??""),EXIT.refused)}async function knownProject(context,repoFlag,match){const registered=await loadRepos(registryPathOf(context)).catch(()=>({error:"unreadable"}));return[...new Set([...context.store.knownRepos(),...match.listed?context.store.listProjects().map(one=>one.path):[],..."error"in registered?[]:registered.repos])].find(one=>one===repoFlag||one===resolve(repoFlag)||match.canonical&&one===canonicalProject(repoFlag))}export function ownValueFlags(command,argv){if(command==="flows")return FLOWS_VALUE_FLAGS;if(command==="card")return CARD_PANEL_VALUE_FLAGS;if(command==="project"&&argv.find(arg=>!arg.startsWith("-"))==="network")return PROJECT_NETWORK_VALUE_FLAGS}async function projectCheckAccessCommand(positional,flags,context){const command="project check-access",wanted=positional[1],repo=await projectAsked(context,flags,positional,command,{own:[],most:2,usage:"Use project check-access --repo <project path> [sandboxed | sign-ins | unsandboxed].",invalid:wanted!==void 0&&!isCheckAccess(wanted),match:{listed:!0,canonical:!0}});if(typeof repo=="number")return repo;const current=context.store.projectCheckAccess(repo),platform=context.platform??process.platform,fenced=context.fenceAvailable?.()??(macosFenceAvailable()||linuxFenceAvailable()),runsAs=one=>checkAccessRunsAs(one,{platform,fenced,unconfinedAllowed:context.store.unfencedAgentsAllowed(),localMode:localModeOn(context.store)}),here=runsAs(current),words=one=>{if(runsAs(one)==="unsandboxed"&&one!=="unsandboxed")return[`${repo}: saved as ${checkAccessWords(one)}, but this machine can't sandbox checks, so they run without a sandbox.`];if(runsAs(one)!==one)return[`${repo}: saved with model and GitHub sign-ins, but its checks run sandboxed: sign-ins can't be shared with checks safely yet.`];const missing=one==="sign-ins"?signInHostsMissing(context.store.projectNetwork(repo)):[];return[`${repo}: checks run ${checkAccessWords(one)}.`,...one==="sandboxed"?[]:[CHECK_ACCESS_WARNINGS[one]],...missing.length===0?[]:[`Model sign-ins need these hosts in this project's network allowlist: ${missing.join(", ")}. Add them with: toolroll project network --repo ${repo} --allow ${missing.join(",")}`]]};if(wanted===void 0)return succeed(context.write,context.json,command,{repo,checkAccess:current,...here===current?{}:{runsAs:here},...here==="sign-ins"?{missingHosts:signInHostsMissing(context.store.projectNetwork(repo))}:{}},()=>words(current));const unavailable=wanted==="sign-ins"?signInsUnavailableWords(platform):null;if(unavailable!==null)return fail(context.write,context.json,command,"refused",unavailable,EXIT.refused);const widening=widerThan(wanted,current);if(wanted==="unsandboxed"&&localModeOn(context.store))return fail(context.write,context.json,command,"refused",LOCAL_MODE_CONFINES,EXIT.refused);const acting=await askCredentials(flags,context),proved=acting===null?null:authenticateApprover(context.store,acting.name,acting.token,repo);if(widening){if(acting===null||proved===null||!proved.ok||proved.method!=="password-now"||!context.store.isInstanceOperator(acting.name))return fail(context.write,context.json,command,"refused","An instance operator widens what a project's checks reach, with their password typed now: pass --as and --token.",EXIT.refused)}else if(acting===null||proved===null||!proved.ok||!credentialProof(proved.method)||!context.store.accountCanAccess(acting.name,repo))return fail(context.write,context.json,command,"refused","An approver for this project narrows what its checks reach, with their password: pass --as and --token.",EXIT.refused);const changed=context.store.setProjectCheckAccess(repo,wanted,acting.name,context.clock(),{may:widening?"widen":"narrow"});return changed===null?fail(context.write,context.json,command,"refused","The project's check access changed meanwhile, and this would now widen it: an instance operator widens it, with their password typed now.",EXIT.refused):succeed(context.write,context.json,command,{repo,before:changed.before,checkAccess:changed.after},()=>[...words(changed.after),"Scopes written from now on use this; scopes already approved keep what they were approved with."])}async function projectSandboxCommand(positional,flags,context){const command="project sandbox",repo=await projectAsked(context,flags,positional,command,{own:["read-deny","mach"],most:1,usage:"Use project sandbox --repo <project path> [--read-deny <paths>] [--mach <services>] (comma-separated; empty clears).",match:{listed:!0,canonical:!0}});if(typeof repo=="number")return repo;const words=one=>[`${repo}: ${readDenyWords(one.readDeny)}`,...one.machLookup.length===0?[]:[`macOS services also allowed: ${one.machLookup.join(", ")}`]],current=context.store.projectSandbox(repo),asked=name=>{const value=flags.get(name);return value===void 0?void 0:value===!0?[]:value.split(",")},changes={readDeny:asked("read-deny"),machLookup:asked("mach")};if(changes.readDeny===void 0&&changes.machLookup===void 0)return succeed(context.write,context.json,command,{repo,sandbox:current},()=>words(current));const parsed={readDeny:parseReadDeny(changes.readDeny??current.readDeny),machLookup:parseMachLookup(changes.machLookup??current.machLookup)};for(const[name,one]of Object.entries(parsed))if(!one.ok)return fail(context.write,context.json,command,"usage",`${name}: ${one.problem}. Nothing changed.`,EXIT.usage);const wanted={readDeny:parsed.readDeny.ok?parsed.readDeny.list:[],machLookup:parsed.machLookup.ok?parsed.machLookup.list:[]},acting=await askCredentials(flags,context),verified=acting===null?null:credentialApprover(context.store,acting.name,acting.token,repo);if(acting===null||!verified?.ok||!context.store.accountCanAccess(acting.name,repo))return fail(context.write,context.json,command,"refused","An approver for this project changes its sandbox, with their password: pass --as and --token.",EXIT.refused);const changed=context.store.setProjectSandbox(repo,wanted,acting.name,context.clock());return changed===null?fail(context.write,context.json,command,"refused","An approver for this project changes its sandbox. Nothing changed.",EXIT.refused):succeed(context.write,context.json,command,{repo,before:changed.before,sandbox:changed.after},()=>[...words(changed.after),"Scopes written from now on use this; scopes already approved keep what they were approved with."])}function gitTooOld(command,context){const problem=installedGitFloorProblem();return problem===null?null:fail(context.write,context.json,command,"git-too-old",problem,EXIT.refused)}function upBuildIdentity(){return buildIdentity(PACKAGE_VERSION,fileURLToPath(import.meta.url))}function upNeedsOneProcess(options){return options.openDatabase!==void 0||options.desktopIdentity!==void 0||options.additionalProjectRepos!==void 0||options.agentRunner!==void 0||options.gitRunner!==void 0||options.telegramTransport!==void 0||options.telegramEnv!==void 0||options.publishExec!==void 0||options.dispatchAdapter!==void 0||options.flowTriggerIo!==void 0||options.flowStepIo!==void 0||options.flowEveryMs!==void 0||options.watchHeartbeatMs!==void 0||options.loopRelaunchMs!==void 0||options.platform!==void 0||options.fenceAvailable!==void 0||options.flowFetch!==void 0||options.integrationIo!==void 0||options.shouldStop!==void 0||options.leadSeams!==void 0||options.waitSleep!==void 0||options.releaseIo!==void 0||options.installBin!==void 0||options.tempRoots!==void 0||options.filingSizer!==void 0||options.now!==void 0||options.folderLook!==void 0}function recordRunnerProcess(databaseFile,holder,role,pid){try{const started=processStart(pid);if(started===null)return!1;const file=runnerProcessFile(databaseFile,holder.runner.name),credential=credentialDigest(holder.credentialHash),current=readRunnerProcessRecord(file),same=current!==null&¤t.runner===holder.runner.name&¤t.registeredAt===holder.runner.registeredAt&¤t.credential===credential;if(role!=="up"&&(!same||current.signature!==sealRunnerProcessRecord(current,holder.credentialHash).signature))return!1;const kept=same?current.processes.filter(one=>one.role!==role||!processGone(one)):[],record={v:1,runner:holder.runner.name,host:holder.runner.host,registeredAt:holder.runner.registeredAt,credential,processes:[...kept.filter(one=>one.pid!==pid),{pid,role,started}]};return record.processes.length>64?!1:(writeRunnerProcessRecord(file,sealRunnerProcessRecord(record,holder.credentialHash)),!0)}catch{return!1}}function upRoleChildCommand(role){const source=import.meta.url.endsWith(".ts"),entry=fileURLToPath(new URL(source?"./up-role-child.ts":"./up-role-child.js",import.meta.url));return{file:process.execPath,argv:[...source?["--import",import.meta.resolve("tsx")]:[],entry,role]}}function startUpRole(args){const{role}=args;let resolveReady=()=>{};const ready=new Promise(resolve2=>resolveReady=resolve2),generations=new RoleGenerations;let stopping=!1,endedForGood=!1;const endForGood=detail=>{stopping||endedForGood||(endedForGood=!0,args.onEnded(detail,!1))};let failed=null,fatal=null,closedProblem=null,livePid=null;const receive=(raw,abort)=>{const message=roleMessage(raw,role);if(message!==null){if(message.type==="ready"){if(message.build!==args.build){fatal=`the ${role} is a different build (${message.build}) from this one (${args.build}) — restart Toolroll`,failed={reason:"start",detail:fatal},generations.refused(fatal),abort();return}livePid=message.pid;const again=!generations.ready();again||resolveReady({ok:!0,url:message.url??"",port:message.port,pid:message.pid}),args.onReady(message,again);return}if(message.type==="failed"){failed={reason:message.reason,detail:message.detail},generations.refused(message.detail);return}if(message.type==="fatal"){fatal=message.detail;return}if(message.type==="closed"){closedProblem=message.problem;return}message.type!=="alive"&&args.onMessage(message)}};if(!args.split){const channel=memoryChannel(role);channel.parent.onMessage(message=>receive(message,()=>channel.parent.stop(!1)));const done2=upRoleCommand(args.context,{start:args.start(1),port:channel.port}).catch(error=>(fatal=describe(error),EXIT.failed)).then(code=>(livePid=null,generations.wasReady()?endForGood(fatal??`the ${role} stopped (exit ${code})`):resolveReady({ok:!1,...failed??{reason:"start",detail:fatal??`the ${role} stopped while starting (exit ${code})`}}),{problem:closedProblem}));return{ready,done:done2,send:message=>channel.parent.send(message),stop:()=>{stopping=!0,channel.parent.stop(!1)},hardStop:()=>{channel.parent.stop(!0)},kill:()=>{stopping=!0,channel.parent.stop(!0)},pid:()=>livePid}}const controller=new AbortController;let child=null;const command=upRoleChildCommand(role);let heardAt=Date.now(),stoppingSince=null,liveBuilds=0,saidPaused=!1,saidWaiting=!1;const watchdog=args.watchdog===void 0?null:setInterval(()=>{const owned=child;if(stopping||controller.signal.aborted||owned===null||owned.exitCode!==null||owned.signalCode!==null||!generations.current())return;const now=Date.now(),silentMs=now-heardAt,silenceMs=args.watchdog.silenceMs??WORKER_SILENCE_MS,facts={silentMs,silenceMs,stoppingForMs:stoppingSince===null?null:now-stoppingSince,graceMs:args.watchdog.graceMs,deadlineMs:SHUTDOWN_DEADLINE_MS,liveBuilds,paused:!1};if(watchdogVerdict(facts)==="fine"){saidPaused=!1,saidWaiting=!1;return}try{facts.paused=args.watchdog.paused()}catch{facts.paused=!0}const verdict=watchdogVerdict(facts);if(verdict==="leave"){saidPaused||args.watchdog.say(`the ${role} isn't answering, but an update or restart is under way; leaving it to that`),saidPaused=!0;return}if(verdict==="wait"){saidWaiting||args.watchdog.say(`the ${role} is still stopping: ${liveBuilds===1?"a build hasn't":`${liveBuilds} builds haven't`} confirmed ${liveBuilds===1?"it":"they"} stopped; leaving it to finish`),saidWaiting=!0;return}verdict==="restart"&&(args.watchdog.say(silentMs<silenceMs?`the ${role}'s stop overran its deadline; stopping it and starting it again`:`the ${role} hasn't answered for ${Math.round(silentMs/1e3)}s; stopping it and starting it again`),stopProcessTree(owned)||owned.kill("SIGKILL"),heardAt=now)},WORKER_ALIVE_EVERY_MS);watchdog?.unref?.();const done=superviseController({file:command.file,argv:command.argv,signal:controller.signal,ipc:!0,shutdownMs:args.shutdownMs,label:envValue(process.env,"LOG_FORMAT")==="json"?"":`[${role}]`,onSpawn:(owned,generation)=>{child=owned,fatal=null,failed=null,generations.spawned(),heardAt=Date.now(),stoppingSince=null,owned.on("message",raw=>{heardAt=Date.now();const alive=roleMessage(raw,role);alive?.type==="alive"&&(stoppingSince=alive.stopping?stoppingSince??heardAt:null,liveBuilds=alive.liveBuilds),receive(raw,()=>controller.abort())}),owned.on("error",()=>{});let recorded=!1;try{recorded=owned.pid!==void 0&&(args.onSpawned?.(owned.pid)??!0)}catch{}if(!recorded){fatal="The worker process record could not be saved",failed={reason:"start",detail:fatal},generations.refused(fatal),owned.kill("SIGKILL"),controller.abort(),resolveReady({ok:!1,...failed});return}owned.send(args.start(generation),error=>{error!=null&&owned.kill("SIGTERM")})},onState:state=>{if(state.phase!=="backoff")return;child=null,livePid=null;const exit=state.exit?.signal??state.exit?.code??"unknown";if(stopping&&generations.wasReady())return;const verdict=generations.ended();if(verdict==="fail-start"){controller.abort(),resolveReady({ok:!1,...failed??{reason:"start",detail:fatal??`the ${role} stopped while starting (exit ${exit})`}});return}if(verdict==="end"){controller.abort(),endForGood(generations.refusedWith()??fatal??`the ${role} kept stopping before it was ready (exit ${exit})`);return}if(controller.signal.aborted){endForGood(fatal??`the ${role} stopped (exit ${exit})`);return}if(generations.struggling()){args.onEnded(`${fatal===null?"":`${fatal} — `}the ${role} is still restarting (${generations.notReady()} tries so far, exit ${exit})`,!0);return}args.onEnded(`${fatal===null?"":`${fatal} — `}the ${role} stopped unexpectedly (exit ${exit})`,!0)}}).catch(error=>{generations.wasReady()||resolveReady({ok:!1,reason:"start",detail:describe(error)})}).finally(()=>{watchdog!==null&&clearInterval(watchdog)}).then(()=>(generations.wasReady()?endForGood(generations.refusedWith()??fatal??`the ${role} stopped`):resolveReady({ok:!1,...failed??{reason:"start",detail:fatal??`the ${role} did not start`}}),{problem:closedProblem}));return{ready,done,send:message=>{const owned=child;if(owned!==null&&owned.connected)try{owned.send(message,()=>{})}catch{}},stop:()=>{stopping=!0,controller.abort()},hardStop:()=>{const owned=child;if(owned!==null&&owned.connected)try{owned.send({type:"hard-stop"},()=>{})}catch{}},kill:()=>{stopping=!0,controller.abort();const owned=child;owned!==null&&owned.exitCode===null&&owned.signalCode===null&&!stopProcessTree(owned)&&owned.kill("SIGKILL")},pid:()=>livePid}}export async function runUpRole(start,port){return runOperate("up",["--db",start.databaseFile,...start.containment===null?[]:["--containment",start.containment]],line=>port.send({type:"log",line}),{upRole:{start,port}})}async function upRoleCommand(context,host){const{start,port}=host;return start.build!==upBuildIdentity()?(port.send({type:"failed",reason:"start",detail:`this ${start.role} is a different build (${upBuildIdentity()}) from the \`up\` that started it (${start.build})`}),EXIT.refused):resolve(start.databaseFile)!==resolve(context.databaseFile)?(port.send({type:"failed",reason:"start",detail:`the ${start.role} opened a different database`}),EXIT.refused):start.role==="console"?runUpConsoleRole(context,start.config,port,start.build):runUpWorkerRole(context,start.config,port,start.build)}async function runUpConsoleRole(context,config,port,build2){const{store,clock}=context,progress=line=>port.send({type:"log",line}),activeRepos=new Set(config.repos);let instanceSecret=null,draining=!1;const keyEpoch=randomBytes(16).toString("hex");let console_;try{console_=await startConsole({keyEpoch,instanceSecret:()=>instanceSecret,draining:()=>draining,context,host:config.host,port:config.port,...config.allowedHosts===null?{}:{allowedHosts:config.allowedHosts},...config.publicUrl===null?{}:{publicUrl:config.publicUrl},localRunner:config.localRunner,poolRoot:config.poolRoot,repos:config.repos,currentRepos:()=>[...activeRepos],admittedRepos:()=>[...activeRepos],upConsole:!0,registryPath:config.registryPath,projectRoots:await(async()=>{const saved=await loadProjectRegistry(config.registryPath);return"error"in saved?config.projectRoots:saved.roots})(),...config.editor?{editorLinks:"vscode"}:{}})}catch(error){return port.send({type:"failed",reason:"port-busy",detail:describe(error)}),EXIT.refused}let codingClosed=!1;const closeCoding=()=>{codingClosed||(codingClosed=!0,console_.server.closeCoding().catch(()=>{}))};let resolveStopped=()=>{};const stopped=new Promise(resolveStop=>resolveStopped=resolveStop);port.onStop(()=>resolveStopped());const lifecycleComponent=consoleComponent(config.host,console_.port),lifecycleHolder=`${process.pid}:${randomUUID().slice(0,8)}`;try{reportLifecycle(store,lifecycleComponent,"started",lifecycleHolder,clock(),{pid:process.pid})}catch{}const lifecycleBeat=setInterval(()=>{try{beatLifecycle(store,lifecycleComponent,lifecycleHolder,clock())}catch{}},RUNNER_HEARTBEAT_MS);lifecycleBeat.unref?.(),port.onMessage(message=>{if(message.type==="repos"){activeRepos.clear();for(const repo of message.repos)activeRepos.add(repo)}else if(message.type==="stopping"){draining=!0;try{reportLifecycle(store,lifecycleComponent,"draining",lifecycleHolder,clock(),{drainUntil:new Date(clock().getTime()+6e4)})}catch{}closeCoding()}else if(message.type==="sign-in-link"){let link=null;try{link=consoleSignInLink(console_.server,config.startAuthority,message)}catch{link=null}port.send({type:"sign-in-link",id:message.id,link})}});let mintedSecret=null;const instanceSocket=await openInstanceSocket(context.databaseFile,{pid:process.pid,build:packageVersion(),database:context.databaseFile,port:console_.port},()=>mintedSecret,()=>console_.server.mintLocalLink());instanceSocket.ok?(mintedSecret=await claimInstance(store,context.databaseFile,{pid:process.pid,port:console_.port,build:packageVersion(),socket:instanceSocket.name,keyEpoch:console_.server.keyEpoch},clock()),instanceSecret=mintedSecret,mintedSecret===null&&progress("attach: another console is running on this database — `toolroll` in a repository opens that one")):progress(`attach: ${instanceSocket.problem} — \`toolroll\` in a repository won't find this console`),port.send({type:"ready",role:"console",build:build2,pid:process.pid,url:console_.url,port:console_.port}),await stopped,draining=!0,closeCoding(),clearInterval(lifecycleBeat),instanceSocket.ok&&instanceSocket.close(),mintedSecret!==null&&clearInstance(store,mintedSecret);let closeProblem=null;await new Promise(done=>console_.server.close(error=>{closeProblem=error==null?null:error.message,done()}));try{reportLifecycle(store,lifecycleComponent,"stopped",lifecycleHolder,clock())}catch{}return port.send({type:"closed",problem:closeProblem}),closeProblem===null?EXIT.ok:EXIT.failed}async function runUpWorkerRole(context,config,port,build2){const{store,clock}=context,progress=line=>port.send({type:"log",line}),runnerName=config.runner,runnerToken=config.token,pool=config.pool,registryPath=config.registryPath,pinnedRepos=new Set(config.pinnedRepos),gitRun=context.gitRunner??((file,args,opts)=>run(file,[...args],{...opts?.cwd===void 0?{}:{cwd:opts.cwd},timeoutMs:1e4})),proveRepo=async input=>(await upProveSaved(gitRun,input))?.root??null,activeRepos=new Set(config.repos),reportRepos=()=>port.send({type:"repos",repos:[...activeRepos]});let stopping=!1,fatal=null,graceTimer;const followControllers=[];let resolveStopped=()=>{};const stopped=new Promise(resolveStop=>resolveStopped=resolveStop),hardStop=()=>{const terminated=terminateLiveProviders();terminated>0&&progress(`Stopped ${terminated} running build(s). Their work is saved, and each resumes when the builder starts again.`)},loopHealth=new Map;let deadlineTimer;const stillWaitingOn=()=>{const named2=[...loopHealth.values()].map(read=>read()).filter(one=>one.cleanup!==null).map(one=>`${projectName(one.repo)}: ${one.cleanup}`);return named2.length===0?"the worker's own shutdown":named2.join(", ")},forceEnd=async()=>{const waiting=stillWaitingOn();progress(`Stopping is taking too long (still waiting on ${waiting}); stopping this worker's builds now`),await endAfterExitProof({hardStop,liveBuilds:liveProviderCount,say:progress,exit:port.exit,code:EXIT.failed,before:()=>port.send({type:"fatal",detail:`the worker's stop didn't finish (still waiting on ${waiting}); Toolroll is restarting it`})})},armDeadline=()=>{deadlineTimer===void 0&&(deadlineTimer=setTimeout(()=>{forceEnd()},config.stopGraceMs+SHUTDOWN_DEADLINE_MS),deadlineTimer.unref?.())},stop=()=>{if(stopping){hardStop();return}stopping=!0,armDeadline(),resolveStopped();for(const controller of followControllers)controller.abort();wakeHubFor(store,read=>briefly(store,read)).poke();const building=store.liveClaimCount(runnerName,clock());building>0&&progress(`Stopping: ${building} build(s) running. Waiting up to ${Math.round(config.stopGraceMs/1e3)}s for them to finish; any still running then is saved and resumes when the builder starts again.`),graceTimer=setTimeout(hardStop,config.stopGraceMs),graceTimer.unref?.()};port.onStop(hard=>{stopping||stop(),hard&&hardStop()});const loopFlagsFor=repo=>{const copy=new Map;return config.forMs!==null&©.set("for",String(config.forMs)),copy.set("runner",runnerName),copy.set("token",runnerToken),copy.set("repo",repo),copy.set("pool",pool),config.publicUrl!==null&©.set("public-url",config.publicUrl),copy},prefix=repo=>activeRepos.size>1?`[${projectName(repo)}] `:"",containmentDetail=config.verbose||!config.terminal;let containmentSaid=!1;const firstContainmentNotice=()=>{try{return noticeDueOnce(context.store,CONTAINMENT_NOTICE_FACT,clock())}catch{return!0}},containmentLines=effective=>{const notice=containmentNotice(effective);return notice!==null&&!containmentSaid&&(containmentDetail||firstContainmentNotice())&&progress(notice),containmentSaid=!0,containmentDetail||effective.refusal!==null?[`watch: ${describeContainment(effective)}`]:[]},loopResults=new Map,projectPasses=new ProjectPasses,releasedRepos=new Set,relaunches=new Map,relaunchAttempts=new Map,relaunchAbort=new AbortController;followControllers.push(relaunchAbort);const relaunchPause=ms=>new Promise(resolvePause=>{const timer=setTimeout(done,ms);function done(){clearTimeout(timer),relaunchAbort.signal.removeEventListener("abort",done),resolvePause()}relaunchAbort.signal.aborted?done():relaunchAbort.signal.addEventListener("abort",done,{once:!0})}),stoppedAt=new Map,stillTimers=new Map,noticed=write=>{try{briefly(store,write)}catch{}},builderBack=(repo,relaunching)=>{const at=stoppedAt.get(repo);stoppedAt.delete(repo);const timer=stillTimers.get(repo);timer!==void 0&&clearTimeout(timer),stillTimers.delete(repo),noticed(relaunching&&at!==void 0?()=>noteRestarted(store,{repo,stoppedAt:at,now:clock()}):()=>closeStillRestarting(store,repo,clock()))},scheduleRelaunch=(repo,detail)=>{if(relaunches.has(repo)||stopping)return;if(!stoppedAt.has(repo)){const at=clock();stoppedAt.set(repo,at);const timer=setTimeout(()=>{!stopping&&stoppedAt.get(repo)===at&¬iced(()=>noteStillRestarting(store,{repo,stoppedAt:at,now:clock()}))},STILL_RESTARTING_AFTER_MS);timer.unref?.(),stillTimers.set(repo,timer)}const attempt=relaunchAttempts.get(repo)??0;relaunchAttempts.set(repo,attempt+1);const delay=relaunchDelayMs(attempt,context.loopRelaunchMs);progress(`${prefix(repo)}this project's builder stopped (${detail}); Toolroll is restarting it in ${Math.max(1,Math.round(delay/1e3))}s`);const pending=(async()=>{await relaunchPause(delay);let waited=0,saidWaiting=!1;for(;;){if(stopping)return;if(releasedRepos.has(repo)){fatal=`${prefix(repo)}${detail}`,stop();return}if(!activeRepos.has(repo))return;let admission;try{admission=briefly(store,()=>relaunchAdmission(store,runnerName,repo,clock()))}catch(error){if(!isDatabaseBusy(error))throw error;await relaunchPause(relaunchDelayMs(waited++,context.loopRelaunchMs));continue}if(admission==="identity"){fatal=`the builder identity changed while restarting ${projectName(repo)}`,stop();return}if(admission==="gone"){loopResults.delete(repo),activeRepos.delete(repo),reportRepos(),progress(`project removed — ${projectName(repo)} is no longer built here`);return}if(admission==="go")break;saidWaiting||progress(`${prefix(repo)}still restarting: waiting for ${RELAUNCH_WAIT_WORDS[admission]}`),saidWaiting=!0,await relaunchPause(relaunchDelayMs(waited++,context.loopRelaunchMs))}loopResults.delete(repo),relaunches.delete(repo),await launchRepo(repo,!1,!1,!0)})().catch(error=>{fatal=`${prefix(repo)}the builder couldn't be restarted (${describe(error)})`,stop()}).finally(()=>{relaunches.get(repo)===pending&&relaunches.delete(repo)});relaunches.set(repo,pending)},launchRepo=async(repo,bind,drain=!1,relaunching=!1)=>{if(loopResults.has(repo)||stopping)return;let readyAt=null;if(drain&&releasedRepos.add(repo),bind){const bound=addRunnerReposAuthed(store,{name:runnerName,token:runnerToken,repos:[repo]},clock());if(!bound.ok){fatal=`the builder identity changed while adding ${repo} (${bound.reason})`,stop();return}activeRepos.add(repo),reportRepos(),store.listProjects().some(one=>one.path===repo)||store.upsertProject(repo,projectName(repo),clock())}let markReady=()=>{};const ready=new Promise(resolveReady=>markReady=resolveReady),loop=runWatchLoop({flags:loopFlagsFor(repo),context,runner:runnerName,token:runnerToken,repo,progress:line=>progress(`${prefix(repo)}${line}`),isStopping:()=>stopping||releasedRepos.has(repo),onFollowController:controller=>followControllers.push(controller),containmentLines,passes:projectPasses,serviceBridge:!0,health:read=>loopHealth.set(repo,read),leaseWaitMs:config.leaseWaitMs,...drain?{leaseWaitStopping:()=>stopping}:{},onReady:()=>{readyAt=Date.now(),markReady(),bind&&progress(`${prefix(repo)}builder connected — queued work can start`),relaunching&&progress(`${prefix(repo)}builder restarted automatically — queued work can start`),builderBack(repo,relaunching)}}).then(result=>({repo,result}),error=>({repo,result:{ok:!1,reason:"loop-failed",detail:describe(error),ticks:0,built:0,broke:0,busy:isDatabaseBusy(error)}}));loopResults.set(repo,loop),loop.then(({repo:endedRepo,result})=>{if(releasedRepos.has(endedRepo)&&!stopping&&!result.ok){fatal=`${prefix(endedRepo)}${result.detail}`,stop(),markReady();return}if(releasedRepos.has(endedRepo)&&!stopping){const unbound=removeRunnerRepoAuthed(store,{name:runnerName,token:runnerToken,repo:endedRepo},clock());unbound.ok||(fatal=`the builder identity changed while removing ${endedRepo} (${unbound.reason})`,stop()),loopResults.delete(endedRepo),releasedRepos.delete(endedRepo),progress(`project removed — ${projectName(endedRepo)} is no longer built here`),markReady();return}if(!result.ok&&!stopping){if(readyAt!==null&&Date.now()-readyAt>=LOOP_STABLE_MS&&relaunchAttempts.delete(endedRepo),loopEndRecovery(result,relaunching)==="relaunch"&&activeRepos.has(endedRepo)){scheduleRelaunch(endedRepo,result.detail),markReady();return}fatal=`${prefix(endedRepo)}${result.detail}`,stop()}markReady()}),await ready},named=new Set(config.repos),boundNow=new Set(store.getRunner(runnerName)?.runner.repos??[]),draining=[...new Set(predecessorWatches(store,runnerName,clock()).map(one=>one.repo))].filter(repo=>!named.has(repo)&&boundNow.has(repo));for(const repo of draining)progress(`${projectName(repo)} was being removed when the previous worker stopped: recovering its work first`);await Promise.all(draining.map(repo=>launchRepo(repo,!1,!0))),await Promise.all(config.repos.map(repo=>launchRepo(repo,!1)));const telegramController=new AbortController;followControllers.push(telegramController),stopping&&telegramController.abort();const telegramSupervisor=(async()=>{const pause=ms=>new Promise(resolvePause=>{const timer=setTimeout(done,ms);function done(){clearTimeout(timer),telegramController.signal.removeEventListener("abort",done),resolvePause()}telegramController.signal.aborted?done():telegramController.signal.addEventListener("abort",done,{once:!0})});for(;!stopping&&!telegramController.signal.aborted;){const follower=startTelegramFollower({context,publicUrl:config.publicUrl??void 0,signal:telegramController.signal,progress,label:"telegram:",died:{prefix:"",next:"starting it again"},owner:`service-${randomUUID()}`});if(follower!==null&&await follower,follower===null&&loadBotToken(process.env,context.telegramTokenFile)!==null)break;await pause(follower===null?2e3:5e3)}})(),dynamicCeiling=resolveCeiling(config.repos,config.projectRoots,path=>resolve(path)).ceiling,rejected=new Set,lineIdentities=projectIdentities(),admittedLines=new Map(Object.entries(config.repoLines??{})),deferred=upDeferredRetry(config.deferredRepos??[],input=>upProveSaved(gitRun,input)),deferredGenerations=config.deferredGenerations??{},reportDeferred=()=>port.send({type:"deferred",repos:deferred.list()}),registrySupervisor=(async()=>{const sleep=ms=>new Promise(resolveSleep=>setTimeout(resolveSleep,ms));for(;!stopping;){const loaded=await loadProjectRegistry(registryPath);if("error"in loaded){fatal=loaded.error,stop();break}deferred.keepOnly(loaded.repos)&&reportDeferred();const plain=loaded.repos.filter(one=>!deferred.has(one));await lineIdentities.refresh(plain);const saved=new Set(loaded.repos);let removed=!1;for(const repo of[...activeRepos]){const lines=admittedLines.get(repo)??[repo];stopping||pinnedRepos.has(repo)||saved.has(repo)||lines.some(line=>saved.has(line))||(activeRepos.delete(repo),removed=!0,releasedRepos.add(repo),loopResults.has(repo)||releasedRepos.delete(repo))}removed&&reportRepos();for(const candidate of loaded.repos){if(stopping)break;if(deferred.has(candidate)){await connectDeferred(candidate);continue}const canonical=lineIdentities.known(candidate);if(canonical===void 0||canonical!==null&&(activeRepos.has(canonical)||releasedRepos.has(canonical)))continue;const approvedAdditions=context.additionalProjectRepos?.()??[],admittedRepos=[...dynamicCeiling.repos,...approvedAdditions],admittedCeiling={repos:admittedRepos.length===0&&dynamicCeiling.roots.length===0?["/\0nothing-admitted"]:admittedRepos,roots:dynamicCeiling.roots,canon:path=>lineIdentities.known(path)??null};if(!(canonical!==null&&(await authorizedProject(admittedCeiling,canonical)||admissionRecorded(store,canonical))&&await proveRepo(canonical)===canonical)){rejected.has(candidate)||(rejected.add(candidate),progress(`project not connected — ${candidate} isn't a Git repository added with \`toolroll repos add\` or the console`));continue}rejected.delete(candidate),admittedLines.set(canonical,[...new Set([...admittedLines.get(canonical)??[],candidate])]),await launchRepo(canonical,!0)}stopping||await sleep(500)}})().catch(error=>{fatal=`the project registry stopped (${describe(error)})`,stop()});async function connectDeferred(candidate){const proved=await deferred.retry(candidate);if(proved===null||stopping)return;if(proved.line!==candidate||proved.root!==candidate){deferred.revoke(candidate),reportDeferred(),progress(proved.root!==proved.line?`saved project not connected — ${candidate} came back as part of ${proved.root}; add it again to connect it`:`saved project not connected — ${candidate} now leads to ${proved.line}; add it again to connect it`);return}const root=candidate;if(activeRepos.has(root)||releasedRepos.has(root)){deferred.revoke(candidate),reportDeferred();return}let launching=null,removedSince=!1;if(await updateProjectRegistry(registryPath,current=>{if(stopping||!deferred.has(candidate))return current;const count=registryRemovals(registryPath)?.[candidate]??(registryRemovals(registryPath)===null?-2:0);return!current.repos.includes(candidate)||count!==deferredGenerations[candidate]?(deferred.revoke(candidate),removedSince=!0,current):(deferred.revoke(candidate),admittedLines.set(root,[candidate]),launching=launchRepo(root,!0),current)}),removedSince){reportDeferred(),progress(`saved project not connected — ${candidate} was removed while it was away; add it again to connect it`);return}launching!==null&&(reportDeferred(),progress(`saved project is back — connecting ${root}`),await launching)}let readinessTimer;if(context.agentRunner===void 0){let observing=!1;const observeReadiness=()=>{observing||stopping||(observing=!0,observeProviderReadiness((file,args,options)=>run(file,args,{timeoutMs:options?.timeoutMs??5e3,...options?.omitEnv===void 0?{}:{omitEnv:options.omitEnv}}),process.env,PROVIDER_IDS,provider=>store.acpAttestationFor(provider,runnerName)).then(observed=>{stopping||reportProviderReadinessAuthed(store,{name:runnerName,token:runnerToken,observations:observed},clock())}).catch(()=>{}).finally(()=>{observing=!1}))};observeReadiness(),readinessTimer=setInterval(observeReadiness,12e4),readinessTimer.unref?.()}try{notifyVersionLive(context.store,dirname(context.databaseFile),PACKAGE_VERSION,clock())}catch{}recordRunnerVersion(dirname(context.databaseFile),runnerName,PACKAGE_VERSION,clock());const stopLiveBackups=context.agentRunner===void 0?startLiveBackups(store,context.databaseFile,()=>[...new Set([...activeRepos,...store.knownRepos(),pool])]):null;fatal===null&&!stopping&&port.send({type:"ready",role:"worker",build:build2,pid:process.pid,url:null,port:null});const cleanupSince=new Map,aliveTimer=setInterval(()=>{const repos=[...loopHealth.entries()].filter(([repo])=>loopResults.has(repo)).map(([,read])=>read());if(port.send({type:"alive",stopping,repos,liveBuilds:liveProviderCount()}),!stopping)for(const one of repos){if(one.cleanup===null||one.cleanup==="its builds"){cleanupSince.delete(one.repo);continue}const since=cleanupSince.get(one.repo);if(since===void 0||since.stage!==one.cleanup){cleanupSince.set(one.repo,{stage:one.cleanup,at:Date.now()});continue}if(!(Date.now()-since.at<config.stopGraceMs+SHUTDOWN_DEADLINE_MS)){fatal=`${prefix(one.repo)}its loop stopped but never finished stopping (still waiting on ${one.cleanup})`,stop();return}}},WORKER_ALIVE_EVERY_MS);return aliveTimer.unref?.(),await stopped,readinessTimer!==void 0&&clearInterval(readinessTimer),await registrySupervisor,await Promise.all(relaunches.values()),await Promise.all(loopResults.values()),await stopLiveBackups?.(),await new Promise(done=>{const timer=setTimeout(done,TELEGRAM_STOP_WAIT_MS),finish=()=>{clearTimeout(timer),done()};telegramSupervisor.then(finish,finish)}),graceTimer!==void 0&&clearTimeout(graceTimer),deadlineTimer!==void 0&&clearTimeout(deadlineTimer),clearInterval(aliveTimer),fatal!==null?(port.send({type:"fatal",detail:fatal}),EXIT.failed):EXIT.ok}export async function refreshGithubNightlies(store,now,reads){return githubNightlyRepos(store).length===0?0:readGithubNightlies(store,{gh:reads??githubReads(releaseExec,releaseTools().gh,{retry:!0}),now})}export async function evalsCommand(positional,flags,context){const{write,json}=context,{admitEvalCampaign,campaignSpending,EVALS_ROOT,installedBuildDigest,loadEvalSet,planCampaign,recoverEvalCampaigns,runEvalCampaign}=await import("./evals.js"),{inEvalWorld}=await import("./eval-gate.js"),{evalCliEntry,runEvalWorld}=await import("./eval-world.js"),action=positional[0],command=`evals${action===void 0?"":` ${action}`}`,usage="Use: toolroll evals run [--diagnostic] [--case <ids>] [--k <n>] --as <you> --token <password> | toolroll evals cases | toolroll evals recover [--abandon <campaign> --as <you> --token <password>]";if(action==="recover"&&flags.has("abandon"))return evalsAbandonCommand(flags,context);if(action==="recover"){const recovered=recoverEvalCampaigns(context.store,context.clock());return succeed(write,json,command,{campaigns:recovered},()=>recovered.length===0?["No campaign is running."]:recovered.map(one=>`${one.id}: ${one.recovered?"recovered":"left running"} (${one.why})`))}if(action==="cases"){const set2=loadEvalSet();if(!set2.ok)return fail(write,json,command,"unreadable",set2.problem,EXIT.failed);const cases2=set2.cases.map(one=>({id:one.id,kind:one.kind,version:one.version,pin:one.pin,validatedBy:one.validatedBy,draft:one.validatedBy===null}));return succeed(write,json,command,{manifestDigest:set2.manifestDigest,cases:cases2},()=>cases2.map(one=>`${one.id} (${one.kind}) ${one.version.slice(0,12)} on ${one.pin.model}: ${one.draft?"draft, awaiting a person's validation":`validated by ${one.validatedBy}`}`))}if(action==="attempt"){if(!inEvalWorld())return fail(write,json,command,"refused","An eval attempt runs only from its campaign's runner.",EXIT.refused);const[,campaign,caseId,n]=positional,world=text(flags,"world");if(campaign===void 0||caseId===void 0||n===void 0||!/^[1-9][0-9]?$/.test(n)||world===void 0)return fail(write,json,command,"usage","Use: toolroll evals attempt <campaign> <case> <n> --world <dir> --db <world>/toolroll/orders.db",EXIT.usage);let worldDir;try{worldDir=realpathSync(world)}catch{return fail(write,json,command,"refused","The world's folder can't be read.",EXIT.refused)}if(resolve(context.databaseFile)!==join(worldDir,"toolroll","orders.db"))return fail(write,json,command,"refused","An eval attempt runs only on its world's own database.",EXIT.refused);const set2=loadEvalSet(),one=set2.ok?set2.cases.find(item=>item.id===caseId):void 0;if(one===void 0)return fail(write,json,command,"refused",set2.ok?`No case is named ${caseId}.`:set2.problem,EXIT.refused);const deny=(text(flags,"deny")??"").split(",").filter(path=>path!==""&&isAbsolute(path)),report=await runEvalWorld(one,{worldDir,databaseFile:context.databaseFile,deny,timeoutMs:one.timeoutMinutes*6e4});return succeed(write,json,command,{...report},()=>[JSON.stringify(report)])}if(action!=="run"||positional.length!==1)return fail(write,json,command,"usage",usage,EXIT.usage);if(inEvalWorld())return fail(write,json,command,"refused","An eval world doesn't start campaigns of its own.",EXIT.refused);if(machineActing()||process.env.TOOLROLL_LEAD_TOKEN!==void 0)return fail(write,json,command,"person-only","Only a person starts an eval campaign: it spends money.",EXIT.refused);const k=text(flags,"k"),cases=text(flags,"case"),set=loadEvalSet();if(!set.ok)return fail(write,json,command,"unreadable",set.problem,EXIT.failed);const planned=planCampaign(set,{...cases===void 0?{}:{cases:cases.split(",").filter(Boolean)},...k===void 0?{}:{k:Number(k)},diagnostic:flag(flags,"diagnostic")});if(!planned.ok)return fail(write,json,command,"refused",planned.problem,EXIT.refused);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,command,"usage","An eval campaign is started with your password: add --as <you> --token <password>.",EXIT.usage);const{plan}=planned,buildDigest=()=>installedBuildDigest(PACKAGE_VERSION),sealed={cases:plan.cases.map(one=>({id:one.id,version:one.version,pin:one.pin,maxDispatches:one.maxDispatches})),k:plan.k,baseline:null,evals:EVALS_ROOT};recoverEvalCampaigns(context.store,context.clock());const admitted=admitEvalCampaign(context.store,{kind:"eval",canonical:plan.canonical,manifestDigest:set.manifestDigest,buildDigest:buildDigest(),version:PACKAGE_VERSION,k:plan.k,sealed,as:acting.name,token:acting.token,now:context.clock()});if(!admitted.ok)return fail(write,json,command,admitted.reason,admitted.message,EXIT.refused);const stateDir=dirname(context.databaseFile),entry=evalCliEntry(),keep=["PATH","HOME","USER","LOGNAME","LANG","SHELL","TMPDIR"],ended=await runEvalCampaign(context.store,admitted.id,plan.cases,{workRoot:join(dirname(stateDir),"toolroll-eval-worlds",admitted.id),buildDigest,keepWorlds:flag(flags,"keep"),now:context.clock,command:input=>({file:entry.file,args:[...entry.args,"evals","attempt",input.campaign,input.caseId,String(input.n),"--world",input.worldDir,"--deny",stateDir,"--db",input.databaseFile,"--json"],env:{...Object.fromEntries(keep.flatMap(name=>process.env[name]===void 0?[]:[[name,process.env[name]]])),XDG_CONFIG_HOME:join(input.worldDir,"config")}})}),rows=context.store.handle.prepare("SELECT case_id, n, replaces, outcome, error_why, api_microusd, subscription_microusd, usage_unknown FROM eval_attempt WHERE campaign = ? ORDER BY case_id, n, replaces").all(admitted.id),nullable=value=>value==null?null:Number(value),attempts=rows.map(row=>({case:String(row.case_id),n:Number(row.n),replaces:Number(row.replaces),outcome:row.outcome===null?null:String(row.outcome),why:row.error_why===null?null:String(row.error_why),apiMicrousd:nullable(row.api_microusd),subscriptionMicrousd:nullable(row.subscription_microusd),usageUnknown:Number(row.usage_unknown)===1})),spent=campaignSpending(context.store,admitted.id),dollars=(micro,unknown)=>micro===null?`unknown (${unknown} attempt${unknown===1?"":"s"} with unknown spending)`:`$${(micro/1e6).toFixed(2)}`;return succeed(write,json,command,{campaign:admitted.id,canonical:plan.canonical,state:ended.state,why:ended.why,attempts,spending:spent},()=>[`Campaign ${admitted.id} (${plan.canonical?"canonical":"diagnostic"}) is ${ended.state}${ended.why===null?"":`: ${ended.why}`}.`,...attempts.map(one=>`${one.case} #${one.n}${one.replaces===0?"":" (replacement)"}: ${one.outcome??"not finished"}${one.why===null?"":` — ${one.why}`}`),`API dollars: ${dollars(spent.apiMicrousd,spent.unknownAttempts)}. Subscription usage, not billed: ${dollars(spent.subscriptionMicrousd,spent.unknownAttempts)}.`])}async function evalsAbandonCommand(flags,context){const{write,json}=context,command="evals recover",{abandonEvalCampaign}=await import("./evals.js"),{inEvalWorld}=await import("./eval-gate.js"),id=text(flags,"abandon");if(id===void 0||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/.test(id))return fail(write,json,command,"usage","Use: toolroll evals recover --abandon <campaign> --as <you> --token <password>",EXIT.usage);if(inEvalWorld()||machineActing()||process.env.TOOLROLL_LEAD_TOKEN!==void 0)return fail(write,json,command,"person-only","Only a person abandons an eval campaign.",EXIT.refused);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,command,"usage","A campaign is abandoned with your password: add --as <you> --token <password>.",EXIT.usage);const ended=abandonEvalCampaign(context.store,{id,as:acting.name,token:acting.token,now:context.clock()});return ended.ok?succeed(write,json,command,{campaign:id,state:"incomplete",attempts:ended.attempts,spending:"unknown"},()=>[`Campaign ${id} ended incomplete. ${ended.attempts} unfinished attempt${ended.attempts===1?"":"s"} recorded as errors; what it spent is unknown. Nothing was stopped: check for its processes yourself.`]):fail(write,json,command,ended.reason,ended.message,EXIT.refused)}export function upDeferredRetry(inputs,prove,everyMs=5e3,now=Date.now){const nextAt=new Map(inputs.map(input=>[input,now()+everyMs]));return{has:input=>nextAt.has(input),list:()=>[...nextAt.keys()],retry:async input=>{const due=nextAt.get(input);return due===void 0||now()<due?null:(nextAt.set(input,now()+everyMs),prove(input))},revoke:input=>{nextAt.delete(input)},keepOnly:saved=>{const keep=new Set(saved);let changed=!1;for(const input of[...nextAt.keys()])keep.has(input)||(nextAt.delete(input),changed=!0);return changed}}}export async function upProveSaved(gitRun,input,look={}){const top=await gitRun("git",["rev-parse","--show-toplevel"],{cwd:resolve(input)});if(top.code!==0)return null;const answered=await lookIdentities([resolve(input),top.stdout.trim()],look);if(!answered.ok)return null;const line=answered.value.get(resolve(input))??null,root=answered.value.get(top.stdout.trim())??null;return line===null||root===null?null:{line,root}}export function upNarrowDeferred(held,reported){const kept=new Set(reported);return held.filter(one=>kept.has(one))}export function consoleIdentitiesInBackground(identities,paths){identities.refresh(paths).catch(()=>!1)}export function writeModelRow(store,proved,scope,knownProject2,slot,to,now,extra=[]){const followRepair=slot!==null&&to!==null&&slot.phase==="build"&&(slot.tier==="routine"||slot.tier==="strong");return applyModelChoices(store,{scope,change:slot===null?[]:[{slot,to}],expected:null,strict:!1,knownProject:knownProject2,extra,followRepair},{...proved,live:()=>!0},now)}function refuseMachineTidy(context,command,method){return machineActing()||process.env.TOOLROLL_LEAD_TOKEN!==void 0||method!==void 0&&!personProof(method)?fail(context.write,context.json,command,"person-only","Only a person puts tasks away or restores them. Use the console or your own login.",EXIT.refused):null}async function archiveTasksCommand(positional,flags,context){const{store,write,json,clock}=context,command="task archive",ids=[...new Set(positional)];if(ids.length===0||ids.length>100)return fail(write,json,command,"usage","`toolroll task archive <id...> [--reason <why>] --as <you> --token <t>` — 1 to 100 tasks",EXIT.usage);const machine=refuseMachineTidy(context,command);if(machine!==null)return machine;const demo=refuseDemo(context,command);if(demo!==null)return demo;const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token,firstVisibleRepo(store,acting.name,ids));if(acting===null||!verified?.ok)return refuseApprover(context,command,verified,"putting a task away takes `--as <you> --token <t>` — it is recorded against your name",ids[0]);const personal=refuseMachineTidy(context,command,verified.method);if(personal!==null)return personal;const reason=text(flags,"reason")??"Put away by hand",archived=[],refused=[];for(const id of ids){const ref=store.lookupRef(id);if(ref===null||store.getTask(id)===null||!store.accountCanAccess(acting.name,ref.repo)){refused.push({id,reason:"unknown-task",message:`No task ${id}.`});continue}const done=archiveTaskFamily(store,id,{by:acting.name,byKind:"person",rule:null,reason},clock(),{guard:refs=>approverStandsNow(store,acting.name,familyRepoOf(store,refs))});done.ok?archived.push({id,versions:done.refs.length}):refused.push({id,reason:done.reason,message:done.message})}const lines=()=>[...archived.map(one=>`Put away ${one.id}${one.versions>1?` (${one.versions} versions)`:""}.`),...refused.map(one=>`Not put away: ${one.message}`),...archived.length===0?[]:[`Restore with \`toolroll task restore ${archived.map(one=>one.id).join(" ")}\`.`]];return refused.length===0?succeed(write,json,command,{archived,refused},lines):json?fail(write,json,command,refused[0].reason,refused[0].message,EXIT.refused,{archived,refused}):(write(lines().join(`
|
|
505
|
+
`)),EXIT.ok}function fail(write,json,command,reason,message,code,extra={}){return write(json?envelopeJson({ok:!1,command,reason,message,...extra}):message),code}function text(flags,name){const value=flags.get(name);return typeof value=="string"?value:void 0}function flag(flags,name){return flags.get(name)===!0||flags.get(name)==="true"}function consoleLinkFor(context,path){const base=loadConsoleUrl(process.env,dirname(context.databaseFile));return base===null?null:`${base}${path}`}function refuseDemo(context,command){return context.store.isDemo()?fail(context.write,context.json,command,"demo-database","this database is a demo sandbox — it never spends money or touches a remote; point this command at a real database",EXIT.refused):null}function readTtl(flags){const given=text(flags,"ttl");if(given===void 0)return DEFAULT_LEASE_MS;const seconds=Number(given);return!Number.isInteger(seconds)||seconds<=0?null:seconds*1e3}function mutationFrom(flags,now){const key=text(flags,"key");return key===void 0?{at:now}:{idempotencyKey:key,at:now}}function slug(title,now){const words=title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").split("-").filter(Boolean).slice(0,4).join("-"),stamp=now.toISOString().slice(11,19).replace(/:/g,"");return words===""?`task-${stamp}`:`${words}-${stamp}`}function describe(error){return error instanceof Error?error.message:String(error)}function databaseFailure(write,json,command,file,error){return isDatabaseBusy(error)?fail(write,json,command,"database-busy",`The database ${file} stayed busy for ${CONCURRENT_WRITER_WAIT_MS/1e3} seconds. Wait for the other Toolroll process to finish, then try again.`,EXIT.failed):fail(write,json,command,"database",describe(error),EXIT.failed)}function refuseApprover(context,command,verified,usage,subject){if(verified===null)return fail(context.write,context.json,command,"usage",usage,EXIT.usage);const reason=verified.ok?"":verified.reason;return fail(context.write,context.json,command,reason,describeApproveFailure(reason,subject??""),EXIT.refused)}async function knownProject(context,repoFlag,match){const registered=await loadRepos(registryPathOf(context)).catch(()=>({error:"unreadable"}));return[...new Set([...context.store.knownRepos(),...match.listed?context.store.listProjects().map(one=>one.path):[],..."error"in registered?[]:registered.repos])].find(one=>one===repoFlag||one===resolve(repoFlag)||match.canonical&&one===canonicalProject(repoFlag))}export function ownValueFlags(command,argv){if(command==="flows")return FLOWS_VALUE_FLAGS;if(command==="card")return CARD_PANEL_VALUE_FLAGS;if(command==="project"&&argv.find(arg=>!arg.startsWith("-"))==="network")return PROJECT_NETWORK_VALUE_FLAGS}async function projectCheckAccessCommand(positional,flags,context){const command="project check-access",wanted=positional[1],repo=await projectAsked(context,flags,positional,command,{own:[],most:2,usage:"Use project check-access --repo <project path> [sandboxed | sign-ins | unsandboxed].",invalid:wanted!==void 0&&!isCheckAccess(wanted),match:{listed:!0,canonical:!0}});if(typeof repo=="number")return repo;const current=context.store.projectCheckAccess(repo),platform=context.platform??process.platform,fenced=context.fenceAvailable?.()??(macosFenceAvailable()||linuxFenceAvailable()),runsAs=one=>checkAccessRunsAs(one,{platform,fenced,unconfinedAllowed:context.store.unfencedAgentsAllowed(),localMode:localModeOn(context.store)}),here=runsAs(current),words=one=>{if(runsAs(one)==="unsandboxed"&&one!=="unsandboxed")return[`${repo}: saved as ${checkAccessWords(one)}, but this machine can't sandbox checks, so they run without a sandbox.`];if(runsAs(one)!==one)return[`${repo}: saved with model and GitHub sign-ins, but its checks run sandboxed: sign-ins can't be shared with checks safely yet.`];const missing=one==="sign-ins"?signInHostsMissing(context.store.projectNetwork(repo)):[];return[`${repo}: checks run ${checkAccessWords(one)}.`,...one==="sandboxed"?[]:[CHECK_ACCESS_WARNINGS[one]],...missing.length===0?[]:[`Model sign-ins need these hosts in this project's network allowlist: ${missing.join(", ")}. Add them with: toolroll project network --repo ${repo} --allow ${missing.join(",")}`]]};if(wanted===void 0)return succeed(context.write,context.json,command,{repo,checkAccess:current,...here===current?{}:{runsAs:here},...here==="sign-ins"?{missingHosts:signInHostsMissing(context.store.projectNetwork(repo))}:{}},()=>words(current));const unavailable=wanted==="sign-ins"?signInsUnavailableWords(platform):null;if(unavailable!==null)return fail(context.write,context.json,command,"refused",unavailable,EXIT.refused);const widening=widerThan(wanted,current);if(wanted==="unsandboxed"&&localModeOn(context.store))return fail(context.write,context.json,command,"refused",LOCAL_MODE_CONFINES,EXIT.refused);const acting=await askCredentials(flags,context),proved=acting===null?null:authenticateApprover(context.store,acting.name,acting.token,repo);if(widening){if(acting===null||proved===null||!proved.ok||proved.method!=="password-now"||!context.store.isInstanceOperator(acting.name))return fail(context.write,context.json,command,"refused","An instance operator widens what a project's checks reach, with their password typed now: pass --as and --token.",EXIT.refused)}else if(acting===null||proved===null||!proved.ok||!credentialProof(proved.method)||!context.store.accountCanAccess(acting.name,repo))return fail(context.write,context.json,command,"refused","An approver for this project narrows what its checks reach, with their password: pass --as and --token.",EXIT.refused);const changed=context.store.setProjectCheckAccess(repo,wanted,acting.name,context.clock(),{may:widening?"widen":"narrow"});return changed===null?fail(context.write,context.json,command,"refused","The project's check access changed meanwhile, and this would now widen it: an instance operator widens it, with their password typed now.",EXIT.refused):succeed(context.write,context.json,command,{repo,before:changed.before,checkAccess:changed.after},()=>[...words(changed.after),"Scopes written from now on use this; scopes already approved keep what they were approved with."])}async function projectSandboxCommand(positional,flags,context){const command="project sandbox",repo=await projectAsked(context,flags,positional,command,{own:["read-deny","mach"],most:1,usage:"Use project sandbox --repo <project path> [--read-deny <paths>] [--mach <services>] (comma-separated; empty clears).",match:{listed:!0,canonical:!0}});if(typeof repo=="number")return repo;const words=one=>[`${repo}: ${readDenyWords(one.readDeny)}`,...one.machLookup.length===0?[]:[`macOS services also allowed: ${one.machLookup.join(", ")}`]],current=context.store.projectSandbox(repo),asked=name=>{const value=flags.get(name);return value===void 0?void 0:value===!0?[]:value.split(",")},changes={readDeny:asked("read-deny"),machLookup:asked("mach")};if(changes.readDeny===void 0&&changes.machLookup===void 0)return succeed(context.write,context.json,command,{repo,sandbox:current},()=>words(current));const parsed={readDeny:parseReadDeny(changes.readDeny??current.readDeny),machLookup:parseMachLookup(changes.machLookup??current.machLookup)};for(const[name,one]of Object.entries(parsed))if(!one.ok)return fail(context.write,context.json,command,"usage",`${name}: ${one.problem}. Nothing changed.`,EXIT.usage);const wanted={readDeny:parsed.readDeny.ok?parsed.readDeny.list:[],machLookup:parsed.machLookup.ok?parsed.machLookup.list:[]},acting=await askCredentials(flags,context),verified=acting===null?null:credentialApprover(context.store,acting.name,acting.token,repo);if(acting===null||!verified?.ok||!context.store.accountCanAccess(acting.name,repo))return fail(context.write,context.json,command,"refused","An approver for this project changes its sandbox, with their password: pass --as and --token.",EXIT.refused);const changed=context.store.setProjectSandbox(repo,wanted,acting.name,context.clock());return changed===null?fail(context.write,context.json,command,"refused","An approver for this project changes its sandbox. Nothing changed.",EXIT.refused):succeed(context.write,context.json,command,{repo,before:changed.before,sandbox:changed.after},()=>[...words(changed.after),"Scopes written from now on use this; scopes already approved keep what they were approved with."])}function gitTooOld(command,context){const problem=installedGitFloorProblem();return problem===null?null:fail(context.write,context.json,command,"git-too-old",problem,EXIT.refused)}function upBuildIdentity(){return buildIdentity(PACKAGE_VERSION,fileURLToPath(import.meta.url))}function upNeedsOneProcess(options){return options.openDatabase!==void 0||options.desktopIdentity!==void 0||options.additionalProjectRepos!==void 0||options.agentRunner!==void 0||options.gitRunner!==void 0||options.telegramTransport!==void 0||options.telegramEnv!==void 0||options.publishExec!==void 0||options.dispatchAdapter!==void 0||options.flowTriggerIo!==void 0||options.flowStepIo!==void 0||options.flowEveryMs!==void 0||options.reviewEveryMs!==void 0||options.watchHeartbeatMs!==void 0||options.loopRelaunchMs!==void 0||options.platform!==void 0||options.fenceAvailable!==void 0||options.flowFetch!==void 0||options.integrationIo!==void 0||options.shouldStop!==void 0||options.leadSeams!==void 0||options.waitSleep!==void 0||options.releaseIo!==void 0||options.installBin!==void 0||options.tempRoots!==void 0||options.filingSizer!==void 0||options.now!==void 0||options.folderLook!==void 0}function recordRunnerProcess(databaseFile,holder,role,pid){try{const started=processStart(pid);if(started===null)return!1;const file=runnerProcessFile(databaseFile,holder.runner.name),credential=credentialDigest(holder.credentialHash),current=readRunnerProcessRecord(file),same=current!==null&¤t.runner===holder.runner.name&¤t.registeredAt===holder.runner.registeredAt&¤t.credential===credential;if(role!=="up"&&(!same||current.signature!==sealRunnerProcessRecord(current,holder.credentialHash).signature))return!1;const kept=same?current.processes.filter(one=>one.role!==role||!processGone(one)):[],record={v:1,runner:holder.runner.name,host:holder.runner.host,registeredAt:holder.runner.registeredAt,credential,processes:[...kept.filter(one=>one.pid!==pid),{pid,role,started}]};return record.processes.length>64?!1:(writeRunnerProcessRecord(file,sealRunnerProcessRecord(record,holder.credentialHash)),!0)}catch{return!1}}function upRoleChildCommand(role){const source=import.meta.url.endsWith(".ts"),entry=fileURLToPath(new URL(source?"./up-role-child.ts":"./up-role-child.js",import.meta.url));return{file:process.execPath,argv:[...source?["--import",import.meta.resolve("tsx")]:[],entry,role]}}function startUpRole(args){const{role}=args;let resolveReady=()=>{};const ready=new Promise(resolve2=>resolveReady=resolve2),generations=new RoleGenerations;let stopping=!1,endedForGood=!1;const endForGood=detail=>{stopping||endedForGood||(endedForGood=!0,args.onEnded(detail,!1))};let failed=null,fatal=null,closedProblem=null,livePid=null;const receive=(raw,abort)=>{const message=roleMessage(raw,role);if(message!==null){if(message.type==="ready"){if(message.build!==args.build){fatal=`the ${role} is a different build (${message.build}) from this one (${args.build}) — restart Toolroll`,failed={reason:"start",detail:fatal},generations.refused(fatal),abort();return}livePid=message.pid;const again=!generations.ready();again||resolveReady({ok:!0,url:message.url??"",port:message.port,pid:message.pid}),args.onReady(message,again);return}if(message.type==="failed"){failed={reason:message.reason,detail:message.detail},generations.refused(message.detail);return}if(message.type==="fatal"){fatal=message.detail;return}if(message.type==="closed"){closedProblem=message.problem;return}message.type!=="alive"&&args.onMessage(message)}};if(!args.split){const channel=memoryChannel(role);channel.parent.onMessage(message=>receive(message,()=>channel.parent.stop(!1)));const done2=upRoleCommand(args.context,{start:args.start(1),port:channel.port}).catch(error=>(fatal=describe(error),EXIT.failed)).then(code=>(livePid=null,generations.wasReady()?endForGood(fatal??`the ${role} stopped (exit ${code})`):resolveReady({ok:!1,...failed??{reason:"start",detail:fatal??`the ${role} stopped while starting (exit ${code})`}}),{problem:closedProblem}));return{ready,done:done2,send:message=>channel.parent.send(message),stop:()=>{stopping=!0,channel.parent.stop(!1)},hardStop:()=>{channel.parent.stop(!0)},kill:()=>{stopping=!0,channel.parent.stop(!0)},pid:()=>livePid}}const controller=new AbortController;let child=null;const command=upRoleChildCommand(role);let heardAt=Date.now(),stoppingSince=null,liveBuilds=0,saidPaused=!1,saidWaiting=!1;const watchdog=args.watchdog===void 0?null:setInterval(()=>{const owned=child;if(stopping||controller.signal.aborted||owned===null||owned.exitCode!==null||owned.signalCode!==null||!generations.current())return;const now=Date.now(),silentMs=now-heardAt,silenceMs=args.watchdog.silenceMs??WORKER_SILENCE_MS,facts={silentMs,silenceMs,stoppingForMs:stoppingSince===null?null:now-stoppingSince,graceMs:args.watchdog.graceMs,deadlineMs:SHUTDOWN_DEADLINE_MS,liveBuilds,paused:!1};if(watchdogVerdict(facts)==="fine"){saidPaused=!1,saidWaiting=!1;return}try{facts.paused=args.watchdog.paused()}catch{facts.paused=!0}const verdict=watchdogVerdict(facts);if(verdict==="leave"){saidPaused||args.watchdog.say(`the ${role} isn't answering, but an update or restart is under way; leaving it to that`),saidPaused=!0;return}if(verdict==="wait"){saidWaiting||args.watchdog.say(`the ${role} is still stopping: ${liveBuilds===1?"a build hasn't":`${liveBuilds} builds haven't`} confirmed ${liveBuilds===1?"it":"they"} stopped; leaving it to finish`),saidWaiting=!0;return}verdict==="restart"&&(args.watchdog.say(silentMs<silenceMs?`the ${role}'s stop overran its deadline; stopping it and starting it again`:`the ${role} hasn't answered for ${Math.round(silentMs/1e3)}s; stopping it and starting it again`),stopProcessTree(owned)||owned.kill("SIGKILL"),heardAt=now)},WORKER_ALIVE_EVERY_MS);watchdog?.unref?.();const done=superviseController({file:command.file,argv:command.argv,signal:controller.signal,ipc:!0,shutdownMs:args.shutdownMs,label:envValue(process.env,"LOG_FORMAT")==="json"?"":`[${role}]`,onSpawn:(owned,generation)=>{child=owned,fatal=null,failed=null,generations.spawned(),heardAt=Date.now(),stoppingSince=null,owned.on("message",raw=>{heardAt=Date.now();const alive=roleMessage(raw,role);alive?.type==="alive"&&(stoppingSince=alive.stopping?stoppingSince??heardAt:null,liveBuilds=alive.liveBuilds),receive(raw,()=>controller.abort())}),owned.on("error",()=>{});let recorded=!1;try{recorded=owned.pid!==void 0&&(args.onSpawned?.(owned.pid)??!0)}catch{}if(!recorded){fatal="The worker process record could not be saved",failed={reason:"start",detail:fatal},generations.refused(fatal),owned.kill("SIGKILL"),controller.abort(),resolveReady({ok:!1,...failed});return}owned.send(args.start(generation),error=>{error!=null&&owned.kill("SIGTERM")})},onState:state=>{if(state.phase!=="backoff")return;child=null,livePid=null;const exit=state.exit?.signal??state.exit?.code??"unknown";if(stopping&&generations.wasReady())return;const verdict=generations.ended();if(verdict==="fail-start"){controller.abort(),resolveReady({ok:!1,...failed??{reason:"start",detail:fatal??`the ${role} stopped while starting (exit ${exit})`}});return}if(verdict==="end"){controller.abort(),endForGood(generations.refusedWith()??fatal??`the ${role} kept stopping before it was ready (exit ${exit})`);return}if(controller.signal.aborted){endForGood(fatal??`the ${role} stopped (exit ${exit})`);return}if(generations.struggling()){args.onEnded(`${fatal===null?"":`${fatal} — `}the ${role} is still restarting (${generations.notReady()} tries so far, exit ${exit})`,!0);return}args.onEnded(`${fatal===null?"":`${fatal} — `}the ${role} stopped unexpectedly (exit ${exit})`,!0)}}).catch(error=>{generations.wasReady()||resolveReady({ok:!1,reason:"start",detail:describe(error)})}).finally(()=>{watchdog!==null&&clearInterval(watchdog)}).then(()=>(generations.wasReady()?endForGood(generations.refusedWith()??fatal??`the ${role} stopped`):resolveReady({ok:!1,...failed??{reason:"start",detail:fatal??`the ${role} did not start`}}),{problem:closedProblem}));return{ready,done,send:message=>{const owned=child;if(owned!==null&&owned.connected)try{owned.send(message,()=>{})}catch{}},stop:()=>{stopping=!0,controller.abort()},hardStop:()=>{const owned=child;if(owned!==null&&owned.connected)try{owned.send({type:"hard-stop"},()=>{})}catch{}},kill:()=>{stopping=!0,controller.abort();const owned=child;owned!==null&&owned.exitCode===null&&owned.signalCode===null&&!stopProcessTree(owned)&&owned.kill("SIGKILL")},pid:()=>livePid}}export async function runUpRole(start,port){return runOperate("up",["--db",start.databaseFile,...start.containment===null?[]:["--containment",start.containment]],line=>port.send({type:"log",line}),{upRole:{start,port}})}async function upRoleCommand(context,host){const{start,port}=host;return start.build!==upBuildIdentity()?(port.send({type:"failed",reason:"start",detail:`this ${start.role} is a different build (${upBuildIdentity()}) from the \`up\` that started it (${start.build})`}),EXIT.refused):resolve(start.databaseFile)!==resolve(context.databaseFile)?(port.send({type:"failed",reason:"start",detail:`the ${start.role} opened a different database`}),EXIT.refused):start.role==="console"?runUpConsoleRole(context,start.config,port,start.build):runUpWorkerRole(context,start.config,port,start.build)}async function runUpConsoleRole(context,config,port,build2){const{store,clock}=context,progress=line=>port.send({type:"log",line}),activeRepos=new Set(config.repos);let instanceSecret=null,draining=!1;const keyEpoch=randomBytes(16).toString("hex");let console_;try{console_=await startConsole({keyEpoch,instanceSecret:()=>instanceSecret,draining:()=>draining,context,host:config.host,port:config.port,...config.allowedHosts===null?{}:{allowedHosts:config.allowedHosts},...config.publicUrl===null?{}:{publicUrl:config.publicUrl},localRunner:config.localRunner,poolRoot:config.poolRoot,repos:config.repos,currentRepos:()=>[...activeRepos],admittedRepos:()=>[...activeRepos],upConsole:!0,registryPath:config.registryPath,projectRoots:await(async()=>{const saved=await loadProjectRegistry(config.registryPath);return"error"in saved?config.projectRoots:saved.roots})(),...config.editor?{editorLinks:"vscode"}:{}})}catch(error){return port.send({type:"failed",reason:"port-busy",detail:describe(error)}),EXIT.refused}let codingClosed=!1;const closeCoding=()=>{codingClosed||(codingClosed=!0,console_.server.closeCoding().catch(()=>{}))};let resolveStopped=()=>{};const stopped=new Promise(resolveStop=>resolveStopped=resolveStop);port.onStop(()=>resolveStopped());const lifecycleComponent=consoleComponent(config.host,console_.port),lifecycleHolder=`${process.pid}:${randomUUID().slice(0,8)}`;try{reportLifecycle(store,lifecycleComponent,"started",lifecycleHolder,clock(),{pid:process.pid})}catch{}const lifecycleBeat=setInterval(()=>{try{beatLifecycle(store,lifecycleComponent,lifecycleHolder,clock())}catch{}},RUNNER_HEARTBEAT_MS);lifecycleBeat.unref?.(),port.onMessage(message=>{if(message.type==="repos"){activeRepos.clear();for(const repo of message.repos)activeRepos.add(repo)}else if(message.type==="stopping"){draining=!0;try{reportLifecycle(store,lifecycleComponent,"draining",lifecycleHolder,clock(),{drainUntil:new Date(clock().getTime()+6e4)})}catch{}closeCoding()}else if(message.type==="sign-in-link"){let link=null;try{link=consoleSignInLink(console_.server,config.startAuthority,message)}catch{link=null}port.send({type:"sign-in-link",id:message.id,link})}});let mintedSecret=null;const instanceSocket=await openInstanceSocket(context.databaseFile,{pid:process.pid,build:packageVersion(),database:context.databaseFile,port:console_.port},()=>mintedSecret,()=>console_.server.mintLocalLink());instanceSocket.ok?(mintedSecret=await claimInstance(store,context.databaseFile,{pid:process.pid,port:console_.port,build:packageVersion(),socket:instanceSocket.name,keyEpoch:console_.server.keyEpoch},clock()),instanceSecret=mintedSecret,mintedSecret===null&&progress("attach: another console is running on this database — `toolroll` in a repository opens that one")):progress(`attach: ${instanceSocket.problem} — \`toolroll\` in a repository won't find this console`),port.send({type:"ready",role:"console",build:build2,pid:process.pid,url:console_.url,port:console_.port}),await stopped,draining=!0,closeCoding(),clearInterval(lifecycleBeat),instanceSocket.ok&&instanceSocket.close(),mintedSecret!==null&&clearInstance(store,mintedSecret);let closeProblem=null;await new Promise(done=>console_.server.close(error=>{closeProblem=error==null?null:error.message,done()}));try{reportLifecycle(store,lifecycleComponent,"stopped",lifecycleHolder,clock())}catch{}return port.send({type:"closed",problem:closeProblem}),closeProblem===null?EXIT.ok:EXIT.failed}async function runUpWorkerRole(context,config,port,build2){const{store,clock}=context,progress=line=>port.send({type:"log",line}),runnerName=config.runner,runnerToken=config.token,pool=config.pool,registryPath=config.registryPath,pinnedRepos=new Set(config.pinnedRepos),gitRun=context.gitRunner??((file,args,opts)=>run(file,[...args],{...opts?.cwd===void 0?{}:{cwd:opts.cwd},timeoutMs:1e4})),proveRepo=async input=>(await upProveSaved(gitRun,input))?.root??null,activeRepos=new Set(config.repos),reportRepos=()=>port.send({type:"repos",repos:[...activeRepos]});let stopping=!1,fatal=null,graceTimer;const followControllers=[];let resolveStopped=()=>{};const stopped=new Promise(resolveStop=>resolveStopped=resolveStop),hardStop=()=>{const terminated=terminateLiveProviders();terminated>0&&progress(`Stopped ${terminated} running build(s). Their work is saved, and each resumes when the builder starts again.`)},loopHealth=new Map;let deadlineTimer;const stillWaitingOn=()=>{const named2=[...loopHealth.values()].map(read=>read()).filter(one=>one.cleanup!==null).map(one=>`${projectName(one.repo)}: ${one.cleanup}`);return named2.length===0?"the worker's own shutdown":named2.join(", ")},forceEnd=async()=>{const waiting=stillWaitingOn();progress(`Stopping is taking too long (still waiting on ${waiting}); stopping this worker's builds now`),await endAfterExitProof({hardStop,liveBuilds:liveProviderCount,say:progress,exit:port.exit,code:EXIT.failed,before:()=>port.send({type:"fatal",detail:`the worker's stop didn't finish (still waiting on ${waiting}); Toolroll is restarting it`})})},armDeadline=()=>{deadlineTimer===void 0&&(deadlineTimer=setTimeout(()=>{forceEnd()},config.stopGraceMs+SHUTDOWN_DEADLINE_MS),deadlineTimer.unref?.())},stop=()=>{if(stopping){hardStop();return}stopping=!0,armDeadline(),resolveStopped();for(const controller of followControllers)controller.abort();wakeHubFor(store,read=>briefly(store,read)).poke();const building=store.liveClaimCount(runnerName,clock());building>0&&progress(`Stopping: ${building} build(s) running. Waiting up to ${Math.round(config.stopGraceMs/1e3)}s for them to finish; any still running then is saved and resumes when the builder starts again.`),graceTimer=setTimeout(hardStop,config.stopGraceMs),graceTimer.unref?.()};port.onStop(hard=>{stopping||stop(),hard&&hardStop()});const loopFlagsFor=repo=>{const copy=new Map;return config.forMs!==null&©.set("for",String(config.forMs)),copy.set("runner",runnerName),copy.set("token",runnerToken),copy.set("repo",repo),copy.set("pool",pool),config.publicUrl!==null&©.set("public-url",config.publicUrl),copy},prefix=repo=>activeRepos.size>1?`[${projectName(repo)}] `:"",containmentDetail=config.verbose||!config.terminal;let containmentSaid=!1;const firstContainmentNotice=()=>{try{return noticeDueOnce(context.store,CONTAINMENT_NOTICE_FACT,clock())}catch{return!0}},containmentLines=effective=>{const notice=containmentNotice(effective);return notice!==null&&!containmentSaid&&(containmentDetail||firstContainmentNotice())&&progress(notice),containmentSaid=!0,containmentDetail||effective.refusal!==null?[`watch: ${describeContainment(effective)}`]:[]},loopResults=new Map,projectPasses=new ProjectPasses,releasedRepos=new Set,relaunches=new Map,relaunchAttempts=new Map,relaunchAbort=new AbortController;followControllers.push(relaunchAbort);const relaunchPause=ms=>new Promise(resolvePause=>{const timer=setTimeout(done,ms);function done(){clearTimeout(timer),relaunchAbort.signal.removeEventListener("abort",done),resolvePause()}relaunchAbort.signal.aborted?done():relaunchAbort.signal.addEventListener("abort",done,{once:!0})}),stoppedAt=new Map,stillTimers=new Map,noticed=write=>{try{briefly(store,write)}catch{}},builderBack=(repo,relaunching)=>{const at=stoppedAt.get(repo);stoppedAt.delete(repo);const timer=stillTimers.get(repo);timer!==void 0&&clearTimeout(timer),stillTimers.delete(repo),noticed(relaunching&&at!==void 0?()=>noteRestarted(store,{repo,stoppedAt:at,now:clock()}):()=>closeStillRestarting(store,repo,clock()))},scheduleRelaunch=(repo,detail)=>{if(relaunches.has(repo)||stopping)return;if(!stoppedAt.has(repo)){const at=clock();stoppedAt.set(repo,at);const timer=setTimeout(()=>{!stopping&&stoppedAt.get(repo)===at&¬iced(()=>noteStillRestarting(store,{repo,stoppedAt:at,now:clock()}))},STILL_RESTARTING_AFTER_MS);timer.unref?.(),stillTimers.set(repo,timer)}const attempt=relaunchAttempts.get(repo)??0;relaunchAttempts.set(repo,attempt+1);const delay=relaunchDelayMs(attempt,context.loopRelaunchMs);progress(`${prefix(repo)}this project's builder stopped (${detail}); Toolroll is restarting it in ${Math.max(1,Math.round(delay/1e3))}s`);const pending=(async()=>{await relaunchPause(delay);let waited=0,saidWaiting=!1;for(;;){if(stopping)return;if(releasedRepos.has(repo)){fatal=`${prefix(repo)}${detail}`,stop();return}if(!activeRepos.has(repo))return;let admission;try{admission=briefly(store,()=>relaunchAdmission(store,runnerName,repo,clock()))}catch(error){if(!isDatabaseBusy(error))throw error;await relaunchPause(relaunchDelayMs(waited++,context.loopRelaunchMs));continue}if(admission==="identity"){fatal=`the builder identity changed while restarting ${projectName(repo)}`,stop();return}if(admission==="gone"){loopResults.delete(repo),activeRepos.delete(repo),reportRepos(),progress(`project removed — ${projectName(repo)} is no longer built here`);return}if(admission==="go")break;saidWaiting||progress(`${prefix(repo)}still restarting: waiting for ${RELAUNCH_WAIT_WORDS[admission]}`),saidWaiting=!0,await relaunchPause(relaunchDelayMs(waited++,context.loopRelaunchMs))}loopResults.delete(repo),relaunches.delete(repo),await launchRepo(repo,!1,!1,!0)})().catch(error=>{fatal=`${prefix(repo)}the builder couldn't be restarted (${describe(error)})`,stop()}).finally(()=>{relaunches.get(repo)===pending&&relaunches.delete(repo)});relaunches.set(repo,pending)},launchRepo=async(repo,bind,drain=!1,relaunching=!1)=>{if(loopResults.has(repo)||stopping)return;let readyAt=null;if(drain&&releasedRepos.add(repo),bind){const bound=addRunnerReposAuthed(store,{name:runnerName,token:runnerToken,repos:[repo]},clock());if(!bound.ok){fatal=`the builder identity changed while adding ${repo} (${bound.reason})`,stop();return}activeRepos.add(repo),reportRepos(),store.listProjects().some(one=>one.path===repo)||store.upsertProject(repo,projectName(repo),clock())}let markReady=()=>{};const ready=new Promise(resolveReady=>markReady=resolveReady),loop=runWatchLoop({flags:loopFlagsFor(repo),context,runner:runnerName,token:runnerToken,repo,progress:line=>progress(`${prefix(repo)}${line}`),isStopping:()=>stopping||releasedRepos.has(repo),onFollowController:controller=>followControllers.push(controller),containmentLines,passes:projectPasses,serviceBridge:!0,health:read=>loopHealth.set(repo,read),leaseWaitMs:config.leaseWaitMs,...drain?{leaseWaitStopping:()=>stopping}:{},onReady:()=>{readyAt=Date.now(),markReady(),bind&&progress(`${prefix(repo)}builder connected — queued work can start`),relaunching&&progress(`${prefix(repo)}builder restarted automatically — queued work can start`),builderBack(repo,relaunching)}}).then(result=>({repo,result}),error=>({repo,result:{ok:!1,reason:"loop-failed",detail:describe(error),ticks:0,built:0,broke:0,busy:isDatabaseBusy(error)}}));loopResults.set(repo,loop),loop.then(({repo:endedRepo,result})=>{if(releasedRepos.has(endedRepo)&&!stopping&&!result.ok){fatal=`${prefix(endedRepo)}${result.detail}`,stop(),markReady();return}if(releasedRepos.has(endedRepo)&&!stopping){const unbound=removeRunnerRepoAuthed(store,{name:runnerName,token:runnerToken,repo:endedRepo},clock());unbound.ok||(fatal=`the builder identity changed while removing ${endedRepo} (${unbound.reason})`,stop()),loopResults.delete(endedRepo),releasedRepos.delete(endedRepo),progress(`project removed — ${projectName(endedRepo)} is no longer built here`),markReady();return}if(!result.ok&&!stopping){if(readyAt!==null&&Date.now()-readyAt>=LOOP_STABLE_MS&&relaunchAttempts.delete(endedRepo),loopEndRecovery(result,relaunching)==="relaunch"&&activeRepos.has(endedRepo)){scheduleRelaunch(endedRepo,result.detail),markReady();return}fatal=`${prefix(endedRepo)}${result.detail}`,stop()}markReady()}),await ready},named=new Set(config.repos),boundNow=new Set(store.getRunner(runnerName)?.runner.repos??[]),draining=[...new Set(predecessorWatches(store,runnerName,clock()).map(one=>one.repo))].filter(repo=>!named.has(repo)&&boundNow.has(repo));for(const repo of draining)progress(`${projectName(repo)} was being removed when the previous worker stopped: recovering its work first`);await Promise.all(draining.map(repo=>launchRepo(repo,!1,!0))),await Promise.all(config.repos.map(repo=>launchRepo(repo,!1)));const telegramController=new AbortController;followControllers.push(telegramController),stopping&&telegramController.abort();const telegramSupervisor=(async()=>{const pause=ms=>new Promise(resolvePause=>{const timer=setTimeout(done,ms);function done(){clearTimeout(timer),telegramController.signal.removeEventListener("abort",done),resolvePause()}telegramController.signal.aborted?done():telegramController.signal.addEventListener("abort",done,{once:!0})});for(;!stopping&&!telegramController.signal.aborted;){const follower=startTelegramFollower({context,publicUrl:config.publicUrl??void 0,signal:telegramController.signal,progress,label:"telegram:",died:{prefix:"",next:"starting it again"},owner:`service-${randomUUID()}`});if(follower!==null&&await follower,follower===null&&loadBotToken(process.env,context.telegramTokenFile)!==null)break;await pause(follower===null?2e3:5e3)}})(),dynamicCeiling=resolveCeiling(config.repos,config.projectRoots,path=>resolve(path)).ceiling,rejected=new Set,lineIdentities=projectIdentities(),admittedLines=new Map(Object.entries(config.repoLines??{})),deferred=upDeferredRetry(config.deferredRepos??[],input=>upProveSaved(gitRun,input)),deferredGenerations=config.deferredGenerations??{},reportDeferred=()=>port.send({type:"deferred",repos:deferred.list()}),registrySupervisor=(async()=>{const sleep=ms=>new Promise(resolveSleep=>setTimeout(resolveSleep,ms));for(;!stopping;){const loaded=await loadProjectRegistry(registryPath);if("error"in loaded){fatal=loaded.error,stop();break}deferred.keepOnly(loaded.repos)&&reportDeferred();const plain=loaded.repos.filter(one=>!deferred.has(one));await lineIdentities.refresh(plain);const saved=new Set(loaded.repos);let removed=!1;for(const repo of[...activeRepos]){const lines=admittedLines.get(repo)??[repo];stopping||pinnedRepos.has(repo)||saved.has(repo)||lines.some(line=>saved.has(line))||(activeRepos.delete(repo),removed=!0,releasedRepos.add(repo),loopResults.has(repo)||releasedRepos.delete(repo))}removed&&reportRepos();for(const candidate of loaded.repos){if(stopping)break;if(deferred.has(candidate)){await connectDeferred(candidate);continue}const canonical=lineIdentities.known(candidate);if(canonical===void 0||canonical!==null&&(activeRepos.has(canonical)||releasedRepos.has(canonical)))continue;const approvedAdditions=context.additionalProjectRepos?.()??[],admittedRepos=[...dynamicCeiling.repos,...approvedAdditions],admittedCeiling={repos:admittedRepos.length===0&&dynamicCeiling.roots.length===0?["/\0nothing-admitted"]:admittedRepos,roots:dynamicCeiling.roots,canon:path=>lineIdentities.known(path)??null};if(!(canonical!==null&&(await authorizedProject(admittedCeiling,canonical)||admissionRecorded(store,canonical))&&await proveRepo(canonical)===canonical)){rejected.has(candidate)||(rejected.add(candidate),progress(`project not connected — ${candidate} isn't a Git repository added with \`toolroll repos add\` or the console`));continue}rejected.delete(candidate),admittedLines.set(canonical,[...new Set([...admittedLines.get(canonical)??[],candidate])]),await launchRepo(canonical,!0)}stopping||await sleep(500)}})().catch(error=>{fatal=`the project registry stopped (${describe(error)})`,stop()});async function connectDeferred(candidate){const proved=await deferred.retry(candidate);if(proved===null||stopping)return;if(proved.line!==candidate||proved.root!==candidate){deferred.revoke(candidate),reportDeferred(),progress(proved.root!==proved.line?`saved project not connected — ${candidate} came back as part of ${proved.root}; add it again to connect it`:`saved project not connected — ${candidate} now leads to ${proved.line}; add it again to connect it`);return}const root=candidate;if(activeRepos.has(root)||releasedRepos.has(root)){deferred.revoke(candidate),reportDeferred();return}let launching=null,removedSince=!1;if(await updateProjectRegistry(registryPath,current=>{if(stopping||!deferred.has(candidate))return current;const count=registryRemovals(registryPath)?.[candidate]??(registryRemovals(registryPath)===null?-2:0);return!current.repos.includes(candidate)||count!==deferredGenerations[candidate]?(deferred.revoke(candidate),removedSince=!0,current):(deferred.revoke(candidate),admittedLines.set(root,[candidate]),launching=launchRepo(root,!0),current)}),removedSince){reportDeferred(),progress(`saved project not connected — ${candidate} was removed while it was away; add it again to connect it`);return}launching!==null&&(reportDeferred(),progress(`saved project is back — connecting ${root}`),await launching)}let readinessTimer;if(context.agentRunner===void 0){let observing=!1;const observeReadiness=()=>{observing||stopping||(observing=!0,observeProviderReadiness((file,args,options)=>run(file,args,{timeoutMs:options?.timeoutMs??5e3,...options?.omitEnv===void 0?{}:{omitEnv:options.omitEnv}}),process.env,PROVIDER_IDS,provider=>store.acpAttestationFor(provider,runnerName)).then(observed=>{stopping||reportProviderReadinessAuthed(store,{name:runnerName,token:runnerToken,observations:observed},clock())}).catch(()=>{}).finally(()=>{observing=!1}))};observeReadiness(),readinessTimer=setInterval(observeReadiness,12e4),readinessTimer.unref?.()}try{notifyVersionLive(context.store,dirname(context.databaseFile),PACKAGE_VERSION,clock())}catch{}recordRunnerVersion(dirname(context.databaseFile),runnerName,PACKAGE_VERSION,clock());const stopLiveBackups=context.agentRunner===void 0?startLiveBackups(store,context.databaseFile,()=>[...new Set([...activeRepos,...store.knownRepos(),pool])]):null;fatal===null&&!stopping&&port.send({type:"ready",role:"worker",build:build2,pid:process.pid,url:null,port:null});const cleanupSince=new Map,aliveTimer=setInterval(()=>{const repos=[...loopHealth.entries()].filter(([repo])=>loopResults.has(repo)).map(([,read])=>read());if(port.send({type:"alive",stopping,repos,liveBuilds:liveProviderCount()}),!stopping)for(const one of repos){if(one.cleanup===null||one.cleanup==="its builds"){cleanupSince.delete(one.repo);continue}const since=cleanupSince.get(one.repo);if(since===void 0||since.stage!==one.cleanup){cleanupSince.set(one.repo,{stage:one.cleanup,at:Date.now()});continue}if(!(Date.now()-since.at<config.stopGraceMs+SHUTDOWN_DEADLINE_MS)){fatal=`${prefix(one.repo)}its loop stopped but never finished stopping (still waiting on ${one.cleanup})`,stop();return}}},WORKER_ALIVE_EVERY_MS);return aliveTimer.unref?.(),await stopped,readinessTimer!==void 0&&clearInterval(readinessTimer),await registrySupervisor,await Promise.all(relaunches.values()),await Promise.all(loopResults.values()),await stopLiveBackups?.(),await new Promise(done=>{const timer=setTimeout(done,TELEGRAM_STOP_WAIT_MS),finish=()=>{clearTimeout(timer),done()};telegramSupervisor.then(finish,finish)}),graceTimer!==void 0&&clearTimeout(graceTimer),deadlineTimer!==void 0&&clearTimeout(deadlineTimer),clearInterval(aliveTimer),fatal!==null?(port.send({type:"fatal",detail:fatal}),EXIT.failed):EXIT.ok}export async function refreshGithubNightlies(store,now,reads){return githubNightlyRepos(store).length===0?0:readGithubNightlies(store,{gh:reads??githubReads(releaseExec,releaseTools().gh,{retry:!0}),now})}export async function evalsCommand(positional,flags,context){const{write,json}=context,{admitEvalCampaign,campaignSpending,EVALS_ROOT,installedBuildDigest,loadEvalSet,planCampaign,recoverEvalCampaigns,runEvalCampaign}=await import("./evals.js"),{inEvalWorld}=await import("./eval-gate.js"),{evalCliEntry,runEvalWorld}=await import("./eval-world.js"),action=positional[0],command=`evals${action===void 0?"":` ${action}`}`,usage="Use: toolroll evals run [--diagnostic] [--case <ids>] [--k <n>] --as <you> --token <password> | toolroll evals cases | toolroll evals recover [--abandon <campaign> --as <you> --token <password>]";if(action==="recover"&&flags.has("abandon"))return evalsAbandonCommand(flags,context);if(action==="recover"){const recovered=recoverEvalCampaigns(context.store,context.clock());return succeed(write,json,command,{campaigns:recovered},()=>recovered.length===0?["No campaign is running."]:recovered.map(one=>`${one.id}: ${one.recovered?"recovered":"left running"} (${one.why})`))}if(action==="cases"){const set2=loadEvalSet();if(!set2.ok)return fail(write,json,command,"unreadable",set2.problem,EXIT.failed);const cases2=set2.cases.map(one=>({id:one.id,kind:one.kind,version:one.version,pin:one.pin,validatedBy:one.validatedBy,draft:one.validatedBy===null}));return succeed(write,json,command,{manifestDigest:set2.manifestDigest,cases:cases2},()=>cases2.map(one=>`${one.id} (${one.kind}) ${one.version.slice(0,12)} on ${one.pin.model}: ${one.draft?"draft, awaiting a person's validation":`validated by ${one.validatedBy}`}`))}if(action==="attempt"){if(!inEvalWorld())return fail(write,json,command,"refused","An eval attempt runs only from its campaign's runner.",EXIT.refused);const[,campaign,caseId,n]=positional,world=text(flags,"world");if(campaign===void 0||caseId===void 0||n===void 0||!/^[1-9][0-9]?$/.test(n)||world===void 0)return fail(write,json,command,"usage","Use: toolroll evals attempt <campaign> <case> <n> --world <dir> --db <world>/toolroll/orders.db",EXIT.usage);let worldDir;try{worldDir=realpathSync(world)}catch{return fail(write,json,command,"refused","The world's folder can't be read.",EXIT.refused)}if(resolve(context.databaseFile)!==join(worldDir,"toolroll","orders.db"))return fail(write,json,command,"refused","An eval attempt runs only on its world's own database.",EXIT.refused);const set2=loadEvalSet(),one=set2.ok?set2.cases.find(item=>item.id===caseId):void 0;if(one===void 0)return fail(write,json,command,"refused",set2.ok?`No case is named ${caseId}.`:set2.problem,EXIT.refused);const deny=(text(flags,"deny")??"").split(",").filter(path=>path!==""&&isAbsolute(path)),report=await runEvalWorld(one,{worldDir,databaseFile:context.databaseFile,deny,timeoutMs:one.timeoutMinutes*6e4});return succeed(write,json,command,{...report},()=>[JSON.stringify(report)])}if(action!=="run"||positional.length!==1)return fail(write,json,command,"usage",usage,EXIT.usage);if(inEvalWorld())return fail(write,json,command,"refused","An eval world doesn't start campaigns of its own.",EXIT.refused);if(machineActing()||process.env.TOOLROLL_LEAD_TOKEN!==void 0)return fail(write,json,command,"person-only","Only a person starts an eval campaign: it spends money.",EXIT.refused);const k=text(flags,"k"),cases=text(flags,"case"),set=loadEvalSet();if(!set.ok)return fail(write,json,command,"unreadable",set.problem,EXIT.failed);const planned=planCampaign(set,{...cases===void 0?{}:{cases:cases.split(",").filter(Boolean)},...k===void 0?{}:{k:Number(k)},diagnostic:flag(flags,"diagnostic")});if(!planned.ok)return fail(write,json,command,"refused",planned.problem,EXIT.refused);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,command,"usage","An eval campaign is started with your password: add --as <you> --token <password>.",EXIT.usage);const{plan}=planned,buildDigest=()=>installedBuildDigest(PACKAGE_VERSION),sealed={cases:plan.cases.map(one=>({id:one.id,version:one.version,pin:one.pin,maxDispatches:one.maxDispatches})),k:plan.k,baseline:null,evals:EVALS_ROOT};recoverEvalCampaigns(context.store,context.clock());const admitted=admitEvalCampaign(context.store,{kind:"eval",canonical:plan.canonical,manifestDigest:set.manifestDigest,buildDigest:buildDigest(),version:PACKAGE_VERSION,k:plan.k,sealed,as:acting.name,token:acting.token,now:context.clock()});if(!admitted.ok)return fail(write,json,command,admitted.reason,admitted.message,EXIT.refused);const stateDir=dirname(context.databaseFile),entry=evalCliEntry(),keep=["PATH","HOME","USER","LOGNAME","LANG","SHELL","TMPDIR"],ended=await runEvalCampaign(context.store,admitted.id,plan.cases,{workRoot:join(dirname(stateDir),"toolroll-eval-worlds",admitted.id),buildDigest,keepWorlds:flag(flags,"keep"),now:context.clock,command:input=>({file:entry.file,args:[...entry.args,"evals","attempt",input.campaign,input.caseId,String(input.n),"--world",input.worldDir,"--deny",stateDir,"--db",input.databaseFile,"--json"],env:{...Object.fromEntries(keep.flatMap(name=>process.env[name]===void 0?[]:[[name,process.env[name]]])),XDG_CONFIG_HOME:join(input.worldDir,"config")}})}),rows=context.store.handle.prepare("SELECT case_id, n, replaces, outcome, error_why, api_microusd, subscription_microusd, usage_unknown FROM eval_attempt WHERE campaign = ? ORDER BY case_id, n, replaces").all(admitted.id),nullable=value=>value==null?null:Number(value),attempts=rows.map(row=>({case:String(row.case_id),n:Number(row.n),replaces:Number(row.replaces),outcome:row.outcome===null?null:String(row.outcome),why:row.error_why===null?null:String(row.error_why),apiMicrousd:nullable(row.api_microusd),subscriptionMicrousd:nullable(row.subscription_microusd),usageUnknown:Number(row.usage_unknown)===1})),spent=campaignSpending(context.store,admitted.id),dollars=(micro,unknown)=>micro===null?`unknown (${unknown} attempt${unknown===1?"":"s"} with unknown spending)`:`$${(micro/1e6).toFixed(2)}`;return succeed(write,json,command,{campaign:admitted.id,canonical:plan.canonical,state:ended.state,why:ended.why,attempts,spending:spent},()=>[`Campaign ${admitted.id} (${plan.canonical?"canonical":"diagnostic"}) is ${ended.state}${ended.why===null?"":`: ${ended.why}`}.`,...attempts.map(one=>`${one.case} #${one.n}${one.replaces===0?"":" (replacement)"}: ${one.outcome??"not finished"}${one.why===null?"":` — ${one.why}`}`),`API dollars: ${dollars(spent.apiMicrousd,spent.unknownAttempts)}. Subscription usage, not billed: ${dollars(spent.subscriptionMicrousd,spent.unknownAttempts)}.`])}async function evalsAbandonCommand(flags,context){const{write,json}=context,command="evals recover",{abandonEvalCampaign}=await import("./evals.js"),{inEvalWorld}=await import("./eval-gate.js"),id=text(flags,"abandon");if(id===void 0||!/^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/.test(id))return fail(write,json,command,"usage","Use: toolroll evals recover --abandon <campaign> --as <you> --token <password>",EXIT.usage);if(inEvalWorld()||machineActing()||process.env.TOOLROLL_LEAD_TOKEN!==void 0)return fail(write,json,command,"person-only","Only a person abandons an eval campaign.",EXIT.refused);const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,command,"usage","A campaign is abandoned with your password: add --as <you> --token <password>.",EXIT.usage);const ended=abandonEvalCampaign(context.store,{id,as:acting.name,token:acting.token,now:context.clock()});return ended.ok?succeed(write,json,command,{campaign:id,state:"incomplete",attempts:ended.attempts,spending:"unknown"},()=>[`Campaign ${id} ended incomplete. ${ended.attempts} unfinished attempt${ended.attempts===1?"":"s"} recorded as errors; what it spent is unknown. Nothing was stopped: check for its processes yourself.`]):fail(write,json,command,ended.reason,ended.message,EXIT.refused)}export function upDeferredRetry(inputs,prove,everyMs=5e3,now=Date.now){const nextAt=new Map(inputs.map(input=>[input,now()+everyMs]));return{has:input=>nextAt.has(input),list:()=>[...nextAt.keys()],retry:async input=>{const due=nextAt.get(input);return due===void 0||now()<due?null:(nextAt.set(input,now()+everyMs),prove(input))},revoke:input=>{nextAt.delete(input)},keepOnly:saved=>{const keep=new Set(saved);let changed=!1;for(const input of[...nextAt.keys()])keep.has(input)||(nextAt.delete(input),changed=!0);return changed}}}export async function upProveSaved(gitRun,input,look={}){const top=await gitRun("git",["rev-parse","--show-toplevel"],{cwd:resolve(input)});if(top.code!==0)return null;const answered=await lookIdentities([resolve(input),top.stdout.trim()],look);if(!answered.ok)return null;const line=answered.value.get(resolve(input))??null,root=answered.value.get(top.stdout.trim())??null;return line===null||root===null?null:{line,root}}export function upNarrowDeferred(held,reported){const kept=new Set(reported);return held.filter(one=>kept.has(one))}export function consoleIdentitiesInBackground(identities,paths){identities.refresh(paths).catch(()=>!1)}export function writeModelRow(store,proved,scope,knownProject2,slot,to,now,extra=[]){const followRepair=slot!==null&&to!==null&&slot.phase==="build"&&(slot.tier==="routine"||slot.tier==="strong");return applyModelChoices(store,{scope,change:slot===null?[]:[{slot,to}],expected:null,strict:!1,knownProject:knownProject2,extra,followRepair},{...proved,live:()=>!0},now)}function refuseMachineTidy(context,command,method){return machineActing()||process.env.TOOLROLL_LEAD_TOKEN!==void 0||method!==void 0&&!personProof(method)?fail(context.write,context.json,command,"person-only","Only a person puts tasks away or restores them. Use the console or your own login.",EXIT.refused):null}async function archiveTasksCommand(positional,flags,context){const{store,write,json,clock}=context,command="task archive",ids=[...new Set(positional)];if(ids.length===0||ids.length>100)return fail(write,json,command,"usage","`toolroll task archive <id...> [--reason <why>] --as <you> --token <t>` — 1 to 100 tasks",EXIT.usage);const machine=refuseMachineTidy(context,command);if(machine!==null)return machine;const demo=refuseDemo(context,command);if(demo!==null)return demo;const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token,firstVisibleRepo(store,acting.name,ids));if(acting===null||!verified?.ok)return refuseApprover(context,command,verified,"putting a task away takes `--as <you> --token <t>` — it is recorded against your name",ids[0]);const personal=refuseMachineTidy(context,command,verified.method);if(personal!==null)return personal;const reason=text(flags,"reason")??"Put away by hand",archived=[],refused=[];for(const id of ids){const ref=store.lookupRef(id);if(ref===null||store.getTask(id)===null||!store.accountCanAccess(acting.name,ref.repo)){refused.push({id,reason:"unknown-task",message:`No task ${id}.`});continue}const done=archiveTaskFamily(store,id,{by:acting.name,byKind:"person",rule:null,reason},clock(),{guard:refs=>approverStandsNow(store,acting.name,familyRepoOf(store,refs))});done.ok?archived.push({id,versions:done.refs.length}):refused.push({id,reason:done.reason,message:done.message})}const lines=()=>[...archived.map(one=>`Put away ${one.id}${one.versions>1?` (${one.versions} versions)`:""}.`),...refused.map(one=>`Not put away: ${one.message}`),...archived.length===0?[]:[`Restore with \`toolroll task restore ${archived.map(one=>one.id).join(" ")}\`.`]];return refused.length===0?succeed(write,json,command,{archived,refused},lines):json?fail(write,json,command,refused[0].reason,refused[0].message,EXIT.refused,{archived,refused}):(write(lines().join(`
|
|
506
506
|
`)),EXIT.refused)}async function restoreTasksCommand(positional,flags,context){const{store,write,json,clock}=context,command="task restore",ids=[...new Set(positional)];if(ids.length===0||ids.length>100)return fail(write,json,command,"usage","`toolroll task restore <id...> --as <you> --token <t>` — 1 to 100 tasks",EXIT.usage);const machine=refuseMachineTidy(context,command);if(machine!==null)return machine;const demo=refuseDemo(context,command);if(demo!==null)return demo;const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token,firstVisibleRepo(store,acting.name,ids));if(acting===null||!verified?.ok)return refuseApprover(context,command,verified,"restoring takes `--as <you> --token <t>` — it is recorded against your name",ids[0]);const personal=refuseMachineTidy(context,command,verified.method);if(personal!==null)return personal;const restored=[],refused=[];for(const id of ids){const ref=store.lookupRef(id);if(ref===null||store.getTask(id)===null||!store.accountCanAccess(acting.name,ref.repo)){refused.push({id,reason:"unknown-task",message:`No task ${id}.`});continue}const done=restoreTaskFamily(store,id,acting.name,clock(),refs=>approverStandsNow(store,acting.name,familyRepoOf(store,refs)));done.ok?restored.push(id):refused.push({id,reason:done.reason,message:done.message})}const lines=()=>[...restored.map(id=>`Restored ${id}.`),...refused.map(one=>`Not restored: ${one.message}`)];return refused.length===0?succeed(write,json,command,{restored,refused},lines):json?fail(write,json,command,refused[0].reason,refused[0].message,EXIT.refused,{restored,refused}):(write(lines().join(`
|
|
507
507
|
`)),EXIT.refused)}async function tidyTasksCommand(positional,flags,context){const{store,write,json,clock}=context,command="task tidy",preview=flag(flags,"preview"),apply=flag(flags,"apply"),days=tidyDays(text(flags,"days")),digest=text(flags,"digest"),except=(text(flags,"except")??"").split(",").map(one=>one.trim()).filter(one=>one!==""),usage="`toolroll task tidy --preview [--days N]`, then `toolroll task tidy --apply --digest <d> [--days N] [--except <id,...>]`";if(positional.length>0||preview===apply||days===null||preview&&(digest!==void 0||except.length>0)||apply&&digest===void 0)return fail(write,json,command,"usage",usage,EXIT.usage);const releases=releaseFactsFor(context.databaseFile),previewAs=text(flags,"as")??readLoginFile(savedLoginFile(dirname(context.databaseFile)))?.name,daysArg=`${days===TIDY_DEFAULT_DAYS?"":` --days ${days}`}${previewAs===void 0?"":` --as ${previewAs}`}`,lens=context.principal?.lens??null,access=previewAs!==void 0?withinLens(accessOf(store,previewAs),lens):{principal:"operator",repos:lens,includeUnplaced:lens===null};if(preview){const items=tidyPreview(store,clock(),{releases,days,access}),shown=tidyDigest(items,days),groups=tidyGroups(items,days),next=`toolroll task tidy --apply --digest ${shown}${daysArg}`;return succeed(write,json,command,{preview:!0,days,digest:shown,count:items.length,groups,next:items.length===0?null:next,...releases.problem===null?{}:{releasesSkipped:releases.problem}},()=>items.length===0?["Nothing to put away."]:[`Put away old tasks: ${items.length} task${items.length===1?"":"s"}.`,...groups.flatMap(group=>["",`${group.label} (${group.items.length})`,...group.items.map(one=>` ${one.taskId} ${one.reason}${one.members.length>1?` (${one.members.length} versions)`:""}`)]),...releases.problem===null?[]:["",`Release tasks were left out: ${releases.problem}.`],"",`To put these away, run: ${next}`,"Leave some out with --except <id,...>.",...previewAs===void 0?["Limited to some projects? Preview with --as <you> so the list is yours."]:[]])}const machine=refuseMachineTidy(context,command);if(machine!==null)return machine;const demo=refuseDemo(context,command);if(demo!==null)return demo;const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token,firstVisibleRepo(store,acting.name,[]));if(acting===null||!verified?.ok)return refuseApprover(context,command,verified,"putting tasks away takes `--as <you> --token <t>` — it is recorded against your name",void 0);const personal=refuseMachineTidy(context,command,verified.method);if(personal!==null)return personal;const mine=withinLens(accessOf(store,acting.name),lens),shownItems=tidyPreview(store,clock(),{releases,days,access:mine}),only=except.length===0?null:shownItems.map(one=>one.taskId).filter(id=>!except.includes(id));if(except.some(id=>!shownItems.some(one=>one.taskId===id)))return fail(write,json,command,"outside","--except names a task that isn't in the list. Check it again with --preview.",EXIT.refused);const done=applyTidy(store,clock(),{by:acting.name,days,digest,only,releases,access:mine});if(!done.ok){const again=`toolroll task tidy --apply --digest ${done.digest}${daysArg}`;return fail(write,json,command,done.reason,done.reason==="changed"?`${done.message} Look again with \`toolroll task tidy --preview${daysArg}\`.`:done.message,EXIT.refused,{digest:done.digest,count:done.items.length,...done.reason==="changed"?{next:done.items.length===0?null:again}:{}})}return succeed(write,json,command,{archived:done.archived.map(one=>({id:one.taskId,rule:one.rule,reason:one.reason})),skipped:done.skipped},()=>[`Put away ${done.archived.length} task${done.archived.length===1?"":"s"}.`,...done.skipped.map(one=>`Not put away: ${one.message}`),"Find them with `toolroll task list --view archived`; bring one back with `toolroll task restore <id>`."])}function firstVisibleRepo(store,name,ids){for(const id of ids){const repo=store.lookupRef(id)?.repo??null;if(repo!==null&&store.accountCanAccess(name,repo))return repo}return store.accountCanAccess(name,null)?null:store.knownRepos().find(repo=>store.accountCanAccess(name,repo))??null}const SHIP_CHECK_WORDS={queued:"queued",running:"running",passed:"passed",failed:"failed",skipped:"skipped",cancelled:"cancelled",neutral:"neutral"};function taskShipCommand(positional,context){const{store,write,json}=context,command="task ship",id=positional[0];if(id===void 0||positional.length>1)return fail(write,json,command,"usage","`toolroll task ship <task>`",EXIT.usage);const ref=store.lookupRef(id),lens=context.principal?.lens??null;if(ref===null||store.getTask(id)===null||lens!==null&&(ref.repo===null||!lens.includes(ref.repo)))return fail(write,json,command,"unknown-task",`no task \`${id}\``,EXIT.refused);const ship=shipChecksForTask(store,id);if(ship===null)return fail(write,json,command,"no-pull-request",`${id} has no pull request with observed checks yet`,EXIT.refused);const now=(context.clock??(()=>context.now))(),checks=ship.checks.map(one=>({...one,seconds:elapsedSeconds(one.startedAt,one.completedAt,now)})),passed=checks.filter(one=>one.state==="passed").length,overall=ship.observed==="failing"?"failing":ship.observed==="passing"?"passing":ship.observed==="running"?"running":"not read";return succeed(write,json,command,{task:id,pullRequest:ship.prNumber,githubRepo:ship.githubRepo,head:ship.headSha,observedAt:ship.observedAt,status:ship.observed,checks},()=>[`Pull request #${ship.prNumber} (${ship.githubRepo}) at ${ship.headSha.slice(0,7)}: checks ${overall} · ${passed} of ${checks.length} passed`,...checks.map(one=>` ${(one.workflow===null?one.name:`${one.workflow} / ${one.name}`).padEnd(32)} ${(SHIP_CHECK_WORDS[one.state]??one.state).padEnd(9)} ${one.seconds===null?"–":dur(one.seconds)}`)])}function upLaptopProjectsRoot(home){const folder=join(home,"Projects");try{mkdirSync(folder,{recursive:!0,mode:448})}catch{return null}return canonicalProject(folder)}function upLaptopLocalMode(context,asFlag,caller){const fence=context.upSeams?.fenceAvailable??defaultFenceAvailable,owner=asFlag??process.env.USER??process.env.USERNAME??"operator";return initLocalModeForPerson(context.store,caller,{owner,fence,now:context.clock()})}export function upLinkRequest(authority,account){return authority==="local"?{kind:"local"}:authority==="full"&&account!==null?{kind:"full",account}:null}export function consoleSignInLink(server,startAuthority,message){return message.kind==="local"?startAuthority==="local"?server.mintLocalLink():null:startAuthority==="full"?server.mintSignInLink(message.account):null}function localOwnerCommand(store,command,positional,flags){const binding=localOwnerBinding(store);if(binding===null)return{ok:!1,message:"Local mode is off. Sign in with your password in the browser."};const act=localOwnerRowAct(command,positional,flags);return act===null?{ok:!1,message:localOwnerRefusal(store.accountOf(binding.account)?.passwordSet===!0,"/").message}:{ok:!0,principal:{account:binding.account,localGeneration:binding.localGeneration,accountGeneration:binding.accountGeneration,transport:"terminal",act,sessionHash:null,request:null}}}function localOwnerRowAct(command,positional,flags){if(["as","token","token-file","token-env"].some(name=>flags.has(name)))return null;const row=remoteRowOf(command,positional);if(row?.invocation==="repos add"&&flags.has("remote"))return null;const mark=row===null?void 0:LOCAL_POLICY.get(row.invocation);return mark===void 0||mark.local!=="allow"?null:mark.act}function laptopSeamsOf(context){return{terminal:!context.json&&process.stdin.isTTY===!0&&process.stdout.isTTY===!0&&!underAgent(process.env),confirm:promptConfirm,...context.laptopSeams}}async function backgroundCommand(positional,flags,context){const{write,json}=context,[action="show",...rest]=positional,command=`background ${action}`;if(!["on","off","show"].includes(action)||rest.length>0)return fail(write,json,"background","usage","Use `toolroll background on|off|show [--port <n>]`.",EXIT.usage);for(const name of flags.keys())if(!["db","json","port"].includes(name))return fail(write,json,command,"usage",`--${name} is not a background option.`,EXIT.usage);if(context.principal!==void 0)return fail(write,json,command,"not-remote","The background service is this computer's own; run it there.",EXIT.refused);const portGiven=text(flags,"port"),port=portGiven===void 0?null:Number(portGiven);if(port!==null&&(!Number.isInteger(port)||port<1||port>=65536))return fail(write,json,command,"usage","--port is a whole number under 65536",EXIT.usage);const seams=laptopSeamsOf(context);if(action==="show"){const shown=await backgroundShow(context.store,context.databaseFile,port,seams);if(!shown.ok)return fail(write,json,command,shown.reason,shown.message,EXIT.refused);const show=shown.show,state=show.installed==="absent"?"off":show.loaded?"on":"installed, not running";return succeed(write,json,command,{...show,background:show.installed==="absent"?"off":"on"},()=>[`Background: ${state}${show.installed==="different"?" (set up for a different version or port; `toolroll background on` updates it)":""}`,show.running===null?"Toolroll isn't running.":`Toolroll is running at ${show.running.url}`,...show.conflicts.map(one=>`Also here: ${one.reason}`)])}const demo=refuseDemo(context,command);if(demo!==null)return demo;if(action==="off"){const off=await backgroundOff(context.store,context.databaseFile,seams);return off.ok?succeed(write,json,command,off,()=>[off.action==="already-off"?"Toolroll wasn't set to run in the background.":"Toolroll no longer runs in the background. Start it with `toolroll` when you need it."]):fail(write,json,command,off.reason,off.message,off.reason==="supervisor"||off.reason==="still-running"?EXIT.failed:EXIT.refused)}const on=await backgroundOn(context.store,context.databaseFile,port,seams);if(on.ok&&recordBuilderWish(context.store,"running","background on",packageVersion(),context.clock()),!on.ok){const code=["agent","conflict","declined","running-elsewhere","unsupported","console-unproven","invalid-unit","unreadable"].includes(on.reason)?EXIT.refused:EXIT.failed;if(json)return write(envelopeJson({ok:!1,command,reason:on.reason,message:on.message,...on.rolledBack===void 0?{}:{rolledBack:on.rolledBack}})),code;write(`✗ ${on.message}.`);for(const line of on.rolledBack??[])write(` ${line}`);return code}return succeed(write,json,command,on,()=>[on.action==="unchanged"?`Toolroll already runs in the background at ${on.url}.`:`Toolroll now runs in the background at ${on.url}. It starts when you log in.`])}async function stopCommand(positional,flags,context){const{write,json}=context,command="stop";if(positional.length>0)return fail(write,json,command,"usage","Use `toolroll stop`.",EXIT.usage);for(const name of flags.keys())if(!["db","json"].includes(name))return fail(write,json,command,"usage",`--${name} is not a stop option.`,EXIT.usage);if(context.principal!==void 0)return fail(write,json,command,"not-remote","Stopping Toolroll is done on its own computer.",EXIT.refused);const stopped=await laptopStop(context.store,context.databaseFile,laptopSeamsOf(context));return stopped.ok?succeed(write,json,command,stopped,()=>[stopped.action==="not-running"?"Toolroll isn't running.":stopped.action==="service-stopped"?"Toolroll stopped. It starts again when you log in — run `toolroll background off` to stop that.":"Toolroll stopped."]):fail(write,json,command,stopped.reason,stopped.message,stopped.reason==="still-running"||stopped.reason==="supervisor"?EXIT.failed:EXIT.refused)}function personAtTerminal(context){return!context.json&&(context.easySeams?.terminal??(process.stdin.isTTY===!0&&process.stdout.isTTY===!0&&!underAgent(process.env)))}async function openCommand(positional,flags,context){const{write,json}=context,command="open";if(positional.length>0)return fail(write,json,command,"usage","Use `toolroll open [--web]`.",EXIT.usage);for(const name of flags.keys())if(!["db","json","web"].includes(name))return fail(write,json,command,"usage",`--${name} is not an open option.`,EXIT.usage);if(context.principal!==void 0)return fail(write,json,command,"not-remote","Toolroll opens on its own computer.",EXIT.refused);if(!personAtTerminal(context))return fail(write,json,command,"not-a-terminal","Run `toolroll open` yourself at a terminal: it opens Toolroll here, signed in.",EXIT.refused);const easy=await import("./easy-start.js"),seams=easy.defaultEasyStartSeams({databaseFile:context.databaseFile,write,build:packageVersion(),admit:async()=>EXIT.ok});return easy.runEasyStart("open",{web:flags.has("web"),projectRoot:null},{...seams,...context.easySeams?.seams})}async function welcomeCommand(positional,flags,context){const{write,json}=context,command="welcome";if(positional[0]==="sample")return welcomeSampleCommand(positional.slice(1),flags,context);if(positional.length>0)return fail(write,json,command,"usage","Use `toolroll welcome [--json]`, or `toolroll welcome sample`.",EXIT.usage);for(const name of flags.keys())if(!["db","json"].includes(name))return fail(write,json,command,"usage",`--${name} is not a welcome option.`,EXIT.usage);const{welcomeHere,welcomeLines,welcomeStepLines,WELCOME_STEPS,sampleOffered}=await import("./welcome-facts.js"),read=async()=>(await welcomeHere(context.store,context.databaseFile,context.clock(),context.easySeams?.check===void 0?{}:{check:context.easySeams.check})).model;let model=await read();const shellMayAdd=()=>{const mode=localModeOf(context.store);return mode?.enabled===!0&&context.store.accountOf(mode.owner)?.passwordSet!==!0},offer=()=>sampleOffered(model,shellMayAdd(),context.store.isDemo())?"command":null;if(json||!personAtTerminal(context)||localOwnerRequested())return succeed(write,json,command,{...model},()=>welcomeLines(model,offer()));const askNow=context.easySeams?.ask??ask;write(model.left===0?"Setup is done.":`Welcome to Toolroll. ${model.left} ${model.left===1?"step":"steps"} to your first result.`);for(const key of WELCOME_STEPS)for(;;){write("");for(const line of welcomeStepLines(model,key,offer()))write(line);if(model[key].done)break;const said=(await askNow("Press Enter once it's done, s to skip, q to stop: ")).trim().toLowerCase();if(said==="q")return EXIT.ok;if(said==="s")break;model=await read()}return write(""),write(model.left===0?"You're set. Run `toolroll` to open Toolroll.":"Run `toolroll` to open Toolroll; the steps left are there too."),EXIT.ok}async function passwordCommand(positional,flags,context){const{write,json,store}=context,[action,...rest]=positional,command=action===void 0?"password":`password ${action}`;if(action==="reset")return passwordResetCommand(rest,flags,context);if(action!=="set"||rest.length>0)return fail(write,json,command,"usage","Use `toolroll password set` (a first password) or `toolroll password reset` (a forgotten one).",EXIT.usage);for(const name of flags.keys())if(!["db","json"].includes(name))return fail(write,json,command,"usage",`--${name} is not a password set option: the password is only ever typed.`,EXIT.usage);if(context.principal!==void 0)return fail(write,json,command,"not-remote","A password is set on Toolroll's own computer.",EXIT.refused);if(localOwnerRequested()||!personAtTerminal(context))return fail(write,json,command,"not-a-terminal","Set your password yourself at a terminal: run `toolroll password set`.",EXIT.refused);const binding=localOwnerBinding(store);if(binding===null)return fail(write,json,command,"not-local","This Toolroll already signs in with a password. Sign in with it in the browser.",EXIT.refused);if(store.accountOf(binding.account)?.passwordSet===!0)return fail(write,json,command,"already-set","A password is already set. Sign in with it in the browser.",EXIT.refused);const typeHidden=context.easySeams?.askHidden??askHidden;write("Setting a password signs out open browser tabs and the open Toolroll screen. You can open it again right after."),write(`Choose a password for ${binding.account}. It signs you in from other devices and approves what this computer's browser can't.`);const chosen=await typeHidden("New password: ");if(chosen.length<8)return fail(write,json,command,"weak-password","A password needs at least 8 characters. Nothing changed.",EXIT.refused);if(await typeHidden("Type it again: ")!==chosen)return fail(write,json,command,"mismatch","The two passwords didn't match. Nothing changed.",EXIT.refused);const enrolled=enrollOwnerPassword(store,binding.account,hashPassword(chosen),binding.localGeneration,context.clock());if(!enrolled.ok){const words=enrolled.reason==="already-set"?"A password was just set. Sign in with it in the browser.":enrolled.reason==="local-mode-changed"?"Local mode changed while you were typing. Nothing changed.":"Only this computer's owner sets the first password. Nothing changed.";return fail(write,json,command,enrolled.reason,words,EXIT.refused)}return succeed(write,json,command,{account:binding.account,generation:enrolled.generation},()=>["Password set.","Sign in with it in your browser; an open Toolroll screen asks to open again."])}export function upLaptopPortCandidates(store,fromSeam,localInstall=!1){const saved=laptopPortOf(store);if(saved!==null)return[saved];const range=fromSeam??Array.from({length:20},(_,index)=>4180+index);return installationCreatedBy(store)!=="laptop"&&!localInstall?[range[0]??4180]:[...range]}const MEMORY_WRITE_VERBS=new Set(["decide","retire","apply","propose","tidy","restore","unmerge"]);function memoryWriteVerb(positional){return MEMORY_WRITE_VERBS.has(positional[0]??"")}const MEMORY_WRITE_REFUSAL="Project memory is changed by a person with their own sign-in, not the lead. The lead proposes decisions in chat for you to confirm.";async function releaseApproveCommand(positional,flags,context){const{store,write,json}=context,command="release approve",usage="`toolroll release approve [<branch>] [--repo <path>]` (with --json: --as <you> --token <password> --digest <card digest>)",branchFlag=text(flags,"branch");if(positional[0]!=="approve"||positional.length>2||branchFlag!==void 0&&positional.length>1)return fail(write,json,command,"usage",usage,EXIT.usage);const branch=branchFlag??positional[1];if(branch!==void 0&&(!/^[A-Za-z0-9._/-]{1,255}$/.test(branch)||branch.startsWith("-")||branch.includes("..")))return fail(write,json,command,"usage",`${branch} is not a branch name this command takes.`,EXIT.usage);const repoFlag=text(flags,"repo"),repo=repoFlag===void 0?null:resolve(repoFlag),stateDir=dirname(context.databaseFile),{journals,unreadable}=waitingJournals(stateDir,name2=>journalFile(stateDir,name2)),named=branch===void 0?journals:journals.filter(one=>one.branch===branch||/^\d+\.\d+\.\d+$/.test(branch)&&one.version===branch&&one.file.endsWith(`/from-main/${branch}.json`));if(branch!==void 0&&named.length===0&&unreadable.includes(basename(journalFile(stateDir,branch))))return fail(write,json,command,"unreadable",`${branch}'s release journal can't be read as one; nothing was approved. Run \`toolroll release ${branch}\` again.`,EXIT.refused);const matches=[],refusals=[];for(const one of named){if(releaseTaskOf(store,one.taskId)!==null&&approvalOf(store.getScope(one.taskId)).approved)continue;const proved=journalMatchesPlane(store,one,repo);proved.ok?matches.push(one):refusals.push(proved.why)}if(matches.length===0){const why=refusals.length>0?`${refusals[0]}; nothing was approved`:branch===void 0?"No release is waiting for your approval":`No release of ${branch} is waiting for your approval`;return fail(write,json,command,refusals.length>0?"mismatch":"none",`${why}.`,EXIT.refused)}if(matches.length>1)return fail(write,json,command,"ambiguous",`More than one release is waiting: ${matches.map(one=>`${one.branch} (${one.version})`).join(", ")}. Name the branch: \`toolroll release approve <branch>\`.`,EXIT.refused,{releases:matches.map(one=>({branch:one.branch,version:one.version,task:one.taskId}))});const chosen=matches[0],built=releaseApprovalCard(store,chosen.taskId);if(!built.ok)return fail(write,json,command,"none",built.why,EXIT.refused);const shown=built.card,cardData={task:shown.taskId,version:shown.seal.identity.packageVersion,branch:shown.seal.identity.branch,candidate:shown.seal.identity.approvedSha,digest:shown.digest,ci:shown.ci?.state??null};if(shown.approved!==null)return fail(write,json,command,"approved",`Release ${cardData.version} is already approved by ${shown.approved.by}.`,EXIT.refused,{release:cardData});if(shown.refusal!==null){if(!json)for(const line of releaseCardLines(shown))write(line);return fail(write,json,command,"refused",`Can't approve now: ${shown.refusal}`,EXIT.refused,{release:cardData})}let name,token;if(json){const given=credentialsFrom(flags,context);if(given.name===void 0||given.token===void 0||given.name===""||given.token==="")return fail(write,json,command,"credentials","Approving a release needs who is agreeing: --as <you> --token <password>. Nothing was approved.",EXIT.usage,{release:cardData});if(text(flags,"digest")!==shown.digest)return fail(write,json,command,"unconfirmed","Name the card you read: --digest <card digest>. Nothing was approved.",EXIT.refused,{release:cardData});name=given.name,token=given.token}else{for(const line of releaseCardLines(shown))write(line);if(write(""),interactive()){if(!await confirm(`Approve release ${cardData.version}?`))return write("Nothing approved."),EXIT.refused}else if(!flags.has("yes")||text(flags,"digest")!==shown.digest)return write(`Nothing has been approved. Agree to exactly this card with: toolroll release approve ${chosen.branch} --yes --digest ${shown.digest} --as <you> --token <your password>`),EXIT.refused;const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,command,"credentials","Approving a release needs who is agreeing. Nothing was approved.",EXIT.usage);name=acting.name,token=acting.token}const again=releaseApprovalCard(store,chosen.taskId);if(!again.ok||again.card.digest!==shown.digest)return fail(write,json,command,"changed","This release changed while you were being asked; nothing was approved. Run the command again to read it.",EXIT.refused);const now=context.clock(),answer=approveReleaseCard(store,{taskId:chosen.taskId,cardDigest:shown.digest,approveNow:scopeDigest=>approve(store,chosen.taskId,name,now,scopeDigest,token,mutationFrom(flags,now))});if(!answer.ok){if(answer.reason!=="approve")return fail(write,json,command,answer.reason,`${answer.message} Nothing was approved.`,EXIT.refused);const refused=answer.result;return refused.reason==="policy"?fail(write,json,command,"policy",`${chosen.taskId}: ${refused.message}`,EXIT.refused):fail(write,json,command,refused.reason,describeApproveFailure(refused.reason,chosen.taskId),EXIT.refused)}return succeed(write,json,command,{release:cardData},()=>[`Approved release ${cardData.version} (${cardData.candidate.slice(0,7)}). The release check runs next; it deploys, merges and publishes once GitHub CI and the check pass.`,...shown.stopped===null?[]:[`The release isn't running: run \`toolroll release ${chosen.branch}\` to go on.`]])}function taskReadyCommand(positional,context){const{store,write,json}=context,command="task ready",id=positional[0];if(id===void 0||positional.length>1)return fail(write,json,command,"usage","`toolroll task ready <task>`",EXIT.usage);const lens=context.principal?.lens??null,ref=store.lookupRef(id);if(ref===null||store.getTask(id)===null||lens!==null&&(ref.repo===null||!lens.includes(ref.repo)))return fail(write,json,command,"unknown-task",`no task \`${id}\``,EXIT.refused);const now=(context.clock??(()=>context.now))(),list=mergeChecklistOf(store,id,now,{principal:"operator",repos:lens,includeUnplaced:lens===null,dependencyRepos:lens},context.evidenceRoot);return list===null?fail(write,json,command,"unknown-task",`no task \`${id}\``,EXIT.refused):succeed(write,json,command,list,()=>checklistLines(list))}function uncommittedLines(plan){const changed=plan.stay.filter(one=>one.why==="has changes");return changed.length===0?[]:[`${changed.length===1?"This folder has":"These folders have"} uncommitted changes and stay${changed.length===1?"s":""} until you decide (toolroll storage discard <path> --yes throws one away):`,...changed.map(one=>` ${bytesWords(one.bytes).padStart(8)} ${one.path}${one.taskId===null?"":` (${one.taskId})`}`)]}async function mapCommand(positional,flags,context){const{store}=context,local=currentLocalOwner(),{name,token}=credentialsFrom(flags,context);let actor=null,repos=null;const all=[...new Set([...store.knownRepos(),...store.listProjects().map(one=>one.path)])];if(local!==null)actor=local.account,repos=all.filter(repo=>store.accountCanAccess(local.account,repo));else if(name!==void 0&&token!==void 0){if(!authenticateAccount(store,name,token).ok)return fail(context.write,context.json,"map","unauthenticated","Sign in again: that login doesn't work here.",EXIT.refused);const remote=activeRemote();actor=name,repos=all.filter(repo=>store.accountCanAccess(name,repo)&&(remote===null||remote.allows(repo)))}else repos=all;return runMapCommand(positional,flags,{store,write:context.write,json:context.json,now:context.clock(),actor,repos,approver:repo=>local===null&&name!==void 0&&token!==void 0&&authenticateApprover(store,name,token,repo).ok,door:repo=>{if(local!==null)return{kind:"local-owner",actor:local.account};if(name===void 0||token===void 0)return null;const generation=store.accountOf(name)?.generation??-1,proved=authenticateApprover(store,name,token,repo);return proved.ok?{kind:"person",person:{actor:name,generation,method:proved.method}}:null}})}async function newTaskCommand(positional,flags,context){const{store,write,json}=context,clock=context.clock??(()=>new Date),command="task new",local=currentLocalOwner();if(context.principal!==void 0||machineActing())return fail(write,json,command,"person-only","Only a person starts a build this way. File it with `task add`.",EXIT.refused);if(local===null&&(json||!personAtTerminal(context)))return fail(write,json,command,"person-only","`task new` asks a person at a terminal. Use `task add` from a script or an agent.",EXIT.refused);let{name,token}=credentialsFrom(flags,context);const passwordFree=token!==void 0&&(local!==null||sessionStandsIn(store)),facts={passwordless:local===null&&passwordFree,localOwner:local!==null,freshAt:null,returnTo:"/"},buildNow=(preview,digest)=>fastStartBuild(store,{preview,digest,actor:name??"",via:local===null?"cli":"terminal-ui",password:facts,approveNow:(taskId,sawDigest,fast)=>approve(store,taskId,name??"",clock(),sawDigest,token??"",{},fast)},clock()),answerBuild=built=>built.ok?succeed(write,json,command,{task:built.taskId},()=>[`Building ${built.taskId}. It starts next.`]):fail(write,json,command,built.reason,built.message,EXIT.refused),pressed=text(flags,"build");if(pressed!==void 0)return local===null?fail(write,json,command,"person-only","--build is the terminal UI's own.",EXIT.refused):answerBuild(buildNow(pressed,text(flags,"digest")??""));const fromLink=text(flags,"from");if(fromLink!==void 0)return importTaskCommand(fromLink,flags,context,name);const words=positional.join(" ").trim(),repo=text(flags,"repo");if(words==="")return fail(write,json,command,"usage",`Say what should change: \`toolroll task new "<what should change>" --repo ${repo??"<project>"}\``,EXIT.usage);if(repo===void 0)return fail(write,json,command,"usage","Name the project it's for with --repo (its folder, or `--repo .` for the one you're in): `toolroll task new \"<what should change>\" --repo <project>`",EXIT.usage);const placed=canonicalProject(repo)??resolve(repo);if(local===null&&(flags.has("token")||!facts.passwordless&&!passwordFreeOwner(store))){let given=flags.has("token")?token:void 0;if(given===void 0){const usual=name===void 0?soloOperatorOf(store):null;if(name===void 0){const answered=await(context.easySeams?.ask??ask)(usual===null?"username: ":`username [${usual}]: `);name=answered===""&&usual!==null?usual:answered}given=await(context.easySeams?.askHidden??askHidden)("password: ")}else name===void 0&&(name=soloOperatorOf(store)??void 0);if(name===void 0||name===""||given==="")return write("Nothing was filed."),EXIT.refused;const person=name;if(!verifyApproverByPassword(store,person,given,store.knownRepos().filter(one=>store.accountCanAccess(person,one))).ok)return fail(write,json,command,"unauthenticated","That username and password didn't work. Nothing was filed.",EXIT.refused);token=given,facts.freshAt=clock().getTime()}const prepared=name===void 0||token===void 0?{eligible:!1,reason:"password"}:await prepareFastStart(store,{actor:name,repo:placed,title:words,via:local===null?"cli":"terminal-ui",password:facts},clock()),terms=prepared.eligible?fastTermsLines(store,prepared.scope,placed):[];if(flags.has("preview"))return local===null?fail(write,json,command,"person-only","--preview is the terminal UI's own.",EXIT.refused):succeed(write,json,command,prepared.eligible?{eligible:!0,preview:prepared.preview,digest:prepared.digest,terms}:{eligible:!1,reason:prepared.reason,message:fastRefusalWords(prepared.reason)},()=>[]);if(!prepared.eligible)return write(`${fastRefusalWords(prepared.reason)} Filing it for a plan.`),addTask([words],flags,context,!0);write("Build approves exactly this:"),write("");for(const line of terms)write(` ${line.label}: ${line.words}`);return write(""),await(context.easySeams?.confirm??confirm)("Build now?")?answerBuild(buildNow(prepared.preview,prepared.digest)):(write("Nothing started. File it for a plan with `toolroll task add`."),EXIT.refused)}async function keepGrownCommand(positional,flags,context){const{store,write,json,clock}=context,id=positional[0];if(id===void 0)return fail(write,json,"task keep","usage","`toolroll task keep <id> --as <you> --token <t>`",EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:authenticateApprover(store,acting.name,acting.token);if(acting===null||!verified?.ok)return refuseApprover(context,"task keep",verified,"keeping a change takes `--as <you> --token <t>`",id);const kept=keepGrownChange(store,id,clock());return kept.ok?succeed(write,json,"task keep",{id,digest:kept.digest},()=>[`Its plan now names the exact commit. ${passwordFreeOwner(store)?"Approve it in `toolroll`: press a on the task.":`Approve it with \`toolroll task approve ${id}\`.`}`]):fail(write,json,"task keep","refused",kept.message,EXIT.refused)}let resumingReleases=!1;async function resumeHeldReleases(store,stateDir,now){if(!resumingReleases){resumingReleases=!0;try{await resumeAllowedReleases(store,stateDir,journal=>runRelease({branch:journal.branch,checkout:journal.checkout,stateDir,limits:{}},releaseAdapters({checkout:journal.checkout,say:()=>{}})),now)}catch{}finally{resumingReleases=!1}}}async function importTaskCommand(url,flags,context,actor){const{store,write,json}=context,clock=context.clock??(()=>new Date),command="task new",repo=text(flags,"repo");if(repo===void 0)return fail(write,json,command,"usage","`toolroll task new --from <url> --repo <project>`",EXIT.usage);const placed=canonicalProject(repo)??resolve(repo),read=await readGithubItem(store,{url,repo:placed},context.easySeams?.github??{});if(!read.ok)return fail(write,json,command,read.reason,read.message,EXIT.refused);write(`${read.item.kind==="pull"?"Pull request":"Issue"} #${read.item.number}, written outside Toolroll:`),write(` > ${read.item.title}`);for(const line of read.item.body.split(/\r?\n/))write(` > ${line}`);if(write(""),!await(context.easySeams?.confirm??confirm)("Add this task? You approve its plan before anything builds."))return write("Nothing filed."),EXIT.refused;const filed=await fileGithubItem(store,{url,repo:placed,actor:actor??"cli",shownHead:read.item.head},clock(),context.easySeams?.github??{});return filed.ok?succeed(write,json,command,{task:filed.taskId},()=>[`Filed ${filed.taskId}. Its plan is ready for you to approve.`]):fail(write,json,command,filed.reason,filed.message,EXIT.refused)}async function flakyCommand(positional,flags,context){const acting=await askCredentials(flags,context),verified=acting===null||currentLocalOwner()!==null?null:verifyApproverByPassword(context.store,acting.name,acting.token,context.store.knownRepos().filter(repo=>context.store.accountCanAccess(acting.name,repo))),who=currentLocalOwner()!==null?localReader(context):verified!==null&&verified.ok?verified.who:null;return runFlakyCommand(positional,flags,{store:context.store,write:context.write,json:context.json,now:context.clock(),actor:who?.name??null,repos:who?.repos??[]})}export async function refreshLearning(store,now,reads){try{backfillMemoryUse(store,now())}catch{}for(const repo of store.knownRepos())try{scheduledTidy(store,repo,now())}catch{}for(const repo of store.knownRepos())try{const key=ciCursorKey(repo),at=now();if(at.getTime()-store.serviceCursor(key)<CI_READ_EVERY_MS||ciRepositoriesOf(store,repo).length===0)continue;store.setServiceCursor(key,at.getTime(),at),await observeCiAttempts(store,repo,reads??githubReads(releaseExec,releaseTools().gh,{retry:!0}),at)}catch{}}async function cardCommand(positional,flags,context){if(activeRemote()===null&&isPanelCardCliInvocation(positional,flags,CARD_SOURCES))return runPanelCardCommand(positional,flags,{json:context.json,now:context.clock(),repos:context.store.knownRepos(),ok:(result,lines)=>succeed(context.write,context.json,"card",result,lines),no:(reason,message)=>fail(context.write,context.json,"card",reason,message,reason==="usage"?EXIT.usage:EXIT.refused)});const acting=await askCredentials(flags,context),verified=acting===null||currentLocalOwner()!==null?null:verifyApproverByPassword(context.store,acting.name,acting.token,context.store.knownRepos().filter(repo=>context.store.accountCanAccess(acting.name,repo))),who=currentLocalOwner()!==null?localReader(context):verified!==null&&verified.ok?verified.who:null;return runCardCommand(positional,flags,{store:context.store,write:context.write,json:context.json,now:context.clock(),actor:who?.name??null,repos:who?.repos??[],evidenceRoot:context.evidenceRoot,ok:(result,lines)=>succeed(context.write,context.json,"card",result,lines),no:(reason,message)=>fail(context.write,context.json,"card",reason,message,reason==="usage"?EXIT.usage:EXIT.refused)})}function localReader(context){const local=currentLocalOwner();return local===null?null:{name:local.account,repos:context.store.knownRepos().filter(repo=>context.store.accountCanAccess(local.account,repo))}}function followThroughContext(context,flags){const{store,write,json,clock,evidenceRoot}=context;return{store,evidenceRoot,now:clock(),ok:(command,result,lines)=>succeed(write,json,command,result,lines),no:(command,reason,message)=>fail(write,json,command,reason,message,reason==="usage"?EXIT.usage:EXIT.refused),prove:async(command,repo)=>{const acting=await askCredentials(flags,context);return acting===null?(fail(write,json,command,"usage","this takes `--as <you> --token <t>`",EXIT.usage),null):authenticateApprover(store,acting.name,acting.token,repo).ok?acting.name:(fail(write,json,command,"not-an-approver","that is not an approver, or the token does not match",EXIT.refused),null)}}}async function projectFallbackCommand(positional,flags,context){const command="project fallback",agents=text(flags,"agents"),clearing=flags.has("clear"),allowing=flags.has("allow-paid"),withdrawing=flags.has("no-paid"),repo=await projectAsked(context,flags,positional,command,{own:["agents","clear","allow-paid","no-paid"],most:1,usage:"Use project fallback --repo <project path> [--agents provider:model:plan|api-key,…] [--clear] [--allow-paid|--no-paid].",invalid:clearing&&agents!==void 0||allowing&&withdrawing,match:{listed:!0,canonical:!0}});if(typeof repo=="number")return repo;const words=()=>{const setting=fallbackSettingOf(context.store,repo);return setting===null?[`${repo}: no fallback agents. A task stops when its agent runs out of its plan.`]:[`${repo}: when an agent runs out of its plan, the work moves on to:`,...setting.entries.map((one,at)=>` ${at+1}. ${entryWords(one)}. ${entryMovesOnWords(one)}.`),setting.paidGrant===null?"Paid fallback: not allowed.":`Paid fallback: allowed by ${setting.paidGrant.by}.`]},shown=()=>{const setting=fallbackSettingOf(context.store,repo);return{repo,agents:setting?.entries??[],paidAllowed:setting?.paidGrant!=null}};if(agents===void 0&&!clearing&&!allowing&&!withdrawing)return succeed(context.write,context.json,command,shown(),words);const parsed=agents===void 0?[]:agents.split(",").map(one=>parseEntry(one.trim())),bad=parsed.find(one=>typeof one=="string");if(bad!==void 0)return fail(context.write,context.json,command,"usage",bad,EXIT.usage);const acting=await askCredentials(flags,context),verified=acting===null?null:credentialApprover(context.store,acting.name,acting.token,repo);if(acting===null||!verified?.ok||!context.store.accountCanAccess(acting.name,repo))return fail(context.write,context.json,command,"refused","An approver for this project changes its fallback agents, with their password: pass --as and --token.",EXIT.refused);const now=context.clock(),done=context.store.transact(()=>{if(clearing){const one=clearFallbackChain(context.store,repo,acting.name,now);if(!one.ok)return one}if(agents!==void 0){const one=setFallbackChain(context.store,repo,parsed,acting.name,now);if(!one.ok)return one}if(allowing||withdrawing){const one=setPaidGrant(context.store,repo,allowing,acting.name,now);if(!one.ok)return one}return{ok:!0}});return done.ok?succeed(context.write,context.json,command,shown(),()=>[...words(),"Tasks scoped from now on use this; tasks already approved keep the chain they were approved with."]):fail(context.write,context.json,command,"refused",done.problem,EXIT.refused)}async function quickAnswersConfig(action,repoGiven,flags,context){const{store,write,json,clock}=context,command=`config ${action}`;if(repoGiven)return fail(write,json,command,"usage","quick answers are installation-wide: no --repo",EXIT.usage);const said=()=>{const on=leadQuickAnswersOn(store),model=quickLeadModel(store);return{payload:{quickAnswers:{on,model}},lines:()=>[on?`Quick answers are on: plain status questions are answered by ${modelName(model)}; anything that asks for a change stays on the lead's main model.`:"Quick answers are off: the lead's main model answers everything."]}};if(action==="show"){const shown2=said();return succeed(write,json,command,shown2.payload,shown2.lines)}const acting=await askCredentials(flags,context);if(acting===null)return fail(write,json,command,"usage","changing quick answers takes `--as <you> --token <t>`",EXIT.usage);if(!authenticateApprover(store,acting.name,acting.token).ok||!store.isInstanceOperator(acting.name))return fail(write,json,command,"unauthenticated","an instance operator changes quick answers, with their password",EXIT.refused);setLeadQuickAnswers(store,action==="set",acting.name,clock());const shown=said();return succeed(write,json,command,shown.payload,shown.lines)}export const DELIVERY_EVERY_MS=5e3,FAST_CI_EVERY_MS=3e4,FAST_CI_LIMIT=10;const FAST_CI_NONE_WINDOW_MS=30*6e4,serviceBeats=new WeakMap;function newestNotificationId(store){return Number(store.handle.prepare("SELECT COALESCE(MAX(id), 0) AS id FROM notification").get()?.id??0)}export function fastCiWaiting(store,now,limit=FAST_CI_LIMIT,attempted=new Map){const waiting=store.openedPublications().filter(publication=>{if(publication.prNumber===null)return!1;const state=publication.lastCheckState;if(state===null||state==="running")return!0;if(state==="none")return now.getTime()-Date.parse(publication.lastCheckAt??publication.updatedAt)<FAST_CI_NONE_WINDOW_MS&&now.getTime()-Date.parse(publication.updatedAt)<FAST_CI_NONE_WINDOW_MS;if(state!=="passing")return!1;const intent=store.mergeIntentFor(publication.id);if(intent!==null&&["pending","claimed","waiting-human","firing"].includes(intent.state))return!0;const follow=store.handle.prepare("SELECT flow_card, ready_head, merge_commit FROM pull_request_follow WHERE publication = ?").get(publication.id);return follow!==void 0&&follow.flow_card==null&&follow.merge_commit==null&&follow.ready_head!==publication.headSha}),last=one=>{const read=one.lastCheckAt??"",tried=attempted.get(one.id)??"";return tried>read?tried:read};return waiting.sort((a,b)=>last(a).localeCompare(last(b))||a.id-b.id).slice(0,limit)}export function joinServiceBeats(member){const store=member.context.store;let beats=serviceBeats.get(store);beats===void 0&&(beats=startServiceBeats(store)),beats.members.add(member);const joined=beats;return async()=>{!joined.members.delete(member)||joined.members.size>0||(joined.stopped=!0,serviceBeats.get(store)===joined&&serviceBeats.delete(store),joined.poker.poke(),await joined.delivery.stop(),await joined.fastCi.stop(),await joined.wakeLoop)}}function startServiceBeats(store){const anyMember=()=>beats.members.values().next().value;let deliveredThrough=newestNotificationId(store),deliveryProblem=null;const attempted=new Map,delivery=startMaintenance({intervalMs:DELIVERY_EVERY_MS,shouldStop:()=>beats.stopped,onError:error=>{const detail=describe(error);detail!==deliveryProblem&&anyMember()?.progress(`watch: outgoing webhooks failed — ${detail}; they try again in a few seconds`),deliveryProblem=detail},run:async()=>{const member=anyMember();if(member===void 0)return;const{context}=member,dir=dirname(context.databaseFile);deliveredThrough=newestNotificationId(store);try{await pushPass(store,{configDir:dir,clock:()=>new Date})}catch{}const primary=effectivePrimary(process.env,dir,loadBotToken(process.env,context.telegramTokenFile)!==null),targets=activeWebhookTargets(process.env,dir,primary.channel);targets.length>0&&await webhookPass(store,{targets,consoleUrl:loadConsoleUrl(process.env,dir),clock:context.clock}),deliveryProblem=null}}),fastCi=startMaintenance({intervalMs:FAST_CI_EVERY_MS,shouldStop:()=>beats.stopped,onError:()=>{},run:async()=>{const standingMembers=()=>[...beats.members].filter(one=>one.stopping?.()!==!0),standing=()=>{const members=standingMembers();return!beats.stopped&&members.length>0&&members.every(one=>one.ciReady())};if(!standing())return;const{context,progress}=standingMembers()[0],now=context.clock(),waiting=fastCiWaiting(store,now,FAST_CI_LIMIT,attempted);if(waiting.length===0)return;attempted.size>500&&attempted.clear();for(const one of waiting)attempted.set(one.id,now.toISOString());const exec=context.publishExec===void 0?{}:{exec:context.publishExec},checks=await observeChecks(store,{...exec,publications:waiting});if(!standing())return;checks.failing>0&&progress(`watch: CI is red on ${checks.failing} published PR(s) — the outbox has it`);const followed=await followPullRequests(store,checks.seen,{evidenceRoot:context.evidenceRoot,...exec,proceed:standing});followed.revisions>0&&progress(`watch: filed ${followed.revisions} CI revision(s)`),followed.merged>0&&progress(`watch: merged ${followed.merged} pull request(s) whose checks passed`)}}),poker=new WakePoker,hub=wakeHubFor(store,read=>briefly(store,read)),beats={members:new Set,stopped:!1,delivery,fastCi,poker,wakeLoop:Promise.resolve()};return beats.wakeLoop=(async()=>{for(;!beats.stopped;)try{await hub.changed({baseline:store.wakeSeq(),deadline:Number.MAX_SAFE_INTEGER,until:()=>beats.stopped,poker})==="wake"&&!beats.stopped&&newestNotificationId(store)>deliveredThrough&&delivery.runNow()}catch{await new Promise(resolveLater=>{setTimeout(resolveLater,1e3).unref?.()})}})(),serviceBeats.set(store,beats),delivery.runNow(),beats}function claimAndMarkRunning(store,backend,id,taskRef,runner,options){const{now}=options;return store.transact(()=>{const result=acquire(store,taskRef,runner,options);if(!result.ok||backend!==BUILT_IN)return result;if(result.replayed===!0){const task=store.getTask(id),stillMine=store.currentLiveLease(taskRef,now)===result.claim.leaseId;return task!==null&&task.state==="queued"&&stillMine&&store.setTaskState(id,"running",now),result}if(!moveTask(store.handle,id,"claim",now))throw new Error(`claim: ${id} could not be marked running`);return store.bumpWake(),result})}function closedClaimWords(store,id,state,now){const head=`${id} is ${state}, so it can't be claimed.`;return state==="cancelled"?`${head} To run it again, reopen it: \`toolroll task state ${id} queued\``:requeueEligibility(store,id,now).ok?`${head} To run it again: \`toolroll task requeue ${id}\``:`${head} See its result: \`toolroll task show ${id}\``}function releaseToQueue(store,lease,now){return store.transact(()=>{const result=release(store,lease,now);if(!result.ok||result.duplicate===!0)return result;const ref=store.refForId(result.claim.taskRef);return ref===null||ref.backend!==BUILT_IN||store.getTask(ref.externalId)?.state==="running"&&store.setTaskState(ref.externalId,"queued",now),result})}async function localPlanCommand(positional,flags,context){const{store,write,json,clock}=context,command="task plan";if(flags.has("provider")||flags.has("model")){const passwordSet=store.accountOf(currentLocalOwner()?.account??"")?.passwordSet===!0;return fail(write,json,command,"local-owner",`Choosing which agent plans needs your password. ${passwordSet?"Sign in with your password to do this.":"Set a password first: run `toolroll password set`."}`,EXIT.refused)}for(const name of flags.keys())if(!["json","db","digest","incident"].includes(name))return fail(write,json,command,"usage",`--${name} is not a ${command} option.`,EXIT.usage);const id=positional[0],digest=flags.get("digest"),incident=flags.get("incident"),usage="Use task plan <task> --digest <the plan source you read> [--incident <the planning incident you read>].";if(positional.length!==1||!id||id.length>64||/[\x00-\x1f]/.test(id))return fail(write,json,command,"usage",usage,EXIT.usage);if(typeof digest!="string"||!/^[a-f0-9]{64}$/.test(digest))return fail(write,json,command,"usage",`--digest needs the exact task you read. ${usage}`,EXIT.usage);if(incident!==void 0){if(typeof incident!="string"||!/^[1-9]\d{0,14}$/.test(incident))return fail(write,json,command,"usage",`--incident needs the incident you read. ${usage}`,EXIT.usage);const again=planAgainAsLocalOwner(store,id,{incident:Number(incident),source:digest},clock());return again.ok?succeed(write,json,command,{id,replayed:again.replayed,again:!0},()=>[again.replayed?`${id} · Already planning again.`:`${id} · Planning again. You approve the plan before anything is built.`]):fail(write,json,command,again.reason,again.message,EXIT.refused)}const done=requestPlanAsLocalOwner(store,id,digest,clock());return done.ok?succeed(write,json,command,{id,replayed:done.replayed,autoPlan:!1},()=>[done.replayed?`${id} · Already asked for a plan.`:`${id} · Asked for a plan. You approve the plan before anything is built.`]):fail(write,json,command,done.reason,done.message,EXIT.refused)}async function localRetryCommand(positional,flags,context){const{store,write,json,clock}=context,command="task requeue";for(const name of flags.keys())if(!["json","db","run","digest"].includes(name))return fail(write,json,command,"usage",`--${name} is not a ${command} option.`,EXIT.usage);const id=positional[0],run2=flags.get("run"),digest=flags.get("digest"),usage="Use task requeue <task> --run <the build you read> --digest <its approved plan>.";if(positional.length!==1||!id||id.length>64||/[\x00-\x1f]/.test(id))return fail(write,json,command,"usage",usage,EXIT.usage);if(typeof run2!="string"||!/^[1-9]\d{0,14}$/.test(run2))return fail(write,json,command,"usage",`--run needs the exact build you read. ${usage}`,EXIT.usage);if(typeof digest!="string"||!/^[a-f0-9]{32}$/.test(digest))return fail(write,json,command,"usage",`--digest needs the exact plan you read. ${usage}`,EXIT.usage);await proveTaskBuildsStopped(store,id,clock);const done=retryAsLocalOwner(store,id,{run:Number(run2),digest},clock());return done.ok?succeed(write,json,command,{id,replayed:done.replayed,retries:done.retries},()=>[done.replayed?`${id} · Already retrying build #${run2}.`:`${id} · Retrying build #${run2}. It starts next.`]):fail(write,json,command,done.reason,done.message,EXIT.refused)}export function personMayInitLocalMode(caller){return caller.stdin&&caller.stdout&&!caller.agent&&!caller.json&&!caller.remote}function defaultFenceAvailable(){return process.platform==="darwin"?macosFenceAvailable():linuxFenceAvailable()}function upLocalInitCaller(context,flags){const terminal=context.upSeams?.terminal;return{stdin:terminal??process.stdin.isTTY===!0,stdout:terminal??process.stdout.isTTY===!0,agent:underAgent(context.upSeams?.env??process.env),json:context.json,remote:context.principal!==void 0||localOwnerRequested()||["token","token-file","token-env"].some(name=>flags.has(name))}}export async function initLocalModeForPerson(store,caller,input){if(!personMayInitLocalMode(caller))return{ok:!1,reason:"not-a-person"};if(!localModeCandidate(store))return{ok:!1,reason:"already"};const consolesDown=await consolesProvenDown(store,input.now,input.probe);return initLocalMode(store,{owner:input.owner,fenceAvailable:input.fence(),now:input.now,consolesProvenDown:consolesDown})}export async function easyStartInitLocalMode(databaseFile,caller,options={}){if(!personMayInitLocalMode(caller)||!(options.fence??defaultFenceAvailable)())return!1;let store;try{store=openStore(databaseFile,{createdBy:"laptop"})}catch{return!1}try{const owner=options.owner??process.env.USER??process.env.USERNAME??"operator";return await initLocalModeForPerson(store,caller,{owner,fence:()=>!0,now:options.now??new Date,...options.probe===void 0?{}:{probe:options.probe}}),localOwnerBinding(store)!==null}catch{return!1}finally{store.close()}}function serveConsoleLifecycle(store,host,port,clock){const component=consoleComponent(host,port),holder=`serve:${process.pid}:${randomUUID().slice(0,8)}`;try{reportLifecycle(store,component,"started",holder,clock(),{pid:process.pid})}catch{return null}const beat=setInterval(()=>{try{beatLifecycle(store,component,holder,clock())}catch{}},RUNNER_HEARTBEAT_MS);return beat.unref?.(),()=>{clearInterval(beat);try{reportLifecycle(store,component,"stopped",holder,clock())}catch{}}}const probeConsoleAddress=(host,port)=>new Promise(resolve2=>{const socket=createNetConnection({host,port}),done=answer=>{socket.destroy(),resolve2(answer)};socket.setTimeout(1e3,()=>done("unknown")),socket.once("connect",()=>done("listening")),socket.once("error",error=>{const code=error.code??"";done(["ECONNREFUSED","EADDRNOTAVAIL","EAFNOSUPPORT"].includes(code)?"refused":"unknown")})});export async function consolesProvenDown(store,now,probe=probeConsoleAddress){const down=new Set;let rows;try{rows=openConsoleRows(store,now)}catch{return down}for(const row of rows){if(row.beatRecent||row.port===null)continue;const addresses=row.host===null||["0.0.0.0","::","localhost"].includes(row.host)?["127.0.0.1","::1"]:[row.host];let allRefused=!0;for(const address of addresses)await probe(address,row.port)!=="refused"&&(allRefused=!1);allRefused&&down.add(row.key)}return down}async function closeServedConsole(server){await new Promise(resolve2=>{server.close(()=>resolve2()),server.closeAllConnections?.()})}async function welcomeSampleCommand(positional,flags,context){const{write,json,store}=context,command="welcome sample";if(positional.length>0)return fail(write,json,command,"usage","Use `toolroll welcome sample`: it takes no folder or name.",EXIT.usage);for(const name of flags.keys())if(!["db","json"].includes(name))return fail(write,json,command,"usage",`--${name} is not a welcome sample option.`,EXIT.usage);if(context.principal!==void 0)return fail(write,json,command,"not-remote","The sample project is added on Toolroll's own computer.",EXIT.refused);const lead=envValue(process.env,"LEAD_TOKEN");if(context.leadToken!==void 0||lead!==void 0&&lead!=="")return fail(write,json,command,"refused","A lead token can't add the sample project. Run `toolroll` yourself and press s.",EXIT.refused);if(store.isDemo())return fail(write,json,command,"refused","The sandbox never makes projects.",EXIT.refused);const viaScreen=localOwnerRequested();if(!viaScreen&&!personAtTerminal(context))return fail(write,json,command,"not-a-terminal","Add the sample project yourself at a terminal: run `toolroll` and press s, or `toolroll welcome sample`.",EXIT.refused);const binding=localOwnerBinding(store);if(binding===null)return fail(write,json,command,"not-local","This Toolroll signs in with a password. Open it in the browser and choose Try a sample project on the welcome page.",EXIT.refused);if(!viaScreen&&store.accountOf(binding.account)?.passwordSet===!0)return fail(write,json,command,"password-set","This Toolroll has a password. Run `toolroll` and press s, or sign in in the browser and choose Try a sample project.",EXIT.refused);const principal=viaScreen?currentLocalOwner():{account:binding.account,localGeneration:binding.localGeneration,accountGeneration:binding.accountGeneration,transport:"terminal",act:"add-project",sessionHash:null,request:null};if(principal===null||principal.act!=="add-project")return fail(write,json,command,"refused","Set a password, or sign in with your password, to do this.",EXIT.refused);const registryFile=registryPathOf(context),{readProjectRegistryNow}=await import("./repos.js"),ceiling=registry=>{const read=registry??readProjectRegistryNow(registryFile);return"error"in read?{repos:[],roots:[]}:resolveCeiling(read.repos,read.roots).ceiling};if("error"in readProjectRegistryNow(registryFile))return fail(write,json,command,"registry","Toolroll's project list can't be read, so nothing was added.",EXIT.refused);const{addSampleProject}=await import("./sample-project.js"),added=await asLocalOwner(principal,async()=>{const stands=()=>localActNow(store,"add-project")!==null;return addSampleProject({store,registryFile,now:context.clock(),ceiling,authority:{actor:{label:principal.account,origin:"cli"},stands}})});if(!added.ok){const words={"no-root":"There's no projects folder to put the sample in. Run `toolroll` once to choose one, then try again.",exists:"A folder named toolroll-sample is already in your projects folder and wasn't made by Toolroll, so nothing was changed.",failed:"The sample project couldn't be made. Nothing was added. Try again.","not-added":"The sample project was made but couldn't be added. Try again.",refused:"Your local sign-in changed while the sample was being added. Nothing was added. Run `toolroll` to sign in again.",incomplete:"The sample project wasn't added, and its line in your project list couldn't be taken back."};return fail(write,json,command,added.reason,added.message??words[added.reason],EXIT.refused)}return succeed(write,json,command,{repo:added.repo,created:added.created,added:added.added,checkSet:added.checkSet},()=>[added.added?`Added the sample project: ${added.repo}`:`The sample project is already added: ${added.repo}`,"Next: write a first task. Run `toolroll` and press n."])}async function passwordResetCommand(rest,flags,context){const{write,json,store}=context,command="password reset";if(rest.length>0)return fail(write,json,command,"usage","Use `toolroll password reset` (or `--as <name>` when several people sign in here).",EXIT.usage);for(const name of flags.keys())if(!["db","json","as"].includes(name))return fail(write,json,command,"usage",`--${name} is not a password reset option: the new password is only ever typed.`,EXIT.usage);const leadInShell=envValue(process.env,"LEAD_TOKEN");if(context.principal!==void 0||activeRemote()!==null||context.leadToken!==void 0||leadInShell!==void 0&&leadInShell!=="")return fail(write,json,command,"not-remote","A password is reset by a person at the computer running Toolroll, from their own shell (not with a remote or lead token).",EXIT.refused);if(localOwnerRequested()||!personAtTerminal(context))return fail(write,json,command,"not-a-terminal","Reset the password yourself at a terminal on the computer running Toolroll: run `toolroll password reset`.",EXIT.refused);const asked=flags.get("as");if(asked===!0||asked==="")return fail(write,json,command,"usage","Say whose password: `--as <name>`.",EXIT.usage);let account;if(typeof asked=="string")account=asked;else{const people=store.listApprovers().map(one=>one.name).filter(name=>store.accountOf(name)?.revokedAt===null);if(people.length===0)return fail(write,json,command,"no-account","No one signs in to this Toolroll yet. Nothing changed.",EXIT.refused);if(people.length>1)return fail(write,json,command,"several",`Several people sign in here (${people.join(", ")}). Say whose: \`toolroll password reset --as <name>\`.`,EXIT.usage);account=people[0]}const sso=(await import("./sso-settings.js")).readSsoSettings(dirname(context.databaseFile)),operatorsOnly=sso!==null&&sso.passwords==="operators",refusalWords=reason=>reason==="no-account"?`No account named \`${account}\`. Nothing changed.`:reason==="revoked"?`${account} was removed and can't sign in. Nothing changed.`:reason==="sso-only"?`${account} signs in with ${sso?.label??"your identity provider"} and has no password to reset. Nothing changed.`:reason==="no-password"?`${account} has no password yet. Set one with \`toolroll password set\`. Nothing changed.`:reason==="password-not-allowed"?`${account} signs in with ${sso?.label??"your identity provider"}: passwords are only for instance operators here. Nothing changed.`:"The account changed while you were typing. Nothing changed; run `toolroll password reset` again.",before=passwordResetRefusal(store,account,operatorsOnly);if(before!==null)return fail(write,json,command,before,refusalWords(before),EXIT.refused);const generation=store.accountOf(account).generation;write(`Reset the password for ${account}.`),write(`This ends ${account}'s browser sessions and remembered passwords, the terminal UI's sign-in, paired chats, phone notifications, lead sessions and lead tokens (mint a new one with \`toolroll lead token\`).`),write("It keeps API and MCP tokens (revoke them in Settings → Sessions & tokens) and coordinator credentials (`toolroll coordinator revoke`). Revoke those too if someone else may know the old password.");const typeHidden=context.easySeams?.askHidden??askHidden,chosen=await typeHidden("New password: ");if(chosen.length<8)return fail(write,json,command,"weak-password","A password needs at least 8 characters. Nothing changed.",EXIT.refused);if(await typeHidden("Type it again: ")!==chosen)return fail(write,json,command,"mismatch","The two passwords didn't match. Nothing changed.",EXIT.refused);const reset=resetAccountPassword(store,account,hashPassword(chosen),generation,operatorsOnly,context.clock());if(!reset.ok)return fail(write,json,command,reset.reason,refusalWords(reset.reason),EXIT.refused);const cleanup=removeStaleSavedLogin(dirname(context.databaseFile),account,chosen),{shownPath}=await import("./server/login-help.js"),shown=path=>shownPath(path,homedir(),null)??path;return succeed(write,json,command,{account,generation:reset.generation,removed:cleanup.removed},()=>[`Password reset for ${account}. Every session of ${account} has ended; sign in with the new password.`,...reset.leadTokens>0?[`${account}'s lead token ended: mint a new one with \`toolroll lead token\`.`]:[],...cleanup.removed.map(path=>`Removed ${shown(path)}: it held the old password.`),...cleanup.stale.map(path=>`The saved first password at ${shown(path)} no longer works; delete it yourself.`),...cleanup.unchecked.map(path=>`${shown(path)} isn't a plain file in Toolroll's folder, so it was left alone. If it holds ${account}'s old password, delete it yourself.`)])}function shellCallerFacts(context){return{json:context.json,agent:context.easySeams?.agent??underAgent(process.env),terminal:context.easySeams?.terminal??(process.stdin.isTTY===!0&&process.stdout.isTTY===!0)}}async function projectFlexibleCommand(positional,flags,context){const action=positional[1]??"show",command=`project flexible ${action}`,{write,json}=context,own={show:[],enable:["max","default","digest"],lower:["max"],off:[]}[action];if(own===void 0||positional.length>2)return fail(write,json,command,"usage","Use project flexible [show | enable [--max <level>] [--default <level>] [--digest <d>] | lower --max <level> | off] --repo <project path>.",EXIT.usage);const allowed=new Set(["repo","db","json",...own,...action==="show"?[]:["as","token","token-file","token-env"]]);for(const name of flags.keys())if(!allowed.has(name))return fail(write,json,command,"usage",`--${name} is not a project flexible ${action} option.`,EXIT.usage);const repoFlag=text(flags,"repo");if(repoFlag===void 0)return fail(write,json,command,"usage","Name the project with --repo <path>.",EXIT.usage);const level=name=>{const value=text(flags,name);return value===void 0?void 0:isFlexibleLevel(value)?value:null},max=level("max"),chosenDefault=level("default");if(max===null||chosenDefault===null)return fail(write,json,command,"usage","A level is supervised, auto or full.",EXIT.usage);const repo=await knownProject(context,repoFlag,{listed:!0,canonical:!0});if(repo===void 0)return fail(write,json,command,"not-found","That isn't a project Toolroll knows.",EXIT.refused);const store=context.store,termsLines=(terms,digest)=>[...flexibleTermsWords(terms),`Terms ${digest}`],shown=standing=>{if(standing.state==="secure")return{data:{state:"secure"},lines:[`${repo}: Secure. Work is planned and approved before it starts.`]};if(standing.state==="unreadable")return{data:{state:"unreadable"},lines:[`${repo}: its thread terms can't be read, so they allow nothing. Turn interactive agent threads off for it, then on again.`]};const data={state:standing.state,digest:standing.digest,terms:standing.terms,signedBy:standing.signedBy,signedAt:standing.signedAt,...standing.state==="lapsed"?{lapse:standing.reason}:{}};return standing.state==="lapsed"?{data,lines:[`${repo}: Flexible terms no longer count. ${FLEXIBLE_LAPSE_WORDS[standing.reason]} Turn it on again to sign new terms.`]}:{data,lines:[`${repo}: interactive agent threads are on, turned on by ${standing.signedBy}.`,...termsLines(standing.terms,standing.digest)]}};if(action==="show"){const now=shown(flexibleStanding(store,repo));return succeed(write,json,command,{repo,flexible:now.data},()=>now.lines)}const refused=message=>fail(write,json,command,"person-only",message,EXIT.refused);if(machineActing()||process.env.TOOLROLL_LEAD_TOKEN!==void 0||process.env.TOOLROLL_REMOTE_TOKEN!==void 0)return refused("Only a person changes a project's thread terms, never the lead, a token or a chat app.");const acting=await askCredentials(flags,context);if(acting===null)return refused(action==="enable"?"Turning on interactive agent threads needs your Toolroll password: run it again with `--as <your name>` and type the password when asked (`--token` is that password, only for scripts: it stays in shell history). Or turn them on in the browser, on the project's page in Settings.":"This needs your sign-in: run it again with `--as <your name>` and type your Toolroll password when asked.");if(action==="enable"){if(!flexibleAvailable(store))return fail(write,json,command,"not-available",FLEXIBLE_UNAVAILABLE,EXIT.refused);const proved2=credentialApprover(store,acting.name,acting.token,repo);if(!proved2.ok)return refused("Only an approver of this project, with their password typed now, turns on interactive agent threads.");const choice={...max===void 0?{}:{max},...chosenDefault===void 0?{}:{default:chosenDefault}},proposed=proposedFlexibleTerms(store,repo,acting.name,choice);if(!proposed.ok)return fail(write,json,command,proposed.reason,proposed.message,EXIT.refused);let digest=text(flags,"digest");if(digest===void 0){if(!interactive()||json)return fail(write,json,command,"review-terms",[...termsLines(proposed.terms,proposed.digest),`Read these terms, then run again with --digest ${proposed.digest} to agree to them. Nothing changed.`].join(`
|
|
508
508
|
`),EXIT.refused,{digest:proposed.digest,terms:proposed.terms});if(write(termsLines(proposed.terms,proposed.digest).join(`
|