@amistio/cli 0.1.36 → 0.1.37

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/dist/index.js.map DELETED
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../src/index.ts", "../../shared/src/schemas.ts", "../../shared/src/api-url.ts", "../../shared/src/brain-documents.ts", "../../shared/src/repo-metadata.ts", "../../shared/src/repository-link.ts", "../../shared/src/sync.ts", "../../shared/src/next-action.ts", "../src/bootstrap.ts", "../src/credential-store.ts", "../src/control-plane.ts", "../src/api-client.ts", "../src/orchestrator.ts", "../src/result-finalization-outbox.ts", "../src/local-tool-runner.ts", "../src/runner-daemon.ts", "../src/runner-service.ts", "../src/tool-session-lifecycle.ts", "../src/session-policy.ts", "../src/runner-activation-smoke.ts", "../src/sync.ts", "../src/tool-session-store.ts", "../src/work-runner.ts", "../src/runner-status.ts", "../src/runner-resources.ts", "../src/importer.ts", "../src/runner-actions.ts", "../src/git-worktree.ts", "../src/implementation-handoff.ts", "../src/version.ts"],
4
- "sourcesContent": ["#!/usr/bin/env node\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { writeFile } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { Command } from \"commander\";\nimport { AMISTIO_API_URL_ENV, computeProjectNextAction, formatProjectNextAction, isOfficialAmistioApiUrl, officialAmistioApiUrl, parseRepositoryCloneUrl, type GeneratedBrainArtifact, type ImplementationHandoff, type ImplementationHandoffRecoveryAction, type ProjectNextAction, type RepoLinkMetadata, type RepositoryLinkItem, type RunnerCommandItem, type RunnerCommandKind, type RunnerEffectiveInvocationChannel, type RunnerInvocationChannel, type RunnerPreferenceSource, type RunnerPreferenceStatus, type RunnerReasoningEffort, type RunnerToolCapability, type RunnerToolName, type RunnerToolSelection, type SessionDecision, type SessionPolicy, type SessionResumabilityScope, type ToolSessionItem, type WorkItem, type WorkKind, type WorkStatus } from \"@amistio/shared\";\nimport { cloneOrValidateRepository } from \"./bootstrap.js\";\nimport { credentialKey, LocalCredentialStore } from \"./credential-store.js\";\nimport { initControlPlane, inspectControlPlane, readProjectLink, resolvePairingRoot, writeProjectLink } from \"./control-plane.js\";\nimport { AmistioApiError, ApiClient, isRetryableApiError, type ActivityEventMutation, type AppEvaluationScanResultMutation, type AssistantResultMutation, type BrainConsolidationScanResultMutation, type BrainGenerationResultMutation, type ImpactPreviewResultMutation, type ImplementationTestGateResultMutation, type ImplementationVerificationResultMutation, type IssueDiagnosisResultMutation, type ProjectContextRefreshResultMutation, type RunnerHeartbeatMetadata, type ProjectContextResponse, type SecurityPostureScanResultMutation, type TestQualityScanResultMutation, type WorkStatusTelemetry } from \"./api-client.js\";\nimport { createOrchestrationPrompt, writePromptFile } from \"./orchestrator.js\";\nimport { createBrainGenerationFinalizationEntry, createDurableResultFinalizationEntry, deleteBrainGenerationFinalizationEntry, deleteDurableResultFinalizationEntry, listPendingBrainGenerationFinalizations, listPendingDurableResultFinalizations, markBrainGenerationFinalizationRetry, markBrainGenerationFinalizationTerminal, markDurableResultFinalizationRetry, markDurableResultFinalizationTerminal, upsertBrainGenerationFinalizationEntry, upsertDurableResultFinalizationEntry, type BrainGenerationFinalizationEntry, type BrainGenerationFinalizationScope, type BrainGenerationFinalizationWorkKind, type DurableResultFinalizationEntry, type DurableResultFinalizationResult, type DurableResultFinalizationResultKind, type DurableResultFinalizationWorkKind } from \"./result-finalization-outbox.js\";\nimport { createToolRunPreview, detectLocalTools, isLocalToolName, runLocalTool, type DetectedLocalTool, type LocalToolRunResult } from \"./local-tool-runner.js\";\nimport { currentRunnerMode, listRunnerDaemonMetadata, markRunnerDaemonStopped, restartRunnerDaemonProcess, runnerDaemonRuntimeStatus, runnerDaemonUptime, startRunnerDaemon, stopRunnerDaemonProcess, updatedCliRunnerLaunchOptions } from \"./runner-daemon.js\";\nimport { createRunnerServiceDescriptor, detectRunnerServicePlatform, installRunnerService, readRunnerServiceMetadata, removeRunnerService, runnerServiceRuntimeStatus } from \"./runner-service.js\";\nimport { runRunnerActivationSmoke } from \"./runner-activation-smoke.js\";\nimport { normalizeSessionPolicy, selectToolSession } from \"./session-policy.js\";\nimport { collectAutoSyncDocumentsForPush, collectDirtyDocumentsForPush, collectSyncStatus, materializeBrainDocuments, type AutoSyncPushCollection } from \"./sync.js\";\nimport { completedToolSessionClosedReason, completedToolSessionStatus, staleToolSessionClosedReason } from \"./tool-session-lifecycle.js\";\nimport { LocalToolSessionStore } from \"./tool-session-store.js\";\nimport { createWorkExecutionPrompt, parseAppEvaluationScanResult, parseAssistantAnswerResult, parseBrainConsolidationScanResult, parseBrainGenerationArtifacts, parseImpactPreviewResult, parseImplementationTestGateResult, parseImplementationVerificationResult, parseIssueDiagnosisResult, parseProjectContextRefreshResult, parseSecurityPostureScanResult, parseTestQualityScanResult, projectContextRefreshSubmissionFailureSummary } from \"./work-runner.js\";\nimport { formatWatchIdleLine, formatWatchStartupContext, shouldPrintWatchState, stableRunnerId, watchStateKey, type WatchStateLog } from \"./runner-status.js\";\nimport { formatRunnerResourceUsage, sampleCurrentRunnerResourceUsage } from \"./runner-resources.js\";\nimport { buildImportedBrainDocuments, importSkipCounts, inspectLocalRepository, scanLegacyDocuments } from \"./importer.js\";\nimport { buildBackgroundRunnerArgs, runOfficialCliUpdateWithRuntimeRefresh } from \"./runner-actions.js\";\nimport { needsGitWorktreeIsolation, prepareGitWorktreeIsolation, resolveExistingGitWorktreeIsolation, resolveWorktreeIdentity, type GitWorktreeIsolation } from \"./git-worktree.js\";\nimport { cleanupImplementationWorktree, completeImplementationHandoff } from \"./implementation-handoff.js\";\nimport { CLI_VERSION } from \"./version.js\";\n\nconst program = new Command();\nconst defaultRoot = process.env.INIT_CWD ?? process.cwd();\nconst apiUrlOptionDescription = `Amistio API URL override (or ${AMISTIO_API_URL_ENV})`;\nconst DEFAULT_MAX_PREFLIGHT_ATTEMPTS = 3;\nconst DEFAULT_TOOL_TIMEOUT_SECONDS = 30 * 60;\nconst RUNNER_WORK_LEASE_SECONDS = 300;\nconst RUNNER_WORK_LEASE_RENEWAL_MS = 120_000;\nconst MAX_CONCURRENT_RUNNER_WORK = 4;\nconst runnerSupportedWorkKinds: WorkKind[] = [\"brainGeneration\", \"implementation\", \"planRevision\", \"assistantQuestion\", \"impactPreview\", \"issueDiagnosis\", \"securityPostureScan\", \"appEvaluationScan\", \"brainConsolidationScan\", \"projectContextRefresh\", \"implementationVerification\", \"testQualityScan\", \"implementationTestGate\"];\n\nprogram.name(\"amistio\").description(\"Amistio project brain CLI\").version(CLI_VERSION);\n\nprogram\n .command(\"init\")\n .description(\"Create Amistio control-plane folders for a new project\")\n .option(\"--root <path>\", \"Repository root\", defaultRoot)\n .action(async (options: { root: string }) => {\n const created = await initControlPlane(options.root);\n console.log(created.length ? `Created ${created.length} control-plane folders.` : \"Control-plane folders already exist.\");\n });\n\nprogram\n .command(\"onboard\")\n .description(\"Inspect and prepare an existing repository for Amistio\")\n .option(\"--root <path>\", \"Repository root\", defaultRoot)\n .action(async (options: { root: string }) => {\n const result = await inspectControlPlane(options.root);\n console.log(`Present: ${result.present.length ? result.present.join(\", \") : \"none\"}`);\n console.log(`Missing: ${result.missing.length ? result.missing.join(\", \") : \"none\"}`);\n if (result.missing.length) {\n console.log(\"Run `amistio init` to create missing control-plane folders without overwriting existing files.\");\n }\n });\n\nprogram\n .command(\"bootstrap\")\n .description(\"Clone a linked repository locally, prepare the control plane, and pair it with Amistio\")\n .requiredOption(\"--repo-url <url>\", \"Linked repository clone URL\")\n .requiredOption(\"--target <path>\", \"Local checkout target path\")\n .requiredOption(\"--account <accountId>\", \"Amistio account ID\")\n .requiredOption(\"--project <projectId>\", \"Amistio project ID\")\n .requiredOption(\"--repository-link <repositoryLinkId>\", \"Existing repository link ID\")\n .option(\"--api-url <url>\", apiUrlOptionDescription, defaultApiUrl())\n .requiredOption(\"--pairing-code <code>\", \"Short-lived pairing code from the Amistio app\")\n .option(\"--default-branch <branch>\", \"Default branch\", \"main\")\n .action(async (options: { repoUrl: string; target: string; account: string; project: string; repositoryLink: string; apiUrl: string; pairingCode: string; defaultBranch: string }) => {\n const parsedRepoUrl = parseRepositoryCloneUrl(options.repoUrl);\n const checkout = await cloneOrValidateRepository({ repoUrl: parsedRepoUrl.cloneUrl, targetDir: options.target });\n await initControlPlane(checkout.targetDir);\n\n const pairing = await new ApiClient({\n apiUrl: options.apiUrl,\n accountId: options.account\n }).consumePairingSession({\n projectId: options.project,\n pairingCode: options.pairingCode,\n repositoryLinkId: options.repositoryLink,\n repoName: parsedRepoUrl.repoName,\n repoFingerprint: createRepoFingerprint(options.account, options.project, options.repositoryLink),\n defaultBranch: options.defaultBranch,\n machineId: runnerMachineId()\n });\n\n const filePath = await writeProjectLink(checkout.targetDir, {\n amistioAccountId: options.account,\n amistioProjectId: options.project,\n repositoryLinkId: pairing.repositoryLink.repositoryLinkId,\n defaultBranch: options.defaultBranch,\n lastSyncedRevision: 0\n });\n\n await new LocalCredentialStore().set(credentialKey(options.account, options.project, pairing.repositoryLink.repositoryLinkId), pairing.token);\n\n console.log(checkout.status === \"cloned\" ? `Cloned repository to ${checkout.targetDir}.` : `Validated existing checkout at ${checkout.targetDir}.`);\n console.log(`Pairing confirmed for ${pairing.repositoryLink.repoName}.`);\n console.log(`Wrote non-secret project metadata to ${filePath}.`);\n console.log(`Next: cd ${formatShellArg(checkout.targetDir)} && amistio run${formatApiUrlFlag(options.apiUrl)} --watch`);\n });\n\nprogram\n .command(\"import\")\n .description(\"Pair an existing checkout and import legacy Markdown docs as accepted brain records\")\n .argument(\"[code]\", \"Short-lived pairing code from the Amistio app\")\n .option(\"--pairing-code <code>\", \"Short-lived pairing code from the Amistio app\")\n .option(\"--root <path>\", \"Repository root\", defaultRoot)\n .option(\"--api-url <url>\", apiUrlOptionDescription, defaultApiUrl())\n .option(\"--default-branch <branch>\", \"Default branch fallback\", \"main\")\n .option(\"--include <glob>\", \"Only import files matching a repo-relative glob\", collectRepeatedOption, [] as string[])\n .option(\"--exclude <glob>\", \"Exclude files matching a repo-relative glob\", collectRepeatedOption, [] as string[])\n .option(\"--max-file-kb <kb>\", \"Maximum Markdown file size to import\", parsePositiveInteger, 256)\n .option(\"--dry-run\", \"Inspect and print import candidates without consuming the code or uploading documents\")\n .action(async (code: string | undefined, options: { pairingCode?: string; root: string; apiUrl: string; defaultBranch: string; include: string[]; exclude: string[]; maxFileKb: number; dryRun?: boolean }) => {\n const pairingCode = (options.pairingCode ?? code)?.trim();\n if (!pairingCode) {\n throw new Error(\"Provide a pairing code as `amistio import <code>` or with `--pairing-code <code>`.\");\n }\n\n const repository = await inspectLocalRepository(options.root, options.defaultBranch);\n const scan = await scanLegacyDocuments({\n rootDir: repository.rootDir,\n include: options.include,\n exclude: options.exclude,\n maxFileKb: options.maxFileKb\n });\n const skipCounts = importSkipCounts(scan.skipped);\n\n console.log(`Repository: ${repository.repoName}`);\n console.log(`Root: ${repository.rootDir}`);\n console.log(`Default branch: ${repository.defaultBranch}`);\n if (repository.originRemoteWarning) {\n console.log(repository.originRemoteWarning);\n }\n console.log(`Import candidates: ${scan.candidates.length}`);\n console.log(formatImportSkipSummary(skipCounts));\n for (const candidate of scan.candidates.slice(0, 12)) {\n console.log(`- ${candidate.sourcePath} -> ${candidate.repoPath} (${candidate.documentType})`);\n }\n if (scan.candidates.length > 12) {\n console.log(`...and ${scan.candidates.length - 12} more.`);\n }\n\n if (options.dryRun) {\n console.log(\"Dry run complete. No pairing code was consumed and no files or Amistio records were written.\");\n return;\n }\n\n const parsedCloneUrl = repository.parsedCloneUrl;\n const pairing = await new ApiClient({ apiUrl: options.apiUrl }).importPairingSession({\n pairingCode,\n repoName: repository.repoName,\n repoFingerprint: repository.repoFingerprint,\n defaultBranch: repository.defaultBranch,\n machineId: runnerMachineId(),\n ...(parsedCloneUrl ? { cloneUrl: parsedCloneUrl.cloneUrl } : {}),\n ...(parsedCloneUrl?.provider ? { provider: parsedCloneUrl.provider } : {}),\n ...(parsedCloneUrl?.repoOwner ? { repoOwner: parsedCloneUrl.repoOwner } : {}),\n ...(parsedCloneUrl?.repoFullName ? { repoFullName: parsedCloneUrl.repoFullName } : {})\n });\n\n await initControlPlane(repository.rootDir);\n const metadataFilePath = await writeProjectLink(repository.rootDir, {\n amistioAccountId: pairing.accountId,\n amistioProjectId: pairing.projectId,\n repositoryLinkId: pairing.repositoryLink.repositoryLinkId,\n defaultBranch: repository.defaultBranch,\n lastSyncedRevision: 0\n });\n await new LocalCredentialStore().set(credentialKey(pairing.accountId, pairing.projectId, pairing.repositoryLink.repositoryLinkId), pairing.token);\n\n const authenticatedClient = new ApiClient({ apiUrl: options.apiUrl, accountId: pairing.accountId, token: pairing.token });\n const { documents: existingDocuments } = await authenticatedClient.listBrainDocuments(pairing.projectId);\n const documents = buildImportedBrainDocuments({\n accountId: pairing.accountId,\n projectId: pairing.projectId,\n repositoryLinkId: pairing.repositoryLink.repositoryLinkId,\n candidates: scan.candidates,\n existingDocuments\n });\n\n if (documents.length) {\n await authenticatedClient.pushBrainDocuments(pairing.projectId, documents);\n }\n\n console.log(`Pairing confirmed for ${pairing.repositoryLink.repoName}; repository link ${pairing.repositoryLinkAction}.`);\n console.log(`Wrote non-secret project metadata to ${metadataFilePath}.`);\n console.log(`Imported ${documents.length} legacy document${documents.length === 1 ? \"\" : \"s\"} as accepted brain record${documents.length === 1 ? \"\" : \"s\"}.`);\n console.log(`Next: amistio sync status${formatApiUrlFlag(options.apiUrl)}`);\n });\n\nprogram\n .command(\"pair\")\n .description(\"Pair this repository with an Amistio web project\")\n .requiredOption(\"--account <accountId>\", \"Amistio account ID\")\n .requiredOption(\"--project <projectId>\", \"Amistio project ID\")\n .option(\"--repository-link <repositoryLinkId>\", \"Existing repository link ID\")\n .option(\"--default-branch <branch>\", \"Default branch\", \"main\")\n .option(\"--api-url <url>\", apiUrlOptionDescription, defaultApiUrl())\n .option(\"--pairing-code <code>\", \"Short-lived pairing code from the Amistio app\")\n .option(\"--token <token>\", \"Runner/device credential to store outside the repository\")\n .option(\"--root <path>\", \"Repository root\", defaultRoot)\n .action(async (options: { account: string; project: string; repositoryLink?: string; defaultBranch: string; apiUrl: string; pairingCode?: string; token?: string; root: string }, command: Command) => {\n const pairingRoot = await resolvePairingRoot(options.root, { explicitRoot: command.getOptionValueSource(\"root\") === \"cli\" });\n let repositoryLinkId = options.repositoryLink ?? `repo_${randomUUID()}`;\n let credential = options.token;\n\n if (options.pairingCode) {\n const pairing = await new ApiClient({\n apiUrl: options.apiUrl,\n accountId: options.account,\n ...(credential ? { token: credential } : {})\n }).consumePairingSession({\n projectId: options.project,\n pairingCode: options.pairingCode,\n repositoryLinkId,\n repoName: inferRepoName(pairingRoot),\n repoFingerprint: createRepoFingerprint(options.account, options.project, repositoryLinkId),\n defaultBranch: options.defaultBranch,\n machineId: runnerMachineId()\n });\n repositoryLinkId = pairing.repositoryLink.repositoryLinkId;\n credential = credential ?? pairing.token;\n console.log(`Pairing confirmed for ${pairing.repositoryLink.repoName}.`);\n }\n\n const filePath = await writeProjectLink(pairingRoot, {\n amistioAccountId: options.account,\n amistioProjectId: options.project,\n repositoryLinkId,\n defaultBranch: options.defaultBranch,\n lastSyncedRevision: 0\n });\n\n if (credential) {\n await new LocalCredentialStore().set(credentialKey(options.account, options.project, repositoryLinkId), credential);\n }\n\n if (!options.pairingCode && apiUrlOverrideWasRequested(command)) {\n const session = await new ApiClient({\n apiUrl: options.apiUrl,\n accountId: options.account,\n ...(credential ? { token: credential } : {})\n }).createPairingSession(options.project);\n console.log(`Pairing code: ${session.pairingCode}`);\n console.log(`Expires at: ${session.expiresAt}`);\n }\n\n console.log(`Wrote non-secret project metadata to ${filePath}.`);\n });\n\nconst sync = program.command(\"sync\").description(\"Inspect or move project brain changes between the repo and Amistio\");\n\nsync\n .command(\"status\")\n .description(\"Show local sync status\")\n .option(\"--api-url <url>\", apiUrlOptionDescription, defaultApiUrl())\n .option(\"--root <path>\", \"Repository root\", defaultRoot)\n .action(async (options: { apiUrl: string; root: string }) => {\n const metadata = await readProjectLink(options.root);\n if (!metadata) {\n console.log(\"Repository is not paired. Run `amistio pair` first.\");\n return;\n }\n const context = await loadPairedApiContext(options.root, options.apiUrl);\n const webDocuments = context ? await context.client.listBrainDocuments(metadata.amistioProjectId).then((result) => result.documents).catch(() => []) : [];\n const report = await collectSyncStatus(options.root, webDocuments);\n console.log(`Paired project: ${metadata.amistioProjectId}`);\n console.log(`Repository link: ${metadata.repositoryLinkId}`);\n console.log(`Last synced revision: ${metadata.lastSyncedRevision}`);\n console.log(`Sync status: ${report.status}`);\n console.log(`Clean: ${report.counts.clean}; Pending: ${report.counts.pending}; Dirty: ${report.counts.dirty}; Conflicted: ${report.counts.conflicted}`);\n for (const item of report.items.filter((entry) => entry.status !== \"clean\")) {\n console.log(`${item.status}: ${item.repoPath} - ${item.reason}`);\n }\n });\n\nsync\n .command(\"pull\")\n .description(\"Pull approved web changes into the repository\")\n .option(\"--api-url <url>\", apiUrlOptionDescription, defaultApiUrl())\n .option(\"--root <path>\", \"Repository root\", defaultRoot)\n .action(async (options: { apiUrl: string; root: string }) => {\n const context = await loadPairedApiContext(options.root, options.apiUrl);\n if (!context) {\n console.log(\"Repository is not paired. Run `amistio pair` first.\");\n return;\n }\n\n const { documents } = await context.client.listBrainDocuments(context.metadata.amistioProjectId);\n const approvedDocuments = documents.filter((document) => document.syncState === \"approved\" || document.syncState === \"synced\");\n const result = await materializeBrainDocuments(options.root, approvedDocuments);\n for (const conflict of result.conflicts) {\n console.log(`conflicted: ${conflict}`);\n }\n if (result.conflicts.length) {\n process.exitCode = 1;\n return;\n }\n\n const latestRevision = Math.max(context.metadata.lastSyncedRevision, ...approvedDocuments.map((document) => document.revision));\n if (latestRevision !== context.metadata.lastSyncedRevision) {\n await writeProjectLink(options.root, { ...context.metadata, lastSyncedRevision: latestRevision });\n }\n console.log(result.written.length ? `Pulled ${result.written.length} approved document${result.written.length === 1 ? \"\" : \"s\"}.` : \"No approved web changes were pulled.\");\n });\n\nsync\n .command(\"push\")\n .description(\"Push local brain changes to Amistio for review\")\n .option(\"--api-url <url>\", apiUrlOptionDescription, defaultApiUrl())\n .option(\"--root <path>\", \"Repository root\", defaultRoot)\n .action(async (options: { apiUrl: string; root: string }) => {\n const context = await loadPairedApiContext(options.root, options.apiUrl);\n if (!context) {\n console.log(\"Repository is not paired. Run `amistio pair` first.\");\n return;\n }\n\n const dirtyDocuments = await collectDirtyDocumentsForPush(options.root, context.metadata);\n if (!dirtyDocuments.length) {\n console.log(\"No local brain changes were pushed.\");\n return;\n }\n\n const { documents } = await context.client.pushBrainDocuments(context.metadata.amistioProjectId, dirtyDocuments);\n const conflictedDocuments = documents.filter((document) => document.syncState === \"conflicted\" || document.status === \"conflicted\");\n if (conflictedDocuments.length) {\n for (const document of conflictedDocuments) {\n console.log(`conflicted: ${document.repoPath} - web and repository revisions both changed`);\n }\n process.exitCode = 1;\n return;\n }\n await materializeBrainDocuments(options.root, documents, { allowDirtyOverwrite: true });\n console.log(`Pushed ${documents.length} local document${documents.length === 1 ? \"\" : \"s\"} for web review.`);\n });\n\nsync\n .command(\"watch\")\n .description(\"Watch repository brain folders and auto-sync eligible local changes\")\n .option(\"--api-url <url>\", apiUrlOptionDescription, defaultApiUrl())\n .option(\"--root <path>\", \"Repository root\", defaultRoot)\n .option(\"--runner-id <runnerId>\", \"Stable watcher runner ID\")\n .option(\"--interval-seconds <seconds>\", \"Polling interval\", parsePositiveInteger, 10)\n .option(\"--max-iterations <count>\", \"Stop watch mode after this many polling attempts\", parsePositiveInteger)\n .option(\"--max-file-kb <kb>\", \"Maximum Markdown/MDX file size to auto-sync\", parsePositiveInteger, 256)\n .option(\"--once\", \"Run one auto-sync cycle and exit\")\n .action(async (options: { apiUrl: string; root: string; runnerId?: string; intervalSeconds: number; maxIterations?: number; maxFileKb: number; once?: boolean }) => {\n const context = await loadPairedApiContext(options.root, options.apiUrl);\n if (!context) {\n console.log(\"Repository is not paired. Run `amistio pair` first.\");\n return;\n }\n if (!context.token) {\n console.log(\"No local runner credential found. Run `amistio pair --pairing-code <code>` to store this machine credential.\");\n process.exitCode = 1;\n return;\n }\n\n const runnerId = options.runnerId ?? stableRunnerId({\n accountId: context.metadata.amistioAccountId,\n projectId: context.metadata.amistioProjectId,\n repositoryLinkId: context.metadata.repositoryLinkId,\n machineId: runnerMachineId()\n });\n console.log(`Auto-sync watcher: ${runnerId}`);\n console.log(`Project: ${context.metadata.amistioProjectId}`);\n console.log(`Repository link: ${context.metadata.repositoryLinkId}`);\n\n let iterations = 0;\n while (true) {\n iterations += 1;\n const result = await runAutoSyncCycle({\n context,\n maxFileKb: options.maxFileKb,\n quietDisabled: false,\n root: options.root,\n runnerId\n });\n console.log(formatAutoSyncCycleResult(result));\n\n if (options.once || result.status === \"disabled\") return;\n if (options.maxIterations !== undefined && iterations >= options.maxIterations) {\n console.log(`Auto-sync watcher stopped after ${iterations} polling attempt${iterations === 1 ? \"\" : \"s\"}.`);\n return;\n }\n await delay(options.intervalSeconds * 1000);\n }\n });\n\nconst work = program.command(\"work\").description(\"Inspect approved work items\");\n\nwork\n .command(\"list\")\n .description(\"List queued work without claiming it\")\n .option(\"--api-url <url>\", apiUrlOptionDescription, defaultApiUrl())\n .option(\"--root <path>\", \"Repository root\", defaultRoot)\n .action(async (options: { apiUrl: string; root: string }) => {\n const context = await loadPairedApiContext(options.root, options.apiUrl);\n if (!context) {\n console.log(\"Repository is not paired. Run `amistio pair` first.\");\n return;\n }\n\n const [{ workItems }, { documents }, { runners }] = await Promise.all([\n context.client.listWorkItems(context.metadata.amistioProjectId),\n context.client.listBrainDocuments(context.metadata.amistioProjectId),\n context.client.listRunners(context.metadata.amistioProjectId).catch(() => ({ runners: [] }))\n ]);\n const nextAction = computeProjectNextAction({\n projectId: context.metadata.amistioProjectId,\n repositoryLinks: [createCliRepositoryLink(context.metadata, options.root)],\n documents,\n workItems,\n runnerHeartbeats: runners\n });\n console.log(`Next action: ${formatProjectNextAction(nextAction)}`);\n if (!workItems.length) {\n console.log(\"No work items are queued for this project.\");\n return;\n }\n\n for (const item of workItems) {\n console.log(`${item.workItemId} [${item.status}] ${item.title}${formatAutopilotListSuffix(item)}`);\n }\n });\n\nwork\n .command(\"prompt\")\n .description(\"Print or write an approved work prompt without claiming a runner lease\")\n .argument(\"[workItemId]\", \"Work item ID. Defaults to the newest approved work item.\")\n .option(\"--api-url <url>\", apiUrlOptionDescription, defaultApiUrl())\n .option(\"--root <path>\", \"Repository root\", defaultRoot)\n .option(\"--out <path>\", \"Write the prompt to a file instead of stdout\")\n .action(async (workItemId: string | undefined, options: { apiUrl: string; root: string; out?: string }) => {\n const context = await loadPairedApiContext(options.root, options.apiUrl);\n if (!context) {\n console.log(\"Repository is not paired. Run `amistio pair` first.\");\n return;\n }\n\n const { workItems } = await context.client.listWorkItems(context.metadata.amistioProjectId);\n const workItem = selectPromptWorkItem(workItems, workItemId);\n if (!workItem) {\n console.log(workItemId ? `No work item found for ${workItemId}.` : \"No approved work item is ready for prompt export.\");\n return;\n }\n\n const prompt = await createRunnerWorkPrompt(context.client, context.metadata.amistioProjectId, workItem);\n if (options.out) {\n await writeFile(options.out, prompt, \"utf8\");\n console.log(`Wrote work prompt to ${options.out}.`);\n } else {\n console.log(prompt);\n }\n });\n\nprogram\n .command(\"tools\")\n .description(\"List local AI coding tools that the Amistio CLI can use\")\n .action(async () => {\n const tools = await detectLocalTools();\n for (const tool of tools) {\n const mode = tool.execution === \"sdk\" ? \"sdk\" : tool.execution === \"command\" ? \"cli\" : \"--\";\n console.log(`${tool.available ? \"yes\" : \"no \"} ${mode} ${tool.name} - ${tool.description}`);\n }\n console.log(\"custom - pass --tool-command to use any other local runner command.\");\n });\n\nprogram\n .command(\"orchestrate\")\n .description(\"Update the Amistio control plane through a user-installed local AI tool\")\n .argument(\"[goal...]\", \"Goal or next-step instruction for the orchestration pass\")\n .option(\"--root <path>\", \"Repository root\", defaultRoot)\n .option(\"--tool <name>\", \"Local tool to use: auto, none, opencode, claude, codex, copilot, gemini, aider, cursor-agent\", \"auto\")\n .option(\"--invocation-channel <channel>\", \"Local invocation channel: auto, sdk, or command\", parseInvocationChannel, \"auto\")\n .option(\"--model <model>\", \"Model to request when the selected local tool supports model selection\")\n .option(\"--provider <providerId>\", \"Provider id for provider-backed model configuration\")\n .option(\"--model-id <modelId>\", \"Provider catalog model id to request\")\n .option(\"--model-variant <variant>\", \"Provider catalog model variant to request\")\n .option(\"--reasoning-effort <effort>\", \"Reasoning effort: auto, low, medium, high, or xhigh\", parseReasoningEffort)\n .option(\"--tool-command <command>\", \"Custom local command. Use {promptFile} and {root} placeholders when supported\")\n .option(\"--session <policy>\", \"Tool session policy: auto, new, continue:<toolSessionId>, or none\", \"auto\")\n .option(\"--prompt-out <path>\", \"Write the generated orchestration prompt to a file before running\")\n .option(\"--dry-run\", \"Print the generated orchestration prompt without running a tool\")\n .option(\"--no-stream\", \"Capture local tool output instead of streaming it\")\n .action(async (goalParts: string[] | undefined, options: { root: string; tool: string; invocationChannel: RunnerInvocationChannel; toolCommand?: string; model?: string; provider?: string; modelId?: string; modelVariant?: string; reasoningEffort?: RunnerReasoningEffort; session: string; promptOut?: string; dryRun?: boolean; stream: boolean }) => {\n const goal = goalParts?.join(\" \").trim() || \"Review the current repository state and update the Amistio control plane with the next useful orchestration steps.\";\n const prompt = await createOrchestrationPrompt({ rootDir: options.root, goal });\n\n if (options.promptOut) {\n const promptPath = await writePromptFile(options.promptOut, prompt);\n console.log(`Wrote orchestration prompt to ${promptPath}.`);\n }\n\n if (options.dryRun || options.tool === \"none\") {\n console.log(prompt);\n return;\n }\n\n const sessionPolicy = normalizeSessionPolicy(options.session);\n const localModelConfig = localModelConfigOptions(options);\n const preview = await createToolRunPreview({ rootDir: options.root, prompt, tool: options.tool, invocationChannel: options.invocationChannel, ...(options.toolCommand ? { toolCommand: options.toolCommand } : {}), ...localModelConfig });\n console.log(`Running ${preview.toolName}: ${preview.displayCommand}`);\n const result = await runLocalTool({\n rootDir: options.root,\n prompt,\n tool: options.tool,\n invocationChannel: options.invocationChannel,\n ...(options.toolCommand ? { toolCommand: options.toolCommand } : {}),\n ...localModelConfig,\n streamOutput: options.stream,\n ...(sessionPolicy === \"none\" ? {} : { session: { toolSessionId: `local_orchestration_${randomUUID()}`, policy: sessionPolicy, decision: localSessionDecision(sessionPolicy) } })\n });\n if (!options.stream && result.stdout.trim()) {\n console.log(result.stdout.trim());\n }\n if (!options.stream && result.stderr.trim()) {\n console.error(result.stderr.trim());\n }\n if (result.exitCode !== 0) {\n process.exitCode = result.exitCode;\n }\n });\n\nprogram\n .command(\"run\")\n .description(\"Claim and run approved Amistio work locally\")\n .option(\"--api-url <url>\", apiUrlOptionDescription, defaultApiUrl())\n .option(\"--runner-id <runnerId>\", \"Stable runner ID\")\n .option(\"--root <path>\", \"Repository root\", defaultRoot)\n .option(\"--tool <name>\", \"Local tool to use: auto, none, opencode, claude, codex, copilot, gemini, aider, cursor-agent\")\n .option(\"--invocation-channel <channel>\", \"Local invocation channel: auto, sdk, or command\", parseInvocationChannel)\n .option(\"--model <model>\", \"Model to request when the selected local tool supports model selection\")\n .option(\"--provider <providerId>\", \"Provider id for provider-backed model configuration\")\n .option(\"--model-id <modelId>\", \"Provider catalog model id to request\")\n .option(\"--model-variant <variant>\", \"Provider catalog model variant to request\")\n .option(\"--reasoning-effort <effort>\", \"Reasoning effort: auto, low, medium, high, or xhigh\", parseReasoningEffort)\n .option(\"--tool-command <command>\", \"Custom local command. Use {promptFile} and {root} placeholders when supported\")\n .option(\"--session <policy>\", \"Tool session policy: auto, new, continue:<toolSessionId>, or none\", \"auto\")\n .option(\"--dry-run\", \"Claim work and print the generated execution prompt without running a tool\")\n .option(\"--watch\", \"Keep polling for approved work until stopped\")\n .option(\"--background\", \"Start a detached background runner that watches for approved work\")\n .option(\"--interval-seconds <seconds>\", \"Polling interval for --watch\", parsePositiveInteger, 10)\n .option(\"--max-iterations <count>\", \"Stop watch mode after this many polling attempts\", parsePositiveInteger)\n .option(\"--max-concurrent-work <count>\", \"Maximum approved work items to run in parallel in --watch mode\", parsePositiveInteger, 1)\n .option(\"--max-preflight-attempts <count>\", \"Fail setup/preflight failures after this many claimed attempts\", parsePositiveInteger, DEFAULT_MAX_PREFLIGHT_ATTEMPTS)\n .option(\"--tool-timeout-seconds <seconds>\", \"Fail local tool execution after this many seconds\", parsePositiveInteger, DEFAULT_TOOL_TIMEOUT_SECONDS)\n .option(\"--no-stream\", \"Capture local tool output instead of streaming it\")\n .option(\"--verbose\", \"Print detailed runner errors while watching\")\n .action(async (options: RunCommandOptions, command: Command) => {\n const context = await loadPairedApiContext(options.root, options.apiUrl);\n if (!context) {\n console.log(\"Repository is not paired. Run `amistio pair` first.\");\n return;\n }\n if (!context.token) {\n console.log(\"No local runner credential found. Run `amistio pair --pairing-code <code>` to store this machine credential.\");\n process.exitCode = 1;\n return;\n }\n\n const runnerId = options.runnerId ?? stableRunnerId({\n accountId: context.metadata.amistioAccountId,\n projectId: context.metadata.amistioProjectId,\n repositoryLinkId: context.metadata.repositoryLinkId,\n machineId: runnerMachineId()\n });\n const resolvedOptions = { ...options, runnerId };\n if (resolvedOptions.maxConcurrentWork > MAX_CONCURRENT_RUNNER_WORK) {\n console.log(`--max-concurrent-work is capped at ${MAX_CONCURRENT_RUNNER_WORK}.`);\n process.exitCode = 1;\n return;\n }\n\n if (options.background) {\n if (options.dryRun) {\n console.log(\"Background runners cannot be started in dry-run mode.\");\n process.exitCode = 1;\n return;\n }\n\n const metadata = await startRunnerDaemon({\n accountId: context.metadata.amistioAccountId,\n projectId: context.metadata.amistioProjectId,\n repositoryLinkId: context.metadata.repositoryLinkId,\n runnerId,\n rootDir: path.resolve(options.root),\n apiUrl: options.apiUrl,\n args: buildBackgroundRunnerArgs(resolvedOptions)\n });\n console.log(`Started background runner ${metadata.runnerId} with PID ${metadata.pid}.`);\n if (metadata.logPath) {\n console.log(`Log: ${metadata.logPath}`);\n }\n return;\n }\n\n if (options.watch) {\n for (const line of formatWatchStartupContext({ runnerId, projectId: context.metadata.amistioProjectId, repositoryLinkId: context.metadata.repositoryLinkId, apiUrl: options.apiUrl, intervalSeconds: options.intervalSeconds })) {\n console.log(line);\n }\n }\n\n let offlineSent = false;\n const sendOfflineHeartbeat = async (message?: string) => {\n if (offlineSent || options.dryRun) return;\n offlineSent = true;\n await context.client.sendRunnerHeartbeat(context.metadata.amistioProjectId, runnerId, context.metadata.repositoryLinkId, \"offline\", { ...runnerHeartbeatMetadata(), ...(message ? { preferenceMessage: message } : {}) }).catch(() => undefined);\n };\n const handleShutdownSignal = (signal: NodeJS.Signals) => {\n void sendOfflineHeartbeat(`Runner stopped by ${signal}.`).finally(() => {\n process.exit(signal === \"SIGINT\" ? 130 : 143);\n });\n };\n process.once(\"SIGINT\", handleShutdownSignal);\n process.once(\"SIGTERM\", handleShutdownSignal);\n\n let iterations = 0;\n let lastWatchStateLog: WatchStateLog | undefined;\n try {\n while (true) {\n iterations += 1;\n const result = await runWatchIteration({\n command,\n context,\n options: resolvedOptions,\n runnerId\n });\n\n if (!options.watch || options.dryRun) {\n if (result.exitCode !== 0) {\n process.exitCode = result.exitCode;\n }\n return;\n }\n\n if (result.status === \"idle\" && result.nextAction) {\n const nowMs = Date.now();\n if (shouldPrintWatchState(result.nextAction, lastWatchStateLog, nowMs)) {\n console.log(formatWatchIdleLine(result.nextAction, options.intervalSeconds));\n lastWatchStateLog = { key: watchStateKey(result.nextAction), printedAtMs: nowMs };\n }\n }\n\n if (result.stopRunner) {\n return;\n }\n\n if (options.maxIterations !== undefined && iterations >= options.maxIterations) {\n console.log(`Runner stopped after ${iterations} polling attempt${iterations === 1 ? \"\" : \"s\"}.`);\n return;\n }\n await delay(options.intervalSeconds * 1000);\n }\n } finally {\n process.off(\"SIGINT\", handleShutdownSignal);\n process.off(\"SIGTERM\", handleShutdownSignal);\n await sendOfflineHeartbeat(\"Runner stopped.\");\n }\n });\n\nconst runner = program.command(\"runner\").description(\"Manage local Amistio runner processes\");\n\nrunner\n .command(\"status\")\n .description(\"Show background runner status for the paired repository\")\n .option(\"--api-url <url>\", apiUrlOptionDescription, defaultApiUrl())\n .option(\"--root <path>\", \"Repository root\", defaultRoot)\n .option(\"--runner-id <runnerId>\", \"Limit status to one runner ID\")\n .action(async (options: { apiUrl: string; root: string; runnerId?: string }) => {\n const context = await loadPairedApiContext(options.root, options.apiUrl);\n if (!context) {\n console.log(\"Repository is not paired. Run `amistio pair` first.\");\n return;\n }\n\n const records = await listRunnerDaemonMetadata({\n accountId: context.metadata.amistioAccountId,\n projectId: context.metadata.amistioProjectId,\n repositoryLinkId: context.metadata.repositoryLinkId,\n ...(options.runnerId ? { runnerId: options.runnerId } : {})\n });\n const runners = await context.client.listRunners(context.metadata.amistioProjectId).then((result) => result.runners).catch(() => []);\n if (!records.length) {\n console.log(\"No background runner metadata found for this paired repository.\");\n if (runners.length) {\n console.log(`Last runner heartbeat: ${runners[0]!.runnerId} ${runners[0]!.status} at ${runners[0]!.lastSeenAt}.`);\n console.log(`Resource usage: ${formatRunnerResourceUsage(runners[0]!.resourceUsage)}`);\n }\n return;\n }\n\n for (const record of records) {\n const runtimeStatus = runnerDaemonRuntimeStatus(record);\n const heartbeat = runners.find((item) => item.runnerId === record.runnerId);\n console.log(`Runner ${record.runnerId}: ${runtimeStatus}`);\n console.log(` PID: ${record.pid}`);\n console.log(` Uptime: ${runtimeStatus === \"running\" ? runnerDaemonUptime(record) : \"not running\"}`);\n console.log(` Project: ${record.projectId}`);\n console.log(` Repository link: ${record.repositoryLinkId}`);\n console.log(` Root: ${record.rootDir}`);\n console.log(` API: ${record.apiUrl}`);\n console.log(` Host: ${record.hostname}`);\n if (record.logPath) {\n console.log(` Log: ${record.logPath}`);\n }\n if (heartbeat) {\n console.log(` Last heartbeat: ${heartbeat.status} at ${heartbeat.lastSeenAt}${heartbeat.version ? ` (${heartbeat.version})` : \"\"}`);\n }\n console.log(` Resource usage: ${formatRunnerResourceUsage(heartbeat?.resourceUsage)}`);\n }\n });\n\nrunner\n .command(\"smoke-session-lifecycle\")\n .description(\"Run a local no-claim smoke for runner tool-session lifecycle behavior\")\n .option(\"--json\", \"Print the smoke report as JSON\")\n .action((options: { json?: boolean }) => {\n const report = runRunnerActivationSmoke();\n if (options.json) {\n console.log(JSON.stringify(report, null, 2));\n } else {\n console.log(`Runner session lifecycle smoke: ${report.passed ? \"passed\" : \"failed\"}`);\n for (const check of report.checks) {\n console.log(` ${check.passed ? \"ok\" : \"fail\"} ${check.name}: ${check.detail}`);\n }\n }\n if (!report.passed) {\n process.exitCode = 1;\n }\n });\n\nrunner\n .command(\"stop\")\n .description(\"Stop a background runner for the paired repository\")\n .option(\"--api-url <url>\", apiUrlOptionDescription, defaultApiUrl())\n .option(\"--root <path>\", \"Repository root\", defaultRoot)\n .option(\"--runner-id <runnerId>\", \"Runner ID to stop when multiple background runners exist\")\n .action(async (options: { apiUrl: string; root: string; runnerId?: string }) => {\n const context = await loadPairedApiContext(options.root, options.apiUrl);\n if (!context) {\n console.log(\"Repository is not paired. Run `amistio pair` first.\");\n return;\n }\n\n const records = await listRunnerDaemonMetadata({\n accountId: context.metadata.amistioAccountId,\n projectId: context.metadata.amistioProjectId,\n repositoryLinkId: context.metadata.repositoryLinkId,\n ...(options.runnerId ? { runnerId: options.runnerId } : {})\n });\n if (!records.length) {\n console.log(\"No background runner metadata found for this paired repository.\");\n return;\n }\n if (records.length > 1 && !options.runnerId) {\n console.log(`Multiple background runners found: ${records.map((record) => record.runnerId).join(\", \")}. Pass --runner-id to stop one.`);\n process.exitCode = 1;\n return;\n }\n\n const record = records[0]!;\n const existingRunner = await context.client.listRunners(context.metadata.amistioProjectId).then((result) => result.runners.find((runner) => runner.runnerId === record.runnerId && runner.repositoryLinkId === context.metadata.repositoryLinkId)).catch(() => undefined);\n const stopResult = await stopRunnerDaemonProcess(record);\n await markRunnerDaemonStopped(record);\n await context.client.sendRunnerHeartbeat(context.metadata.amistioProjectId, record.runnerId, context.metadata.repositoryLinkId, \"offline\", {\n version: CLI_VERSION,\n mode: \"background\",\n hostname: record.hostname,\n ...(existingRunner?.resourceUsage ? { resourceUsage: existingRunner.resourceUsage } : {})\n }).catch(() => undefined);\n console.log(stopResult === \"stopped\" ? `Stopped background runner ${record.runnerId}.` : `Marked background runner ${record.runnerId} stopped; process was not running.`);\n });\n\nconst runnerService = runner.command(\"service\").description(\"Manage a user-level startup service for the paired runner\");\n\nrunnerService\n .command(\"install\")\n .description(\"Install a user-level startup service for this paired repository runner\")\n .option(\"--api-url <url>\", apiUrlOptionDescription, defaultApiUrl())\n .option(\"--root <path>\", \"Repository root\", defaultRoot)\n .option(\"--runner-id <runnerId>\", \"Stable runner ID\")\n .option(\"--tool <name>\", \"Local tool to use: auto, opencode, claude, codex, copilot, gemini, aider, cursor-agent\")\n .option(\"--invocation-channel <channel>\", \"Local invocation channel: auto, sdk, or command\", parseInvocationChannel)\n .option(\"--model <model>\", \"Model to request when the selected local tool supports model selection\")\n .option(\"--provider <providerId>\", \"Provider id for provider-backed model configuration\")\n .option(\"--model-id <modelId>\", \"Provider catalog model id to request\")\n .option(\"--model-variant <variant>\", \"Provider catalog model variant to request\")\n .option(\"--reasoning-effort <effort>\", \"Reasoning effort: auto, low, medium, high, or xhigh\", parseReasoningEffort)\n .option(\"--session <policy>\", \"Tool session policy: auto, new, continue:<toolSessionId>, or none\", \"auto\")\n .option(\"--interval-seconds <seconds>\", \"Polling interval for the service runner\", parsePositiveInteger, 10)\n .option(\"--max-concurrent-work <count>\", \"Maximum approved work items to run in parallel in --watch mode\", parsePositiveInteger, 1)\n .option(\"--max-preflight-attempts <count>\", \"Fail setup/preflight failures after this many claimed attempts\", parsePositiveInteger, DEFAULT_MAX_PREFLIGHT_ATTEMPTS)\n .option(\"--tool-timeout-seconds <seconds>\", \"Fail local tool execution after this many seconds\", parsePositiveInteger, DEFAULT_TOOL_TIMEOUT_SECONDS)\n .option(\"--no-stream\", \"Capture local tool output instead of streaming it\")\n .option(\"--verbose\", \"Print detailed runner errors\")\n .option(\"--dry-run\", \"Print the startup service descriptor without installing it\")\n .action(async (options: { apiUrl: string; root: string; runnerId?: string; tool?: string; invocationChannel?: RunnerInvocationChannel; model?: string; provider?: string; modelId?: string; modelVariant?: string; reasoningEffort?: RunnerReasoningEffort; session: string; intervalSeconds: number; maxConcurrentWork: number; maxPreflightAttempts: number; toolTimeoutSeconds: number; stream: boolean; verbose?: boolean; dryRun?: boolean }) => {\n const context = await loadPairedApiContext(options.root, options.apiUrl);\n if (!context) {\n console.log(\"Repository is not paired. Run `amistio pair` first.\");\n return;\n }\n if (!context.token) {\n console.log(\"No local runner credential found. Run `amistio pair --pairing-code <code>` to store this machine credential.\");\n process.exitCode = 1;\n return;\n }\n\n const platform = detectRunnerServicePlatform();\n if (platform === \"unsupported\") {\n console.log(\"Startup services are supported for user-level launchd on macOS and systemd user services on Linux.\");\n process.exitCode = 1;\n return;\n }\n\n const runnerId = options.runnerId ?? stableRunnerId({\n accountId: context.metadata.amistioAccountId,\n projectId: context.metadata.amistioProjectId,\n repositoryLinkId: context.metadata.repositoryLinkId,\n machineId: runnerMachineId()\n });\n if (options.maxConcurrentWork > MAX_CONCURRENT_RUNNER_WORK) {\n console.log(`--max-concurrent-work is capped at ${MAX_CONCURRENT_RUNNER_WORK}.`);\n process.exitCode = 1;\n return;\n }\n const args = buildBackgroundRunnerArgs({ ...options, runnerId, apiUrl: options.apiUrl, root: options.root });\n const serviceInput = {\n accountId: context.metadata.amistioAccountId,\n projectId: context.metadata.amistioProjectId,\n repositoryLinkId: context.metadata.repositoryLinkId,\n runnerId,\n rootDir: path.resolve(options.root),\n apiUrl: options.apiUrl,\n args,\n platform\n };\n\n if (options.dryRun) {\n const descriptor = createRunnerServiceDescriptor(serviceInput);\n console.log(`Startup service file: ${descriptor.metadata.serviceFilePath}`);\n console.log(descriptor.content.trim());\n return;\n }\n\n try {\n const metadata = await installRunnerService(serviceInput);\n console.log(`Installed startup service ${metadata.serviceName}.`);\n console.log(`Service file: ${metadata.serviceFilePath}`);\n } catch (error) {\n console.error(errorMessage(error));\n process.exitCode = 1;\n }\n });\n\nrunnerService\n .command(\"status\")\n .description(\"Show the startup service status for this paired repository runner\")\n .option(\"--api-url <url>\", apiUrlOptionDescription, defaultApiUrl())\n .option(\"--root <path>\", \"Repository root\", defaultRoot)\n .option(\"--runner-id <runnerId>\", \"Stable runner ID\")\n .action(async (options: { apiUrl: string; root: string; runnerId?: string }) => {\n const context = await loadPairedApiContext(options.root, options.apiUrl);\n if (!context) {\n console.log(\"Repository is not paired. Run `amistio pair` first.\");\n return;\n }\n const runnerId = options.runnerId ?? stableRunnerId({\n accountId: context.metadata.amistioAccountId,\n projectId: context.metadata.amistioProjectId,\n repositoryLinkId: context.metadata.repositoryLinkId,\n machineId: runnerMachineId()\n });\n const metadata = await readRunnerServiceMetadata({ accountId: context.metadata.amistioAccountId, projectId: context.metadata.amistioProjectId, repositoryLinkId: context.metadata.repositoryLinkId, runnerId });\n if (!metadata) {\n console.log(\"No startup service metadata found for this paired repository runner.\");\n return;\n }\n const runtimeStatus = await runnerServiceRuntimeStatus(metadata);\n console.log(`Startup service ${metadata.serviceName}: ${runtimeStatus}`);\n console.log(` Platform: ${metadata.platform}`);\n console.log(` File: ${metadata.serviceFilePath}`);\n console.log(` Root: ${metadata.rootDir}`);\n console.log(` API: ${metadata.apiUrl}`);\n });\n\nrunnerService\n .command(\"remove\")\n .description(\"Remove the startup service for this paired repository runner\")\n .option(\"--api-url <url>\", apiUrlOptionDescription, defaultApiUrl())\n .option(\"--root <path>\", \"Repository root\", defaultRoot)\n .option(\"--runner-id <runnerId>\", \"Stable runner ID\")\n .action(async (options: { apiUrl: string; root: string; runnerId?: string }) => {\n const context = await loadPairedApiContext(options.root, options.apiUrl);\n if (!context) {\n console.log(\"Repository is not paired. Run `amistio pair` first.\");\n return;\n }\n const runnerId = options.runnerId ?? stableRunnerId({\n accountId: context.metadata.amistioAccountId,\n projectId: context.metadata.amistioProjectId,\n repositoryLinkId: context.metadata.repositoryLinkId,\n machineId: runnerMachineId()\n });\n const removed = await removeRunnerService({ accountId: context.metadata.amistioAccountId, projectId: context.metadata.amistioProjectId, repositoryLinkId: context.metadata.repositoryLinkId, runnerId });\n console.log(removed ? `Removed startup service ${removed.serviceName}.` : \"No startup service metadata found for this paired repository runner.\");\n });\n\ninterface RunCommandOptions {\n apiUrl: string;\n runnerId?: string;\n root: string;\n tool?: string;\n invocationChannel?: RunnerInvocationChannel;\n toolCommand?: string;\n model?: string;\n provider?: string;\n modelId?: string;\n modelVariant?: string;\n reasoningEffort?: RunnerReasoningEffort;\n session: string;\n dryRun?: boolean;\n watch?: boolean;\n background?: boolean;\n intervalSeconds: number;\n maxIterations?: number;\n maxConcurrentWork: number;\n maxPreflightAttempts: number;\n toolTimeoutSeconds: number;\n stream: boolean;\n verbose?: boolean;\n}\n\ntype ResolvedRunCommandOptions = RunCommandOptions & { runnerId: string };\n\nasync function runWatchIteration({ command, context, options, runnerId }: { command: Command; context: PairedApiContext; options: ResolvedRunCommandOptions; runnerId: string }): ReturnType<typeof runNextWorkItem> {\n try {\n if (options.watch && !options.dryRun) {\n await runAutoSyncCycle({\n context,\n maxFileKb: 256,\n quiet: true,\n quietDisabled: true,\n root: options.root,\n runnerId\n });\n }\n if (!options.dryRun) {\n const replayResult = await replayPendingResultFinalizations({\n accountId: context.metadata.amistioAccountId,\n apiClient: context.client,\n projectId: context.metadata.amistioProjectId,\n repositoryLinkId: context.metadata.repositoryLinkId,\n runnerId\n });\n if (replayResult) {\n return replayResult;\n }\n }\n const activeClaimLaneIds = claimLaneIds(options.maxConcurrentWork);\n const runLane = (claimLaneId: string, laneIndex: number) => runNextWorkItem({\n apiClient: context.client,\n projectId: context.metadata.amistioProjectId,\n repositoryLinkId: context.metadata.repositoryLinkId,\n runnerId,\n root: options.root,\n sessionPolicy: normalizeSessionPolicy(options.session),\n ...(command.getOptionValueSource(\"tool\") === \"cli\" && options.tool ? { explicitTool: options.tool } : {}),\n ...(command.getOptionValueSource(\"invocationChannel\") === \"cli\" && options.invocationChannel ? { explicitInvocationChannel: options.invocationChannel } : {}),\n ...(command.getOptionValueSource(\"model\") === \"cli\" && options.model ? { explicitModel: options.model } : {}),\n ...(command.getOptionValueSource(\"provider\") === \"cli\" && options.provider ? { explicitProviderId: options.provider } : {}),\n ...(command.getOptionValueSource(\"modelId\") === \"cli\" && options.modelId ? { explicitModelId: options.modelId } : {}),\n ...(command.getOptionValueSource(\"modelVariant\") === \"cli\" && options.modelVariant ? { explicitModelVariant: options.modelVariant } : {}),\n ...(command.getOptionValueSource(\"reasoningEffort\") === \"cli\" && options.reasoningEffort ? { explicitReasoningEffort: options.reasoningEffort } : {}),\n ...(options.toolCommand ? { toolCommand: options.toolCommand } : {}),\n dryRun: Boolean(options.dryRun),\n stream: options.stream,\n commandContext: {\n accountId: context.metadata.amistioAccountId,\n apiUrl: options.apiUrl,\n backgroundArgs: buildBackgroundRunnerArgs(options),\n projectId: context.metadata.amistioProjectId,\n repositoryLinkId: context.metadata.repositoryLinkId,\n root: options.root,\n runnerId\n },\n suppressIdleOutput: Boolean(options.watch),\n maxPreflightAttempts: options.maxPreflightAttempts,\n toolTimeoutMs: options.toolTimeoutSeconds * 1000,\n verbose: Boolean(options.verbose),\n claimLaneId,\n maxConcurrentWork: options.maxConcurrentWork,\n activeClaimLaneIds,\n skipRunnerCommands: laneIndex > 0\n });\n if (options.watch && !options.dryRun && options.maxConcurrentWork > 1) {\n return aggregateRunnerLaneResults(await Promise.all(activeClaimLaneIds.map((claimLaneId, laneIndex) => runLane(claimLaneId, laneIndex))));\n }\n return await runLane(\"default\", 0);\n } catch (error) {\n if (!options.watch) {\n throw error;\n }\n const detail = truncateLogExcerpt(errorDetail(error));\n const message = \"Runner hit an error while watching and will keep listening.\";\n if (options.verbose) {\n console.error(`${message}\\n${detail}`);\n } else {\n console.error(`${message} Run with --verbose for details.`);\n }\n const settlements = await Promise.allSettled([\n context.client.sendRunnerHeartbeat(context.metadata.amistioProjectId, runnerId, context.metadata.repositoryLinkId, \"blocked\", { ...runnerHeartbeatMetadata(), preferenceMessage: message }),\n context.client.recordRunnerLog(context.metadata.amistioProjectId, {\n runnerId,\n repositoryLinkId: context.metadata.repositoryLinkId,\n status: \"failed\",\n message,\n error: detail,\n machineId: runnerMachineId()\n })\n ]);\n logRejectedSettlements(\"record watch error\", settlements);\n return { status: \"failed\", exitCode: 1, message };\n }\n}\n\ntype RunnerIterationResult = Awaited<ReturnType<typeof runNextWorkItem>>;\n\nfunction claimLaneIds(maxConcurrentWork: number): string[] {\n return Array.from({ length: maxConcurrentWork }, (_, index) => index === 0 ? \"default\" : `lane_${index + 1}`);\n}\n\nfunction supportsConcurrentLocalToolExecution(toolConfig: RunnerToolConfig): boolean {\n return toolConfig.tool === \"none\" || toolConfig.effectiveInvocationChannel === \"command\" || toolConfig.effectiveTool === \"custom\";\n}\n\nfunction aggregateRunnerLaneResults(results: RunnerIterationResult[]): RunnerIterationResult {\n const stopResult = results.find((result) => result.stopRunner);\n if (stopResult) return stopResult;\n const failedResult = results.find((result) => result.status === \"failed\");\n if (failedResult) return failedResult;\n const blockedResult = results.find((result) => result.status === \"blocked\");\n if (blockedResult) return blockedResult;\n const completedResult = results.find((result) => result.status === \"completed\" || result.status === \"preview\");\n if (completedResult) return completedResult;\n return results.find((result) => result.status === \"idle\") ?? { status: \"idle\", exitCode: 0 };\n}\n\ntype AutoSyncCycleStatus = \"disabled\" | \"synced\" | \"conflicted\" | \"failed\" | \"blocked\";\n\ninterface AutoSyncCycleResult {\n status: AutoSyncCycleStatus;\n message: string;\n pushedCount: number;\n skippedCount: number;\n conflictCount: number;\n collection?: AutoSyncPushCollection;\n}\n\nasync function runAutoSyncCycle({ context, maxFileKb, quiet, quietDisabled, root, runnerId }: { context: PairedApiContext; maxFileKb: number; quiet?: boolean; quietDisabled?: boolean; root: string; runnerId: string }): Promise<AutoSyncCycleResult> {\n const projectId = context.metadata.amistioProjectId;\n const repositoryLinkId = context.metadata.repositoryLinkId;\n const heartbeatBase = runnerHeartbeatMetadata(undefined);\n const startedAt = new Date().toISOString();\n\n try {\n const { repositoryLinks } = await context.client.listRepositoryLinks(projectId);\n const repositoryLink = repositoryLinks.find((link) => link.repositoryLinkId === repositoryLinkId && link.status !== \"revoked\");\n if (!repositoryLink) {\n const message = \"Repository link is not active for auto-sync.\";\n await context.client.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"blocked\", { ...heartbeatBase, autoSyncStatus: \"blocked\", autoSyncMessage: message, autoSyncLastFailureAt: startedAt }).catch(() => undefined);\n return { status: \"blocked\", message, pushedCount: 0, skippedCount: 0, conflictCount: 0 };\n }\n if (!repositoryLink.autoSyncEnabled) {\n const message = \"Repository brain auto-sync is disabled.\";\n if (!quietDisabled) {\n await context.client.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", { ...heartbeatBase, autoSyncStatus: \"disabled\", autoSyncMessage: message }).catch(() => undefined);\n }\n return { status: \"disabled\", message, pushedCount: 0, skippedCount: 0, conflictCount: 0 };\n }\n\n await context.client.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", { ...heartbeatBase, autoSyncStatus: \"active\", autoSyncMessage: \"Scanning repository brain folders.\", autoSyncLastStartedAt: startedAt }).catch(() => undefined);\n const { documents: existingDocuments } = await context.client.listBrainDocuments(projectId);\n const collection = await collectAutoSyncDocumentsForPush(root, context.metadata, existingDocuments, { maxFileKb, syncedAt: startedAt });\n if (!collection.documents.length) {\n const skippedCount = collection.skipped.length;\n const message = skippedCount ? `No local brain changes pushed; ${skippedCount} file${skippedCount === 1 ? \"\" : \"s\"} skipped or unchanged.` : \"No local brain changes found.\";\n await context.client.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", { ...heartbeatBase, autoSyncStatus: \"synced\", autoSyncMessage: message, autoSyncLastSuccessAt: startedAt, autoSyncPushedCount: 0, autoSyncSkippedCount: skippedCount, autoSyncConflictCount: 0 }).catch(() => undefined);\n return { status: \"synced\", message, pushedCount: 0, skippedCount, conflictCount: 0, collection };\n }\n\n const { documents } = await context.client.pushBrainDocuments(projectId, collection.documents);\n const conflictedDocuments = documents.filter((document) => document.syncState === \"conflicted\" || document.status === \"conflicted\");\n const managedDocumentIds = new Set(collection.managedDocumentIds);\n const managedDocuments = documents.filter((document) => managedDocumentIds.has(document.documentId) && document.syncState !== \"conflicted\" && document.status !== \"conflicted\");\n if (managedDocuments.length) {\n await materializeBrainDocuments(root, managedDocuments, { allowDirtyOverwrite: true });\n }\n\n const conflictCount = conflictedDocuments.length;\n const skippedCount = collection.skipped.length;\n const pushedCount = documents.length - conflictCount;\n const status = conflictCount ? \"conflicted\" : \"synced\";\n const message = conflictCount ? `Auto-sync found ${conflictCount} conflict${conflictCount === 1 ? \"\" : \"s\"}.` : `Auto-sync pushed ${pushedCount} brain document${pushedCount === 1 ? \"\" : \"s\"}.`;\n await context.client.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", { ...heartbeatBase, autoSyncStatus: status, autoSyncMessage: message, ...(conflictCount ? { autoSyncLastFailureAt: startedAt } : { autoSyncLastSuccessAt: startedAt }), autoSyncPushedCount: pushedCount, autoSyncSkippedCount: skippedCount, autoSyncConflictCount: conflictCount }).catch(() => undefined);\n if (!quiet && conflictCount) {\n for (const document of conflictedDocuments) {\n console.log(`conflicted: ${document.repoPath} - web and repository revisions both changed`);\n }\n }\n return { status, message, pushedCount, skippedCount, conflictCount, collection };\n } catch (error) {\n const message = `Auto-sync failed: ${errorMessage(error)}`;\n await context.client.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"blocked\", { ...heartbeatBase, autoSyncStatus: \"failed\", autoSyncMessage: message, autoSyncLastFailureAt: startedAt }).catch(() => undefined);\n return { status: \"failed\", message, pushedCount: 0, skippedCount: 0, conflictCount: 0 };\n }\n}\n\nfunction formatAutoSyncCycleResult(result: AutoSyncCycleResult): string {\n const details = [`pushed ${result.pushedCount}`, `skipped ${result.skippedCount}`, `conflicts ${result.conflictCount}`];\n return `${result.message} (${details.join(\"; \")})`;\n}\n\nasync function runNextWorkItem({\n apiClient,\n dryRun,\n projectId,\n repositoryLinkId,\n root,\n runnerId,\n sessionPolicy,\n stream,\n explicitModel,\n explicitModelId,\n explicitModelVariant,\n explicitProviderId,\n explicitReasoningEffort,\n explicitInvocationChannel,\n explicitTool,\n maxPreflightAttempts,\n toolCommand,\n commandContext,\n suppressIdleOutput,\n toolTimeoutMs,\n verbose,\n claimLaneId,\n maxConcurrentWork,\n activeClaimLaneIds,\n skipRunnerCommands\n}: {\n apiClient: ApiClient;\n dryRun: boolean;\n projectId: string;\n repositoryLinkId: string;\n root: string;\n runnerId: string;\n sessionPolicy: SessionPolicy;\n stream: boolean;\n explicitModel?: string;\n explicitProviderId?: string;\n explicitModelId?: string;\n explicitModelVariant?: string;\n explicitReasoningEffort?: RunnerReasoningEffort;\n explicitInvocationChannel?: RunnerInvocationChannel;\n explicitTool?: string;\n maxPreflightAttempts: number;\n suppressIdleOutput?: boolean;\n toolTimeoutMs: number;\n verbose?: boolean;\n claimLaneId: string;\n maxConcurrentWork: number;\n activeClaimLaneIds: string[];\n skipRunnerCommands?: boolean;\n commandContext: RunnerCommandExecutionContext;\n toolCommand?: string;\n}): Promise<{ status: \"completed\" | \"failed\" | \"idle\" | \"preview\" | \"blocked\"; exitCode: number; nextAction?: ProjectNextAction; message?: string; stopRunner?: boolean }> {\n const toolConfig = await resolveRunnerToolConfig({\n apiClient,\n projectId,\n ...(explicitInvocationChannel ? { explicitInvocationChannel } : {}),\n ...(explicitModel ? { explicitModel } : {}),\n ...(explicitProviderId ? { explicitProviderId } : {}),\n ...(explicitModelId ? { explicitModelId } : {}),\n ...(explicitModelVariant ? { explicitModelVariant } : {}),\n ...(explicitReasoningEffort ? { explicitReasoningEffort } : {}),\n ...(explicitTool ? { explicitTool } : {}),\n ...(toolCommand ? { toolCommand } : {})\n });\n const effectiveMaxConcurrentWork = supportsConcurrentLocalToolExecution(toolConfig) ? maxConcurrentWork : 1;\n const effectiveActiveClaimLaneIds = claimLaneIds(effectiveMaxConcurrentWork);\n const heartbeatConcurrency = { maxConcurrentWork: effectiveMaxConcurrentWork, activeClaimLaneIds: effectiveActiveClaimLaneIds };\n if (claimLaneId !== \"default\" && effectiveMaxConcurrentWork === 1) {\n return { status: \"idle\", exitCode: 0 };\n }\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, toolConfig.ready ? \"online\" : \"blocked\", runnerHeartbeatMetadata(toolConfig, currentRunnerMode(), heartbeatConcurrency));\n if (!skipRunnerCommands) {\n const commandResult = await runPendingRunnerCommand(apiClient, commandContext, runnerHeartbeatMetadata(toolConfig, currentRunnerMode(), heartbeatConcurrency));\n if (commandResult.handled) {\n if (commandResult.message) {\n console.log(commandResult.message);\n }\n return { status: commandResult.succeeded ? \"completed\" : \"failed\", exitCode: commandResult.succeeded ? 0 : 1, ...(commandResult.stopRunner ? { stopRunner: true } : {}) };\n }\n }\n if (!toolConfig.ready) {\n console.log(toolConfig.message);\n return { status: \"blocked\", exitCode: 1 };\n }\n const result = await apiClient.claimWork(projectId, runnerId, repositoryLinkId, RUNNER_WORK_LEASE_SECONDS, runnerIsolationCapabilityMetadata({ claimLaneId, maxConcurrentWork: effectiveMaxConcurrentWork }));\n if (!result.workItem) {\n const nextAction = await loadProjectNextAction(apiClient, projectId, repositoryLinkId, root);\n const message = formatProjectNextAction(nextAction);\n if (!suppressIdleOutput) {\n console.log(message);\n }\n return { status: \"idle\", exitCode: 0, nextAction, message };\n }\n\n const prompt = await createRunnerWorkPrompt(apiClient, projectId, result.workItem);\n await recordRunnerMilestone(apiClient, projectId, result.workItem, runnerId, repositoryLinkId, {\n status: \"running\",\n summary: \"Prepared local runner execution prompt.\",\n idempotencyKey: `runner_milestone_prompt_${result.workItem.workItemId}_${result.workItem.attempt}`,\n metadata: { workKind: result.workItem.workKind ?? \"implementation\", attempt: result.workItem.attempt }\n });\n if (dryRun || toolConfig.tool === \"none\") {\n console.log(prompt);\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig, currentRunnerMode(), heartbeatConcurrency));\n return { status: \"preview\", exitCode: 0 };\n }\n\n const worktreeIsolation = await prepareWorktreeForClaimedItem({ apiClient, heartbeatConcurrency, maxPreflightAttempts, projectId, repositoryLinkId, root, runnerId, toolConfig, workItem: result.workItem });\n if (worktreeIsolation.status !== \"ready\") {\n return { status: worktreeIsolation.status === \"failed\" ? \"failed\" : \"blocked\", exitCode: 1, message: worktreeIsolation.message };\n }\n const executionRoot = worktreeIsolation.isolation?.worktreePath ?? root;\n const isolationTelemetry = workItemIsolationTelemetry(result.workItem, worktreeIsolation.isolation);\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"running\", {\n ...runnerHeartbeatMetadata(toolConfig, currentRunnerMode(), heartbeatConcurrency),\n currentWorkItemId: result.workItem.workItemId,\n ...(isolationTelemetry.implementationScopeId ? { currentImplementationScopeId: isolationTelemetry.implementationScopeId } : {}),\n ...(isolationTelemetry.executionWorktreeKey ? { currentWorktreeKey: isolationTelemetry.executionWorktreeKey } : {}),\n ...(isolationTelemetry.executionBranch ? { currentBranch: isolationTelemetry.executionBranch } : {})\n });\n\n const resolvedModelConfig = toolConfigModelOptions(toolConfig);\n const preview = await createToolRunPreview({ rootDir: executionRoot, prompt, tool: toolConfig.tool, invocationChannel: toolConfig.requestedInvocationChannel ?? \"auto\", ...(toolCommand ? { toolCommand } : {}), ...resolvedModelConfig });\n const sessionContext = await prepareToolSession({\n apiClient,\n projectId,\n repositoryLinkId,\n runnerId,\n machineId: runnerMachineId(),\n sessionPolicy: result.workItem.sessionPolicy ?? sessionPolicy,\n toolName: preview.toolName,\n ...(toolConfig.model ? { model: toolConfig.model } : {}),\n supportsSessionReuse: preview.supportsSessionReuse,\n resumabilityScope: preview.resumabilityScope,\n workItem: result.workItem,\n isolationTelemetry\n });\n console.log(`Claimed ${result.workItem.workItemId}. Running ${preview.toolName}: ${preview.displayCommand}`);\n const autopilotClaimLine = formatAutopilotClaimLine(result.workItem);\n if (autopilotClaimLine) {\n console.log(autopilotClaimLine);\n }\n await recordRunnerMilestone(apiClient, projectId, result.workItem, runnerId, repositoryLinkId, {\n status: \"running\",\n summary: `Local runner started ${preview.toolName} execution.`,\n idempotencyKey: `runner_milestone_started_${result.workItem.workItemId}_${result.workItem.attempt}`,\n metadata: { tool: preview.toolName, invocationChannel: toolConfig.requestedInvocationChannel ?? \"auto\" }\n });\n const startedAt = Date.now();\n const providerSessionStore = new LocalToolSessionStore();\n const providerSessionId = sessionContext.toolSession\n ? await providerSessionStore.getProviderSessionId(sessionContext.toolSession.toolSessionId, preview.toolName)\n : undefined;\n let toolResult: LocalToolRunResult;\n const stopLeaseRenewal = startWorkLeaseRenewal({ apiClient, projectId, repositoryLinkId, runnerId, toolConfig, workItem: result.workItem, telemetry: isolationTelemetry, heartbeatConcurrency });\n try {\n toolResult = await runLocalTool({\n rootDir: executionRoot,\n prompt,\n tool: toolConfig.tool,\n invocationChannel: toolConfig.requestedInvocationChannel ?? \"auto\",\n ...(toolCommand ? { toolCommand } : {}),\n ...resolvedModelConfig,\n streamOutput: stream,\n timeoutMs: toolTimeoutMs,\n ...(sessionContext.toolSession\n ? {\n session: {\n toolSessionId: sessionContext.toolSession.toolSessionId,\n policy: sessionContext.policy,\n decision: sessionContext.decision,\n ...(providerSessionId ? { providerSessionId } : {})\n }\n }\n : {})\n });\n } catch (error) {\n stopLeaseRenewal();\n const detail = truncateLogExcerpt(errorDetail(error));\n const durationMs = Date.now() - startedAt;\n const message = `${preview.toolName} failed before returning a result.`;\n const settlements = await Promise.allSettled([\n apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig, currentRunnerMode(), heartbeatConcurrency)),\n markToolSessionBlocked(apiClient, projectId, sessionContext.toolSession, errorMessage(error)),\n apiClient.updateWorkStatus(projectId, result.workItem.workItemId, \"failed\", `run_failed_${result.workItem.workItemId}_${result.workItem.attempt}_${runnerId}`, runnerId, {\n ...isolationTelemetry,\n tool: preview.toolName,\n ...(toolConfig.model ? { model: toolConfig.model } : {}),\n durationMs,\n message,\n error: detail,\n ...(sessionContext.toolSession ? { toolSessionId: sessionContext.toolSession.toolSessionId } : {}),\n sessionPolicy: sessionContext.policy,\n sessionDecision: sessionContext.decision,\n sessionDecisionReason: sessionContext.reason\n }),\n recordRunnerMilestone(apiClient, projectId, result.workItem, runnerId, repositoryLinkId, {\n status: \"failed\",\n summary: message,\n idempotencyKey: `runner_milestone_tool_throw_${result.workItem.workItemId}_${result.workItem.attempt}`,\n metadata: { tool: preview.toolName, error: detail }\n })\n ]);\n logRejectedSettlements(\"record local tool failure\", settlements);\n if (verbose || !stream) {\n console.error(detail);\n }\n return { status: \"failed\", exitCode: 1, message };\n }\n stopLeaseRenewal();\n if (sessionContext.toolSession && toolResult.providerSessionId) {\n await providerSessionStore.setProviderSessionId(sessionContext.toolSession.toolSessionId, preview.toolName, toolResult.providerSessionId);\n }\n if (!stream && toolResult.stdout.trim()) {\n console.log(toolResult.stdout.trim());\n }\n if (!stream && toolResult.stderr.trim()) {\n console.error(toolResult.stderr.trim());\n }\n\n if (result.workItem.workKind === \"brainGeneration\" || result.workItem.workKind === \"planRevision\") {\n try {\n return await finalizeBrainGenerationWork({\n apiClient,\n durationMs: Date.now() - startedAt,\n projectId,\n repositoryLinkId,\n runnerId,\n sessionContext,\n toolConfig,\n toolName: preview.toolName,\n toolResult,\n workItem: result.workItem\n });\n } catch (error) {\n return recordFinalizationFailure({ apiClient, error, isolationTelemetry, projectId, repositoryLinkId, runnerId, sessionContext, toolConfig, toolName: preview.toolName, workItem: result.workItem, durationMs: Date.now() - startedAt });\n }\n }\n\n if (result.workItem.workKind === \"assistantQuestion\") {\n try {\n return await finalizeAssistantQuestionWork({\n apiClient,\n durationMs: Date.now() - startedAt,\n projectId,\n repositoryLinkId,\n runnerId,\n sessionContext,\n toolConfig,\n toolName: preview.toolName,\n toolResult,\n workItem: result.workItem\n });\n } catch (error) {\n return recordFinalizationFailure({ apiClient, error, isolationTelemetry, projectId, repositoryLinkId, runnerId, sessionContext, toolConfig, toolName: preview.toolName, workItem: result.workItem, durationMs: Date.now() - startedAt });\n }\n }\n\n if (result.workItem.workKind === \"impactPreview\") {\n try {\n return await finalizeImpactPreviewWork({\n apiClient,\n durationMs: Date.now() - startedAt,\n projectId,\n repositoryLinkId,\n root,\n runnerId,\n sessionContext,\n toolConfig,\n toolName: preview.toolName,\n toolResult,\n workItem: result.workItem\n });\n } catch (error) {\n return recordFinalizationFailure({ apiClient, error, isolationTelemetry, projectId, repositoryLinkId, runnerId, sessionContext, toolConfig, toolName: preview.toolName, workItem: result.workItem, durationMs: Date.now() - startedAt });\n }\n }\n\n if (result.workItem.workKind === \"issueDiagnosis\") {\n try {\n return await finalizeIssueDiagnosisWork({\n apiClient,\n durationMs: Date.now() - startedAt,\n projectId,\n repositoryLinkId,\n runnerId,\n sessionContext,\n toolConfig,\n toolName: preview.toolName,\n toolResult,\n workItem: result.workItem\n });\n } catch (error) {\n return recordFinalizationFailure({ apiClient, error, isolationTelemetry, projectId, repositoryLinkId, runnerId, sessionContext, toolConfig, toolName: preview.toolName, workItem: result.workItem, durationMs: Date.now() - startedAt });\n }\n }\n\n if (result.workItem.workKind === \"securityPostureScan\") {\n try {\n return await finalizeSecurityPostureScanWork({\n apiClient,\n durationMs: Date.now() - startedAt,\n projectId,\n repositoryLinkId,\n runnerId,\n sessionContext,\n toolConfig,\n toolName: preview.toolName,\n toolResult,\n workItem: result.workItem\n });\n } catch (error) {\n return recordFinalizationFailure({ apiClient, error, isolationTelemetry, projectId, repositoryLinkId, runnerId, sessionContext, toolConfig, toolName: preview.toolName, workItem: result.workItem, durationMs: Date.now() - startedAt });\n }\n }\n\n if (result.workItem.workKind === \"appEvaluationScan\") {\n try {\n return await finalizeAppEvaluationScanWork({\n apiClient,\n durationMs: Date.now() - startedAt,\n projectId,\n repositoryLinkId,\n runnerId,\n sessionContext,\n toolConfig,\n toolName: preview.toolName,\n toolResult,\n workItem: result.workItem\n });\n } catch (error) {\n return recordFinalizationFailure({ apiClient, error, isolationTelemetry, projectId, repositoryLinkId, runnerId, sessionContext, toolConfig, toolName: preview.toolName, workItem: result.workItem, durationMs: Date.now() - startedAt });\n }\n }\n\n if (result.workItem.workKind === \"brainConsolidationScan\") {\n try {\n return await finalizeBrainConsolidationScanWork({\n apiClient,\n durationMs: Date.now() - startedAt,\n projectId,\n repositoryLinkId,\n runnerId,\n sessionContext,\n toolConfig,\n toolName: preview.toolName,\n toolResult,\n workItem: result.workItem\n });\n } catch (error) {\n return recordFinalizationFailure({ apiClient, error, isolationTelemetry, projectId, repositoryLinkId, runnerId, sessionContext, toolConfig, toolName: preview.toolName, workItem: result.workItem, durationMs: Date.now() - startedAt });\n }\n }\n\n if (result.workItem.workKind === \"projectContextRefresh\") {\n try {\n return await finalizeProjectContextRefreshWork({\n apiClient,\n durationMs: Date.now() - startedAt,\n executionRoot,\n projectId,\n repositoryLinkId,\n runnerId,\n sessionContext,\n toolConfig,\n toolName: preview.toolName,\n toolResult,\n workItem: result.workItem\n });\n } catch (error) {\n return recordFinalizationFailure({ apiClient, error, isolationTelemetry, projectId, repositoryLinkId, runnerId, sessionContext, toolConfig, toolName: preview.toolName, workItem: result.workItem, durationMs: Date.now() - startedAt });\n }\n }\n\n if (result.workItem.workKind === \"implementationVerification\") {\n try {\n return await finalizeImplementationVerificationWork({\n apiClient,\n durationMs: Date.now() - startedAt,\n projectId,\n repositoryLinkId,\n runnerId,\n sessionContext,\n toolConfig,\n toolName: preview.toolName,\n toolResult,\n workItem: result.workItem\n });\n } catch (error) {\n return recordFinalizationFailure({ apiClient, error, isolationTelemetry, projectId, repositoryLinkId, runnerId, sessionContext, toolConfig, toolName: preview.toolName, workItem: result.workItem, durationMs: Date.now() - startedAt });\n }\n }\n\n if (result.workItem.workKind === \"testQualityScan\") {\n try {\n return await finalizeTestQualityScanWork({\n apiClient,\n durationMs: Date.now() - startedAt,\n projectId,\n repositoryLinkId,\n runnerId,\n sessionContext,\n toolConfig,\n toolName: preview.toolName,\n toolResult,\n workItem: result.workItem\n });\n } catch (error) {\n return recordFinalizationFailure({ apiClient, error, isolationTelemetry, projectId, repositoryLinkId, runnerId, sessionContext, toolConfig, toolName: preview.toolName, workItem: result.workItem, durationMs: Date.now() - startedAt });\n }\n }\n\n if (result.workItem.workKind === \"implementationTestGate\") {\n try {\n return await finalizeImplementationTestGateWork({\n apiClient,\n durationMs: Date.now() - startedAt,\n projectId,\n repositoryLinkId,\n runnerId,\n sessionContext,\n toolConfig,\n toolName: preview.toolName,\n toolResult,\n workItem: result.workItem\n });\n } catch (error) {\n return recordFinalizationFailure({ apiClient, error, isolationTelemetry, projectId, repositoryLinkId, runnerId, sessionContext, toolConfig, toolName: preview.toolName, workItem: result.workItem, durationMs: Date.now() - startedAt });\n }\n }\n\n let finalStatus: \"completed\" | \"failed\" | \"blocked\" = toolResult.exitCode === 0 ? \"completed\" : \"failed\";\n const durationMs = Date.now() - startedAt;\n const failureExcerpt = toolResult.exitCode === 0 ? undefined : truncateLogExcerpt(toolResult.stderr || toolResult.stdout);\n let implementationHandoff: ImplementationHandoff | undefined;\n let finalMessage = `${preview.toolName} exited with code ${toolResult.exitCode}.`;\n let finalError = failureExcerpt;\n\n if (toolResult.exitCode === 0 && (result.workItem.workKind ?? \"implementation\") === \"implementation\") {\n await recordRunnerMilestone(apiClient, projectId, result.workItem, runnerId, repositoryLinkId, {\n status: \"running\",\n summary: \"Preparing GitHub PR handoff for implementation work.\",\n idempotencyKey: `runner_milestone_handoff_started_${result.workItem.workItemId}_${result.workItem.attempt}`,\n metadata: { executionWorktreeKey: isolationTelemetry.executionWorktreeKey ?? \"\", executionBranch: isolationTelemetry.executionBranch ?? \"\" }\n });\n const repositoryLink = await loadWorkItemRepositoryLink(apiClient, projectId, result.workItem.repositoryLinkId ?? repositoryLinkId);\n const approvedArtifacts = await apiClient.listBrainDocuments(projectId).then((response) => response.documents).catch((error) => {\n implementationHandoff = {\n status: \"blocked\",\n cleanupStatus: \"pending\",\n artifacts: { included: [], skipped: [], blocked: [] },\n message: \"Implementation handoff is blocked because approved artifact metadata could not be loaded.\",\n error: truncateLogExcerpt(errorDetail(error))\n };\n return undefined;\n });\n if (!implementationHandoff) {\n implementationHandoff = await completeImplementationHandoff({\n ...(approvedArtifacts ? { approvedArtifacts } : {}),\n primaryRepoRoot: root,\n ...(repositoryLink ? { repositoryLink } : {}),\n verificationSummary: \"Local execution reported completion.\",\n workItem: result.workItem,\n ...(worktreeIsolation.isolation ? { worktreeIsolation: worktreeIsolation.isolation } : {}),\n worktreePath: executionRoot\n });\n }\n finalStatus = implementationHandoff.status === \"prReady\" || implementationHandoff.status === \"noChanges\" ? \"completed\" : \"blocked\";\n finalMessage = implementationHandoff.message ?? \"Implementation handoff finished.\";\n finalError = implementationHandoff.error;\n }\n\n const updatedToolSession = await finalizeToolSession({\n apiClient,\n projectId,\n status: toolResult.exitCode === 0 ? \"completed\" : \"failed\",\n runnerId,\n workItemId: result.workItem.workItemId,\n stdout: toolResult.stdout,\n ...(sessionContext.toolSession ? { session: sessionContext.toolSession } : {}),\n ...(toolResult.messageCount !== undefined ? { messageCount: toolResult.messageCount } : {}),\n ...(toolResult.tokensIn !== undefined ? { tokensIn: toolResult.tokensIn } : {}),\n ...(toolResult.tokensOut !== undefined ? { tokensOut: toolResult.tokensOut } : {}),\n ...(toolResult.costUsd !== undefined ? { costUsd: toolResult.costUsd } : {})\n });\n let statusResult: Awaited<ReturnType<ApiClient[\"updateWorkStatus\"]>>;\n try {\n statusResult = await apiClient.updateWorkStatus(\n projectId,\n result.workItem.workItemId,\n finalStatus,\n `run_${result.workItem.workItemId}_${randomUUID()}`,\n runnerId,\n {\n tool: preview.toolName,\n ...(toolResult.model ? { model: toolResult.model } : {}),\n durationMs,\n message: finalMessage,\n ...isolationTelemetry,\n ...(finalStatus === \"blocked\" ? { blockerReason: finalMessage } : {}),\n sessionPolicy: sessionContext.policy,\n sessionDecision: sessionContext.decision,\n sessionDecisionReason: sessionContext.reason,\n ...(updatedToolSession ? { toolSessionId: updatedToolSession.toolSessionId } : {}),\n ...(updatedToolSession?.sessionGroupKey ? { sessionGroupKey: updatedToolSession.sessionGroupKey } : {}),\n ...(toolResult.tokensIn !== undefined ? { tokensIn: toolResult.tokensIn } : {}),\n ...(toolResult.tokensOut !== undefined ? { tokensOut: toolResult.tokensOut } : {}),\n ...(toolResult.costUsd !== undefined ? { costUsd: toolResult.costUsd } : {}),\n ...(implementationHandoff ? { implementationHandoff } : {}),\n ...(finalError ? { error: finalError } : {})\n }\n );\n } catch (error) {\n if (error instanceof AmistioApiError && error.status === 409 && error.detail.includes(\"implementation_test_gate_required\")) {\n const gateMessage = \"Implementation test gate was queued and must pass before completion or PR handoff is finalized.\";\n await recordRunnerMilestone(apiClient, projectId, result.workItem, runnerId, repositoryLinkId, {\n status: \"queued\",\n summary: gateMessage,\n idempotencyKey: `runner_milestone_test_gate_required_${result.workItem.workItemId}_${result.workItem.attempt}`,\n metadata: { tool: preview.toolName, durationMs, executionWorktreeKey: isolationTelemetry.executionWorktreeKey ?? \"\", executionBranch: isolationTelemetry.executionBranch ?? \"\" }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig, currentRunnerMode(), heartbeatConcurrency));\n console.log(gateMessage);\n return { status: \"blocked\", exitCode: 0 };\n }\n throw error;\n }\n await recordRunnerMilestone(apiClient, projectId, result.workItem, runnerId, repositoryLinkId, {\n status: finalStatus,\n summary: finalMessage,\n idempotencyKey: `runner_milestone_finished_${result.workItem.workItemId}_${statusResult.workItem.idempotencyKey}`,\n metadata: {\n tool: preview.toolName,\n durationMs,\n exitCode: toolResult.exitCode,\n verificationSummary: finalStatus === \"completed\" ? \"Local execution reported completion.\" : \"Local execution reported failure.\",\n executionWorktreeKey: isolationTelemetry.executionWorktreeKey ?? \"\",\n executionBranch: isolationTelemetry.executionBranch ?? \"\",\n ...(implementationHandoff?.status ? { handoffStatus: implementationHandoff.status } : {}),\n ...(implementationHandoff?.prUrl ? { prUrl: implementationHandoff.prUrl } : {}),\n ...(implementationHandoff?.cleanupStatus ? { cleanupStatus: implementationHandoff.cleanupStatus } : {}),\n ...(implementationHandoff?.artifacts ? artifactHandoffMetadata(implementationHandoff.artifacts) : {})\n }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig, currentRunnerMode(), heartbeatConcurrency));\n const durationSeconds = Math.round(durationMs / 1000);\n console.log(`Marked ${statusResult.workItem.workItemId} ${statusResult.workItem.status} after ${durationSeconds}s.`);\n\n return { status: finalStatus, exitCode: finalStatus === \"completed\" ? toolResult.exitCode : 1 };\n}\n\nfunction artifactHandoffMetadata(artifacts: NonNullable<ImplementationHandoff[\"artifacts\"]>): Record<string, number> {\n return {\n artifactIncludedCount: artifacts.included.length,\n artifactSkippedCount: artifacts.skipped.length,\n artifactBlockedCount: artifacts.blocked.length\n };\n}\n\nasync function loadWorkItemRepositoryLink(apiClient: ApiClient, projectId: string, repositoryLinkId: string): Promise<RepositoryLinkItem | undefined> {\n const { repositoryLinks } = await apiClient.listRepositoryLinks(projectId);\n return repositoryLinks.find((link) => link.repositoryLinkId === repositoryLinkId && link.status !== \"revoked\");\n}\n\nasync function prepareWorktreeForClaimedItem({ apiClient, heartbeatConcurrency, maxPreflightAttempts, projectId, repositoryLinkId, root, runnerId, toolConfig, workItem }: {\n apiClient: ApiClient;\n heartbeatConcurrency: RunnerHeartbeatConcurrencyMetadata;\n maxPreflightAttempts: number;\n projectId: string;\n repositoryLinkId: string;\n root: string;\n runnerId: string;\n toolConfig: RunnerToolConfig;\n workItem: WorkItem;\n}): Promise<{ status: \"ready\"; isolation?: GitWorktreeIsolation } | { status: \"retrying\" | \"failed\"; message: string }> {\n if (!needsGitWorktreeIsolation(workItem)) {\n return { status: \"ready\" };\n }\n\n const identity = resolveWorktreeIdentity(workItem);\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: \"running\",\n summary: `Checking Git worktree isolation for attempt ${workItem.attempt}/${maxPreflightAttempts}.`,\n idempotencyKey: `runner_milestone_worktree_preflight_${workItem.workItemId}_${workItem.attempt}`,\n metadata: { executionWorktreeKey: identity.worktreeKey, executionBranch: identity.branch, implementationScopeId: identity.implementationScopeId, attempt: workItem.attempt, maxAttempts: maxPreflightAttempts }\n });\n try {\n const isolation = await prepareGitWorktreeIsolation(root, workItem);\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: \"running\",\n summary: isolation.preparedLocalEnvironmentFileCount ? `Prepared Git worktree ${isolation.worktreeKey} on ${isolation.branch} and local environment files.` : `Prepared Git worktree ${isolation.worktreeKey} on ${isolation.branch}.`,\n idempotencyKey: `runner_milestone_worktree_${workItem.workItemId}_${workItem.attempt}`,\n metadata: { executionWorktreeKey: isolation.worktreeKey, executionBranch: isolation.branch, implementationScopeId: isolation.implementationScopeId, ...(isolation.preparedLocalEnvironmentFileCount ? { preparedLocalEnvironmentFileCount: isolation.preparedLocalEnvironmentFileCount } : {}) }\n });\n return { status: \"ready\", isolation };\n } catch (error) {\n const message = errorMessage(error);\n const telemetry = workItemIsolationTelemetry(workItem, { ...identity, baseRevision: workItem.baseRevision ?? \"unknown\", worktreePath: \"\" });\n const finalAttempt = workItem.attempt >= maxPreflightAttempts;\n const statusMessage = finalAttempt\n ? `Git worktree preflight failed after ${workItem.attempt}/${maxPreflightAttempts} attempts. ${message}`\n : `Git worktree preflight attempt ${workItem.attempt}/${maxPreflightAttempts} failed. Requeueing for retry. ${message}`;\n const statusResult = await apiClient.updateWorkStatus(projectId, workItem.workItemId, finalAttempt ? \"failed\" : \"approved\", `worktree_${finalAttempt ? \"failed\" : \"retry\"}_${workItem.workItemId}_${workItem.attempt}_${randomUUID()}`, runnerId, {\n ...telemetry,\n message: statusMessage,\n ...(finalAttempt ? { blockerReason: message } : { releaseClaim: true }),\n error: message\n });\n await recordRunnerMilestone(apiClient, projectId, statusResult.workItem, runnerId, repositoryLinkId, {\n status: finalAttempt ? \"failed\" : \"warning\",\n summary: statusMessage,\n idempotencyKey: `runner_milestone_worktree_${finalAttempt ? \"failed\" : \"retry\"}_${workItem.workItemId}_${statusResult.workItem.idempotencyKey}`,\n metadata: { executionWorktreeKey: telemetry.executionWorktreeKey ?? \"\", executionBranch: telemetry.executionBranch ?? \"\", implementationScopeId: telemetry.implementationScopeId ?? \"\", attempt: workItem.attempt, maxAttempts: maxPreflightAttempts, error: message }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", {\n ...runnerHeartbeatMetadata(toolConfig, currentRunnerMode(), heartbeatConcurrency),\n preferenceMessage: statusMessage\n });\n console.error(statusMessage);\n return { status: finalAttempt ? \"failed\" : \"retrying\", message: statusMessage };\n }\n}\n\nfunction startWorkLeaseRenewal({ apiClient, projectId, repositoryLinkId, runnerId, toolConfig, workItem, telemetry, heartbeatConcurrency }: {\n apiClient: ApiClient;\n projectId: string;\n repositoryLinkId: string;\n runnerId: string;\n toolConfig: RunnerToolConfig;\n workItem: WorkItem;\n telemetry: WorkStatusTelemetryLike;\n heartbeatConcurrency: RunnerHeartbeatConcurrencyMetadata;\n}) {\n let stopped = false;\n const renew = async () => {\n if (stopped) return;\n const leaseExpiresAt = new Date(Date.now() + RUNNER_WORK_LEASE_SECONDS * 1000).toISOString();\n try {\n await apiClient.updateWorkStatus(projectId, workItem.workItemId, \"running\", `lease_renewal_${workItem.workItemId}_${workItem.attempt}_${Date.now()}`, runnerId, {\n ...telemetry,\n leaseExpiresAt\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"running\", {\n ...runnerHeartbeatMetadata(toolConfig, currentRunnerMode(), heartbeatConcurrency),\n currentWorkItemId: workItem.workItemId,\n ...(telemetry.implementationScopeId ? { currentImplementationScopeId: telemetry.implementationScopeId } : {}),\n ...(telemetry.executionWorktreeKey ? { currentWorktreeKey: telemetry.executionWorktreeKey } : {}),\n ...(telemetry.executionBranch ? { currentBranch: telemetry.executionBranch } : {})\n });\n } catch (error) {\n const detail = truncateLogExcerpt(errorDetail(error));\n console.error(`Could not renew Amistio work lease for ${workItem.workItemId}: ${detail}`);\n await apiClient.recordRunnerLog(projectId, {\n runnerId,\n repositoryLinkId,\n status: \"failed\",\n workItemId: workItem.workItemId,\n workTitle: workItem.title,\n ...(workItem.workKind ? { workKind: workItem.workKind } : {}),\n ...(workItem.claimLaneId ? { claimLaneId: workItem.claimLaneId } : {}),\n message: \"Runner could not renew the active work lease.\",\n error: detail,\n machineId: runnerMachineId()\n }).catch(() => undefined);\n }\n };\n const timer = setInterval(() => { void renew(); }, RUNNER_WORK_LEASE_RENEWAL_MS);\n timer.unref?.();\n return () => {\n stopped = true;\n clearInterval(timer);\n };\n}\n\nasync function recordFinalizationFailure({ apiClient, durationMs, error, isolationTelemetry, projectId, repositoryLinkId, runnerId, sessionContext, toolConfig, toolName, workItem }: {\n apiClient: ApiClient;\n durationMs: number;\n error: unknown;\n isolationTelemetry: WorkStatusTelemetryLike;\n projectId: string;\n repositoryLinkId: string;\n runnerId: string;\n sessionContext: PreparedToolSession;\n toolConfig: RunnerToolConfig;\n toolName: string;\n workItem: WorkItem;\n}): Promise<{ status: \"failed\"; exitCode: number; message: string }> {\n const detail = truncateLogExcerpt(errorDetail(error));\n const message = `${toolName} completed, but Amistio could not finalize the result. ${safeFinalizationFailureSummary(error)}`;\n const settlements = await Promise.allSettled([\n apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig)),\n markToolSessionBlocked(apiClient, projectId, sessionContext.toolSession, errorMessage(error)),\n apiClient.updateWorkStatus(projectId, workItem.workItemId, \"failed\", `finalize_failed_${workItem.workItemId}_${workItem.attempt}_${randomUUID()}`, runnerId, {\n ...isolationTelemetry,\n tool: toolName,\n durationMs,\n message,\n error: detail,\n ...(sessionContext.toolSession ? { toolSessionId: sessionContext.toolSession.toolSessionId } : {}),\n sessionPolicy: sessionContext.policy,\n sessionDecision: sessionContext.decision,\n sessionDecisionReason: sessionContext.reason\n }),\n apiClient.recordRunnerLog(projectId, {\n runnerId,\n repositoryLinkId,\n status: \"failed\",\n workItemId: workItem.workItemId,\n workTitle: workItem.title,\n ...(workItem.workKind ? { workKind: workItem.workKind } : {}),\n ...(workItem.claimLaneId ? { claimLaneId: workItem.claimLaneId } : {}),\n tool: toolName,\n durationMs,\n message,\n error: detail,\n machineId: runnerMachineId()\n }),\n recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: \"failed\",\n summary: message,\n idempotencyKey: `runner_milestone_finalization_failed_${workItem.workItemId}_${workItem.attempt}`,\n metadata: { tool: toolName, durationMs, error: detail }\n })\n ]);\n logRejectedSettlements(\"record finalization failure\", settlements);\n console.error(detail);\n return { status: \"failed\", exitCode: 1, message };\n}\n\nfunction safeFinalizationFailureSummary(error: unknown): string {\n if (error instanceof AmistioApiError) {\n return truncateLogExcerpt(error.message);\n }\n return \"Review the runner log for the finalization error.\";\n}\n\nfunction workItemIsolationTelemetry(workItem: WorkItem, isolation: GitWorktreeIsolation | undefined): WorkStatusTelemetryLike {\n const implementationScopeId = isolation?.implementationScopeId ?? workItem.implementationScopeId;\n const executionBranch = isolation?.branch ?? workItem.executionBranch;\n const executionWorktreeKey = isolation?.worktreeKey ?? workItem.executionWorktreeKey;\n const repositoryLockId = isolation?.repositoryLockId ?? workItem.repositoryLockId;\n return {\n ...(needsGitWorktreeIsolation(workItem) ? { isolationMode: \"gitWorktree\" as const } : workItem.isolationMode ? { isolationMode: workItem.isolationMode } : {}),\n ...(workItem.claimLaneId ? { claimLaneId: workItem.claimLaneId } : {}),\n ...(workItem.claimLeaseId ? { claimLeaseId: workItem.claimLeaseId } : {}),\n ...(workItem.controllingAdrId ? { controllingAdrId: workItem.controllingAdrId } : {}),\n ...(implementationScopeId ? { implementationScopeId } : {}),\n ...(executionBranch ? { executionBranch } : {}),\n ...(executionWorktreeKey ? { executionWorktreeKey } : {}),\n ...(repositoryLockId ? { repositoryLockId } : {}),\n ...(isolation?.baseRevision && isolation.baseRevision !== \"unknown\" ? { baseRevision: isolation.baseRevision } : {}),\n machineId: runnerMachineId()\n };\n}\n\ntype WorkStatusTelemetryLike = Pick<WorkStatusTelemetry, \"baseRevision\" | \"claimLaneId\" | \"claimLeaseId\" | \"controllingAdrId\" | \"executionBranch\" | \"executionWorktreeKey\" | \"implementationScopeId\" | \"isolationMode\" | \"machineId\" | \"repositoryLockId\">;\n\nasync function recordRunnerMilestone(apiClient: ApiClient, projectId: string, workItem: WorkItem, runnerId: string, repositoryLinkId: string, input: Omit<ActivityEventMutation, \"eventType\" | \"runnerId\" | \"repositoryLinkId\" | \"relatedWorkItemId\" | \"relatedDocumentId\" | \"generatedDraftId\">): Promise<void> {\n const autopilot = autopilotWorkMetadata(workItem);\n const metadata = { ...autopilotRunnerMetadata(workItem), ...(workItem.claimLaneId ? { claimLaneId: workItem.claimLaneId } : {}), ...(input.metadata ?? {}) };\n await apiClient.recordActivityEvent(projectId, {\n eventType: \"runnerMilestone\",\n runnerId,\n repositoryLinkId,\n ...(workItem.claimLaneId ? { claimLaneId: workItem.claimLaneId } : {}),\n relatedWorkItemId: workItem.workItemId,\n ...(workItem.reviewDocumentId ? { relatedDocumentId: workItem.reviewDocumentId } : workItem.impactDocumentId ? { relatedDocumentId: workItem.impactDocumentId } : {}),\n ...(workItem.issueId ? { relatedIssueId: workItem.issueId } : {}),\n ...(autopilot.autopilotAuthorizationId ? { relatedAutopilotAuthorizationId: autopilot.autopilotAuthorizationId } : {}),\n ...(autopilot.autopilotCandidateId ? { relatedAutopilotCandidateId: autopilot.autopilotCandidateId } : {}),\n ...(workItem.generatedDraftId ? { generatedDraftId: workItem.generatedDraftId } : {}),\n ...input,\n ...(Object.keys(metadata).length ? { metadata } : {})\n }).catch(() => undefined);\n}\n\nfunction formatAutopilotListSuffix(workItem: WorkItem): string {\n const autopilot = autopilotWorkMetadata(workItem);\n if (!autopilot.autopilotAuthorizationId) {\n return \"\";\n }\n const details = [\n autopilot.autopilotClassificationOutcome ?? \"authorized\",\n workItem.workKind ?? \"implementation\",\n autopilot.autopilotCandidateType,\n autopilot.autopilotPolicyVersion ? `policy ${autopilot.autopilotPolicyVersion}` : undefined,\n `auth ${autopilot.autopilotAuthorizationId}`,\n autopilot.autopilotCandidateId ? `candidate ${autopilot.autopilotCandidateId}` : undefined\n ].filter(Boolean).join(\", \");\n return ` (autopilot: ${details})`;\n}\n\nfunction formatAutopilotClaimLine(workItem: WorkItem): string | undefined {\n const autopilot = autopilotWorkMetadata(workItem);\n if (!autopilot.autopilotAuthorizationId) {\n return undefined;\n }\n const candidate = autopilot.autopilotCandidateId ? `, candidate ${autopilot.autopilotCandidateId}` : \"\";\n const candidateType = autopilot.autopilotCandidateType ? `, ${autopilot.autopilotCandidateType}` : \"\";\n return `Autopilot authorization: ${autopilot.autopilotAuthorizationId} (${autopilot.autopilotClassificationOutcome ?? \"authorized\"}, ${workItem.workKind ?? \"implementation\"}${candidateType}, policy ${autopilot.autopilotPolicyVersion ?? \"unknown\"}${candidate}). Local runner safety rules still apply.`;\n}\n\nfunction autopilotRunnerMetadata(workItem: WorkItem): Record<string, string> {\n const autopilot = autopilotWorkMetadata(workItem);\n return {\n ...(autopilot.autopilotAuthorizationId ? { autopilotAuthorizationId: autopilot.autopilotAuthorizationId } : {}),\n ...(autopilot.autopilotCandidateId ? { autopilotCandidateId: autopilot.autopilotCandidateId } : {}),\n ...(autopilot.autopilotCandidateType ? { autopilotCandidateType: autopilot.autopilotCandidateType } : {}),\n ...(autopilot.autopilotClassificationOutcome ? { autopilotOutcome: autopilot.autopilotClassificationOutcome } : {}),\n ...(autopilot.autopilotPolicyVersion ? { autopilotPolicyVersion: autopilot.autopilotPolicyVersion } : {})\n };\n}\n\nfunction autopilotWorkMetadata(workItem: WorkItem): WorkItem & { autopilotAuthorizationId?: string; autopilotCandidateId?: string; autopilotCandidateType?: string; autopilotClassificationOutcome?: string; autopilotPolicyVersion?: string } {\n return workItem as WorkItem & { autopilotAuthorizationId?: string; autopilotCandidateId?: string; autopilotCandidateType?: string; autopilotClassificationOutcome?: string; autopilotPolicyVersion?: string };\n}\n\nfunction logRejectedSettlements(action: string, settlements: PromiseSettledResult<unknown>[]) {\n for (const settlement of settlements) {\n if (settlement.status === \"rejected\") {\n console.error(`${action} failed: ${errorMessage(settlement.reason)}`);\n }\n }\n}\n\ninterface RunnerCommandExecutionContext {\n accountId: string;\n apiUrl: string;\n backgroundArgs: string[];\n projectId: string;\n repositoryLinkId: string;\n root: string;\n runnerId: string;\n}\n\ninterface RunnerCommandExecutionResult {\n handled: boolean;\n succeeded: boolean;\n stopRunner?: boolean;\n message?: string;\n}\n\nasync function runPendingRunnerCommand(apiClient: ApiClient, context: RunnerCommandExecutionContext, heartbeatMetadata: RunnerHeartbeatMetadata): Promise<RunnerCommandExecutionResult> {\n const { commands } = await apiClient.listRunnerCommands(context.projectId, context.runnerId, context.repositoryLinkId).catch(() => ({ commands: [] }));\n const command = commands\n .filter((item) => item.status === \"pending\" || item.status === \"acknowledged\" || item.status === \"running\")\n .sort((first, second) => Date.parse(first.createdAt) - Date.parse(second.createdAt))[0];\n if (!command) {\n return { handled: false, succeeded: true };\n }\n\n await updateRunnerCommandStatus(apiClient, context, command, \"acknowledged\", \"Command acknowledged by local runner.\");\n await updateRunnerCommandStatus(apiClient, context, command, \"running\", `Running ${runnerCommandLabel(command.commandKind)} command.`);\n\n const result = await executeRunnerCommand(apiClient, command, context);\n await updateRunnerCommandStatus(apiClient, context, command, result.succeeded ? \"completed\" : \"failed\", result.message, result.error);\n if (command.commandKind === \"remove\" && result.succeeded) {\n await new LocalCredentialStore().delete(credentialKey(context.accountId, context.projectId, context.repositoryLinkId));\n }\n if (result.stopRunner && command.commandKind === \"remove\") {\n await apiClient.sendRunnerHeartbeat(context.projectId, context.runnerId, context.repositoryLinkId, \"offline\", heartbeatMetadata).catch(() => undefined);\n }\n\n return { handled: true, succeeded: result.succeeded, message: result.message, ...(result.stopRunner ? { stopRunner: true } : {}) };\n}\n\nasync function updateRunnerCommandStatus(apiClient: ApiClient, context: RunnerCommandExecutionContext, command: RunnerCommandItem, status: \"acknowledged\" | \"running\" | \"completed\" | \"failed\", message: string, error?: string): Promise<RunnerCommandItem> {\n const result = await apiClient.updateRunnerCommand(context.projectId, command.commandId, {\n runnerId: context.runnerId,\n repositoryLinkId: context.repositoryLinkId,\n status,\n idempotencyKey: `runner_command_${command.commandId}_${status}_${randomUUID()}`,\n message,\n ...(error ? { error } : {})\n });\n return result.command;\n}\n\nasync function executeRunnerCommand(apiClient: ApiClient, command: RunnerCommandItem, context: RunnerCommandExecutionContext): Promise<{ succeeded: boolean; stopRunner?: boolean; message: string; error?: string }> {\n if (command.commandKind === \"remove\") {\n return { succeeded: true, stopRunner: true, message: \"Runner credential revoked. This local runner will stop after removing its stored credential.\" };\n }\n\n if (command.commandKind === \"restart\") {\n return restartCurrentRunner(context);\n }\n\n if (command.commandKind === \"implementationHandoffRecovery\") {\n return executeImplementationHandoffRecoveryCommand(apiClient, command, context);\n }\n\n return runOfficialCliUpdateWithRuntimeRefresh({\n mode: currentRunnerMode(),\n restartBackgroundRunner: () => restartCurrentRunner(context, { useUpdatedCliExecutable: true })\n });\n}\n\nasync function executeImplementationHandoffRecoveryCommand(apiClient: ApiClient, command: RunnerCommandItem, context: RunnerCommandExecutionContext): Promise<{ succeeded: boolean; message: string; error?: string }> {\n if (!command.workItemId || !command.handoffRecoveryAction) {\n return { succeeded: false, message: \"Handoff recovery command is missing a scoped work item or action.\" };\n }\n const workItem = await findRecoveryWorkItem(apiClient, context.projectId, command.workItemId);\n if (!workItem) {\n return { succeeded: false, message: \"Handoff recovery work item was not found.\" };\n }\n if (workItem.repositoryLinkId && workItem.repositoryLinkId !== context.repositoryLinkId) {\n return { succeeded: false, message: \"Handoff recovery command is not scoped to this repository link.\" };\n }\n if (!workItem.implementationHandoff?.recovery?.availableActions.includes(command.handoffRecoveryAction)) {\n return { succeeded: false, message: \"Handoff recovery action is no longer available for this work item.\" };\n }\n\n try {\n if (command.handoffRecoveryAction === \"retryHandoff\") {\n return retryImplementationHandoff(apiClient, context, workItem);\n }\n if (isCleanupHandoffRecoveryAction(command.handoffRecoveryAction)) {\n return retryImplementationHandoffCleanup(apiClient, context, workItem);\n }\n return { succeeded: false, message: \"Handoff recovery action is not a runner-local command.\" };\n } catch (error) {\n return { succeeded: false, message: \"Handoff recovery command failed locally.\", error: errorMessage(error) };\n }\n}\n\nasync function retryImplementationHandoff(apiClient: ApiClient, context: RunnerCommandExecutionContext, workItem: WorkItem): Promise<{ succeeded: boolean; message: string; error?: string }> {\n const worktreeIsolation = await resolveExistingGitWorktreeIsolation(context.root, workItem);\n const [{ repositoryLinks }, { documents }] = await Promise.all([apiClient.listRepositoryLinks(context.projectId), apiClient.listBrainDocuments(context.projectId)]);\n const repositoryLink = repositoryLinks.find((link) => link.repositoryLinkId === context.repositoryLinkId);\n const handoff = await completeImplementationHandoff({ approvedArtifacts: documents, primaryRepoRoot: context.root, ...(repositoryLink ? { repositoryLink } : {}), workItem, worktreeIsolation, worktreePath: worktreeIsolation.worktreePath });\n await submitRecoveredHandoff(apiClient, context, workItem, handoff, \"retryHandoff\");\n return {\n succeeded: handoff.status === \"prReady\" || handoff.status === \"noChanges\",\n message: handoff.message ?? handoffStatusMessage(handoff),\n ...(handoff.error ? { error: handoff.error } : {})\n };\n}\n\nasync function retryImplementationHandoffCleanup(apiClient: ApiClient, context: RunnerCommandExecutionContext, workItem: WorkItem): Promise<{ succeeded: boolean; message: string; error?: string }> {\n const worktreeIsolation = await resolveExistingGitWorktreeIsolation(context.root, workItem);\n const cleanup = await cleanupImplementationWorktree({ primaryRepoRoot: context.root, worktreePath: worktreeIsolation.worktreePath });\n const previousHandoff = workItem.implementationHandoff;\n const handoff: ImplementationHandoff = {\n ...(previousHandoff ?? { status: \"noChanges\" as const }),\n cleanupStatus: cleanup.status,\n ...(cleanup.message ? { cleanupMessage: cleanup.message } : {}),\n message: cleanup.status === \"completed\" ? \"Local handoff worktree cleanup completed.\" : \"Local handoff worktree cleanup still needs attention.\",\n ...(cleanup.status === \"failed\" && previousHandoff?.recovery ? { recovery: previousHandoff.recovery } : {})\n };\n await submitRecoveredHandoff(apiClient, context, workItem, handoff, \"retryCleanup\");\n return { succeeded: cleanup.status === \"completed\", message: handoff.message ?? handoffStatusMessage(handoff), ...(cleanup.message ? { error: cleanup.message } : {}) };\n}\n\nasync function findRecoveryWorkItem(apiClient: ApiClient, projectId: string, workItemId: string): Promise<WorkItem | undefined> {\n const { workItems } = await apiClient.listWorkItems(projectId);\n return workItems.find((item) => item.workItemId === workItemId);\n}\n\nasync function submitRecoveredHandoff(apiClient: ApiClient, context: RunnerCommandExecutionContext, workItem: WorkItem, handoff: ImplementationHandoff, action: ImplementationHandoffRecoveryAction): Promise<void> {\n await apiClient.updateWorkStatus(context.projectId, workItem.workItemId, recoveredHandoffWorkStatus(handoff), `handoff_recovery_${workItem.workItemId}_${action}_${randomUUID()}`, context.runnerId, {\n implementationHandoff: handoff,\n ...(handoff.message ? { message: handoff.message } : {}),\n ...(workItem.controllingAdrId ? { controllingAdrId: workItem.controllingAdrId } : {}),\n ...(workItem.implementationScopeId ? { implementationScopeId: workItem.implementationScopeId } : {}),\n ...(workItem.executionBranch ? { executionBranch: workItem.executionBranch } : {}),\n ...(workItem.executionWorktreeKey ? { executionWorktreeKey: workItem.executionWorktreeKey } : {}),\n ...(workItem.isolationMode ? { isolationMode: workItem.isolationMode } : {}),\n ...(workItem.repositoryLockId ? { repositoryLockId: workItem.repositoryLockId } : {})\n });\n}\n\nfunction recoveredHandoffWorkStatus(handoff: ImplementationHandoff): WorkStatus {\n return handoff.status === \"prReady\" || handoff.status === \"noChanges\" ? \"completed\" : \"blocked\";\n}\n\nfunction handoffStatusMessage(handoff: ImplementationHandoff): string {\n if (handoff.status === \"prReady\") return \"GitHub pull request is ready for review.\";\n if (handoff.status === \"noChanges\") return \"No repository changes were found.\";\n return \"Implementation handoff remains blocked.\";\n}\n\nfunction isCleanupHandoffRecoveryAction(action: ImplementationHandoffRecoveryAction): boolean {\n return action === \"retryCleanup\" || action === \"cleanNoChangeWorktree\";\n}\n\nasync function restartCurrentRunner(context: RunnerCommandExecutionContext, options: { useUpdatedCliExecutable?: boolean } = {}): Promise<{ succeeded: boolean; stopRunner?: boolean; message: string; error?: string }> {\n if (currentRunnerMode() !== \"background\") {\n return { succeeded: false, message: \"Foreground runners cannot be restarted remotely. Stop and start the local command manually.\" };\n }\n\n const [metadata] = await listRunnerDaemonMetadata({ accountId: context.accountId, projectId: context.projectId, repositoryLinkId: context.repositoryLinkId, runnerId: context.runnerId });\n if (!metadata) {\n return { succeeded: false, message: \"Background runner metadata was not found, so restart needs manual action.\" };\n }\n\n try {\n const replacement = await restartRunnerDaemonProcess(metadata, context.backgroundArgs, options.useUpdatedCliExecutable ? updatedCliRunnerLaunchOptions() : {});\n return { succeeded: true, stopRunner: true, message: `Replacement background runner started with PID ${replacement.pid}.` };\n } catch (error) {\n return { succeeded: false, message: \"Background restart failed.\", error: errorMessage(error) };\n }\n}\n\nfunction runnerCommandLabel(commandKind: RunnerCommandKind): string {\n if (commandKind === \"update\") return \"update\";\n if (commandKind === \"restart\") return \"restart\";\n if (commandKind === \"implementationHandoffRecovery\") return \"handoff recovery\";\n return \"remove\";\n}\n\nasync function replayPendingBrainGenerationFinalizations({ accountId, apiClient, projectId, repositoryLinkId, runnerId }: {\n accountId: string;\n apiClient: ApiClient;\n projectId: string;\n repositoryLinkId: string;\n runnerId: string;\n}): Promise<{ status: \"completed\" | \"failed\"; exitCode: number; message: string } | undefined> {\n const pendingEntries = await listPendingBrainGenerationFinalizations({ accountId, projectId, repositoryLinkId, runnerId });\n if (!pendingEntries.length) {\n return undefined;\n }\n\n let completedCount = 0;\n for (const entry of pendingEntries) {\n const replay = await submitBrainGenerationFinalizationEntry(apiClient, entry, { recordReplayTelemetry: true });\n if (replay.status === \"completed\") {\n completedCount += 1;\n continue;\n }\n return { status: \"failed\", exitCode: 1, message: replay.message };\n }\n\n const message = `Replayed ${completedCount} pending brain generation finalization${completedCount === 1 ? \"\" : \"s\"}.`;\n console.log(message);\n return { status: \"completed\", exitCode: 0, message };\n}\n\nasync function replayPendingResultFinalizations({ accountId, apiClient, projectId, repositoryLinkId, runnerId }: {\n accountId: string;\n apiClient: ApiClient;\n projectId: string;\n repositoryLinkId: string;\n runnerId: string;\n}): Promise<{ status: \"completed\" | \"failed\"; exitCode: number; message: string } | undefined> {\n const brainReplay = await replayPendingBrainGenerationFinalizations({ accountId, apiClient, projectId, repositoryLinkId, runnerId });\n if (brainReplay) {\n return brainReplay;\n }\n\n const pendingEntries = await listPendingDurableResultFinalizations({ accountId, projectId, repositoryLinkId, runnerId });\n if (!pendingEntries.length) {\n return undefined;\n }\n\n let completedCount = 0;\n for (const entry of pendingEntries) {\n const replay = await submitDurableResultFinalizationEntry(apiClient, entry, { recordReplayTelemetry: true });\n if (replay.status === \"completed\") {\n completedCount += 1;\n continue;\n }\n return { status: \"failed\", exitCode: 1, message: replay.message };\n }\n\n const message = `Replayed ${completedCount} pending runner result finalization${completedCount === 1 ? \"\" : \"s\"}.`;\n console.log(message);\n return { status: \"completed\", exitCode: 0, message };\n}\n\nasync function submitBrainGenerationFinalizationEntry(apiClient: ApiClient, entry: BrainGenerationFinalizationEntry, options: { recordReplayTelemetry?: boolean } = {}): Promise<{ status: \"completed\"; workItem: WorkItem; documentCount: number } | { status: \"failed\"; message: string; retryable: boolean }> {\n let result: Awaited<ReturnType<ApiClient[\"submitBrainGenerationResult\"]>>;\n try {\n result = await apiClient.submitBrainGenerationResult(entry.projectId, entry.workItemId, entry.result);\n } catch (error) {\n const detail = truncateLogExcerpt(errorMessage(error));\n if (isRetryableApiError(error)) {\n const updated = await markBrainGenerationFinalizationRetry(entry, detail);\n const message = `Pending brain generation finalization ${entry.workItemId} could not be replayed yet (${updated.retryCount} attempt${updated.retryCount === 1 ? \"\" : \"s\"}): ${detail}`;\n console.error(message);\n return { status: \"failed\", message, retryable: true };\n }\n await markBrainGenerationFinalizationTerminal(entry, detail);\n const message = `Pending brain generation finalization ${entry.workItemId} reached a terminal API failure: ${detail}`;\n console.error(message);\n return { status: \"failed\", message, retryable: false };\n }\n\n await deleteBrainGenerationFinalizationEntry(entry).catch((error) => {\n console.error(`delete pending brain generation finalization ${entry.workItemId} failed: ${errorMessage(error)}`);\n });\n if (options.recordReplayTelemetry) {\n await recordRunnerMilestone(apiClient, entry.projectId, result.workItem, entry.runnerId, entry.repositoryLinkId, {\n status: entry.result.status,\n summary: entry.result.status === \"completed\" ? \"Replayed pending brain generation result finalization.\" : \"Replayed pending brain generation failure finalization.\",\n idempotencyKey: `runner_milestone_generation_replayed_${entry.workItemId}_${result.workItem.idempotencyKey}`,\n metadata: { artifactCount: result.documents.length, replayedFinalization: true, workKind: entry.workKind }\n });\n await apiClient.sendRunnerHeartbeat(entry.projectId, entry.runnerId, entry.repositoryLinkId, \"online\", {\n ...runnerHeartbeatMetadata(),\n preferenceMessage: \"Pending result finalization replayed.\"\n }).catch(() => undefined);\n }\n return { status: \"completed\", workItem: result.workItem, documentCount: result.documents.length };\n}\n\nasync function submitDurableResultFinalizationEntry(apiClient: ApiClient, entry: DurableResultFinalizationEntry, options: { recordReplayTelemetry?: boolean } = {}): Promise<{ status: \"completed\"; workItem: WorkItem; response: unknown } | { status: \"failed\"; message: string; retryable: boolean }> {\n let response: unknown;\n try {\n response = await submitDurableResultMutation(apiClient, entry);\n } catch (error) {\n const detail = truncateLogExcerpt(errorMessage(error));\n if (isRetryableApiError(error)) {\n const updated = await markDurableResultFinalizationRetry(entry, detail);\n const message = `Pending ${runnerResultFinalizationLabel(entry)} finalization ${entry.workItemId} could not be replayed yet (${updated.retryCount} attempt${updated.retryCount === 1 ? \"\" : \"s\"}): ${detail}`;\n console.error(message);\n return { status: \"failed\", message, retryable: true };\n }\n await markDurableResultFinalizationTerminal(entry, detail);\n const message = `Pending ${runnerResultFinalizationLabel(entry)} finalization ${entry.workItemId} reached a terminal API failure: ${detail}`;\n console.error(message);\n return { status: \"failed\", message, retryable: false };\n }\n\n const workItem = durableResultResponseWorkItem(response);\n await deleteDurableResultFinalizationEntry(entry).catch((error) => {\n console.error(`delete pending ${runnerResultFinalizationLabel(entry)} finalization ${entry.workItemId} failed: ${errorMessage(error)}`);\n });\n if (options.recordReplayTelemetry) {\n await recordRunnerMilestone(apiClient, entry.projectId, workItem, entry.runnerId, entry.repositoryLinkId, {\n status: entry.result.status,\n summary: entry.result.status === \"completed\" ? `Replayed pending ${runnerResultFinalizationLabel(entry)} finalization.` : `Replayed pending ${runnerResultFinalizationLabel(entry)} failure finalization.`,\n idempotencyKey: `runner_milestone_result_replayed_${entry.workItemId}_${workItem.idempotencyKey}`,\n metadata: { replayedFinalization: true, resultKind: entry.resultKind, workKind: entry.workKind }\n });\n await apiClient.sendRunnerHeartbeat(entry.projectId, entry.runnerId, entry.repositoryLinkId, \"online\", {\n ...runnerHeartbeatMetadata(),\n preferenceMessage: \"Pending result finalization replayed.\"\n }).catch(() => undefined);\n }\n return { status: \"completed\", workItem, response };\n}\n\nasync function submitDurableResultMutation(apiClient: ApiClient, entry: DurableResultFinalizationEntry): Promise<unknown> {\n if (entry.resultKind === \"assistantResult\") {\n return apiClient.submitAssistantResult(entry.projectId, entry.workItemId, entry.result as AssistantResultMutation);\n }\n if (entry.resultKind === \"impactPreviewResult\") {\n return apiClient.submitImpactPreviewResult(entry.projectId, entry.workItemId, entry.result as ImpactPreviewResultMutation);\n }\n if (entry.resultKind === \"issueDiagnosisResult\") {\n return apiClient.submitIssueDiagnosisResult(entry.projectId, entry.workItemId, entry.result as IssueDiagnosisResultMutation);\n }\n if (entry.resultKind === \"securityPostureScanResult\") {\n return apiClient.submitSecurityPostureScanResult(entry.projectId, entry.workItemId, entry.result as SecurityPostureScanResultMutation);\n }\n if (entry.resultKind === \"appEvaluationScanResult\") {\n return apiClient.submitAppEvaluationScanResult(entry.projectId, entry.workItemId, entry.result as AppEvaluationScanResultMutation);\n }\n if (entry.resultKind === \"brainConsolidationScanResult\") {\n return apiClient.submitBrainConsolidationScanResult(entry.projectId, entry.workItemId, entry.result as BrainConsolidationScanResultMutation);\n }\n if (entry.resultKind === \"projectContextRefreshResult\") {\n return apiClient.submitProjectContextRefreshResult(entry.projectId, entry.workItemId, entry.result as ProjectContextRefreshResultMutation);\n }\n if (entry.resultKind === \"testQualityScanResult\") {\n return apiClient.submitTestQualityScanResult(entry.projectId, entry.workItemId, entry.result as TestQualityScanResultMutation);\n }\n if (entry.resultKind === \"implementationTestGateResult\") {\n return apiClient.submitImplementationTestGateResult(entry.projectId, entry.workItemId, entry.result as ImplementationTestGateResultMutation);\n }\n return apiClient.submitImplementationVerificationResult(entry.projectId, entry.workItemId, entry.result as ImplementationVerificationResultMutation);\n}\n\nfunction durableResultResponseWorkItem(response: unknown): WorkItem {\n if (response && typeof response === \"object\" && \"workItem\" in response) {\n return (response as { workItem: WorkItem }).workItem;\n }\n throw new Error(\"Runner result finalization response did not include a work item.\");\n}\n\nfunction runnerResultFinalizationLabel(entry: Pick<DurableResultFinalizationEntry, \"workKind\">): string {\n if (entry.workKind === \"appEvaluationScan\") return \"app evaluation scan\";\n if (entry.workKind === \"brainConsolidationScan\") return \"brain consolidation scan\";\n if (entry.workKind === \"securityPostureScan\") return \"security posture scan\";\n if (entry.workKind === \"projectContextRefresh\") return \"project context refresh\";\n if (entry.workKind === \"implementationVerification\") return \"implementation verification\";\n if (entry.workKind === \"testQualityScan\") return \"test quality scan\";\n if (entry.workKind === \"implementationTestGate\") return \"implementation test gate\";\n if (entry.workKind === \"issueDiagnosis\") return \"issue diagnosis\";\n if (entry.workKind === \"impactPreview\") return \"impact preview\";\n return \"assistant answer\";\n}\n\nasync function submitStagedDurableResultFinalization(apiClient: ApiClient, input: BrainGenerationFinalizationScope & {\n attempt: number;\n idempotencyKey: string;\n result: DurableResultFinalizationResult;\n resultKind: DurableResultFinalizationResultKind;\n workItemId: string;\n workKind: DurableResultFinalizationWorkKind;\n}): Promise<{ status: \"completed\"; workItem: WorkItem; response: unknown } | { status: \"failed\"; message: string; retryable: boolean }> {\n const entry = createDurableResultFinalizationEntry(input);\n await upsertDurableResultFinalizationEntry(entry);\n return submitDurableResultFinalizationEntry(apiClient, entry);\n}\n\nasync function submitPrimaryRunnerResult<TResponse>(apiClient: ApiClient, input: Parameters<typeof submitStagedDurableResultFinalization>[1]): Promise<TResponse | undefined> {\n const replay = await submitStagedDurableResultFinalization(apiClient, input);\n if (replay.status === \"failed\") {\n if (!replay.retryable) {\n throw new Error(replay.message);\n }\n return undefined;\n }\n return replay.response as TResponse;\n}\n\nfunction pendingSessionTelemetry(sessionContext: PreparedToolSession) {\n return {\n sessionPolicy: sessionContext.policy,\n sessionDecision: sessionContext.decision,\n sessionDecisionReason: sessionContext.reason,\n ...(sessionContext.toolSession ? { toolSessionId: sessionContext.toolSession.toolSessionId } : {}),\n ...(sessionContext.toolSession?.sessionGroupKey ? { sessionGroupKey: sessionContext.toolSession.sessionGroupKey } : {})\n };\n}\n\nasync function finalizeToolSessionBestEffort({ apiClient, projectId, runnerId, sessionContext, status, toolResult, workItemId }: {\n apiClient: ApiClient;\n projectId: string;\n runnerId: string;\n sessionContext: PreparedToolSession;\n status: \"completed\" | \"failed\";\n toolResult: LocalToolRunResult;\n workItemId: string;\n}): Promise<void> {\n const settlements = await Promise.allSettled([\n finalizeToolSession({\n apiClient,\n projectId,\n status,\n runnerId,\n workItemId,\n stdout: toolResult.stdout,\n ...(sessionContext.toolSession ? { session: sessionContext.toolSession } : {}),\n ...(toolResult.messageCount !== undefined ? { messageCount: toolResult.messageCount } : {}),\n ...(toolResult.tokensIn !== undefined ? { tokensIn: toolResult.tokensIn } : {}),\n ...(toolResult.tokensOut !== undefined ? { tokensOut: toolResult.tokensOut } : {}),\n ...(toolResult.costUsd !== undefined ? { costUsd: toolResult.costUsd } : {})\n })\n ]);\n logRejectedSettlements(\"finalize runner result tool session\", settlements);\n}\n\nasync function finalizeBrainGenerationWork({\n apiClient,\n durationMs,\n projectId,\n repositoryLinkId,\n runnerId,\n sessionContext,\n toolConfig,\n toolName,\n toolResult,\n workItem\n}: {\n apiClient: ApiClient;\n durationMs: number;\n projectId: string;\n repositoryLinkId: string;\n runnerId: string;\n sessionContext: PreparedToolSession;\n toolConfig: RunnerToolConfig;\n toolName: string;\n toolResult: LocalToolRunResult;\n workItem: WorkItem;\n}): Promise<{ status: \"completed\" | \"failed\"; exitCode: number }> {\n let artifacts: GeneratedBrainArtifact[] | undefined;\n let generationError: string | undefined;\n if (toolResult.exitCode === 0) {\n try {\n artifacts = parseBrainGenerationArtifacts(`${toolResult.stdout}\\n${toolResult.stderr}`);\n } catch (error) {\n generationError = errorMessage(error);\n }\n } else {\n generationError = truncateLogExcerpt(toolResult.stderr || toolResult.stdout) || `${toolName} exited with code ${toolResult.exitCode}.`;\n }\n\n const finalStatus = artifacts ? \"completed\" : \"failed\";\n const sessionTelemetry = {\n sessionPolicy: sessionContext.policy,\n sessionDecision: sessionContext.decision,\n sessionDecisionReason: sessionContext.reason,\n ...(sessionContext.toolSession ? { toolSessionId: sessionContext.toolSession.toolSessionId } : {}),\n ...(sessionContext.toolSession?.sessionGroupKey ? { sessionGroupKey: sessionContext.toolSession.sessionGroupKey } : {})\n };\n\n if (artifacts) {\n const completionMessage = workItem.workKind === \"planRevision\" ? `${toolName} returned a revised plan for review.` : `${toolName} generated ${artifacts.length} brain artifact${artifacts.length === 1 ? \"\" : \"s\"}.`;\n const resultMutation: BrainGenerationResultMutation = {\n status: \"completed\",\n runnerId,\n idempotencyKey: `generation_${workItem.workItemId}_${workItem.attempt}_${randomUUID()}`,\n artifacts,\n tool: toolName,\n durationMs,\n ...sessionTelemetry,\n message: completionMessage\n };\n const entry = createBrainGenerationFinalizationEntry({\n accountId: workItem.accountId,\n projectId,\n repositoryLinkId,\n runnerId,\n workItemId: workItem.workItemId,\n workKind: brainGenerationFinalizationWorkKind(workItem.workKind),\n attempt: workItem.attempt,\n idempotencyKey: resultMutation.idempotencyKey,\n result: resultMutation\n });\n await upsertBrainGenerationFinalizationEntry(entry);\n const replay = await submitBrainGenerationFinalizationEntry(apiClient, entry);\n if (replay.status === \"failed\") {\n if (!replay.retryable) {\n throw new Error(replay.message);\n }\n return { status: \"failed\", exitCode: 1 };\n }\n const toolSessionSettlement = await Promise.allSettled([\n finalizeToolSession({\n apiClient,\n projectId,\n status: finalStatus,\n runnerId,\n workItemId: workItem.workItemId,\n stdout: toolResult.stdout,\n ...(sessionContext.toolSession ? { session: sessionContext.toolSession } : {}),\n ...(toolResult.messageCount !== undefined ? { messageCount: toolResult.messageCount } : {}),\n ...(toolResult.tokensIn !== undefined ? { tokensIn: toolResult.tokensIn } : {}),\n ...(toolResult.tokensOut !== undefined ? { tokensOut: toolResult.tokensOut } : {}),\n ...(toolResult.costUsd !== undefined ? { costUsd: toolResult.costUsd } : {})\n })\n ]);\n logRejectedSettlements(\"finalize generation tool session\", toolSessionSettlement);\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: \"completed\",\n summary: completionMessage,\n idempotencyKey: `runner_milestone_generation_completed_${workItem.workItemId}_${entry.idempotencyKey}`,\n metadata: { tool: toolName, durationMs, artifactCount: replay.documentCount, verificationSummary: \"Generated artifacts were accepted by the Amistio API for review.\" }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig)).catch((error) => {\n console.error(`send generation completion heartbeat failed: ${errorMessage(error)}`);\n });\n console.log(workItem.workKind === \"planRevision\" ? \"Revised plan returned for review.\" : `Generated ${replay.documentCount} brain artifact${replay.documentCount === 1 ? \"\" : \"s\"} for review.`);\n return { status: \"completed\", exitCode: 0 };\n }\n\n const updatedToolSession = await finalizeToolSession({\n apiClient,\n projectId,\n status: finalStatus,\n runnerId,\n workItemId: workItem.workItemId,\n stdout: toolResult.stdout,\n ...(sessionContext.toolSession ? { session: sessionContext.toolSession } : {}),\n ...(toolResult.messageCount !== undefined ? { messageCount: toolResult.messageCount } : {}),\n ...(toolResult.tokensIn !== undefined ? { tokensIn: toolResult.tokensIn } : {}),\n ...(toolResult.tokensOut !== undefined ? { tokensOut: toolResult.tokensOut } : {}),\n ...(toolResult.costUsd !== undefined ? { costUsd: toolResult.costUsd } : {})\n });\n const failedSessionTelemetry = {\n ...sessionTelemetry,\n ...(updatedToolSession ? { toolSessionId: updatedToolSession.toolSessionId } : {}),\n ...(updatedToolSession?.sessionGroupKey ? { sessionGroupKey: updatedToolSession.sessionGroupKey } : {})\n };\n\n const failedResult = await apiClient.submitBrainGenerationResult(projectId, workItem.workItemId, {\n status: \"failed\",\n runnerId,\n idempotencyKey: `generation_${workItem.workItemId}_${randomUUID()}`,\n tool: toolName,\n durationMs,\n ...failedSessionTelemetry,\n message: `${toolName} did not produce valid brain artifacts.`,\n ...(generationError ? { error: generationError } : {})\n });\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: \"failed\",\n summary: generationError ?? `${toolName} did not produce valid brain artifacts.`,\n idempotencyKey: `runner_milestone_generation_failed_${workItem.workItemId}_${failedResult.workItem.idempotencyKey}`,\n metadata: { tool: toolName, durationMs, verificationSummary: \"Generation output could not be parsed into approved artifact JSON.\" }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig));\n console.error(generationError ?? \"Local runner generation failed.\");\n return { status: \"failed\", exitCode: toolResult.exitCode || 1 };\n}\n\nfunction brainGenerationFinalizationWorkKind(workKind: WorkKind | undefined): BrainGenerationFinalizationWorkKind {\n return workKind === \"planRevision\" ? \"planRevision\" : \"brainGeneration\";\n}\n\nasync function finalizeAssistantQuestionWork({\n apiClient,\n durationMs,\n projectId,\n repositoryLinkId,\n runnerId,\n sessionContext,\n toolConfig,\n toolName,\n toolResult,\n workItem\n}: {\n apiClient: ApiClient;\n durationMs: number;\n projectId: string;\n repositoryLinkId: string;\n runnerId: string;\n sessionContext: PreparedToolSession;\n toolConfig: RunnerToolConfig;\n toolName: string;\n toolResult: LocalToolRunResult;\n workItem: WorkItem;\n}): Promise<{ status: \"completed\" | \"failed\"; exitCode: number }> {\n let answerResult: ReturnType<typeof parseAssistantAnswerResult> | undefined;\n let answerError: string | undefined;\n if (toolResult.exitCode === 0) {\n try {\n answerResult = parseAssistantAnswerResult(`${toolResult.stdout}\\n${toolResult.stderr}`);\n } catch (error) {\n answerError = errorMessage(error);\n }\n } else {\n answerError = truncateLogExcerpt(toolResult.stderr || toolResult.stdout) || `${toolName} exited with code ${toolResult.exitCode}.`;\n }\n\n const finalStatus = answerResult ? \"completed\" : \"failed\";\n const sessionTelemetry = pendingSessionTelemetry(sessionContext);\n\n if (answerResult) {\n const resultMutation: AssistantResultMutation = {\n status: \"completed\",\n runnerId,\n idempotencyKey: `assistant_${workItem.workItemId}_${randomUUID()}`,\n answer: answerResult.answer,\n sourceBoundary: answerResult.sourceBoundary,\n citations: answerResult.citations,\n tool: toolName,\n durationMs,\n ...sessionTelemetry,\n message: `${toolName} returned a project knowledge answer.`\n };\n const result = await submitPrimaryRunnerResult<Awaited<ReturnType<ApiClient[\"submitAssistantResult\"]>>>(apiClient, {\n accountId: workItem.accountId,\n projectId,\n repositoryLinkId,\n runnerId,\n workItemId: workItem.workItemId,\n workKind: \"assistantQuestion\",\n resultKind: \"assistantResult\",\n attempt: workItem.attempt,\n idempotencyKey: resultMutation.idempotencyKey,\n result: resultMutation\n });\n if (!result) return { status: \"failed\", exitCode: 1 };\n await finalizeToolSessionBestEffort({ apiClient, projectId, runnerId, sessionContext, status: finalStatus, toolResult, workItemId: workItem.workItemId });\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: \"completed\",\n summary: `${toolName} returned a project knowledge answer.`,\n idempotencyKey: `runner_milestone_assistant_completed_${workItem.workItemId}_${result.workItem.idempotencyKey}`,\n metadata: { tool: toolName, durationMs, sourceBoundary: answerResult.sourceBoundary, citationCount: answerResult.citations.length }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig));\n console.log(\"Project knowledge answer returned.\");\n return { status: \"completed\", exitCode: 0 };\n }\n\n const failedMutation: AssistantResultMutation = {\n status: \"failed\",\n runnerId,\n idempotencyKey: `assistant_${workItem.workItemId}_${randomUUID()}`,\n tool: toolName,\n durationMs,\n ...sessionTelemetry,\n message: `${toolName} did not produce a valid project knowledge answer.`,\n ...(answerError ? { error: answerError } : {})\n };\n const failedResult = await submitPrimaryRunnerResult<Awaited<ReturnType<ApiClient[\"submitAssistantResult\"]>>>(apiClient, {\n accountId: workItem.accountId,\n projectId,\n repositoryLinkId,\n runnerId,\n workItemId: workItem.workItemId,\n workKind: \"assistantQuestion\",\n resultKind: \"assistantResult\",\n attempt: workItem.attempt,\n idempotencyKey: failedMutation.idempotencyKey,\n result: failedMutation\n });\n if (!failedResult) return { status: \"failed\", exitCode: 1 };\n await finalizeToolSessionBestEffort({ apiClient, projectId, runnerId, sessionContext, status: finalStatus, toolResult, workItemId: workItem.workItemId });\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: \"failed\",\n summary: answerError ?? `${toolName} did not produce a valid project knowledge answer.`,\n idempotencyKey: `runner_milestone_assistant_failed_${workItem.workItemId}_${failedResult.workItem.idempotencyKey}`,\n metadata: { tool: toolName, durationMs, verificationSummary: \"Assistant output did not include a valid structured answer.\" }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig));\n console.error(answerError ?? \"Local runner assistant answer failed.\");\n return { status: \"failed\", exitCode: toolResult.exitCode || 1 };\n}\n\nasync function finalizeImpactPreviewWork({\n apiClient,\n durationMs,\n projectId,\n repositoryLinkId,\n root,\n runnerId,\n sessionContext,\n toolConfig,\n toolName,\n toolResult,\n workItem\n}: {\n apiClient: ApiClient;\n durationMs: number;\n projectId: string;\n repositoryLinkId: string;\n root: string;\n runnerId: string;\n sessionContext: PreparedToolSession;\n toolConfig: RunnerToolConfig;\n toolName: string;\n toolResult: LocalToolRunResult;\n workItem: WorkItem;\n}): Promise<{ status: \"completed\" | \"failed\"; exitCode: number }> {\n let report = undefined as ReturnType<typeof parseImpactPreviewResult> | undefined;\n let previewError: string | undefined;\n if (toolResult.exitCode === 0) {\n try {\n report = parseImpactPreviewResult(`${toolResult.stdout}\\n${toolResult.stderr}`);\n } catch (error) {\n previewError = errorMessage(error);\n }\n } else {\n previewError = truncateLogExcerpt(toolResult.stderr || toolResult.stdout) || `${toolName} exited with code ${toolResult.exitCode}.`;\n }\n\n const finalStatus = report ? \"completed\" : \"failed\";\n const sessionTelemetry = pendingSessionTelemetry(sessionContext);\n\n if (report) {\n const metadata = await readProjectLink(root).catch(() => undefined);\n const resultMutation: ImpactPreviewResultMutation = {\n status: \"completed\",\n runnerId,\n idempotencyKey: `impact_${workItem.workItemId}_${randomUUID()}`,\n report: {\n ...report,\n analyzedRepoRevision: report.analyzedRepoRevision ?? metadata?.lastSyncedRevision\n },\n tool: toolName,\n durationMs,\n ...sessionTelemetry,\n message: `${toolName} returned an implementation impact preview.`\n };\n const result = await submitPrimaryRunnerResult<Awaited<ReturnType<ApiClient[\"submitImpactPreviewResult\"]>>>(apiClient, {\n accountId: workItem.accountId,\n projectId,\n repositoryLinkId,\n runnerId,\n workItemId: workItem.workItemId,\n workKind: \"impactPreview\",\n resultKind: \"impactPreviewResult\",\n attempt: workItem.attempt,\n idempotencyKey: resultMutation.idempotencyKey,\n result: resultMutation\n });\n if (!result) return { status: \"failed\", exitCode: 1 };\n await finalizeToolSessionBestEffort({ apiClient, projectId, runnerId, sessionContext, status: finalStatus, toolResult, workItemId: workItem.workItemId });\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: \"completed\",\n summary: `${toolName} returned an implementation impact preview.`,\n idempotencyKey: `runner_milestone_impact_completed_${workItem.workItemId}_${result.workItem.idempotencyKey}`,\n metadata: { tool: toolName, durationMs, riskLevel: report.riskLevel, likelyPathCount: report.likelyPaths.length, verificationSummary: report.verificationPlan }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig));\n console.log(result.implementationWorkItem ? \"Impact preview returned; implementation work is now queued.\" : \"Impact preview returned.\");\n return { status: \"completed\", exitCode: 0 };\n }\n\n const failedMutation: ImpactPreviewResultMutation = {\n status: \"failed\",\n runnerId,\n idempotencyKey: `impact_${workItem.workItemId}_${randomUUID()}`,\n tool: toolName,\n durationMs,\n ...sessionTelemetry,\n message: `${toolName} did not produce a valid impact preview.`,\n ...(previewError ? { error: previewError } : {})\n };\n const failedResult = await submitPrimaryRunnerResult<Awaited<ReturnType<ApiClient[\"submitImpactPreviewResult\"]>>>(apiClient, {\n accountId: workItem.accountId,\n projectId,\n repositoryLinkId,\n runnerId,\n workItemId: workItem.workItemId,\n workKind: \"impactPreview\",\n resultKind: \"impactPreviewResult\",\n attempt: workItem.attempt,\n idempotencyKey: failedMutation.idempotencyKey,\n result: failedMutation\n });\n if (!failedResult) return { status: \"failed\", exitCode: 1 };\n await finalizeToolSessionBestEffort({ apiClient, projectId, runnerId, sessionContext, status: finalStatus, toolResult, workItemId: workItem.workItemId });\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: \"failed\",\n summary: previewError ?? `${toolName} did not produce a valid impact preview.`,\n idempotencyKey: `runner_milestone_impact_failed_${workItem.workItemId}_${failedResult.workItem.idempotencyKey}`,\n metadata: { tool: toolName, durationMs, verificationSummary: \"Impact preview output did not include valid structured JSON.\" }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig));\n console.error(previewError ?? \"Local runner impact preview failed.\");\n return { status: \"failed\", exitCode: toolResult.exitCode || 1 };\n}\n\nasync function finalizeIssueDiagnosisWork({\n apiClient,\n durationMs,\n projectId,\n repositoryLinkId,\n runnerId,\n sessionContext,\n toolConfig,\n toolName,\n toolResult,\n workItem\n}: {\n apiClient: ApiClient;\n durationMs: number;\n projectId: string;\n repositoryLinkId: string;\n runnerId: string;\n sessionContext: PreparedToolSession;\n toolConfig: RunnerToolConfig;\n toolName: string;\n toolResult: LocalToolRunResult;\n workItem: WorkItem;\n}): Promise<{ status: \"completed\" | \"failed\"; exitCode: number }> {\n let diagnosis = undefined as ReturnType<typeof parseIssueDiagnosisResult> | undefined;\n let diagnosisError: string | undefined;\n if (toolResult.exitCode === 0) {\n try {\n diagnosis = parseIssueDiagnosisResult(`${toolResult.stdout}\\n${toolResult.stderr}`);\n } catch (error) {\n diagnosisError = errorMessage(error);\n }\n } else {\n diagnosisError = truncateLogExcerpt(toolResult.stderr || toolResult.stdout) || `${toolName} exited with code ${toolResult.exitCode}.`;\n }\n\n const finalStatus = diagnosis ? \"completed\" : \"failed\";\n const sessionTelemetry = pendingSessionTelemetry(sessionContext);\n\n if (diagnosis) {\n const resultMutation: IssueDiagnosisResultMutation = {\n status: \"completed\",\n runnerId,\n idempotencyKey: `issue_${workItem.workItemId}_${randomUUID()}`,\n diagnosis,\n tool: toolName,\n durationMs,\n ...sessionTelemetry,\n message: `${toolName} returned an issue root-cause analysis.`\n };\n const result = await submitPrimaryRunnerResult<Awaited<ReturnType<ApiClient[\"submitIssueDiagnosisResult\"]>>>(apiClient, {\n accountId: workItem.accountId,\n projectId,\n repositoryLinkId,\n runnerId,\n workItemId: workItem.workItemId,\n workKind: \"issueDiagnosis\",\n resultKind: \"issueDiagnosisResult\",\n attempt: workItem.attempt,\n idempotencyKey: resultMutation.idempotencyKey,\n result: resultMutation\n });\n if (!result) return { status: \"failed\", exitCode: 1 };\n await finalizeToolSessionBestEffort({ apiClient, projectId, runnerId, sessionContext, status: finalStatus, toolResult, workItemId: workItem.workItemId });\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: \"completed\",\n summary: `${toolName} returned an issue root-cause analysis.`,\n idempotencyKey: `runner_milestone_issue_completed_${workItem.workItemId}_${result.workItem.idempotencyKey}`,\n metadata: { tool: toolName, durationMs, riskLevel: diagnosis.riskLevel, likelyPathCount: diagnosis.likelyPaths.length, verificationSummary: diagnosis.verificationPlan.join(\" | \") }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig));\n console.log(\"Issue diagnosis returned for approval.\");\n return { status: \"completed\", exitCode: 0 };\n }\n\n const failedMutation: IssueDiagnosisResultMutation = {\n status: \"failed\",\n runnerId,\n idempotencyKey: `issue_${workItem.workItemId}_${randomUUID()}`,\n tool: toolName,\n durationMs,\n ...sessionTelemetry,\n message: `${toolName} did not produce a valid issue diagnosis.`,\n ...(diagnosisError ? { error: diagnosisError } : {})\n };\n const failedResult = await submitPrimaryRunnerResult<Awaited<ReturnType<ApiClient[\"submitIssueDiagnosisResult\"]>>>(apiClient, {\n accountId: workItem.accountId,\n projectId,\n repositoryLinkId,\n runnerId,\n workItemId: workItem.workItemId,\n workKind: \"issueDiagnosis\",\n resultKind: \"issueDiagnosisResult\",\n attempt: workItem.attempt,\n idempotencyKey: failedMutation.idempotencyKey,\n result: failedMutation\n });\n if (!failedResult) return { status: \"failed\", exitCode: 1 };\n await finalizeToolSessionBestEffort({ apiClient, projectId, runnerId, sessionContext, status: finalStatus, toolResult, workItemId: workItem.workItemId });\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: \"failed\",\n summary: diagnosisError ?? `${toolName} did not produce a valid issue diagnosis.`,\n idempotencyKey: `runner_milestone_issue_failed_${workItem.workItemId}_${failedResult.workItem.idempotencyKey}`,\n metadata: { tool: toolName, durationMs, verificationSummary: \"Issue diagnosis output did not include valid structured JSON.\" }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig));\n console.error(diagnosisError ?? \"Local runner issue diagnosis failed.\");\n return { status: \"failed\", exitCode: toolResult.exitCode || 1 };\n}\n\nasync function finalizeSecurityPostureScanWork({\n apiClient,\n durationMs,\n projectId,\n repositoryLinkId,\n runnerId,\n sessionContext,\n toolConfig,\n toolName,\n toolResult,\n workItem\n}: {\n apiClient: ApiClient;\n durationMs: number;\n projectId: string;\n repositoryLinkId: string;\n runnerId: string;\n sessionContext: PreparedToolSession;\n toolConfig: RunnerToolConfig;\n toolName: string;\n toolResult: LocalToolRunResult;\n workItem: WorkItem;\n}): Promise<{ status: \"completed\" | \"failed\"; exitCode: number }> {\n let scanResult = undefined as ReturnType<typeof parseSecurityPostureScanResult> | undefined;\n let scanError: string | undefined;\n if (toolResult.exitCode === 0) {\n try {\n scanResult = parseSecurityPostureScanResult(`${toolResult.stdout}\\n${toolResult.stderr}`);\n } catch (error) {\n scanError = errorMessage(error);\n }\n } else {\n scanError = truncateLogExcerpt(toolResult.stderr || toolResult.stdout) || `${toolName} exited with code ${toolResult.exitCode}.`;\n }\n\n const finalStatus = scanResult ? \"completed\" : \"failed\";\n const sessionTelemetry = pendingSessionTelemetry(sessionContext);\n\n if (scanResult) {\n const resultMutation: SecurityPostureScanResultMutation = {\n status: \"completed\",\n runnerId,\n idempotencyKey: `security_${workItem.workItemId}_${randomUUID()}`,\n result: scanResult,\n tool: toolName,\n durationMs,\n ...sessionTelemetry,\n message: `${toolName} returned a security posture scan.`\n };\n const result = await submitPrimaryRunnerResult<Awaited<ReturnType<ApiClient[\"submitSecurityPostureScanResult\"]>>>(apiClient, {\n accountId: workItem.accountId,\n projectId,\n repositoryLinkId,\n runnerId,\n workItemId: workItem.workItemId,\n workKind: \"securityPostureScan\",\n resultKind: \"securityPostureScanResult\",\n attempt: workItem.attempt,\n idempotencyKey: resultMutation.idempotencyKey,\n result: resultMutation\n });\n if (!result) return { status: \"failed\", exitCode: 1 };\n await finalizeToolSessionBestEffort({ apiClient, projectId, runnerId, sessionContext, status: finalStatus, toolResult, workItemId: workItem.workItemId });\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: \"completed\",\n summary: `${toolName} returned a security posture scan.`,\n idempotencyKey: `runner_milestone_security_completed_${workItem.workItemId}_${result.workItem.idempotencyKey}`,\n metadata: { tool: toolName, durationMs, findingCount: scanResult.findings.length, critical: result.scan.severityCounts.critical, high: result.scan.severityCounts.high, verificationSummary: scanResult.verificationPlan.join(\" | \") }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig));\n console.log(\"Security posture scan returned for review.\");\n return { status: \"completed\", exitCode: 0 };\n }\n\n const failedMutation: SecurityPostureScanResultMutation = {\n status: \"failed\",\n runnerId,\n idempotencyKey: `security_${workItem.workItemId}_${randomUUID()}`,\n tool: toolName,\n durationMs,\n ...sessionTelemetry,\n message: `${toolName} did not produce a valid security posture scan.`,\n ...(scanError ? { error: scanError } : {})\n };\n const failedResult = await submitPrimaryRunnerResult<Awaited<ReturnType<ApiClient[\"submitSecurityPostureScanResult\"]>>>(apiClient, {\n accountId: workItem.accountId,\n projectId,\n repositoryLinkId,\n runnerId,\n workItemId: workItem.workItemId,\n workKind: \"securityPostureScan\",\n resultKind: \"securityPostureScanResult\",\n attempt: workItem.attempt,\n idempotencyKey: failedMutation.idempotencyKey,\n result: failedMutation\n });\n if (!failedResult) return { status: \"failed\", exitCode: 1 };\n await finalizeToolSessionBestEffort({ apiClient, projectId, runnerId, sessionContext, status: finalStatus, toolResult, workItemId: workItem.workItemId });\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: \"failed\",\n summary: scanError ?? `${toolName} did not produce a valid security posture scan.`,\n idempotencyKey: `runner_milestone_security_failed_${workItem.workItemId}_${failedResult.workItem.idempotencyKey}`,\n metadata: { tool: toolName, durationMs, verificationSummary: \"Security posture output did not include valid structured JSON.\" }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig));\n console.error(scanError ?? \"Local runner security posture scan failed.\");\n return { status: \"failed\", exitCode: toolResult.exitCode || 1 };\n}\n\nasync function finalizeAppEvaluationScanWork({\n apiClient,\n durationMs,\n projectId,\n repositoryLinkId,\n runnerId,\n sessionContext,\n toolConfig,\n toolName,\n toolResult,\n workItem\n}: {\n apiClient: ApiClient;\n durationMs: number;\n projectId: string;\n repositoryLinkId: string;\n runnerId: string;\n sessionContext: PreparedToolSession;\n toolConfig: RunnerToolConfig;\n toolName: string;\n toolResult: LocalToolRunResult;\n workItem: WorkItem;\n}): Promise<{ status: \"completed\" | \"failed\"; exitCode: number }> {\n let scanResult = undefined as ReturnType<typeof parseAppEvaluationScanResult> | undefined;\n let scanError: string | undefined;\n if (toolResult.exitCode === 0) {\n try {\n scanResult = parseAppEvaluationScanResult(`${toolResult.stdout}\\n${toolResult.stderr}`);\n } catch (error) {\n scanError = errorMessage(error);\n }\n } else {\n scanError = truncateLogExcerpt(toolResult.stderr || toolResult.stdout) || `${toolName} exited with code ${toolResult.exitCode}.`;\n }\n\n const finalStatus = scanResult ? \"completed\" : \"failed\";\n const sessionTelemetry = pendingSessionTelemetry(sessionContext);\n\n if (scanResult) {\n const resultMutation: AppEvaluationScanResultMutation = {\n status: \"completed\",\n runnerId,\n idempotencyKey: `app_evaluation_${workItem.workItemId}_${randomUUID()}`,\n result: scanResult,\n tool: toolName,\n durationMs,\n ...sessionTelemetry,\n message: `${toolName} returned an app evaluation scan.`\n };\n const result = await submitPrimaryRunnerResult<Awaited<ReturnType<ApiClient[\"submitAppEvaluationScanResult\"]>>>(apiClient, {\n accountId: workItem.accountId,\n projectId,\n repositoryLinkId,\n runnerId,\n workItemId: workItem.workItemId,\n workKind: \"appEvaluationScan\",\n resultKind: \"appEvaluationScanResult\",\n attempt: workItem.attempt,\n idempotencyKey: resultMutation.idempotencyKey,\n result: resultMutation\n });\n if (!result) return { status: \"failed\", exitCode: 1 };\n await finalizeToolSessionBestEffort({ apiClient, projectId, runnerId, sessionContext, status: finalStatus, toolResult, workItemId: workItem.workItemId });\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: \"completed\",\n summary: `${toolName} returned an app evaluation scan.`,\n idempotencyKey: `runner_milestone_app_evaluation_completed_${workItem.workItemId}_${result.workItem.idempotencyKey}`,\n metadata: { tool: toolName, durationMs, findingCount: scanResult.findings.length, verificationSummary: scanResult.verificationPlan.join(\" | \") }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig));\n console.log(\"App evaluation scan returned for review.\");\n return { status: \"completed\", exitCode: 0 };\n }\n\n const failedMutation: AppEvaluationScanResultMutation = {\n status: \"failed\",\n runnerId,\n idempotencyKey: `app_evaluation_${workItem.workItemId}_${randomUUID()}`,\n tool: toolName,\n durationMs,\n ...sessionTelemetry,\n message: `${toolName} did not produce a valid app evaluation scan.`,\n ...(scanError ? { error: scanError } : {})\n };\n const failedResult = await submitPrimaryRunnerResult<Awaited<ReturnType<ApiClient[\"submitAppEvaluationScanResult\"]>>>(apiClient, {\n accountId: workItem.accountId,\n projectId,\n repositoryLinkId,\n runnerId,\n workItemId: workItem.workItemId,\n workKind: \"appEvaluationScan\",\n resultKind: \"appEvaluationScanResult\",\n attempt: workItem.attempt,\n idempotencyKey: failedMutation.idempotencyKey,\n result: failedMutation\n });\n if (!failedResult) return { status: \"failed\", exitCode: 1 };\n await finalizeToolSessionBestEffort({ apiClient, projectId, runnerId, sessionContext, status: finalStatus, toolResult, workItemId: workItem.workItemId });\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: \"failed\",\n summary: scanError ?? `${toolName} did not produce a valid app evaluation scan.`,\n idempotencyKey: `runner_milestone_app_evaluation_failed_${workItem.workItemId}_${failedResult.workItem.idempotencyKey}`,\n metadata: { tool: toolName, durationMs, verificationSummary: \"App evaluation output did not include valid structured JSON.\" }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig));\n console.error(scanError ?? \"Local runner app evaluation scan failed.\");\n return { status: \"failed\", exitCode: toolResult.exitCode || 1 };\n}\n\nasync function finalizeBrainConsolidationScanWork({\n apiClient,\n durationMs,\n projectId,\n repositoryLinkId,\n runnerId,\n sessionContext,\n toolConfig,\n toolName,\n toolResult,\n workItem\n}: {\n apiClient: ApiClient;\n durationMs: number;\n projectId: string;\n repositoryLinkId: string;\n runnerId: string;\n sessionContext: PreparedToolSession;\n toolConfig: RunnerToolConfig;\n toolName: string;\n toolResult: LocalToolRunResult;\n workItem: WorkItem;\n}): Promise<{ status: \"completed\" | \"failed\"; exitCode: number }> {\n let scanResult = undefined as ReturnType<typeof parseBrainConsolidationScanResult> | undefined;\n let scanError: string | undefined;\n if (toolResult.exitCode === 0) {\n try {\n scanResult = parseBrainConsolidationScanResult(`${toolResult.stdout}\\n${toolResult.stderr}`);\n } catch (error) {\n scanError = errorMessage(error);\n }\n } else {\n scanError = truncateLogExcerpt(toolResult.stderr || toolResult.stdout) || `${toolName} exited with code ${toolResult.exitCode}.`;\n }\n\n const finalStatus = scanResult ? \"completed\" : \"failed\";\n const sessionTelemetry = pendingSessionTelemetry(sessionContext);\n\n if (scanResult) {\n const resultMutation: BrainConsolidationScanResultMutation = {\n status: \"completed\",\n runnerId,\n idempotencyKey: `brain_consolidation_${workItem.workItemId}_${randomUUID()}`,\n result: scanResult,\n tool: toolName,\n durationMs,\n ...sessionTelemetry,\n message: `${toolName} returned a semantic brain consolidation scan.`\n };\n const result = await submitPrimaryRunnerResult<Awaited<ReturnType<ApiClient[\"submitBrainConsolidationScanResult\"]>>>(apiClient, {\n accountId: workItem.accountId,\n projectId,\n repositoryLinkId,\n runnerId,\n workItemId: workItem.workItemId,\n workKind: \"brainConsolidationScan\",\n resultKind: \"brainConsolidationScanResult\",\n attempt: workItem.attempt,\n idempotencyKey: resultMutation.idempotencyKey,\n result: resultMutation\n });\n if (!result) return { status: \"failed\", exitCode: 1 };\n await finalizeToolSessionBestEffort({ apiClient, projectId, runnerId, sessionContext, status: finalStatus, toolResult, workItemId: workItem.workItemId });\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: \"completed\",\n summary: `${toolName} returned a semantic brain consolidation scan.`,\n idempotencyKey: `runner_milestone_brain_consolidation_completed_${workItem.workItemId}_${result.workItem.idempotencyKey}`,\n metadata: { tool: toolName, durationMs, recommendationCount: scanResult.recommendations.length, autoArchivedCount: result.autoArchivedDocuments.length, proposalCount: result.proposals.length, verificationSummary: scanResult.summary }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig));\n console.log(`Brain consolidation scan returned: archived ${result.autoArchivedDocuments.length}, opened ${result.proposals.length} proposal${result.proposals.length === 1 ? \"\" : \"s\"}.`);\n return { status: \"completed\", exitCode: 0 };\n }\n\n const failedMutation: BrainConsolidationScanResultMutation = {\n status: \"failed\",\n runnerId,\n idempotencyKey: `brain_consolidation_${workItem.workItemId}_${randomUUID()}`,\n tool: toolName,\n durationMs,\n ...sessionTelemetry,\n message: `${toolName} did not produce a valid semantic brain consolidation scan.`,\n ...(scanError ? { error: scanError } : {})\n };\n const failedResult = await submitPrimaryRunnerResult<Awaited<ReturnType<ApiClient[\"submitBrainConsolidationScanResult\"]>>>(apiClient, {\n accountId: workItem.accountId,\n projectId,\n repositoryLinkId,\n runnerId,\n workItemId: workItem.workItemId,\n workKind: \"brainConsolidationScan\",\n resultKind: \"brainConsolidationScanResult\",\n attempt: workItem.attempt,\n idempotencyKey: failedMutation.idempotencyKey,\n result: failedMutation\n });\n if (!failedResult) return { status: \"failed\", exitCode: 1 };\n await finalizeToolSessionBestEffort({ apiClient, projectId, runnerId, sessionContext, status: finalStatus, toolResult, workItemId: workItem.workItemId });\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: \"failed\",\n summary: scanError ?? `${toolName} did not produce a valid semantic brain consolidation scan.`,\n idempotencyKey: `runner_milestone_brain_consolidation_failed_${workItem.workItemId}_${failedResult.workItem.idempotencyKey}`,\n metadata: { tool: toolName, durationMs, verificationSummary: \"Brain consolidation output did not include valid structured JSON.\" }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig));\n console.error(scanError ?? \"Local runner brain consolidation scan failed.\");\n return { status: \"failed\", exitCode: toolResult.exitCode || 1 };\n}\n\nasync function finalizeProjectContextRefreshWork({\n apiClient,\n durationMs,\n executionRoot,\n projectId,\n repositoryLinkId,\n runnerId,\n sessionContext,\n toolConfig,\n toolName,\n toolResult,\n workItem\n}: {\n apiClient: ApiClient;\n durationMs: number;\n executionRoot: string;\n projectId: string;\n repositoryLinkId: string;\n runnerId: string;\n sessionContext: PreparedToolSession;\n toolConfig: RunnerToolConfig;\n toolName: string;\n toolResult: LocalToolRunResult;\n workItem: WorkItem;\n}): Promise<{ status: \"completed\" | \"failed\"; exitCode: number }> {\n let refreshResult = undefined as ReturnType<typeof parseProjectContextRefreshResult> | undefined;\n let refreshError: string | undefined;\n if (toolResult.exitCode === 0) {\n try {\n refreshResult = parseProjectContextRefreshResult(`${toolResult.stdout}\\n${toolResult.stderr}`, { repositoryRoot: executionRoot });\n } catch (error) {\n refreshError = errorMessage(error);\n }\n } else {\n refreshError = truncateLogExcerpt(toolResult.stderr || toolResult.stdout) || `${toolName} exited with code ${toolResult.exitCode}.`;\n }\n\n const finalStatus = refreshResult ? \"completed\" : \"failed\";\n const sessionTelemetry = pendingSessionTelemetry(sessionContext);\n\n if (refreshResult) {\n const resultMutation: ProjectContextRefreshResultMutation = {\n status: \"completed\",\n runnerId,\n idempotencyKey: `project_context_${workItem.workItemId}_${randomUUID()}`,\n result: refreshResult,\n tool: toolName,\n durationMs,\n ...sessionTelemetry,\n message: `${toolName} returned a project context refresh.`\n };\n const result = await submitPrimaryRunnerResult<Awaited<ReturnType<ApiClient[\"submitProjectContextRefreshResult\"]>>>(apiClient, {\n accountId: workItem.accountId,\n projectId,\n repositoryLinkId,\n runnerId,\n workItemId: workItem.workItemId,\n workKind: \"projectContextRefresh\",\n resultKind: \"projectContextRefreshResult\",\n attempt: workItem.attempt,\n idempotencyKey: resultMutation.idempotencyKey,\n result: resultMutation\n });\n if (!result) return { status: \"failed\", exitCode: 1 };\n await finalizeToolSessionBestEffort({ apiClient, projectId, runnerId, sessionContext, status: finalStatus, toolResult, workItemId: workItem.workItemId });\n const failureSummary = projectContextRefreshSubmissionFailureSummary(result);\n if (failureSummary) {\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: \"failed\",\n summary: failureSummary,\n idempotencyKey: `runner_milestone_project_context_failed_${workItem.workItemId}_${result.workItem.idempotencyKey}`,\n metadata: { tool: toolName, durationMs, sliceCount: refreshResult.slices.length, entityCount: refreshResult.entities.length, verificationSummary: \"Server rejected the project context refresh result.\" }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig));\n console.error(failureSummary);\n return { status: \"failed\", exitCode: 1 };\n }\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: \"completed\",\n summary: `${toolName} returned a project context refresh.`,\n idempotencyKey: `runner_milestone_project_context_completed_${workItem.workItemId}_${result.workItem.idempotencyKey}`,\n metadata: { tool: toolName, durationMs, sliceCount: refreshResult.slices.length, entityCount: refreshResult.entities.length, mapId: result.map?.projectContextMapId ?? \"\", verificationSummary: refreshResult.verificationPlan.join(\" | \") }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig));\n console.log(\"Project context refresh returned for review.\");\n return { status: \"completed\", exitCode: 0 };\n }\n\n const failedMutation: ProjectContextRefreshResultMutation = {\n status: \"failed\",\n runnerId,\n idempotencyKey: `project_context_${workItem.workItemId}_${randomUUID()}`,\n tool: toolName,\n durationMs,\n ...sessionTelemetry,\n message: `${toolName} did not produce a valid project context refresh.`,\n ...(refreshError ? { error: refreshError } : {})\n };\n const failedResult = await submitPrimaryRunnerResult<Awaited<ReturnType<ApiClient[\"submitProjectContextRefreshResult\"]>>>(apiClient, {\n accountId: workItem.accountId,\n projectId,\n repositoryLinkId,\n runnerId,\n workItemId: workItem.workItemId,\n workKind: \"projectContextRefresh\",\n resultKind: \"projectContextRefreshResult\",\n attempt: workItem.attempt,\n idempotencyKey: failedMutation.idempotencyKey,\n result: failedMutation\n });\n if (!failedResult) return { status: \"failed\", exitCode: 1 };\n await finalizeToolSessionBestEffort({ apiClient, projectId, runnerId, sessionContext, status: finalStatus, toolResult, workItemId: workItem.workItemId });\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: \"failed\",\n summary: refreshError ?? `${toolName} did not produce a valid project context refresh.`,\n idempotencyKey: `runner_milestone_project_context_failed_${workItem.workItemId}_${failedResult.workItem.idempotencyKey}`,\n metadata: { tool: toolName, durationMs, verificationSummary: \"Project context output did not include valid structured JSON.\" }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig));\n console.error(refreshError ?? \"Local runner project context refresh failed.\");\n return { status: \"failed\", exitCode: toolResult.exitCode || 1 };\n}\n\nasync function finalizeImplementationVerificationWork({\n apiClient,\n durationMs,\n projectId,\n repositoryLinkId,\n runnerId,\n sessionContext,\n toolConfig,\n toolName,\n toolResult,\n workItem\n}: {\n apiClient: ApiClient;\n durationMs: number;\n projectId: string;\n repositoryLinkId: string;\n runnerId: string;\n sessionContext: PreparedToolSession;\n toolConfig: RunnerToolConfig;\n toolName: string;\n toolResult: LocalToolRunResult;\n workItem: WorkItem;\n}): Promise<{ status: \"completed\" | \"failed\"; exitCode: number }> {\n let verificationResult = undefined as ReturnType<typeof parseImplementationVerificationResult> | undefined;\n let verificationError: string | undefined;\n if (toolResult.exitCode === 0) {\n try {\n verificationResult = parseImplementationVerificationResult(`${toolResult.stdout}\\n${toolResult.stderr}`);\n } catch (error) {\n verificationError = errorMessage(error);\n }\n } else {\n verificationError = truncateLogExcerpt(toolResult.stderr || toolResult.stdout) || `${toolName} exited with code ${toolResult.exitCode}.`;\n }\n\n const finalStatus = verificationResult ? \"completed\" : \"failed\";\n const sessionTelemetry = pendingSessionTelemetry(sessionContext);\n\n if (verificationResult) {\n const resultMutation: ImplementationVerificationResultMutation = {\n status: \"completed\",\n runnerId,\n idempotencyKey: `implementation_verification_${workItem.workItemId}_${randomUUID()}`,\n result: verificationResult,\n tool: toolName,\n durationMs,\n ...sessionTelemetry,\n message: `${toolName} returned implementation verification proof.`\n };\n const result = await submitPrimaryRunnerResult<Awaited<ReturnType<ApiClient[\"submitImplementationVerificationResult\"]>>>(apiClient, {\n accountId: workItem.accountId,\n projectId,\n repositoryLinkId,\n runnerId,\n workItemId: workItem.workItemId,\n workKind: \"implementationVerification\",\n resultKind: \"implementationVerificationResult\",\n attempt: workItem.attempt,\n idempotencyKey: resultMutation.idempotencyKey,\n result: resultMutation\n });\n if (!result) return { status: \"failed\", exitCode: 1 };\n await finalizeToolSessionBestEffort({ apiClient, projectId, runnerId, sessionContext, status: finalStatus, toolResult, workItemId: workItem.workItemId });\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: verificationResult.outcome === \"verifiedImplemented\" ? \"completed\" : verificationResult.outcome === \"verificationBlocked\" ? \"blocked\" : \"warning\",\n summary: verificationResult.summary,\n idempotencyKey: `runner_milestone_implementation_verification_completed_${workItem.workItemId}_${result.workItem.idempotencyKey}`,\n metadata: { tool: toolName, durationMs, outcome: verificationResult.outcome, recommendation: verificationResult.recommendation, gapCount: verificationResult.gaps.length, verificationSummary: verificationResult.verificationPlan.join(\" | \") }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig));\n console.log(\"Implementation verification returned for review.\");\n return { status: \"completed\", exitCode: 0 };\n }\n\n const failedMutation: ImplementationVerificationResultMutation = {\n status: \"failed\",\n runnerId,\n idempotencyKey: `implementation_verification_${workItem.workItemId}_${randomUUID()}`,\n tool: toolName,\n durationMs,\n ...sessionTelemetry,\n message: `${toolName} did not produce valid implementation verification proof.`,\n ...(verificationError ? { error: verificationError } : {})\n };\n const failedResult = await submitPrimaryRunnerResult<Awaited<ReturnType<ApiClient[\"submitImplementationVerificationResult\"]>>>(apiClient, {\n accountId: workItem.accountId,\n projectId,\n repositoryLinkId,\n runnerId,\n workItemId: workItem.workItemId,\n workKind: \"implementationVerification\",\n resultKind: \"implementationVerificationResult\",\n attempt: workItem.attempt,\n idempotencyKey: failedMutation.idempotencyKey,\n result: failedMutation\n });\n if (!failedResult) return { status: \"failed\", exitCode: 1 };\n await finalizeToolSessionBestEffort({ apiClient, projectId, runnerId, sessionContext, status: finalStatus, toolResult, workItemId: workItem.workItemId });\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: \"failed\",\n summary: verificationError ?? `${toolName} did not produce valid implementation verification proof.`,\n idempotencyKey: `runner_milestone_implementation_verification_failed_${workItem.workItemId}_${failedResult.workItem.idempotencyKey}`,\n metadata: { tool: toolName, durationMs, verificationSummary: \"Implementation verification output did not include valid structured JSON.\" }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig));\n console.error(verificationError ?? \"Local runner implementation verification failed.\");\n return { status: \"failed\", exitCode: toolResult.exitCode || 1 };\n}\n\nasync function finalizeTestQualityScanWork({\n apiClient,\n durationMs,\n projectId,\n repositoryLinkId,\n runnerId,\n sessionContext,\n toolConfig,\n toolName,\n toolResult,\n workItem\n}: {\n apiClient: ApiClient;\n durationMs: number;\n projectId: string;\n repositoryLinkId: string;\n runnerId: string;\n sessionContext: PreparedToolSession;\n toolConfig: RunnerToolConfig;\n toolName: string;\n toolResult: LocalToolRunResult;\n workItem: WorkItem;\n}): Promise<{ status: \"completed\" | \"failed\"; exitCode: number }> {\n let scanResult = undefined as ReturnType<typeof parseTestQualityScanResult> | undefined;\n let scanError: string | undefined;\n if (toolResult.exitCode === 0) {\n try {\n scanResult = parseTestQualityScanResult(`${toolResult.stdout}\\n${toolResult.stderr}`);\n } catch (error) {\n scanError = errorMessage(error);\n }\n } else {\n scanError = truncateLogExcerpt(toolResult.stderr || toolResult.stdout) || `${toolName} exited with code ${toolResult.exitCode}.`;\n }\n\n const finalStatus = scanResult ? \"completed\" : \"failed\";\n const sessionTelemetry = pendingSessionTelemetry(sessionContext);\n\n if (scanResult) {\n const resultMutation: TestQualityScanResultMutation = {\n status: \"completed\",\n runnerId,\n idempotencyKey: `test_quality_${workItem.workItemId}_${randomUUID()}`,\n result: scanResult,\n tool: toolName,\n durationMs,\n ...sessionTelemetry,\n message: `${toolName} returned a test quality scan.`\n };\n const result = await submitPrimaryRunnerResult<Awaited<ReturnType<ApiClient[\"submitTestQualityScanResult\"]>>>(apiClient, {\n accountId: workItem.accountId,\n projectId,\n repositoryLinkId,\n runnerId,\n workItemId: workItem.workItemId,\n workKind: \"testQualityScan\",\n resultKind: \"testQualityScanResult\",\n attempt: workItem.attempt,\n idempotencyKey: resultMutation.idempotencyKey,\n result: resultMutation\n });\n if (!result) return { status: \"failed\", exitCode: 1 };\n await finalizeToolSessionBestEffort({ apiClient, projectId, runnerId, sessionContext, status: finalStatus, toolResult, workItemId: workItem.workItemId });\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: scanResult.findings.some((finding) => finding.severity === \"critical\" || finding.severity === \"high\") ? \"warning\" : \"completed\",\n summary: scanResult.summary,\n idempotencyKey: `runner_milestone_test_quality_completed_${workItem.workItemId}_${result.workItem.idempotencyKey}`,\n metadata: { tool: toolName, durationMs, findingCount: scanResult.findings.length, commandCount: scanResult.commandSummaries.length, verificationSummary: scanResult.verificationPlan.join(\" | \") }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig));\n console.log(\"Test quality scan returned for review.\");\n return { status: \"completed\", exitCode: 0 };\n }\n\n const failedMutation: TestQualityScanResultMutation = {\n status: \"failed\",\n runnerId,\n idempotencyKey: `test_quality_${workItem.workItemId}_${randomUUID()}`,\n tool: toolName,\n durationMs,\n ...sessionTelemetry,\n message: `${toolName} did not produce a valid test quality scan.`,\n ...(scanError ? { error: scanError } : {})\n };\n const failedResult = await submitPrimaryRunnerResult<Awaited<ReturnType<ApiClient[\"submitTestQualityScanResult\"]>>>(apiClient, {\n accountId: workItem.accountId,\n projectId,\n repositoryLinkId,\n runnerId,\n workItemId: workItem.workItemId,\n workKind: \"testQualityScan\",\n resultKind: \"testQualityScanResult\",\n attempt: workItem.attempt,\n idempotencyKey: failedMutation.idempotencyKey,\n result: failedMutation\n });\n if (!failedResult) return { status: \"failed\", exitCode: 1 };\n await finalizeToolSessionBestEffort({ apiClient, projectId, runnerId, sessionContext, status: finalStatus, toolResult, workItemId: workItem.workItemId });\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: \"failed\",\n summary: scanError ?? `${toolName} did not produce a valid test quality scan.`,\n idempotencyKey: `runner_milestone_test_quality_failed_${workItem.workItemId}_${failedResult.workItem.idempotencyKey}`,\n metadata: { tool: toolName, durationMs, verificationSummary: \"Test quality output did not include valid structured JSON.\" }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig));\n console.error(scanError ?? \"Local runner test quality scan failed.\");\n return { status: \"failed\", exitCode: toolResult.exitCode || 1 };\n}\n\nasync function finalizeImplementationTestGateWork({\n apiClient,\n durationMs,\n projectId,\n repositoryLinkId,\n runnerId,\n sessionContext,\n toolConfig,\n toolName,\n toolResult,\n workItem\n}: {\n apiClient: ApiClient;\n durationMs: number;\n projectId: string;\n repositoryLinkId: string;\n runnerId: string;\n sessionContext: PreparedToolSession;\n toolConfig: RunnerToolConfig;\n toolName: string;\n toolResult: LocalToolRunResult;\n workItem: WorkItem;\n}): Promise<{ status: \"completed\" | \"failed\"; exitCode: number }> {\n let gateResult = undefined as ReturnType<typeof parseImplementationTestGateResult> | undefined;\n let gateError: string | undefined;\n if (toolResult.exitCode === 0) {\n try {\n gateResult = parseImplementationTestGateResult(`${toolResult.stdout}\\n${toolResult.stderr}`);\n } catch (error) {\n gateError = errorMessage(error);\n }\n } else {\n gateError = truncateLogExcerpt(toolResult.stderr || toolResult.stdout) || `${toolName} exited with code ${toolResult.exitCode}.`;\n }\n\n const finalStatus = gateResult ? \"completed\" : \"failed\";\n const sessionTelemetry = pendingSessionTelemetry(sessionContext);\n\n if (gateResult) {\n const resultMutation: ImplementationTestGateResultMutation = {\n status: \"completed\",\n runnerId,\n idempotencyKey: `implementation_test_gate_${workItem.workItemId}_${randomUUID()}`,\n result: gateResult,\n tool: toolName,\n durationMs,\n ...sessionTelemetry,\n message: `${toolName} returned an implementation test gate result.`\n };\n const result = await submitPrimaryRunnerResult<Awaited<ReturnType<ApiClient[\"submitImplementationTestGateResult\"]>>>(apiClient, {\n accountId: workItem.accountId,\n projectId,\n repositoryLinkId,\n runnerId,\n workItemId: workItem.workItemId,\n workKind: \"implementationTestGate\",\n resultKind: \"implementationTestGateResult\",\n attempt: workItem.attempt,\n idempotencyKey: resultMutation.idempotencyKey,\n result: resultMutation\n });\n if (!result) return { status: \"failed\", exitCode: 1 };\n await finalizeToolSessionBestEffort({ apiClient, projectId, runnerId, sessionContext, status: finalStatus, toolResult, workItemId: workItem.workItemId });\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: gateResult.outcome === \"passed\" ? \"completed\" : gateResult.outcome === \"blocked\" ? \"blocked\" : \"failed\",\n summary: gateResult.summary,\n idempotencyKey: `runner_milestone_implementation_test_gate_completed_${workItem.workItemId}_${result.workItem.idempotencyKey}`,\n metadata: { tool: toolName, durationMs, outcome: gateResult.outcome, findingCount: gateResult.findings.length, commandCount: gateResult.commandSummaries.length, verificationSummary: gateResult.verificationPlan.join(\" | \") }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig));\n console.log(\"Implementation test gate returned for review.\");\n return { status: gateResult.outcome === \"passed\" ? \"completed\" : \"failed\", exitCode: gateResult.outcome === \"passed\" ? 0 : 1 };\n }\n\n const failedMutation: ImplementationTestGateResultMutation = {\n status: \"failed\",\n runnerId,\n idempotencyKey: `implementation_test_gate_${workItem.workItemId}_${randomUUID()}`,\n tool: toolName,\n durationMs,\n ...sessionTelemetry,\n message: `${toolName} did not produce a valid implementation test gate result.`,\n ...(gateError ? { error: gateError } : {})\n };\n const failedResult = await submitPrimaryRunnerResult<Awaited<ReturnType<ApiClient[\"submitImplementationTestGateResult\"]>>>(apiClient, {\n accountId: workItem.accountId,\n projectId,\n repositoryLinkId,\n runnerId,\n workItemId: workItem.workItemId,\n workKind: \"implementationTestGate\",\n resultKind: \"implementationTestGateResult\",\n attempt: workItem.attempt,\n idempotencyKey: failedMutation.idempotencyKey,\n result: failedMutation\n });\n if (!failedResult) return { status: \"failed\", exitCode: 1 };\n await finalizeToolSessionBestEffort({ apiClient, projectId, runnerId, sessionContext, status: finalStatus, toolResult, workItemId: workItem.workItemId });\n await recordRunnerMilestone(apiClient, projectId, workItem, runnerId, repositoryLinkId, {\n status: \"failed\",\n summary: gateError ?? `${toolName} did not produce a valid implementation test gate result.`,\n idempotencyKey: `runner_milestone_implementation_test_gate_failed_${workItem.workItemId}_${failedResult.workItem.idempotencyKey}`,\n metadata: { tool: toolName, durationMs, verificationSummary: \"Implementation test gate output did not include valid structured JSON.\" }\n });\n await apiClient.sendRunnerHeartbeat(projectId, runnerId, repositoryLinkId, \"online\", runnerHeartbeatMetadata(toolConfig));\n console.error(gateError ?? \"Local runner implementation test gate failed.\");\n return { status: \"failed\", exitCode: toolResult.exitCode || 1 };\n}\n\nasync function createRunnerWorkPrompt(apiClient: ApiClient, projectId: string, workItem: WorkItem): Promise<string> {\n if (workItem.workKind === \"assistantQuestion\") {\n const emptyProjectContext: ProjectContextResponse = { maps: [], refreshes: [], misses: [] };\n const [{ documents }, { messages }, context] = await Promise.all([\n apiClient.listBrainDocuments(projectId),\n apiClient.listAssistantMessages(projectId),\n apiClient.listProjectContext(projectId).catch(() => emptyProjectContext)\n ]);\n const question = messages.find((message) => message.messageId === workItem.assistantMessageId || message.id === workItem.assistantMessageId)\n ?? messages.filter((message) => message.workItemId === workItem.workItemId).sort((first, second) => Date.parse(first.createdAt) - Date.parse(second.createdAt))[0];\n const contextPack = await apiClient.buildProjectContextPack(projectId, question?.content ?? workItem.sourceWish ?? workItem.title, workItem.workItemId).catch(() => undefined);\n return createWorkExecutionPrompt(workItem, {\n ...(question ? { assistantQuestion: { question, messages, documents, ...(context.activeMap ? { activeMap: context.activeMap } : {}), ...(contextPack ? { contextPack } : {}) } } : {})\n });\n }\n\n if (workItem.workKind === \"impactPreview\") {\n const emptyProjectContext: ProjectContextResponse = { maps: [], refreshes: [], misses: [] };\n const [{ documents }, context] = await Promise.all([\n apiClient.listBrainDocuments(projectId),\n apiClient.listProjectContext(projectId).catch(() => emptyProjectContext)\n ]);\n const implementationPrompt = workItem.impactDocumentId\n ? documents.find((document) => document.documentId === workItem.impactDocumentId || document.id === workItem.impactDocumentId)\n : documents.find((document) => document.frontmatter.generatedDraftId === workItem.generatedDraftId && (document.frontmatter.createsWorkItem === true || document.documentType === \"prompt\"));\n const contextPack = await apiClient.buildProjectContextPack(projectId, implementationPrompt?.content ?? workItem.sourceWish ?? workItem.title, workItem.workItemId).catch(() => undefined);\n return createWorkExecutionPrompt(workItem, {\n impactPreview: {\n documents,\n ...(context.activeMap ? { activeMap: context.activeMap } : {}),\n ...(contextPack ? { contextPack } : {}),\n ...(implementationPrompt ? { implementationPrompt } : {})\n }\n });\n }\n\n if (workItem.workKind === \"issueDiagnosis\") {\n const [{ documents }, { issues }] = await Promise.all([\n apiClient.listBrainDocuments(projectId),\n apiClient.listIssues(projectId)\n ]);\n const issue = issues.find((item) => item.issueId === workItem.issueId || item.id === workItem.issueId);\n return createWorkExecutionPrompt(workItem, {\n issueDiagnosis: {\n documents,\n ...(issue ? { issue } : {})\n }\n });\n }\n\n if (workItem.workKind === \"securityPostureScan\") {\n const { documents } = await apiClient.listBrainDocuments(projectId);\n return createWorkExecutionPrompt(workItem, {\n securityPostureScan: { documents }\n });\n }\n\n if (workItem.workKind === \"appEvaluationScan\") {\n const { documents } = await apiClient.listBrainDocuments(projectId);\n return createWorkExecutionPrompt(workItem, {\n appEvaluationScan: { documents }\n });\n }\n\n if (workItem.workKind === \"brainConsolidationScan\") {\n const { documents } = await apiClient.listBrainDocuments(projectId);\n return createWorkExecutionPrompt(workItem, {\n brainConsolidationScan: { documents }\n });\n }\n\n if (workItem.workKind === \"testQualityScan\") {\n const { documents } = await apiClient.listBrainDocuments(projectId);\n return createWorkExecutionPrompt(workItem, {\n testQualityScan: { documents }\n });\n }\n\n if (workItem.workKind === \"implementationTestGate\") {\n return createWorkExecutionPrompt(workItem);\n }\n\n if (workItem.workKind === \"projectContextRefresh\") {\n const emptyProjectContext: ProjectContextResponse = { maps: [], refreshes: [], misses: [] };\n const [{ documents }, context] = await Promise.all([\n apiClient.listBrainDocuments(projectId),\n apiClient.listProjectContext(projectId).catch(() => emptyProjectContext)\n ]);\n return createWorkExecutionPrompt(workItem, {\n projectContextRefresh: {\n documents,\n ...(context.activeMap ? { activeMap: context.activeMap } : {})\n }\n });\n }\n\n if (workItem.workKind !== \"planRevision\" || !workItem.reviewDocumentId) {\n return createWorkExecutionPrompt(workItem);\n }\n\n const [{ documents }, { messages }] = await Promise.all([\n apiClient.listBrainDocuments(projectId),\n apiClient.listPlanReviewMessages(projectId, workItem.reviewDocumentId)\n ]);\n const planDocument = documents.find((document) => document.documentId === workItem.reviewDocumentId || document.id === workItem.reviewDocumentId);\n return createWorkExecutionPrompt(workItem, {\n ...(planDocument ? { planRevision: { planDocument, messages } } : {})\n });\n}\n\ninterface PairedApiContext {\n client: ApiClient;\n metadata: RepoLinkMetadata;\n token?: string;\n}\n\nasync function loadPairedApiContext(root: string, apiUrl: string): Promise<PairedApiContext | undefined> {\n const metadata = await readProjectLink(root);\n if (!metadata) {\n return undefined;\n }\n\n const token = await new LocalCredentialStore().get(\n credentialKey(metadata.amistioAccountId, metadata.amistioProjectId, metadata.repositoryLinkId)\n );\n return {\n metadata,\n ...(token ? { token } : {}),\n client: new ApiClient({\n apiUrl,\n accountId: metadata.amistioAccountId,\n ...(token ? { token } : {})\n })\n };\n}\n\nasync function loadProjectNextAction(apiClient: ApiClient, projectId: string, repositoryLinkId: string, root: string): Promise<ProjectNextAction> {\n const [{ workItems }, { documents }, { runners }] = await Promise.all([\n apiClient.listWorkItems(projectId),\n apiClient.listBrainDocuments(projectId),\n apiClient.listRunners(projectId).catch(() => ({ runners: [] }))\n ]);\n\n return computeProjectNextAction({\n projectId,\n repositoryLinks: [createCliRepositoryLink({ amistioAccountId: \"local_runner\", amistioProjectId: projectId, repositoryLinkId, defaultBranch: \"main\", lastSyncedRevision: 0 }, root)],\n documents,\n workItems,\n runnerHeartbeats: runners\n });\n}\n\nfunction createCliRepositoryLink(metadata: RepoLinkMetadata, root: string): RepositoryLinkItem {\n const now = new Date().toISOString();\n return {\n id: metadata.repositoryLinkId,\n type: \"repositoryLink\",\n schemaVersion: 1,\n accountId: metadata.amistioAccountId,\n projectId: metadata.amistioProjectId,\n repositoryLinkId: metadata.repositoryLinkId,\n repoName: inferRepoName(root),\n repoFingerprint: createRepoFingerprint(metadata.amistioAccountId, metadata.amistioProjectId, metadata.repositoryLinkId),\n defaultBranch: metadata.defaultBranch,\n status: \"active\",\n createdAt: now,\n updatedAt: now\n };\n}\n\nfunction selectPromptWorkItem(workItems: WorkItem[], workItemId: string | undefined): WorkItem | undefined {\n if (workItemId) {\n return workItems.find((item) => item.workItemId === workItemId || item.id === workItemId);\n }\n\n return workItems.find((item) => isPromptReadyStatus(item.status));\n}\n\nfunction isPromptReadyStatus(status: WorkStatus): boolean {\n return status === \"approved\" || status === \"running\" || status === \"blocked\" || status === \"changesRequested\";\n}\n\ninterface PreparedToolSession {\n policy: SessionPolicy;\n decision: SessionDecision;\n reason: string;\n toolSession?: ToolSessionItem;\n}\n\nasync function prepareToolSession({\n apiClient,\n isolationTelemetry,\n machineId,\n projectId,\n repositoryLinkId,\n runnerId,\n sessionPolicy,\n supportsSessionReuse,\n resumabilityScope,\n toolName,\n model,\n workItem\n}: {\n apiClient: ApiClient;\n isolationTelemetry: WorkStatusTelemetryLike;\n machineId: string;\n projectId: string;\n repositoryLinkId: string;\n runnerId: string;\n sessionPolicy: SessionPolicy;\n supportsSessionReuse: boolean;\n resumabilityScope: SessionResumabilityScope;\n toolName: string;\n model?: string;\n workItem: WorkItem;\n}): Promise<PreparedToolSession> {\n const { toolSessions } = await apiClient.listToolSessions(projectId);\n const now = new Date();\n await closeStaleToolSessionsBestEffort(apiClient, projectId, toolSessions, now);\n const selection = selectToolSession({\n policy: sessionPolicy,\n workItem,\n sessions: toolSessions,\n toolName,\n runnerId,\n repositoryLinkId,\n machineId,\n supportsSessionReuse,\n now\n });\n\n if (selection.decision === \"skipped\") {\n return selection;\n }\n\n if (selection.toolSession) {\n const { toolSession } = await apiClient.updateToolSession(projectId, selection.toolSession.toolSessionId, {\n status: \"active\",\n runnerId,\n machineId,\n lastWorkItemId: workItem.workItemId,\n reusePolicy: sessionPolicy,\n ...(isolationTelemetry.implementationScopeId ? { implementationScopeId: isolationTelemetry.implementationScopeId } : {}),\n ...(isolationTelemetry.executionWorktreeKey ? { executionWorktreeKey: isolationTelemetry.executionWorktreeKey } : {}),\n ...(isolationTelemetry.isolationMode ? { isolationMode: isolationTelemetry.isolationMode } : {})\n });\n return { ...selection, toolSession };\n }\n\n const toolSessionId = `tool_session_${randomUUID()}`;\n const { toolSession } = await apiClient.createToolSession(projectId, {\n toolSessionId,\n repositoryLinkId,\n tool: toolName,\n provider: toolName,\n ...(model ? { model } : {}),\n resumabilityScope: supportsSessionReuse ? resumabilityScope : \"none\",\n title: workItem.title,\n summary: selection.reason,\n status: \"active\",\n runnerId,\n machineId,\n lastWorkItemId: workItem.workItemId,\n messageCount: 0,\n reusePolicy: sessionPolicy,\n ...(workItem.requestedByUserId ?? workItem.requestedBy ? { createdByUserId: workItem.requestedByUserId ?? workItem.requestedBy } : {}),\n ...(isolationTelemetry.implementationScopeId ? { implementationScopeId: isolationTelemetry.implementationScopeId } : {}),\n ...(isolationTelemetry.executionWorktreeKey ? { executionWorktreeKey: isolationTelemetry.executionWorktreeKey } : {}),\n ...(isolationTelemetry.isolationMode ? { isolationMode: isolationTelemetry.isolationMode } : {}),\n ...(workItem.sessionGroupKey ? { sessionGroupKey: workItem.sessionGroupKey } : {})\n });\n\n return { ...selection, toolSession };\n}\n\nasync function closeStaleToolSessionsBestEffort(apiClient: ApiClient, projectId: string, toolSessions: ToolSessionItem[], now: Date): Promise<void> {\n const staleSessions = toolSessions\n .map((session) => ({ session, reason: staleToolSessionClosedReason(session, now) }))\n .filter((item): item is { session: ToolSessionItem; reason: string } => Boolean(item.reason));\n if (!staleSessions.length) {\n return;\n }\n\n const settlements = await Promise.allSettled(staleSessions.map(({ session, reason }) => apiClient.updateToolSession(projectId, session.toolSessionId, {\n status: \"closed\",\n closedReason: reason,\n summary: session.summary ?? reason\n })));\n logRejectedSettlements(\"close stale tool sessions\", settlements);\n}\n\nasync function finalizeToolSession({\n apiClient,\n costUsd,\n messageCount,\n projectId,\n runnerId,\n session,\n status,\n stdout,\n tokensIn,\n tokensOut,\n workItemId\n}: {\n apiClient: ApiClient;\n costUsd?: number;\n messageCount?: number;\n projectId: string;\n runnerId: string;\n session?: ToolSessionItem;\n status: \"completed\" | \"failed\";\n stdout: string;\n tokensIn?: number;\n tokensOut?: number;\n workItemId: string;\n}): Promise<ToolSessionItem | undefined> {\n if (!session) {\n return undefined;\n }\n\n const summary = summarizeToolOutput(stdout) ?? session.summary;\n const nextStatus = status === \"completed\" ? completedToolSessionStatus(session) : \"blocked\";\n const closedReason = status === \"completed\" ? completedToolSessionClosedReason(session) : \"Last run failed or returned a non-zero exit code.\";\n const { toolSession } = await apiClient.updateToolSession(projectId, session.toolSessionId, {\n status: nextStatus,\n runnerId,\n lastWorkItemId: workItemId,\n messageCount: (session.messageCount ?? 0) + (messageCount ?? 1),\n ...(summary ? { summary } : {}),\n ...(tokensIn !== undefined ? { estimatedInputTokens: (session.estimatedInputTokens ?? 0) + tokensIn } : {}),\n ...(tokensOut !== undefined ? { estimatedOutputTokens: (session.estimatedOutputTokens ?? 0) + tokensOut } : {}),\n ...(costUsd !== undefined ? { costUsd: (session.costUsd ?? 0) + costUsd } : {}),\n ...(closedReason ? { closedReason } : {})\n });\n return toolSession;\n}\n\nasync function markToolSessionBlocked(apiClient: ApiClient, projectId: string, session: ToolSessionItem | undefined, reason: string) {\n if (!session) {\n return;\n }\n\n await apiClient.updateToolSession(projectId, session.toolSessionId, {\n status: \"blocked\",\n summary: reason,\n closedReason: reason\n });\n}\n\nfunction localSessionDecision(policy: SessionPolicy): SessionDecision {\n if (policy === \"new\") {\n return \"forcedNew\";\n }\n if (typeof policy === \"string\" && policy.startsWith(\"continue:\")) {\n return \"forcedContinue\";\n }\n return \"created\";\n}\n\nfunction summarizeToolOutput(value: string): string | undefined {\n const trimmed = value.trim();\n if (!trimmed) {\n return undefined;\n }\n return trimmed.length > 300 ? `${trimmed.slice(0, 300)}...` : trimmed;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction errorDetail(error: unknown): string {\n return error instanceof Error ? error.stack ?? error.message : String(error);\n}\n\nfunction truncateLogExcerpt(value: string) {\n const trimmed = value.trim();\n return trimmed.length > 1200 ? `${trimmed.slice(0, 1200)}...` : trimmed;\n}\n\nfunction collectRepeatedOption(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n\nfunction formatImportSkipSummary(counts: Record<\"notMarkdown\" | \"excluded\" | \"tooLarge\" | \"alreadyManaged\" | \"unreadable\", number>): string {\n return `Skipped: ${counts.excluded} excluded, ${counts.tooLarge} too large, ${counts.alreadyManaged} already managed, ${counts.unreadable} unreadable, ${counts.notMarkdown} non-Markdown.`;\n}\n\nfunction parsePositiveInteger(value: string) {\n const parsed = Number(value);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n throw new Error(`Expected a positive integer, received ${value}.`);\n }\n\n return parsed;\n}\n\nfunction parseInvocationChannel(value: string): RunnerInvocationChannel {\n if (value === \"auto\" || value === \"sdk\" || value === \"command\") {\n return value;\n }\n throw new Error(`Expected invocation channel auto, sdk, or command; received ${value}.`);\n}\n\nfunction parseReasoningEffort(value: string): RunnerReasoningEffort {\n if (value === \"auto\" || value === \"low\" || value === \"medium\" || value === \"high\" || value === \"xhigh\") {\n return value;\n }\n throw new Error(`Expected reasoning effort auto, low, medium, high, or xhigh; received ${value}.`);\n}\n\nfunction inferRepoName(root: string): string {\n return path.basename(path.resolve(root)) || \"repository\";\n}\n\nfunction createRepoFingerprint(accountId: string, projectId: string, repositoryLinkId: string): string {\n return createHash(\"sha256\").update(`${accountId}:${projectId}:${repositoryLinkId}`).digest(\"hex\");\n}\n\nfunction defaultApiUrl(): string {\n const envApiUrl = process.env[AMISTIO_API_URL_ENV]?.trim();\n return envApiUrl || officialAmistioApiUrl;\n}\n\nfunction apiUrlOverrideWasRequested(command: Command): boolean {\n return command.getOptionValueSource(\"apiUrl\") === \"cli\" || Boolean(process.env[AMISTIO_API_URL_ENV]?.trim());\n}\n\nfunction formatApiUrlFlag(apiUrl: string): string {\n return isOfficialAmistioApiUrl(apiUrl) ? \"\" : ` --api-url ${formatShellArg(apiUrl)}`;\n}\n\nfunction formatShellArg(value: string): string {\n return /^[A-Za-z0-9_./:@-]+$/.test(value) ? value : `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n\ntype RunnerToolConfig =\n | {\n ready: true;\n tool: string;\n capabilities: RunnerToolCapability[];\n source: RunnerPreferenceSource;\n status: RunnerPreferenceStatus;\n requestedTool?: RunnerToolSelection;\n requestedInvocationChannel?: RunnerInvocationChannel;\n effectiveTool?: RunnerToolName | \"custom\";\n effectiveInvocationChannel?: RunnerEffectiveInvocationChannel;\n model?: string | undefined;\n providerId?: string | undefined;\n modelId?: string | undefined;\n modelVariant?: string | undefined;\n reasoningEffort?: RunnerReasoningEffort | undefined;\n message?: string;\n }\n | {\n ready: false;\n tool: string;\n capabilities: RunnerToolCapability[];\n source: RunnerPreferenceSource;\n status: RunnerPreferenceStatus;\n requestedTool?: RunnerToolSelection;\n requestedInvocationChannel?: RunnerInvocationChannel;\n effectiveTool?: RunnerToolName | \"custom\";\n effectiveInvocationChannel?: RunnerEffectiveInvocationChannel;\n model?: string | undefined;\n providerId?: string | undefined;\n modelId?: string | undefined;\n modelVariant?: string | undefined;\n reasoningEffort?: RunnerReasoningEffort | undefined;\n message: string;\n };\n\ninterface RunnerModelConfig {\n model?: string | undefined;\n providerId?: string | undefined;\n modelId?: string | undefined;\n modelVariant?: string | undefined;\n reasoningEffort?: RunnerReasoningEffort | undefined;\n}\n\nasync function resolveRunnerToolConfig({ apiClient, explicitInvocationChannel, explicitModel, explicitModelId, explicitModelVariant, explicitProviderId, explicitReasoningEffort, explicitTool, projectId, toolCommand }: { apiClient: ApiClient; explicitInvocationChannel?: RunnerInvocationChannel; explicitModel?: string; explicitProviderId?: string; explicitModelId?: string; explicitModelVariant?: string; explicitReasoningEffort?: RunnerReasoningEffort; explicitTool?: string; projectId: string; toolCommand?: string }): Promise<RunnerToolConfig> {\n const capabilities = toRunnerToolCapabilities(await detectLocalTools());\n\n if (toolCommand) {\n const modelConfig = normalizeModelConfig({ model: explicitModel, providerId: explicitProviderId, modelId: explicitModelId, modelVariant: explicitModelVariant, reasoningEffort: explicitReasoningEffort });\n return {\n ready: true,\n tool: explicitTool ?? \"auto\",\n capabilities,\n source: \"cli\",\n status: \"custom\",\n effectiveTool: \"custom\",\n requestedInvocationChannel: explicitInvocationChannel ?? \"command\",\n effectiveInvocationChannel: \"command\",\n ...(explicitTool && explicitTool !== \"none\" && explicitTool !== \"auto\" && isLocalToolName(explicitTool) ? { requestedTool: explicitTool } : explicitTool === \"auto\" ? { requestedTool: \"auto\" } : {}),\n ...modelConfig,\n message: \"Using local custom tool command.\"\n };\n }\n\n if (explicitTool === \"none\") {\n const modelConfig = normalizeModelConfig({ model: explicitModel, providerId: explicitProviderId, modelId: explicitModelId, modelVariant: explicitModelVariant, reasoningEffort: explicitReasoningEffort });\n if (hasModelConfig(modelConfig)) {\n return unavailableToolConfig({ capabilities, source: \"cli\", status: \"modelUnsupported\", message: \"Model configuration cannot be used with --tool none.\", tool: \"none\", requestedInvocationChannel: explicitInvocationChannel ?? \"auto\", ...modelConfig });\n }\n return { ready: true, tool: \"none\", capabilities, source: \"cli\", status: \"none\", requestedInvocationChannel: explicitInvocationChannel ?? \"auto\", message: \"No local tool selected.\" };\n }\n\n if (explicitTool && explicitTool !== \"auto\" && !isLocalToolName(explicitTool)) {\n const modelConfig = normalizeModelConfig({ model: explicitModel, providerId: explicitProviderId, modelId: explicitModelId, modelVariant: explicitModelVariant, reasoningEffort: explicitReasoningEffort });\n return unavailableToolConfig({ capabilities, source: \"cli\", status: \"unavailable\", message: `Unsupported local tool: ${explicitTool}.`, tool: explicitTool, requestedInvocationChannel: explicitInvocationChannel ?? \"auto\", ...modelConfig });\n }\n\n const remotePreference = await apiClient.getRunnerPreferences(projectId).then((response) => response.effective).catch(() => undefined);\n const requestedTool = (explicitTool as RunnerToolSelection | undefined) ?? remotePreference?.tool ?? \"auto\";\n const requestedInvocationChannel = explicitInvocationChannel ?? remotePreference?.invocationChannel ?? \"auto\";\n const modelConfig = normalizeModelConfig({\n model: explicitModel ?? remotePreference?.model,\n providerId: explicitProviderId ?? remotePreference?.providerId,\n modelId: explicitModelId ?? remotePreference?.modelId,\n modelVariant: explicitModelVariant ?? remotePreference?.modelVariant,\n reasoningEffort: explicitReasoningEffort ?? remotePreference?.reasoningEffort\n });\n const source: RunnerPreferenceSource = explicitTool || explicitInvocationChannel || hasExplicitModelConfig({ model: explicitModel, providerId: explicitProviderId, modelId: explicitModelId, modelVariant: explicitModelVariant, reasoningEffort: explicitReasoningEffort }) ? \"cli\" : remotePreference?.source ?? \"default\";\n\n return resolveRequestedTool({ capabilities, modelConfig, requestedInvocationChannel, requestedTool, source });\n}\n\nfunction resolveRequestedTool({ capabilities, modelConfig, requestedInvocationChannel, requestedTool, source }: { capabilities: RunnerToolCapability[]; modelConfig: RunnerModelConfig; requestedInvocationChannel: RunnerInvocationChannel; requestedTool: RunnerToolSelection; source: RunnerPreferenceSource }): RunnerToolConfig {\n const needsModelSelection = hasModelConfig(modelConfig);\n if (requestedTool === \"auto\") {\n const candidate = capabilities.find((capability) => capability.available && capabilitySupportsInvocationChannel(capability, requestedInvocationChannel) && (!needsModelSelection || capability.supportsModelSelection));\n if (!candidate) {\n const anyAvailable = capabilities.some((capability) => capability.available);\n const anyChannelAvailable = capabilities.some((capability) => capability.available && capabilitySupportsInvocationChannel(capability, requestedInvocationChannel));\n const status: RunnerPreferenceStatus = !anyAvailable ? \"unavailable\" : requestedInvocationChannel !== \"auto\" && !anyChannelAvailable ? \"channelUnsupported\" : needsModelSelection ? \"modelUnsupported\" : \"unavailable\";\n return unavailableToolConfig({\n capabilities,\n source,\n status,\n requestedTool,\n requestedInvocationChannel,\n tool: \"auto\",\n ...modelConfig,\n message: status === \"channelUnsupported\" ? `No installed local AI tool can honor ${requestedInvocationChannel} invocation.` : needsModelSelection ? \"No installed local tool can honor the selected provider/model configuration.\" : \"No supported local AI tool is installed.\"\n });\n }\n const modelResolution = resolveProviderModelConfig(candidate, modelConfig);\n if (!modelResolution.ready) {\n return unavailableToolConfig({ capabilities, source, status: modelResolution.status, requestedTool, requestedInvocationChannel, effectiveTool: candidate.name, effectiveInvocationChannel: effectiveInvocationChannel(candidate, requestedInvocationChannel), tool: \"auto\", ...modelConfig, message: modelResolution.message });\n }\n return { ready: true, tool: \"auto\", capabilities, source, status: \"resolved\", requestedTool, requestedInvocationChannel, effectiveTool: candidate.name, effectiveInvocationChannel: effectiveInvocationChannel(candidate, requestedInvocationChannel), ...modelResolution.config };\n }\n\n const capability = capabilities.find((candidate) => candidate.name === requestedTool);\n if (!capability?.available) {\n return unavailableToolConfig({ capabilities, source, status: \"unavailable\", requestedTool, requestedInvocationChannel, tool: requestedTool, ...modelConfig, message: `${requestedTool} is selected but is not available on this runner.` });\n }\n if (!capabilitySupportsInvocationChannel(capability, requestedInvocationChannel)) {\n return unavailableToolConfig({ capabilities, source, status: \"channelUnsupported\", requestedTool, requestedInvocationChannel, effectiveTool: requestedTool, tool: requestedTool, ...modelConfig, message: `${requestedTool} is available but does not support ${requestedInvocationChannel} invocation on this runner.` });\n }\n if (needsModelSelection && !capability.supportsModelSelection) {\n return unavailableToolConfig({ capabilities, source, status: \"modelUnsupported\", requestedTool, requestedInvocationChannel, effectiveTool: requestedTool, effectiveInvocationChannel: effectiveInvocationChannel(capability, requestedInvocationChannel), tool: requestedTool, ...modelConfig, message: `${requestedTool} is available but does not support Amistio model selection yet.` });\n }\n const modelResolution = resolveProviderModelConfig(capability, modelConfig);\n if (!modelResolution.ready) {\n return unavailableToolConfig({ capabilities, source, status: modelResolution.status, requestedTool, requestedInvocationChannel, effectiveTool: requestedTool, effectiveInvocationChannel: effectiveInvocationChannel(capability, requestedInvocationChannel), tool: requestedTool, ...modelConfig, message: modelResolution.message });\n }\n\n return { ready: true, tool: requestedTool, capabilities, source, status: \"resolved\", requestedTool, requestedInvocationChannel, effectiveTool: requestedTool, effectiveInvocationChannel: effectiveInvocationChannel(capability, requestedInvocationChannel), ...modelResolution.config };\n}\n\nfunction unavailableToolConfig(input: { capabilities: RunnerToolCapability[]; source: RunnerPreferenceSource; status: RunnerPreferenceStatus; tool: string; message: string; requestedTool?: RunnerToolSelection; requestedInvocationChannel?: RunnerInvocationChannel; effectiveTool?: RunnerToolName | \"custom\"; effectiveInvocationChannel?: RunnerEffectiveInvocationChannel } & RunnerModelConfig): RunnerToolConfig {\n return {\n ready: false,\n tool: input.tool,\n capabilities: input.capabilities,\n source: input.source,\n status: input.status,\n message: input.message,\n ...(input.requestedTool ? { requestedTool: input.requestedTool } : {}),\n ...(input.requestedInvocationChannel ? { requestedInvocationChannel: input.requestedInvocationChannel } : {}),\n ...(input.effectiveTool ? { effectiveTool: input.effectiveTool } : {}),\n ...(input.effectiveInvocationChannel ? { effectiveInvocationChannel: input.effectiveInvocationChannel } : {}),\n ...normalizeModelConfig(input)\n };\n}\n\nfunction resolveProviderModelConfig(capability: RunnerToolCapability, modelConfig: RunnerModelConfig): { ready: true; config: RunnerModelConfig } | { ready: false; status: RunnerPreferenceStatus; message: string } {\n const normalized = normalizeModelConfig(modelConfig);\n if (!hasModelConfig(normalized)) {\n return { ready: true, config: {} };\n }\n if (!capability.supportsModelSelection) {\n return { ready: false, status: \"modelUnsupported\", message: `${capability.name} does not support Amistio model selection yet.` };\n }\n if (!normalized.providerId && !normalized.modelId && !normalized.modelVariant && (!normalized.reasoningEffort || normalized.reasoningEffort === \"auto\")) {\n return { ready: true, config: normalized };\n }\n\n const catalog = capability.providerCatalog;\n if (!catalog) {\n return { ready: false, status: \"modelUnsupported\", message: `${capability.name} does not report a provider model catalog yet.` };\n }\n const providerId = normalized.providerId ?? inferProviderIdForModel(catalog, normalized.modelId ?? normalized.model);\n if (!providerId) {\n return { ready: false, status: \"modelUnsupported\", message: \"Select a provider id with the provider-backed model preference.\" };\n }\n const provider = catalog[providerId];\n if (!provider) {\n return { ready: false, status: \"modelUnsupported\", message: `${providerId} is not available in ${capability.name}'s provider catalog.` };\n }\n const modelId = normalized.modelId ?? inferModelId(provider.models, normalized.model);\n if (!modelId) {\n return { ready: false, status: \"modelUnsupported\", message: \"Select a model id with the provider-backed model preference.\" };\n }\n const model = provider.models[modelId];\n if (!model) {\n return { ready: false, status: \"modelUnsupported\", message: `${providerId}/${modelId} is not available in ${capability.name}'s provider catalog.` };\n }\n if (normalized.modelVariant) {\n const variant = model.variants?.[normalized.modelVariant];\n if (!variant || variant.disabled) {\n return { ready: false, status: \"variantUnsupported\", message: `${providerId}/${modelId} does not support variant ${normalized.modelVariant}.` };\n }\n }\n if (normalized.reasoningEffort && normalized.reasoningEffort !== \"auto\") {\n const supportedEfforts = model.supportedReasoningEfforts ?? (model.reasoning ? [\"auto\", \"low\", \"medium\", \"high\", \"xhigh\"] : []);\n if (!supportedEfforts.includes(normalized.reasoningEffort)) {\n return { ready: false, status: \"reasoningUnsupported\", message: `${providerId}/${modelId} does not support ${normalized.reasoningEffort} reasoning effort.` };\n }\n }\n\n return {\n ready: true,\n config: {\n model: normalized.model ?? `${providerId}/${modelId}`,\n providerId,\n modelId,\n ...(normalized.modelVariant ? { modelVariant: normalized.modelVariant } : {}),\n ...(normalized.reasoningEffort ? { reasoningEffort: normalized.reasoningEffort } : {})\n }\n };\n}\n\nfunction normalizeModelConfig(config: RunnerModelConfig): RunnerModelConfig {\n const model = cleanPreferenceText(config.model);\n const providerId = cleanPreferenceText(config.providerId);\n const modelId = cleanPreferenceText(config.modelId);\n const modelVariant = cleanPreferenceText(config.modelVariant);\n return {\n ...(model ? { model } : {}),\n ...(providerId ? { providerId } : {}),\n ...(modelId ? { modelId } : {}),\n ...(modelVariant ? { modelVariant } : {}),\n ...(config.reasoningEffort ? { reasoningEffort: config.reasoningEffort } : {})\n };\n}\n\nfunction hasExplicitModelConfig(config: RunnerModelConfig): boolean {\n return hasModelConfig(normalizeModelConfig(config));\n}\n\nfunction hasModelConfig(config: RunnerModelConfig): boolean {\n return Boolean(config.model || config.providerId || config.modelId || config.modelVariant || config.reasoningEffort);\n}\n\nfunction cleanPreferenceText(value: string | undefined): string | undefined {\n const trimmed = value?.trim();\n return trimmed ? trimmed : undefined;\n}\n\nfunction inferProviderIdForModel(catalog: NonNullable<RunnerToolCapability[\"providerCatalog\"]>, model: string | undefined): string | undefined {\n if (!model) return undefined;\n if (model.includes(\"/\")) {\n const [providerId, modelId] = model.split(\"/\", 2);\n if (providerId && modelId && catalog[providerId]?.models[modelId]) return providerId;\n }\n return Object.entries(catalog).find(([, provider]) => Boolean(provider.models[model]))?.[0];\n}\n\nfunction inferModelId(models: NonNullable<RunnerToolCapability[\"providerCatalog\"]>[string][\"models\"], model: string | undefined): string | undefined {\n if (!model) return undefined;\n if (models[model]) return model;\n const slashIndex = model.indexOf(\"/\");\n if (slashIndex !== -1) {\n const modelId = model.slice(slashIndex + 1);\n if (models[modelId]) return modelId;\n }\n return undefined;\n}\n\nfunction toolConfigModelOptions(toolConfig: RunnerToolConfig): RunnerModelConfig {\n return normalizeModelConfig(toolConfig);\n}\n\nfunction localModelConfigOptions(options: RunnerModelConfig & { provider?: string }): RunnerModelConfig {\n return normalizeModelConfig({\n model: options.model,\n providerId: options.providerId ?? options.provider,\n modelId: options.modelId,\n modelVariant: options.modelVariant,\n reasoningEffort: options.reasoningEffort\n });\n}\n\nfunction capabilitySupportsInvocationChannel(capability: RunnerToolCapability, channel: RunnerInvocationChannel): boolean {\n if (channel === \"auto\") return capability.available;\n if (channel === \"sdk\") return capability.sdkAvailable;\n return capability.commandAvailable;\n}\n\nfunction effectiveInvocationChannel(capability: RunnerToolCapability, channel: RunnerInvocationChannel): RunnerEffectiveInvocationChannel {\n if (channel === \"sdk\" || channel === \"command\") return channel;\n return capability.sdkAvailable ? \"sdk\" : \"command\";\n}\n\nfunction toRunnerToolCapabilities(tools: DetectedLocalTool[]): RunnerToolCapability[] {\n return tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n available: tool.available,\n sdkAvailable: tool.sdkAvailable,\n commandAvailable: tool.commandAvailable,\n execution: tool.execution,\n supportsSessionReuse: tool.supportsSessionReuse,\n resumabilityScope: tool.resumabilityScope,\n supportsModelSelection: tool.supportsModelSelection,\n supportsBranchIsolation: true,\n supportsGitWorktreeIsolation: true\n }));\n}\n\ninterface RunnerClaimLaneMetadata {\n claimLaneId?: string;\n maxConcurrentWork?: number;\n}\n\ninterface RunnerHeartbeatConcurrencyMetadata {\n maxConcurrentWork: number;\n activeClaimLaneIds: string[];\n}\n\nfunction runnerIsolationCapabilityMetadata(laneMetadata: RunnerClaimLaneMetadata = {}) {\n return {\n machineId: runnerMachineId(),\n supportedWorkKinds: runnerSupportedWorkKinds,\n supportsBranchIsolation: true,\n supportsGitWorktreeIsolation: true,\n ...(laneMetadata.claimLaneId ? { claimLaneId: laneMetadata.claimLaneId } : {}),\n ...(laneMetadata.maxConcurrentWork !== undefined ? { maxConcurrentWork: laneMetadata.maxConcurrentWork } : {})\n };\n}\n\nfunction runnerHeartbeatMetadata(toolConfig?: RunnerToolConfig, mode = currentRunnerMode(), concurrencyMetadata: RunnerHeartbeatConcurrencyMetadata = { maxConcurrentWork: 1, activeClaimLaneIds: [\"default\"] }) {\n const modelConfig = toolConfig ? toolConfigModelOptions(toolConfig) : {};\n const effectiveModelConfig = toolConfig?.ready ? modelConfig : {};\n return {\n version: CLI_VERSION,\n mode,\n hostname: os.hostname(),\n ...runnerIsolationCapabilityMetadata(),\n maxConcurrentWork: concurrencyMetadata.maxConcurrentWork,\n activeClaimLaneIds: concurrencyMetadata.activeClaimLaneIds,\n resourceUsage: sampleCurrentRunnerResourceUsage(),\n ...(toolConfig?.capabilities ? { capabilities: toolConfig.capabilities } : {}),\n ...(toolConfig?.requestedTool ? { requestedTool: toolConfig.requestedTool } : {}),\n ...(toolConfig?.requestedInvocationChannel ? { requestedInvocationChannel: toolConfig.requestedInvocationChannel } : {}),\n ...(modelConfig.providerId ? { requestedProviderId: modelConfig.providerId } : {}),\n ...(modelConfig.modelId ? { requestedModelId: modelConfig.modelId } : {}),\n ...(modelConfig.modelVariant ? { requestedModelVariant: modelConfig.modelVariant } : {}),\n ...(modelConfig.reasoningEffort ? { requestedReasoningEffort: modelConfig.reasoningEffort } : {}),\n ...(toolConfig?.effectiveTool ? { effectiveTool: toolConfig.effectiveTool } : {}),\n ...(toolConfig?.effectiveInvocationChannel ? { effectiveInvocationChannel: toolConfig.effectiveInvocationChannel } : {}),\n ...(effectiveModelConfig.model ? { effectiveModel: effectiveModelConfig.model } : {}),\n ...(effectiveModelConfig.providerId ? { effectiveProviderId: effectiveModelConfig.providerId } : {}),\n ...(effectiveModelConfig.modelId ? { effectiveModelId: effectiveModelConfig.modelId } : {}),\n ...(effectiveModelConfig.modelVariant ? { effectiveModelVariant: effectiveModelConfig.modelVariant } : {}),\n ...(effectiveModelConfig.reasoningEffort ? { effectiveReasoningEffort: effectiveModelConfig.reasoningEffort } : {}),\n ...(toolConfig?.source ? { preferenceSource: toolConfig.source } : {}),\n ...(toolConfig?.status ? { preferenceStatus: toolConfig.status } : {}),\n ...(toolConfig?.message ? { preferenceMessage: toolConfig.message } : {})\n };\n}\n\nfunction runnerMachineId(): string {\n return createHash(\"sha256\").update(`${os.hostname()}:${os.platform()}:${os.arch()}`).digest(\"hex\").slice(0, 20);\n}\n\nasync function delay(milliseconds: number) {\n await new Promise((resolve) => setTimeout(resolve, milliseconds));\n}\n\nprogram.parseAsync().catch((error: unknown) => {\n console.error(error instanceof Error ? error.message : String(error));\n process.exitCode = 1;\n});\n", "import { z } from \"zod\";\n\nexport const isoDateTimeSchema = z.string().datetime({ offset: true });\n\nexport const itemTypeSchema = z.enum([\n \"account\",\n \"accountUser\",\n \"accountInvite\",\n \"accountSettings\",\n \"user\",\n \"project\",\n \"repositoryLink\",\n \"brainDocument\",\n \"generatedDraft\",\n \"issue\",\n \"securityScan\",\n \"securityFinding\",\n \"securityPostureSnapshot\",\n \"testProfile\",\n \"testQualityScan\",\n \"testQualityFinding\",\n \"implementationTestGate\",\n \"appEvaluationScan\",\n \"appEvaluationFinding\",\n \"brainConsolidationScan\",\n \"brainConsolidationProposal\",\n \"implementationVerification\",\n \"projectContextMap\",\n \"projectContextRefresh\",\n \"projectSystemDiagram\",\n \"contextMiss\",\n \"syncCursor\",\n \"syncConflict\",\n \"workItem\",\n \"runnerHeartbeat\",\n \"runnerExecutionLog\",\n \"runnerCredential\",\n \"runnerCommand\",\n \"planReviewMessage\",\n \"assistantMessage\",\n \"impactReport\",\n \"toolSession\",\n \"activityEvent\",\n \"pairingSession\"\n]);\n\nexport const documentTypeSchema = z.enum([\n \"architecture\",\n \"context\",\n \"decision\",\n \"feature\",\n \"memory\",\n \"plan\",\n \"prompt\",\n \"workflow\"\n]);\n\nexport const documentContentFormatSchema = z.enum([\"markdown\", \"html\"]);\n\nexport const artifactFormatPreferenceSchema = z.enum([\"markdown\", \"html\", \"both\", \"auto\"]);\n\nexport const syncStateSchema = z.enum([\n \"draft\",\n \"approved\",\n \"synced\",\n \"dirtyInRepo\",\n \"dirtyInWeb\",\n \"conflicted\",\n \"archived\"\n]);\n\nexport const workStatusSchema = z.enum([\n \"drafted\",\n \"approved\",\n \"synced\",\n \"running\",\n \"blocked\",\n \"completed\",\n \"changesRequested\",\n \"failed\",\n \"conflicted\"\n]);\n\nexport const sourceSchema = z.enum([\"web\", \"repo\", \"generated\", \"runner\"]);\n\nexport const executionModeSchema = z.enum([\"localRunner\", \"cloudSandbox\"]);\n\nexport const workKindSchema = z.enum([\"brainGeneration\", \"implementation\", \"planRevision\", \"assistantQuestion\", \"impactPreview\", \"issueDiagnosis\", \"securityPostureScan\", \"appEvaluationScan\", \"brainConsolidationScan\", \"projectContextRefresh\", \"implementationVerification\", \"testQualityScan\", \"implementationTestGate\", \"runnerCommand\"]);\n\nexport const autopilotModeSchema = z.enum([\"disabled\", \"enabled\", \"paused\"]);\n\nexport const autopilotClassificationOutcomeSchema = z.enum([\"safeAutopilotEligible\", \"requiresReview\", \"blocked\", \"unsafe\"]);\n\nexport const autopilotCandidateTypeSchema = z.enum([\n \"generatedDraftApproval\",\n \"projectBrainSync\",\n \"issueDiagnosis\",\n \"issueFixHandoff\",\n \"securityPostureScan\",\n \"securityRemediationHandoff\",\n \"appEvaluationScan\",\n \"appEvaluationPlanHandoff\",\n \"appEvaluationCleanup\",\n \"projectContextRefresh\",\n \"impactPreview\",\n \"implementationQueue\",\n \"implementationVerification\",\n \"testQualityScan\",\n \"implementationTestGate\",\n \"requeueWork\",\n \"runnerCommand\"\n]);\n\nexport const autopilotReasonCodeSchema = z.enum([\n \"allowedLowRisk\",\n \"disabled\",\n \"paused\",\n \"runnerRequired\",\n \"runnerIncompatible\",\n \"repositoryRequired\",\n \"staleRevision\",\n \"duplicateInFlight\",\n \"budgetExceeded\",\n \"protectedSurface\",\n \"destructiveAction\",\n \"rawSourceUpload\",\n \"secretRisk\",\n \"primaryCheckoutMutation\",\n \"policyBlocked\",\n \"reviewRequired\",\n \"cooldownActive\",\n \"expired\",\n \"failureBudgetExceeded\",\n \"verificationFailed\",\n \"redactionHit\",\n \"candidateTypeNotAllowed\",\n \"riskTierExceeded\",\n \"unsafePath\",\n \"schemaInvalid\",\n \"notAdditive\",\n \"scopeMismatch\",\n \"sizeLimitExceeded\",\n \"worktreeIsolationRequired\",\n \"verificationRequired\",\n \"organizationPolicyRequired\",\n \"unsafe\"\n]);\n\nexport const autopilotGuardCheckSchema = z.object({\n name: z.string().trim().min(1).max(120),\n status: z.enum([\"passed\", \"failed\", \"warning\"]),\n summary: z.string().trim().min(1).max(600)\n});\n\nexport const implementationHandoffStatusSchema = z.enum([\"notStarted\", \"noChanges\", \"prReady\", \"blocked\", \"failed\"]);\n\nexport const implementationHandoffCleanupStatusSchema = z.enum([\"notApplicable\", \"pending\", \"completed\", \"failed\"]);\n\nexport const implementationHandoffRecoveryCategorySchema = z.enum([\"noChangeCleaned\", \"rebaseConflict\", \"dirtyWorktree\", \"unresolvedConflicts\", \"providerBlocked\", \"cleanupRetryAvailable\", \"manualReview\", \"artifactBlocked\", \"nonGithubProvider\"]);\n\nexport const implementationHandoffRecoveryActionSchema = z.enum([\"retryHandoff\", \"requeueFreshAttempt\", \"keepForManualRepair\", \"cleanNoChangeWorktree\", \"markSupersededNoChanges\", \"exportHandoffDetails\", \"retryCleanup\"]);\n\nexport const implementationHandoffRebaseAbortStatusSchema = z.enum([\"notAttempted\", \"succeeded\", \"failed\", \"notApplicable\"]);\n\nconst safeRepoPathSchema = z.string().trim().min(1).max(300).refine((value) => {\n if (value.startsWith(\"/\") || /^[A-Za-z]:[\\\\/]/.test(value)) {\n return false;\n }\n return !value.split(/[\\\\/]+/).includes(\"..\");\n}, \"Path must be repository-relative without traversal\");\n\nexport const implementationHandoffArtifactStatusSchema = z.enum([\"included\", \"skipped\", \"blocked\"]);\n\nexport const implementationHandoffArtifactSchema = z.object({\n documentId: z.string().trim().min(1).max(200),\n title: z.string().trim().min(1).max(200).optional(),\n repoPath: safeRepoPathSchema,\n contentFormat: documentContentFormatSchema,\n status: implementationHandoffArtifactStatusSchema,\n message: z.string().trim().min(1).max(600).optional()\n}).strict();\n\nexport const implementationHandoffArtifactsSchema = z.object({\n included: z.array(implementationHandoffArtifactSchema).max(50).default([]),\n skipped: z.array(implementationHandoffArtifactSchema).max(50).default([]),\n blocked: z.array(implementationHandoffArtifactSchema).max(50).default([])\n}).strict();\n\nexport const implementationHandoffRecoverySchema = z.object({\n category: implementationHandoffRecoveryCategorySchema,\n availableActions: z.array(implementationHandoffRecoveryActionSchema).max(8).default([]),\n cleanupEligible: z.boolean().optional(),\n conflictFiles: z.array(safeRepoPathSchema).max(25).default([]),\n rebaseAbortStatus: implementationHandoffRebaseAbortStatusSchema.optional(),\n summary: z.string().trim().min(1).max(600).optional(),\n worktreeKey: z.string().trim().min(1).max(200).optional()\n}).strict();\n\nexport const implementationVerificationOutcomeSchema = z.enum([\"verifiedImplemented\", \"partiallyImplemented\", \"notImplemented\", \"inconclusive\", \"verificationBlocked\"]);\n\nexport const implementationVerificationStatusSchema = z.enum([\"queued\", \"running\", \"completed\", \"failed\", \"blocked\", \"stale\"]);\n\nexport const implementationProofStatusSchema = z.enum([\"unverified\", \"verificationQueued\", \"verificationRunning\", \"verifiedImplemented\", \"partiallyImplemented\", \"notImplemented\", \"inconclusive\", \"verificationBlocked\", \"humanOverride\"]);\n\nexport const implementationHandoffSchema = z.object({\n provider: z.string().trim().min(1).max(80).optional(),\n status: implementationHandoffStatusSchema,\n baseBranch: z.string().trim().min(1).max(200).optional(),\n headBranch: z.string().trim().min(1).max(200).optional(),\n remoteName: z.string().trim().min(1).max(80).optional(),\n commitSha: z.string().trim().min(7).max(64).optional(),\n prNumber: z.number().int().positive().optional(),\n prUrl: z.string().trim().url().max(500).optional(),\n cleanupStatus: implementationHandoffCleanupStatusSchema.optional(),\n cleanupMessage: z.string().trim().min(1).max(600).optional(),\n artifacts: implementationHandoffArtifactsSchema.optional(),\n recovery: implementationHandoffRecoverySchema.optional(),\n message: z.string().trim().min(1).max(600).optional(),\n error: z.string().trim().min(1).max(1200).optional()\n}).strict();\n\nexport const generatedDraftStatusSchema = z.enum([\"queued\", \"generating\", \"reviewing\", \"approved\", \"rejected\", \"changesRequested\", \"failed\"]);\n\nexport const assistantQuestionModeSchema = z.enum([\"brainOnly\", \"sourceAware\"]);\n\nexport const impactRiskLevelSchema = z.enum([\"low\", \"medium\", \"high\", \"critical\"]);\n\nexport const autopilotBudgetWindowSchema = z.object({\n name: z.string().trim().min(1).max(80),\n limit: z.number().int().nonnegative(),\n used: z.number().int().nonnegative(),\n remaining: z.number().int().nonnegative().optional(),\n windowStartedAt: isoDateTimeSchema,\n windowEndsAt: isoDateTimeSchema\n}).strict();\n\nexport const autopilotPolicySnapshotSchema = z.object({\n policyVersion: z.string().trim().min(1).max(80),\n mode: autopilotModeSchema,\n enabledByUserId: z.string().min(1).optional(),\n repositoryLinkId: z.string().min(1).optional(),\n runnerId: z.string().min(1).optional(),\n allowedWorkKinds: z.array(workKindSchema).max(20).default([]),\n allowedCandidateTypes: z.array(autopilotCandidateTypeSchema).max(30).default([]),\n maxRiskLevel: impactRiskLevelSchema.default(\"low\"),\n dailyWorkLimit: z.number().int().positive().max(100).optional(),\n dailyPrLimit: z.number().int().nonnegative().max(100).optional(),\n concurrentWorkLimit: z.number().int().positive().max(20).optional(),\n runnerMinuteBudget: z.number().int().nonnegative().max(1440).optional(),\n failureBudget: z.number().int().nonnegative().max(50).optional(),\n expiresAt: isoDateTimeSchema.optional(),\n reviewAfter: isoDateTimeSchema.optional(),\n cooldownUntil: isoDateTimeSchema.optional(),\n pausedReason: z.string().trim().min(1).max(600).optional(),\n budgetWindows: z.array(autopilotBudgetWindowSchema).max(10).default([])\n}).strict();\n\nexport const autopilotCandidateLinksSchema = z.object({\n workItemId: z.string().min(1).optional(),\n documentId: z.string().min(1).optional(),\n generatedDraftId: z.string().min(1).optional(),\n issueId: z.string().min(1).optional(),\n securityScanId: z.string().min(1).optional(),\n securityFindingId: z.string().min(1).optional(),\n appEvaluationScanId: z.string().min(1).optional(),\n appEvaluationFindingId: z.string().min(1).optional(),\n brainConsolidationScanId: z.string().min(1).optional(),\n implementationVerificationId: z.string().min(1).optional(),\n testQualityScanId: z.string().min(1).optional(),\n testQualityFindingId: z.string().min(1).optional(),\n implementationTestGateId: z.string().min(1).optional(),\n projectContextRefreshId: z.string().min(1).optional(),\n runnerCommandId: z.string().min(1).optional(),\n repositoryLinkId: z.string().min(1).optional(),\n runnerId: z.string().min(1).optional(),\n branchName: z.string().trim().min(1).max(200).optional(),\n worktreeKey: z.string().trim().min(1).max(300).optional(),\n pullRequestUrl: z.string().trim().url().max(500).optional()\n}).strict();\n\nexport const autopilotCandidateActionSchema = z.object({\n candidateId: z.string().trim().min(1).max(160),\n candidateType: autopilotCandidateTypeSchema,\n subjectId: z.string().trim().min(1).max(200),\n workKind: workKindSchema.optional(),\n riskLevel: impactRiskLevelSchema.default(\"low\"),\n summary: z.string().trim().min(1).max(600),\n safeRepoPaths: z.array(safeRepoPathSchema).max(50).default([]),\n evidenceSummaries: z.array(z.string().trim().min(1).max(300)).max(20).default([]),\n links: autopilotCandidateLinksSchema.default({}),\n policySnapshot: autopilotPolicySnapshotSchema.optional(),\n outcome: autopilotClassificationOutcomeSchema.optional(),\n reasonCodes: z.array(autopilotReasonCodeSchema).max(30).optional(),\n guardChecks: z.array(autopilotGuardCheckSchema).max(30).optional()\n}).strict();\n\nexport const autopilotAuthorizationSchema = z.object({\n authorizationId: z.string().trim().min(1).max(160),\n policyVersion: z.string().trim().min(1).max(80),\n mode: autopilotModeSchema,\n outcome: autopilotClassificationOutcomeSchema,\n candidateId: z.string().trim().min(1).max(160).optional(),\n candidateType: autopilotCandidateTypeSchema.optional(),\n subjectId: z.string().trim().min(1).max(200).optional(),\n riskLevel: impactRiskLevelSchema,\n reasonCodes: z.array(autopilotReasonCodeSchema).min(1),\n guardChecks: z.array(autopilotGuardCheckSchema).default([]),\n policySnapshot: autopilotPolicySnapshotSchema.optional(),\n budgetWindows: z.array(autopilotBudgetWindowSchema).max(10).default([]),\n linkedRecords: autopilotCandidateLinksSchema.optional(),\n evidenceSummaries: z.array(z.string().trim().min(1).max(300)).max(20).default([]),\n authorizedAt: isoDateTimeSchema.optional(),\n authorizedBy: z.literal(\"autopilot\").optional(),\n reviewedByUserId: z.string().min(1).optional(),\n summary: z.string().trim().min(1).max(600)\n}).strict();\n\nexport const impactReportStatusSchema = z.enum([\"queued\", \"running\", \"completed\", \"failed\", \"stale\"]);\n\nexport const issueCategorySchema = z.enum([\"bug\", \"regression\", \"brokenWorkflow\", \"security\", \"operational\", \"other\"]);\n\nexport const issueSeveritySchema = z.enum([\"low\", \"medium\", \"high\", \"critical\"]);\n\nexport const issueStatusSchema = z.enum([\"queued\", \"diagnosing\", \"analysisReady\", \"approved\", \"changesRequested\", \"rejected\", \"implementationQueued\", \"implemented\", \"failed\"]);\n\nexport const issueApprovalStateSchema = z.enum([\"proposed\", \"approved\", \"changesRequested\", \"rejected\", \"implemented\", \"blocked\"]);\n\nexport const securityScanStatusSchema = z.enum([\"queued\", \"running\", \"completed\", \"failed\", \"stale\", \"skipped\"]);\n\nexport const securityScanSourceSchema = z.enum([\"nightly\", \"manual\", \"runner\"]);\n\nexport const securityFindingCategorySchema = z.enum([\"owasp\", \"dependency\", \"supplyChain\", \"secretHygiene\", \"authentication\", \"authorization\", \"tenantIsolation\", \"headers\", \"redirects\", \"csrf\", \"cors\", \"ciCd\", \"logging\", \"rateLimiting\", \"runnerBoundary\", \"other\"]);\n\nexport const securityFindingSeveritySchema = z.enum([\"info\", \"low\", \"medium\", \"high\", \"critical\"]);\n\nexport const securityFindingConfidenceSchema = z.enum([\"low\", \"medium\", \"high\"]);\n\nexport const securityFindingStatusSchema = z.enum([\"open\", \"planReady\", \"approved\", \"changesRequested\", \"dismissed\", \"acceptedRisk\", \"remediationQueued\", \"resolved\", \"failed\"]);\n\nexport const securityApprovalStateSchema = z.enum([\"proposed\", \"approved\", \"changesRequested\", \"dismissed\", \"acceptedRisk\", \"implemented\", \"blocked\"]);\n\nexport const testProfileStatusSchema = z.enum([\"detected\", \"reviewReady\", \"approved\", \"disabled\", \"stale\"]);\n\nexport const testPackageManagerSchema = z.enum([\"pnpm\", \"npm\", \"yarn\", \"bun\", \"dotnet\", \"maven\", \"gradle\", \"mixed\", \"unknown\"]);\n\nexport const testCommandKindSchema = z.enum([\"verify\", \"test\", \"coverage\", \"lint\", \"typecheck\", \"build\", \"focused\"]);\n\nexport const testCommandSourceSchema = z.enum([\"detected\", \"approved\", \"manual\"]);\n\nexport const testCoverageMetricStatusSchema = z.enum([\"met\", \"belowThreshold\", \"missing\", \"blocked\", \"unknown\"]);\n\nexport const testCommandStatusSchema = z.enum([\"passed\", \"failed\", \"blocked\", \"skipped\", \"missing\"]);\n\nexport const testRedactionStatusSchema = z.enum([\"clean\", \"redacted\", \"blocked\"]);\n\nexport const testQualityScanStatusSchema = z.enum([\"queued\", \"running\", \"completed\", \"failed\", \"stale\", \"skipped\"]);\n\nexport const testQualityFindingCategorySchema = z.enum([\"missingTests\", \"missingCoverage\", \"missingCommand\", \"lowCoverage\", \"failingTests\", \"failingQuality\", \"failingQualityCheck\", \"staleScan\", \"blockedEnvironment\", \"weakTests\", \"flakyTests\", \"unverifiedImplementation\", \"testGap\", \"other\"]);\n\nexport const testQualityFindingSeveritySchema = z.enum([\"info\", \"low\", \"medium\", \"high\", \"critical\"]);\n\nexport const testQualityFindingConfidenceSchema = z.enum([\"low\", \"medium\", \"high\"]);\n\nexport const testQualityFindingStatusSchema = z.enum([\"open\", \"planReady\", \"approved\", \"changesRequested\", \"dismissed\", \"acceptedRisk\", \"implementationQueued\", \"resolved\", \"failed\"]);\n\nexport const testQualityApprovalStateSchema = z.enum([\"proposed\", \"approved\", \"changesRequested\", \"dismissed\", \"acceptedRisk\", \"implemented\", \"blocked\"]);\n\nexport const implementationTestGateStatusSchema = z.enum([\"queued\", \"running\", \"passed\", \"failed\", \"blocked\", \"overridden\", \"stale\"]);\n\nexport const implementationTestGateOutcomeSchema = z.enum([\"passed\", \"failed\", \"blocked\", \"missingTests\", \"belowThreshold\", \"overridden\"]);\n\nexport const implementationTestGateSourceSchema = z.enum([\"manual\", \"runner\", \"completion\", \"prHandoff\", \"push\", \"system\"]);\n\nexport const appEvaluationScanStatusSchema = z.enum([\"queued\", \"running\", \"completed\", \"failed\", \"stale\", \"skipped\"]);\n\nexport const appEvaluationFindingCategorySchema = z.enum([\"verification\", \"productDrift\", \"planCleanup\", \"promptRot\", \"missingMemory\", \"releaseReadiness\", \"ux\", \"accessibility\", \"performance\", \"reliability\", \"securityPosture\", \"other\"]);\n\nexport const appEvaluationFindingSeveritySchema = z.enum([\"info\", \"low\", \"medium\", \"high\", \"critical\"]);\n\nexport const appEvaluationFindingConfidenceSchema = z.enum([\"low\", \"medium\", \"high\"]);\n\nexport const appEvaluationFindingStatusSchema = z.enum([\"open\", \"planReady\", \"approved\", \"changesRequested\", \"dismissed\", \"acceptedRisk\", \"implementationQueued\", \"resolved\", \"failed\"]);\n\nexport const appEvaluationApprovalStateSchema = z.enum([\"proposed\", \"approved\", \"changesRequested\", \"dismissed\", \"acceptedRisk\", \"implemented\", \"blocked\"]);\n\nexport const appEvaluationPlanLifecycleActionSchema = z.enum([\"createPlan\", \"updatePlan\", \"markCompleted\", \"markImplemented\", \"markSuperseded\", \"markBlocked\", \"archive\", \"keepActive\", \"none\"]);\n\nexport const brainConsolidationScanStatusSchema = z.enum([\"running\", \"completed\", \"failed\"]);\n\nexport const brainConsolidationScanSourceSchema = z.enum([\"manual\", \"system\", \"runner\"]);\n\nexport const brainConsolidationProposalStatusSchema = z.enum([\"open\", \"approved\", \"changesRequested\", \"dismissed\", \"acceptedRisk\", \"resolved\", \"failed\"]);\n\nexport const brainConsolidationProposalActionSchema = z.enum([\"archiveDuplicates\", \"supersedeDuplicates\", \"keepCanonical\", \"manualReview\"]);\n\nexport const brainConsolidationRiskLevelSchema = z.enum([\"low\", \"medium\", \"high\", \"critical\"]);\n\nexport const brainConsolidationRecommendationCoverageSchema = z.enum([\"full\", \"partial\", \"notCovered\", \"ambiguous\"]);\n\nexport const brainConsolidationRecommendationConfidenceSchema = z.enum([\"low\", \"medium\", \"high\"]);\n\nexport const brainConsolidationRecommendationActionSchema = z.enum([\"archiveDuplicate\", \"proposeArchive\", \"manualReview\", \"skip\"]);\n\nexport const activityEventTypeSchema = z.enum([\n \"autopilotAuthorized\",\n \"autopilotReviewRequired\",\n \"autopilotBlocked\",\n \"autopilotPaused\",\n \"commandSubmitted\",\n \"generationQueued\",\n \"generationCompleted\",\n \"generationFailed\",\n \"documentGenerated\",\n \"documentReview\",\n \"documentSync\",\n \"projectTransferred\",\n \"workQueued\",\n \"workClaimed\",\n \"workStatusChanged\",\n \"runnerMilestone\",\n \"assistantAnswered\",\n \"assistantFailed\",\n \"impactPreviewQueued\",\n \"impactPreviewCompleted\",\n \"impactPreviewFailed\",\n \"impactPreviewStale\",\n \"issueDiagnosisQueued\",\n \"issueDiagnosisCompleted\",\n \"issueDiagnosisFailed\",\n \"issueReview\",\n \"issueImplementationQueued\",\n \"securityScanQueued\",\n \"securityScanStarted\",\n \"securityScanCompleted\",\n \"securityScanFailed\",\n \"securityFindingOpened\",\n \"securityFindingReviewed\",\n \"securityRemediationPlanCreated\",\n \"securityRemediationQueued\",\n \"appEvaluationQueued\",\n \"appEvaluationStarted\",\n \"appEvaluationCompleted\",\n \"appEvaluationFailed\",\n \"appEvaluationFindingOpened\",\n \"appEvaluationFindingReviewed\",\n \"appEvaluationPlanCreated\",\n \"appEvaluationImplementationQueued\",\n \"brainConsolidationStarted\",\n \"brainConsolidationCompleted\",\n \"brainConsolidationFailed\",\n \"brainConsolidationProposalCreated\",\n \"brainConsolidationProposalReviewed\",\n \"testProfileDetected\",\n \"testProfileUpdated\",\n \"testQualityScanQueued\",\n \"testQualityScanStarted\",\n \"testQualityScanCompleted\",\n \"testQualityScanFailed\",\n \"testQualityFindingOpened\",\n \"testQualityFindingReviewed\",\n \"testQualityPlanCreated\",\n \"implementationTestGateQueued\",\n \"implementationTestGateStarted\",\n \"implementationTestGatePassed\",\n \"implementationTestGateFailed\",\n \"implementationTestGateBlocked\",\n \"implementationTestGateOverride\",\n \"ciWorkflowRetired\",\n \"workRequeueRequested\",\n \"workRequeueQueued\",\n \"workRequeueBlocked\",\n \"implementationVerificationQueued\",\n \"implementationVerificationStarted\",\n \"implementationVerificationCompleted\",\n \"implementationVerificationBlocked\",\n \"implementationVerificationOverride\",\n \"projectContextRefreshQueued\",\n \"projectContextRefreshStarted\",\n \"projectContextRefreshCompleted\",\n \"projectContextRefreshFailed\",\n \"projectContextMissRecorded\",\n \"projectSystemDiagramGenerated\",\n \"projectSystemDiagramReviewed\",\n \"projectSystemDiagramMissRecorded\",\n \"handoffExported\"\n]);\n\nexport const activityEventActorSchema = z.enum([\"webUser\", \"runner\", \"cli\", \"system\"]);\n\nexport const activityEventStatusSchema = z.enum([\"info\", \"queued\", \"running\", \"completed\", \"failed\", \"blocked\", \"warning\"]);\n\nconst activityMetadataValueSchema = z.union([\n z.string().max(600),\n z.number(),\n z.boolean(),\n z.null(),\n z.array(z.string().max(200)).max(20)\n]);\n\nexport const activityMetadataSchema = z.record(z.string().min(1).max(80), activityMetadataValueSchema).default({});\n\nexport const generatedBrainArtifactSchema = z.object({\n documentType: documentTypeSchema,\n contentFormat: documentContentFormatSchema.default(\"markdown\"),\n title: z.string().trim().min(1),\n repoPath: z.string().trim().min(1),\n content: z.string().min(1)\n});\n\nexport const brainGenerationResultSchema = z.object({\n artifacts: z.array(generatedBrainArtifactSchema).min(1),\n summary: z.string().optional()\n});\n\nexport const sessionPolicySchema = z.union([z.enum([\"auto\", \"new\", \"none\"]), z.string().regex(/^continue:[A-Za-z0-9_.:-]+$/)]);\n\nexport const sessionDecisionSchema = z.enum([\"created\", \"continued\", \"forcedNew\", \"forcedContinue\", \"notSupported\", \"skipped\"]);\n\nexport const toolSessionStatusSchema = z.enum([\"open\", \"active\", \"closed\", \"archived\", \"blocked\", \"unavailable\"]);\n\nexport const sessionResumabilityScopeSchema = z.enum([\"none\", \"localMachine\", \"repository\", \"account\", \"providerCloud\"]);\n\nexport const runnerToolNames = [\"opencode\", \"claude\", \"codex\", \"copilot\", \"gemini\", \"aider\", \"cursor-agent\"] as const;\n\nexport const runnerToolNameSchema = z.enum(runnerToolNames);\n\nexport const runnerToolSelectionSchema = z.union([runnerToolNameSchema, z.literal(\"auto\")]);\n\nexport const runnerPreferenceScopeSchema = z.enum([\"account\", \"project\"]);\n\nexport const runnerPreferenceSourceSchema = z.enum([\"cli\", \"project\", \"account\", \"default\"]);\n\nexport const runnerPreferenceStatusSchema = z.enum([\"resolved\", \"unavailable\", \"modelUnsupported\", \"variantUnsupported\", \"reasoningUnsupported\", \"channelUnsupported\", \"custom\", \"none\"]);\n\nexport const runnerInvocationChannelSchema = z.enum([\"auto\", \"sdk\", \"command\"]);\n\nexport const runnerEffectiveInvocationChannelSchema = z.enum([\"sdk\", \"command\"]);\n\nexport const runnerReasoningEffortSchema = z.enum([\"auto\", \"low\", \"medium\", \"high\", \"xhigh\"]);\n\nexport const runnerProviderModelStatusSchema = z.enum([\"alpha\", \"beta\", \"deprecated\", \"active\"]);\n\nconst runnerProviderIdSchema = z.string().trim().min(1).max(120);\n\nconst runnerProviderModelIdSchema = z.string().trim().min(1).max(200);\n\nexport const runnerProviderModelLimitSchema = z.object({\n context: z.number().nonnegative().optional(),\n input: z.number().nonnegative().optional(),\n output: z.number().nonnegative().optional()\n}).strict();\n\nexport const runnerProviderModelModalitiesSchema = z.object({\n input: z.array(z.enum([\"text\", \"audio\", \"image\", \"video\", \"pdf\"])).max(12).optional(),\n output: z.array(z.enum([\"text\", \"audio\", \"image\", \"video\", \"pdf\"])).max(12).optional()\n}).strict();\n\nexport const runnerProviderModelVariantSchema = z.object({\n disabled: z.boolean().optional()\n}).strict();\n\nexport const runnerProviderModelSchema = z.object({\n id: runnerProviderModelIdSchema.optional(),\n name: z.string().trim().min(1).max(200).optional(),\n family: z.string().trim().min(1).max(120).optional(),\n releaseDate: z.string().trim().min(1).max(40).optional(),\n attachment: z.boolean().optional(),\n reasoning: z.boolean().optional(),\n temperature: z.boolean().optional(),\n toolCall: z.boolean().optional(),\n status: runnerProviderModelStatusSchema.optional(),\n limit: runnerProviderModelLimitSchema.optional(),\n modalities: runnerProviderModelModalitiesSchema.optional(),\n supportedReasoningEfforts: z.array(runnerReasoningEffortSchema).max(8).optional(),\n variants: z.record(z.string().trim().min(1).max(120), runnerProviderModelVariantSchema).optional()\n}).strict();\n\nexport const runnerProviderConfigSchema = z.object({\n id: runnerProviderIdSchema.optional(),\n name: z.string().trim().min(1).max(160).optional(),\n api: z.string().trim().min(1).max(80).optional(),\n models: z.record(runnerProviderModelIdSchema, runnerProviderModelSchema).default({})\n}).strict();\n\nexport const runnerProviderCatalogSchema = z.record(runnerProviderIdSchema, runnerProviderConfigSchema);\n\nexport const runnerToolModelPreferenceSchema = z.object({\n tool: runnerToolSelectionSchema.optional(),\n invocationChannel: runnerInvocationChannelSchema.optional(),\n model: z.string().trim().min(1).max(160).optional(),\n providerId: runnerProviderIdSchema.optional(),\n modelId: runnerProviderModelIdSchema.optional(),\n modelVariant: z.string().trim().min(1).max(120).optional(),\n reasoningEffort: runnerReasoningEffortSchema.optional()\n});\n\nexport const runnerToolCapabilitySchema = z.object({\n name: runnerToolNameSchema,\n description: z.string().min(1),\n available: z.boolean(),\n sdkAvailable: z.boolean(),\n commandAvailable: z.boolean(),\n execution: z.enum([\"sdk\", \"command\", \"unavailable\"]),\n supportsSessionReuse: z.boolean(),\n resumabilityScope: sessionResumabilityScopeSchema,\n supportsModelSelection: z.boolean(),\n providerCatalog: runnerProviderCatalogSchema.optional(),\n supportsBranchIsolation: z.boolean().optional(),\n supportsGitWorktreeIsolation: z.boolean().optional()\n});\n\nexport const runnerResourceUsageSchema = z.object({\n sampledAt: isoDateTimeSchema,\n processUptimeSeconds: z.number().nonnegative().optional(),\n processMemoryRssBytes: z.number().int().nonnegative().optional(),\n processMemoryHeapUsedBytes: z.number().int().nonnegative().optional(),\n processMemoryHeapTotalBytes: z.number().int().nonnegative().optional(),\n processCpuUserMicros: z.number().int().nonnegative().optional(),\n processCpuSystemMicros: z.number().int().nonnegative().optional(),\n processCpuPercent: z.number().nonnegative().optional(),\n systemMemoryTotalBytes: z.number().int().nonnegative().optional(),\n systemMemoryFreeBytes: z.number().int().nonnegative().optional(),\n systemLoadAverage1m: z.number().nonnegative().optional(),\n systemLoadAverage5m: z.number().nonnegative().optional(),\n systemLoadAverage15m: z.number().nonnegative().optional()\n});\n\nexport const runnerClaimLaneIdSchema = z.string().trim().min(1).max(80);\n\nexport const workIsolationModeSchema = z.enum([\"none\", \"primaryCheckout\", \"branch\", \"gitWorktree\"]);\n\nexport const repositoryLinkSourceSchema = z.enum([\"web\", \"cli\"]);\n\nexport const repositoryCloneStatusSchema = z.enum([\"notCloned\", \"cloned\", \"validated\", \"failed\"]);\n\nexport const repositoryBrainAutoSyncStatusSchema = z.enum([\"disabled\", \"enabledInactive\", \"active\", \"synced\", \"failed\", \"blocked\", \"conflicted\"]);\n\nexport const projectStatusSchema = z.enum([\"active\", \"archived\"]);\n\nexport const workspaceScopeKindSchema = z.enum([\"personal\", \"organization\"]);\n\nexport const personalWorkspaceScopeSchema = z.object({\n kind: z.literal(\"personal\"),\n accountId: z.string().min(1),\n userId: z.string().min(1),\n label: z.string().trim().min(1).default(\"Personal workspace\")\n});\n\nexport const organizationWorkspaceScopeSchema = z.object({\n kind: z.literal(\"organization\"),\n accountId: z.string().min(1),\n organizationId: z.string().min(1),\n userId: z.string().min(1).optional(),\n organizationSlug: z.string().trim().min(1).optional(),\n organizationRole: z.string().trim().min(1).optional(),\n label: z.string().trim().min(1).default(\"Organization workspace\")\n});\n\nexport const activeWorkspaceScopeSchema = z.discriminatedUnion(\"kind\", [personalWorkspaceScopeSchema, organizationWorkspaceScopeSchema]);\n\nexport const organizationWorkspaceOnboardingStatusSchema = z.enum([\"available\", \"upgradeRequired\", \"authRequired\", \"unconfigured\"]);\n\nexport const organizationWorkspaceOnboardingSchema = z.object({\n enabled: z.boolean(),\n canCreate: z.boolean(),\n status: organizationWorkspaceOnboardingStatusSchema,\n reason: z.string().trim().min(1).optional()\n});\n\nexport const baseItemSchema = z.object({\n id: z.string().min(1),\n type: itemTypeSchema,\n schemaVersion: z.number().int().positive().default(1),\n accountId: z.string().min(1),\n projectId: z.string().min(1).optional(),\n createdAt: isoDateTimeSchema,\n updatedAt: isoDateTimeSchema\n});\n\nexport const accountItemSchema = baseItemSchema.extend({\n type: z.literal(\"account\"),\n name: z.string().min(1),\n slug: z.string().min(1)\n});\n\nexport const userItemSchema = baseItemSchema.extend({\n type: z.literal(\"user\"),\n userId: z.string().min(1),\n email: z.string().email(),\n firstName: z.string(),\n lastName: z.string()\n});\n\nexport const projectItemSchema = baseItemSchema.extend({\n type: z.literal(\"project\"),\n projectId: z.string().min(1),\n name: z.string().min(1),\n slug: z.string().min(1),\n description: z.string().optional(),\n artifactFormatPreference: artifactFormatPreferenceSchema.optional(),\n status: projectStatusSchema.default(\"active\"),\n archivedAt: isoDateTimeSchema.optional(),\n archivedByUserId: z.string().min(1).optional(),\n archiveReason: z.string().min(1).optional(),\n transferredFromAccountId: z.string().min(1).optional(),\n transferredFromProjectId: z.string().min(1).optional(),\n transferredByUserId: z.string().min(1).optional(),\n transferredAt: isoDateTimeSchema.optional()\n});\n\nexport const repositoryLinkItemSchema = baseItemSchema.extend({\n type: z.literal(\"repositoryLink\"),\n projectId: z.string().min(1),\n repositoryLinkId: z.string().min(1),\n repoName: z.string().min(1),\n repoFingerprint: z.string().min(1).optional(),\n defaultBranch: z.string().min(1),\n cloneUrl: z.string().min(1).optional(),\n provider: z.string().min(1).optional(),\n repoOwner: z.string().min(1).optional(),\n repoFullName: z.string().min(1).optional(),\n linkedByUserId: z.string().min(1).optional(),\n linkSource: repositoryLinkSourceSchema.optional(),\n cloneStatus: repositoryCloneStatusSchema.optional(),\n autoSyncEnabled: z.boolean().optional(),\n appEvaluationEnabled: z.boolean().optional(),\n testQualityEnabled: z.boolean().optional(),\n autopilotMode: autopilotModeSchema.optional(),\n autopilotPolicyVersion: z.string().trim().min(1).max(80).optional(),\n autopilotSafeWorkKinds: z.array(workKindSchema).optional(),\n autopilotAllowedCandidateTypes: z.array(autopilotCandidateTypeSchema).optional(),\n autopilotMaxRiskLevel: impactRiskLevelSchema.optional(),\n autopilotRunnerId: z.string().min(1).optional(),\n autopilotPausedReason: z.string().trim().min(1).max(600).optional(),\n autopilotDailyWorkLimit: z.number().int().positive().max(100).optional(),\n autopilotDailyPrLimit: z.number().int().nonnegative().max(100).optional(),\n autopilotConcurrentWorkLimit: z.number().int().positive().max(20).optional(),\n autopilotRunnerMinuteBudget: z.number().int().nonnegative().max(1440).optional(),\n autopilotFailureBudget: z.number().int().nonnegative().max(50).optional(),\n autopilotExpiresAt: isoDateTimeSchema.optional(),\n autopilotReviewAfter: isoDateTimeSchema.optional(),\n autopilotCooldownUntil: isoDateTimeSchema.optional(),\n autopilotBudgetWindows: z.array(autopilotBudgetWindowSchema).max(10).optional(),\n autopilotUpdatedByUserId: z.string().min(1).optional(),\n autopilotUpdatedAt: isoDateTimeSchema.optional(),\n lastValidatedAt: isoDateTimeSchema.optional(),\n status: z.enum([\"active\", \"revoked\"]).default(\"active\")\n});\n\nexport const brainDocumentItemSchema = baseItemSchema.extend({\n type: z.literal(\"brainDocument\"),\n projectId: z.string().min(1),\n documentId: z.string().min(1),\n documentType: documentTypeSchema,\n contentFormat: documentContentFormatSchema.default(\"markdown\"),\n title: z.string().min(1),\n status: z.string().min(1),\n repoPath: z.string().min(1),\n content: z.string(),\n contentHash: z.string().min(1),\n frontmatter: z.record(z.string(), z.unknown()).default({}),\n revision: z.number().int().nonnegative(),\n approvedRevision: z.number().int().nonnegative().optional(),\n source: sourceSchema,\n syncState: syncStateSchema\n});\n\nexport const brainConsolidationScanItemSchema = baseItemSchema.extend({\n type: z.literal(\"brainConsolidationScan\"),\n projectId: z.string().min(1),\n brainConsolidationScanId: z.string().min(1),\n source: brainConsolidationScanSourceSchema,\n status: brainConsolidationScanStatusSchema,\n workItemId: z.string().min(1).optional(),\n repositoryLinkId: z.string().min(1).optional(),\n runnerId: z.string().min(1).optional(),\n activeReviewCount: z.number().int().nonnegative(),\n exactDuplicateGroupCount: z.number().int().nonnegative(),\n autoArchivedCount: z.number().int().nonnegative(),\n proposalCount: z.number().int().nonnegative(),\n skippedCount: z.number().int().nonnegative(),\n residualReviewCount: z.number().int().nonnegative(),\n summary: z.string().trim().min(1).max(800),\n startedAt: isoDateTimeSchema,\n completedAt: isoDateTimeSchema.optional(),\n error: z.string().trim().min(1).max(800).optional()\n});\n\nexport const brainConsolidationProposalItemSchema = baseItemSchema.extend({\n type: z.literal(\"brainConsolidationProposal\"),\n projectId: z.string().min(1),\n brainConsolidationProposalId: z.string().min(1),\n brainConsolidationScanId: z.string().min(1).optional(),\n status: brainConsolidationProposalStatusSchema,\n action: brainConsolidationProposalActionSchema,\n riskLevel: brainConsolidationRiskLevelSchema,\n canonicalDocumentId: z.string().min(1),\n candidateDocumentIds: z.array(z.string().min(1)).min(1).max(50),\n evidence: z.array(z.string().trim().min(1).max(300)).min(1).max(20),\n reason: z.string().trim().min(1).max(800),\n reviewedByUserId: z.string().min(1).optional(),\n reviewedAt: isoDateTimeSchema.optional()\n});\n\nexport const brainConsolidationRecommendationSchema = z.object({\n recommendationId: z.string().trim().min(1).max(160).optional(),\n canonicalDocumentId: z.string().min(1),\n candidateDocumentIds: z.array(z.string().min(1)).min(1).max(25),\n coverage: brainConsolidationRecommendationCoverageSchema,\n confidence: brainConsolidationRecommendationConfidenceSchema.default(\"medium\"),\n recommendedAction: brainConsolidationRecommendationActionSchema,\n riskLevel: brainConsolidationRiskLevelSchema.default(\"medium\"),\n evidence: z.array(z.string().trim().min(1).max(300)).min(1).max(10),\n reason: z.string().trim().min(1).max(800)\n});\n\nexport const brainConsolidationScanResultSchema = z.object({\n summary: z.string().trim().min(1).max(2000),\n recommendations: z.array(brainConsolidationRecommendationSchema).max(100).default([]),\n warnings: z.array(z.string().trim().min(1).max(600)).default([])\n});\n\nexport const generatedDraftItemSchema = baseItemSchema.extend({\n type: z.literal(\"generatedDraft\"),\n projectId: z.string().min(1),\n wishId: z.string().min(1),\n title: z.string().min(1),\n status: generatedDraftStatusSchema,\n documentIds: z.array(z.string()).default([]),\n wish: z.string().min(1).optional(),\n requestedByUserId: z.string().min(1).optional(),\n workItemId: z.string().min(1).optional(),\n runnerId: z.string().min(1).optional(),\n generationAttempt: z.number().int().nonnegative().optional(),\n lastGenerationError: z.string().optional()\n});\n\nexport const syncCursorItemSchema = baseItemSchema.extend({\n type: z.literal(\"syncCursor\"),\n projectId: z.string().min(1),\n repositoryLinkId: z.string().min(1),\n lastSyncedRevision: z.number().int().nonnegative(),\n lastSyncedAt: isoDateTimeSchema.optional()\n});\n\nexport const syncConflictItemSchema = baseItemSchema.extend({\n type: z.literal(\"syncConflict\"),\n projectId: z.string().min(1),\n conflictId: z.string().min(1),\n documentId: z.string().min(1),\n repoPath: z.string().min(1),\n webRevision: z.number().int().nonnegative(),\n repoContentHash: z.string().min(1),\n status: z.enum([\"open\", \"resolved\", \"ignored\"])\n});\n\nexport const workItemSchema = baseItemSchema.extend({\n type: z.literal(\"workItem\"),\n projectId: z.string().min(1),\n workItemId: z.string().min(1),\n workKind: workKindSchema.optional(),\n status: workStatusSchema,\n executionMode: executionModeSchema.optional(),\n title: z.string().min(1),\n requestedBy: z.string().min(1),\n requestedByUserId: z.string().min(1).optional(),\n approvedBy: z.string().min(1).optional(),\n approvedByUserId: z.string().min(1).optional(),\n sourceWish: z.string().min(1).optional(),\n generatedDraftId: z.string().min(1).optional(),\n issueId: z.string().min(1).optional(),\n securityScanId: z.string().min(1).optional(),\n securityFindingId: z.string().min(1).optional(),\n appEvaluationScanId: z.string().min(1).optional(),\n appEvaluationFindingId: z.string().min(1).optional(),\n brainConsolidationScanId: z.string().min(1).optional(),\n implementationVerificationId: z.string().min(1).optional(),\n testQualityScanId: z.string().min(1).optional(),\n testQualityFindingId: z.string().min(1).optional(),\n implementationTestGateId: z.string().min(1).optional(),\n projectContextRefreshId: z.string().min(1).optional(),\n contextMissId: z.string().min(1).optional(),\n sourceWorkItemId: z.string().min(1).optional(),\n requeueReason: z.string().trim().min(1).max(600).optional(),\n requeuedByUserId: z.string().min(1).optional(),\n requeuedAt: isoDateTimeSchema.optional(),\n sourceAttempt: z.number().int().nonnegative().optional(),\n sourceTerminalStatus: workStatusSchema.optional(),\n sourceFailureSummary: z.string().trim().min(1).max(1000).optional(),\n implementationProofStatus: implementationProofStatusSchema.optional(),\n implementationVerificationOutcome: implementationVerificationOutcomeSchema.optional(),\n implementationVerificationResultId: z.string().min(1).optional(),\n humanImplementationOverrideReason: z.string().trim().min(1).max(1000).optional(),\n repositoryLinkId: z.string().min(1).optional(),\n reviewThreadId: z.string().min(1).optional(),\n reviewDocumentId: z.string().min(1).optional(),\n reviewDocumentRevision: z.number().int().nonnegative().optional(),\n reviewMessageId: z.string().min(1).optional(),\n assistantMessageId: z.string().min(1).optional(),\n assistantQuestionMode: assistantQuestionModeSchema.optional(),\n artifactFormatPreference: artifactFormatPreferenceSchema.optional(),\n impactReportId: z.string().min(1).optional(),\n impactDocumentId: z.string().min(1).optional(),\n impactDocumentRevision: z.number().int().nonnegative().optional(),\n claimedByRunnerId: z.string().optional(),\n pairedByUserId: z.string().min(1).optional(),\n machineId: z.string().min(1).optional(),\n claimLaneId: runnerClaimLaneIdSchema.optional(),\n claimLeaseId: z.string().min(1).optional(),\n claimAttempt: z.number().int().nonnegative().optional(),\n leaseExpiresAt: isoDateTimeSchema.optional(),\n controllingAdrId: z.string().min(1).optional(),\n implementationScopeId: z.string().min(1).optional(),\n executionBranch: z.string().min(1).optional(),\n executionWorktreeKey: z.string().min(1).optional(),\n isolationMode: workIsolationModeSchema.optional(),\n repositoryLockId: z.string().min(1).optional(),\n baseRevision: z.string().min(1).optional(),\n baseContentHash: z.string().min(1).optional(),\n blockerReason: z.string().min(1).optional(),\n attempt: z.number().int().nonnegative().default(0),\n idempotencyKey: z.string().min(1),\n sessionPolicy: sessionPolicySchema.optional(),\n sessionGroupKey: z.string().min(1).optional(),\n toolSessionId: z.string().min(1).optional(),\n sessionDecision: sessionDecisionSchema.optional(),\n sessionDecisionReason: z.string().min(1).optional(),\n implementationHandoff: implementationHandoffSchema.optional(),\n autopilotAuthorization: autopilotAuthorizationSchema.optional(),\n autopilotAuthorizationId: z.string().min(1).optional(),\n autopilotCandidateId: z.string().min(1).optional(),\n autopilotCandidateType: autopilotCandidateTypeSchema.optional(),\n autopilotClassificationOutcome: autopilotClassificationOutcomeSchema.optional(),\n autopilotPolicyVersion: z.string().trim().min(1).max(80).optional(),\n lastStatusMessage: z.string().optional(),\n lastStatusAt: isoDateTimeSchema\n});\n\nexport const runnerHeartbeatItemSchema = baseItemSchema.extend({\n type: z.literal(\"runnerHeartbeat\"),\n projectId: z.string().min(1),\n runnerId: z.string().min(1),\n repositoryLinkId: z.string().min(1),\n status: z.enum([\"online\", \"offline\", \"running\", \"blocked\", \"removed\"]),\n workspaceId: z.string().min(1).optional(),\n pairedByUserId: z.string().min(1).optional(),\n machineId: z.string().min(1).optional(),\n version: z.string().optional(),\n mode: z.enum([\"foreground\", \"background\"]).optional(),\n hostname: z.string().min(1).optional(),\n runnerName: z.string().min(1).optional(),\n supportedWorkKinds: z.array(workKindSchema).optional(),\n supportsBranchIsolation: z.boolean().optional(),\n supportsGitWorktreeIsolation: z.boolean().optional(),\n maxConcurrentWork: z.number().int().min(1).max(4).optional(),\n activeClaimLaneIds: z.array(runnerClaimLaneIdSchema).max(4).optional(),\n currentWorkItemId: z.string().min(1).optional(),\n currentImplementationScopeId: z.string().min(1).optional(),\n currentWorktreeKey: z.string().min(1).optional(),\n currentBranch: z.string().min(1).optional(),\n capabilities: z.array(runnerToolCapabilitySchema).optional(),\n requestedTool: runnerToolSelectionSchema.optional(),\n requestedInvocationChannel: runnerInvocationChannelSchema.optional(),\n requestedProviderId: runnerProviderIdSchema.optional(),\n requestedModelId: runnerProviderModelIdSchema.optional(),\n requestedModelVariant: z.string().trim().min(1).max(120).optional(),\n requestedReasoningEffort: runnerReasoningEffortSchema.optional(),\n effectiveTool: z.union([runnerToolNameSchema, z.literal(\"custom\")]).optional(),\n effectiveInvocationChannel: runnerEffectiveInvocationChannelSchema.optional(),\n effectiveModel: z.string().min(1).optional(),\n effectiveProviderId: runnerProviderIdSchema.optional(),\n effectiveModelId: runnerProviderModelIdSchema.optional(),\n effectiveModelVariant: z.string().trim().min(1).max(120).optional(),\n effectiveReasoningEffort: runnerReasoningEffortSchema.optional(),\n preferenceSource: runnerPreferenceSourceSchema.optional(),\n preferenceStatus: runnerPreferenceStatusSchema.optional(),\n preferenceMessage: z.string().optional(),\n resourceUsage: runnerResourceUsageSchema.optional(),\n autoSyncStatus: repositoryBrainAutoSyncStatusSchema.optional(),\n autoSyncMessage: z.string().max(400).optional(),\n autoSyncLastStartedAt: isoDateTimeSchema.optional(),\n autoSyncLastSuccessAt: isoDateTimeSchema.optional(),\n autoSyncLastFailureAt: isoDateTimeSchema.optional(),\n autoSyncPushedCount: z.number().int().nonnegative().optional(),\n autoSyncSkippedCount: z.number().int().nonnegative().optional(),\n autoSyncConflictCount: z.number().int().nonnegative().optional(),\n lastSeenAt: isoDateTimeSchema\n});\n\nexport const runnerSettingsItemSchema = baseItemSchema.extend({\n type: z.literal(\"accountSettings\"),\n projectId: z.string().min(1),\n settingsType: z.literal(\"runnerPreferences\"),\n scope: runnerPreferenceScopeSchema,\n preferences: runnerToolModelPreferenceSchema\n});\n\nexport const runnerExecutionLogItemSchema = baseItemSchema.extend({\n type: z.literal(\"runnerExecutionLog\"),\n projectId: z.string().min(1),\n runnerLogId: z.string().min(1),\n runnerId: z.string().min(1),\n workKind: workKindSchema.optional(),\n workItemId: z.string().min(1).optional(),\n workTitle: z.string().min(1).optional(),\n initiatedBy: z.string().min(1).optional(),\n approvedBy: z.string().min(1).optional(),\n repositoryLinkId: z.string().min(1).optional(),\n pairedByUserId: z.string().min(1).optional(),\n machineId: z.string().min(1).optional(),\n controllingAdrId: z.string().min(1).optional(),\n implementationScopeId: z.string().min(1).optional(),\n executionBranch: z.string().min(1).optional(),\n executionWorktreeKey: z.string().min(1).optional(),\n isolationMode: workIsolationModeSchema.optional(),\n repositoryLockId: z.string().min(1).optional(),\n claimLaneId: runnerClaimLaneIdSchema.optional(),\n claimLeaseId: z.string().min(1).optional(),\n status: z.enum([\"claimed\", \"running\", \"completed\", \"failed\", \"blocked\", \"idle\"]),\n executionMode: executionModeSchema.optional(),\n tool: z.string().min(1).optional(),\n model: z.string().min(1).optional(),\n attempt: z.number().int().nonnegative().optional(),\n startedAt: isoDateTimeSchema.optional(),\n endedAt: isoDateTimeSchema.optional(),\n durationMs: z.number().int().nonnegative().optional(),\n costUsd: z.number().nonnegative().optional(),\n tokensIn: z.number().int().nonnegative().optional(),\n tokensOut: z.number().int().nonnegative().optional(),\n sessionPolicy: sessionPolicySchema.optional(),\n sessionGroupKey: z.string().min(1).optional(),\n toolSessionId: z.string().min(1).optional(),\n sessionDecision: sessionDecisionSchema.optional(),\n sessionDecisionReason: z.string().min(1).optional(),\n implementationHandoff: implementationHandoffSchema.optional(),\n message: z.string().optional(),\n error: z.string().optional()\n});\n\nexport const runnerCredentialItemSchema = baseItemSchema.extend({\n type: z.literal(\"runnerCredential\"),\n projectId: z.string().min(1),\n runnerCredentialId: z.string().min(1),\n repositoryLinkId: z.string().min(1),\n runnerId: z.string().min(1).optional(),\n pairedByUserId: z.string().min(1).optional(),\n machineId: z.string().min(1).optional(),\n tokenHash: z.string().min(32),\n issuedAt: isoDateTimeSchema,\n lastUsedAt: isoDateTimeSchema.optional(),\n status: z.enum([\"active\", \"revoked\"]).default(\"active\")\n});\n\nexport const runnerCommandKindSchema = z.enum([\"update\", \"restart\", \"remove\", \"implementationHandoffRecovery\"]);\n\nexport const runnerCommandStatusSchema = z.enum([\"pending\", \"acknowledged\", \"running\", \"completed\", \"failed\", \"expired\", \"cancelled\"]);\n\nexport const runnerCommandItemSchema = baseItemSchema.extend({\n type: z.literal(\"runnerCommand\"),\n projectId: z.string().min(1),\n commandId: z.string().min(1),\n commandKind: runnerCommandKindSchema,\n status: runnerCommandStatusSchema,\n runnerId: z.string().min(1),\n repositoryLinkId: z.string().min(1),\n workItemId: z.string().min(1).optional(),\n handoffRecoveryAction: implementationHandoffRecoveryActionSchema.optional(),\n executionBranch: z.string().min(1).optional(),\n executionWorktreeKey: z.string().min(1).optional(),\n requestedByUserId: z.string().min(1),\n idempotencyKey: z.string().min(1),\n lastStatusIdempotencyKey: z.string().min(1).optional(),\n expiresAt: isoDateTimeSchema,\n acknowledgedAt: isoDateTimeSchema.optional(),\n startedAt: isoDateTimeSchema.optional(),\n completedAt: isoDateTimeSchema.optional(),\n cancelledAt: isoDateTimeSchema.optional(),\n message: z.string().optional(),\n error: z.string().optional()\n});\n\nexport const planReviewMessageRoleSchema = z.enum([\"user\", \"assistant\", \"system\"]);\n\nexport const planReviewMessageIntentSchema = z.enum([\"ask\", \"revisionRequest\", \"revisionResult\"]);\n\nexport const planReviewMessageStatusSchema = z.enum([\"posted\", \"queued\", \"running\", \"completed\", \"failed\"]);\n\nexport const planReviewMessageItemSchema = baseItemSchema.extend({\n type: z.literal(\"planReviewMessage\"),\n projectId: z.string().min(1),\n messageId: z.string().min(1),\n threadId: z.string().min(1),\n generatedDraftId: z.string().min(1),\n documentId: z.string().min(1),\n documentRevision: z.number().int().nonnegative(),\n role: planReviewMessageRoleSchema,\n intent: planReviewMessageIntentSchema,\n status: planReviewMessageStatusSchema,\n content: z.string().min(1),\n workItemId: z.string().min(1).optional(),\n responseToMessageId: z.string().min(1).optional(),\n createdByUserId: z.string().min(1).optional(),\n runnerId: z.string().min(1).optional()\n});\n\nexport const assistantMessageRoleSchema = z.enum([\"user\", \"assistant\", \"system\"]);\n\nexport const assistantMessageStatusSchema = z.enum([\"posted\", \"queued\", \"running\", \"completed\", \"failed\"]);\n\nexport const assistantSourceBoundarySchema = z.enum([\"projectBrain\", \"localSource\", \"runnerState\", \"mixed\"]);\n\nexport const assistantCitationSchema = z.object({\n source: assistantSourceBoundarySchema,\n documentId: z.string().min(1).optional(),\n title: z.string().min(1).optional(),\n repoPath: z.string().min(1).optional(),\n documentRevision: z.number().int().nonnegative().optional(),\n excerpt: z.string().max(600).optional()\n});\n\nexport const assistantMessageItemSchema = baseItemSchema.extend({\n type: z.literal(\"assistantMessage\"),\n projectId: z.string().min(1),\n messageId: z.string().min(1),\n threadId: z.string().min(1),\n role: assistantMessageRoleSchema,\n status: assistantMessageStatusSchema,\n content: z.string().min(1),\n questionMode: assistantQuestionModeSchema.optional(),\n sourceBoundary: assistantSourceBoundarySchema.optional(),\n citations: z.array(assistantCitationSchema).default([]),\n relatedDocumentIds: z.array(z.string().min(1)).default([]),\n workItemId: z.string().min(1).optional(),\n responseToMessageId: z.string().min(1).optional(),\n createdByUserId: z.string().min(1).optional(),\n runnerId: z.string().min(1).optional(),\n repositoryLinkId: z.string().min(1).optional(),\n repoFingerprint: z.string().min(1).optional(),\n answeredAt: isoDateTimeSchema.optional(),\n error: z.string().optional()\n});\n\nexport const assistantAnswerResultSchema = z.object({\n answer: z.string().trim().min(1),\n sourceBoundary: assistantSourceBoundarySchema.default(\"localSource\"),\n citations: z.array(assistantCitationSchema).default([]),\n summary: z.string().optional()\n});\n\nexport const knowledgeSearchScopeSchema = z.enum([\"project\", \"organization\"]);\n\nexport const knowledgeSourceTypeSchema = z.enum([\"brainDocument\", \"generatedArtifact\", \"runnerSummary\", \"knowledgeEntity\", \"knowledgeRelation\", \"projectContextMap\", \"projectContextSlice\", \"projectSystemDiagram\", \"projectSystemDiagramNode\", \"projectSystemDiagramEdge\"]);\n\nexport const knowledgeChunkStatusSchema = z.enum([\"approved\", \"synced\", \"stale\"]);\n\nexport const knowledgeEntityTypeSchema = z.enum([\"project\", \"system\", \"component\", \"domain\", \"tool\", \"decision\", \"feature\", \"risk\", \"team\", \"workflow\", \"unknown\"]);\n\nexport const knowledgeRelationTypeSchema = z.enum([\"uses\", \"depends_on\", \"decides\", \"supersedes\", \"touches\", \"blocks\", \"implements\", \"mentions\"]);\n\nexport const knowledgeIndexFreshnessSchema = z.object({\n status: z.enum([\"disabled\", \"fresh\", \"stale\", \"indexing\", \"degraded\"]),\n indexedAt: isoDateTimeSchema.optional(),\n staleReason: z.string().trim().min(1).optional(),\n failedChunkCount: z.number().int().nonnegative().default(0),\n indexedChunkCount: z.number().int().nonnegative().default(0)\n});\n\nexport const knowledgeSearchChunkSchema = z.object({\n chunkId: z.string().min(1),\n accountId: z.string().min(1),\n projectId: z.string().min(1),\n sourceType: knowledgeSourceTypeSchema.default(\"brainDocument\"),\n documentId: z.string().min(1),\n documentType: documentTypeSchema,\n title: z.string().min(1),\n repoPath: z.string().min(1),\n revision: z.number().int().nonnegative(),\n sectionHeading: z.string().trim().min(1).optional(),\n chunkText: z.string().trim().min(1).max(12000),\n chunkHash: z.string().min(1),\n contentHash: z.string().min(1),\n sourceBoundary: assistantSourceBoundarySchema.default(\"projectBrain\"),\n status: knowledgeChunkStatusSchema,\n embeddingModel: z.string().trim().min(1).optional(),\n embedding: z.array(z.number()).max(8192).optional(),\n indexedAt: isoDateTimeSchema.optional(),\n createdAt: isoDateTimeSchema,\n updatedAt: isoDateTimeSchema\n});\n\nexport const knowledgeEntitySchema = z.object({\n entityId: z.string().min(1),\n accountId: z.string().min(1),\n projectIds: z.array(z.string().min(1)).min(1),\n name: z.string().trim().min(1).max(200),\n entityType: knowledgeEntityTypeSchema,\n aliases: z.array(z.string().trim().min(1).max(200)).default([]),\n description: z.string().trim().min(1).max(1200).optional(),\n sourceDocumentIds: z.array(z.string().min(1)).default([]),\n confidence: z.number().min(0).max(1).default(0.6),\n createdAt: isoDateTimeSchema,\n updatedAt: isoDateTimeSchema\n});\n\nexport const knowledgeRelationEndpointSchema = z.object({\n entityId: z.string().min(1),\n name: z.string().trim().min(1).max(200),\n entityType: knowledgeEntityTypeSchema.default(\"unknown\")\n});\n\nexport const knowledgeRelationSchema = z.object({\n relationId: z.string().min(1),\n accountId: z.string().min(1),\n projectIds: z.array(z.string().min(1)).min(1),\n relationType: knowledgeRelationTypeSchema,\n from: knowledgeRelationEndpointSchema,\n to: knowledgeRelationEndpointSchema,\n summary: z.string().trim().min(1).max(1200),\n citations: z.array(assistantCitationSchema).default([]),\n confidence: z.number().min(0).max(1).default(0.6),\n createdAt: isoDateTimeSchema,\n updatedAt: isoDateTimeSchema\n});\n\nexport const knowledgeSearchRequestSchema = z.object({\n query: z.string().trim().min(1).max(2000),\n scope: knowledgeSearchScopeSchema.default(\"project\"),\n projectIds: z.array(z.string().min(1)).max(100).optional(),\n topK: z.number().int().min(1).max(20).default(6),\n includeRelations: z.boolean().default(true),\n useSemanticRanking: z.boolean().default(false)\n});\n\nexport const knowledgeSearchResultSchema = z.object({\n chunkId: z.string().min(1),\n accountId: z.string().min(1),\n projectId: z.string().min(1),\n documentId: z.string().min(1),\n documentType: documentTypeSchema,\n title: z.string().min(1),\n repoPath: z.string().min(1),\n revision: z.number().int().nonnegative(),\n sectionHeading: z.string().trim().min(1).optional(),\n excerpt: z.string().trim().min(1).max(1200),\n sourceBoundary: assistantSourceBoundarySchema.default(\"projectBrain\"),\n score: z.number().optional(),\n citation: assistantCitationSchema\n});\n\nexport const knowledgeSearchResponseSchema = z.object({\n query: z.string().trim().min(1),\n scope: knowledgeSearchScopeSchema,\n results: z.array(knowledgeSearchResultSchema).default([]),\n relations: z.array(knowledgeRelationSchema).default([]),\n freshness: knowledgeIndexFreshnessSchema,\n degradedReason: z.string().trim().min(1).optional()\n});\n\nexport const knowledgeDiagramFormatSchema = z.enum([\"mermaid\"]);\n\nexport const knowledgeDiagramRequestSchema = knowledgeSearchRequestSchema.extend({\n format: knowledgeDiagramFormatSchema.default(\"mermaid\"),\n saveAsDocument: z.boolean().default(false),\n title: z.string().trim().min(1).max(160).optional()\n});\n\nexport const knowledgeDiagramResultSchema = z.object({\n diagramId: z.string().min(1),\n title: z.string().trim().min(1).max(160),\n format: knowledgeDiagramFormatSchema,\n content: z.string().trim().min(1),\n citations: z.array(assistantCitationSchema).default([]),\n sourceResultIds: z.array(z.string().min(1)).default([]),\n documentId: z.string().min(1).optional(),\n freshness: knowledgeIndexFreshnessSchema,\n warnings: z.array(z.string().trim().min(1).max(600)).default([])\n});\n\nexport const projectContextSliceKindSchema = z.enum([\"overview\", \"architecture\", \"domain\", \"data\", \"api\", \"frontend\", \"backend\", \"cli\", \"workflow\", \"operations\", \"security\", \"testing\", \"unknown\"]);\n\nexport const projectContextFreshnessSchema = z.enum([\"fresh\", \"stale\", \"partial\", \"missing\"]);\n\nexport const projectContextMapStatusSchema = z.enum([\"draft\", \"proposed\", \"approved\", \"stale\", \"archived\"]);\n\nexport const projectContextRefreshStatusSchema = z.enum([\"queued\", \"running\", \"completed\", \"failed\", \"skipped\"]);\n\nexport const contextMissStatusSchema = z.enum([\"open\", \"resolved\", \"dismissed\"]);\n\nexport const projectContextRepoPathSchema = safeRepoPathSchema;\n\nexport const projectContextCitationSchema = assistantCitationSchema.extend({\n repoPath: projectContextRepoPathSchema.optional()\n});\n\nexport const projectContextCoverageSchema = z.object({\n status: projectContextFreshnessSchema.default(\"missing\"),\n sliceCount: z.number().int().nonnegative().default(0),\n staleSliceCount: z.number().int().nonnegative().default(0),\n missingAreas: z.array(z.string().trim().min(1).max(160)).default([]),\n warnings: z.array(z.string().trim().min(1).max(300)).default([])\n});\n\nconst defaultProjectContextCoverage = { status: \"missing\" as const, sliceCount: 0, staleSliceCount: 0, missingAreas: [], warnings: [] };\n\nexport const projectContextSliceSchema = z.object({\n sliceId: z.string().trim().min(1).max(160),\n kind: projectContextSliceKindSchema.default(\"unknown\"),\n title: z.string().trim().min(1).max(200),\n summary: z.string().trim().min(1).max(4000),\n repoPaths: z.array(projectContextRepoPathSchema).max(80).default([]),\n ownerHints: z.array(z.string().trim().min(1).max(160)).max(20).default([]),\n tags: z.array(z.string().trim().min(1).max(80)).max(30).default([]),\n citations: z.array(projectContextCitationSchema).default([]),\n dependsOn: z.array(z.string().trim().min(1).max(160)).max(50).default([]),\n freshness: projectContextFreshnessSchema.default(\"fresh\"),\n confidence: z.number().min(0).max(1).default(0.6),\n contentHash: z.string().trim().min(1).max(160).optional(),\n lastVerifiedAt: isoDateTimeSchema.optional()\n});\n\nexport const projectContextEntitySchema = z.object({\n entityId: z.string().trim().min(1).max(200),\n name: z.string().trim().min(1).max(200),\n entityType: knowledgeEntityTypeSchema.default(\"unknown\"),\n summary: z.string().trim().min(1).max(1200).optional(),\n aliases: z.array(z.string().trim().min(1).max(200)).default([]),\n sliceIds: z.array(z.string().trim().min(1).max(160)).default([]),\n citations: z.array(projectContextCitationSchema).default([]),\n confidence: z.number().min(0).max(1).default(0.6)\n});\n\nexport const projectContextRelationSchema = z.object({\n relationId: z.string().trim().min(1).max(200),\n relationType: knowledgeRelationTypeSchema.default(\"mentions\"),\n fromId: z.string().trim().min(1).max(200),\n toId: z.string().trim().min(1).max(200),\n summary: z.string().trim().min(1).max(1200),\n citations: z.array(projectContextCitationSchema).default([]),\n confidence: z.number().min(0).max(1).default(0.6)\n});\n\nexport const projectSystemDiagramStatusSchema = z.enum([\"draft\", \"proposed\", \"approved\", \"stale\", \"archived\"]);\n\nexport const projectSystemDiagramViewKindSchema = z.enum([\"wholeSystem\", \"projectBrainLifecycle\", \"contextRefresh\", \"runtimeTopology\", \"featureFlow\"]);\n\nexport const projectSystemDiagramNodeKindSchema = z.enum([\"actor\", \"app\", \"api\", \"cli\", \"runner\", \"dataStore\", \"searchIndex\", \"authBoundary\", \"repository\", \"externalService\", \"workflow\", \"component\", \"unknown\"]);\n\nexport const projectSystemDiagramGroupKindSchema = z.enum([\"boundary\", \"lane\", \"group\"]);\n\nexport const projectSystemDiagramDirectionSchema = z.enum([\"TD\", \"LR\"]);\n\nexport const projectSystemDiagramNodeSchema = z.object({\n nodeId: z.string().trim().min(1).max(200),\n label: z.string().trim().min(1).max(120),\n kind: projectSystemDiagramNodeKindSchema.default(\"unknown\"),\n summary: z.string().trim().min(1).max(1200).optional(),\n groupId: z.string().trim().min(1).max(160).optional(),\n lane: z.string().trim().min(1).max(120).optional(),\n sliceIds: z.array(z.string().trim().min(1).max(160)).default([]),\n entityIds: z.array(z.string().trim().min(1).max(200)).default([]),\n citations: z.array(projectContextCitationSchema).min(1),\n confidence: z.number().min(0).max(1).default(0.6),\n freshness: projectContextFreshnessSchema.default(\"fresh\")\n});\n\nexport const projectSystemDiagramEdgeSchema = z.object({\n edgeId: z.string().trim().min(1).max(220),\n fromNodeId: z.string().trim().min(1).max(200),\n toNodeId: z.string().trim().min(1).max(200),\n relationType: knowledgeRelationTypeSchema.default(\"mentions\"),\n label: z.string().trim().min(1).max(120).optional(),\n summary: z.string().trim().min(1).max(1200),\n citations: z.array(projectContextCitationSchema).min(1),\n confidence: z.number().min(0).max(1).default(0.6),\n freshness: projectContextFreshnessSchema.default(\"fresh\")\n});\n\nexport const projectSystemDiagramGroupSchema = z.object({\n groupId: z.string().trim().min(1).max(160),\n label: z.string().trim().min(1).max(120),\n kind: projectSystemDiagramGroupKindSchema.default(\"group\"),\n summary: z.string().trim().min(1).max(1200).optional(),\n citations: z.array(projectContextCitationSchema).default([])\n});\n\nexport const projectSystemDiagramViewSchema = z.object({\n viewId: z.string().trim().min(1).max(160),\n kind: projectSystemDiagramViewKindSchema,\n title: z.string().trim().min(1).max(160),\n summary: z.string().trim().min(1).max(1200),\n nodeIds: z.array(z.string().trim().min(1).max(200)).min(1),\n edgeIds: z.array(z.string().trim().min(1).max(220)).default([]),\n groupIds: z.array(z.string().trim().min(1).max(160)).default([]),\n mermaid: z.string().trim().min(1).max(12000),\n warnings: z.array(z.string().trim().min(1).max(600)).default([]),\n freshness: projectContextFreshnessSchema.default(\"fresh\")\n});\n\nexport const projectSystemDiagramGraphManifestSchema = z.object({\n manifestId: z.string().trim().min(1).max(200),\n layoutVersion: z.number().int().positive().default(1),\n direction: projectSystemDiagramDirectionSchema.default(\"LR\"),\n nodes: z.array(projectSystemDiagramNodeSchema).min(1),\n edges: z.array(projectSystemDiagramEdgeSchema).default([]),\n groups: z.array(projectSystemDiagramGroupSchema).default([]),\n views: z.array(projectSystemDiagramViewSchema).min(1),\n citations: z.array(projectContextCitationSchema).default([]),\n unknowns: z.array(z.string().trim().min(1).max(300)).default([]),\n warnings: z.array(z.string().trim().min(1).max(600)).default([])\n});\n\nexport const projectSystemDiagramItemSchema = baseItemSchema.extend({\n type: z.literal(\"projectSystemDiagram\"),\n projectId: z.string().min(1),\n projectSystemDiagramId: z.string().min(1),\n version: z.number().int().positive(),\n status: projectSystemDiagramStatusSchema,\n source: sourceSchema.default(\"generated\"),\n repositoryLinkId: z.string().min(1).optional(),\n projectContextMapId: z.string().min(1),\n projectContextMapVersion: z.number().int().positive(),\n sourceBrainRevision: z.number().int().nonnegative().optional(),\n summary: z.string().trim().min(1).max(4000),\n graph: projectSystemDiagramGraphManifestSchema,\n coverage: projectContextCoverageSchema.default(defaultProjectContextCoverage),\n mermaid: z.string().trim().min(1).max(12000),\n approvedByUserId: z.string().min(1).optional(),\n approvedAt: isoDateTimeSchema.optional(),\n generatedAt: isoDateTimeSchema,\n supersedesDiagramId: z.string().min(1).optional(),\n error: z.string().max(1000).optional()\n});\n\nexport const projectContextMapItemSchema = baseItemSchema.extend({\n type: z.literal(\"projectContextMap\"),\n projectId: z.string().min(1),\n projectContextMapId: z.string().min(1),\n version: z.number().int().positive(),\n status: projectContextMapStatusSchema,\n source: sourceSchema.default(\"runner\"),\n repositoryLinkId: z.string().min(1).optional(),\n refreshId: z.string().min(1).optional(),\n summary: z.string().trim().min(1).max(4000),\n slices: z.array(projectContextSliceSchema).default([]),\n entities: z.array(projectContextEntitySchema).default([]),\n relations: z.array(projectContextRelationSchema).default([]),\n coverage: projectContextCoverageSchema.default(defaultProjectContextCoverage),\n approvedByUserId: z.string().min(1).optional(),\n approvedAt: isoDateTimeSchema.optional(),\n generatedAt: isoDateTimeSchema,\n supersedesMapId: z.string().min(1).optional(),\n error: z.string().max(1000).optional()\n});\n\nexport const projectContextRefreshResultSchema = z.object({\n summary: z.string().trim().min(1).max(4000),\n slices: z.array(projectContextSliceSchema).default([]),\n entities: z.array(projectContextEntitySchema).default([]),\n relations: z.array(projectContextRelationSchema).default([]),\n coverage: projectContextCoverageSchema.default(defaultProjectContextCoverage),\n changedSliceIds: z.array(z.string().trim().min(1).max(160)).default([]),\n staleSliceIds: z.array(z.string().trim().min(1).max(160)).default([]),\n verificationPlan: z.array(z.string().trim().min(1).max(300)).min(1),\n warnings: z.array(z.string().trim().min(1).max(600)).default([])\n});\n\nexport const projectContextRefreshItemSchema = baseItemSchema.extend({\n type: z.literal(\"projectContextRefresh\"),\n projectId: z.string().min(1),\n projectContextRefreshId: z.string().min(1),\n status: projectContextRefreshStatusSchema,\n source: z.enum([\"manual\", \"runner\", \"scheduled\"]).default(\"manual\"),\n repositoryLinkId: z.string().min(1).optional(),\n workItemId: z.string().min(1).optional(),\n runnerId: z.string().min(1).optional(),\n previousMapId: z.string().min(1).optional(),\n proposedMapId: z.string().min(1).optional(),\n summary: z.string().trim().min(1).max(4000).optional(),\n changedSliceIds: z.array(z.string().trim().min(1).max(160)).default([]),\n staleSliceIds: z.array(z.string().trim().min(1).max(160)).default([]),\n startedAt: isoDateTimeSchema.optional(),\n completedAt: isoDateTimeSchema.optional(),\n failedAt: isoDateTimeSchema.optional(),\n error: z.string().max(1000).optional()\n});\n\nexport const projectContextPackSchema = z.object({\n packId: z.string().min(1),\n accountId: z.string().min(1),\n projectId: z.string().min(1),\n workItemId: z.string().min(1).optional(),\n query: z.string().trim().min(1).max(2000),\n mapId: z.string().min(1).optional(),\n mapVersion: z.number().int().positive().optional(),\n slices: z.array(projectContextSliceSchema).default([]),\n entities: z.array(projectContextEntitySchema).default([]),\n relations: z.array(projectContextRelationSchema).default([]),\n citations: z.array(projectContextCitationSchema).default([]),\n freshnessWarnings: z.array(z.string().trim().min(1).max(600)).default([]),\n tokenEstimate: z.number().int().nonnegative().default(0),\n generatedAt: isoDateTimeSchema\n});\n\nexport const implementationVerificationCheckStatusSchema = z.enum([\"passed\", \"failed\", \"blocked\", \"skipped\"]);\n\nexport const implementationVerificationRecommendationSchema = z.enum([\"none\", \"requeue\", \"createFollowUpPlan\", \"requestHumanReview\", \"markBlocked\"]);\n\nexport const implementationVerificationEvidenceSchema = z.object({\n acceptanceCriterion: z.string().trim().min(1).max(500),\n status: z.enum([\"satisfied\", \"partial\", \"missing\", \"unknown\"]),\n summary: z.string().trim().min(1).max(1200),\n citations: z.array(projectContextCitationSchema).default([])\n});\n\nexport const implementationVerificationCheckSchema = z.object({\n name: z.string().trim().min(1).max(200),\n status: implementationVerificationCheckStatusSchema,\n summary: z.string().trim().min(1).max(1200),\n safePaths: z.array(projectContextRepoPathSchema).default([])\n});\n\nexport const implementationVerificationResultSchema = z.object({\n outcome: implementationVerificationOutcomeSchema,\n summary: z.string().trim().min(1).max(2000),\n evidence: z.array(implementationVerificationEvidenceSchema).min(1),\n checks: z.array(implementationVerificationCheckSchema).default([]),\n gaps: z.array(z.string().trim().min(1).max(600)).default([]),\n branch: z.string().trim().min(1).max(200).optional(),\n pullRequestUrl: z.string().trim().url().max(500).optional(),\n worktreeKey: z.string().trim().min(1).max(300).optional(),\n recommendation: implementationVerificationRecommendationSchema.default(\"none\"),\n verificationPlan: z.array(z.string().trim().min(1).max(300)).default([]),\n warnings: z.array(z.string().trim().min(1).max(600)).default([])\n});\n\nexport const implementationVerificationItemSchema = baseItemSchema.extend({\n type: z.literal(\"implementationVerification\"),\n projectId: z.string().min(1),\n implementationVerificationId: z.string().min(1),\n status: implementationVerificationStatusSchema,\n source: z.enum([\"manual\", \"runner\", \"appEvaluation\", \"planCleanup\", \"system\"]).default(\"manual\"),\n planDocumentId: z.string().min(1).optional(),\n planDocumentRevision: z.number().int().nonnegative().optional(),\n sourceWorkItemId: z.string().min(1).optional(),\n verificationWorkItemId: z.string().min(1).optional(),\n repositoryLinkId: z.string().min(1).optional(),\n runnerId: z.string().min(1).optional(),\n sourceRevision: z.string().trim().min(1).max(160).optional(),\n brainRevision: z.number().int().nonnegative().optional(),\n contextPackId: z.string().min(1).optional(),\n outcome: implementationVerificationOutcomeSchema.optional(),\n result: implementationVerificationResultSchema.optional(),\n summary: z.string().trim().min(1).max(2000).optional(),\n startedAt: isoDateTimeSchema.optional(),\n completedAt: isoDateTimeSchema.optional(),\n failedAt: isoDateTimeSchema.optional(),\n overriddenByUserId: z.string().min(1).optional(),\n overrideReason: z.string().trim().min(1).max(1000).optional(),\n overriddenAt: isoDateTimeSchema.optional(),\n error: z.string().max(1000).optional()\n});\n\nexport const contextMissItemSchema = baseItemSchema.extend({\n type: z.literal(\"contextMiss\"),\n projectId: z.string().min(1),\n contextMissId: z.string().min(1),\n status: contextMissStatusSchema.default(\"open\"),\n source: z.enum([\"runner\", \"web\", \"system\"]).default(\"runner\"),\n workItemId: z.string().min(1).optional(),\n projectContextMapId: z.string().min(1).optional(),\n query: z.string().trim().min(1).max(2000),\n missingSurface: z.string().trim().min(1).max(200),\n reason: z.string().trim().min(1).max(1200),\n suggestedPaths: z.array(projectContextRepoPathSchema).default([]),\n resolvedAt: isoDateTimeSchema.optional(),\n dismissedAt: isoDateTimeSchema.optional()\n});\n\nexport const impactAffectedAreaSchema = z.object({\n name: z.string().trim().min(1),\n description: z.string().trim().min(1).optional()\n});\n\nexport const impactPathSchema = z.object({\n repoPath: z.string().trim().min(1),\n reason: z.string().trim().min(1).optional()\n});\n\nexport const impactReportItemSchema = baseItemSchema.extend({\n type: z.literal(\"impactReport\"),\n projectId: z.string().min(1),\n impactReportId: z.string().min(1),\n status: impactReportStatusSchema,\n riskLevel: impactRiskLevelSchema.optional(),\n summary: z.string().trim().min(1).optional(),\n affectedAreas: z.array(impactAffectedAreaSchema).default([]),\n likelyPaths: z.array(impactPathSchema).default([]),\n dependencies: z.array(z.string().trim().min(1)).default([]),\n dataSchemaImpact: z.string().trim().min(1).optional(),\n securityPrivacyImpact: z.string().trim().min(1).optional(),\n verificationPlan: z.array(z.string().trim().min(1)).default([]),\n rollbackPlan: z.string().trim().min(1).optional(),\n generatedDraftId: z.string().min(1).optional(),\n sourceWorkItemId: z.string().min(1).optional(),\n documentId: z.string().min(1).optional(),\n documentRevision: z.number().int().nonnegative().optional(),\n repositoryLinkId: z.string().min(1).optional(),\n repoFingerprint: z.string().min(1).optional(),\n analyzedRepoRevision: z.number().int().nonnegative().optional(),\n workItemId: z.string().min(1).optional(),\n runnerId: z.string().min(1).optional(),\n createdByUserId: z.string().min(1).optional(),\n completedAt: isoDateTimeSchema.optional(),\n staleReason: z.string().optional(),\n error: z.string().optional()\n});\n\nexport const impactPreviewResultSchema = z.object({\n riskLevel: impactRiskLevelSchema,\n summary: z.string().trim().min(1),\n affectedAreas: z.array(impactAffectedAreaSchema).min(1),\n likelyPaths: z.array(impactPathSchema).default([]),\n dependencies: z.array(z.string().trim().min(1)).default([]),\n dataSchemaImpact: z.string().trim().min(1),\n securityPrivacyImpact: z.string().trim().min(1),\n verificationPlan: z.array(z.string().trim().min(1)).min(1),\n rollbackPlan: z.string().trim().min(1),\n analyzedRepoRevision: z.number().int().nonnegative().optional(),\n repoFingerprint: z.string().min(1).optional()\n});\n\nexport const issueDiagnosisResultSchema = z.object({\n summary: z.string().trim().min(1),\n impact: z.string().trim().min(1),\n evidence: z.array(z.string().trim().min(1)).default([]),\n affectedSurfaces: z.array(z.string().trim().min(1)).default([]),\n rootCauseAnalysis: z.string().trim().min(1),\n falsifiableHypothesis: z.string().trim().min(1).optional(),\n nextCheck: z.string().trim().min(1).optional(),\n proposedFix: z.string().trim().min(1),\n expectedBehavior: z.string().trim().min(1),\n verificationPlan: z.array(z.string().trim().min(1)).min(1),\n riskLevel: impactRiskLevelSchema.default(\"medium\"),\n likelyPaths: z.array(impactPathSchema).default([]),\n approvalState: issueApprovalStateSchema.default(\"proposed\")\n});\n\nexport const issueItemSchema = baseItemSchema.extend({\n type: z.literal(\"issue\"),\n projectId: z.string().min(1),\n issueId: z.string().min(1),\n title: z.string().trim().min(1).max(200),\n description: z.string().trim().min(1).max(12000),\n category: issueCategorySchema.default(\"bug\"),\n severity: issueSeveritySchema.default(\"medium\"),\n status: issueStatusSchema,\n approvalState: issueApprovalStateSchema.default(\"proposed\"),\n submittedByUserId: z.string().min(1).optional(),\n repositoryLinkId: z.string().min(1).optional(),\n diagnosisWorkItemId: z.string().min(1).optional(),\n implementationWorkItemId: z.string().min(1).optional(),\n diagnosis: issueDiagnosisResultSchema.optional(),\n reviewNotes: z.string().trim().min(1).optional(),\n approvedByUserId: z.string().min(1).optional(),\n approvedAt: isoDateTimeSchema.optional(),\n requestedChangesByUserId: z.string().min(1).optional(),\n requestedChangesAt: isoDateTimeSchema.optional(),\n rejectedByUserId: z.string().min(1).optional(),\n rejectedAt: isoDateTimeSchema.optional(),\n diagnosedAt: isoDateTimeSchema.optional(),\n runnerId: z.string().min(1).optional(),\n lastDiagnosisError: z.string().optional()\n});\n\nexport const securityStandardReferenceSchema = z.object({\n standard: z.string().trim().min(1).max(120),\n control: z.string().trim().min(1).max(160),\n url: z.string().url().optional()\n});\n\nexport const securitySeverityCountsSchema = z.object({\n info: z.number().int().nonnegative().default(0),\n low: z.number().int().nonnegative().default(0),\n medium: z.number().int().nonnegative().default(0),\n high: z.number().int().nonnegative().default(0),\n critical: z.number().int().nonnegative().default(0)\n});\n\nconst defaultSecuritySeverityCounts = { info: 0, low: 0, medium: 0, high: 0, critical: 0 };\n\nexport const securityCategorySummarySchema = z.object({\n category: securityFindingCategorySchema,\n status: z.enum([\"pass\", \"warning\", \"fail\", \"unknown\"]),\n summary: z.string().trim().min(1).max(600)\n});\n\nexport const securityFindingResultSchema = z.object({\n title: z.string().trim().min(1).max(200),\n category: securityFindingCategorySchema,\n severity: securityFindingSeveritySchema,\n confidence: securityFindingConfidenceSchema.default(\"medium\"),\n summary: z.string().trim().min(1).max(2000),\n standardReferences: z.array(securityStandardReferenceSchema).default([]),\n affectedSurfaces: z.array(z.string().trim().min(1).max(300)).default([]),\n evidence: z.array(z.string().trim().min(1).max(600)).default([]),\n recommendedRemediation: z.string().trim().min(1).max(4000),\n verificationPlan: z.array(z.string().trim().min(1).max(300)).min(1),\n safePaths: z.array(z.string().trim().min(1).max(300)).default([]),\n status: securityFindingStatusSchema.default(\"open\")\n});\n\nconst securityPostureGradeSchema = z.enum([\"A\", \"B\", \"C\", \"D\", \"F\", \"Unknown\"]);\nconst securityPostureScanResultGradeSchema = z.preprocess((value) => {\n if (typeof value !== \"string\") {\n return value;\n }\n const trimmed = value.trim();\n if (trimmed.toUpperCase() === \"UNKNOWN\") {\n return \"Unknown\";\n }\n const gradeMatch = /^(?:GRADE\\s*)?([ABCDF])(?:\\s*[+-])?(?:\\b|$)/i.exec(trimmed);\n if (gradeMatch?.[1]) {\n return gradeMatch[1].toUpperCase();\n }\n return \"Unknown\";\n}, securityPostureGradeSchema);\n\nexport const securityPostureScanResultSchema = z.object({\n summary: z.string().trim().min(1).max(2000),\n baselineVersion: z.string().trim().min(1).max(80),\n postureScore: z.number().min(0).max(100).optional(),\n postureGrade: securityPostureScanResultGradeSchema.default(\"Unknown\"),\n categorySummaries: z.array(securityCategorySummarySchema).default([]),\n findings: z.array(securityFindingResultSchema).default([]),\n verificationPlan: z.array(z.string().trim().min(1).max(300)).min(1)\n});\n\nexport const securityScanItemSchema = baseItemSchema.extend({\n type: z.literal(\"securityScan\"),\n projectId: z.string().min(1),\n securityScanId: z.string().min(1),\n scheduledDate: z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/),\n source: securityScanSourceSchema,\n status: securityScanStatusSchema,\n baselineVersion: z.string().trim().min(1).max(80).default(\"amistio-security-baseline-v1\"),\n workItemId: z.string().min(1).optional(),\n repositoryLinkId: z.string().min(1).optional(),\n runnerId: z.string().min(1).optional(),\n findingIds: z.array(z.string().min(1)).default([]),\n summary: z.string().trim().min(1).max(2000).optional(),\n severityCounts: securitySeverityCountsSchema.default(defaultSecuritySeverityCounts),\n startedAt: isoDateTimeSchema.optional(),\n completedAt: isoDateTimeSchema.optional(),\n failedAt: isoDateTimeSchema.optional(),\n error: z.string().max(1000).optional()\n});\n\nexport const securityFindingItemSchema = baseItemSchema.extend({\n type: z.literal(\"securityFinding\"),\n projectId: z.string().min(1),\n securityFindingId: z.string().min(1),\n securityScanId: z.string().min(1),\n title: z.string().trim().min(1).max(200),\n category: securityFindingCategorySchema,\n severity: securityFindingSeveritySchema,\n confidence: securityFindingConfidenceSchema.default(\"medium\"),\n status: securityFindingStatusSchema,\n approvalState: securityApprovalStateSchema.default(\"proposed\"),\n summary: z.string().trim().min(1).max(2000),\n standardReferences: z.array(securityStandardReferenceSchema).default([]),\n affectedSurfaces: z.array(z.string().trim().min(1).max(300)).default([]),\n evidence: z.array(z.string().trim().min(1).max(600)).default([]),\n safePaths: z.array(z.string().trim().min(1).max(300)).default([]),\n recommendedRemediation: z.string().trim().min(1).max(4000),\n verificationPlan: z.array(z.string().trim().min(1).max(300)).min(1),\n remediationPlanDocumentId: z.string().min(1).optional(),\n remediationPromptDocumentId: z.string().min(1).optional(),\n implementationWorkItemId: z.string().min(1).optional(),\n reviewNotes: z.string().trim().min(1).optional(),\n reviewedByUserId: z.string().min(1).optional(),\n reviewedAt: isoDateTimeSchema.optional(),\n resolvedAt: isoDateTimeSchema.optional(),\n lastReviewAction: z.enum([\"approve\", \"requestChanges\", \"dismiss\", \"acceptRisk\", \"reopen\"]).optional()\n});\n\nexport const securityPostureSnapshotItemSchema = baseItemSchema.extend({\n type: z.literal(\"securityPostureSnapshot\"),\n projectId: z.string().min(1),\n securityPostureSnapshotId: z.string().min(1),\n latestScanId: z.string().min(1).optional(),\n status: z.enum([\"unknown\", \"fresh\", \"stale\", \"running\", \"failed\"]),\n baselineVersion: z.string().trim().min(1).max(80).default(\"amistio-security-baseline-v1\"),\n postureScore: z.number().min(0).max(100).optional(),\n postureGrade: securityPostureGradeSchema.default(\"Unknown\"),\n severityCounts: securitySeverityCountsSchema.default(defaultSecuritySeverityCounts),\n categorySummaries: z.array(securityCategorySummarySchema).default([]),\n lastScannedAt: isoDateTimeSchema.optional(),\n nextScheduledAt: isoDateTimeSchema.optional(),\n summary: z.string().trim().min(1).max(2000).optional()\n});\n\nexport const testCoverageThresholdsSchema = z.object({\n lines: z.number().min(0).max(100).optional(),\n statements: z.number().min(0).max(100).optional(),\n branches: z.number().min(0).max(100).optional(),\n functions: z.number().min(0).max(100).optional()\n}).strict();\n\nexport const testProfileCommandSchema = z.object({\n commandId: z.string().trim().min(1).max(160),\n kind: testCommandKindSchema,\n label: z.string().trim().min(1).max(200),\n source: testCommandSourceSchema.default(\"detected\"),\n packageName: z.string().trim().min(1).max(200).optional(),\n scriptName: z.string().trim().min(1).max(120).optional(),\n tool: z.string().trim().min(1).max(120).optional(),\n workingDirectory: projectContextRepoPathSchema.optional(),\n required: z.boolean().default(false),\n estimatedDurationSeconds: z.number().int().positive().max(7200).optional()\n}).strict();\n\nexport const testProfileItemSchema = baseItemSchema.extend({\n type: z.literal(\"testProfile\"),\n projectId: z.string().min(1),\n testProfileId: z.string().min(1),\n repositoryLinkId: z.string().min(1),\n status: testProfileStatusSchema,\n enabled: z.boolean().default(true),\n detectedPackageManager: testPackageManagerSchema.default(\"unknown\"),\n packageManagers: z.array(testPackageManagerSchema).default([]),\n commands: z.array(testProfileCommandSchema).max(40).default([]),\n coverageThresholds: testCoverageThresholdsSchema.default({}),\n defaultWholeAppCommandId: z.string().trim().min(1).max(160).optional(),\n focusedCommandIds: z.array(z.string().trim().min(1).max(160)).max(20).default([]),\n lastDetectedAt: isoDateTimeSchema.optional(),\n lastReviewedRevision: z.string().trim().min(1).max(160).optional(),\n reviewedByUserId: z.string().min(1).optional(),\n reviewedAt: isoDateTimeSchema.optional()\n});\n\nexport const testCommandSummarySchema = z.object({\n commandId: z.string().trim().min(1).max(160).optional(),\n kind: testCommandKindSchema,\n label: z.string().trim().min(1).max(200),\n status: testCommandStatusSchema,\n durationMs: z.number().int().nonnegative().optional(),\n exitCode: z.number().int().min(0).max(255).optional(),\n summary: z.string().trim().min(1).max(1200),\n outputExcerpt: z.string().trim().min(1).max(1200).optional(),\n safePaths: z.array(projectContextRepoPathSchema).max(30).default([])\n}).strict();\n\nexport const testCoverageSummarySchema = z.object({\n status: testCoverageMetricStatusSchema,\n lines: z.number().min(0).max(100).optional(),\n statements: z.number().min(0).max(100).optional(),\n branches: z.number().min(0).max(100).optional(),\n functions: z.number().min(0).max(100).optional(),\n thresholds: testCoverageThresholdsSchema.default({}),\n reportPath: projectContextRepoPathSchema.optional(),\n summary: z.string().trim().min(1).max(1200).optional()\n}).strict();\n\nexport const testRedactionStateSchema = z.object({\n status: testRedactionStatusSchema.default(\"clean\"),\n redactedFields: z.array(z.string().trim().min(1).max(120)).max(40).default([]),\n summary: z.string().trim().min(1).max(600).optional()\n}).strict();\n\nexport const testQualityFindingResultSchema = z.object({\n title: z.string().trim().min(1).max(200),\n category: testQualityFindingCategorySchema,\n severity: testQualityFindingSeveritySchema,\n confidence: testQualityFindingConfidenceSchema.default(\"medium\"),\n summary: z.string().trim().min(1).max(2000),\n affectedSurfaces: z.array(z.string().trim().min(1).max(300)).default([]),\n evidence: z.array(z.string().trim().min(1).max(600)).default([]),\n safePaths: z.array(projectContextRepoPathSchema).max(30).default([]),\n suggestedAction: z.string().trim().min(1).max(4000),\n verificationPlan: z.array(z.string().trim().min(1).max(300)).min(1),\n proposedPlanTitle: z.string().trim().min(1).max(200).optional(),\n proposedPlanRepoPath: projectContextRepoPathSchema.optional(),\n proposedPlanContent: z.string().trim().min(1).max(30000).optional(),\n dedupeKey: z.string().trim().min(1).max(240).optional(),\n status: testQualityFindingStatusSchema.default(\"open\")\n}).strict();\n\nexport const testQualityScanResultSchema = z.object({\n summary: z.string().trim().min(1).max(2000),\n profile: testProfileItemSchema.omit({ id: true, type: true, schemaVersion: true, accountId: true, projectId: true, createdAt: true, updatedAt: true }).optional(),\n commandSummaries: z.array(testCommandSummarySchema).max(40).default([]),\n coverage: testCoverageSummarySchema.optional(),\n findings: z.array(testQualityFindingResultSchema).max(50).default([]),\n blockedReasons: z.array(z.string().trim().min(1).max(600)).max(20).default([]),\n redactionState: testRedactionStateSchema.default({ status: \"clean\", redactedFields: [] }),\n verificationPlan: z.array(z.string().trim().min(1).max(300)).min(1),\n warnings: z.array(z.string().trim().min(1).max(600)).default([])\n}).strict();\n\nexport const testQualityScanItemSchema = baseItemSchema.extend({\n type: z.literal(\"testQualityScan\"),\n projectId: z.string().min(1),\n testQualityScanId: z.string().min(1),\n scheduledDate: z.string().regex(/^\\d{4}-\\d{2}-\\d{2}$/),\n source: z.enum([\"runner\", \"manual\"]),\n status: testQualityScanStatusSchema,\n repositoryLinkId: z.string().min(1).optional(),\n runnerId: z.string().min(1).optional(),\n workItemId: z.string().min(1).optional(),\n testProfileId: z.string().min(1).optional(),\n findingIds: z.array(z.string().min(1)).default([]),\n summary: z.string().trim().min(1).max(2000).optional(),\n result: testQualityScanResultSchema.optional(),\n startedAt: isoDateTimeSchema.optional(),\n completedAt: isoDateTimeSchema.optional(),\n failedAt: isoDateTimeSchema.optional(),\n error: z.string().max(1000).optional()\n});\n\nexport const testQualityFindingItemSchema = baseItemSchema.extend({\n type: z.literal(\"testQualityFinding\"),\n projectId: z.string().min(1),\n testQualityFindingId: z.string().min(1),\n testQualityScanId: z.string().min(1).optional(),\n implementationTestGateId: z.string().min(1).optional(),\n repositoryLinkId: z.string().min(1).optional(),\n title: z.string().trim().min(1).max(200),\n category: testQualityFindingCategorySchema,\n severity: testQualityFindingSeveritySchema,\n confidence: testQualityFindingConfidenceSchema.default(\"medium\"),\n status: testQualityFindingStatusSchema,\n approvalState: testQualityApprovalStateSchema.default(\"proposed\"),\n summary: z.string().trim().min(1).max(2000),\n affectedSurfaces: z.array(z.string().trim().min(1).max(300)).default([]),\n evidence: z.array(z.string().trim().min(1).max(600)).default([]),\n safePaths: z.array(projectContextRepoPathSchema).max(30).default([]),\n suggestedAction: z.string().trim().min(1).max(4000),\n verificationPlan: z.array(z.string().trim().min(1).max(300)).min(1),\n dedupeKey: z.string().trim().min(1).max(240).optional(),\n proposedPlanDocumentId: z.string().min(1).optional(),\n implementationWorkItemId: z.string().min(1).optional(),\n reviewNotes: z.string().trim().min(1).optional(),\n reviewedByUserId: z.string().min(1).optional(),\n reviewedAt: isoDateTimeSchema.optional(),\n resolvedAt: isoDateTimeSchema.optional(),\n lastReviewAction: z.enum([\"approve\", \"requestChanges\", \"dismiss\", \"acceptRisk\", \"reopen\"]).optional()\n});\n\nexport const implementationTestGateResultSchema = z.object({\n outcome: implementationTestGateOutcomeSchema,\n summary: z.string().trim().min(1).max(2000),\n commandSummaries: z.array(testCommandSummarySchema).max(40).default([]),\n coverage: testCoverageSummarySchema.optional(),\n findings: z.array(testQualityFindingResultSchema).max(50).default([]),\n testGapJustification: z.string().trim().min(1).max(1200).optional(),\n blockedReasons: z.array(z.string().trim().min(1).max(600)).max(20).default([]),\n redactionState: testRedactionStateSchema.default({ status: \"clean\", redactedFields: [] }),\n verificationPlan: z.array(z.string().trim().min(1).max(300)).default([]),\n warnings: z.array(z.string().trim().min(1).max(600)).default([])\n}).strict();\n\nexport const implementationTestGateItemSchema = baseItemSchema.extend({\n type: z.literal(\"implementationTestGate\"),\n projectId: z.string().min(1),\n implementationTestGateId: z.string().min(1),\n status: implementationTestGateStatusSchema,\n source: implementationTestGateSourceSchema.default(\"system\"),\n sourceWorkItemId: z.string().min(1),\n gateWorkItemId: z.string().min(1).optional(),\n repositoryLinkId: z.string().min(1).optional(),\n runnerId: z.string().min(1).optional(),\n planDocumentId: z.string().min(1).optional(),\n planDocumentRevision: z.number().int().nonnegative().optional(),\n testProfileId: z.string().min(1).optional(),\n outcome: implementationTestGateOutcomeSchema.optional(),\n result: implementationTestGateResultSchema.optional(),\n summary: z.string().trim().min(1).max(2000).optional(),\n startedAt: isoDateTimeSchema.optional(),\n completedAt: isoDateTimeSchema.optional(),\n failedAt: isoDateTimeSchema.optional(),\n overriddenByUserId: z.string().min(1).optional(),\n overrideReason: z.string().trim().min(1).max(1000).optional(),\n overriddenAt: isoDateTimeSchema.optional(),\n error: z.string().max(1000).optional()\n});\n\nexport const appEvaluationFindingResultSchema = z.object({\n title: z.string().trim().min(1).max(200),\n category: appEvaluationFindingCategorySchema,\n severity: appEvaluationFindingSeveritySchema,\n confidence: appEvaluationFindingConfidenceSchema.default(\"medium\"),\n summary: z.string().trim().min(1).max(2000),\n affectedSurfaces: z.array(z.string().trim().min(1).max(300)).default([]),\n evidence: z.array(z.string().trim().min(1).max(600)).default([]),\n suggestedAction: z.string().trim().min(1).max(4000),\n verificationPlan: z.array(z.string().trim().min(1).max(300)).min(1),\n safePaths: z.array(z.string().trim().min(1).max(300)).default([]),\n proposedLifecycleAction: appEvaluationPlanLifecycleActionSchema.default(\"none\"),\n relatedArtifactIds: z.array(z.string().trim().min(1).max(160)).default([]),\n proposedPlanTitle: z.string().trim().min(1).max(200).optional(),\n proposedPlanRepoPath: z.string().trim().min(1).max(300).optional(),\n proposedPlanContent: z.string().trim().min(1).max(30000).optional(),\n dedupeKey: z.string().trim().min(1).max(240).optional(),\n status: appEvaluationFindingStatusSchema.default(\"open\")\n});\n\nexport const appEvaluationScanResultSchema = z.object({\n summary: z.string().trim().min(1).max(2000),\n baselineVersion: z.string().trim().min(1).max(80),\n findings: z.array(appEvaluationFindingResultSchema).default([]),\n verificationPlan: z.array(z.string().trim().min(1).max(300)).min(1)\n});\n\nexport const appEvaluationScanItemSchema = baseItemSchema.extend({\n type: z.literal(\"appEvaluationScan\"),\n projectId: z.string().min(1),\n appEvaluationScanId: z.string().min(1),\n hourBucket: z.string().regex(/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:00:00\\.000Z$/),\n source: z.enum([\"runner\", \"manual\"]),\n status: appEvaluationScanStatusSchema,\n baselineVersion: z.string().trim().min(1).max(80).default(\"amistio-app-evaluation-v1\"),\n workItemId: z.string().min(1).optional(),\n repositoryLinkId: z.string().min(1).optional(),\n runnerId: z.string().min(1).optional(),\n findingIds: z.array(z.string().min(1)).default([]),\n summary: z.string().trim().min(1).max(2000).optional(),\n startedAt: isoDateTimeSchema.optional(),\n completedAt: isoDateTimeSchema.optional(),\n failedAt: isoDateTimeSchema.optional(),\n error: z.string().max(1000).optional()\n});\n\nexport const appEvaluationFindingItemSchema = baseItemSchema.extend({\n type: z.literal(\"appEvaluationFinding\"),\n projectId: z.string().min(1),\n appEvaluationFindingId: z.string().min(1),\n appEvaluationScanId: z.string().min(1),\n title: z.string().trim().min(1).max(200),\n category: appEvaluationFindingCategorySchema,\n severity: appEvaluationFindingSeveritySchema,\n confidence: appEvaluationFindingConfidenceSchema.default(\"medium\"),\n status: appEvaluationFindingStatusSchema,\n approvalState: appEvaluationApprovalStateSchema.default(\"proposed\"),\n summary: z.string().trim().min(1).max(2000),\n affectedSurfaces: z.array(z.string().trim().min(1).max(300)).default([]),\n evidence: z.array(z.string().trim().min(1).max(600)).default([]),\n safePaths: z.array(z.string().trim().min(1).max(300)).default([]),\n suggestedAction: z.string().trim().min(1).max(4000),\n verificationPlan: z.array(z.string().trim().min(1).max(300)).min(1),\n proposedLifecycleAction: appEvaluationPlanLifecycleActionSchema.default(\"none\"),\n relatedArtifactIds: z.array(z.string().trim().min(1).max(160)).default([]),\n dedupeKey: z.string().trim().min(1).max(240).optional(),\n proposedPlanDocumentId: z.string().min(1).optional(),\n implementationWorkItemId: z.string().min(1).optional(),\n reviewNotes: z.string().trim().min(1).optional(),\n reviewedByUserId: z.string().min(1).optional(),\n reviewedAt: isoDateTimeSchema.optional(),\n resolvedAt: isoDateTimeSchema.optional(),\n lastReviewAction: z.enum([\"approve\", \"requestChanges\", \"dismiss\", \"acceptRisk\", \"reopen\"]).optional()\n});\n\nexport const activityEventItemSchema = baseItemSchema.extend({\n type: z.literal(\"activityEvent\"),\n projectId: z.string().min(1),\n activityEventId: z.string().min(1),\n eventType: activityEventTypeSchema,\n actorType: activityEventActorSchema,\n actorId: z.string().min(1).optional(),\n status: activityEventStatusSchema,\n summary: z.string().trim().min(1).max(600),\n metadata: activityMetadataSchema,\n idempotencyKey: z.string().min(1),\n occurredAt: isoDateTimeSchema,\n relatedWorkItemId: z.string().min(1).optional(),\n relatedDocumentId: z.string().min(1).optional(),\n relatedIssueId: z.string().min(1).optional(),\n relatedSecurityScanId: z.string().min(1).optional(),\n relatedSecurityFindingId: z.string().min(1).optional(),\n relatedAppEvaluationScanId: z.string().min(1).optional(),\n relatedAppEvaluationFindingId: z.string().min(1).optional(),\n relatedImplementationVerificationId: z.string().min(1).optional(),\n relatedTestQualityScanId: z.string().min(1).optional(),\n relatedTestQualityFindingId: z.string().min(1).optional(),\n relatedImplementationTestGateId: z.string().min(1).optional(),\n relatedProjectContextRefreshId: z.string().min(1).optional(),\n relatedProjectSystemDiagramId: z.string().min(1).optional(),\n relatedContextMissId: z.string().min(1).optional(),\n relatedAutopilotAuthorizationId: z.string().min(1).optional(),\n relatedAutopilotCandidateId: z.string().min(1).optional(),\n generatedDraftId: z.string().min(1).optional(),\n runnerId: z.string().min(1).optional(),\n repositoryLinkId: z.string().min(1).optional(),\n runnerLogId: z.string().min(1).optional(),\n claimLaneId: runnerClaimLaneIdSchema.optional(),\n commandId: z.string().min(1).optional()\n});\n\nexport const activityHandoffExportSchema = z.object({\n markdown: z.string().min(1),\n generatedAt: isoDateTimeSchema,\n eventCount: z.number().int().nonnegative()\n});\n\nexport const toolSessionItemSchema = baseItemSchema.extend({\n type: z.literal(\"toolSession\"),\n projectId: z.string().min(1),\n toolSessionId: z.string().min(1),\n repositoryLinkId: z.string().min(1).optional(),\n tool: z.string().min(1),\n provider: z.string().min(1).optional(),\n model: z.string().min(1).optional(),\n resumabilityScope: sessionResumabilityScopeSchema,\n title: z.string().min(1),\n summary: z.string().optional(),\n tags: z.array(z.string().min(1)).default([]),\n relatedDocumentIds: z.array(z.string().min(1)).default([]),\n status: toolSessionStatusSchema,\n createdByUserId: z.string().min(1).optional(),\n runnerId: z.string().min(1).optional(),\n machineId: z.string().min(1).optional(),\n implementationScopeId: z.string().min(1).optional(),\n executionWorktreeKey: z.string().min(1).optional(),\n isolationMode: workIsolationModeSchema.optional(),\n lastWorkItemId: z.string().min(1).optional(),\n lastActivityAt: isoDateTimeSchema,\n messageCount: z.number().int().nonnegative().optional(),\n estimatedInputTokens: z.number().int().nonnegative().optional(),\n estimatedOutputTokens: z.number().int().nonnegative().optional(),\n costUsd: z.number().nonnegative().optional(),\n sessionGroupKey: z.string().min(1).optional(),\n reusePolicy: sessionPolicySchema.optional(),\n closedReason: z.string().optional()\n});\n\nexport const pairingSessionItemSchema = baseItemSchema.extend({\n type: z.literal(\"pairingSession\"),\n pairingCodeHash: z.string().min(1),\n projectId: z.string().min(1),\n createdByUserId: z.string().min(1),\n expiresAt: isoDateTimeSchema,\n failedAttemptCount: z.number().int().nonnegative().optional(),\n lastFailedAttemptAt: isoDateTimeSchema.optional(),\n status: z.enum([\"pending\", \"confirmed\", \"expired\", \"revoked\"])\n});\n\nexport const projectItemUnionSchema = z.discriminatedUnion(\"type\", [\n projectItemSchema,\n repositoryLinkItemSchema,\n brainDocumentItemSchema,\n generatedDraftItemSchema,\n issueItemSchema,\n securityScanItemSchema,\n securityFindingItemSchema,\n securityPostureSnapshotItemSchema,\n testProfileItemSchema,\n testQualityScanItemSchema,\n testQualityFindingItemSchema,\n implementationTestGateItemSchema,\n appEvaluationScanItemSchema,\n appEvaluationFindingItemSchema,\n brainConsolidationScanItemSchema,\n brainConsolidationProposalItemSchema,\n implementationVerificationItemSchema,\n projectContextMapItemSchema,\n projectContextRefreshItemSchema,\n projectSystemDiagramItemSchema,\n contextMissItemSchema,\n syncCursorItemSchema,\n syncConflictItemSchema,\n workItemSchema,\n runnerHeartbeatItemSchema,\n runnerSettingsItemSchema,\n runnerExecutionLogItemSchema,\n runnerCredentialItemSchema,\n runnerCommandItemSchema,\n planReviewMessageItemSchema,\n assistantMessageItemSchema,\n impactReportItemSchema,\n activityEventItemSchema,\n toolSessionItemSchema\n]);\n\nexport type ItemType = z.infer<typeof itemTypeSchema>;\nexport type DocumentType = z.infer<typeof documentTypeSchema>;\nexport type DocumentContentFormat = z.infer<typeof documentContentFormatSchema>;\nexport type ArtifactFormatPreference = z.infer<typeof artifactFormatPreferenceSchema>;\nexport type SyncState = z.infer<typeof syncStateSchema>;\nexport type WorkStatus = z.infer<typeof workStatusSchema>;\nexport type ExecutionMode = z.infer<typeof executionModeSchema>;\nexport type WorkKind = z.infer<typeof workKindSchema>;\nexport type AutopilotMode = z.infer<typeof autopilotModeSchema>;\nexport type AutopilotClassificationOutcome = z.infer<typeof autopilotClassificationOutcomeSchema>;\nexport type AutopilotCandidateType = z.infer<typeof autopilotCandidateTypeSchema>;\nexport type AutopilotReasonCode = z.infer<typeof autopilotReasonCodeSchema>;\nexport type AutopilotGuardCheck = z.infer<typeof autopilotGuardCheckSchema>;\nexport type AutopilotBudgetWindow = z.infer<typeof autopilotBudgetWindowSchema>;\nexport type AutopilotPolicySnapshot = z.infer<typeof autopilotPolicySnapshotSchema>;\nexport type AutopilotCandidateLinks = z.infer<typeof autopilotCandidateLinksSchema>;\nexport type AutopilotCandidateAction = z.infer<typeof autopilotCandidateActionSchema>;\nexport type AutopilotAuthorization = z.infer<typeof autopilotAuthorizationSchema>;\nexport type ImplementationHandoffStatus = z.infer<typeof implementationHandoffStatusSchema>;\nexport type ImplementationHandoffCleanupStatus = z.infer<typeof implementationHandoffCleanupStatusSchema>;\nexport type ImplementationHandoffRecoveryCategory = z.infer<typeof implementationHandoffRecoveryCategorySchema>;\nexport type ImplementationHandoffRecoveryAction = z.infer<typeof implementationHandoffRecoveryActionSchema>;\nexport type ImplementationHandoffRebaseAbortStatus = z.infer<typeof implementationHandoffRebaseAbortStatusSchema>;\nexport type ImplementationHandoffArtifactStatus = z.infer<typeof implementationHandoffArtifactStatusSchema>;\nexport type ImplementationHandoffArtifact = z.infer<typeof implementationHandoffArtifactSchema>;\nexport type ImplementationHandoffArtifacts = z.infer<typeof implementationHandoffArtifactsSchema>;\nexport type ImplementationHandoffRecovery = z.infer<typeof implementationHandoffRecoverySchema>;\nexport type ImplementationHandoff = z.infer<typeof implementationHandoffSchema>;\nexport type ImplementationVerificationOutcome = z.infer<typeof implementationVerificationOutcomeSchema>;\nexport type ImplementationVerificationStatus = z.infer<typeof implementationVerificationStatusSchema>;\nexport type ImplementationProofStatus = z.infer<typeof implementationProofStatusSchema>;\nexport type ImplementationVerificationCheckStatus = z.infer<typeof implementationVerificationCheckStatusSchema>;\nexport type ImplementationVerificationRecommendation = z.infer<typeof implementationVerificationRecommendationSchema>;\nexport type ImplementationVerificationEvidence = z.infer<typeof implementationVerificationEvidenceSchema>;\nexport type ImplementationVerificationCheck = z.infer<typeof implementationVerificationCheckSchema>;\nexport type ImplementationVerificationResult = z.infer<typeof implementationVerificationResultSchema>;\nexport type ImplementationVerificationItem = z.infer<typeof implementationVerificationItemSchema>;\nexport type GeneratedDraftStatus = z.infer<typeof generatedDraftStatusSchema>;\ntype GeneratedBrainArtifactOutput = z.infer<typeof generatedBrainArtifactSchema>;\nexport type GeneratedBrainArtifact = Omit<GeneratedBrainArtifactOutput, \"contentFormat\"> & { contentFormat?: DocumentContentFormat };\nexport type BrainGenerationResult = z.infer<typeof brainGenerationResultSchema>;\nexport type SessionPolicy = z.infer<typeof sessionPolicySchema>;\nexport type SessionDecision = z.infer<typeof sessionDecisionSchema>;\nexport type ToolSessionStatus = z.infer<typeof toolSessionStatusSchema>;\nexport type SessionResumabilityScope = z.infer<typeof sessionResumabilityScopeSchema>;\nexport type RunnerToolName = z.infer<typeof runnerToolNameSchema>;\nexport type RunnerToolSelection = z.infer<typeof runnerToolSelectionSchema>;\nexport type RunnerPreferenceScope = z.infer<typeof runnerPreferenceScopeSchema>;\nexport type RunnerPreferenceSource = z.infer<typeof runnerPreferenceSourceSchema>;\nexport type RunnerPreferenceStatus = z.infer<typeof runnerPreferenceStatusSchema>;\nexport type RunnerInvocationChannel = z.infer<typeof runnerInvocationChannelSchema>;\nexport type RunnerEffectiveInvocationChannel = z.infer<typeof runnerEffectiveInvocationChannelSchema>;\nexport type RunnerReasoningEffort = z.infer<typeof runnerReasoningEffortSchema>;\nexport type RunnerProviderModelStatus = z.infer<typeof runnerProviderModelStatusSchema>;\nexport type RunnerProviderModelLimit = z.infer<typeof runnerProviderModelLimitSchema>;\nexport type RunnerProviderModelModalities = z.infer<typeof runnerProviderModelModalitiesSchema>;\nexport type RunnerProviderModelVariant = z.infer<typeof runnerProviderModelVariantSchema>;\nexport type RunnerProviderModel = z.infer<typeof runnerProviderModelSchema>;\nexport type RunnerProviderConfig = z.infer<typeof runnerProviderConfigSchema>;\nexport type RunnerProviderCatalog = z.infer<typeof runnerProviderCatalogSchema>;\nexport type RunnerToolModelPreference = z.infer<typeof runnerToolModelPreferenceSchema>;\nexport type RunnerToolCapability = z.infer<typeof runnerToolCapabilitySchema>;\nexport type RunnerResourceUsage = z.infer<typeof runnerResourceUsageSchema>;\nexport type WorkIsolationMode = z.infer<typeof workIsolationModeSchema>;\nexport type RepositoryLinkSource = z.infer<typeof repositoryLinkSourceSchema>;\nexport type RepositoryCloneStatus = z.infer<typeof repositoryCloneStatusSchema>;\nexport type ProjectStatus = z.infer<typeof projectStatusSchema>;\nexport type WorkspaceScopeKind = z.infer<typeof workspaceScopeKindSchema>;\nexport type PersonalWorkspaceScope = z.infer<typeof personalWorkspaceScopeSchema>;\nexport type OrganizationWorkspaceScope = z.infer<typeof organizationWorkspaceScopeSchema>;\nexport type ActiveWorkspaceScope = z.infer<typeof activeWorkspaceScopeSchema>;\nexport type OrganizationWorkspaceOnboardingStatus = z.infer<typeof organizationWorkspaceOnboardingStatusSchema>;\nexport type OrganizationWorkspaceOnboarding = z.infer<typeof organizationWorkspaceOnboardingSchema>;\nexport type AccountItem = z.infer<typeof accountItemSchema>;\nexport type UserItem = z.infer<typeof userItemSchema>;\nexport type ProjectItem = z.infer<typeof projectItemSchema>;\nexport type RepositoryLinkItem = z.infer<typeof repositoryLinkItemSchema>;\ntype BrainDocumentItemOutput = z.infer<typeof brainDocumentItemSchema>;\nexport type BrainDocumentItem = Omit<BrainDocumentItemOutput, \"contentFormat\"> & { contentFormat?: DocumentContentFormat };\nexport type GeneratedDraftItem = z.infer<typeof generatedDraftItemSchema>;\nexport type IssueCategory = z.infer<typeof issueCategorySchema>;\nexport type IssueSeverity = z.infer<typeof issueSeveritySchema>;\nexport type IssueStatus = z.infer<typeof issueStatusSchema>;\nexport type IssueApprovalState = z.infer<typeof issueApprovalStateSchema>;\nexport type IssueDiagnosisResult = z.infer<typeof issueDiagnosisResultSchema>;\nexport type IssueItem = z.infer<typeof issueItemSchema>;\nexport type SecurityScanStatus = z.infer<typeof securityScanStatusSchema>;\nexport type SecurityScanSource = z.infer<typeof securityScanSourceSchema>;\nexport type SecurityFindingCategory = z.infer<typeof securityFindingCategorySchema>;\nexport type SecurityFindingSeverity = z.infer<typeof securityFindingSeveritySchema>;\nexport type SecurityFindingConfidence = z.infer<typeof securityFindingConfidenceSchema>;\nexport type SecurityFindingStatus = z.infer<typeof securityFindingStatusSchema>;\nexport type SecurityApprovalState = z.infer<typeof securityApprovalStateSchema>;\nexport type SecurityStandardReference = z.infer<typeof securityStandardReferenceSchema>;\nexport type SecuritySeverityCounts = z.infer<typeof securitySeverityCountsSchema>;\nexport type SecurityCategorySummary = z.infer<typeof securityCategorySummarySchema>;\nexport type SecurityFindingResult = z.infer<typeof securityFindingResultSchema>;\nexport type SecurityPostureScanResult = z.infer<typeof securityPostureScanResultSchema>;\nexport type SecurityScanItem = z.infer<typeof securityScanItemSchema>;\nexport type SecurityFindingItem = z.infer<typeof securityFindingItemSchema>;\nexport type SecurityPostureSnapshotItem = z.infer<typeof securityPostureSnapshotItemSchema>;\nexport type TestProfileStatus = z.infer<typeof testProfileStatusSchema>;\nexport type TestPackageManager = z.infer<typeof testPackageManagerSchema>;\nexport type TestCommandKind = z.infer<typeof testCommandKindSchema>;\nexport type TestCommandSource = z.infer<typeof testCommandSourceSchema>;\nexport type TestCoverageMetricStatus = z.infer<typeof testCoverageMetricStatusSchema>;\nexport type TestCommandStatus = z.infer<typeof testCommandStatusSchema>;\nexport type TestRedactionStatus = z.infer<typeof testRedactionStatusSchema>;\nexport type TestQualityScanStatus = z.infer<typeof testQualityScanStatusSchema>;\nexport type TestQualityFindingCategory = z.infer<typeof testQualityFindingCategorySchema>;\nexport type TestQualityFindingSeverity = z.infer<typeof testQualityFindingSeveritySchema>;\nexport type TestQualityFindingConfidence = z.infer<typeof testQualityFindingConfidenceSchema>;\nexport type TestQualityFindingStatus = z.infer<typeof testQualityFindingStatusSchema>;\nexport type TestQualityApprovalState = z.infer<typeof testQualityApprovalStateSchema>;\nexport type ImplementationTestGateStatus = z.infer<typeof implementationTestGateStatusSchema>;\nexport type ImplementationTestGateOutcome = z.infer<typeof implementationTestGateOutcomeSchema>;\nexport type ImplementationTestGateSource = z.infer<typeof implementationTestGateSourceSchema>;\nexport type TestCoverageThresholds = z.infer<typeof testCoverageThresholdsSchema>;\nexport type TestProfileCommand = z.infer<typeof testProfileCommandSchema>;\nexport type TestProfileItem = z.infer<typeof testProfileItemSchema>;\nexport type TestCommandSummary = z.infer<typeof testCommandSummarySchema>;\nexport type TestCoverageSummary = z.infer<typeof testCoverageSummarySchema>;\nexport type TestRedactionState = z.infer<typeof testRedactionStateSchema>;\nexport type TestQualityFindingResult = z.infer<typeof testQualityFindingResultSchema>;\nexport type TestQualityScanResult = z.infer<typeof testQualityScanResultSchema>;\nexport type TestQualityScanItem = z.infer<typeof testQualityScanItemSchema>;\nexport type TestQualityFindingItem = z.infer<typeof testQualityFindingItemSchema>;\nexport type ImplementationTestGateResult = z.infer<typeof implementationTestGateResultSchema>;\nexport type ImplementationTestGateItem = z.infer<typeof implementationTestGateItemSchema>;\nexport type AppEvaluationScanStatus = z.infer<typeof appEvaluationScanStatusSchema>;\nexport type AppEvaluationFindingCategory = z.infer<typeof appEvaluationFindingCategorySchema>;\nexport type AppEvaluationFindingSeverity = z.infer<typeof appEvaluationFindingSeveritySchema>;\nexport type AppEvaluationFindingConfidence = z.infer<typeof appEvaluationFindingConfidenceSchema>;\nexport type AppEvaluationFindingStatus = z.infer<typeof appEvaluationFindingStatusSchema>;\nexport type AppEvaluationApprovalState = z.infer<typeof appEvaluationApprovalStateSchema>;\nexport type AppEvaluationPlanLifecycleAction = z.infer<typeof appEvaluationPlanLifecycleActionSchema>;\nexport type AppEvaluationFindingResult = z.infer<typeof appEvaluationFindingResultSchema>;\nexport type AppEvaluationScanResult = z.infer<typeof appEvaluationScanResultSchema>;\nexport type AppEvaluationScanItem = z.infer<typeof appEvaluationScanItemSchema>;\nexport type AppEvaluationFindingItem = z.infer<typeof appEvaluationFindingItemSchema>;\nexport type BrainConsolidationScanStatus = z.infer<typeof brainConsolidationScanStatusSchema>;\nexport type BrainConsolidationScanSource = z.infer<typeof brainConsolidationScanSourceSchema>;\nexport type BrainConsolidationProposalStatus = z.infer<typeof brainConsolidationProposalStatusSchema>;\nexport type BrainConsolidationProposalAction = z.infer<typeof brainConsolidationProposalActionSchema>;\nexport type BrainConsolidationRiskLevel = z.infer<typeof brainConsolidationRiskLevelSchema>;\nexport type BrainConsolidationRecommendationCoverage = z.infer<typeof brainConsolidationRecommendationCoverageSchema>;\nexport type BrainConsolidationRecommendationConfidence = z.infer<typeof brainConsolidationRecommendationConfidenceSchema>;\nexport type BrainConsolidationRecommendationAction = z.infer<typeof brainConsolidationRecommendationActionSchema>;\nexport type BrainConsolidationRecommendation = z.infer<typeof brainConsolidationRecommendationSchema>;\nexport type BrainConsolidationScanResult = z.infer<typeof brainConsolidationScanResultSchema>;\nexport type BrainConsolidationScanItem = z.infer<typeof brainConsolidationScanItemSchema>;\nexport type BrainConsolidationProposalItem = z.infer<typeof brainConsolidationProposalItemSchema>;\nexport type SyncCursorItem = z.infer<typeof syncCursorItemSchema>;\nexport type SyncConflictItem = z.infer<typeof syncConflictItemSchema>;\nexport type WorkItem = z.infer<typeof workItemSchema>;\nexport type RunnerHeartbeatItem = z.infer<typeof runnerHeartbeatItemSchema>;\nexport type RunnerSettingsItem = z.infer<typeof runnerSettingsItemSchema>;\nexport type RunnerExecutionLogItem = z.infer<typeof runnerExecutionLogItemSchema>;\nexport type RunnerCredentialItem = z.infer<typeof runnerCredentialItemSchema>;\nexport type RunnerCommandKind = z.infer<typeof runnerCommandKindSchema>;\nexport type RunnerCommandStatus = z.infer<typeof runnerCommandStatusSchema>;\nexport type RunnerCommandItem = z.infer<typeof runnerCommandItemSchema>;\nexport type PlanReviewMessageRole = z.infer<typeof planReviewMessageRoleSchema>;\nexport type PlanReviewMessageIntent = z.infer<typeof planReviewMessageIntentSchema>;\nexport type PlanReviewMessageStatus = z.infer<typeof planReviewMessageStatusSchema>;\nexport type PlanReviewMessageItem = z.infer<typeof planReviewMessageItemSchema>;\nexport type AssistantMessageRole = z.infer<typeof assistantMessageRoleSchema>;\nexport type AssistantMessageStatus = z.infer<typeof assistantMessageStatusSchema>;\nexport type AssistantQuestionMode = z.infer<typeof assistantQuestionModeSchema>;\nexport type AssistantSourceBoundary = z.infer<typeof assistantSourceBoundarySchema>;\nexport type AssistantCitation = z.infer<typeof assistantCitationSchema>;\nexport type AssistantMessageItem = z.infer<typeof assistantMessageItemSchema>;\nexport type AssistantAnswerResult = z.infer<typeof assistantAnswerResultSchema>;\nexport type KnowledgeSearchScope = z.infer<typeof knowledgeSearchScopeSchema>;\nexport type KnowledgeSourceType = z.infer<typeof knowledgeSourceTypeSchema>;\nexport type KnowledgeChunkStatus = z.infer<typeof knowledgeChunkStatusSchema>;\nexport type KnowledgeEntityType = z.infer<typeof knowledgeEntityTypeSchema>;\nexport type KnowledgeRelationType = z.infer<typeof knowledgeRelationTypeSchema>;\nexport type KnowledgeIndexFreshness = z.infer<typeof knowledgeIndexFreshnessSchema>;\nexport type KnowledgeSearchChunk = z.infer<typeof knowledgeSearchChunkSchema>;\nexport type KnowledgeEntity = z.infer<typeof knowledgeEntitySchema>;\nexport type KnowledgeRelation = z.infer<typeof knowledgeRelationSchema>;\nexport type KnowledgeSearchRequest = z.infer<typeof knowledgeSearchRequestSchema>;\nexport type KnowledgeSearchResult = z.infer<typeof knowledgeSearchResultSchema>;\nexport type KnowledgeSearchResponse = z.infer<typeof knowledgeSearchResponseSchema>;\nexport type KnowledgeDiagramFormat = z.infer<typeof knowledgeDiagramFormatSchema>;\nexport type KnowledgeDiagramRequest = z.infer<typeof knowledgeDiagramRequestSchema>;\nexport type KnowledgeDiagramResult = z.infer<typeof knowledgeDiagramResultSchema>;\nexport type ProjectContextSliceKind = z.infer<typeof projectContextSliceKindSchema>;\nexport type ProjectContextFreshness = z.infer<typeof projectContextFreshnessSchema>;\nexport type ProjectContextMapStatus = z.infer<typeof projectContextMapStatusSchema>;\nexport type ProjectContextRefreshStatus = z.infer<typeof projectContextRefreshStatusSchema>;\nexport type ContextMissStatus = z.infer<typeof contextMissStatusSchema>;\nexport type ProjectContextCoverage = z.infer<typeof projectContextCoverageSchema>;\nexport type ProjectContextRepoPath = z.infer<typeof projectContextRepoPathSchema>;\nexport type ProjectContextCitation = z.infer<typeof projectContextCitationSchema>;\nexport type ProjectContextSlice = z.infer<typeof projectContextSliceSchema>;\nexport type ProjectContextEntity = z.infer<typeof projectContextEntitySchema>;\nexport type ProjectContextRelation = z.infer<typeof projectContextRelationSchema>;\nexport type ProjectContextMapItem = z.infer<typeof projectContextMapItemSchema>;\nexport type ProjectContextRefreshResult = z.infer<typeof projectContextRefreshResultSchema>;\nexport type ProjectContextRefreshItem = z.infer<typeof projectContextRefreshItemSchema>;\nexport type ProjectContextPack = z.infer<typeof projectContextPackSchema>;\nexport type ContextMissItem = z.infer<typeof contextMissItemSchema>;\nexport type ProjectSystemDiagramStatus = z.infer<typeof projectSystemDiagramStatusSchema>;\nexport type ProjectSystemDiagramViewKind = z.infer<typeof projectSystemDiagramViewKindSchema>;\nexport type ProjectSystemDiagramNodeKind = z.infer<typeof projectSystemDiagramNodeKindSchema>;\nexport type ProjectSystemDiagramNode = z.infer<typeof projectSystemDiagramNodeSchema>;\nexport type ProjectSystemDiagramEdge = z.infer<typeof projectSystemDiagramEdgeSchema>;\nexport type ProjectSystemDiagramGroup = z.infer<typeof projectSystemDiagramGroupSchema>;\nexport type ProjectSystemDiagramView = z.infer<typeof projectSystemDiagramViewSchema>;\nexport type ProjectSystemDiagramGraphManifest = z.infer<typeof projectSystemDiagramGraphManifestSchema>;\nexport type ProjectSystemDiagramItem = z.infer<typeof projectSystemDiagramItemSchema>;\nexport type ImpactRiskLevel = z.infer<typeof impactRiskLevelSchema>;\nexport type ImpactReportStatus = z.infer<typeof impactReportStatusSchema>;\nexport type ImpactAffectedArea = z.infer<typeof impactAffectedAreaSchema>;\nexport type ImpactPath = z.infer<typeof impactPathSchema>;\nexport type ImpactReportItem = z.infer<typeof impactReportItemSchema>;\nexport type ImpactPreviewResult = z.infer<typeof impactPreviewResultSchema>;\nexport type ActivityEventType = z.infer<typeof activityEventTypeSchema>;\nexport type ActivityEventActor = z.infer<typeof activityEventActorSchema>;\nexport type ActivityEventStatus = z.infer<typeof activityEventStatusSchema>;\nexport type ActivityMetadata = z.infer<typeof activityMetadataSchema>;\nexport type ActivityEventItem = z.infer<typeof activityEventItemSchema>;\nexport type ActivityHandoffExport = z.infer<typeof activityHandoffExportSchema>;\nexport type ToolSessionItem = z.infer<typeof toolSessionItemSchema>;\nexport type PairingSessionItem = z.infer<typeof pairingSessionItemSchema>;\n", "export const AMISTIO_API_URL_ENV = \"AMISTIO_API_URL\";\nexport const OFFICIAL_AMISTIO_WEB_ORIGIN = \"https://www.amistio.com\";\n\nconst API_PATH = \"/api\";\n\nexport const officialAmistioApiUrl = normalizeAmistioApiUrl(new URL(API_PATH, OFFICIAL_AMISTIO_WEB_ORIGIN).toString());\n\nexport function normalizeAmistioApiUrl(value: string): string {\n const parsed = new URL(value);\n parsed.hash = \"\";\n parsed.search = \"\";\n if (parsed.pathname.length > 1 && parsed.pathname.endsWith(\"/\")) {\n parsed.pathname = parsed.pathname.slice(0, -1);\n }\n return parsed.toString().replace(/\\/$/, \"\");\n}\n\nexport function isOfficialAmistioApiUrl(value: string): boolean {\n try {\n return normalizeAmistioApiUrl(value) === officialAmistioApiUrl;\n } catch {\n return false;\n }\n}", "import type { BrainDocumentItem, DocumentContentFormat, DocumentType } from \"./schemas.js\";\n\nconst controlPlaneRoots = new Set([\"architecture\", \"context\", \"decisions\", \"features\", \"memory\", \"plans\", \"prompts\", \"workflows\"]);\n\nconst documentTypeFolders: Record<DocumentType, string> = {\n architecture: \"architecture\",\n context: \"context\",\n decision: \"decisions\",\n feature: \"features\",\n memory: \"memory\",\n plan: \"plans\",\n prompt: \"prompts\",\n workflow: \"workflows\"\n};\n\nconst documentTypeByFolder = Object.fromEntries(Object.entries(documentTypeFolders).map(([documentType, folder]) => [folder, documentType])) as Record<string, DocumentType>;\n\nexport function isControlPlaneTemplateRepoPath(repoPath: string): boolean {\n const normalized = normalizeRepoPath(repoPath);\n const segments = normalized.split(\"/\").filter(Boolean);\n const root = controlPlaneRootFromSegments(segments);\n const basename = segments[segments.length - 1]?.toLowerCase();\n return Boolean(root && controlPlaneRoots.has(root) && (basename === \"_template.md\" || basename === \"_template.mdx\"));\n}\n\nexport function documentTypeFolder(documentType: DocumentType): string {\n return documentTypeFolders[documentType];\n}\n\nexport function documentTypeForBrainRepoPath(repoPath: string): DocumentType | undefined {\n const normalized = normalizeRepoPath(repoPath);\n const segments = normalized.split(\"/\").filter(Boolean);\n const root = controlPlaneRootFromSegments(segments);\n return root ? documentTypeByFolder[root] : undefined;\n}\n\nexport function inferContentFormatFromRepoPath(repoPath: string): DocumentContentFormat | undefined {\n if (/\\.html?$/i.test(repoPath)) return \"html\";\n if (/\\.mdx?$/i.test(repoPath)) return \"markdown\";\n return undefined;\n}\n\nexport function isSupportedBrainArtifactPath(repoPath: string): boolean {\n return Boolean(documentTypeForBrainRepoPath(repoPath) && inferContentFormatFromRepoPath(repoPath));\n}\n\nexport function normalizeBrainRepoPath(repoPath: string): string {\n return normalizeRepoPath(repoPath);\n}\n\nexport function isActiveReviewBrainDocument(document: BrainDocumentItem): boolean {\n const normalizedStatus = document.status.toLowerCase();\n if (normalizedStatus === \"approved\" || normalizedStatus === \"rejected\" || normalizedStatus === \"resolved\" || normalizedStatus === \"archived\" || normalizedStatus === \"synced\") return false;\n if (document.syncState === \"approved\" || document.syncState === \"archived\" || document.syncState === \"synced\") return false;\n return document.syncState === \"draft\" || normalizedStatus === \"draft\" || normalizedStatus === \"drafted\" || normalizedStatus === \"reviewing\" || normalizedStatus === \"changesrequested\";\n}\n\nexport function brainDocumentConsolidationKeys(document: BrainDocumentItem): string[] {\n const contentFormat = document.contentFormat ?? inferContentFormatFromRepoPath(document.repoPath) ?? \"markdown\";\n const keys = new Set<string>([\n `document:${document.documentId}`,\n `repo:${normalizeRepoPath(document.repoPath)}:${document.documentType}:${contentFormat}`,\n `content:${document.contentHash}`\n ]);\n\n for (const key of [\"generatedDraftId\", \"appEvaluationFindingId\", \"securityFindingId\", \"testQualityFindingId\", \"projectContextMapId\", \"projectSystemDiagramId\", \"convertedFromDocumentId\"] as const) {\n const value = document.frontmatter[key];\n if (typeof value === \"string\" && value.trim()) keys.add(`${key}:${value.trim()}`);\n }\n\n for (const key of [\"legacySourcePath\", \"externalBrainPath\", \"convertedFromRepoPath\"] as const) {\n const value = document.frontmatter[key];\n if (typeof value === \"string\" && value.trim()) keys.add(`${key}:${normalizeRepoPath(value)}`);\n }\n\n for (const key of [\"autoSyncedSourceHash\", \"convertedFromContentHash\"] as const) {\n const value = document.frontmatter[key];\n if (typeof value === \"string\" && value.trim()) keys.add(`${key}:${value.trim()}`);\n }\n\n const titleSlug = slugifyPathSegment(document.title);\n if (titleSlug) keys.add(`title:${document.documentType}:${titleSlug}`);\n\n return [...keys];\n}\n\nexport function convertedHtmlRepoPathForSource(source: Pick<BrainDocumentItem, \"documentType\" | \"repoPath\" | \"title\">): string {\n const basename = source.repoPath.split(\"/\").at(-1) ?? source.title;\n const slug = slugifyPathSegment(basename.replace(/\\.(md|mdx|html?)$/i, \"\")) || slugifyPathSegment(source.title) || \"document\";\n return `docs/html/${documentTypeFolder(source.documentType)}/${slug}.html`;\n}\n\nexport function markdownToHtmlDocument(input: { title: string; markdown: string }): string {\n const title = escapeHtml(input.title);\n const body = markdownToHtmlBody(input.markdown);\n return [\n \"<!doctype html>\",\n '<html lang=\"en\">',\n \"<head>\",\n ' <meta charset=\"utf-8\">',\n ' <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">',\n ` <title>${title}</title>`,\n \" <style>body{font-family:ui-sans-serif,system-ui,sans-serif;line-height:1.6;margin:2rem;max-width:72rem;color:#16202a;background:#f8fafc}pre,code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}pre{overflow:auto;padding:1rem;background:#101820;color:#f8fafc;border-radius:.5rem}blockquote{border-left:4px solid #8aa; margin-left:0; padding-left:1rem; color:#41515f}table{border-collapse:collapse}td,th{border:1px solid #ccd6dd;padding:.35rem .5rem}</style>\",\n \"</head>\",\n \"<body>\",\n body,\n \"</body>\",\n \"</html>\"\n ].join(\"\\n\");\n}\n\nexport function extractTextFromHtml(html: string): string {\n return html\n .replace(/<script\\b[^>]*>[\\s\\S]*?<\\/script>/gi, \" \")\n .replace(/<style\\b[^>]*>[\\s\\S]*?<\\/style>/gi, \" \")\n .replace(/<noscript\\b[^>]*>[\\s\\S]*?<\\/noscript>/gi, \" \")\n .replace(/<!--[\\s\\S]*?-->/g, \" \")\n .replace(/<[^>]+>/g, \" \")\n .replace(/&nbsp;/g, \" \")\n .replace(/&amp;/g, \"&\")\n .replace(/&lt;/g, \"<\")\n .replace(/&gt;/g, \">\")\n .replace(/&quot;/g, '\"')\n .replace(/&#39;/g, \"'\")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\nfunction normalizeRepoPath(repoPath: string): string {\n return repoPath.replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\").replace(/^\\/+/, \"\");\n}\n\nfunction controlPlaneRootFromSegments(segments: string[]): string | undefined {\n if (segments[0] === \"docs\" && segments[1] === \"html\") return segments[2];\n if (segments[0] === \"docs\") return segments[1];\n return segments[0];\n}\n\nfunction markdownToHtmlBody(markdown: string): string {\n const lines = markdown.replace(/^---\\n[\\s\\S]*?\\n---\\n?/, \"\").split(/\\r?\\n/);\n const html: string[] = [];\n let paragraph: string[] = [];\n let listItems: string[] = [];\n let codeBlock: string[] | undefined;\n\n const flushParagraph = () => {\n if (paragraph.length) {\n html.push(`<p>${inlineMarkdownToHtml(paragraph.join(\" \"))}</p>`);\n paragraph = [];\n }\n };\n const flushList = () => {\n if (listItems.length) {\n html.push(\"<ul>\", ...listItems.map((item) => `<li>${inlineMarkdownToHtml(item)}</li>`), \"</ul>\");\n listItems = [];\n }\n };\n\n for (const line of lines) {\n if (line.startsWith(\"```\")) {\n if (codeBlock) {\n html.push(`<pre><code>${escapeHtml(codeBlock.join(\"\\n\"))}</code></pre>`);\n codeBlock = undefined;\n } else {\n flushParagraph();\n flushList();\n codeBlock = [];\n }\n continue;\n }\n if (codeBlock) {\n codeBlock.push(line);\n continue;\n }\n\n const heading = line.match(/^(#{1,6})\\s+(.+)$/);\n if (heading) {\n flushParagraph();\n flushList();\n html.push(`<h${heading[1]?.length}>${inlineMarkdownToHtml(heading[2] ?? \"\")}</h${heading[1]?.length}>`);\n continue;\n }\n\n const list = line.match(/^[-*]\\s+(.+)$/);\n if (list) {\n flushParagraph();\n listItems.push(list[1] ?? \"\");\n continue;\n }\n\n if (!line.trim()) {\n flushParagraph();\n flushList();\n continue;\n }\n\n paragraph.push(line.trim());\n }\n\n if (codeBlock) html.push(`<pre><code>${escapeHtml(codeBlock.join(\"\\n\"))}</code></pre>`);\n flushParagraph();\n flushList();\n return html.length ? html.join(\"\\n\") : \"<p></p>\";\n}\n\nfunction inlineMarkdownToHtml(value: string): string {\n return escapeHtml(value)\n .replace(/`([^`]+)`/g, \"<code>$1</code>\")\n .replace(/\\*\\*([^*]+)\\*\\*/g, \"<strong>$1</strong>\")\n .replace(/\\[([^\\]]+)\\]\\((https?:\\/\\/[^\\s)]+)\\)/g, '<a href=\"$2\" rel=\"noreferrer\">$1</a>');\n}\n\nfunction escapeHtml(value: string): string {\n return value.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\").replace(/'/g, \"&#39;\");\n}\n\nfunction slugifyPathSegment(value: string): string {\n return value.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 100);\n}", "import { z } from \"zod\";\n\nexport const repoLinkMetadataSchema = z.object({\n amistioProjectId: z.string().min(1),\n amistioAccountId: z.string().min(1),\n repositoryLinkId: z.string().min(1),\n defaultBranch: z.string().min(1).default(\"main\"),\n lastSyncedRevision: z.coerce.number().int().nonnegative().default(0)\n});\n\nexport type RepoLinkMetadata = z.infer<typeof repoLinkMetadataSchema>;\n\nexport const syncedDocumentFrontmatterSchema = z.object({\n amistioDocumentId: z.string().min(1),\n amistioDocumentType: z.string().min(1),\n amistioContentFormat: z.enum([\"markdown\", \"html\"]).default(\"markdown\"),\n amistioRevision: z.coerce.number().int().nonnegative(),\n amistioContentHash: z.string().min(1),\n status: z.string().optional()\n});\n\nexport type SyncedDocumentFrontmatter = z.infer<typeof syncedDocumentFrontmatterSchema>;\n\nexport function createProjectLinkMarkdown(metadata: RepoLinkMetadata): string {\n return [\n \"---\",\n `amistioProjectId: ${metadata.amistioProjectId}`,\n `amistioAccountId: ${metadata.amistioAccountId}`,\n `repositoryLinkId: ${metadata.repositoryLinkId}`,\n `defaultBranch: ${metadata.defaultBranch}`,\n `lastSyncedRevision: ${metadata.lastSyncedRevision}`,\n \"---\",\n \"\",\n \"# Amistio Project Link\",\n \"\",\n \"This repository is paired with an Amistio project. Credentials are stored outside the repository on each user's machine.\",\n \"\"\n ].join(\"\\n\");\n}", "export type RepositoryCloneProtocol = \"https\" | \"ssh\";\n\nexport interface ParsedRepositoryCloneUrl {\n cloneUrl: string;\n protocol: RepositoryCloneProtocol;\n host: string;\n path: string;\n repoName: string;\n normalizedKey: string;\n provider?: string;\n repoOwner?: string;\n repoFullName?: string;\n}\n\nconst scpStyleSshPattern = /^([A-Za-z0-9._-]+)@([A-Za-z0-9.-]+):(.+)$/;\n\nexport function parseRepositoryCloneUrl(input: string): ParsedRepositoryCloneUrl {\n const cloneUrl = input.trim();\n if (!cloneUrl) {\n throw new Error(\"Repository URL is required.\");\n }\n\n if (isLocalPathLike(cloneUrl)) {\n throw new Error(\"Use an HTTPS or SSH repository clone URL, not a local path.\");\n }\n\n const scpMatch = scpStyleSshPattern.exec(cloneUrl);\n if (scpMatch) {\n const host = scpMatch[2];\n const rawPath = scpMatch[3];\n if (!host || !rawPath) {\n throw new Error(\"Repository URL must include an owner and repository name.\");\n }\n return buildParsedRepositoryCloneUrl({ cloneUrl, protocol: \"ssh\", host, rawPath });\n }\n\n let url: URL;\n try {\n url = new URL(cloneUrl);\n } catch {\n throw new Error(\"Repository URL must be a valid HTTPS or SSH clone URL.\");\n }\n\n if (url.protocol === \"file:\") {\n throw new Error(\"Use an HTTPS or SSH repository clone URL, not a local path.\");\n }\n\n if (url.protocol !== \"https:\" && url.protocol !== \"ssh:\") {\n throw new Error(\"Repository URL must use HTTPS or SSH.\");\n }\n\n if (url.protocol === \"https:\" && (url.username || url.password)) {\n throw new Error(\"Repository URL must not include embedded credentials.\");\n }\n\n if (url.protocol === \"ssh:\" && url.password) {\n throw new Error(\"Repository SSH URL must not include a password.\");\n }\n\n if (url.search || url.hash) {\n throw new Error(\"Repository URL must not include query strings or fragments.\");\n }\n\n return buildParsedRepositoryCloneUrl({\n cloneUrl,\n protocol: url.protocol === \"https:\" ? \"https\" : \"ssh\",\n host: url.hostname,\n rawPath: url.pathname\n });\n}\n\nexport function repositoryCloneUrlsMatch(firstUrl: string, secondUrl: string): boolean {\n try {\n return parseRepositoryCloneUrl(firstUrl).normalizedKey === parseRepositoryCloneUrl(secondUrl).normalizedKey;\n } catch {\n return false;\n }\n}\n\nexport function redactRepositoryCloneUrl(input: string): string {\n try {\n const url = new URL(input);\n if (url.username || url.password) {\n url.username = \"redacted\";\n url.password = \"redacted\";\n return url.toString();\n }\n } catch {\n // Non-URL SSH forms do not carry password userinfo.\n }\n return input;\n}\n\nfunction buildParsedRepositoryCloneUrl({ cloneUrl, host, protocol, rawPath }: { cloneUrl: string; host: string; protocol: RepositoryCloneProtocol; rawPath: string }): ParsedRepositoryCloneUrl {\n const normalizedHost = host.trim().toLowerCase();\n if (!normalizedHost) {\n throw new Error(\"Repository URL must include a host.\");\n }\n\n const pathWithoutSlash = normalizeRepoPath(rawPath);\n const segments = pathWithoutSlash.split(\"/\").filter(Boolean);\n if (segments.length < 2) {\n throw new Error(\"Repository URL must include an owner and repository name.\");\n }\n\n const repoSegment = segments[segments.length - 1];\n const ownerSegment = segments[segments.length - 2];\n const repoName = stripGitSuffix(repoSegment ?? \"\");\n if (!repoName || !ownerSegment) {\n throw new Error(\"Repository URL must include an owner and repository name.\");\n }\n\n const normalizedSegments = [...segments.slice(0, -1), repoName].map((segment) => segment.toLowerCase());\n const provider = inferRepositoryProvider(normalizedHost);\n const repoOwner = ownerSegment;\n const repoFullName = `${repoOwner}/${repoName}`;\n\n return {\n cloneUrl,\n protocol,\n host: normalizedHost,\n path: pathWithoutSlash,\n repoName,\n normalizedKey: `${normalizedHost}/${normalizedSegments.join(\"/\")}`,\n ...(provider ? { provider } : {}),\n repoOwner,\n repoFullName\n };\n}\n\nfunction normalizeRepoPath(rawPath: string): string {\n const withoutLeadingSlash = rawPath.trim().replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n if (!withoutLeadingSlash || withoutLeadingSlash.includes(\"..\")) {\n throw new Error(\"Repository URL path is not supported.\");\n }\n return withoutLeadingSlash;\n}\n\nfunction stripGitSuffix(value: string): string {\n return value.replace(/\\.git$/i, \"\");\n}\n\nfunction inferRepositoryProvider(host: string): string | undefined {\n if (host === \"github.com\" || host.endsWith(\".github.com\")) return \"github\";\n if (host === \"gitlab.com\" || host.endsWith(\".gitlab.com\")) return \"gitlab\";\n if (host === \"bitbucket.org\" || host.endsWith(\".bitbucket.org\")) return \"bitbucket\";\n if (host.endsWith(\"dev.azure.com\") || host.endsWith(\"visualstudio.com\")) return \"azureDevOps\";\n return \"other\";\n}\n\nfunction isLocalPathLike(value: string): boolean {\n return (\n value.startsWith(\"/\") ||\n value.startsWith(\"./\") ||\n value.startsWith(\"../\") ||\n value.startsWith(\"~/\") ||\n /^[A-Za-z]:[\\\\/]/.test(value)\n );\n}", "import { createHash } from \"node:crypto\";\n\nexport type SyncDecision = \"clean\" | \"pullWeb\" | \"pushRepo\" | \"conflict\";\n\nexport interface SyncRevisionState {\n lastSyncedHash?: string;\n webHash?: string;\n repoHash?: string;\n}\n\nexport function sha256ContentHash(content: string): string {\n return createHash(\"sha256\").update(content, \"utf8\").digest(\"hex\");\n}\n\nexport function decideSyncState(state: SyncRevisionState): SyncDecision {\n const webChanged = Boolean(state.webHash && state.webHash !== state.lastSyncedHash);\n const repoChanged = Boolean(state.repoHash && state.repoHash !== state.lastSyncedHash);\n\n if (webChanged && repoChanged && state.webHash !== state.repoHash) {\n return \"conflict\";\n }\n\n if (webChanged) {\n return \"pullWeb\";\n }\n\n if (repoChanged) {\n return \"pushRepo\";\n }\n\n return \"clean\";\n}", "import type { BrainDocumentItem, RepositoryLinkItem, RunnerHeartbeatItem, WorkItem } from \"./schemas.js\";\n\nexport const workFailureGuidanceCodes = [\"unsafe_context_path\", \"unsafe_context_result\", \"invalid_context_result\", \"context_map_too_large\", \"context_map_store_failed\"] as const;\n\nexport type WorkFailureGuidanceCode = (typeof workFailureGuidanceCodes)[number];\n\nexport interface WorkFailureGuidance {\n code: WorkFailureGuidanceCode;\n title: string;\n message: string;\n steps: string[];\n}\n\nexport interface WorkFailureGuidanceInput {\n message?: string | undefined;\n workKind?: WorkItem[\"workKind\"] | undefined;\n}\n\nconst projectContextFailureGuidance: Record<WorkFailureGuidanceCode, WorkFailureGuidance> = {\n unsafe_context_path: {\n code: \"unsafe_context_path\",\n title: \"Attention needed\",\n message: \"Project context refresh was rejected because a returned path looked unsafe.\",\n steps: [\n \"Deploy the latest web/API fix and update the local runner if this started after a path-safety release.\",\n \"Retry the project context refresh.\",\n \"If it fails again, capture the failing repo-relative path or bounded runner output without sharing secrets.\"\n ]\n },\n unsafe_context_result: {\n code: \"unsafe_context_result\",\n title: \"Attention needed\",\n message: \"Project context refresh was rejected because the result looked like it contained unsafe evidence.\",\n steps: [\n \"Review the local runner output for accidental secret-looking evidence without pasting secrets into Amistio.\",\n \"Retry the project context refresh after removing or narrowing unsafe evidence.\",\n \"If it repeats, capture a bounded redacted summary of the runner output.\"\n ]\n },\n invalid_context_result: {\n code: \"invalid_context_result\",\n title: \"Attention needed\",\n message: \"Project context refresh returned structured data the server could not accept.\",\n steps: [\n \"Update and restart the local runner so it uses the latest context refresh schema.\",\n \"Retry the project context refresh.\",\n \"If it fails again, capture the bounded marker-delimited result without source dumps or secrets.\"\n ]\n },\n context_map_too_large: {\n code: \"context_map_too_large\",\n title: \"Attention needed\",\n message: \"Project context refresh produced a map too large to store safely.\",\n steps: [\n \"Retry the refresh after narrowing the context scope or waiting for smaller incremental refresh support.\",\n \"Keep raw source and large dumps out of the context result.\",\n \"If this repeats on normal output, split the context-map storage model before retrying large repositories.\"\n ]\n },\n context_map_store_failed: {\n code: \"context_map_store_failed\",\n title: \"Attention needed\",\n message: \"Project context refresh could not be stored safely after validation.\",\n steps: [\n \"Retry the project context refresh once.\",\n \"If it repeats, check the web/API storage logs for the safe rejection reason.\",\n \"Keep the runner output bounded and avoid sharing raw source or secrets.\"\n ]\n }\n};\n\nexport function getWorkFailureGuidance(input: WorkFailureGuidanceInput): WorkFailureGuidance | undefined {\n const normalizedMessage = (input.message ?? \"\").toLowerCase();\n const code = workFailureGuidanceCodes.find((candidate) => normalizedMessage.includes(candidate));\n if (!code) {\n return undefined;\n }\n if (input.workKind && input.workKind !== \"projectContextRefresh\" && !normalizedMessage.includes(\"project context\")) {\n return undefined;\n }\n return projectContextFailureGuidance[code];\n}\n\nexport function formatWorkFailureGuidanceDetail(guidance: WorkFailureGuidance): string {\n return `Next steps: ${guidance.steps.join(\" \")}`;\n}\n\nexport const projectNextActionKinds = [\n \"noProject\",\n \"linkRepository\",\n \"pairRepository\",\n \"runnerMissing\",\n \"runnerOffline\",\n \"runnerStale\",\n \"brainGenerationQueued\",\n \"brainGenerationRunning\",\n \"brainGenerationFailed\",\n \"planRevisionQueued\",\n \"planRevisionRunning\",\n \"planRevisionFailed\",\n \"generatedArtifactsReview\",\n \"generatedArtifactsPartiallyApproved\",\n \"implementationQueued\",\n \"runnerRunningWork\",\n \"workBlocked\",\n \"workFailed\",\n \"workCompleted\",\n \"idle\"\n] as const;\n\nexport type ProjectNextActionKind = (typeof projectNextActionKinds)[number];\nexport type ProjectNextActionActor = \"user\" | \"runner\" | \"system\" | \"none\";\nexport type ProjectNextActionTone = \"neutral\" | \"success\" | \"warning\" | \"danger\";\n\nexport interface ProjectNextAction {\n kind: ProjectNextActionKind;\n actor: ProjectNextActionActor;\n tone: ProjectNextActionTone;\n title: string;\n message: string;\n detail?: string;\n count?: number;\n documentId?: string;\n repositoryLinkId?: string;\n runnerId?: string;\n updatedAt?: string;\n workItemId?: string;\n}\n\nexport interface ProjectNextActionInput {\n projectId?: string;\n projectName?: string;\n repositoryLinks: RepositoryLinkItem[];\n documents: BrainDocumentItem[];\n workItems: WorkItem[];\n runnerHeartbeats: RunnerHeartbeatItem[];\n nowMs?: number;\n}\n\nexport const nextActionRunnerHeartbeatFreshMs = 15 * 60 * 1000;\nexport const nextActionCompletedWorkFreshMs = 60 * 60 * 1000;\n\nexport function computeProjectNextAction(input: ProjectNextActionInput): ProjectNextAction {\n const nowMs = input.nowMs ?? Date.now();\n if (!input.projectId) {\n return {\n kind: \"noProject\",\n actor: \"user\",\n tone: \"neutral\",\n title: \"Create a project\",\n message: \"Create a project before linking a repository or starting runner work.\"\n };\n }\n\n const activeRepositoryLinks = input.repositoryLinks.filter((link) => link.status !== \"revoked\");\n const repositoryLink = activeRepositoryLinks[0];\n if (!repositoryLink) {\n return {\n kind: \"linkRepository\",\n actor: \"user\",\n tone: \"warning\",\n title: \"Link a repository\",\n message: \"Add the project repository so Amistio can pair a local runner.\"\n };\n }\n\n const pairedRepositoryLinks = activeRepositoryLinks.filter((link) => Boolean(link.repoFingerprint));\n if (!pairedRepositoryLinks.length) {\n return {\n kind: \"pairRepository\",\n actor: \"user\",\n tone: \"warning\",\n title: \"Pair the repository\",\n message: `Run the pairing command from ${repositoryLink.repoName} before queueing runner work.`,\n repositoryLinkId: repositoryLink.repositoryLinkId,\n updatedAt: repositoryLink.updatedAt\n };\n }\n\n const runningWork = latestWorkItem(input.workItems.filter((item) => item.status === \"running\"));\n if (runningWork) {\n if (runningWork.workKind === \"brainGeneration\") {\n return workAction(runningWork, \"brainGenerationRunning\", \"runner\", \"warning\", \"Generating project brain\", \"The local runner is generating draft brain artifacts for review.\");\n }\n if (runningWork.workKind === \"planRevision\") {\n return workAction(runningWork, \"planRevisionRunning\", \"runner\", \"warning\", \"Revising the plan\", \"The local runner is revising the generated plan from the conversation.\");\n }\n return workAction(runningWork, \"runnerRunningWork\", \"runner\", \"warning\", \"Runner is working\", \"The local runner has claimed approved implementation work.\");\n }\n\n const generatedReview = generatedReviewState(input.documents);\n if (generatedReview.unapproved.length > 0) {\n const partial = generatedReview.approved.length > 0;\n const title = partial ? \"Finish generated review\" : \"Review generated artifacts\";\n const message = partial\n ? `${generatedReview.unapproved.length} generated artifact${generatedReview.unapproved.length === 1 ? \"\" : \"s\"} still need approval before implementation work can queue.`\n : `${generatedReview.unapproved.length} generated artifact${generatedReview.unapproved.length === 1 ? \"\" : \"s\"} need approval in the web app before the runner can implement them.`;\n return {\n kind: partial ? \"generatedArtifactsPartiallyApproved\" : \"generatedArtifactsReview\",\n actor: \"user\",\n tone: \"warning\",\n title,\n message,\n count: generatedReview.unapproved.length,\n ...(generatedReview.unapproved[0]?.documentId ? { documentId: generatedReview.unapproved[0].documentId } : {}),\n ...(latestTimestamp(generatedReview.unapproved.map((document) => document.updatedAt)) ? { updatedAt: latestTimestamp(generatedReview.unapproved.map((document) => document.updatedAt))! } : {})\n };\n }\n\n const failedBrainGeneration = latestWorkItem(input.workItems.filter((item) => item.workKind === \"brainGeneration\" && item.status === \"failed\"));\n if (failedBrainGeneration) {\n return failedWorkAction(failedBrainGeneration, \"brainGenerationFailed\", \"Brain generation failed\", failedBrainGeneration.lastStatusMessage ?? \"Retry generation after checking the runner output.\");\n }\n\n const failedPlanRevision = latestWorkItem(input.workItems.filter((item) => item.workKind === \"planRevision\" && item.status === \"failed\"));\n if (failedPlanRevision) {\n return failedWorkAction(failedPlanRevision, \"planRevisionFailed\", \"Plan revision failed\", failedPlanRevision.lastStatusMessage ?? \"Review the conversation and request another revision if needed.\");\n }\n\n const blockedWorkItems = input.workItems.filter((item) => item.status === \"blocked\" || item.status === \"changesRequested\");\n const blockedWork = latestWorkItem(blockedWorkItems);\n if (blockedWork) {\n const message = workStatusReason(blockedWork, \"Review the blocked work item before the runner can continue.\");\n return workAction(blockedWork, \"workBlocked\", \"user\", \"danger\", \"Work is blocked\", blockedWorkItems.length > 1 ? `Latest blocked work ${blockedWork.workItemId}: ${message}` : message);\n }\n\n const failedWork = latestWorkItem(input.workItems.filter((item) => item.status === \"failed\"));\n if (failedWork) {\n return failedWorkAction(failedWork, \"workFailed\", \"Work failed\", failedWork.lastStatusMessage ?? \"Review the failure and retry or update the plan.\");\n }\n\n const queuedBrainGeneration = latestWorkItem(input.workItems.filter((item) => item.workKind === \"brainGeneration\" && item.status === \"approved\"));\n const queuedPlanRevision = latestWorkItem(input.workItems.filter((item) => item.workKind === \"planRevision\" && item.status === \"approved\"));\n const queuedImplementation = latestWorkItem(input.workItems.filter((item) => item.workKind !== \"brainGeneration\" && item.workKind !== \"planRevision\" && item.status === \"approved\"));\n const queuedWork = queuedBrainGeneration ?? queuedPlanRevision ?? queuedImplementation;\n const readiness = getSharedRunnerReadiness(pairedRepositoryLinks, input.runnerHeartbeats, nowMs);\n\n if (queuedWork && !readiness.ready) {\n const title = queuedWork.workKind === \"brainGeneration\" ? \"Brain generation is queued\" : queuedWork.workKind === \"planRevision\" ? \"Plan revision is queued\" : \"Implementation is queued\";\n return runnerWaitAction(readiness, title);\n }\n\n if (queuedBrainGeneration) {\n return workAction(queuedBrainGeneration, \"brainGenerationQueued\", \"runner\", \"warning\", \"Brain generation queued\", \"The local runner can claim this queued brain-generation work.\");\n }\n\n if (queuedPlanRevision) {\n return workAction(queuedPlanRevision, \"planRevisionQueued\", \"runner\", \"warning\", \"Plan revision queued\", \"The local runner can claim the requested plan revision.\");\n }\n\n if (queuedImplementation) {\n return workAction(queuedImplementation, \"implementationQueued\", \"runner\", \"warning\", \"Implementation queued\", \"The local runner can claim approved implementation work.\");\n }\n\n if (!readiness.ready) {\n return runnerWaitAction(readiness, \"Runner setup needed\");\n }\n\n const completedWork = latestWorkItem(input.workItems.filter((item) => item.status === \"completed\" && isFreshCompletedWork(item, nowMs)));\n if (completedWork) {\n return workAction(completedWork, \"workCompleted\", \"none\", \"success\", \"Work completed\", completedWork.lastStatusMessage ?? \"The latest runner work is complete.\");\n }\n\n return {\n kind: \"idle\",\n actor: \"user\",\n tone: \"success\",\n title: \"Ready for the next task\",\n message: \"The repository and runner are ready for a new project-brain request.\",\n ...(readiness.repositoryLink?.repositoryLinkId ? { repositoryLinkId: readiness.repositoryLink.repositoryLinkId } : {}),\n ...(readiness.heartbeat?.runnerId ? { runnerId: readiness.heartbeat.runnerId } : {}),\n ...(readiness.heartbeat?.lastSeenAt ? { updatedAt: readiness.heartbeat.lastSeenAt } : {})\n };\n}\n\nexport function formatProjectNextAction(action: ProjectNextAction): string {\n return `${action.title}: ${action.message}${action.detail ? ` ${action.detail}` : \"\"}`;\n}\n\ninterface SharedRunnerReadiness {\n ready: boolean;\n reason: \"ready\" | \"runnerMissing\" | \"runnerOffline\" | \"runnerStale\";\n repositoryLink?: RepositoryLinkItem;\n heartbeat?: RunnerHeartbeatItem;\n}\n\nfunction runnerWaitAction(readiness: SharedRunnerReadiness, fallbackTitle: string): ProjectNextAction {\n const repositoryName = readiness.repositoryLink?.repoName ?? \"the paired repository\";\n if (readiness.reason === \"runnerOffline\") {\n return {\n kind: \"runnerOffline\",\n actor: \"user\",\n tone: \"danger\",\n title: \"Restart the runner\",\n message: `The runner for ${repositoryName} is offline. Start amistio run --watch from the paired checkout.`,\n ...(readiness.repositoryLink?.repositoryLinkId ? { repositoryLinkId: readiness.repositoryLink.repositoryLinkId } : {}),\n ...(readiness.heartbeat?.runnerId ? { runnerId: readiness.heartbeat.runnerId } : {}),\n ...(readiness.heartbeat?.lastSeenAt ? { updatedAt: readiness.heartbeat.lastSeenAt } : {})\n };\n }\n if (readiness.reason === \"runnerStale\") {\n return {\n kind: \"runnerStale\",\n actor: \"user\",\n tone: \"warning\",\n title: \"Refresh the runner\",\n message: `The runner for ${repositoryName} has not checked in recently. Restart amistio run --watch from the paired checkout.`,\n ...(readiness.repositoryLink?.repositoryLinkId ? { repositoryLinkId: readiness.repositoryLink.repositoryLinkId } : {}),\n ...(readiness.heartbeat?.runnerId ? { runnerId: readiness.heartbeat.runnerId } : {}),\n ...(readiness.heartbeat?.lastSeenAt ? { updatedAt: readiness.heartbeat.lastSeenAt } : {})\n };\n }\n\n return {\n kind: \"runnerMissing\",\n actor: \"user\",\n tone: \"warning\",\n title: fallbackTitle,\n message: `Start amistio run --watch from ${repositoryName} so the local runner can claim work.`,\n ...(readiness.repositoryLink?.repositoryLinkId ? { repositoryLinkId: readiness.repositoryLink.repositoryLinkId } : {})\n };\n}\n\nfunction getSharedRunnerReadiness(repositoryLinks: RepositoryLinkItem[], runnerHeartbeats: RunnerHeartbeatItem[], nowMs: number): SharedRunnerReadiness {\n const repositoryLinkIds = new Set(repositoryLinks.map((link) => link.repositoryLinkId));\n const latestHeartbeat = runnerHeartbeats\n .filter((heartbeat) => repositoryLinkIds.has(heartbeat.repositoryLinkId) && heartbeat.status !== \"removed\")\n .sort((first, second) => heartbeatTime(second) - heartbeatTime(first))[0];\n const repositoryLink = latestHeartbeat\n ? repositoryLinks.find((link) => link.repositoryLinkId === latestHeartbeat.repositoryLinkId) ?? repositoryLinks[0]\n : repositoryLinks[0];\n\n if (!latestHeartbeat) {\n return { ready: false, reason: \"runnerMissing\", ...(repositoryLink ? { repositoryLink } : {}) };\n }\n if (latestHeartbeat.status === \"offline\") {\n return { ready: false, reason: \"runnerOffline\", ...(repositoryLink ? { repositoryLink } : {}), heartbeat: latestHeartbeat };\n }\n if (!isFreshHeartbeat(latestHeartbeat, nowMs)) {\n return { ready: false, reason: \"runnerStale\", ...(repositoryLink ? { repositoryLink } : {}), heartbeat: latestHeartbeat };\n }\n\n return { ready: true, reason: \"ready\", ...(repositoryLink ? { repositoryLink } : {}), heartbeat: latestHeartbeat };\n}\n\nfunction generatedReviewState(documents: BrainDocumentItem[]) {\n const generated = documents.filter(isGeneratedDocument);\n return {\n approved: generated.filter((document) => document.status === \"approved\"),\n unapproved: generated.filter((document) => document.status !== \"approved\" && document.status !== \"rejected\" && document.syncState !== \"archived\")\n };\n}\n\nfunction isGeneratedDocument(document: BrainDocumentItem): boolean {\n const generatedDraftId = document.frontmatter.generatedDraftId;\n return typeof generatedDraftId === \"string\" && generatedDraftId.length > 0;\n}\n\nfunction failedWorkAction(workItem: WorkItem, kind: ProjectNextActionKind, fallbackTitle: string, fallbackMessage: string): ProjectNextAction {\n const guidance = getWorkFailureGuidance({ message: workItem.lastStatusMessage, workKind: workItem.workKind });\n if (guidance) {\n return workAction(workItem, kind, \"user\", \"danger\", guidance.title, guidance.message, formatWorkFailureGuidanceDetail(guidance));\n }\n return workAction(workItem, kind, \"user\", \"danger\", fallbackTitle, fallbackMessage);\n}\n\nfunction workStatusReason(workItem: WorkItem, fallbackMessage: string): string {\n return workItem.blockerReason ?? workItem.sourceFailureSummary ?? workItem.lastStatusMessage ?? fallbackMessage;\n}\n\nfunction workAction(workItem: WorkItem, kind: ProjectNextActionKind, actor: ProjectNextActionActor, tone: ProjectNextActionTone, title: string, message: string, detail?: string): ProjectNextAction {\n return {\n kind,\n actor,\n tone,\n title,\n message,\n ...(detail ? { detail } : {}),\n workItemId: workItem.workItemId,\n ...(workItem.claimedByRunnerId ? { runnerId: workItem.claimedByRunnerId } : {}),\n updatedAt: workItem.lastStatusAt\n };\n}\n\nfunction latestWorkItem(workItems: WorkItem[]): WorkItem | undefined {\n return [...workItems].sort((first, second) => Date.parse(second.updatedAt) - Date.parse(first.updatedAt))[0];\n}\n\nfunction isFreshCompletedWork(workItem: WorkItem, nowMs: number): boolean {\n const timestamp = Date.parse(workItem.lastStatusAt ?? workItem.updatedAt);\n return timestamp > 0 && nowMs - timestamp <= nextActionCompletedWorkFreshMs;\n}\n\nfunction latestTimestamp(values: string[]): string | undefined {\n return values.sort((first, second) => Date.parse(second) - Date.parse(first))[0];\n}\n\nfunction heartbeatTime(heartbeat: RunnerHeartbeatItem): number {\n const timestamp = Date.parse(heartbeat.lastSeenAt);\n return Number.isNaN(timestamp) ? 0 : timestamp;\n}\n\nfunction isFreshHeartbeat(heartbeat: RunnerHeartbeatItem, nowMs: number): boolean {\n const lastSeenMs = heartbeatTime(heartbeat);\n return lastSeenMs > 0 && nowMs - lastSeenMs <= nextActionRunnerHeartbeatFreshMs;\n}\n", "import { execFile } from \"node:child_process\";\nimport { mkdir, readdir, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { repositoryCloneUrlsMatch } from \"@amistio/shared\";\n\nconst execFileAsync = promisify(execFile);\n\nexport interface BootstrapCheckoutResult {\n status: \"cloned\" | \"validated\";\n targetDir: string;\n originUrl?: string;\n}\n\nexport function buildGitCloneArgs(repoUrl: string, targetDir: string): string[] {\n return [\"clone\", repoUrl, targetDir];\n}\n\nexport async function cloneOrValidateRepository({ repoUrl, targetDir }: { repoUrl: string; targetDir: string }): Promise<BootstrapCheckoutResult> {\n const resolvedTarget = path.resolve(targetDir);\n const targetStat = await stat(resolvedTarget).catch((error: unknown) => {\n if (isNotFoundError(error)) return undefined;\n throw error;\n });\n\n if (!targetStat) {\n await mkdir(path.dirname(resolvedTarget), { recursive: true });\n await runGit(buildGitCloneArgs(repoUrl, resolvedTarget), \"clone\");\n return { status: \"cloned\", targetDir: resolvedTarget };\n }\n\n if (!targetStat.isDirectory()) {\n throw new Error(\"Bootstrap target exists and is not a directory.\");\n }\n\n if (await isGitCheckout(resolvedTarget)) {\n const originUrl = await runGit([\"-C\", resolvedTarget, \"remote\", \"get-url\", \"origin\"], \"remote\");\n if (!repositoryCloneUrlsMatch(repoUrl, originUrl)) {\n throw new Error(\"Bootstrap target is a Git checkout for a different repository.\");\n }\n return { status: \"validated\", targetDir: resolvedTarget, originUrl };\n }\n\n const entries = await readdir(resolvedTarget);\n if (entries.length > 0) {\n throw new Error(\"Bootstrap target exists, is not empty, and is not the linked repository checkout.\");\n }\n\n await runGit(buildGitCloneArgs(repoUrl, resolvedTarget), \"clone\");\n return { status: \"cloned\", targetDir: resolvedTarget };\n}\n\nasync function isGitCheckout(targetDir: string): Promise<boolean> {\n try {\n const result = await runGit([\"-C\", targetDir, \"rev-parse\", \"--is-inside-work-tree\"], \"rev-parse\");\n return result.trim() === \"true\";\n } catch {\n return false;\n }\n}\n\nasync function runGit(args: string[], operation: \"clone\" | \"remote\" | \"rev-parse\"): Promise<string> {\n try {\n const { stdout } = await execFileAsync(\"git\", args, { maxBuffer: 1024 * 1024 });\n return stdout.trim();\n } catch {\n if (operation === \"clone\") {\n throw new Error(\"git clone failed. Confirm local Git credentials can access the repository.\");\n }\n if (operation === \"remote\") {\n throw new Error(\"Could not read the target checkout origin remote.\");\n }\n throw new Error(\"Could not inspect the target Git checkout.\");\n }\n}\n\nfunction isNotFoundError(error: unknown): boolean {\n return Boolean(error && typeof error === \"object\" && \"code\" in error && error.code === \"ENOENT\");\n}", "import { chmod, mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\ninterface StoredCredentialFile {\n credentials: Record<string, string>;\n}\n\nexport class LocalCredentialStore {\n constructor(private readonly filePath = path.join(os.homedir(), \".config\", \"amistio\", \"credentials.json\")) { }\n\n async set(key: string, value: string): Promise<void> {\n const data = await this.read();\n data.credentials[key] = value;\n await mkdir(path.dirname(this.filePath), { recursive: true });\n await writeFile(this.filePath, JSON.stringify(data, null, 2), { encoding: \"utf8\", mode: 0o600 });\n await chmod(this.filePath, 0o600);\n }\n\n async get(key: string): Promise<string | undefined> {\n const data = await this.read();\n return data.credentials[key];\n }\n\n async delete(key: string): Promise<void> {\n const data = await this.read();\n if (!(key in data.credentials)) {\n return;\n }\n delete data.credentials[key];\n await mkdir(path.dirname(this.filePath), { recursive: true });\n await writeFile(this.filePath, JSON.stringify(data, null, 2), { encoding: \"utf8\", mode: 0o600 });\n await chmod(this.filePath, 0o600);\n }\n\n private async read(): Promise<StoredCredentialFile> {\n try {\n return JSON.parse(await readFile(this.filePath, \"utf8\")) as StoredCredentialFile;\n } catch {\n return { credentials: {} };\n }\n }\n}\n\nexport function credentialKey(accountId: string, projectId: string, repositoryLinkId: string): string {\n return `${accountId}:${projectId}:${repositoryLinkId}`;\n}", "import { execFile } from \"node:child_process\";\nimport { mkdir, readFile, stat, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { createProjectLinkMarkdown, repoLinkMetadataSchema, type RepoLinkMetadata } from \"@amistio/shared\";\n\nconst execFileAsync = promisify(execFile);\n\nexport const controlPlaneFolders = [\n path.join(\"docs\", \"architecture\"),\n path.join(\"docs\", \"context\"),\n path.join(\"docs\", \"decisions\"),\n path.join(\"docs\", \"features\"),\n path.join(\"docs\", \"memory\"),\n path.join(\"docs\", \"plans\"),\n path.join(\"docs\", \"prompts\", \"shared\"),\n path.join(\"docs\", \"workflows\")\n] as const;\n\nexport async function initControlPlane(rootDir: string): Promise<string[]> {\n const created: string[] = [];\n\n for (const folder of controlPlaneFolders) {\n const fullPath = path.join(rootDir, folder);\n if (!(await exists(fullPath))) {\n await mkdir(fullPath, { recursive: true });\n created.push(folder);\n }\n }\n\n await writeIfMissing(\n path.join(rootDir, \"AGENTS.md\"),\n \"# Agents\\n\\nThe docs/ control-plane folders are the project brain. Keep docs/architecture, docs/context, docs/decisions, docs/features, docs/memory, docs/plans, docs/prompts, and docs/workflows in sync with product intent.\\n\"\n );\n await writeIfMissing(path.join(rootDir, \"docs\", \"context\", \"product.md\"), \"# Product Context\\n\\nDescribe the product direction here.\\n\");\n await writeIfMissing(path.join(rootDir, \"docs\", \"architecture\", \"overview.md\"), \"# Architecture Overview\\n\\nDescribe the system shape here.\\n\");\n\n return created;\n}\n\nexport async function inspectControlPlane(rootDir: string): Promise<{ present: string[]; missing: string[] }> {\n const present: string[] = [];\n const missing: string[] = [];\n\n for (const folder of controlPlaneFolders) {\n if (await exists(path.join(rootDir, folder))) {\n present.push(folder);\n } else {\n missing.push(folder);\n }\n }\n\n return { present, missing };\n}\n\nexport async function writeProjectLink(rootDir: string, metadata: RepoLinkMetadata): Promise<string> {\n const contextDir = path.join(rootDir, \"docs\", \"context\");\n await mkdir(contextDir, { recursive: true });\n const filePath = path.join(contextDir, \"amistio-project.md\");\n await writeFile(filePath, createProjectLinkMarkdown(metadata), \"utf8\");\n return filePath;\n}\n\nexport async function resolvePairingRoot(rootDir: string, options: { explicitRoot?: boolean } = {}): Promise<string> {\n const requestedRoot = path.resolve(rootDir);\n const gitRoot = await readGitTopLevel(requestedRoot).catch(() => undefined);\n if (gitRoot) {\n return gitRoot;\n }\n if (options.explicitRoot) {\n return requestedRoot;\n }\n throw new Error(\"Run `amistio pair` from inside the repository checkout, or pass --root <repo-root> explicitly.\");\n}\n\nexport async function readProjectLink(rootDir: string): Promise<RepoLinkMetadata | undefined> {\n const candidatePaths = [\n path.join(rootDir, \"docs\", \"context\", \"amistio-project.md\"),\n path.join(rootDir, \"context\", \"amistio-project.md\")\n ];\n\n for (const filePath of candidatePaths) {\n if (!(await exists(filePath))) {\n continue;\n }\n\n const content = await readFile(filePath, \"utf8\");\n const frontmatter = parseFrontmatter(content);\n return repoLinkMetadataSchema.parse(frontmatter);\n }\n\n return undefined;\n}\n\nexport function parseFrontmatter(content: string): Record<string, string> {\n if (!content.startsWith(\"---\\n\")) {\n return {};\n }\n\n const end = content.indexOf(\"\\n---\", 4);\n if (end === -1) {\n return {};\n }\n\n const lines = content.slice(4, end).split(\"\\n\");\n return Object.fromEntries(\n lines\n .map((line) => {\n const separator = line.indexOf(\":\");\n if (separator === -1) {\n return undefined;\n }\n return [line.slice(0, separator).trim(), line.slice(separator + 1).trim()] as const;\n })\n .filter((entry): entry is readonly [string, string] => Boolean(entry))\n );\n}\n\nasync function writeIfMissing(filePath: string, content: string): Promise<void> {\n if (await exists(filePath)) {\n return;\n }\n await writeFile(filePath, content, \"utf8\");\n}\n\nasync function exists(filePath: string): Promise<boolean> {\n try {\n await stat(filePath);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function readGitTopLevel(rootDir: string): Promise<string> {\n const { stdout } = await execFileAsync(\"git\", [\"-C\", rootDir, \"rev-parse\", \"--show-toplevel\"], { maxBuffer: 1024 * 1024 });\n const gitRoot = stdout.trim();\n if (!gitRoot) {\n throw new Error(\"Git top-level path was empty.\");\n }\n return path.resolve(gitRoot);\n}", "import {\n activityEventItemSchema,\n appEvaluationFindingItemSchema,\n appEvaluationScanItemSchema,\n assistantMessageItemSchema,\n brainConsolidationProposalItemSchema,\n brainConsolidationScanItemSchema,\n brainDocumentItemSchema,\n generatedDraftItemSchema,\n implementationVerificationItemSchema,\n issueItemSchema,\n impactReportItemSchema,\n planReviewMessageItemSchema,\n contextMissItemSchema,\n projectContextMapItemSchema,\n projectContextPackSchema,\n projectContextRefreshItemSchema,\n repositoryLinkItemSchema,\n implementationTestGateItemSchema,\n runnerInvocationChannelSchema,\n runnerReasoningEffortSchema,\n runnerPreferenceSourceSchema,\n runnerCommandItemSchema,\n runnerExecutionLogItemSchema,\n runnerHeartbeatItemSchema,\n runnerSettingsItemSchema,\n securityFindingItemSchema,\n securityPostureScanResultSchema,\n securityPostureSnapshotItemSchema,\n securityScanItemSchema,\n testQualityFindingItemSchema,\n testQualityScanItemSchema,\n runnerToolSelectionSchema,\n type AppEvaluationFindingItem,\n type AppEvaluationScanItem,\n type AppEvaluationScanResult,\n type BrainDocumentItem,\n type ActivityEventItem,\n type AssistantAnswerResult,\n type AssistantMessageItem,\n type BrainConsolidationProposalItem,\n type BrainConsolidationScanItem,\n type BrainConsolidationScanResult,\n type GeneratedBrainArtifact,\n type GeneratedDraftItem,\n type ImplementationHandoff,\n type ImplementationTestGateItem,\n type ImplementationTestGateResult,\n type ImplementationVerificationItem,\n type ImplementationVerificationResult,\n type IssueDiagnosisResult,\n type IssueItem,\n type ImpactPreviewResult,\n type ImpactReportItem,\n type RepositoryLinkItem,\n type RunnerCommandItem,\n type RunnerExecutionLogItem,\n sessionDecisionSchema,\n sessionPolicySchema,\n sessionResumabilityScopeSchema,\n toolSessionItemSchema,\n toolSessionStatusSchema,\n workIsolationModeSchema,\n workItemSchema,\n type ExecutionMode,\n type RunnerHeartbeatItem,\n type PlanReviewMessageItem,\n type ProjectContextMapItem,\n type ProjectContextPack,\n type ProjectContextRefreshItem,\n type ProjectContextRefreshResult,\n type ContextMissItem,\n type RunnerPreferenceSource,\n type RunnerPreferenceStatus,\n type RunnerCommandStatus,\n type RunnerEffectiveInvocationChannel,\n type RunnerSettingsItem,\n type SecurityFindingItem,\n type SecurityPostureScanResult,\n type SecurityPostureSnapshotItem,\n type SecurityScanItem,\n type TestQualityFindingItem,\n type TestQualityScanItem,\n type TestQualityScanResult,\n type RunnerInvocationChannel,\n type RunnerReasoningEffort,\n type RunnerResourceUsage,\n type RunnerToolCapability,\n type RunnerToolModelPreference,\n type RunnerToolName,\n type RunnerToolSelection,\n type SessionDecision,\n type SessionPolicy,\n type SessionResumabilityScope,\n type ToolSessionItem,\n type WorkItem,\n type WorkKind,\n type WorkStatus\n} from \"@amistio/shared\";\nimport { z } from \"zod\";\n\nexport interface ApiClientOptions {\n apiUrl: string;\n accountId?: string;\n token?: string;\n}\n\nexport class AmistioApiError extends Error {\n constructor(readonly status: number, readonly statusText: string, readonly detail: string) {\n super(`Amistio API request failed: ${status} ${statusText}${detail ? ` - ${detail}` : \"\"}`);\n this.name = \"AmistioApiError\";\n }\n}\n\nexport function isRetryableApiError(error: unknown): boolean {\n if (error instanceof AmistioApiError) {\n return error.status === 408 || error.status === 429 || error.status >= 500;\n }\n return error instanceof TypeError;\n}\n\nexport interface ImportPairingInput {\n pairingCode: string;\n repoName: string;\n repoFingerprint: string;\n defaultBranch: string;\n machineId?: string;\n cloneUrl?: string;\n provider?: string;\n repoOwner?: string;\n repoFullName?: string;\n}\n\nexport interface ImportPairingResponse {\n accountId: string;\n projectId: string;\n repositoryLink: RepositoryLinkItem;\n repositoryLinkAction: \"created\" | \"reused\";\n token: string;\n}\n\nexport interface WorkStatusTelemetry {\n executionMode?: ExecutionMode;\n message?: string;\n tool?: string;\n model?: string;\n durationMs?: number;\n costUsd?: number;\n tokensIn?: number;\n tokensOut?: number;\n sessionPolicy?: SessionPolicy;\n sessionGroupKey?: string;\n toolSessionId?: string;\n sessionDecision?: SessionDecision;\n sessionDecisionReason?: string;\n pairedByUserId?: string;\n machineId?: string;\n claimLaneId?: string;\n claimLeaseId?: string;\n controllingAdrId?: string;\n implementationScopeId?: string;\n executionBranch?: string;\n executionWorktreeKey?: string;\n isolationMode?: WorkItem[\"isolationMode\"];\n repositoryLockId?: string;\n baseRevision?: string;\n baseContentHash?: string;\n blockerReason?: string;\n leaseExpiresAt?: string;\n releaseClaim?: boolean;\n error?: string;\n implementationHandoff?: ImplementationHandoff;\n}\n\nexport type BrainGenerationResultMutation =\n | {\n status: \"completed\";\n runnerId: string;\n idempotencyKey: string;\n artifacts: GeneratedBrainArtifact[];\n tool?: string;\n durationMs?: number;\n sessionPolicy?: SessionPolicy;\n sessionGroupKey?: string;\n toolSessionId?: string;\n sessionDecision?: SessionDecision;\n sessionDecisionReason?: string;\n message?: string;\n }\n | {\n status: \"failed\";\n runnerId: string;\n idempotencyKey: string;\n tool?: string;\n durationMs?: number;\n sessionPolicy?: SessionPolicy;\n sessionGroupKey?: string;\n toolSessionId?: string;\n sessionDecision?: SessionDecision;\n sessionDecisionReason?: string;\n message?: string;\n error?: string;\n };\n\nexport type AssistantResultMutation =\n | {\n status: \"completed\";\n runnerId: string;\n idempotencyKey: string;\n answer: string;\n sourceBoundary?: AssistantAnswerResult[\"sourceBoundary\"];\n citations?: AssistantAnswerResult[\"citations\"];\n tool?: string;\n durationMs?: number;\n sessionPolicy?: SessionPolicy;\n sessionGroupKey?: string;\n toolSessionId?: string;\n sessionDecision?: SessionDecision;\n sessionDecisionReason?: string;\n message?: string;\n }\n | {\n status: \"failed\";\n runnerId: string;\n idempotencyKey: string;\n tool?: string;\n durationMs?: number;\n sessionPolicy?: SessionPolicy;\n sessionGroupKey?: string;\n toolSessionId?: string;\n sessionDecision?: SessionDecision;\n sessionDecisionReason?: string;\n message?: string;\n error?: string;\n };\n\nexport type ImpactPreviewResultMutation =\n | {\n status: \"completed\";\n runnerId: string;\n idempotencyKey: string;\n report: ImpactPreviewResult;\n tool?: string;\n durationMs?: number;\n sessionPolicy?: SessionPolicy;\n sessionGroupKey?: string;\n toolSessionId?: string;\n sessionDecision?: SessionDecision;\n sessionDecisionReason?: string;\n message?: string;\n }\n | {\n status: \"failed\";\n runnerId: string;\n idempotencyKey: string;\n tool?: string;\n durationMs?: number;\n sessionPolicy?: SessionPolicy;\n sessionGroupKey?: string;\n toolSessionId?: string;\n sessionDecision?: SessionDecision;\n sessionDecisionReason?: string;\n message?: string;\n error?: string;\n };\n\nexport type IssueDiagnosisResultMutation =\n | {\n status: \"completed\";\n runnerId: string;\n idempotencyKey: string;\n diagnosis: IssueDiagnosisResult;\n tool?: string;\n durationMs?: number;\n sessionPolicy?: SessionPolicy;\n sessionGroupKey?: string;\n toolSessionId?: string;\n sessionDecision?: SessionDecision;\n sessionDecisionReason?: string;\n message?: string;\n }\n | {\n status: \"failed\";\n runnerId: string;\n idempotencyKey: string;\n tool?: string;\n durationMs?: number;\n sessionPolicy?: SessionPolicy;\n sessionGroupKey?: string;\n toolSessionId?: string;\n sessionDecision?: SessionDecision;\n sessionDecisionReason?: string;\n message?: string;\n error?: string;\n };\n\nexport type SecurityPostureScanResultMutation =\n | {\n status: \"completed\";\n runnerId: string;\n idempotencyKey: string;\n result: SecurityPostureScanResult;\n tool?: string;\n durationMs?: number;\n sessionPolicy?: SessionPolicy;\n sessionGroupKey?: string;\n toolSessionId?: string;\n sessionDecision?: SessionDecision;\n sessionDecisionReason?: string;\n message?: string;\n }\n | {\n status: \"failed\";\n runnerId: string;\n idempotencyKey: string;\n tool?: string;\n durationMs?: number;\n sessionPolicy?: SessionPolicy;\n sessionGroupKey?: string;\n toolSessionId?: string;\n sessionDecision?: SessionDecision;\n sessionDecisionReason?: string;\n message?: string;\n error?: string;\n };\n\nexport type AppEvaluationScanResultMutation =\n | {\n status: \"completed\";\n runnerId: string;\n idempotencyKey: string;\n result: AppEvaluationScanResult;\n tool?: string;\n durationMs?: number;\n sessionPolicy?: SessionPolicy;\n sessionGroupKey?: string;\n toolSessionId?: string;\n sessionDecision?: SessionDecision;\n sessionDecisionReason?: string;\n message?: string;\n }\n | {\n status: \"failed\";\n runnerId: string;\n idempotencyKey: string;\n tool?: string;\n durationMs?: number;\n sessionPolicy?: SessionPolicy;\n sessionGroupKey?: string;\n toolSessionId?: string;\n sessionDecision?: SessionDecision;\n sessionDecisionReason?: string;\n message?: string;\n error?: string;\n };\n\nexport type BrainConsolidationScanResultMutation =\n | {\n status: \"completed\";\n runnerId: string;\n idempotencyKey: string;\n result: BrainConsolidationScanResult;\n tool?: string;\n durationMs?: number;\n sessionPolicy?: SessionPolicy;\n sessionGroupKey?: string;\n toolSessionId?: string;\n sessionDecision?: SessionDecision;\n sessionDecisionReason?: string;\n message?: string;\n }\n | {\n status: \"failed\";\n runnerId: string;\n idempotencyKey: string;\n tool?: string;\n durationMs?: number;\n sessionPolicy?: SessionPolicy;\n sessionGroupKey?: string;\n toolSessionId?: string;\n sessionDecision?: SessionDecision;\n sessionDecisionReason?: string;\n message?: string;\n error?: string;\n };\n\nexport type ProjectContextRefreshResultMutation =\n | {\n status: \"completed\";\n runnerId: string;\n idempotencyKey: string;\n result: ProjectContextRefreshResult;\n tool?: string;\n durationMs?: number;\n sessionPolicy?: SessionPolicy;\n sessionGroupKey?: string;\n toolSessionId?: string;\n sessionDecision?: SessionDecision;\n sessionDecisionReason?: string;\n message?: string;\n }\n | {\n status: \"failed\";\n runnerId: string;\n idempotencyKey: string;\n tool?: string;\n durationMs?: number;\n sessionPolicy?: SessionPolicy;\n sessionGroupKey?: string;\n toolSessionId?: string;\n sessionDecision?: SessionDecision;\n sessionDecisionReason?: string;\n message?: string;\n error?: string;\n };\n\nexport type ImplementationVerificationResultMutation =\n | {\n status: \"completed\";\n runnerId: string;\n idempotencyKey: string;\n result: ImplementationVerificationResult;\n tool?: string;\n durationMs?: number;\n sessionPolicy?: SessionPolicy;\n sessionGroupKey?: string;\n toolSessionId?: string;\n sessionDecision?: SessionDecision;\n sessionDecisionReason?: string;\n message?: string;\n }\n | {\n status: \"failed\";\n runnerId: string;\n idempotencyKey: string;\n tool?: string;\n durationMs?: number;\n sessionPolicy?: SessionPolicy;\n sessionGroupKey?: string;\n toolSessionId?: string;\n sessionDecision?: SessionDecision;\n sessionDecisionReason?: string;\n message?: string;\n error?: string;\n };\n\nexport type TestQualityScanResultMutation =\n | {\n status: \"completed\";\n runnerId: string;\n idempotencyKey: string;\n result: TestQualityScanResult;\n tool?: string;\n durationMs?: number;\n sessionPolicy?: SessionPolicy;\n sessionGroupKey?: string;\n toolSessionId?: string;\n sessionDecision?: SessionDecision;\n sessionDecisionReason?: string;\n message?: string;\n }\n | {\n status: \"failed\";\n runnerId: string;\n idempotencyKey: string;\n tool?: string;\n durationMs?: number;\n sessionPolicy?: SessionPolicy;\n sessionGroupKey?: string;\n toolSessionId?: string;\n sessionDecision?: SessionDecision;\n sessionDecisionReason?: string;\n message?: string;\n error?: string;\n };\n\nexport type ImplementationTestGateResultMutation =\n | {\n status: \"completed\";\n runnerId: string;\n idempotencyKey: string;\n result: ImplementationTestGateResult;\n tool?: string;\n durationMs?: number;\n sessionPolicy?: SessionPolicy;\n sessionGroupKey?: string;\n toolSessionId?: string;\n sessionDecision?: SessionDecision;\n sessionDecisionReason?: string;\n message?: string;\n }\n | {\n status: \"failed\";\n runnerId: string;\n idempotencyKey: string;\n tool?: string;\n durationMs?: number;\n sessionPolicy?: SessionPolicy;\n sessionGroupKey?: string;\n toolSessionId?: string;\n sessionDecision?: SessionDecision;\n sessionDecisionReason?: string;\n message?: string;\n error?: string;\n };\n\nexport interface ProjectContextResponse {\n maps: ProjectContextMapItem[];\n refreshes: ProjectContextRefreshItem[];\n misses: ContextMissItem[];\n activeMap?: ProjectContextMapItem | undefined;\n}\n\nexport type ProjectContextPackResponse = ProjectContextPack;\n\nexport interface ToolSessionMutation {\n toolSessionId?: string;\n repositoryLinkId?: string;\n tool?: string;\n provider?: string;\n model?: string;\n resumabilityScope?: SessionResumabilityScope;\n title?: string;\n summary?: string;\n tags?: string[];\n relatedDocumentIds?: string[];\n status?: ToolSessionItem[\"status\"];\n createdByUserId?: string;\n runnerId?: string;\n lastWorkItemId?: string;\n messageCount?: number;\n estimatedInputTokens?: number;\n estimatedOutputTokens?: number;\n costUsd?: number;\n sessionGroupKey?: string;\n reusePolicy?: SessionPolicy;\n closedReason?: string;\n machineId?: string;\n implementationScopeId?: string;\n executionWorktreeKey?: string;\n isolationMode?: ToolSessionItem[\"isolationMode\"];\n}\n\nexport interface ActivityEventMutation {\n eventType: \"runnerMilestone\";\n status: \"running\" | \"completed\" | \"failed\" | \"blocked\" | \"warning\" | \"info\" | \"queued\";\n summary: string;\n idempotencyKey: string;\n metadata?: Record<string, unknown>;\n relatedWorkItemId?: string;\n relatedDocumentId?: string;\n relatedIssueId?: string;\n relatedAutopilotAuthorizationId?: string;\n relatedAutopilotCandidateId?: string;\n generatedDraftId?: string;\n runnerId?: string;\n repositoryLinkId?: string;\n claimLaneId?: string;\n}\n\nexport type RunnerHeartbeatStatus = \"online\" | \"offline\" | \"running\" | \"blocked\";\n\nexport type RunnerCommandUpdateStatus = Extract<RunnerCommandStatus, \"acknowledged\" | \"running\" | \"completed\" | \"failed\">;\n\nexport interface RunnerHeartbeatMetadata {\n version?: string;\n mode?: \"foreground\" | \"background\";\n hostname?: string;\n runnerName?: string;\n machineId?: string;\n supportedWorkKinds?: WorkKind[];\n supportsBranchIsolation?: boolean;\n supportsGitWorktreeIsolation?: boolean;\n maxConcurrentWork?: number;\n activeClaimLaneIds?: string[];\n currentWorkItemId?: string;\n currentImplementationScopeId?: string;\n currentWorktreeKey?: string;\n currentBranch?: string;\n capabilities?: RunnerToolCapability[];\n requestedTool?: RunnerToolSelection;\n requestedInvocationChannel?: RunnerInvocationChannel;\n requestedProviderId?: string;\n requestedModelId?: string;\n requestedModelVariant?: string;\n requestedReasoningEffort?: RunnerReasoningEffort;\n effectiveTool?: RunnerToolName | \"custom\";\n effectiveInvocationChannel?: RunnerEffectiveInvocationChannel;\n effectiveModel?: string;\n effectiveProviderId?: string;\n effectiveModelId?: string;\n effectiveModelVariant?: string;\n effectiveReasoningEffort?: RunnerReasoningEffort;\n preferenceSource?: RunnerPreferenceSource;\n preferenceStatus?: RunnerPreferenceStatus;\n preferenceMessage?: string;\n resourceUsage?: RunnerResourceUsage;\n autoSyncStatus?: \"disabled\" | \"enabledInactive\" | \"active\" | \"synced\" | \"failed\" | \"blocked\" | \"conflicted\";\n autoSyncMessage?: string;\n autoSyncLastStartedAt?: string;\n autoSyncLastSuccessAt?: string;\n autoSyncLastFailureAt?: string;\n autoSyncPushedCount?: number;\n autoSyncSkippedCount?: number;\n autoSyncConflictCount?: number;\n}\n\nexport interface RunnerLogMutation {\n runnerId: string;\n repositoryLinkId: string;\n status: RunnerExecutionLogItem[\"status\"];\n message?: string;\n error?: string;\n workItemId?: string;\n workTitle?: string;\n workKind?: RunnerExecutionLogItem[\"workKind\"];\n tool?: string;\n model?: string;\n durationMs?: number;\n machineId?: string;\n claimLaneId?: string;\n implementationHandoff?: ImplementationHandoff;\n}\n\nexport interface RunnerPreferencesResponse {\n account?: RunnerSettingsItem;\n project?: RunnerSettingsItem;\n effective: RunnerToolModelPreference & { tool: RunnerToolSelection; invocationChannel: RunnerInvocationChannel; source: RunnerPreferenceSource };\n}\n\nexport class ApiClient {\n constructor(private readonly options: ApiClientOptions) { }\n\n async createPairingSession(projectId: string): Promise<{ pairingCode: string; expiresAt: string }> {\n return this.request(\n \"pairing-sessions\",\n z.object({ pairingCode: z.string(), expiresAt: z.string() }),\n {\n method: \"POST\",\n body: JSON.stringify({ projectId })\n }\n );\n }\n\n async consumePairingSession(input: { projectId: string; pairingCode: string; repositoryLinkId: string; repoName: string; repoFingerprint: string; defaultBranch: string; machineId?: string }): Promise<{ repositoryLink: RepositoryLinkItem; token: string }> {\n return this.request(\n \"pairing-sessions\",\n z.object({ repositoryLink: repositoryLinkItemSchema, token: z.string().min(1) }),\n {\n method: \"PATCH\",\n body: JSON.stringify(input)\n }\n );\n }\n\n async importPairingSession(input: ImportPairingInput): Promise<ImportPairingResponse> {\n return this.request(\n \"pairing-sessions\",\n z.object({\n accountId: z.string().min(1),\n projectId: z.string().min(1),\n repositoryLink: repositoryLinkItemSchema,\n repositoryLinkAction: z.enum([\"created\", \"reused\"]),\n token: z.string().min(1)\n }),\n {\n method: \"PATCH\",\n body: JSON.stringify(input)\n }\n );\n }\n\n async claimWork(projectId: string, runnerId: string, repositoryLinkId: string, leaseSeconds = 300, metadata: Pick<RunnerHeartbeatMetadata, \"machineId\" | \"supportedWorkKinds\" | \"supportsBranchIsolation\" | \"supportsGitWorktreeIsolation\" | \"maxConcurrentWork\"> & { claimLaneId?: string } = {}): Promise<{ workItem: WorkItem | undefined }> {\n return this.request(\n `/projects/${projectId}/work-items/claim`,\n z.object({ workItem: workItemSchema.optional() }).transform(({ workItem }) => ({ workItem })),\n {\n method: \"POST\",\n body: JSON.stringify({ runnerId, repositoryLinkId, leaseSeconds, ...metadata })\n }\n );\n }\n\n async listWorkItems(projectId: string): Promise<{ workItems: WorkItem[] }> {\n return this.request(\n `/projects/${projectId}/work-items`,\n z.object({ workItems: z.array(workItemSchema) }),\n { method: \"GET\" }\n );\n }\n\n async listBrainDocuments(projectId: string): Promise<{ documents: BrainDocumentItem[] }> {\n return this.request(\n `/projects/${projectId}/brain-documents`,\n z.object({ documents: z.array(brainDocumentItemSchema) }),\n { method: \"GET\" }\n );\n }\n\n async listRepositoryLinks(projectId: string): Promise<{ repositoryLinks: RepositoryLinkItem[] }> {\n return this.request(\n `/projects/${projectId}/repository-links`,\n z.object({ repositoryLinks: z.array(repositoryLinkItemSchema) }),\n { method: \"GET\" }\n );\n }\n\n async listPlanReviewMessages(projectId: string, documentId?: string): Promise<{ messages: PlanReviewMessageItem[] }> {\n const suffix = documentId ? `?documentId=${encodeURIComponent(documentId)}` : \"\";\n return this.request(\n `/projects/${projectId}/plan-review-messages${suffix}`,\n z.object({ messages: z.array(planReviewMessageItemSchema) }),\n { method: \"GET\" }\n );\n }\n\n async listAssistantMessages(projectId: string): Promise<{ messages: AssistantMessageItem[] }> {\n return this.request(\n `/projects/${projectId}/assistant-messages`,\n z.object({ messages: z.array(assistantMessageItemSchema) }),\n { method: \"GET\" }\n );\n }\n\n async listImpactReports(projectId: string, generatedDraftId?: string): Promise<{ reports: ImpactReportItem[] }> {\n const query = generatedDraftId ? `?generatedDraftId=${encodeURIComponent(generatedDraftId)}` : \"\";\n return this.request(\n `/projects/${projectId}/impact-reports${query}`,\n z.object({ reports: z.array(impactReportItemSchema) }),\n { method: \"GET\" }\n );\n }\n\n async listIssues(projectId: string): Promise<{ issues: IssueItem[] }> {\n return this.request(\n `/projects/${projectId}/issues`,\n z.object({ issues: z.array(issueItemSchema) }),\n { method: \"GET\" }\n );\n }\n\n async listProjectContext(projectId: string): Promise<ProjectContextResponse> {\n return this.request(\n `/projects/${projectId}/project-context`,\n z.object({\n maps: z.array(projectContextMapItemSchema),\n refreshes: z.array(projectContextRefreshItemSchema),\n misses: z.array(contextMissItemSchema),\n activeMap: projectContextMapItemSchema.optional()\n }),\n { method: \"GET\" }\n );\n }\n\n async buildProjectContextPack(projectId: string, query: string, workItemId?: string): Promise<ProjectContextPackResponse> {\n const params = new URLSearchParams({ packQuery: query });\n if (workItemId) params.set(\"workItemId\", workItemId);\n return this.request(\n `/projects/${projectId}/project-context?${params.toString()}`,\n projectContextPackSchema,\n { method: \"GET\" }\n );\n }\n\n async pushBrainDocuments(projectId: string, documents: BrainDocumentItem[]): Promise<{ documents: BrainDocumentItem[] }> {\n return this.request(\n `/projects/${projectId}/brain-documents`,\n z.object({ documents: z.array(brainDocumentItemSchema) }),\n {\n method: \"POST\",\n body: JSON.stringify({ documents })\n }\n );\n }\n\n async listRunners(projectId: string): Promise<{ runners: RunnerHeartbeatItem[] }> {\n return this.request(\n `/projects/${projectId}/runners`,\n z.object({ runners: z.array(runnerHeartbeatItemSchema) }),\n { method: \"GET\" }\n );\n }\n\n async listRunnerCommands(projectId: string, runnerId: string, repositoryLinkId: string): Promise<{ commands: RunnerCommandItem[] }> {\n return this.request(\n `/projects/${projectId}/runner-commands?runnerId=${encodeURIComponent(runnerId)}&repositoryLinkId=${encodeURIComponent(repositoryLinkId)}`,\n z.object({ commands: z.array(runnerCommandItemSchema) }),\n { method: \"GET\" }\n );\n }\n\n async updateRunnerCommand(projectId: string, commandId: string, input: { runnerId: string; repositoryLinkId: string; status: RunnerCommandUpdateStatus; idempotencyKey: string; message?: string; error?: string }): Promise<{ command: RunnerCommandItem }> {\n return this.request(\n `/projects/${projectId}/runner-commands/${commandId}`,\n z.object({ command: runnerCommandItemSchema }),\n {\n method: \"PATCH\",\n body: JSON.stringify(input)\n }\n );\n }\n\n async getRunnerPreferences(projectId: string): Promise<RunnerPreferencesResponse> {\n const response = await this.request(\n `/projects/${projectId}/runner-preferences`,\n z.object({\n account: runnerSettingsItemSchema.optional(),\n project: runnerSettingsItemSchema.optional(),\n effective: z.object({\n tool: runnerToolSelectionSchema,\n invocationChannel: runnerInvocationChannelSchema,\n model: z.string().optional(),\n providerId: z.string().optional(),\n modelId: z.string().optional(),\n modelVariant: z.string().optional(),\n reasoningEffort: runnerReasoningEffortSchema.optional(),\n source: runnerPreferenceSourceSchema\n })\n }),\n { method: \"GET\" }\n );\n return {\n ...(response.account ? { account: response.account } : {}),\n ...(response.project ? { project: response.project } : {}),\n effective: response.effective\n };\n }\n\n async sendRunnerHeartbeat(projectId: string, runnerId: string, repositoryLinkId: string, status: RunnerHeartbeatStatus, metadata?: string | RunnerHeartbeatMetadata): Promise<{ runner: RunnerHeartbeatItem }> {\n const heartbeatMetadata = typeof metadata === \"string\" ? { version: metadata } : metadata ?? {};\n return this.request(\n `/projects/${projectId}/runners`,\n z.object({ runner: runnerHeartbeatItemSchema }),\n {\n method: \"POST\",\n body: JSON.stringify({ runnerId, repositoryLinkId, status, ...heartbeatMetadata, lastSeenAt: new Date().toISOString() })\n }\n );\n }\n\n async recordRunnerLog(projectId: string, input: RunnerLogMutation): Promise<{ runnerLog: RunnerExecutionLogItem }> {\n return this.request(\n `/projects/${projectId}/runner-logs`,\n z.object({ runnerLog: runnerExecutionLogItemSchema }),\n {\n method: \"POST\",\n body: JSON.stringify(input)\n }\n );\n }\n\n async listToolSessions(projectId: string): Promise<{ toolSessions: ToolSessionItem[] }> {\n return this.request(\n `/projects/${projectId}/tool-sessions`,\n z.object({ toolSessions: z.array(toolSessionItemSchema) }),\n { method: \"GET\" }\n );\n }\n\n async createToolSession(projectId: string, session: Required<Pick<ToolSessionMutation, \"tool\" | \"title\">> & ToolSessionMutation): Promise<{ toolSession: ToolSessionItem }> {\n return this.request(\n `/projects/${projectId}/tool-sessions`,\n z.object({ toolSession: toolSessionItemSchema }),\n {\n method: \"POST\",\n body: JSON.stringify(session)\n }\n );\n }\n\n async updateToolSession(projectId: string, toolSessionId: string, session: ToolSessionMutation): Promise<{ toolSession: ToolSessionItem }> {\n return this.request(\n `/projects/${projectId}/tool-sessions/${toolSessionId}`,\n z.object({ toolSession: toolSessionItemSchema }),\n {\n method: \"PATCH\",\n body: JSON.stringify(session)\n }\n );\n }\n\n async recordActivityEvent(projectId: string, event: ActivityEventMutation): Promise<{ event: ActivityEventItem }> {\n return this.request(\n `/projects/${projectId}/activity-events`,\n z.object({ event: activityEventItemSchema }),\n {\n method: \"POST\",\n body: JSON.stringify(event)\n }\n );\n }\n\n async updateWorkStatus(projectId: string, workItemId: string, status: WorkStatus, idempotencyKey: string, runnerId?: string, telemetry: WorkStatusTelemetry = {}): Promise<{ workItem: WorkItem }> {\n return this.request(\n `/projects/${projectId}/work-items/${workItemId}/status`,\n z.object({ workItem: workItemSchema }),\n {\n method: \"PATCH\",\n body: JSON.stringify({ status, idempotencyKey, ...(runnerId ? { runnerId } : {}), ...telemetry })\n }\n );\n }\n\n async submitBrainGenerationResult(projectId: string, workItemId: string, result: BrainGenerationResultMutation): Promise<{ draft: GeneratedDraftItem; documents: BrainDocumentItem[]; workItem: WorkItem }> {\n return this.request(\n `/projects/${projectId}/work-items/${workItemId}/generation-result`,\n z.object({ draft: generatedDraftItemSchema, documents: z.array(brainDocumentItemSchema), workItem: workItemSchema }),\n {\n method: \"POST\",\n body: JSON.stringify(result)\n }\n );\n }\n\n async submitAssistantResult(projectId: string, workItemId: string, result: AssistantResultMutation): Promise<{ message: AssistantMessageItem; answer?: AssistantMessageItem | undefined; workItem: WorkItem }> {\n return this.request(\n `/projects/${projectId}/work-items/${workItemId}/assistant-result`,\n z.object({ message: assistantMessageItemSchema, answer: assistantMessageItemSchema.optional(), workItem: workItemSchema }),\n {\n method: \"POST\",\n body: JSON.stringify(result)\n }\n );\n }\n\n async submitImpactPreviewResult(projectId: string, workItemId: string, result: ImpactPreviewResultMutation): Promise<{ report: ImpactReportItem; workItem: WorkItem; implementationWorkItem?: WorkItem | undefined }> {\n return this.request(\n `/projects/${projectId}/work-items/${workItemId}/impact-result`,\n z.object({ report: impactReportItemSchema, workItem: workItemSchema, implementationWorkItem: workItemSchema.optional() }),\n {\n method: \"POST\",\n body: JSON.stringify(result)\n }\n );\n }\n\n async submitIssueDiagnosisResult(projectId: string, workItemId: string, result: IssueDiagnosisResultMutation): Promise<{ issue: IssueItem; workItem: WorkItem }> {\n return this.request(\n `/projects/${projectId}/work-items/${workItemId}/issue-result`,\n z.object({ issue: issueItemSchema, workItem: workItemSchema }),\n {\n method: \"POST\",\n body: JSON.stringify(result)\n }\n );\n }\n\n async submitSecurityPostureScanResult(projectId: string, workItemId: string, result: SecurityPostureScanResultMutation): Promise<{ scan: SecurityScanItem; findings: SecurityFindingItem[]; snapshot: SecurityPostureSnapshotItem; workItem: WorkItem }> {\n return this.request(\n `/projects/${projectId}/work-items/${workItemId}/security-result`,\n z.object({ scan: securityScanItemSchema, findings: z.array(securityFindingItemSchema), snapshot: securityPostureSnapshotItemSchema, workItem: workItemSchema }),\n {\n method: \"POST\",\n body: JSON.stringify(result)\n }\n );\n }\n\n async submitAppEvaluationScanResult(projectId: string, workItemId: string, result: AppEvaluationScanResultMutation): Promise<{ scan: AppEvaluationScanItem; findings: AppEvaluationFindingItem[]; workItem: WorkItem }> {\n return this.request(\n `/projects/${projectId}/work-items/${workItemId}/app-evaluation-result`,\n z.object({ scan: appEvaluationScanItemSchema, findings: z.array(appEvaluationFindingItemSchema), workItem: workItemSchema }),\n {\n method: \"POST\",\n body: JSON.stringify(result)\n }\n );\n }\n\n async submitBrainConsolidationScanResult(projectId: string, workItemId: string, result: BrainConsolidationScanResultMutation): Promise<{ scan: BrainConsolidationScanItem; proposals: BrainConsolidationProposalItem[]; autoArchivedDocuments: BrainDocumentItem[]; workItem: WorkItem }> {\n return this.request(\n `/projects/${projectId}/work-items/${workItemId}/brain-consolidation-result`,\n z.object({ scan: brainConsolidationScanItemSchema, proposals: z.array(brainConsolidationProposalItemSchema), autoArchivedDocuments: z.array(brainDocumentItemSchema), workItem: workItemSchema }),\n {\n method: \"POST\",\n body: JSON.stringify(result)\n }\n );\n }\n\n async submitProjectContextRefreshResult(projectId: string, workItemId: string, result: ProjectContextRefreshResultMutation): Promise<{ refresh: ProjectContextRefreshItem; map?: ProjectContextMapItem | undefined; workItem: WorkItem }> {\n return this.request(\n `/projects/${projectId}/work-items/${workItemId}/project-context-result`,\n z.object({ refresh: projectContextRefreshItemSchema, map: projectContextMapItemSchema.optional(), workItem: workItemSchema }),\n {\n method: \"POST\",\n body: JSON.stringify(result)\n }\n );\n }\n\n async submitImplementationVerificationResult(projectId: string, workItemId: string, result: ImplementationVerificationResultMutation): Promise<{ verification: ImplementationVerificationItem; workItem: WorkItem; sourceWorkItem?: WorkItem | undefined }> {\n return this.request(\n `/projects/${projectId}/work-items/${workItemId}/implementation-verification-result`,\n z.object({ verification: implementationVerificationItemSchema, workItem: workItemSchema, sourceWorkItem: workItemSchema.optional() }),\n {\n method: \"POST\",\n body: JSON.stringify(result)\n }\n );\n }\n\n async submitTestQualityScanResult(projectId: string, workItemId: string, result: TestQualityScanResultMutation): Promise<{ scan: TestQualityScanItem; findings: TestQualityFindingItem[]; workItem: WorkItem }> {\n return this.request(\n `/projects/${projectId}/work-items/${workItemId}/test-quality-result`,\n z.object({ scan: testQualityScanItemSchema, findings: z.array(testQualityFindingItemSchema), workItem: workItemSchema }),\n {\n method: \"POST\",\n body: JSON.stringify(result)\n }\n );\n }\n\n async submitImplementationTestGateResult(projectId: string, workItemId: string, result: ImplementationTestGateResultMutation): Promise<{ gate: ImplementationTestGateItem; findings: TestQualityFindingItem[]; workItem: WorkItem; sourceWorkItem?: WorkItem | undefined }> {\n return this.request(\n `/projects/${projectId}/work-items/${workItemId}/implementation-test-gate-result`,\n z.object({ gate: implementationTestGateItemSchema, findings: z.array(testQualityFindingItemSchema), workItem: workItemSchema, sourceWorkItem: workItemSchema.optional() }),\n {\n method: \"POST\",\n body: JSON.stringify(result)\n }\n );\n }\n\n private async request<T>(urlPath: string, schema: z.ZodSchema<T>, init: RequestInit): Promise<T> {\n const response = await fetch(resolveApiUrl(this.options.apiUrl, urlPath), {\n ...init,\n headers: {\n \"content-type\": \"application/json\",\n ...(this.options.accountId ? { \"x-amistio-account-id\": this.options.accountId } : {}),\n ...(this.options.token ? { authorization: `Bearer ${this.options.token}` } : {})\n }\n });\n\n if (!response.ok) {\n const detail = await response.text().catch(() => \"\");\n throw new AmistioApiError(response.status, response.statusText, detail);\n }\n\n return schema.parse(await response.json());\n }\n}\n\nexport const toolSessionMutationSchema = z.object({\n toolSessionId: z.string().min(1).optional(),\n repositoryLinkId: z.string().min(1).optional(),\n tool: z.string().min(1).optional(),\n provider: z.string().min(1).optional(),\n model: z.string().min(1).optional(),\n resumabilityScope: sessionResumabilityScopeSchema.optional(),\n title: z.string().min(1).optional(),\n summary: z.string().optional(),\n tags: z.array(z.string()).optional(),\n relatedDocumentIds: z.array(z.string()).optional(),\n status: toolSessionStatusSchema.optional(),\n createdByUserId: z.string().min(1).optional(),\n runnerId: z.string().min(1).optional(),\n lastWorkItemId: z.string().min(1).optional(),\n messageCount: z.number().int().nonnegative().optional(),\n estimatedInputTokens: z.number().int().nonnegative().optional(),\n estimatedOutputTokens: z.number().int().nonnegative().optional(),\n costUsd: z.number().nonnegative().optional(),\n sessionGroupKey: z.string().min(1).optional(),\n reusePolicy: sessionPolicySchema.optional(),\n sessionDecision: sessionDecisionSchema.optional(),\n closedReason: z.string().optional(),\n machineId: z.string().min(1).optional(),\n implementationScopeId: z.string().min(1).optional(),\n executionWorktreeKey: z.string().min(1).optional(),\n isolationMode: workIsolationModeSchema.optional()\n});\n\nfunction resolveApiUrl(apiUrl: string, urlPath: string): URL {\n const base = apiUrl.endsWith(\"/\") ? apiUrl.slice(0, -1) : apiUrl;\n const path = urlPath.startsWith(\"/\") ? urlPath : `/${urlPath}`;\n return new URL(`${base}${path}`);\n}\n", "import { mkdir, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { inspectControlPlane } from \"./control-plane.js\";\n\nexport interface OrchestrationPromptOptions {\n rootDir: string;\n goal: string;\n}\n\nexport async function createOrchestrationPrompt(options: OrchestrationPromptOptions): Promise<string> {\n const controlPlane = await inspectControlPlane(options.rootDir);\n return [\n \"# Amistio Orchestration Task\",\n \"\",\n \"You are running locally through the Amistio CLI inside the user's repository.\",\n \"Your job is to keep future agents on the same track by updating the Amistio control plane, not by rewriting the project from scratch.\",\n \"\",\n \"## Goal\",\n \"\",\n options.goal,\n \"\",\n \"## Orchestrator Principle\",\n \"\",\n \"The docs/ control-plane files are the project brain. They exist so agentic coding sessions can continue from established context, decisions, memory, plans, workflows, and prompts instead of drifting into a fresh interpretation each time.\",\n \"\",\n \"## Repository Rules\",\n \"\",\n \"- Read AGENTS.md first when it exists.\",\n \"- Read existing docs/architecture, docs/context, docs/decisions, docs/features, docs/memory, docs/plans, docs/prompts, and docs/workflows files before proposing changes.\",\n \"- Preserve existing intent. Add the next useful orchestration layer instead of replacing old content wholesale.\",\n \"- Prefer small additive edits, dated notes, explicit decisions, focused plans, and executable prompts.\",\n \"- Do not modify product source code unless the user's goal explicitly asks for implementation.\",\n \"- Do not create a repo-local .amistio folder.\",\n \"- Do not write access tokens, API keys, refresh tokens, local filesystem secrets, or machine-specific credentials into the repository.\",\n \"- Do not commit changes.\",\n \"\",\n \"## Control-Plane Areas\",\n \"\",\n \"- AGENTS.md for agent operating rules.\",\n \"- docs/architecture/**/*.md for system shape and boundaries.\",\n \"- docs/context/**/*.md for product, stack, and implementation context.\",\n \"- docs/decisions/**/*.md for ADRs and durable choices.\",\n \"- docs/features/**/*.md for behavior specs and acceptance criteria.\",\n \"- docs/memory/**/*.md for lessons, patterns, and known pitfalls.\",\n \"- docs/plans/**/*.md for near-term execution plans.\",\n \"- docs/prompts/**/*.md for model-agnostic implementation prompts.\",\n \"- docs/workflows/**/*.md for repeatable procedures.\",\n \"\",\n \"## Current Control-Plane Folder Status\",\n \"\",\n `Present: ${controlPlane.present.length ? controlPlane.present.join(\", \") : \"none\"}`,\n `Missing: ${controlPlane.missing.length ? controlPlane.missing.join(\", \") : \"none\"}`,\n \"\",\n \"## Expected Result\",\n \"\",\n \"- Update the smallest useful set of control-plane files needed to orient the next coding agent.\",\n \"- Record any new decision, plan, prompt, workflow, memory, or context that prevents future drift.\",\n \"- Keep old decisions visible. If something is superseded, say so explicitly instead of silently deleting it.\",\n \"- Summarize changed files, why they changed, and the recommended next agent action.\"\n ].join(\"\\n\");\n}\n\nexport async function writePromptFile(filePath: string, prompt: string): Promise<string> {\n await mkdir(path.dirname(filePath), { recursive: true });\n await writeFile(filePath, prompt, \"utf8\");\n return filePath;\n}", "import { createHash } from \"node:crypto\";\nimport { mkdir, readdir, readFile, rename, rm, writeFile } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { appEvaluationScanResultSchema, assistantAnswerResultSchema, brainConsolidationScanResultSchema, generatedBrainArtifactSchema, impactPreviewResultSchema, implementationTestGateResultSchema, implementationVerificationResultSchema, issueDiagnosisResultSchema, projectContextRefreshResultSchema, securityPostureScanResultSchema, sessionDecisionSchema, sessionPolicySchema, testQualityScanResultSchema, type WorkKind } from \"@amistio/shared\";\nimport { z } from \"zod\";\nimport type { AppEvaluationScanResultMutation, AssistantResultMutation, BrainConsolidationScanResultMutation, BrainGenerationResultMutation, ImpactPreviewResultMutation, ImplementationTestGateResultMutation, ImplementationVerificationResultMutation, IssueDiagnosisResultMutation, ProjectContextRefreshResultMutation, SecurityPostureScanResultMutation, TestQualityScanResultMutation } from \"./api-client.js\";\n\nexport type BrainGenerationFinalizationWorkKind = Extract<WorkKind, \"brainGeneration\" | \"planRevision\">;\nexport type DurableResultFinalizationWorkKind = Extract<WorkKind, \"assistantQuestion\" | \"impactPreview\" | \"issueDiagnosis\" | \"securityPostureScan\" | \"appEvaluationScan\" | \"brainConsolidationScan\" | \"projectContextRefresh\" | \"implementationVerification\" | \"testQualityScan\" | \"implementationTestGate\">;\nexport type DurableResultFinalizationResultKind = \"assistantResult\" | \"impactPreviewResult\" | \"issueDiagnosisResult\" | \"securityPostureScanResult\" | \"appEvaluationScanResult\" | \"brainConsolidationScanResult\" | \"projectContextRefreshResult\" | \"implementationVerificationResult\" | \"testQualityScanResult\" | \"implementationTestGateResult\";\n\nconst brainGenerationResultMutationSchema = z.discriminatedUnion(\"status\", [\n z.object({\n status: z.literal(\"completed\"),\n runnerId: z.string().min(1),\n idempotencyKey: z.string().min(1),\n artifacts: z.array(generatedBrainArtifactSchema).min(1),\n tool: z.string().min(1).optional(),\n durationMs: z.number().int().nonnegative().optional(),\n sessionPolicy: sessionPolicySchema.optional(),\n sessionGroupKey: z.string().min(1).optional(),\n toolSessionId: z.string().min(1).optional(),\n sessionDecision: sessionDecisionSchema.optional(),\n sessionDecisionReason: z.string().min(1).optional(),\n message: z.string().optional()\n }),\n z.object({\n status: z.literal(\"failed\"),\n runnerId: z.string().min(1),\n idempotencyKey: z.string().min(1),\n tool: z.string().min(1).optional(),\n durationMs: z.number().int().nonnegative().optional(),\n sessionPolicy: sessionPolicySchema.optional(),\n sessionGroupKey: z.string().min(1).optional(),\n toolSessionId: z.string().min(1).optional(),\n sessionDecision: sessionDecisionSchema.optional(),\n sessionDecisionReason: z.string().min(1).optional(),\n message: z.string().optional(),\n error: z.string().optional()\n })\n]);\n\nconst brainGenerationFinalizationEntrySchema = z.object({\n schemaVersion: z.literal(1),\n kind: z.literal(\"brainGenerationResult\"),\n status: z.enum([\"pending\", \"terminal\"]),\n accountId: z.string().min(1),\n projectId: z.string().min(1),\n repositoryLinkId: z.string().min(1),\n runnerId: z.string().min(1),\n workItemId: z.string().min(1),\n workKind: z.enum([\"brainGeneration\", \"planRevision\"]),\n attempt: z.number().int().nonnegative(),\n idempotencyKey: z.string().min(1),\n result: brainGenerationResultMutationSchema,\n retryCount: z.number().int().nonnegative(),\n createdAt: z.string().min(1),\n updatedAt: z.string().min(1),\n lastError: z.string().optional()\n});\n\nexport type BrainGenerationFinalizationEntry = z.infer<typeof brainGenerationFinalizationEntrySchema> & { result: BrainGenerationResultMutation };\n\nconst resultFinalizationTelemetrySchema = z.object({\n runnerId: z.string().min(1),\n idempotencyKey: z.string().min(1),\n tool: z.string().min(1).optional(),\n durationMs: z.number().int().nonnegative().optional(),\n sessionPolicy: sessionPolicySchema.optional(),\n sessionGroupKey: z.string().min(1).optional(),\n toolSessionId: z.string().min(1).optional(),\n sessionDecision: sessionDecisionSchema.optional(),\n sessionDecisionReason: z.string().min(1).optional(),\n message: z.string().optional()\n});\n\nconst resultFinalizationFailureSchema = resultFinalizationTelemetrySchema.extend({\n status: z.literal(\"failed\"),\n error: z.string().optional()\n});\n\nconst assistantResultMutationSchema = z.discriminatedUnion(\"status\", [\n resultFinalizationTelemetrySchema.extend({\n status: z.literal(\"completed\"),\n answer: assistantAnswerResultSchema.shape.answer,\n sourceBoundary: assistantAnswerResultSchema.shape.sourceBoundary.optional(),\n citations: assistantAnswerResultSchema.shape.citations.optional()\n }),\n resultFinalizationFailureSchema\n]);\n\nconst impactPreviewResultMutationSchema = z.discriminatedUnion(\"status\", [\n resultFinalizationTelemetrySchema.extend({\n status: z.literal(\"completed\"),\n report: impactPreviewResultSchema\n }),\n resultFinalizationFailureSchema\n]);\n\nconst issueDiagnosisResultMutationSchema = z.discriminatedUnion(\"status\", [\n resultFinalizationTelemetrySchema.extend({\n status: z.literal(\"completed\"),\n diagnosis: issueDiagnosisResultSchema\n }),\n resultFinalizationFailureSchema\n]);\n\nconst securityPostureScanResultMutationSchema = z.discriminatedUnion(\"status\", [\n resultFinalizationTelemetrySchema.extend({\n status: z.literal(\"completed\"),\n result: securityPostureScanResultSchema\n }),\n resultFinalizationFailureSchema\n]);\n\nconst appEvaluationScanResultMutationSchema = z.discriminatedUnion(\"status\", [\n resultFinalizationTelemetrySchema.extend({\n status: z.literal(\"completed\"),\n result: appEvaluationScanResultSchema\n }),\n resultFinalizationFailureSchema\n]);\n\nconst brainConsolidationScanResultMutationSchema = z.discriminatedUnion(\"status\", [\n resultFinalizationTelemetrySchema.extend({\n status: z.literal(\"completed\"),\n result: brainConsolidationScanResultSchema\n }),\n resultFinalizationFailureSchema\n]);\n\nconst projectContextRefreshResultMutationSchema = z.discriminatedUnion(\"status\", [\n resultFinalizationTelemetrySchema.extend({\n status: z.literal(\"completed\"),\n result: projectContextRefreshResultSchema\n }),\n resultFinalizationFailureSchema\n]);\n\nconst implementationVerificationResultMutationSchema = z.discriminatedUnion(\"status\", [\n resultFinalizationTelemetrySchema.extend({\n status: z.literal(\"completed\"),\n result: implementationVerificationResultSchema\n }),\n resultFinalizationFailureSchema\n]);\n\nconst testQualityScanResultMutationSchema = z.discriminatedUnion(\"status\", [\n resultFinalizationTelemetrySchema.extend({\n status: z.literal(\"completed\"),\n result: testQualityScanResultSchema\n }),\n resultFinalizationFailureSchema\n]);\n\nconst implementationTestGateResultMutationSchema = z.discriminatedUnion(\"status\", [\n resultFinalizationTelemetrySchema.extend({\n status: z.literal(\"completed\"),\n result: implementationTestGateResultSchema\n }),\n resultFinalizationFailureSchema\n]);\n\nconst durableResultMutationSchema = z.discriminatedUnion(\"resultKind\", [\n z.object({ resultKind: z.literal(\"assistantResult\"), result: assistantResultMutationSchema }),\n z.object({ resultKind: z.literal(\"impactPreviewResult\"), result: impactPreviewResultMutationSchema }),\n z.object({ resultKind: z.literal(\"issueDiagnosisResult\"), result: issueDiagnosisResultMutationSchema }),\n z.object({ resultKind: z.literal(\"securityPostureScanResult\"), result: securityPostureScanResultMutationSchema }),\n z.object({ resultKind: z.literal(\"appEvaluationScanResult\"), result: appEvaluationScanResultMutationSchema }),\n z.object({ resultKind: z.literal(\"brainConsolidationScanResult\"), result: brainConsolidationScanResultMutationSchema }),\n z.object({ resultKind: z.literal(\"projectContextRefreshResult\"), result: projectContextRefreshResultMutationSchema }),\n z.object({ resultKind: z.literal(\"implementationVerificationResult\"), result: implementationVerificationResultMutationSchema }),\n z.object({ resultKind: z.literal(\"testQualityScanResult\"), result: testQualityScanResultMutationSchema }),\n z.object({ resultKind: z.literal(\"implementationTestGateResult\"), result: implementationTestGateResultMutationSchema })\n]);\n\nconst durableResultFinalizationEntrySchema = z.object({\n schemaVersion: z.literal(1),\n kind: z.literal(\"runnerResult\"),\n status: z.enum([\"pending\", \"terminal\"]),\n accountId: z.string().min(1),\n projectId: z.string().min(1),\n repositoryLinkId: z.string().min(1),\n runnerId: z.string().min(1),\n workItemId: z.string().min(1),\n workKind: z.enum([\"assistantQuestion\", \"impactPreview\", \"issueDiagnosis\", \"securityPostureScan\", \"appEvaluationScan\", \"brainConsolidationScan\", \"projectContextRefresh\", \"implementationVerification\", \"testQualityScan\", \"implementationTestGate\"]),\n attempt: z.number().int().nonnegative(),\n idempotencyKey: z.string().min(1),\n retryCount: z.number().int().nonnegative(),\n createdAt: z.string().min(1),\n updatedAt: z.string().min(1),\n lastError: z.string().optional()\n}).and(durableResultMutationSchema);\n\nexport type DurableResultFinalizationResult =\n | AssistantResultMutation\n | ImpactPreviewResultMutation\n | IssueDiagnosisResultMutation\n | SecurityPostureScanResultMutation\n | AppEvaluationScanResultMutation\n | BrainConsolidationScanResultMutation\n | ProjectContextRefreshResultMutation\n | ImplementationVerificationResultMutation\n | TestQualityScanResultMutation\n | ImplementationTestGateResultMutation;\n\nexport type DurableResultFinalizationEntry = z.infer<typeof durableResultFinalizationEntrySchema> & { result: DurableResultFinalizationResult };\n\nexport interface BrainGenerationFinalizationScope {\n accountId: string;\n projectId: string;\n repositoryLinkId: string;\n runnerId: string;\n}\n\nexport function defaultResultFinalizationOutboxDir(): string {\n return path.join(os.homedir(), \".config\", \"amistio\", \"result-finalizations\");\n}\n\nexport function createBrainGenerationFinalizationEntry(input: BrainGenerationFinalizationScope & {\n attempt: number;\n idempotencyKey: string;\n result: BrainGenerationResultMutation;\n workItemId: string;\n workKind: BrainGenerationFinalizationWorkKind;\n}, now = new Date().toISOString()): BrainGenerationFinalizationEntry {\n return brainGenerationFinalizationEntrySchema.parse({\n schemaVersion: 1,\n kind: \"brainGenerationResult\",\n status: \"pending\",\n accountId: input.accountId,\n projectId: input.projectId,\n repositoryLinkId: input.repositoryLinkId,\n runnerId: input.runnerId,\n workItemId: input.workItemId,\n workKind: input.workKind,\n attempt: input.attempt,\n idempotencyKey: input.idempotencyKey,\n result: input.result,\n retryCount: 0,\n createdAt: now,\n updatedAt: now\n }) as BrainGenerationFinalizationEntry;\n}\n\nexport function createDurableResultFinalizationEntry(input: BrainGenerationFinalizationScope & {\n attempt: number;\n idempotencyKey: string;\n result: DurableResultFinalizationResult;\n resultKind: DurableResultFinalizationResultKind;\n workItemId: string;\n workKind: DurableResultFinalizationWorkKind;\n}, now = new Date().toISOString()): DurableResultFinalizationEntry {\n return durableResultFinalizationEntrySchema.parse({\n schemaVersion: 1,\n kind: \"runnerResult\",\n status: \"pending\",\n accountId: input.accountId,\n projectId: input.projectId,\n repositoryLinkId: input.repositoryLinkId,\n runnerId: input.runnerId,\n workItemId: input.workItemId,\n workKind: input.workKind,\n attempt: input.attempt,\n idempotencyKey: input.idempotencyKey,\n resultKind: input.resultKind,\n result: input.result,\n retryCount: 0,\n createdAt: now,\n updatedAt: now\n }) as DurableResultFinalizationEntry;\n}\n\nexport async function upsertBrainGenerationFinalizationEntry(entry: BrainGenerationFinalizationEntry, outboxDir = defaultResultFinalizationOutboxDir()): Promise<void> {\n await mkdir(outboxDir, { recursive: true });\n const filePath = brainGenerationFinalizationEntryPath(entry, outboxDir);\n const tempPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;\n await writeFile(tempPath, `${JSON.stringify(entry, null, 2)}\\n`, \"utf8\");\n await rename(tempPath, filePath);\n}\n\nexport async function listPendingBrainGenerationFinalizations(scope: BrainGenerationFinalizationScope, outboxDir = defaultResultFinalizationOutboxDir()): Promise<BrainGenerationFinalizationEntry[]> {\n const entries = await readdir(outboxDir, { withFileTypes: true }).catch((error: NodeJS.ErrnoException) => {\n if (error.code === \"ENOENT\") return [];\n throw error;\n });\n const pending: BrainGenerationFinalizationEntry[] = [];\n for (const entry of entries) {\n if (!entry.isFile() || !entry.name.endsWith(\".json\")) continue;\n const filePath = path.join(outboxDir, entry.name);\n let raw: unknown;\n try {\n raw = JSON.parse(await readFile(filePath, \"utf8\"));\n } catch {\n continue;\n }\n const parsed = brainGenerationFinalizationEntrySchema.safeParse(raw);\n if (!parsed.success) continue;\n const value = parsed.data as BrainGenerationFinalizationEntry;\n if (value.status !== \"pending\") continue;\n if (value.accountId !== scope.accountId || value.projectId !== scope.projectId || value.repositoryLinkId !== scope.repositoryLinkId || value.runnerId !== scope.runnerId) continue;\n pending.push(value);\n }\n return pending.sort((first, second) => Date.parse(first.createdAt) - Date.parse(second.createdAt));\n}\n\nexport async function upsertDurableResultFinalizationEntry(entry: DurableResultFinalizationEntry, outboxDir = defaultResultFinalizationOutboxDir()): Promise<void> {\n await mkdir(outboxDir, { recursive: true });\n const filePath = durableResultFinalizationEntryPath(entry, outboxDir);\n const tempPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;\n await writeFile(tempPath, `${JSON.stringify(entry, null, 2)}\\n`, \"utf8\");\n await rename(tempPath, filePath);\n}\n\nexport async function listPendingDurableResultFinalizations(scope: BrainGenerationFinalizationScope, outboxDir = defaultResultFinalizationOutboxDir()): Promise<DurableResultFinalizationEntry[]> {\n const entries = await readdir(outboxDir, { withFileTypes: true }).catch((error: NodeJS.ErrnoException) => {\n if (error.code === \"ENOENT\") return [];\n throw error;\n });\n const pending: DurableResultFinalizationEntry[] = [];\n for (const entry of entries) {\n if (!entry.isFile() || !entry.name.endsWith(\".json\")) continue;\n const filePath = path.join(outboxDir, entry.name);\n let raw: unknown;\n try {\n raw = JSON.parse(await readFile(filePath, \"utf8\"));\n } catch {\n continue;\n }\n const parsed = durableResultFinalizationEntrySchema.safeParse(raw);\n if (!parsed.success) continue;\n const value = parsed.data as DurableResultFinalizationEntry;\n if (value.status !== \"pending\") continue;\n if (value.accountId !== scope.accountId || value.projectId !== scope.projectId || value.repositoryLinkId !== scope.repositoryLinkId || value.runnerId !== scope.runnerId) continue;\n pending.push(value);\n }\n return pending.sort((first, second) => Date.parse(first.createdAt) - Date.parse(second.createdAt));\n}\n\nexport async function markBrainGenerationFinalizationRetry(entry: BrainGenerationFinalizationEntry, error: string, outboxDir = defaultResultFinalizationOutboxDir()): Promise<BrainGenerationFinalizationEntry> {\n const updated = brainGenerationFinalizationEntrySchema.parse({\n ...entry,\n status: \"pending\",\n retryCount: entry.retryCount + 1,\n lastError: truncateLocalError(error),\n updatedAt: new Date().toISOString()\n }) as BrainGenerationFinalizationEntry;\n await upsertBrainGenerationFinalizationEntry(updated, outboxDir);\n return updated;\n}\n\nexport async function markBrainGenerationFinalizationTerminal(entry: BrainGenerationFinalizationEntry, error: string, outboxDir = defaultResultFinalizationOutboxDir()): Promise<BrainGenerationFinalizationEntry> {\n const updated = brainGenerationFinalizationEntrySchema.parse({\n ...entry,\n status: \"terminal\",\n lastError: truncateLocalError(error),\n updatedAt: new Date().toISOString()\n }) as BrainGenerationFinalizationEntry;\n await upsertBrainGenerationFinalizationEntry(updated, outboxDir);\n return updated;\n}\n\nexport async function deleteBrainGenerationFinalizationEntry(entry: BrainGenerationFinalizationEntry, outboxDir = defaultResultFinalizationOutboxDir()): Promise<void> {\n await rm(brainGenerationFinalizationEntryPath(entry, outboxDir), { force: true });\n}\n\nexport async function markDurableResultFinalizationRetry(entry: DurableResultFinalizationEntry, error: string, outboxDir = defaultResultFinalizationOutboxDir()): Promise<DurableResultFinalizationEntry> {\n const updated = durableResultFinalizationEntrySchema.parse({\n ...entry,\n status: \"pending\",\n retryCount: entry.retryCount + 1,\n lastError: truncateLocalError(error),\n updatedAt: new Date().toISOString()\n }) as DurableResultFinalizationEntry;\n await upsertDurableResultFinalizationEntry(updated, outboxDir);\n return updated;\n}\n\nexport async function markDurableResultFinalizationTerminal(entry: DurableResultFinalizationEntry, error: string, outboxDir = defaultResultFinalizationOutboxDir()): Promise<DurableResultFinalizationEntry> {\n const updated = durableResultFinalizationEntrySchema.parse({\n ...entry,\n status: \"terminal\",\n lastError: truncateLocalError(error),\n updatedAt: new Date().toISOString()\n }) as DurableResultFinalizationEntry;\n await upsertDurableResultFinalizationEntry(updated, outboxDir);\n return updated;\n}\n\nexport async function deleteDurableResultFinalizationEntry(entry: DurableResultFinalizationEntry, outboxDir = defaultResultFinalizationOutboxDir()): Promise<void> {\n await rm(durableResultFinalizationEntryPath(entry, outboxDir), { force: true });\n}\n\nfunction brainGenerationFinalizationEntryPath(entry: BrainGenerationFinalizationEntry, outboxDir: string): string {\n return path.join(outboxDir, `${brainGenerationFinalizationEntryKey(entry)}.json`);\n}\n\nfunction brainGenerationFinalizationEntryKey(entry: Pick<BrainGenerationFinalizationEntry, \"accountId\" | \"projectId\" | \"repositoryLinkId\" | \"runnerId\" | \"workItemId\" | \"attempt\" | \"idempotencyKey\">): string {\n const hash = createHash(\"sha256\")\n .update([entry.accountId, entry.projectId, entry.repositoryLinkId, entry.runnerId, entry.workItemId, String(entry.attempt), entry.idempotencyKey].join(\"\\0\"))\n .digest(\"hex\")\n .slice(0, 32);\n return `brain-generation-${hash}`;\n}\n\nfunction durableResultFinalizationEntryPath(entry: DurableResultFinalizationEntry, outboxDir: string): string {\n return path.join(outboxDir, `${durableResultFinalizationEntryKey(entry)}.json`);\n}\n\nfunction durableResultFinalizationEntryKey(entry: Pick<DurableResultFinalizationEntry, \"accountId\" | \"projectId\" | \"repositoryLinkId\" | \"runnerId\" | \"workItemId\" | \"attempt\" | \"idempotencyKey\" | \"resultKind\">): string {\n const hash = createHash(\"sha256\")\n .update([entry.accountId, entry.projectId, entry.repositoryLinkId, entry.runnerId, entry.workItemId, String(entry.attempt), entry.idempotencyKey, entry.resultKind].join(\"\\0\"))\n .digest(\"hex\")\n .slice(0, 32);\n return `runner-result-${hash}`;\n}\n\nfunction truncateLocalError(error: string): string {\n const trimmed = error.trim();\n return trimmed.length > 600 ? `${trimmed.slice(0, 600)}...` : trimmed;\n}\n", "import { spawn } from \"node:child_process\";\nimport { mkdtemp, readFile, rm, writeFile } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { runnerProviderCatalogSchema, runnerToolNames, type RunnerInvocationChannel, type RunnerProviderCatalog, type RunnerProviderModel, type RunnerReasoningEffort, type RunnerToolName, type SessionDecision, type SessionPolicy, type SessionResumabilityScope } from \"@amistio/shared\";\nimport type { PermissionHandler, PermissionRequestResult } from \"@github/copilot-sdk\";\n\nexport const localToolNames = runnerToolNames;\n\nexport type LocalToolName = RunnerToolName;\nexport type ToolRequest = LocalToolName | \"auto\" | \"none\";\n\nexport interface LocalToolAdapter {\n name: LocalToolName;\n description: string;\n sdkPackageName?: string;\n sdkDisplayCommand?: string;\n sdkRequiresExecutable?: boolean;\n executable?: string;\n supportsSessionReuse?: boolean;\n resumabilityScope?: SessionResumabilityScope;\n supportsModelSelection?: boolean;\n providerCatalog?: RunnerProviderCatalog;\n buildInvocation?: (input: ToolInvocationInput) => ToolInvocation;\n runWithSdk?: (input: ToolExecutionInput) => Promise<ToolExecutionResult>;\n}\n\nexport interface DetectedLocalTool {\n name: LocalToolName;\n description: string;\n available: boolean;\n sdkAvailable: boolean;\n commandAvailable: boolean;\n execution: \"sdk\" | \"command\" | \"unavailable\";\n supportsSessionReuse: boolean;\n resumabilityScope: SessionResumabilityScope;\n supportsModelSelection: boolean;\n providerCatalog?: RunnerProviderCatalog;\n}\n\nexport interface ToolInvocationInput {\n prompt: string;\n promptFilePath: string;\n rootDir: string;\n model?: string | undefined;\n providerId?: string | undefined;\n modelId?: string | undefined;\n modelVariant?: string | undefined;\n reasoningEffort?: RunnerReasoningEffort | undefined;\n}\n\nexport interface ToolExecutionInput extends ToolInvocationInput {\n streamOutput: boolean;\n session?: ToolExecutionSession;\n}\n\nexport interface ToolExecutionSession {\n toolSessionId: string;\n policy: SessionPolicy;\n decision: SessionDecision;\n providerSessionId?: string;\n}\n\nexport interface ToolInvocation {\n command: string;\n args: string[];\n displayCommand: string;\n shell?: boolean;\n stdin?: string;\n}\n\nexport interface RunLocalToolOptions {\n rootDir: string;\n prompt: string;\n tool?: string;\n toolCommand?: string;\n invocationChannel?: RunnerInvocationChannel;\n model?: string | undefined;\n providerId?: string | undefined;\n modelId?: string | undefined;\n modelVariant?: string | undefined;\n reasoningEffort?: RunnerReasoningEffort | undefined;\n streamOutput?: boolean;\n session?: ToolExecutionSession;\n timeoutMs?: number;\n}\n\nexport interface LocalToolRunResult {\n toolName: string;\n displayCommand: string;\n exitCode: number;\n stdout: string;\n stderr: string;\n supportsSessionReuse: boolean;\n resumabilityScope: SessionResumabilityScope;\n model?: string;\n providerSessionId?: string;\n messageCount?: number;\n tokensIn?: number;\n tokensOut?: number;\n costUsd?: number;\n providerId?: string | undefined;\n modelId?: string | undefined;\n modelVariant?: string | undefined;\n reasoningEffort?: RunnerReasoningEffort | undefined;\n}\n\ninterface ToolExecutionResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n providerSessionId?: string;\n messageCount?: number;\n tokensIn?: number;\n tokensOut?: number;\n costUsd?: number;\n}\n\ntype ResolvedToolRunner =\n | {\n toolName: string;\n kind: \"sdk\";\n displayCommand: string;\n adapter: LocalToolAdapter;\n allowCommandFallback: boolean;\n }\n | {\n toolName: string;\n kind: \"command\";\n invocation: ToolInvocation;\n };\n\nconst allReasoningEfforts: RunnerReasoningEffort[] = [\"auto\", \"low\", \"medium\", \"high\", \"xhigh\"];\n\nconst highReasoningEfforts: RunnerReasoningEffort[] = [\"auto\", \"high\", \"xhigh\"];\n\nconst builtInProviderCatalogs: Partial<Record<LocalToolName, RunnerProviderCatalog>> = {\n opencode: {\n anthropic: {\n id: \"anthropic\",\n name: \"Anthropic\",\n api: \"anthropic\",\n models: {\n \"claude-opus-4.6\": reasoningModel(\"claude-opus-4.6\", \"Claude Opus 4.6\", \"claude\", highReasoningEfforts),\n \"claude-sonnet-4.5\": reasoningModel(\"claude-sonnet-4.5\", \"Claude Sonnet 4.5\", \"claude\", highReasoningEfforts)\n }\n },\n openai: {\n id: \"openai\",\n name: \"OpenAI\",\n api: \"openai\",\n models: {\n \"gpt-5\": reasoningModel(\"gpt-5\", \"GPT-5\", \"gpt\", allReasoningEfforts)\n }\n }\n },\n claude: {\n anthropic: {\n id: \"anthropic\",\n name: \"Anthropic\",\n api: \"anthropic\",\n models: {\n \"claude-opus-4.6\": reasoningModel(\"claude-opus-4.6\", \"Claude Opus 4.6\", \"claude\", highReasoningEfforts),\n \"claude-sonnet-4.5\": reasoningModel(\"claude-sonnet-4.5\", \"Claude Sonnet 4.5\", \"claude\", highReasoningEfforts)\n }\n }\n },\n codex: {\n openai: {\n id: \"openai\",\n name: \"OpenAI\",\n api: \"openai\",\n models: {\n \"gpt-5\": reasoningModel(\"gpt-5\", \"GPT-5\", \"gpt\", allReasoningEfforts)\n }\n }\n },\n copilot: {\n \"github-copilot\": {\n id: \"github-copilot\",\n name: \"GitHub Copilot\",\n api: \"copilot\",\n models: {\n \"gpt-5\": reasoningModel(\"gpt-5\", \"GPT-5\", \"gpt\", allReasoningEfforts),\n \"claude-opus-4.6\": reasoningModel(\"claude-opus-4.6\", \"Claude Opus 4.6\", \"claude\", highReasoningEfforts)\n }\n }\n },\n gemini: {\n google: {\n id: \"google\",\n name: \"Google\",\n api: \"google\",\n models: {\n \"gemini-3-pro\": reasoningModel(\"gemini-3-pro\", \"Gemini 3 Pro\", \"gemini\", highReasoningEfforts)\n }\n }\n }\n};\n\nfunction reasoningModel(id: string, name: string, family: string, supportedReasoningEfforts: RunnerReasoningEffort[]): RunnerProviderModel {\n return {\n id,\n name,\n family,\n status: \"active\",\n reasoning: true,\n toolCall: true,\n supportedReasoningEfforts,\n variants: { standard: {} }\n };\n}\n\nexport const localToolAdapters: readonly LocalToolAdapter[] = [\n {\n name: \"opencode\",\n description: \"opencode SDK adapter using @opencode-ai/sdk, with CLI fallback.\",\n sdkPackageName: \"@opencode-ai/sdk\",\n sdkDisplayCommand: \"@opencode-ai/sdk createOpencode().client.session.prompt()\",\n sdkRequiresExecutable: true,\n executable: \"opencode\",\n supportsModelSelection: true,\n supportsSessionReuse: true,\n resumabilityScope: \"localMachine\",\n providerCatalog: builtInProviderCatalogs.opencode!,\n runWithSdk: runOpencodeSdk,\n buildInvocation: ({ prompt, model }) => ({\n command: \"opencode\",\n args: [\"run\", ...(model ? [\"--model\", model] : []), prompt],\n displayCommand: model ? \"opencode run --model <selected model> <generated prompt>\" : \"opencode run <generated prompt>\"\n })\n },\n {\n name: \"claude\",\n description: \"Claude Agent SDK adapter using @anthropic-ai/claude-agent-sdk, with CLI fallback.\",\n sdkPackageName: \"@anthropic-ai/claude-agent-sdk\",\n sdkDisplayCommand: \"@anthropic-ai/claude-agent-sdk query()\",\n executable: \"claude\",\n supportsModelSelection: true,\n supportsSessionReuse: false,\n resumabilityScope: \"none\",\n providerCatalog: builtInProviderCatalogs.claude!,\n runWithSdk: runClaudeSdk,\n buildInvocation: ({ prompt, model }) => ({\n command: \"claude\",\n args: [...(model ? [\"--model\", model] : []), \"-p\", prompt],\n displayCommand: model ? \"claude --model <selected model> -p <generated prompt>\" : \"claude -p <generated prompt>\"\n })\n },\n {\n name: \"codex\",\n description: \"Codex SDK adapter using @openai/codex-sdk, with CLI fallback.\",\n sdkPackageName: \"@openai/codex-sdk\",\n sdkDisplayCommand: \"@openai/codex-sdk Codex.startThread().run()\",\n executable: \"codex\",\n supportsModelSelection: true,\n supportsSessionReuse: false,\n resumabilityScope: \"none\",\n providerCatalog: builtInProviderCatalogs.codex!,\n runWithSdk: runCodexSdk,\n buildInvocation: ({ prompt, model }) => ({\n command: \"codex\",\n args: [\"exec\", ...(model ? [\"--model\", model] : []), prompt],\n displayCommand: model ? \"codex exec --model <selected model> <generated prompt>\" : \"codex exec <generated prompt>\"\n })\n },\n {\n name: \"copilot\",\n description: \"GitHub Copilot SDK adapter using @github/copilot-sdk.\",\n sdkPackageName: \"@github/copilot-sdk\",\n sdkDisplayCommand: \"@github/copilot-sdk CopilotClient.createSession().sendAndWait()\",\n supportsModelSelection: true,\n supportsSessionReuse: false,\n resumabilityScope: \"none\",\n providerCatalog: builtInProviderCatalogs.copilot!,\n runWithSdk: runCopilotSdk\n },\n {\n name: \"gemini\",\n description: \"Gemini CLI adapter using prompt mode.\",\n executable: \"gemini\",\n supportsModelSelection: true,\n supportsSessionReuse: false,\n resumabilityScope: \"none\",\n providerCatalog: builtInProviderCatalogs.gemini!,\n buildInvocation: ({ prompt, model }) => ({\n command: \"gemini\",\n args: [...(model ? [\"--model\", model] : []), \"-p\", prompt],\n displayCommand: model ? \"gemini --model <selected model> -p <generated prompt>\" : \"gemini -p <generated prompt>\"\n })\n },\n {\n name: \"aider\",\n description: \"Aider CLI adapter using a one-shot message.\",\n executable: \"aider\",\n supportsSessionReuse: false,\n resumabilityScope: \"none\",\n buildInvocation: ({ prompt }) => ({\n command: \"aider\",\n args: [\"--yes\", \"--message\", prompt],\n displayCommand: \"aider --yes --message <generated prompt>\"\n })\n },\n {\n name: \"cursor-agent\",\n description: \"Cursor agent CLI adapter using prompt mode when installed.\",\n executable: \"cursor-agent\",\n supportsSessionReuse: false,\n resumabilityScope: \"none\",\n buildInvocation: ({ prompt }) => ({\n command: \"cursor-agent\",\n args: [\"-p\", prompt],\n displayCommand: \"cursor-agent -p <generated prompt>\"\n })\n }\n];\n\nexport function isLocalToolName(value: string): value is LocalToolName {\n return localToolNames.includes(value as LocalToolName);\n}\n\nexport async function detectLocalTools(): Promise<DetectedLocalTool[]> {\n return Promise.all(\n localToolAdapters.map(async (adapter) => {\n const sdkAvailable = await isSdkAvailable(adapter);\n const commandAvailable = adapter.executable ? await commandExists(adapter.executable) : false;\n const providerCatalog = await detectRunnerProviderCatalog(adapter);\n return {\n name: adapter.name,\n description: adapter.description,\n available: sdkAvailable || commandAvailable,\n sdkAvailable,\n commandAvailable,\n execution: sdkAvailable ? \"sdk\" : commandAvailable ? \"command\" : \"unavailable\",\n supportsSessionReuse: Boolean(adapter.supportsSessionReuse),\n resumabilityScope: adapter.resumabilityScope ?? \"none\",\n supportsModelSelection: Boolean(adapter.supportsModelSelection),\n ...(providerCatalog ? { providerCatalog } : {})\n };\n })\n );\n}\n\nexport async function runLocalTool(options: RunLocalToolOptions): Promise<LocalToolRunResult> {\n const promptTempDir = await mkdtemp(path.join(os.tmpdir(), \"amistio-prompt-\"));\n const promptFilePath = path.join(promptTempDir, \"prompt.md\");\n await writeFile(promptFilePath, options.prompt, \"utf8\");\n const modelConfig = normalizeModelOptions(options);\n\n try {\n const runnerOptions: CreateToolRunnerOptions = {\n rootDir: options.rootDir,\n prompt: options.prompt,\n promptFilePath,\n tool: options.tool ?? \"auto\",\n invocationChannel: options.invocationChannel ?? \"auto\",\n ...modelConfig\n };\n if (options.toolCommand) {\n runnerOptions.toolCommand = options.toolCommand;\n }\n const runner = await createToolRunner(runnerOptions);\n const result = await executeToolRunner(runner, {\n rootDir: options.rootDir,\n prompt: options.prompt,\n promptFilePath,\n streamOutput: Boolean(options.streamOutput),\n ...modelConfig,\n ...(options.session ? { session: options.session } : {})\n }, options.timeoutMs);\n return {\n toolName: runner.toolName,\n displayCommand: runner.kind === \"sdk\" ? runner.displayCommand : runner.invocation.displayCommand,\n supportsSessionReuse: runner.kind === \"sdk\" ? Boolean(runner.adapter.supportsSessionReuse) : false,\n resumabilityScope: runner.kind === \"sdk\" ? runner.adapter.resumabilityScope ?? \"none\" : \"none\",\n ...modelConfig,\n ...result\n };\n } finally {\n await rm(promptTempDir, { recursive: true, force: true });\n }\n}\n\nexport async function createToolRunPreview(options: RunLocalToolOptions): Promise<{ toolName: string; displayCommand: string; supportsSessionReuse: boolean; resumabilityScope: SessionResumabilityScope; model?: string; providerId?: string; modelId?: string; modelVariant?: string; reasoningEffort?: RunnerReasoningEffort }> {\n const promptFilePath = path.join(os.tmpdir(), \"amistio-generated-prompt.md\");\n const modelConfig = normalizeModelOptions(options);\n const runnerOptions: CreateToolRunnerOptions = {\n rootDir: options.rootDir,\n prompt: options.prompt,\n promptFilePath,\n tool: options.tool ?? \"auto\",\n invocationChannel: options.invocationChannel ?? \"auto\",\n ...modelConfig\n };\n if (options.toolCommand) {\n runnerOptions.toolCommand = options.toolCommand;\n }\n const runner = await createToolRunner(runnerOptions);\n return {\n toolName: runner.toolName,\n displayCommand: runner.kind === \"sdk\" ? runner.displayCommand : runner.invocation.displayCommand,\n supportsSessionReuse: runner.kind === \"sdk\" ? Boolean(runner.adapter.supportsSessionReuse) : false,\n resumabilityScope: runner.kind === \"sdk\" ? runner.adapter.resumabilityScope ?? \"none\" : \"none\",\n ...modelConfig\n };\n}\n\ninterface NormalizedModelOptions {\n model?: string;\n providerId?: string;\n modelId?: string;\n modelVariant?: string;\n reasoningEffort?: RunnerReasoningEffort;\n}\n\nfunction normalizeModelOptions(options: Pick<RunLocalToolOptions, \"model\" | \"providerId\" | \"modelId\" | \"modelVariant\" | \"reasoningEffort\">): NormalizedModelOptions {\n const model = options.model?.trim() || (options.providerId?.trim() && options.modelId?.trim() ? `${options.providerId.trim()}/${options.modelId.trim()}` : options.modelId?.trim()) || undefined;\n const providerId = options.providerId?.trim();\n const modelId = options.modelId?.trim();\n const modelVariant = options.modelVariant?.trim();\n return {\n ...(model ? { model } : {}),\n ...(providerId ? { providerId } : {}),\n ...(modelId ? { modelId } : {}),\n ...(modelVariant ? { modelVariant } : {}),\n ...(options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {})\n };\n}\n\nexport function createCustomToolInvocation(commandTemplate: string, input: ToolInvocationInput): ToolInvocation {\n const displayCommand = commandTemplate\n .replaceAll(\"{promptFile}\", shellQuote(input.promptFilePath))\n .replaceAll(\"{root}\", shellQuote(input.rootDir));\n\n return {\n command: displayCommand,\n args: [],\n displayCommand,\n shell: true,\n ...(commandTemplate.includes(\"{promptFile}\") ? {} : { stdin: input.prompt })\n };\n}\n\ninterface CreateToolRunnerOptions extends ToolInvocationInput {\n tool: string;\n toolCommand?: string;\n invocationChannel: RunnerInvocationChannel;\n}\n\nasync function createToolRunner(options: CreateToolRunnerOptions): Promise<ResolvedToolRunner> {\n if (options.toolCommand) {\n return {\n toolName: \"custom\",\n kind: \"command\",\n invocation: createCustomToolInvocation(options.toolCommand, options)\n };\n }\n\n const tool = normalizeToolRequest(options.tool);\n if (tool === \"none\") {\n throw new Error(\"No local tool selected. Use --tool auto, a supported tool name, or --tool-command.\");\n }\n\n const requiresModelSelection = Boolean(options.model || options.providerId || options.modelId || options.modelVariant || options.reasoningEffort && options.reasoningEffort !== \"auto\");\n if (requiresModelSelection && !options.model) {\n throw new Error(\"Provider-backed model configuration requires --model or --provider with --model-id.\");\n }\n const adapter = tool === \"auto\" ? await selectFirstAvailableAdapter(requiresModelSelection, options.invocationChannel) : await selectRequestedAdapter(tool, options.invocationChannel);\n if (requiresModelSelection && !adapter.supportsModelSelection) {\n throw new Error(`Model selection is not supported by ${adapter.name}. Remove model configuration or choose a model-aware adapter.`);\n }\n if (options.invocationChannel !== \"command\" && adapter.runWithSdk && (await isSdkAvailable(adapter))) {\n return {\n toolName: adapter.name,\n kind: \"sdk\",\n displayCommand: adapter.sdkDisplayCommand ?? `${adapter.name} SDK`,\n adapter,\n allowCommandFallback: options.invocationChannel === \"auto\"\n };\n }\n\n if (options.invocationChannel !== \"sdk\" && adapter.buildInvocation && adapter.executable && (await commandExists(adapter.executable))) {\n return {\n toolName: adapter.name,\n kind: \"command\",\n invocation: adapter.buildInvocation(options)\n };\n }\n\n if (options.invocationChannel === \"sdk\") {\n throw new Error(`The ${adapter.name} SDK was not found. Select Auto or Command invocation, install the SDK/runtime, or pass --tool-command locally.`);\n }\n if (options.invocationChannel === \"command\") {\n throw new Error(`The ${adapter.name} executable was not found. Select Auto or SDK invocation, install the command, or pass --tool-command locally.`);\n }\n throw new Error(`The ${adapter.name} SDK or executable was not found. Install the SDK/runtime or pass --tool-command.`);\n}\n\nasync function executeToolRunner(runner: ResolvedToolRunner, input: ToolExecutionInput, timeoutMs?: number): Promise<ToolExecutionResult> {\n if (runner.kind === \"command\") {\n return executeToolInvocation(runner.invocation, input.rootDir, input.streamOutput, timeoutMs);\n }\n\n try {\n return await withTimeout(runner.adapter.runWithSdk!(input), timeoutMs, runner.displayCommand);\n } catch (error) {\n if (runner.allowCommandFallback && runner.adapter.buildInvocation && runner.adapter.executable && (await commandExists(runner.adapter.executable))) {\n const fallback = runner.adapter.buildInvocation(input);\n const result = await executeToolInvocation(fallback, input.rootDir, input.streamOutput, timeoutMs);\n const sdkFailure = `SDK execution for ${runner.adapter.name} failed, fell back to ${fallback.displayCommand}: ${errorMessage(error)}`;\n return {\n ...result,\n stderr: result.stderr ? `${sdkFailure}\\n${result.stderr}` : sdkFailure\n };\n }\n\n throw error;\n }\n}\n\nfunction normalizeToolRequest(value: string): ToolRequest {\n if (value === \"auto\" || value === \"none\" || isLocalToolName(value)) {\n return value;\n }\n\n throw new Error(`Unsupported local tool: ${value}. Supported tools: auto, none, ${localToolNames.join(\", \")}.`);\n}\n\nasync function selectFirstAvailableAdapter(requiresModelSelection = false, invocationChannel: RunnerInvocationChannel = \"auto\"): Promise<LocalToolAdapter> {\n for (const adapter of localToolAdapters) {\n if (requiresModelSelection && !adapter.supportsModelSelection) {\n continue;\n }\n const sdkAvailable = await isSdkAvailable(adapter);\n const commandAvailable = adapter.executable ? await commandExists(adapter.executable) : false;\n if (supportsRequestedInvocationChannel({ sdkAvailable, commandAvailable }, invocationChannel)) {\n return adapter;\n }\n }\n\n if (invocationChannel !== \"auto\") {\n throw new Error(`No installed local AI tool supports ${invocationChannel} invocation${requiresModelSelection ? \" with model selection\" : \"\"}. Select Auto or install a compatible tool.`);\n }\n throw new Error(\n requiresModelSelection\n ? \"No installed local AI tool supports model selection. Remove --model or choose a model-aware adapter.\"\n : `No supported local AI tool was found. Install one of ${localToolNames.join(\", \")} or pass --tool-command \"your-tool --prompt-file {promptFile}\".`\n );\n}\n\nasync function selectRequestedAdapter(tool: LocalToolName, invocationChannel: RunnerInvocationChannel = \"auto\"): Promise<LocalToolAdapter> {\n const adapter = localToolAdapters.find((candidate) => candidate.name === tool);\n if (!adapter) {\n throw new Error(`Unsupported local tool: ${tool}.`);\n }\n const sdkAvailable = await isSdkAvailable(adapter);\n const commandAvailable = adapter.executable ? await commandExists(adapter.executable) : false;\n if (!supportsRequestedInvocationChannel({ sdkAvailable, commandAvailable }, invocationChannel)) {\n if (invocationChannel === \"sdk\") {\n throw new Error(`The ${tool} SDK was not found. Select Auto or Command invocation, install it, or pass --tool-command locally.`);\n }\n if (invocationChannel === \"command\") {\n throw new Error(`The ${tool} executable was not found. Select Auto or SDK invocation, install it, or pass --tool-command locally.`);\n }\n throw new Error(`The ${tool} SDK or executable was not found. Install it or pass --tool-command.`);\n }\n if (invocationChannel !== \"command\" && sdkAvailable) {\n return adapter;\n }\n if (invocationChannel !== \"sdk\" && commandAvailable) {\n return adapter;\n }\n throw new Error(`The ${tool} SDK or executable was not found. Install it or pass --tool-command.`);\n}\n\nfunction supportsRequestedInvocationChannel(capability: { sdkAvailable: boolean; commandAvailable: boolean }, invocationChannel: RunnerInvocationChannel): boolean {\n if (invocationChannel === \"auto\") return capability.sdkAvailable || capability.commandAvailable;\n if (invocationChannel === \"sdk\") return capability.sdkAvailable;\n return capability.commandAvailable;\n}\n\nasync function isSdkAvailable(adapter: LocalToolAdapter): Promise<boolean> {\n if (!adapter.sdkPackageName || !adapter.runWithSdk) {\n return false;\n }\n if (adapter.sdkRequiresExecutable && adapter.executable && !(await commandExists(adapter.executable))) {\n return false;\n }\n\n return packageAvailable(adapter.sdkPackageName);\n}\n\nasync function packageAvailable(packageName: string): Promise<boolean> {\n try {\n await import(packageName);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function commandExists(command: string): Promise<boolean> {\n const lookupCommand = process.platform === \"win32\" ? \"where\" : \"which\";\n return new Promise((resolve) => {\n const lookup = spawn(lookupCommand, [command], { stdio: \"ignore\" });\n lookup.on(\"error\", () => resolve(false));\n lookup.on(\"close\", (exitCode) => resolve(exitCode === 0));\n });\n}\n\nasync function detectRunnerProviderCatalog(adapter: LocalToolAdapter): Promise<RunnerProviderCatalog | undefined> {\n const localOpencodeConfigCatalog = adapter.name === \"opencode\" ? await loadLocalOpencodeProviderConfigCatalog() : undefined;\n return mergeProviderCatalogs(adapter.providerCatalog, localOpencodeConfigCatalog);\n}\n\nfunction localOpencodeProviderConfigPaths(): string[] {\n return [\n path.join(os.homedir(), \".config\", \"opencode\", \"opencode.json\"),\n path.join(os.homedir(), \".config\", \"opencode\", \"config.json\"),\n path.join(process.cwd(), \"opencode.json\")\n ];\n}\n\nexport async function loadLocalOpencodeProviderConfigCatalog(configPaths = localOpencodeProviderConfigPaths()): Promise<RunnerProviderCatalog | undefined> {\n for (const configPath of configPaths) {\n try {\n const parsed = JSON.parse(await readFile(configPath, \"utf8\")) as unknown;\n const providerValue = isRecord(parsed) ? parsed.provider : undefined;\n const catalog = sanitizeProviderCatalog(providerValue);\n if (catalog) return catalog;\n } catch {\n // OpenCode also accepts JSONC; Amistio only ingests plain JSON here to avoid guessing around comments or secrets.\n }\n }\n return undefined;\n}\n\nfunction mergeProviderCatalogs(...catalogs: Array<RunnerProviderCatalog | undefined>): RunnerProviderCatalog | undefined {\n const merged: Record<string, unknown> = {};\n for (const catalog of catalogs) {\n if (!catalog) continue;\n for (const [providerId, provider] of Object.entries(catalog)) {\n const existing = isRecord(merged[providerId]) ? merged[providerId] : undefined;\n const existingModels = existing && isRecord(existing.models) ? existing.models : {};\n merged[providerId] = {\n ...existing,\n ...provider,\n id: provider.id ?? providerId,\n models: { ...existingModels, ...provider.models }\n };\n }\n }\n const parsed = runnerProviderCatalogSchema.safeParse(merged);\n return parsed.success && Object.keys(parsed.data).length ? parsed.data : undefined;\n}\n\nfunction sanitizeProviderCatalog(value: unknown): RunnerProviderCatalog | undefined {\n if (!isRecord(value)) return undefined;\n const catalog: Record<string, unknown> = {};\n for (const [providerId, providerValue] of Object.entries(value)) {\n const provider = sanitizeProviderConfig(providerId, providerValue);\n if (provider) catalog[providerId] = provider;\n }\n const parsed = runnerProviderCatalogSchema.safeParse(catalog);\n return parsed.success && Object.keys(parsed.data).length ? parsed.data : undefined;\n}\n\nfunction sanitizeProviderConfig(providerId: string, value: unknown): Record<string, unknown> | undefined {\n if (!isRecord(value)) return undefined;\n const models = sanitizeProviderModels(value.models);\n if (!Object.keys(models).length) return undefined;\n return {\n id: stringValue(value.id) ?? providerId,\n ...(stringValue(value.name) ? { name: stringValue(value.name) } : {}),\n ...(stringValue(value.api) ? { api: stringValue(value.api) } : {}),\n models\n };\n}\n\nfunction sanitizeProviderModels(value: unknown): Record<string, unknown> {\n if (!isRecord(value)) return {};\n const models: Record<string, unknown> = {};\n for (const [modelId, modelValue] of Object.entries(value)) {\n const model = sanitizeProviderModel(modelId, modelValue);\n if (model) models[modelId] = model;\n }\n return models;\n}\n\nfunction sanitizeProviderModel(modelId: string, value: unknown): Record<string, unknown> | undefined {\n if (!isRecord(value)) return undefined;\n const reasoning = booleanValue(value.reasoning);\n const releaseDate = stringValue(value.release_date) ?? stringValue(value.releaseDate);\n const toolCall = booleanValue(value.tool_call) ?? booleanValue(value.toolCall);\n const limit = sanitizeLimit(value.limit);\n const modalities = sanitizeModalities(value.modalities);\n const variants = sanitizeVariants(value.variants);\n const model: Record<string, unknown> = {\n id: stringValue(value.id) ?? modelId,\n ...(stringValue(value.name) ? { name: stringValue(value.name) } : {}),\n ...(stringValue(value.family) ? { family: stringValue(value.family) } : {}),\n ...(releaseDate ? { releaseDate } : {}),\n ...(booleanValue(value.attachment) !== undefined ? { attachment: booleanValue(value.attachment) } : {}),\n ...(reasoning !== undefined ? { reasoning } : {}),\n ...(booleanValue(value.temperature) !== undefined ? { temperature: booleanValue(value.temperature) } : {}),\n ...(toolCall !== undefined ? { toolCall } : {}),\n ...(stringValue(value.status) ? { status: stringValue(value.status) } : {}),\n ...(limit ? { limit } : {}),\n ...(modalities ? { modalities } : {}),\n ...(variants ? { variants } : {})\n };\n const supportedReasoningEfforts = sanitizeReasoningEfforts(value.supportedReasoningEfforts) ?? sanitizeReasoningEfforts(value.supported_reasoning_efforts) ?? (reasoning ? allReasoningEfforts : undefined);\n if (supportedReasoningEfforts) model.supportedReasoningEfforts = supportedReasoningEfforts;\n return model;\n}\n\nfunction sanitizeLimit(value: unknown): Record<string, unknown> | undefined {\n if (!isRecord(value)) return undefined;\n const limit = {\n ...(numberValue(value.context) !== undefined ? { context: numberValue(value.context) } : {}),\n ...(numberValue(value.input) !== undefined ? { input: numberValue(value.input) } : {}),\n ...(numberValue(value.output) !== undefined ? { output: numberValue(value.output) } : {})\n };\n return Object.keys(limit).length ? limit : undefined;\n}\n\nfunction sanitizeModalities(value: unknown): Record<string, unknown> | undefined {\n if (!isRecord(value)) return undefined;\n const modalities = {\n ...(stringArrayValue(value.input) ? { input: stringArrayValue(value.input) } : {}),\n ...(stringArrayValue(value.output) ? { output: stringArrayValue(value.output) } : {})\n };\n return Object.keys(modalities).length ? modalities : undefined;\n}\n\nfunction sanitizeVariants(value: unknown): Record<string, unknown> | undefined {\n if (!isRecord(value)) return undefined;\n const variants: Record<string, unknown> = {};\n for (const [variantId, variantValue] of Object.entries(value)) {\n variants[variantId] = isRecord(variantValue) && booleanValue(variantValue.disabled) !== undefined ? { disabled: booleanValue(variantValue.disabled) } : {};\n }\n return Object.keys(variants).length ? variants : undefined;\n}\n\nfunction sanitizeReasoningEfforts(value: unknown): RunnerReasoningEffort[] | undefined {\n const values = stringArrayValue(value);\n if (!values) return undefined;\n const efforts = values.filter((candidate): candidate is RunnerReasoningEffort => allReasoningEfforts.includes(candidate as RunnerReasoningEffort));\n return efforts.length ? efforts : undefined;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim() ? value.trim() : undefined;\n}\n\nfunction numberValue(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) && value >= 0 ? value : undefined;\n}\n\nfunction booleanValue(value: unknown): boolean | undefined {\n return typeof value === \"boolean\" ? value : undefined;\n}\n\nfunction stringArrayValue(value: unknown): string[] | undefined {\n return Array.isArray(value) && value.every((item) => typeof item === \"string\") ? value : undefined;\n}\n\nasync function executeToolInvocation(\n invocation: ToolInvocation,\n rootDir: string,\n streamOutput: boolean,\n timeoutMs?: number\n): Promise<{ exitCode: number; stdout: string; stderr: string }> {\n return new Promise((resolve, reject) => {\n const child = spawn(invocation.command, invocation.args, {\n cwd: rootDir,\n env: process.env,\n shell: invocation.shell ?? false,\n stdio: [\"pipe\", \"pipe\", \"pipe\"]\n });\n let stdout = \"\";\n let stderr = \"\";\n let settled = false;\n let forceKillTimer: ReturnType<typeof setTimeout> | undefined;\n const timeout = timeoutMs && timeoutMs > 0\n ? setTimeout(() => {\n if (settled) return;\n stderr += `${toolTimeoutMessage(invocation.displayCommand, timeoutMs)}\\n`;\n child.kill(\"SIGTERM\");\n forceKillTimer = setTimeout(() => child.kill(\"SIGKILL\"), 5_000);\n forceKillTimer.unref?.();\n rejectOnce(new Error(toolTimeoutMessage(invocation.displayCommand, timeoutMs)));\n }, timeoutMs)\n : undefined;\n timeout?.unref?.();\n\n const resolveOnce = (value: { exitCode: number; stdout: string; stderr: string }) => {\n if (settled) return;\n settled = true;\n if (timeout) clearTimeout(timeout);\n if (forceKillTimer) clearTimeout(forceKillTimer);\n resolve(value);\n };\n const rejectOnce = (error: unknown) => {\n if (settled) return;\n settled = true;\n if (timeout) clearTimeout(timeout);\n if (forceKillTimer) clearTimeout(forceKillTimer);\n reject(error);\n };\n\n child.on(\"error\", rejectOnce);\n child.stdout.setEncoding(\"utf8\");\n child.stderr.setEncoding(\"utf8\");\n child.stdout.on(\"data\", (chunk: string) => {\n stdout += chunk;\n if (streamOutput) {\n process.stdout.write(chunk);\n }\n });\n child.stderr.on(\"data\", (chunk: string) => {\n stderr += chunk;\n if (streamOutput) {\n process.stderr.write(chunk);\n }\n });\n child.stdin.on(\"error\", () => undefined);\n if (invocation.stdin) {\n child.stdin.write(invocation.stdin);\n }\n child.stdin.end();\n child.on(\"close\", (exitCode) => {\n if (forceKillTimer) clearTimeout(forceKillTimer);\n resolveOnce({ exitCode: exitCode ?? 1, stdout, stderr });\n });\n });\n}\n\nasync function withTimeout<T>(promise: Promise<T>, timeoutMs: number | undefined, displayCommand: string): Promise<T> {\n if (!timeoutMs || timeoutMs <= 0) {\n return promise;\n }\n\n return new Promise<T>((resolve, reject) => {\n const timeout = setTimeout(() => reject(new Error(toolTimeoutMessage(displayCommand, timeoutMs))), timeoutMs);\n timeout.unref?.();\n promise.then(\n (value) => {\n clearTimeout(timeout);\n resolve(value);\n },\n (error) => {\n clearTimeout(timeout);\n reject(error);\n }\n );\n });\n}\n\nfunction toolTimeoutMessage(displayCommand: string, timeoutMs: number): string {\n return `Local tool timed out after ${formatTimeoutDuration(timeoutMs)}: ${displayCommand}`;\n}\n\nfunction formatTimeoutDuration(timeoutMs: number): string {\n if (timeoutMs < 1000) {\n return `${timeoutMs}ms`;\n }\n const seconds = timeoutMs / 1000;\n return Number.isInteger(seconds) ? `${seconds}s` : `${seconds.toFixed(1)}s`;\n}\n\nasync function runOpencodeSdk(input: ToolExecutionInput): Promise<ToolExecutionResult> {\n const { createOpencode } = await import(\"@opencode-ai/sdk\");\n const previousDirectory = process.cwd();\n process.chdir(input.rootDir);\n try {\n const opencode = await createOpencode({ timeout: 10_000 });\n try {\n let providerSessionId = input.session?.providerSessionId;\n if (!providerSessionId) {\n const sessionResult = (await opencode.client.session.create({\n query: { directory: input.rootDir },\n body: { title: \"Amistio orchestration\" }\n })) as OpencodeResult<{ id: string }>;\n if (sessionResult.error || !sessionResult.data) {\n throw new Error(`opencode session create failed: ${JSON.stringify(sessionResult.error ?? \"missing data\")}`);\n }\n providerSessionId = sessionResult.data.id;\n }\n\n const promptResult = (await opencode.client.session.prompt({\n path: { id: providerSessionId },\n query: { directory: input.rootDir },\n body: { parts: [{ type: \"text\", text: input.prompt }] }\n })) as OpencodeResult<{ parts?: unknown[] }>;\n if (promptResult.error || !promptResult.data) {\n throw new Error(`opencode prompt failed: ${JSON.stringify(promptResult.error ?? \"missing data\")}`);\n }\n\n const stdout = extractTextParts(promptResult.data.parts);\n if (input.streamOutput && stdout) {\n process.stdout.write(stdout);\n }\n return { exitCode: 0, stdout, stderr: \"\", providerSessionId, messageCount: 1 };\n } finally {\n opencode.server.close();\n }\n } finally {\n process.chdir(previousDirectory);\n }\n}\n\nasync function runClaudeSdk(input: ToolExecutionInput): Promise<ToolExecutionResult> {\n const { query } = await import(\"@anthropic-ai/claude-agent-sdk\");\n let stdout = \"\";\n let stderr = \"\";\n let exitCode = 0;\n\n for await (const message of query({\n prompt: input.prompt,\n options: {\n cwd: input.rootDir,\n permissionMode: \"default\",\n tools: { type: \"preset\", preset: \"claude_code\" },\n env: {\n ...process.env,\n CLAUDE_AGENT_SDK_CLIENT_APP: \"amistio-cli/0.1.0\"\n }\n }\n })) {\n if (isRecord(message) && message.type === \"result\") {\n if (message.subtype === \"success\" && typeof message.result === \"string\") {\n stdout += message.result;\n if (input.streamOutput) {\n process.stdout.write(message.result);\n }\n } else {\n exitCode = 1;\n const resultMessage = message as Record<string, unknown>;\n const errors = Array.isArray(resultMessage.errors) ? resultMessage.errors.map(String).join(\"\\n\") : \"Claude Agent SDK execution failed.\";\n stderr += errors;\n }\n }\n }\n\n return { exitCode, stdout, stderr };\n}\n\nasync function runCodexSdk(input: ToolExecutionInput): Promise<ToolExecutionResult> {\n const { Codex } = await import(\"@openai/codex-sdk\");\n const codex = new Codex();\n const thread = codex.startThread({\n workingDirectory: input.rootDir,\n sandboxMode: \"workspace-write\",\n approvalPolicy: \"on-request\",\n skipGitRepoCheck: true\n });\n if (input.streamOutput) {\n process.stderr.write(\"Codex SDK is running; intermediate progress may be quiet until the final response. Use --invocation-channel command for Codex CLI logs.\\n\");\n }\n const result = await thread.run(input.prompt);\n if (input.streamOutput && result.finalResponse) {\n process.stdout.write(result.finalResponse);\n }\n return { exitCode: 0, stdout: result.finalResponse, stderr: \"\" };\n}\n\nasync function runCopilotSdk(input: ToolExecutionInput): Promise<ToolExecutionResult> {\n const { CopilotClient } = await import(\"@github/copilot-sdk\");\n const client = new CopilotClient({\n cwd: input.rootDir,\n logLevel: \"error\"\n });\n try {\n await client.start();\n const session = await client.createSession({\n clientName: \"amistio-cli\",\n model: input.model ?? process.env.AMISTIO_COPILOT_MODEL ?? \"gpt-5\",\n workingDirectory: input.rootDir,\n enableConfigDiscovery: true,\n streaming: input.streamOutput,\n onPermissionRequest: createCopilotPermissionHandler()\n });\n\n try {\n let streamedOutput = \"\";\n const unsubscribe = input.streamOutput\n ? session.on(\"assistant.message_delta\", (event) => {\n streamedOutput += event.data.deltaContent;\n process.stdout.write(event.data.deltaContent);\n })\n : undefined;\n try {\n const response = await session.sendAndWait({ prompt: input.prompt }, 10 * 60 * 1000);\n const stdout = response?.data.content ?? streamedOutput;\n return { exitCode: 0, stdout, stderr: \"\" };\n } finally {\n unsubscribe?.();\n }\n } finally {\n await session.disconnect();\n }\n } finally {\n await client.stop();\n }\n}\n\nexport function createCopilotPermissionHandler(env: NodeJS.ProcessEnv = process.env): PermissionHandler {\n const allowAllPermissions = isCopilotApproveAllEnabled(env);\n return (request): PermissionRequestResult => {\n if (allowAllPermissions || request.kind === \"read\") {\n return { kind: \"approve-once\" };\n }\n\n return { kind: \"reject\" };\n };\n}\n\nexport function isCopilotApproveAllEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n return /^(1|true|yes)$/i.test(env.AMISTIO_COPILOT_APPROVE_ALL ?? \"\");\n}\n\ninterface OpencodeResult<TData> {\n data?: TData;\n error?: unknown;\n}\n\nfunction extractTextParts(parts: unknown): string {\n if (!Array.isArray(parts)) {\n return \"\";\n }\n\n return parts\n .filter(isRecord)\n .map((part) => (part.type === \"text\" && typeof part.text === \"string\" ? part.text : \"\"))\n .filter(Boolean)\n .join(\"\\n\");\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n}", "import { spawn } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { openSync } from \"node:fs\";\nimport { mkdir, readdir, readFile, writeFile } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nexport type RunnerProcessMode = \"foreground\" | \"background\";\nexport type RunnerDaemonStatus = \"running\" | \"stopped\";\n\nexport interface RunnerDaemonMetadata {\n schemaVersion: 1;\n accountId: string;\n projectId: string;\n repositoryLinkId: string;\n runnerId: string;\n rootDir: string;\n apiUrl: string;\n pid: number;\n status: RunnerDaemonStatus;\n startedAt: string;\n updatedAt: string;\n hostname: string;\n logPath?: string;\n stoppedAt?: string;\n}\n\nexport interface StartRunnerDaemonInput {\n accountId: string;\n projectId: string;\n repositoryLinkId: string;\n runnerId: string;\n rootDir: string;\n apiUrl: string;\n args: string[];\n executablePath?: string;\n scriptPath?: string;\n metadataDir?: string;\n}\n\nexport interface RunnerDaemonLaunchOptions {\n executablePath?: string;\n scriptPath?: string;\n metadataDir?: string;\n directExecutable?: boolean;\n}\n\nexport function currentRunnerMode(): RunnerProcessMode {\n return process.env.AMISTIO_RUNNER_MODE === \"background\" ? \"background\" : \"foreground\";\n}\n\nexport function defaultRunnerMetadataDir(): string {\n return path.join(os.homedir(), \".config\", \"amistio\", \"runners\");\n}\n\nexport function updatedCliRunnerLaunchOptions(): RunnerDaemonLaunchOptions {\n return { executablePath: \"amistio\", directExecutable: true };\n}\n\nexport function resolveRunnerDaemonLaunch(input: { args: string[] } & Pick<RunnerDaemonLaunchOptions, \"directExecutable\" | \"executablePath\" | \"scriptPath\">): { executablePath: string; args: string[] } {\n if (input.directExecutable) {\n return { executablePath: input.executablePath ?? \"amistio\", args: input.args };\n }\n\n return { executablePath: input.executablePath ?? process.execPath, args: [input.scriptPath ?? process.argv[1]!, ...input.args] };\n}\n\nexport async function startRunnerDaemon(input: StartRunnerDaemonInput): Promise<RunnerDaemonMetadata> {\n const metadataDir = input.metadataDir ?? defaultRunnerMetadataDir();\n const existing = await readRunnerDaemonMetadata(input, metadataDir);\n if (existing?.status === \"running\" && isProcessRunning(existing.pid)) {\n throw new Error(`Background runner ${existing.runnerId} is already running with PID ${existing.pid}.`);\n }\n\n await mkdir(metadataDir, { recursive: true });\n const logPath = path.join(metadataDir, `${runnerDaemonKey(input)}.log`);\n const logFd = openSync(logPath, \"a\");\n const launch = resolveRunnerDaemonLaunch({\n args: input.args,\n ...(input.executablePath ? { executablePath: input.executablePath } : {}),\n ...(input.scriptPath ? { scriptPath: input.scriptPath } : {})\n });\n const child = spawn(launch.executablePath, launch.args, {\n cwd: input.rootDir,\n detached: true,\n env: {\n ...process.env,\n AMISTIO_RUNNER_MODE: \"background\"\n },\n stdio: [\"ignore\", logFd, logFd]\n });\n\n if (!child.pid) {\n throw new Error(\"Failed to start background runner process.\");\n }\n\n child.unref();\n\n const now = new Date().toISOString();\n const metadata: RunnerDaemonMetadata = {\n schemaVersion: 1,\n accountId: input.accountId,\n projectId: input.projectId,\n repositoryLinkId: input.repositoryLinkId,\n runnerId: input.runnerId,\n rootDir: path.resolve(input.rootDir),\n apiUrl: input.apiUrl,\n pid: child.pid,\n status: \"running\",\n startedAt: now,\n updatedAt: now,\n hostname: os.hostname(),\n logPath\n };\n await writeRunnerDaemonMetadata(metadata, metadataDir);\n return metadata;\n}\n\nexport async function restartRunnerDaemonProcess(metadata: RunnerDaemonMetadata, args: string[], input: RunnerDaemonLaunchOptions = {}): Promise<RunnerDaemonMetadata> {\n const metadataDir = input.metadataDir ?? defaultRunnerMetadataDir();\n await mkdir(metadataDir, { recursive: true });\n const logPath = metadata.logPath ?? path.join(metadataDir, `${runnerDaemonKey(metadata)}.log`);\n const logFd = openSync(logPath, \"a\");\n const launch = resolveRunnerDaemonLaunch({\n args,\n ...(input.executablePath ? { executablePath: input.executablePath } : {}),\n ...(input.scriptPath ? { scriptPath: input.scriptPath } : {}),\n ...(input.directExecutable ? { directExecutable: true } : {})\n });\n const child = spawn(launch.executablePath, launch.args, {\n cwd: metadata.rootDir,\n detached: true,\n env: {\n ...process.env,\n AMISTIO_RUNNER_MODE: \"background\"\n },\n stdio: [\"ignore\", logFd, logFd]\n });\n\n if (!child.pid) {\n throw new Error(\"Failed to start replacement background runner process.\");\n }\n\n child.unref();\n const now = new Date().toISOString();\n const replacement: RunnerDaemonMetadata = {\n ...metadata,\n pid: child.pid,\n status: \"running\",\n startedAt: now,\n updatedAt: now,\n hostname: os.hostname(),\n logPath\n };\n await writeRunnerDaemonMetadata(replacement, metadataDir);\n return replacement;\n}\n\nexport async function listRunnerDaemonMetadata(input: { accountId: string; projectId: string; repositoryLinkId: string; runnerId?: string }, metadataDir = defaultRunnerMetadataDir()): Promise<RunnerDaemonMetadata[]> {\n let entries: string[];\n try {\n entries = await readdir(metadataDir);\n } catch {\n return [];\n }\n\n const records = await Promise.all(\n entries\n .filter((entry) => entry.endsWith(\".json\"))\n .map(async (entry) => readRunnerDaemonMetadataFile(path.join(metadataDir, entry)))\n );\n\n return records\n .filter((record): record is RunnerDaemonMetadata => Boolean(record))\n .filter((record) => record.accountId === input.accountId && record.projectId === input.projectId && record.repositoryLinkId === input.repositoryLinkId)\n .filter((record) => !input.runnerId || record.runnerId === input.runnerId)\n .sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt));\n}\n\nexport async function readRunnerDaemonMetadata(input: { accountId: string; projectId: string; repositoryLinkId: string; runnerId: string }, metadataDir = defaultRunnerMetadataDir()): Promise<RunnerDaemonMetadata | undefined> {\n return readRunnerDaemonMetadataFile(runnerDaemonMetadataPath(input, metadataDir));\n}\n\nexport async function writeRunnerDaemonMetadata(metadata: RunnerDaemonMetadata, metadataDir = defaultRunnerMetadataDir()): Promise<void> {\n await mkdir(metadataDir, { recursive: true });\n await writeFile(runnerDaemonMetadataPath(metadata, metadataDir), JSON.stringify(metadata, null, 2), { encoding: \"utf8\", mode: 0o600 });\n}\n\nexport async function markRunnerDaemonStopped(metadata: RunnerDaemonMetadata, metadataDir = defaultRunnerMetadataDir()): Promise<RunnerDaemonMetadata> {\n const now = new Date().toISOString();\n const stopped: RunnerDaemonMetadata = {\n ...metadata,\n status: \"stopped\",\n stoppedAt: now,\n updatedAt: now\n };\n await writeRunnerDaemonMetadata(stopped, metadataDir);\n return stopped;\n}\n\nexport async function stopRunnerDaemonProcess(metadata: RunnerDaemonMetadata): Promise<\"stopped\" | \"not-running\"> {\n if (!isProcessRunning(metadata.pid)) {\n return \"not-running\";\n }\n\n process.kill(metadata.pid, \"SIGTERM\");\n for (let attempt = 0; attempt < 30; attempt += 1) {\n if (!isProcessRunning(metadata.pid)) {\n return \"stopped\";\n }\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n\n return isProcessRunning(metadata.pid) ? \"not-running\" : \"stopped\";\n}\n\nexport function isProcessRunning(pid: number): boolean {\n if (!Number.isInteger(pid) || pid <= 0) {\n return false;\n }\n\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n const code = typeof error === \"object\" && error && \"code\" in error ? (error as { code?: string }).code : undefined;\n return code === \"EPERM\";\n }\n}\n\nexport function runnerDaemonRuntimeStatus(metadata: RunnerDaemonMetadata): \"running\" | \"stale\" | \"stopped\" {\n if (metadata.status === \"stopped\") {\n return \"stopped\";\n }\n return isProcessRunning(metadata.pid) ? \"running\" : \"stale\";\n}\n\nexport function runnerDaemonUptime(metadata: RunnerDaemonMetadata, now = Date.now()): string {\n const startedAt = Date.parse(metadata.startedAt);\n if (!Number.isFinite(startedAt)) {\n return \"unknown\";\n }\n const totalSeconds = Math.max(0, Math.floor((now - startedAt) / 1000));\n const hours = Math.floor(totalSeconds / 3600);\n const minutes = Math.floor((totalSeconds % 3600) / 60);\n const seconds = totalSeconds % 60;\n if (hours > 0) {\n return `${hours}h ${minutes}m`;\n }\n if (minutes > 0) {\n return `${minutes}m ${seconds}s`;\n }\n return `${seconds}s`;\n}\n\nfunction runnerDaemonMetadataPath(input: { accountId: string; projectId: string; repositoryLinkId: string; runnerId: string }, metadataDir: string): string {\n return path.join(metadataDir, `${runnerDaemonKey(input)}.json`);\n}\n\nfunction runnerDaemonKey(input: { accountId: string; projectId: string; repositoryLinkId: string; runnerId: string }): string {\n return createHash(\"sha256\").update(`${input.accountId}:${input.projectId}:${input.repositoryLinkId}:${input.runnerId}`).digest(\"hex\");\n}\n\nasync function readRunnerDaemonMetadataFile(filePath: string): Promise<RunnerDaemonMetadata | undefined> {\n try {\n const parsed = JSON.parse(await readFile(filePath, \"utf8\")) as RunnerDaemonMetadata;\n if (parsed.schemaVersion !== 1 || !parsed.runnerId || !parsed.projectId || !parsed.repositoryLinkId) {\n return undefined;\n }\n return parsed;\n } catch {\n return undefined;\n }\n}\n", "import { spawn } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { mkdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { defaultRunnerMetadataDir } from \"./runner-daemon.js\";\n\nexport type RunnerServicePlatform = \"launchd\" | \"systemd\" | \"unsupported\";\nexport type RunnerServiceStatus = \"installed\" | \"removed\";\n\nexport interface RunnerServiceMetadata {\n schemaVersion: 1;\n accountId: string;\n projectId: string;\n repositoryLinkId: string;\n runnerId: string;\n rootDir: string;\n apiUrl: string;\n serviceName: string;\n serviceFilePath: string;\n platform: Exclude<RunnerServicePlatform, \"unsupported\">;\n status: RunnerServiceStatus;\n createdAt: string;\n updatedAt: string;\n args: string[];\n}\n\nexport interface RunnerServiceDescriptor {\n metadata: RunnerServiceMetadata;\n content: string;\n}\n\nexport interface RunnerServiceInput {\n accountId: string;\n projectId: string;\n repositoryLinkId: string;\n runnerId: string;\n rootDir: string;\n apiUrl: string;\n args: string[];\n executablePath?: string;\n scriptPath?: string;\n homeDir?: string;\n metadataDir?: string;\n platform?: RunnerServicePlatform;\n}\n\nexport function detectRunnerServicePlatform(platform = process.platform): RunnerServicePlatform {\n if (platform === \"darwin\") return \"launchd\";\n if (platform === \"linux\") return \"systemd\";\n return \"unsupported\";\n}\n\nexport function createRunnerServiceDescriptor(input: RunnerServiceInput): RunnerServiceDescriptor {\n const platform = input.platform ?? detectRunnerServicePlatform();\n if (platform === \"unsupported\") {\n throw new Error(\"Startup services are supported for user-level launchd on macOS and systemd user services on Linux.\");\n }\n\n const homeDir = input.homeDir ?? os.homedir();\n const serviceName = runnerServiceName(input);\n const serviceFilePath = runnerServiceFilePath(platform, serviceName, homeDir);\n const now = new Date().toISOString();\n const command = [input.executablePath ?? process.execPath, input.scriptPath ?? process.argv[1]!, ...input.args];\n const logPath = path.join(input.metadataDir ?? defaultRunnerMetadataDir(), `${runnerServiceKey(input)}.service.log`);\n const metadata: RunnerServiceMetadata = {\n schemaVersion: 1,\n accountId: input.accountId,\n projectId: input.projectId,\n repositoryLinkId: input.repositoryLinkId,\n runnerId: input.runnerId,\n rootDir: path.resolve(input.rootDir),\n apiUrl: input.apiUrl,\n serviceName,\n serviceFilePath,\n platform,\n status: \"installed\",\n createdAt: now,\n updatedAt: now,\n args: input.args\n };\n\n return {\n metadata,\n content: platform === \"launchd\"\n ? createLaunchdPlist({ command, label: serviceName, logPath, rootDir: metadata.rootDir })\n : createSystemdUnit({ command, description: `Amistio runner ${input.runnerId}`, logPath, rootDir: metadata.rootDir })\n };\n}\n\nexport async function installRunnerService(input: RunnerServiceInput, options: { activate?: boolean } = {}): Promise<RunnerServiceMetadata> {\n const descriptor = createRunnerServiceDescriptor(input);\n await mkdir(path.dirname(descriptor.metadata.serviceFilePath), { recursive: true });\n await mkdir(input.metadataDir ?? defaultRunnerMetadataDir(), { recursive: true });\n await writeFile(descriptor.metadata.serviceFilePath, descriptor.content, { encoding: \"utf8\", mode: 0o600 });\n await writeRunnerServiceMetadata(descriptor.metadata, input.metadataDir);\n\n if (options.activate !== false) {\n const activation = await activateRunnerService(descriptor.metadata);\n if (!activation.succeeded) {\n throw new Error(`Startup service file was written to ${descriptor.metadata.serviceFilePath}, but activation failed: ${activation.message}`);\n }\n }\n\n return descriptor.metadata;\n}\n\nexport async function removeRunnerService(input: { accountId: string; projectId: string; repositoryLinkId: string; runnerId: string; metadataDir?: string }): Promise<RunnerServiceMetadata | undefined> {\n const metadata = await readRunnerServiceMetadata(input, input.metadataDir);\n if (!metadata) {\n return undefined;\n }\n\n await deactivateRunnerService(metadata).catch(() => undefined);\n await rm(metadata.serviceFilePath, { force: true });\n await rm(runnerServiceMetadataPath(input, input.metadataDir ?? defaultRunnerMetadataDir()), { force: true });\n return { ...metadata, status: \"removed\", updatedAt: new Date().toISOString() };\n}\n\nexport async function readRunnerServiceMetadata(input: { accountId: string; projectId: string; repositoryLinkId: string; runnerId: string }, metadataDir = defaultRunnerMetadataDir()): Promise<RunnerServiceMetadata | undefined> {\n try {\n const parsed = JSON.parse(await readFile(runnerServiceMetadataPath(input, metadataDir), \"utf8\")) as RunnerServiceMetadata;\n if (parsed.schemaVersion !== 1 || !parsed.serviceName || !parsed.serviceFilePath) {\n return undefined;\n }\n return parsed;\n } catch {\n return undefined;\n }\n}\n\nexport async function writeRunnerServiceMetadata(metadata: RunnerServiceMetadata, metadataDir = defaultRunnerMetadataDir()): Promise<void> {\n await mkdir(metadataDir, { recursive: true });\n await writeFile(runnerServiceMetadataPath(metadata, metadataDir), JSON.stringify(metadata, null, 2), { encoding: \"utf8\", mode: 0o600 });\n}\n\nexport async function runnerServiceRuntimeStatus(metadata: RunnerServiceMetadata): Promise<string> {\n if (metadata.platform === \"launchd\") {\n const target = launchdTarget(metadata);\n const result = await runProcess(\"launchctl\", [\"print\", target], 5_000);\n return result.exitCode === 0 ? \"loaded\" : \"not loaded\";\n }\n\n const result = await runProcess(\"systemctl\", [\"--user\", \"is-active\", metadata.serviceName], 5_000);\n return result.exitCode === 0 ? result.output.trim() || \"active\" : \"not active\";\n}\n\nasync function activateRunnerService(metadata: RunnerServiceMetadata): Promise<{ succeeded: boolean; message: string }> {\n if (metadata.platform === \"launchd\") {\n await runProcess(\"launchctl\", [\"bootout\", launchdDomain(), metadata.serviceFilePath], 5_000).catch(() => undefined);\n const result = await runProcess(\"launchctl\", [\"bootstrap\", launchdDomain(), metadata.serviceFilePath], 10_000);\n return result.exitCode === 0 ? { succeeded: true, message: \"launchd service loaded.\" } : { succeeded: false, message: result.output || `launchctl exited with ${result.exitCode}.` };\n }\n\n const reload = await runProcess(\"systemctl\", [\"--user\", \"daemon-reload\"], 10_000);\n if (reload.exitCode !== 0) {\n return { succeeded: false, message: reload.output || `systemctl daemon-reload exited with ${reload.exitCode}.` };\n }\n const enable = await runProcess(\"systemctl\", [\"--user\", \"enable\", \"--now\", metadata.serviceName], 20_000);\n return enable.exitCode === 0 ? { succeeded: true, message: \"systemd user service enabled.\" } : { succeeded: false, message: enable.output || `systemctl enable exited with ${enable.exitCode}.` };\n}\n\nasync function deactivateRunnerService(metadata: RunnerServiceMetadata): Promise<void> {\n if (metadata.platform === \"launchd\") {\n await runProcess(\"launchctl\", [\"bootout\", launchdDomain(), metadata.serviceFilePath], 10_000);\n return;\n }\n\n await runProcess(\"systemctl\", [\"--user\", \"disable\", \"--now\", metadata.serviceName], 20_000);\n await runProcess(\"systemctl\", [\"--user\", \"daemon-reload\"], 10_000).catch(() => undefined);\n}\n\nfunction createLaunchdPlist(input: { command: string[]; label: string; logPath: string; rootDir: string }): string {\n const commandItems = input.command.map((item) => ` <string>${xmlEscape(item)}</string>`).join(\"\\n\");\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>Label</key>\n <string>${xmlEscape(input.label)}</string>\n <key>ProgramArguments</key>\n <array>\n${commandItems}\n </array>\n <key>WorkingDirectory</key>\n <string>${xmlEscape(input.rootDir)}</string>\n <key>EnvironmentVariables</key>\n <dict>\n <key>AMISTIO_RUNNER_MODE</key>\n <string>background</string>\n </dict>\n <key>RunAtLoad</key>\n <true/>\n <key>KeepAlive</key>\n <true/>\n <key>StandardOutPath</key>\n <string>${xmlEscape(input.logPath)}</string>\n <key>StandardErrorPath</key>\n <string>${xmlEscape(input.logPath)}</string>\n</dict>\n</plist>\n`;\n}\n\nfunction createSystemdUnit(input: { command: string[]; description: string; logPath: string; rootDir: string }): string {\n return `[Unit]\nDescription=${input.description}\n\n[Service]\nType=simple\nWorkingDirectory=${systemdEscape(input.rootDir)}\nEnvironment=AMISTIO_RUNNER_MODE=background\nExecStart=${input.command.map(systemdEscape).join(\" \")}\nRestart=always\nRestartSec=5\nStandardOutput=append:${systemdEscape(input.logPath)}\nStandardError=append:${systemdEscape(input.logPath)}\n\n[Install]\nWantedBy=default.target\n`;\n}\n\nfunction runnerServiceFilePath(platform: Exclude<RunnerServicePlatform, \"unsupported\">, serviceName: string, homeDir: string): string {\n if (platform === \"launchd\") {\n return path.join(homeDir, \"Library\", \"LaunchAgents\", `${serviceName}.plist`);\n }\n return path.join(homeDir, \".config\", \"systemd\", \"user\", `${serviceName}.service`);\n}\n\nfunction runnerServiceMetadataPath(input: { accountId: string; projectId: string; repositoryLinkId: string; runnerId: string }, metadataDir: string): string {\n return path.join(metadataDir, `${runnerServiceKey(input)}.service.json`);\n}\n\nfunction runnerServiceName(input: { accountId: string; projectId: string; repositoryLinkId: string; runnerId: string }): string {\n return `com.amistio.runner.${runnerServiceKey(input).slice(0, 20)}`;\n}\n\nfunction runnerServiceKey(input: { accountId: string; projectId: string; repositoryLinkId: string; runnerId: string }): string {\n return createHash(\"sha256\").update(`${input.accountId}:${input.projectId}:${input.repositoryLinkId}:${input.runnerId}`).digest(\"hex\");\n}\n\nfunction launchdDomain(): string {\n const uid = typeof process.getuid === \"function\" ? process.getuid() : undefined;\n return uid === undefined ? \"gui/0\" : `gui/${uid}`;\n}\n\nfunction launchdTarget(metadata: RunnerServiceMetadata): string {\n return `${launchdDomain()}/${metadata.serviceName}`;\n}\n\nfunction xmlEscape(value: string): string {\n return value.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\\\"/g, \"&quot;\").replace(/'/g, \"&apos;\");\n}\n\nfunction systemdEscape(value: string): string {\n return value.includes(\" \") || value.includes(\"\\t\") || value.includes(\"\\\"\") ? `\"${value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\\\"/g, \"\\\\\\\"\")}\"` : value;\n}\n\nfunction runProcess(command: string, args: string[], timeoutMs: number): Promise<{ exitCode: number; output: string }> {\n return new Promise((resolve) => {\n const child = spawn(command, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n let output = \"\";\n const timeout = setTimeout(() => {\n output += `Timed out while running ${command}.\\n`;\n child.kill(\"SIGTERM\");\n }, timeoutMs);\n child.stdout?.on(\"data\", (chunk: Buffer) => { output += chunk.toString(\"utf8\"); });\n child.stderr?.on(\"data\", (chunk: Buffer) => { output += chunk.toString(\"utf8\"); });\n child.on(\"error\", (error) => {\n clearTimeout(timeout);\n resolve({ exitCode: 1, output: error.message });\n });\n child.on(\"close\", (code) => {\n clearTimeout(timeout);\n resolve({ exitCode: code ?? 1, output: output.trim() });\n });\n });\n}\n", "import type { ToolSessionItem } from \"@amistio/shared\";\n\nexport const TOOL_SESSION_MAX_IDLE_MS = 6 * 60 * 60 * 1000;\n\nexport function completedToolSessionStatus(session: Pick<ToolSessionItem, \"resumabilityScope\">): ToolSessionItem[\"status\"] {\n return session.resumabilityScope === \"none\" ? \"closed\" : \"open\";\n}\n\nexport function completedToolSessionClosedReason(session: Pick<ToolSessionItem, \"resumabilityScope\">): string | undefined {\n if (session.resumabilityScope !== \"none\") {\n return undefined;\n }\n return \"Completed one-shot tool run; this session is not reusable.\";\n}\n\nexport function staleToolSessionClosedReason(session: Pick<ToolSessionItem, \"lastActivityAt\" | \"status\">, now: Date = new Date()): string | undefined {\n if (session.status !== \"open\") {\n return undefined;\n }\n const lastActivityMs = Date.parse(session.lastActivityAt);\n if (!Number.isFinite(lastActivityMs)) {\n return \"Session has an invalid last activity timestamp; closing to prevent stale context reuse.\";\n }\n if (lastActivityMs + TOOL_SESSION_MAX_IDLE_MS >= now.getTime()) {\n return undefined;\n }\n return \"Session idle window expired; closing to prevent stale context reuse.\";\n}", "import type { SessionDecision, SessionPolicy, ToolSessionItem, WorkItem } from \"@amistio/shared\";\nimport { TOOL_SESSION_MAX_IDLE_MS } from \"./tool-session-lifecycle.js\";\n\nconst maxTotalMs = 7 * 24 * 60 * 60 * 1000;\nconst maxMessageCount = 80;\nconst maxEstimatedTokens = 120_000;\nconst maxCostUsd = 25;\nconst relatednessThreshold = 20;\n\nexport interface SessionSelectionInput {\n policy: SessionPolicy;\n workItem: WorkItem;\n sessions: ToolSessionItem[];\n toolName: string;\n runnerId: string;\n repositoryLinkId: string;\n machineId: string;\n supportsSessionReuse: boolean;\n now?: Date;\n}\n\nexport interface SessionSelection {\n policy: SessionPolicy;\n decision: SessionDecision;\n reason: string;\n toolSession?: ToolSessionItem;\n}\n\nexport function normalizeSessionPolicy(value: string | undefined): SessionPolicy {\n if (!value || value === \"auto\" || value === \"new\" || value === \"none\") {\n return (value ?? \"auto\") as SessionPolicy;\n }\n\n if (/^continue:[A-Za-z0-9_.:-]+$/.test(value)) {\n return value as SessionPolicy;\n }\n\n throw new Error(`Unsupported session policy: ${value}. Use auto, new, continue:<toolSessionId>, or none.`);\n}\n\nexport function selectToolSession(input: SessionSelectionInput): SessionSelection {\n if (input.policy === \"none\") {\n return { policy: input.policy, decision: \"skipped\", reason: \"Session reuse was disabled for this run.\" };\n }\n\n if (!input.supportsSessionReuse) {\n return {\n policy: input.policy,\n decision: \"notSupported\",\n reason: `${input.toolName} does not expose reusable provider sessions; Amistio will record this as a one-shot tool session.`\n };\n }\n\n if (input.policy === \"new\") {\n return { policy: input.policy, decision: \"forcedNew\", reason: \"The user requested a fresh tool session.\" };\n }\n\n const forcedSessionId = forcedContinueSessionId(input.policy);\n if (forcedSessionId) {\n const forced = input.sessions.find((session) => session.toolSessionId === forcedSessionId);\n if (!forced) {\n return { policy: input.policy, decision: \"forcedNew\", reason: `Requested session ${forcedSessionId} was not found; creating a fresh session.` };\n }\n\n const ineligibleReason = sessionIneligibleReason(forced, input, input.now ?? new Date());\n if (ineligibleReason) {\n return { policy: input.policy, decision: \"forcedNew\", reason: `Requested session ${forcedSessionId} cannot be resumed: ${ineligibleReason}` };\n }\n\n return { policy: input.policy, decision: \"forcedContinue\", reason: `The user requested session ${forcedSessionId}.`, toolSession: forced };\n }\n\n const now = input.now ?? new Date();\n const candidates = input.sessions\n .map((session) => ({ session, ineligibleReason: sessionIneligibleReason(session, input, now), score: relatednessScore(session, input.workItem) }))\n .filter((candidate) => !candidate.ineligibleReason)\n .sort((a, b) => b.score - a.score || Date.parse(b.session.lastActivityAt) - Date.parse(a.session.lastActivityAt));\n\n const best = candidates[0];\n if (!best || best.score < relatednessThreshold) {\n return {\n policy: input.policy,\n decision: \"created\",\n reason: best ? `Best related session score ${best.score} was below ${relatednessThreshold}; creating a fresh session.` : \"No eligible related session was found.\"\n };\n }\n\n return {\n policy: input.policy,\n decision: \"continued\",\n reason: `Reusing ${best.session.toolSessionId}; relatedness score ${best.score}.`,\n toolSession: best.session\n };\n}\n\nfunction forcedContinueSessionId(policy: SessionPolicy) {\n return typeof policy === \"string\" && policy.startsWith(\"continue:\") ? policy.slice(\"continue:\".length) : undefined;\n}\n\nfunction sessionIneligibleReason(session: ToolSessionItem, input: SessionSelectionInput, now: Date): string | undefined {\n if (session.tool !== input.toolName) {\n return `tool mismatch (${session.tool} != ${input.toolName})`;\n }\n if (session.repositoryLinkId && session.repositoryLinkId !== input.repositoryLinkId) {\n return \"repository link mismatch\";\n }\n if (session.machineId && session.machineId !== input.machineId) {\n return \"session is scoped to another machine\";\n }\n if (session.resumabilityScope === \"localMachine\" && session.runnerId && session.runnerId !== input.runnerId) {\n return \"session is scoped to another runner machine\";\n }\n const requestedByUserId = input.workItem.requestedByUserId ?? input.workItem.requestedBy;\n if (session.createdByUserId && session.createdByUserId !== requestedByUserId) {\n return \"session belongs to another requester\";\n }\n if (input.workItem.implementationScopeId && session.implementationScopeId !== input.workItem.implementationScopeId) {\n return \"implementation scope mismatch\";\n }\n if (input.workItem.executionWorktreeKey && session.executionWorktreeKey !== input.workItem.executionWorktreeKey) {\n return \"worktree scope mismatch\";\n }\n if (session.status === \"closed\" || session.status === \"archived\" || session.status === \"blocked\" || session.status === \"unavailable\" || session.status === \"active\") {\n return `session is ${session.status}`;\n }\n if (Date.parse(session.lastActivityAt) + TOOL_SESSION_MAX_IDLE_MS < now.getTime()) {\n return \"session is idle past the reuse window\";\n }\n if (Date.parse(session.createdAt) + maxTotalMs < now.getTime()) {\n return \"session is older than the reuse window\";\n }\n if ((session.messageCount ?? 0) >= maxMessageCount) {\n return \"session message count is too high\";\n }\n if ((session.estimatedInputTokens ?? 0) + (session.estimatedOutputTokens ?? 0) >= maxEstimatedTokens) {\n return \"session token estimate is too high\";\n }\n if ((session.costUsd ?? 0) >= maxCostUsd) {\n return \"session cost is too high\";\n }\n\n return undefined;\n}\n\nfunction relatednessScore(session: ToolSessionItem, workItem: WorkItem): number {\n let score = 0;\n if (session.sessionGroupKey && workItem.sessionGroupKey && session.sessionGroupKey === workItem.sessionGroupKey) {\n score += 60;\n }\n if (session.lastWorkItemId && session.lastWorkItemId === workItem.workItemId) {\n score += 40;\n }\n\n const titleOverlap = tokenOverlap(session.title, workItem.title);\n score += titleOverlap * 8;\n\n if (session.summary) {\n score += tokenOverlap(session.summary, workItem.title) * 4;\n }\n\n for (const tag of session.tags) {\n if (workItem.title.toLowerCase().includes(tag.toLowerCase())) {\n score += 10;\n }\n }\n\n return score;\n}\n\nfunction tokenOverlap(firstValue: string, secondValue: string): number {\n const firstTokens = new Set(tokens(firstValue));\n return tokens(secondValue).filter((token) => firstTokens.has(token)).length;\n}\n\nfunction tokens(value: string): string[] {\n return value\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((token) => token.length >= 4);\n}", "import type { ToolSessionItem, WorkItem } from \"@amistio/shared\";\nimport { completedToolSessionClosedReason, completedToolSessionStatus, staleToolSessionClosedReason } from \"./tool-session-lifecycle.js\";\nimport { selectToolSession } from \"./session-policy.js\";\n\nexport interface RunnerActivationSmokeCheck {\n name: string;\n passed: boolean;\n detail: string;\n}\n\nexport interface RunnerActivationSmokeReport {\n checkedAt: string;\n passed: boolean;\n checks: RunnerActivationSmokeCheck[];\n}\n\nexport function runRunnerActivationSmoke(now: Date = new Date()): RunnerActivationSmokeReport {\n const reusableSession = createSmokeSession({ now, status: \"open\", lastActivityAt: new Date(now.getTime() - 60 * 60 * 1000).toISOString() });\n const activeSession = createSmokeSession({ now, status: \"active\", lastActivityAt: new Date(now.getTime() - 60 * 60 * 1000).toISOString() });\n const staleOpenSession = createSmokeSession({ now, status: \"open\", lastActivityAt: new Date(now.getTime() - 7 * 60 * 60 * 1000).toISOString() });\n const workItem = createSmokeWorkItem(now);\n\n const oneShotStatus = completedToolSessionStatus({ resumabilityScope: \"none\" });\n const oneShotClosedReason = completedToolSessionClosedReason({ resumabilityScope: \"none\" });\n const reusableStatus = completedToolSessionStatus({ resumabilityScope: \"localMachine\" });\n const activeSelection = selectToolSession({\n policy: \"auto\",\n workItem,\n sessions: [activeSession],\n toolName: \"opencode\",\n runnerId: \"runner_smoke\",\n repositoryLinkId: \"repo_smoke\",\n machineId: \"machine_smoke\",\n supportsSessionReuse: true,\n now\n });\n const staleSelection = selectToolSession({\n policy: \"auto\",\n workItem,\n sessions: [staleOpenSession],\n toolName: \"opencode\",\n runnerId: \"runner_smoke\",\n repositoryLinkId: \"repo_smoke\",\n machineId: \"machine_smoke\",\n supportsSessionReuse: true,\n now\n });\n const reusableSelection = selectToolSession({\n policy: \"auto\",\n workItem,\n sessions: [reusableSession],\n toolName: \"opencode\",\n runnerId: \"runner_smoke\",\n repositoryLinkId: \"repo_smoke\",\n machineId: \"machine_smoke\",\n supportsSessionReuse: true,\n now\n });\n const staleClosedReason = staleToolSessionClosedReason(staleOpenSession, now);\n\n const checks: RunnerActivationSmokeCheck[] = [\n {\n name: \"completed-one-shot-closes\",\n passed: oneShotStatus === \"closed\" && Boolean(oneShotClosedReason),\n detail: `completed one-shot status=${oneShotStatus}`\n },\n {\n name: \"completed-reusable-stays-open\",\n passed: reusableStatus === \"open\",\n detail: `completed reusable status=${reusableStatus}`\n },\n {\n name: \"active-session-not-reused\",\n passed: activeSelection.decision === \"created\",\n detail: `active selection decision=${activeSelection.decision}`\n },\n {\n name: \"stale-session-not-reused\",\n passed: staleSelection.decision === \"created\" && Boolean(staleClosedReason),\n detail: `stale selection decision=${staleSelection.decision}`\n },\n {\n name: \"fresh-reusable-session-reused\",\n passed: reusableSelection.decision === \"continued\",\n detail: `fresh reusable selection decision=${reusableSelection.decision}`\n }\n ];\n\n return {\n checkedAt: now.toISOString(),\n passed: checks.every((check) => check.passed),\n checks\n };\n}\n\nfunction createSmokeWorkItem(now: Date): WorkItem {\n const timestamp = now.toISOString();\n return {\n id: \"work_smoke\",\n type: \"workItem\",\n schemaVersion: 1,\n accountId: \"acct_smoke\",\n projectId: \"proj_smoke\",\n workItemId: \"work_smoke\",\n workKind: \"implementation\",\n status: \"running\",\n title: \"Implement runner session smoke\",\n requestedBy: \"user_smoke\",\n requestedByUserId: \"user_smoke\",\n attempt: 1,\n idempotencyKey: \"smoke_session_lifecycle\",\n sessionGroupKey: \"session_smoke\",\n lastStatusAt: timestamp,\n createdAt: timestamp,\n updatedAt: timestamp\n };\n}\n\nfunction createSmokeSession({ now, status, lastActivityAt }: { now: Date; status: ToolSessionItem[\"status\"]; lastActivityAt: string }): ToolSessionItem {\n const timestamp = now.toISOString();\n return {\n id: `tool_session_smoke_${status}`,\n type: \"toolSession\",\n schemaVersion: 1,\n accountId: \"acct_smoke\",\n projectId: \"proj_smoke\",\n toolSessionId: `tool_session_smoke_${status}`,\n repositoryLinkId: \"repo_smoke\",\n tool: \"opencode\",\n provider: \"opencode\",\n resumabilityScope: \"localMachine\",\n title: \"Implement runner session smoke\",\n summary: \"Smoke test session\",\n tags: [\"runner\", \"session\", \"smoke\"],\n relatedDocumentIds: [],\n status,\n runnerId: \"runner_smoke\",\n machineId: \"machine_smoke\",\n lastWorkItemId: \"work_previous\",\n lastActivityAt,\n messageCount: 1,\n reusePolicy: \"auto\",\n sessionGroupKey: \"session_smoke\",\n createdAt: timestamp,\n updatedAt: timestamp\n };\n}", "import { execFile } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { mkdir, readdir, readFile, stat, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { promisify } from \"node:util\";\nimport {\n brainDocumentItemSchema,\n decideSyncState,\n documentTypeForBrainRepoPath,\n documentTypeSchema,\n inferContentFormatFromRepoPath,\n isControlPlaneTemplateRepoPath,\n sha256ContentHash,\n syncedDocumentFrontmatterSchema,\n type BrainDocumentItem,\n type RepoLinkMetadata,\n type SyncedDocumentFrontmatter\n} from \"@amistio/shared\";\nimport { parseFrontmatter } from \"./control-plane.js\";\n\nconst execFileAsync = promisify(execFile);\n\nconst legacySyncRoots = [\"architecture\", \"context\", \"decisions\", \"features\", \"memory\", \"plans\", \"prompts\", \"workflows\"];\nconst syncRoots = legacySyncRoots.map((syncRoot) => `docs/${syncRoot}`);\nconst htmlSyncRoot = \"docs/html\";\nconst documentTypeByRoot = {\n architecture: \"architecture\",\n context: \"context\",\n decisions: \"decision\",\n features: \"feature\",\n memory: \"memory\",\n plans: \"plan\",\n prompts: \"prompt\",\n workflows: \"workflow\"\n} as const;\nconst autoSyncMetadataPaths = new Set([\"docs/context/amistio-project.md\", \"context/amistio-project.md\"]);\nconst autoSyncExcludedDirectoryNames = new Set([\".git\", \"node_modules\", \".pnpm-store\", \".next\", \"dist\", \"build\", \"coverage\", \".cache\", \"cache\", \"tmp\", \"temp\", \"vendor\"]);\nconst autoSyncGeneratedPathSegments = new Set([\"generated\", \"__generated__\", \"vendor\", \"vendors\"]);\nconst defaultAutoSyncMaxFileKb = 256;\n\nexport type SyncStatus = \"clean\" | \"pending\" | \"dirty\" | \"conflicted\";\n\nexport interface LocalSyncedDocument {\n fullPath: string;\n repoPath: string;\n frontmatter: SyncedDocumentFrontmatter;\n content: string;\n contentHash: string;\n}\n\nexport interface SyncStatusItem {\n repoPath: string;\n documentId?: string;\n status: SyncStatus;\n reason: string;\n}\n\nexport interface SyncStatusReport {\n status: SyncStatus;\n items: SyncStatusItem[];\n counts: Record<SyncStatus, number>;\n}\n\nexport interface MaterializeResult {\n written: string[];\n skipped: string[];\n conflicts: string[];\n}\n\nexport type AutoSyncSkipReason = \"metadata\" | \"template\" | \"unsupported\" | \"tooLarge\" | \"alreadyManaged\" | \"unchanged\" | \"conflicted\" | \"excluded\" | \"unreadable\";\n\nexport interface AutoSyncSkippedDocument {\n repoPath: string;\n reason: AutoSyncSkipReason;\n}\n\nexport interface AutoSyncPushCollection {\n documents: BrainDocumentItem[];\n managedDocumentIds: string[];\n skipped: AutoSyncSkippedDocument[];\n counts: Record<AutoSyncSkipReason, number>;\n}\n\nexport interface AutoSyncCollectionOptions {\n maxFileKb?: number;\n syncedAt?: string;\n}\n\nexport async function collectSyncStatus(rootDir: string, webDocuments: BrainDocumentItem[] = []): Promise<SyncStatusReport> {\n const localDocuments = await readLocalSyncedDocuments(rootDir);\n const normalizedWebDocuments = webDocuments.map((document) => ({ ...document, repoPath: canonicalControlPlaneRepoPath(document.repoPath) }));\n const webByDocumentId = new Map(normalizedWebDocuments.map((document) => [document.documentId, document]));\n const pullableWebDocuments = normalizedWebDocuments.filter((document) => !isControlPlaneTemplateRepoPath(document.repoPath) && (document.status === \"approved\" || document.syncState === \"approved\" || document.syncState === \"synced\"));\n const localByDocumentId = new Map(localDocuments.map((document) => [document.frontmatter.amistioDocumentId, document]));\n const items: SyncStatusItem[] = [];\n\n for (const localDocument of localDocuments) {\n const webDocument = webByDocumentId.get(localDocument.frontmatter.amistioDocumentId);\n const localDirty = localDocument.contentHash !== localDocument.frontmatter.amistioContentHash;\n const webHash = webDocument?.contentHash;\n const decision = decideSyncState({\n lastSyncedHash: localDocument.frontmatter.amistioContentHash,\n repoHash: localDocument.contentHash,\n ...(webHash ? { webHash } : {})\n });\n\n if (decision === \"conflict\") {\n items.push({\n repoPath: localDocument.repoPath,\n documentId: localDocument.frontmatter.amistioDocumentId,\n status: \"conflicted\",\n reason: \"web and repository revisions both changed\"\n });\n } else if (localDirty || decision === \"pushRepo\") {\n items.push({\n repoPath: localDocument.repoPath,\n documentId: localDocument.frontmatter.amistioDocumentId,\n status: \"dirty\",\n reason: \"repository content changed since last synced hash\"\n });\n } else if (decision === \"pullWeb\") {\n items.push({\n repoPath: localDocument.repoPath,\n documentId: localDocument.frontmatter.amistioDocumentId,\n status: \"pending\",\n reason: \"approved web revision is newer\"\n });\n } else if (localDocument.frontmatter.status && ![\"approved\", \"synced\"].includes(localDocument.frontmatter.status)) {\n items.push({\n repoPath: localDocument.repoPath,\n documentId: localDocument.frontmatter.amistioDocumentId,\n status: \"pending\",\n reason: `local document is ${localDocument.frontmatter.status}`\n });\n } else {\n items.push({\n repoPath: localDocument.repoPath,\n documentId: localDocument.frontmatter.amistioDocumentId,\n status: \"clean\",\n reason: \"repository and web hashes match\"\n });\n }\n }\n\n for (const webDocument of pullableWebDocuments) {\n if (!localByDocumentId.has(webDocument.documentId)) {\n items.push({\n repoPath: webDocument.repoPath,\n documentId: webDocument.documentId,\n status: \"pending\",\n reason: \"approved web document has not been pulled\"\n });\n }\n }\n\n const counts = {\n clean: items.filter((item) => item.status === \"clean\").length,\n pending: items.filter((item) => item.status === \"pending\").length,\n dirty: items.filter((item) => item.status === \"dirty\").length,\n conflicted: items.filter((item) => item.status === \"conflicted\").length\n } satisfies Record<SyncStatus, number>;\n const status: SyncStatus = counts.conflicted ? \"conflicted\" : counts.dirty ? \"dirty\" : counts.pending ? \"pending\" : \"clean\";\n return { status, items, counts };\n}\n\nexport async function readLocalSyncedDocuments(rootDir: string): Promise<LocalSyncedDocument[]> {\n const documentFiles = await findBrainDocumentFiles(rootDir);\n const documents: LocalSyncedDocument[] = [];\n for (const fullPath of documentFiles) {\n const raw = await readFile(fullPath, \"utf8\");\n const repoPath = toRepoPath(rootDir, fullPath);\n const parsed = parseSyncedDocument(raw, repoPath);\n if (!parsed) {\n continue;\n }\n\n if (isControlPlaneTemplateRepoPath(repoPath)) {\n continue;\n }\n\n documents.push({\n fullPath,\n repoPath,\n frontmatter: parsed.frontmatter,\n content: parsed.content,\n contentHash: sha256ContentHash(parsed.content)\n });\n }\n\n return documents;\n}\n\nexport async function materializeBrainDocuments(rootDir: string, documents: BrainDocumentItem[], options: { allowDirtyOverwrite?: boolean } = {}): Promise<MaterializeResult> {\n const result: MaterializeResult = { written: [], skipped: [], conflicts: [] };\n for (const inputDocument of documents) {\n const parsedDocument = brainDocumentItemSchema.parse(inputDocument);\n const document = { ...parsedDocument, repoPath: canonicalControlPlaneRepoPath(parsedDocument.repoPath) };\n const fullPath = safeRepoPath(rootDir, document.repoPath);\n if (isControlPlaneTemplateRepoPath(document.repoPath)) {\n result.skipped.push(document.repoPath);\n continue;\n }\n if (!isControlPlanePath(document.repoPath)) {\n result.conflicts.push(`${document.repoPath}: refusing to write outside docs control-plane folders`);\n continue;\n }\n\n const existing = await readExistingSyncedDocument(fullPath);\n if (existing.exists && !existing.document) {\n result.conflicts.push(`${document.repoPath}: file exists without Amistio document metadata`);\n continue;\n }\n if (existing.document && existing.document.frontmatter.amistioDocumentId !== document.documentId) {\n result.conflicts.push(`${document.repoPath}: file belongs to ${existing.document.frontmatter.amistioDocumentId}`);\n continue;\n }\n if (existing.document && existing.document.contentHash !== existing.document.frontmatter.amistioContentHash && !options.allowDirtyOverwrite) {\n result.conflicts.push(`${document.repoPath}: local edits would be overwritten`);\n continue;\n }\n if (existing.document && existing.document.frontmatter.amistioRevision >= document.revision && existing.document.contentHash === document.contentHash) {\n result.skipped.push(document.repoPath);\n continue;\n }\n\n await mkdir(path.dirname(fullPath), { recursive: true });\n await writeFile(fullPath, createSyncedDocumentContent(document), \"utf8\");\n result.written.push(document.repoPath);\n }\n\n return result;\n}\n\nexport async function collectDirtyDocumentsForPush(rootDir: string, metadata: RepoLinkMetadata): Promise<BrainDocumentItem[]> {\n const localDocuments = await readLocalSyncedDocuments(rootDir);\n const now = new Date().toISOString();\n return localDocuments\n .filter((document) => document.contentHash !== document.frontmatter.amistioContentHash)\n .map((document) => {\n const documentType = documentTypeSchema.parse(document.frontmatter.amistioDocumentType);\n return brainDocumentItemSchema.parse({\n id: document.frontmatter.amistioDocumentId,\n type: \"brainDocument\",\n schemaVersion: 1,\n accountId: metadata.amistioAccountId,\n projectId: metadata.amistioProjectId,\n documentId: document.frontmatter.amistioDocumentId,\n documentType,\n contentFormat: document.frontmatter.amistioContentFormat,\n title: inferTitle(document.content, document.repoPath),\n status: \"reviewing\",\n repoPath: document.repoPath,\n content: document.content,\n contentHash: document.contentHash,\n frontmatter: parseFrontmatterFromSyncedDocument(document.frontmatter),\n revision: document.frontmatter.amistioRevision + 1,\n source: \"repo\",\n syncState: \"dirtyInRepo\",\n createdAt: now,\n updatedAt: now\n });\n });\n}\n\nexport async function collectAutoSyncDocumentsForPush(rootDir: string, metadata: RepoLinkMetadata, existingDocuments: BrainDocumentItem[] = [], options: AutoSyncCollectionOptions = {}): Promise<AutoSyncPushCollection> {\n const dirtyDocuments = await collectDirtyDocumentsForPush(rootDir, metadata);\n const external = await collectExternalBrainDocumentsForPush(rootDir, metadata, existingDocuments, options);\n return {\n documents: [...dirtyDocuments, ...external.documents],\n managedDocumentIds: dirtyDocuments.map((document) => document.documentId),\n skipped: external.skipped,\n counts: autoSyncSkipCounts(external.skipped)\n };\n}\n\nexport function autoSyncSkipCounts(skipped: AutoSyncSkippedDocument[]): Record<AutoSyncSkipReason, number> {\n return {\n metadata: skipped.filter((item) => item.reason === \"metadata\").length,\n template: skipped.filter((item) => item.reason === \"template\").length,\n unsupported: skipped.filter((item) => item.reason === \"unsupported\").length,\n tooLarge: skipped.filter((item) => item.reason === \"tooLarge\").length,\n alreadyManaged: skipped.filter((item) => item.reason === \"alreadyManaged\").length,\n unchanged: skipped.filter((item) => item.reason === \"unchanged\").length,\n conflicted: skipped.filter((item) => item.reason === \"conflicted\").length,\n excluded: skipped.filter((item) => item.reason === \"excluded\").length,\n unreadable: skipped.filter((item) => item.reason === \"unreadable\").length\n };\n}\n\nexport function createSyncedDocumentMarkdown(document: BrainDocumentItem): string {\n return createSyncedDocumentMarkdownContent(document);\n}\n\nexport function createSyncedDocumentContent(document: BrainDocumentItem): string {\n return (document.contentFormat ?? inferContentFormatFromRepoPath(document.repoPath) ?? \"markdown\") === \"html\" ? createSyncedDocumentHtml(document) : createSyncedDocumentMarkdownContent(document);\n}\n\nfunction createSyncedDocumentMarkdownContent(document: BrainDocumentItem): string {\n return [\n \"---\",\n `amistioDocumentId: ${document.documentId}`,\n `amistioDocumentType: ${document.documentType}`,\n `amistioContentFormat: ${document.contentFormat ?? \"markdown\"}`,\n `amistioRevision: ${document.revision}`,\n `amistioContentHash: ${document.contentHash}`,\n `status: ${document.status}`,\n \"---\",\n document.content,\n \"\"\n ].join(\"\\n\");\n}\n\nfunction createSyncedDocumentHtml(document: BrainDocumentItem): string {\n return [\n \"<!--\",\n `amistioDocumentId: ${document.documentId}`,\n `amistioDocumentType: ${document.documentType}`,\n \"amistioContentFormat: html\",\n `amistioRevision: ${document.revision}`,\n `amistioContentHash: ${document.contentHash}`,\n `status: ${document.status}`,\n \"-->\",\n document.content,\n \"\"\n ].join(\"\\n\");\n}\n\nfunction parseSyncedDocument(content: string, repoPath: string): { frontmatter: SyncedDocumentFrontmatter; content: string } | undefined {\n const format = inferContentFormatFromRepoPath(repoPath);\n return format === \"html\" ? parseSyncedHtml(content) : parseSyncedMarkdown(content);\n}\n\nfunction parseSyncedMarkdown(content: string): { frontmatter: SyncedDocumentFrontmatter; content: string } | undefined {\n const rawFrontmatter = parseFrontmatter(content);\n const frontmatter = syncedDocumentFrontmatterSchema.safeParse(rawFrontmatter);\n if (!frontmatter.success) {\n return undefined;\n }\n\n const closingMarker = content.indexOf(\"\\n---\", 4);\n if (closingMarker === -1) {\n return undefined;\n }\n const closingLineEnd = content.indexOf(\"\\n\", closingMarker + 4);\n const bodyStart = closingLineEnd === -1 ? content.length : closingLineEnd + 1;\n return { frontmatter: frontmatter.data, content: content.slice(bodyStart).replace(/\\n$/, \"\") };\n}\n\nfunction parseSyncedHtml(content: string): { frontmatter: SyncedDocumentFrontmatter; content: string } | undefined {\n const trimmedStart = content.trimStart();\n if (!trimmedStart.startsWith(\"<!--\")) {\n return undefined;\n }\n const startOffset = content.indexOf(\"<!--\");\n const closingMarker = content.indexOf(\"-->\", startOffset + 4);\n if (closingMarker === -1) {\n return undefined;\n }\n const metadataLines = content.slice(startOffset + 4, closingMarker).split(/\\r?\\n/);\n const metadata = Object.fromEntries(metadataLines.map((line) => {\n const separator = line.indexOf(\":\");\n return separator === -1 ? undefined : [line.slice(0, separator).trim(), line.slice(separator + 1).trim()];\n }).filter((entry): entry is [string, string] => Boolean(entry?.[0])));\n const frontmatter = syncedDocumentFrontmatterSchema.safeParse({ ...metadata, amistioContentFormat: \"html\" });\n if (!frontmatter.success) {\n return undefined;\n }\n const bodyStart = content.indexOf(\"\\n\", closingMarker + 3);\n return { frontmatter: frontmatter.data, content: content.slice(bodyStart === -1 ? closingMarker + 3 : bodyStart + 1).replace(/\\n$/, \"\") };\n}\n\nasync function readExistingSyncedDocument(fullPath: string): Promise<{ exists: boolean; document?: LocalSyncedDocument }> {\n try {\n const raw = await readFile(fullPath, \"utf8\");\n const parsed = parseSyncedDocument(raw, fullPath);\n if (!parsed) {\n return { exists: true };\n }\n\n return {\n exists: true,\n document: {\n fullPath,\n repoPath: fullPath,\n frontmatter: parsed.frontmatter,\n content: parsed.content,\n contentHash: sha256ContentHash(parsed.content)\n }\n };\n } catch (error: unknown) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n return { exists: false };\n }\n throw error;\n }\n}\n\nasync function findBrainDocumentFiles(rootDir: string): Promise<string[]> {\n const files: string[] = [];\n for (const syncRoot of [...syncRoots, htmlSyncRoot]) {\n const fullRoot = path.join(rootDir, syncRoot);\n if (!(await exists(fullRoot))) {\n continue;\n }\n await walkBrainDocumentFiles(fullRoot, files);\n }\n return files;\n}\n\nasync function walkBrainDocumentFiles(directory: string, files: string[]): Promise<void> {\n for (const entry of await readdir(directory, { withFileTypes: true })) {\n const fullPath = path.join(directory, entry.name);\n if (entry.isDirectory()) {\n await walkBrainDocumentFiles(fullPath, files);\n } else if (entry.isFile() && /\\.(md|mdx|html?)$/i.test(entry.name)) {\n files.push(fullPath);\n }\n }\n}\n\nfunction safeRepoPath(rootDir: string, repoPath: string): string {\n if (path.isAbsolute(repoPath)) {\n throw new Error(`Refusing to use absolute repo path: ${repoPath}`);\n }\n const normalized = path.normalize(repoPath);\n if (normalized === \"..\" || normalized.startsWith(`..${path.sep}`)) {\n throw new Error(`Refusing to use path outside the repository: ${repoPath}`);\n }\n const root = path.resolve(rootDir);\n const fullPath = path.resolve(root, normalized);\n if (!fullPath.startsWith(`${root}${path.sep}`)) {\n throw new Error(`Refusing to use path outside the repository: ${repoPath}`);\n }\n return fullPath;\n}\n\nfunction isControlPlanePath(repoPath: string): boolean {\n const normalized = path.normalize(repoPath);\n return syncRoots.some((syncRoot) => normalized === syncRoot || normalized.startsWith(`${syncRoot}${path.sep}`)) || normalized === htmlSyncRoot || normalized.startsWith(`${htmlSyncRoot}${path.sep}`);\n}\n\nexport function canonicalControlPlaneRepoPath(repoPath: string): string {\n const normalized = repoPath.replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\").replace(/^\\/+/, \"\");\n const [firstSegment] = normalized.split(\"/\");\n if (firstSegment && legacySyncRoots.includes(firstSegment)) {\n return `docs/${normalized}`;\n }\n return normalized;\n}\n\nfunction toRepoPath(rootDir: string, fullPath: string): string {\n return path.relative(rootDir, fullPath).split(path.sep).join(\"/\");\n}\n\nfunction inferTitle(content: string, repoPath: string): string {\n const heading = content.split(\"\\n\").find((line) => line.startsWith(\"# \"))?.replace(/^#\\s+/, \"\").trim();\n if (heading) return heading;\n const htmlHeading = content.match(/<h1\\b[^>]*>([\\s\\S]*?)<\\/h1>/i)?.[1]?.replace(/<[^>]+>/g, \"\").trim();\n return htmlHeading || path.basename(repoPath, path.extname(repoPath));\n}\n\nasync function collectExternalBrainDocumentsForPush(rootDir: string, metadata: RepoLinkMetadata, existingDocuments: BrainDocumentItem[], options: AutoSyncCollectionOptions): Promise<{ documents: BrainDocumentItem[]; skipped: AutoSyncSkippedDocument[] }> {\n const root = path.resolve(rootDir);\n const maxBytes = (options.maxFileKb ?? defaultAutoSyncMaxFileKb) * 1024;\n const syncedAt = options.syncedAt ?? new Date().toISOString();\n const existingById = new Map(existingDocuments.map((document) => [document.documentId, document]));\n const repoPaths = await listAutoSyncCandidatePaths(root);\n const documents: BrainDocumentItem[] = [];\n const skipped: AutoSyncSkippedDocument[] = [];\n\n for (const repoPath of repoPaths) {\n const normalizedRepoPath = normalizeRepoPath(repoPath);\n const canonicalRepoPath = canonicalControlPlaneRepoPath(normalizedRepoPath);\n const skipReason = autoSyncPathSkipReason(normalizedRepoPath);\n if (skipReason) {\n skipped.push({ repoPath: normalizedRepoPath, reason: skipReason });\n continue;\n }\n\n const fullPath = safeRepoPath(root, normalizedRepoPath);\n const fileStat = await stat(fullPath).catch(() => undefined);\n if (!fileStat?.isFile()) {\n skipped.push({ repoPath: normalizedRepoPath, reason: \"unreadable\" });\n continue;\n }\n if (fileStat.size > maxBytes) {\n skipped.push({ repoPath: normalizedRepoPath, reason: \"tooLarge\" });\n continue;\n }\n\n const content = await readFile(fullPath, \"utf8\").catch(() => undefined);\n if (content === undefined) {\n skipped.push({ repoPath: normalizedRepoPath, reason: \"unreadable\" });\n continue;\n }\n if (parseSyncedDocument(content, normalizedRepoPath)) {\n skipped.push({ repoPath: normalizedRepoPath, reason: \"alreadyManaged\" });\n continue;\n }\n\n const documentType = documentTypeForRepoPath(canonicalRepoPath);\n if (!documentType) {\n skipped.push({ repoPath: normalizedRepoPath, reason: \"unsupported\" });\n continue;\n }\n\n const contentHash = sha256ContentHash(content);\n const documentId = stableExternalDocumentId(metadata, canonicalRepoPath);\n const existing = existingById.get(documentId);\n if (existing?.syncState === \"conflicted\" || existing?.status === \"conflicted\") {\n skipped.push({ repoPath: normalizedRepoPath, reason: \"conflicted\" });\n continue;\n }\n const lastAutoSyncedHash = typeof existing?.frontmatter.autoSyncedSourceHash === \"string\" ? existing.frontmatter.autoSyncedSourceHash : undefined;\n if (existing?.contentHash === contentHash || lastAutoSyncedHash === contentHash) {\n skipped.push({ repoPath: normalizedRepoPath, reason: \"unchanged\" });\n continue;\n }\n\n const revision = existing ? existing.revision + 1 : 0;\n documents.push(brainDocumentItemSchema.parse({\n id: documentId,\n type: \"brainDocument\",\n schemaVersion: 1,\n accountId: metadata.amistioAccountId,\n projectId: metadata.amistioProjectId,\n documentId,\n documentType,\n contentFormat: inferContentFormatFromRepoPath(canonicalRepoPath) ?? \"markdown\",\n title: inferTitle(content, canonicalRepoPath),\n status: \"reviewing\",\n repoPath: canonicalRepoPath,\n content,\n contentHash,\n frontmatter: {\n ...(existing?.frontmatter ?? {}),\n externalBrainPath: normalizedRepoPath,\n autoSyncedByCommand: \"amistio sync watch\",\n autoSyncedAt: syncedAt,\n autoSyncedSourceHash: contentHash,\n ...(lastAutoSyncedHash ? { amistioContentHash: lastAutoSyncedHash } : {})\n },\n revision,\n source: \"repo\",\n syncState: \"dirtyInRepo\",\n createdAt: existing?.createdAt ?? syncedAt,\n updatedAt: syncedAt\n }));\n }\n\n return { documents, skipped };\n}\n\nasync function listAutoSyncCandidatePaths(rootDir: string): Promise<string[]> {\n const gitFiles = await execFileAsync(\"git\", [\"-C\", rootDir, \"ls-files\", \"--cached\", \"--others\", \"--exclude-standard\"]).then(({ stdout }) => stdout).catch(() => undefined);\n if (gitFiles !== undefined) {\n return uniqueSortedRepoPaths(gitFiles.split(\"\\n\").map(normalizeRepoPath).filter((repoPath) => repoPath && isRecognizedBrainRepoPath(repoPath)));\n }\n\n const files: string[] = [];\n for (const syncRoot of [...syncRoots, htmlSyncRoot, ...legacySyncRoots]) {\n const fullRoot = path.join(rootDir, syncRoot);\n if (await exists(fullRoot)) {\n await walkAutoSyncFiles(rootDir, fullRoot, files);\n }\n }\n return uniqueSortedRepoPaths(files);\n}\n\nasync function walkAutoSyncFiles(rootDir: string, directory: string, files: string[]): Promise<void> {\n for (const entry of await readdir(directory, { withFileTypes: true }).catch(() => [])) {\n const fullPath = path.join(directory, entry.name);\n const repoPath = normalizeRepoPath(path.relative(rootDir, fullPath));\n if (entry.isDirectory()) {\n if (!autoSyncExcludedDirectoryNames.has(entry.name)) {\n await walkAutoSyncFiles(rootDir, fullPath, files);\n }\n } else if (entry.isFile() && isRecognizedBrainRepoPath(repoPath)) {\n files.push(repoPath);\n }\n }\n}\n\nfunction autoSyncPathSkipReason(repoPath: string): AutoSyncSkipReason | undefined {\n if (autoSyncMetadataPaths.has(repoPath)) return \"metadata\";\n if (isControlPlaneTemplateRepoPath(repoPath)) return \"template\";\n if (!/\\.(md|mdx|html?)$/i.test(repoPath)) return \"unsupported\";\n const basename = repoPath.split(\"/\").at(-1)?.toLowerCase() ?? \"\";\n if (basename.startsWith(\".\") || basename.endsWith(\".lock\") || basename.includes(\".env\") || basename.includes(\"secret\") || basename.includes(\"credential\")) return \"excluded\";\n if (repoPath.split(\"/\").some((segment) => autoSyncExcludedDirectoryNames.has(segment) || autoSyncGeneratedPathSegments.has(segment))) return \"excluded\";\n return undefined;\n}\n\nfunction isRecognizedBrainRepoPath(repoPath: string): boolean {\n const normalized = normalizeRepoPath(repoPath);\n const [firstSegment, secondSegment, thirdSegment] = normalized.split(\"/\");\n return Boolean((firstSegment === \"docs\" && secondSegment === \"html\" && thirdSegment && legacySyncRoots.includes(thirdSegment)) || (firstSegment === \"docs\" && secondSegment && legacySyncRoots.includes(secondSegment)) || (firstSegment && legacySyncRoots.includes(firstSegment)));\n}\n\nfunction documentTypeForRepoPath(repoPath: string): SyncedDocumentFrontmatter[\"amistioDocumentType\"] | undefined {\n return documentTypeForBrainRepoPath(repoPath) ?? legacyDocumentTypeForRepoPath(repoPath);\n}\n\nfunction legacyDocumentTypeForRepoPath(repoPath: string): SyncedDocumentFrontmatter[\"amistioDocumentType\"] | undefined {\n const normalized = normalizeRepoPath(repoPath);\n const segments = normalized.split(\"/\");\n const root = segments[0] === \"docs\" ? segments[1] : segments[0];\n return root && root in documentTypeByRoot ? documentTypeByRoot[root as keyof typeof documentTypeByRoot] : undefined;\n}\n\nfunction stableExternalDocumentId(metadata: RepoLinkMetadata, repoPath: string): string {\n return `doc_external_${createHash(\"sha256\").update(`${metadata.amistioAccountId}:${metadata.amistioProjectId}:${metadata.repositoryLinkId}:${repoPath}`).digest(\"hex\").slice(0, 24)}`;\n}\n\nfunction normalizeRepoPath(repoPath: string): string {\n return repoPath.replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\").replace(/^\\/+/, \"\");\n}\n\nfunction uniqueSortedRepoPaths(repoPaths: string[]): string[] {\n return [...new Set(repoPaths)].sort((first, second) => first.localeCompare(second));\n}\n\nfunction parseFrontmatterFromSyncedDocument(frontmatter: SyncedDocumentFrontmatter): Record<string, unknown> {\n return {\n amistioDocumentId: frontmatter.amistioDocumentId,\n amistioDocumentType: frontmatter.amistioDocumentType,\n amistioContentFormat: frontmatter.amistioContentFormat,\n amistioRevision: frontmatter.amistioRevision,\n amistioContentHash: frontmatter.amistioContentHash,\n ...(frontmatter.status ? { status: frontmatter.status } : {})\n };\n}\n\nasync function exists(filePath: string): Promise<boolean> {\n try {\n await stat(filePath);\n return true;\n } catch {\n return false;\n }\n}", "import { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\ninterface ProviderSessionRecord {\n toolName: string;\n providerSessionId: string;\n updatedAt: string;\n}\n\ntype ProviderSessionFile = Record<string, ProviderSessionRecord>;\n\nexport class LocalToolSessionStore {\n constructor(private readonly filePath = defaultSessionStorePath()) { }\n\n async getProviderSessionId(toolSessionId: string, toolName: string): Promise<string | undefined> {\n const data = await this.read();\n const record = data[toolSessionId];\n return record?.toolName === toolName ? record.providerSessionId : undefined;\n }\n\n async setProviderSessionId(toolSessionId: string, toolName: string, providerSessionId: string): Promise<void> {\n const data = await this.read();\n data[toolSessionId] = { toolName, providerSessionId, updatedAt: new Date().toISOString() };\n await mkdir(path.dirname(this.filePath), { recursive: true });\n await writeFile(this.filePath, JSON.stringify(data, null, 2), \"utf8\");\n }\n\n private async read(): Promise<ProviderSessionFile> {\n try {\n return JSON.parse(await readFile(this.filePath, \"utf8\")) as ProviderSessionFile;\n } catch {\n return {};\n }\n }\n}\n\nfunction defaultSessionStorePath() {\n if (process.platform === \"darwin\") {\n return path.join(os.homedir(), \"Library\", \"Application Support\", \"Amistio\", \"tool-sessions.json\");\n }\n if (process.platform === \"win32\") {\n return path.join(process.env.APPDATA ?? os.homedir(), \"Amistio\", \"tool-sessions.json\");\n }\n return path.join(process.env.XDG_STATE_HOME ?? path.join(os.homedir(), \".local\", \"state\"), \"amistio\", \"tool-sessions.json\");\n}", "import path from \"node:path\";\nimport { appEvaluationScanResultSchema, assistantAnswerResultSchema, brainConsolidationScanResultSchema, brainGenerationResultSchema, formatWorkFailureGuidanceDetail, getWorkFailureGuidance, impactPreviewResultSchema, implementationTestGateResultSchema, implementationVerificationResultSchema, issueDiagnosisResultSchema, projectContextRefreshResultSchema, securityPostureScanResultSchema, testQualityScanResultSchema, type AppEvaluationScanResult, type AssistantAnswerResult, type AssistantMessageItem, type BrainConsolidationScanResult, type BrainDocumentItem, type GeneratedBrainArtifact, type ImpactPreviewResult, type ImplementationTestGateResult, type ImplementationVerificationResult, type IssueDiagnosisResult, type IssueItem, type PlanReviewMessageItem, type ProjectContextMapItem, type ProjectContextPack, type ProjectContextRefreshItem, type ProjectContextRefreshResult, type SecurityPostureScanResult, type TestQualityScanResult, type WorkItem } from \"@amistio/shared\";\n\nconst generationResultStart = \"AMISTIO_BRAIN_GENERATION_RESULT_START\";\nconst generationResultEnd = \"AMISTIO_BRAIN_GENERATION_RESULT_END\";\nconst assistantAnswerStart = \"AMISTIO_ASSISTANT_ANSWER_START\";\nconst assistantAnswerEnd = \"AMISTIO_ASSISTANT_ANSWER_END\";\nconst impactPreviewStart = \"AMISTIO_IMPACT_PREVIEW_START\";\nconst impactPreviewEnd = \"AMISTIO_IMPACT_PREVIEW_END\";\nconst issueDiagnosisStart = \"AMISTIO_ISSUE_DIAGNOSIS_START\";\nconst issueDiagnosisEnd = \"AMISTIO_ISSUE_DIAGNOSIS_END\";\nconst securityPostureStart = \"AMISTIO_SECURITY_POSTURE_START\";\nconst securityPostureEnd = \"AMISTIO_SECURITY_POSTURE_END\";\nconst appEvaluationStart = \"AMISTIO_APP_EVALUATION_START\";\nconst appEvaluationEnd = \"AMISTIO_APP_EVALUATION_END\";\nconst brainConsolidationStart = \"AMISTIO_BRAIN_CONSOLIDATION_START\";\nconst brainConsolidationEnd = \"AMISTIO_BRAIN_CONSOLIDATION_END\";\nconst projectContextRefreshStart = \"AMISTIO_PROJECT_CONTEXT_REFRESH_START\";\nconst projectContextRefreshEnd = \"AMISTIO_PROJECT_CONTEXT_REFRESH_END\";\nconst implementationVerificationStart = \"AMISTIO_IMPLEMENTATION_VERIFICATION_START\";\nconst implementationVerificationEnd = \"AMISTIO_IMPLEMENTATION_VERIFICATION_END\";\nconst testQualityStart = \"AMISTIO_TEST_QUALITY_START\";\nconst testQualityEnd = \"AMISTIO_TEST_QUALITY_END\";\nconst implementationTestGateStart = \"AMISTIO_IMPLEMENTATION_TEST_GATE_START\";\nconst implementationTestGateEnd = \"AMISTIO_IMPLEMENTATION_TEST_GATE_END\";\nconst projectContextMissingAreaMaxLength = 160;\nconst projectContextCoverageWarningMaxLength = 300;\nconst projectContextVerificationPlanMaxLength = 300;\nconst projectContextTopLevelWarningMaxLength = 600;\nconst validProjectContextSliceKinds = new Set([\"overview\", \"architecture\", \"domain\", \"data\", \"api\", \"frontend\", \"backend\", \"cli\", \"workflow\", \"operations\", \"security\", \"testing\", \"unknown\"]);\nconst validProjectContextEntityTypes = new Set([\"project\", \"system\", \"component\", \"domain\", \"tool\", \"decision\", \"feature\", \"risk\", \"team\", \"workflow\", \"unknown\"]);\nconst validProjectContextRelationTypes = new Set([\"uses\", \"depends_on\", \"decides\", \"supersedes\", \"touches\", \"blocks\", \"implements\", \"mentions\"]);\nconst canonicalAppEvaluationCategories = new Map<string, string>([\n [\"verification\", \"verification\"],\n [\"verify\", \"verification\"],\n [\"test\", \"verification\"],\n [\"tests\", \"verification\"],\n [\"testing\", \"verification\"],\n [\"check\", \"verification\"],\n [\"checks\", \"verification\"],\n [\"ci\", \"verification\"],\n [\"continuousintegration\", \"verification\"],\n [\"qa\", \"verification\"],\n [\"qualityassurance\", \"verification\"],\n [\"build\", \"verification\"],\n [\"lint\", \"verification\"],\n [\"linting\", \"verification\"],\n [\"typecheck\", \"verification\"],\n [\"typechecking\", \"verification\"],\n [\"productdrift\", \"productDrift\"],\n [\"drift\", \"productDrift\"],\n [\"docs\", \"productDrift\"],\n [\"doc\", \"productDrift\"],\n [\"documentation\", \"productDrift\"],\n [\"docsdrift\", \"productDrift\"],\n [\"documentationdrift\", \"productDrift\"],\n [\"contextdrift\", \"productDrift\"],\n [\"productdocumentationdrift\", \"productDrift\"],\n [\"plancleanup\", \"planCleanup\"],\n [\"plan\", \"planCleanup\"],\n [\"plans\", \"planCleanup\"],\n [\"staleplan\", \"planCleanup\"],\n [\"staleplans\", \"planCleanup\"],\n [\"cleanup\", \"planCleanup\"],\n [\"cleanupplan\", \"planCleanup\"],\n [\"superseded\", \"planCleanup\"],\n [\"obsolete\", \"planCleanup\"],\n [\"promptrot\", \"promptRot\"],\n [\"prompt\", \"promptRot\"],\n [\"prompts\", \"promptRot\"],\n [\"template\", \"promptRot\"],\n [\"templates\", \"promptRot\"],\n [\"instruction\", \"promptRot\"],\n [\"instructions\", \"promptRot\"],\n [\"runnerprompt\", \"promptRot\"],\n [\"runnerprompttemplate\", \"promptRot\"],\n [\"prompttemplate\", \"promptRot\"],\n [\"missingmemory\", \"missingMemory\"],\n [\"memory\", \"missingMemory\"],\n [\"memories\", \"missingMemory\"],\n [\"lesson\", \"missingMemory\"],\n [\"lessons\", \"missingMemory\"],\n [\"workflow\", \"missingMemory\"],\n [\"workflowlesson\", \"missingMemory\"],\n [\"workflows\", \"missingMemory\"],\n [\"releasereadiness\", \"releaseReadiness\"],\n [\"release\", \"releaseReadiness\"],\n [\"deploy\", \"releaseReadiness\"],\n [\"deployment\", \"releaseReadiness\"],\n [\"readiness\", \"releaseReadiness\"],\n [\"production\", \"releaseReadiness\"],\n [\"productionreadiness\", \"releaseReadiness\"],\n [\"ux\", \"ux\"],\n [\"ui\", \"ux\"],\n [\"userexperience\", \"ux\"],\n [\"accessibility\", \"accessibility\"],\n [\"a11y\", \"accessibility\"],\n [\"accessible\", \"accessibility\"],\n [\"performance\", \"performance\"],\n [\"perf\", \"performance\"],\n [\"reliability\", \"reliability\"],\n [\"resilience\", \"reliability\"],\n [\"resiliency\", \"reliability\"],\n [\"stability\", \"reliability\"],\n [\"uptime\", \"reliability\"],\n [\"securityposture\", \"securityPosture\"],\n [\"security\", \"securityPosture\"],\n [\"posture\", \"securityPosture\"],\n [\"vulnerability\", \"securityPosture\"],\n [\"vulnerabilities\", \"securityPosture\"],\n [\"vulnerabilityposture\", \"securityPosture\"],\n [\"other\", \"other\"],\n [\"technicaldebt\", \"other\"],\n [\"debt\", \"other\"],\n [\"maintainability\", \"other\"],\n [\"codequality\", \"other\"],\n [\"architecture\", \"other\"],\n [\"operations\", \"other\"],\n [\"ops\", \"other\"]\n]);\nconst canonicalTestCommandKinds = new Map<string, string>([\n [\"verify\", \"verify\"],\n [\"verification\", \"verify\"],\n [\"wholeapp\", \"verify\"],\n [\"wholeappverification\", \"verify\"],\n [\"full\", \"verify\"],\n [\"fullcheck\", \"verify\"],\n [\"fullchecks\", \"verify\"],\n [\"allcheck\", \"verify\"],\n [\"allchecks\", \"verify\"],\n [\"ci\", \"verify\"],\n [\"continuousintegration\", \"verify\"],\n [\"test\", \"test\"],\n [\"tests\", \"test\"],\n [\"testing\", \"test\"],\n [\"unittest\", \"test\"],\n [\"unittests\", \"test\"],\n [\"integrationtest\", \"test\"],\n [\"integrationtests\", \"test\"],\n [\"e2etest\", \"test\"],\n [\"e2etests\", \"test\"],\n [\"endtoend\", \"test\"],\n [\"endtoendtest\", \"test\"],\n [\"spec\", \"test\"],\n [\"specs\", \"test\"],\n [\"suite\", \"test\"],\n [\"testsuite\", \"test\"],\n [\"jest\", \"test\"],\n [\"vitest\", \"test\"],\n [\"coverage\", \"coverage\"],\n [\"coveragereport\", \"coverage\"],\n [\"lint\", \"lint\"],\n [\"linting\", \"lint\"],\n [\"eslint\", \"lint\"],\n [\"format\", \"lint\"],\n [\"formatting\", \"lint\"],\n [\"style\", \"lint\"],\n [\"quality\", \"lint\"],\n [\"qualitycheck\", \"lint\"],\n [\"staticanalysis\", \"lint\"],\n [\"typecheck\", \"typecheck\"],\n [\"typechecks\", \"typecheck\"],\n [\"typechecking\", \"typecheck\"],\n [\"typecheck\", \"typecheck\"],\n [\"tsc\", \"typecheck\"],\n [\"typescript\", \"typecheck\"],\n [\"build\", \"build\"],\n [\"compile\", \"build\"],\n [\"focused\", \"focused\"],\n [\"focus\", \"focused\"],\n [\"targeted\", \"focused\"],\n [\"scoped\", \"focused\"],\n [\"package\", \"focused\"],\n [\"packaged\", \"focused\"],\n [\"affected\", \"focused\"],\n [\"affectedtests\", \"focused\"],\n [\"touched\", \"focused\"],\n [\"touchedtests\", \"focused\"],\n [\"changed\", \"focused\"],\n [\"changedtests\", \"focused\"],\n [\"other\", \"focused\"]\n]);\nconst canonicalProjectContextCitationSources = new Map([\n [\"projectbrain\", \"projectBrain\"],\n [\"approvedbrain\", \"projectBrain\"],\n [\"approvedprojectbrain\", \"projectBrain\"],\n [\"localsource\", \"localSource\"],\n [\"runnerstate\", \"runnerState\"],\n [\"mixed\", \"mixed\"]\n]);\nconst canonicalProjectContextFreshnessValues = new Map([\n [\"fresh\", \"fresh\"],\n [\"current\", \"fresh\"],\n [\"uptodate\", \"fresh\"],\n [\"accurate\", \"fresh\"],\n [\"stale\", \"stale\"],\n [\"outdated\", \"stale\"],\n [\"outofdate\", \"stale\"],\n [\"old\", \"stale\"],\n [\"historical\", \"stale\"],\n [\"partial\", \"partial\"],\n [\"partiallyfresh\", \"partial\"],\n [\"incomplete\", \"partial\"],\n [\"mixed\", \"partial\"],\n [\"missing\", \"missing\"],\n [\"absent\", \"missing\"],\n [\"notfound\", \"missing\"],\n [\"notpresent\", \"missing\"]\n]);\n\ninterface PlanRevisionPromptContext {\n planDocument: BrainDocumentItem;\n messages: PlanReviewMessageItem[];\n}\n\ninterface AssistantQuestionPromptContext {\n question: AssistantMessageItem;\n messages: AssistantMessageItem[];\n documents: BrainDocumentItem[];\n activeMap?: ProjectContextMapItem;\n contextPack?: ProjectContextPack;\n}\n\ninterface ImpactPreviewPromptContext {\n implementationPrompt?: BrainDocumentItem;\n documents: BrainDocumentItem[];\n activeMap?: ProjectContextMapItem;\n contextPack?: ProjectContextPack;\n analyzedRepoRevision?: number;\n}\n\ninterface IssueDiagnosisPromptContext {\n issue?: IssueItem;\n documents: BrainDocumentItem[];\n}\n\ninterface SecurityPosturePromptContext {\n documents: BrainDocumentItem[];\n}\n\ninterface AppEvaluationPromptContext {\n documents: BrainDocumentItem[];\n}\n\ninterface BrainConsolidationPromptContext {\n documents: BrainDocumentItem[];\n}\n\ninterface TestQualityPromptContext {\n documents: BrainDocumentItem[];\n}\n\ninterface ProjectContextRefreshPromptContext {\n documents: BrainDocumentItem[];\n activeMap?: ProjectContextMapItem;\n}\n\ninterface ProjectContextRefreshParseOptions {\n repositoryRoot?: string;\n}\n\nfunction createImplementationVerificationPrompt(workItem: WorkItem): string {\n return [\n \"# Amistio Implementation Verification\",\n \"\",\n \"You are running locally through the Amistio CLI inside the user's repository.\",\n \"Verify whether the linked implementation work was actually completed. This is a read-only proof pass.\",\n \"Do not modify files, create branches, commit, install packages, run implementation prompts, or make destructive changes.\",\n \"Use local repository inspection and focused verification commands only when they are safe for this checkout.\",\n \"\",\n \"## Work Item\",\n \"\",\n `Title: ${workItem.title}`,\n `Work item ID: ${workItem.workItemId}`,\n `Project ID: ${workItem.projectId}`,\n `Implementation verification ID: ${workItem.implementationVerificationId ?? \"unknown\"}`,\n `Source work item ID: ${workItem.sourceWorkItemId ?? \"unknown\"}`,\n ...autopilotPromptLines(workItem),\n \"\",\n \"## Verification Request\",\n \"\",\n workItem.sourceWish ?? \"Verify that the linked implementation plan was completed in the local repository.\",\n \"\",\n \"## Verification Requirements\",\n \"\",\n \"- Compare the approved plan or prompt requirements against the current local repository state.\",\n \"- Look beyond runner status. Use source evidence, generated handoff details, PR/branch/worktree metadata when present, and targeted checks.\",\n \"- Treat missing acceptance criteria as an explicit gap instead of guessing.\",\n \"- Record evidence for at least one acceptance criterion with safe repository-relative citations.\",\n \"- Use outcome verifiedImplemented only when the implementation is materially present and checks support it.\",\n \"- Use partiallyImplemented, notImplemented, inconclusive, or verificationBlocked when evidence is incomplete, absent, contradictory, or checks cannot run.\",\n \"\",\n \"## Data Safety\",\n \"\",\n \"- Persist summaries, safe paths, short citation excerpts, and verification status only.\",\n \"- Do not include raw source dumps, secrets, env vars, process lists, absolute local paths, credential values, tokens, provider sessions, or destructive shell output.\",\n \"- Citations and safePaths must be repository-relative and must not use ../ traversal.\",\n \"\",\n \"## Output Contract\",\n \"\",\n \"Print exactly one JSON object between the markers below. The CLI will submit only this structured verification result back to Amistio.\",\n \"Accepted outcome values: verifiedImplemented, partiallyImplemented, notImplemented, inconclusive, verificationBlocked.\",\n \"Accepted recommendation values: none, requeue, createFollowUpPlan, requestHumanReview, markBlocked.\",\n \"\",\n implementationVerificationStart,\n '{\"outcome\":\"partiallyImplemented\",\"summary\":\"The implementation is present in the workspace, but one acceptance check could not be confirmed.\",\"evidence\":[{\"acceptanceCriterion\":\"The requested behavior is wired through the runner lifecycle.\",\"status\":\"partial\",\"summary\":\"The route and UI wiring exist, but the runner result submission still needs validation.\",\"citations\":[{\"source\":\"localSource\",\"repoPath\":\"src/apps/web/components/workspace-client.tsx\",\"excerpt\":\"Implementation verification queued for the local runner.\"}]}],\"checks\":[{\"name\":\"Focused typecheck\",\"status\":\"passed\",\"summary\":\"The touched package typechecked successfully.\",\"safePaths\":[\"src/apps/web\"]}],\"gaps\":[\"Runner result submission was not exercised end to end.\"],\"recommendation\":\"requestHumanReview\",\"verificationPlan\":[\"Run focused CLI tests\",\"Review the verification evidence in Amistio\"],\"warnings\":[]}',\n implementationVerificationEnd,\n \"\",\n \"Do not put Markdown fences around the markers. Do not implement or fix anything during this verification pass.\"\n ].join(\"\\n\");\n}\n\nfunction createTestQualityScanPrompt(workItem: WorkItem, context: TestQualityPromptContext | undefined): string {\n const approvedContext = (context?.documents ?? [])\n .filter((document) => document.status === \"approved\" || document.syncState === \"approved\" || document.syncState === \"synced\")\n .slice(0, 20)\n .map((document) => [\n `### ${document.title}`,\n `documentId: ${document.documentId}`,\n `documentType: ${document.documentType}`,\n `repoPath: ${document.repoPath}`,\n `revision: ${document.revision}`,\n document.content.slice(0, 3000)\n ].join(\"\\n\"))\n .join(\"\\n\\n\");\n\n return [\n \"# Amistio Test Quality Scan\",\n \"\",\n \"You are running locally through the Amistio CLI inside the user's repository.\",\n \"Run a non-mutating daily test, coverage, and quality scan for this repository.\",\n \"Do not modify files, create branches, commit, push, install packages, run implementation prompts, or make unaudited network calls.\",\n \"Use safe local metadata to infer package managers and scripts, then run existing lint, typecheck, test, coverage, and build commands only when they already exist.\",\n \"Return missing tests, missing coverage, low coverage, failing quality commands, and broken whole-app verification as reviewable findings that can become plans.\",\n \"\",\n \"## Work Item\",\n \"\",\n `Title: ${workItem.title}`,\n `Work item ID: ${workItem.workItemId}`,\n `Project ID: ${workItem.projectId}`,\n `Test quality scan ID: ${workItem.testQualityScanId ?? \"unknown\"}`,\n \"\",\n \"## Approved Project Brain Context\",\n \"\",\n approvedContext || \"No approved project-brain records were loaded. Inspect safe local metadata and summarize the context gap.\",\n \"\",\n \"## Requirements\",\n \"\",\n \"- Prefer the repository whole-app verification script when one exists, then focused package scripts.\",\n \"- Detect package managers from lockfiles and package metadata without uploading raw source.\",\n \"- Capture bounded summaries, exit codes, coverage metrics, and repository-relative safe paths only.\",\n \"- If coverage cannot be measured, return a missingCoverage finding instead of guessing.\",\n \"- If tests are missing or impossible to run, return a missingTests or testGap finding with a concrete plan and verification steps.\",\n \"- Redact secrets, absolute paths, env vars, process lists, tokens, provider sessions, and command lines containing secret-looking values.\",\n \"\",\n \"## Output Contract\",\n \"\",\n \"Print exactly one JSON object between the markers below. The CLI will submit only this structured test scan result back to Amistio.\",\n \"Accepted command kind values: verify, test, coverage, lint, typecheck, build, focused.\",\n \"Accepted command status values: passed, failed, skipped, missing, blocked.\",\n \"Accepted finding categories: missingTests, missingCoverage, lowCoverage, failingTests, failingQuality, missingCommand, flakyTests, unverifiedImplementation, testGap, other.\",\n \"Omit optional fields when unavailable; do not emit null for optional command summary fields such as exitCode, durationMs, outputExcerpt, commandId, or safePaths.\",\n \"\",\n testQualityStart,\n '{\"summary\":\"Whole-app verification exists, but coverage reporting is missing for one package.\",\"profile\":{\"testProfileId\":\"test_profile_detected\",\"repositoryLinkId\":\"repository_link_placeholder\",\"status\":\"detected\",\"enabled\":true,\"detectedPackageManager\":\"pnpm\",\"packageManagers\":[\"pnpm\"],\"commands\":[{\"commandId\":\"verify\",\"kind\":\"verify\",\"label\":\"Whole-app verification\",\"source\":\"detected\",\"scriptName\":\"verify\",\"workingDirectory\":\".\",\"required\":true}],\"coverageThresholds\":{\"lines\":80},\"defaultWholeAppCommandId\":\"verify\",\"focusedCommandIds\":[],\"lastDetectedAt\":\"2026-01-01T00:00:00.000Z\"},\"commandSummaries\":[{\"commandId\":\"verify\",\"kind\":\"verify\",\"label\":\"Whole-app verification\",\"status\":\"passed\",\"exitCode\":0,\"summary\":\"The repository verification script completed successfully.\",\"safePaths\":[\"package.json\"]}],\"coverage\":{\"status\":\"missing\",\"thresholds\":{\"lines\":80},\"summary\":\"No coverage report was found.\"},\"findings\":[{\"title\":\"Coverage report is missing\",\"category\":\"missingCoverage\",\"severity\":\"medium\",\"confidence\":\"high\",\"summary\":\"The repository test profile does not produce a coverage summary.\",\"affectedSurfaces\":[\"Test verification\"],\"evidence\":[\"The scan found a test command but no coverage output.\"],\"safePaths\":[\"package.json\"],\"suggestedAction\":\"Add or document a coverage command for the affected package and include it in whole-app verification.\",\"verificationPlan\":[\"Run the new coverage command locally\",\"Confirm coverage appears in the Test panel\"],\"dedupeKey\":\"missing-coverage\"}],\"blockedReasons\":[],\"redactionState\":{\"status\":\"clean\",\"redactedFields\":[]},\"verificationPlan\":[\"Review generated Test findings\",\"Run the whole-app verification command before implementation handoff\"],\"warnings\":[]}',\n testQualityEnd,\n \"\",\n \"Do not put Markdown fences around the markers. Do not implement fixes during this scan.\"\n ].join(\"\\n\");\n}\n\nfunction createImplementationTestGatePrompt(workItem: WorkItem): string {\n return [\n \"# Amistio Implementation Test Gate\",\n \"\",\n \"You are running locally through the Amistio CLI inside the user's repository.\",\n \"Run the required test gate before implementation completion, PR handoff, or runner-managed push.\",\n \"Do not modify files, install packages unless an already-approved preflight policy permits it, commit, push, or upload raw source.\",\n \"Run focused checks for the touched scope first when available, then the whole-app verification command when practical.\",\n \"If tests are missing or impossible, return blocked with a test-gap justification and a finding instead of marking the gate passed.\",\n \"\",\n \"## Work Item\",\n \"\",\n `Title: ${workItem.title}`,\n `Work item ID: ${workItem.workItemId}`,\n `Project ID: ${workItem.projectId}`,\n `Implementation test gate ID: ${workItem.implementationTestGateId ?? \"unknown\"}`,\n `Source work item ID: ${workItem.sourceWorkItemId ?? \"unknown\"}`,\n \"\",\n \"## Gate Request\",\n \"\",\n workItem.sourceWish ?? \"Run focused checks and whole-app verification before marking implementation complete.\",\n \"\",\n \"## Data Safety\",\n \"\",\n \"- Persist only bounded summaries, coverage metrics, exit codes, and repository-relative paths.\",\n \"- Do not include raw source, secrets, env vars, process lists, absolute local paths, credential values, tokens, provider sessions, or destructive shell output.\",\n \"- Use safePaths for repository-relative paths only; never include /absolute paths or ../ traversal.\",\n \"\",\n \"## Output Contract\",\n \"\",\n \"Print exactly one JSON object between the markers below. The CLI will submit only this structured gate result back to Amistio.\",\n \"Accepted outcome values: passed, failed, blocked, missingTests, belowThreshold, overridden.\",\n \"Accepted command kind values: verify, test, coverage, lint, typecheck, build, focused.\",\n \"Accepted command status values: passed, failed, skipped, missing, blocked.\",\n \"Prefer repository-documented verification commands or approved test profile commands over ad hoc package-script inference.\",\n \"For this Amistio monorepo, if plain Corepack pnpm fails before scripts with spawnSync pnpm ENOENT, retry the documented command corepack pnpm --config.verify-deps-before-run=false verify before declaring whole-app verification blocked.\",\n \"Accepted finding categories: missingTests, missingCoverage, missingCommand, lowCoverage, failingTests, failingQuality, failingQualityCheck, staleScan, blockedEnvironment, weakTests, flakyTests, unverifiedImplementation, testGap, other.\",\n \"Accepted finding severity values: info, low, medium, high, critical.\",\n \"Accepted finding confidence values: low, medium, high.\",\n \"Every finding must include title, category, severity, summary, suggestedAction, and a non-empty verificationPlan.\",\n \"Finding optional fields may include confidence, affectedSurfaces, evidence, safePaths, proposedPlanTitle, proposedPlanRepoPath, proposedPlanContent, and dedupeKey.\",\n \"Omit optional fields when unavailable; do not emit null for optional command summary fields such as exitCode, durationMs, outputExcerpt, commandId, or safePaths.\",\n \"\",\n implementationTestGateStart,\n '{\"outcome\":\"blocked\",\"summary\":\"Whole-app verification could not run because the local package-manager wrapper failed before repository checks started.\",\"commandSummaries\":[{\"commandId\":\"verify\",\"kind\":\"verify\",\"label\":\"Whole-app verification\",\"status\":\"blocked\",\"summary\":\"Corepack could not spawn pnpm before repository verification started.\",\"safePaths\":[\"package.json\"]}],\"coverage\":{\"status\":\"unknown\",\"thresholds\":{},\"summary\":\"Coverage was not produced because verification did not run.\"},\"findings\":[{\"title\":\"Local verification toolchain is blocked\",\"category\":\"blockedEnvironment\",\"severity\":\"medium\",\"confidence\":\"high\",\"summary\":\"The implementation test gate could not start the repository verification command because the local package-manager toolchain failed before checks ran.\",\"affectedSurfaces\":[\"Local runner verification\"],\"evidence\":[\"The verification command failed before repository checks started.\"],\"safePaths\":[\"package.json\"],\"suggestedAction\":\"Restore the local package-manager toolchain or run the repository-documented verification command, then rerun the implementation test gate.\",\"verificationPlan\":[\"Run the documented whole-app verification command\",\"Rerun the implementation test gate\"],\"dedupeKey\":\"blocked-environment-package-manager\"}],\"blockedReasons\":[\"The local package-manager toolchain could not start verification.\"],\"redactionState\":{\"status\":\"clean\",\"redactedFields\":[]},\"verificationPlan\":[\"Restore local verification tooling\",\"Rerun the implementation test gate before marking implementation complete\"],\"warnings\":[]}',\n implementationTestGateEnd,\n \"\",\n \"Do not put Markdown fences around the markers.\"\n ].join(\"\\n\");\n}\n\nexport function createWorkExecutionPrompt(workItem: WorkItem, context?: { planRevision?: PlanRevisionPromptContext; assistantQuestion?: AssistantQuestionPromptContext; impactPreview?: ImpactPreviewPromptContext; issueDiagnosis?: IssueDiagnosisPromptContext; securityPostureScan?: SecurityPosturePromptContext; appEvaluationScan?: AppEvaluationPromptContext; brainConsolidationScan?: BrainConsolidationPromptContext; testQualityScan?: TestQualityPromptContext; projectContextRefresh?: ProjectContextRefreshPromptContext }): string {\n if (workItem.workKind === \"brainGeneration\") {\n return createBrainGenerationPrompt(workItem);\n }\n\n if (workItem.workKind === \"planRevision\") {\n return createPlanRevisionPrompt(workItem, context?.planRevision);\n }\n\n if (workItem.workKind === \"assistantQuestion\") {\n return createAssistantQuestionPrompt(workItem, context?.assistantQuestion);\n }\n\n if (workItem.workKind === \"impactPreview\") {\n return createImpactPreviewPrompt(workItem, context?.impactPreview);\n }\n\n if (workItem.workKind === \"issueDiagnosis\") {\n return createIssueDiagnosisPrompt(workItem, context?.issueDiagnosis);\n }\n\n if (workItem.workKind === \"securityPostureScan\") {\n return createSecurityPostureScanPrompt(workItem, context?.securityPostureScan);\n }\n\n if (workItem.workKind === \"appEvaluationScan\") {\n return createAppEvaluationScanPrompt(workItem, context?.appEvaluationScan);\n }\n\n if (workItem.workKind === \"brainConsolidationScan\") {\n return createBrainConsolidationScanPrompt(workItem, context?.brainConsolidationScan);\n }\n\n if (workItem.workKind === \"projectContextRefresh\") {\n return createProjectContextRefreshPrompt(workItem, context?.projectContextRefresh);\n }\n\n if (workItem.workKind === \"implementationVerification\") {\n return createImplementationVerificationPrompt(workItem);\n }\n\n if (workItem.workKind === \"testQualityScan\") {\n return createTestQualityScanPrompt(workItem, context?.testQualityScan);\n }\n\n if (workItem.workKind === \"implementationTestGate\") {\n return createImplementationTestGatePrompt(workItem);\n }\n\n return [\n \"# Amistio Work Execution\",\n \"\",\n \"You are running locally through the Amistio CLI inside the user's repository.\",\n \"Execute the approved work item below using the repository's existing orchestration files, instructions, and constraints.\",\n \"\",\n \"## Work Item\",\n \"\",\n `Title: ${workItem.title}`,\n `Work item ID: ${workItem.workItemId}`,\n `Project ID: ${workItem.projectId}`,\n `Implementation scope: ${workItem.implementationScopeId ?? workItem.controllingAdrId ?? \"work-item\"}`,\n `Execution branch: ${workItem.executionBranch ?? \"managed by Amistio CLI\"}`,\n `Execution worktree key: ${workItem.executionWorktreeKey ?? \"managed by Amistio CLI\"}`,\n ...autopilotPromptLines(workItem),\n \"\",\n \"## Rules\",\n \"\",\n \"- Read AGENTS.md first when it exists.\",\n \"- Read AGENTS.md and the relevant docs/ control-plane files before implementation so the work stays aligned with existing direction.\",\n \"- Treat the current working directory as the Amistio-managed implementation worktree; do not switch back to the paired primary checkout for mutating work.\",\n \"- Keep changes focused on this work item.\",\n \"- Preserve old decisions, plans, memory, and prompts unless the work item explicitly supersedes them.\",\n \"- Do not commit changes.\",\n \"- Do not write secrets into the repository.\",\n \"- Do not create a repo-local .amistio folder.\",\n \"- Run relevant verification commands when feasible and summarize results.\"\n ].join(\"\\n\");\n}\n\nfunction autopilotPromptLines(workItem: WorkItem): string[] {\n const autopilot = autopilotWorkMetadata(workItem);\n if (!autopilot.autopilotAuthorizationId) {\n return [];\n }\n const lines = [\n `Autopilot authorization ID: ${autopilot.autopilotAuthorizationId}`,\n ...(autopilot.autopilotCandidateId ? [`Autopilot candidate ID: ${autopilot.autopilotCandidateId}`] : []),\n ...(autopilot.autopilotCandidateType ? [`Autopilot candidate type: ${autopilot.autopilotCandidateType}`] : []),\n `Autopilot outcome: ${autopilot.autopilotClassificationOutcome ?? \"unknown\"}`,\n `Autopilot policy: ${autopilot.autopilotPolicyVersion ?? \"unknown\"}`\n ];\n if (autopilot.autopilotAuthorization?.summary) {\n lines.push(`Autopilot summary: ${autopilot.autopilotAuthorization.summary}`);\n }\n lines.push(\"Autopilot satisfies the app approval gate only for the audited low-risk work item; it does not loosen local repository, credential, or data-safety boundaries.\");\n return lines;\n}\n\nfunction autopilotWorkMetadata(workItem: WorkItem): WorkItem & { autopilotAuthorizationId?: string; autopilotCandidateId?: string; autopilotCandidateType?: string; autopilotClassificationOutcome?: string; autopilotPolicyVersion?: string; autopilotAuthorization?: { summary?: string } } {\n return workItem as WorkItem & { autopilotAuthorizationId?: string; autopilotCandidateId?: string; autopilotCandidateType?: string; autopilotClassificationOutcome?: string; autopilotPolicyVersion?: string; autopilotAuthorization?: { summary?: string } };\n}\n\nfunction createProjectContextRefreshPrompt(workItem: WorkItem, context: ProjectContextRefreshPromptContext | undefined): string {\n const approvedContext = (context?.documents ?? [])\n .filter((document) => document.status === \"approved\" || document.syncState === \"approved\" || document.syncState === \"synced\")\n .slice(0, 24)\n .map((document) => [\n `### ${document.title}`,\n `documentId: ${document.documentId}`,\n `documentType: ${document.documentType}`,\n `repoPath: ${document.repoPath}`,\n `revision: ${document.revision}`,\n document.content.slice(0, 3000)\n ].join(\"\\n\"))\n .join(\"\\n\\n\");\n const activeMap = context?.activeMap;\n const previousMap = activeMap\n ? [\n `Map ID: ${activeMap.projectContextMapId}`,\n `Version: ${activeMap.version}`,\n `Status: ${activeMap.status}`,\n `Coverage: ${activeMap.coverage.status}`,\n `Summary: ${activeMap.summary}`,\n \"Slices:\",\n ...activeMap.slices.slice(0, 20).map((slice) => `- ${slice.sliceId} / ${slice.kind} / ${slice.freshness}: ${slice.title} - ${slice.summary.slice(0, 500)}`)\n ].join(\"\\n\")\n : \"No approved project context map was loaded. Build the initial map.\";\n\n return [\n \"# Amistio Living Project Context Refresh\",\n \"\",\n \"You are running locally through the Amistio CLI inside the user's repository.\",\n \"Run a read-only project context refresh that captures the whole app as bounded, reviewable knowledge.\",\n \"Do not modify files, create branches, commit, install packages, run implementation prompts, call external services, or make unaudited network calls.\",\n \"Use only safe local inspection and focused diagnostic commands that do not expose secrets.\",\n \"\",\n \"## Work Item\",\n \"\",\n `Title: ${workItem.title}`,\n `Work item ID: ${workItem.workItemId}`,\n `Project ID: ${workItem.projectId}`,\n `Project context refresh ID: ${workItem.projectContextRefreshId ?? \"unknown\"}`,\n \"\",\n \"## Refresh Request\",\n \"\",\n workItem.sourceWish ?? \"Refresh the living project context map.\",\n \"\",\n \"## Approved Project Brain Context\",\n \"\",\n approvedContext || \"No approved project-brain records were loaded. Inspect local repository files as needed and explain the gap in the coverage warnings.\",\n \"\",\n \"## Previous Context Map\",\n \"\",\n previousMap,\n \"\",\n \"## Mapping Requirements\",\n \"\",\n \"- Create slices for architecture, domain, data, API, frontend, backend, CLI, workflows, operations, security, and testing when those surfaces exist.\",\n \"- Use only these exact singular slice kind values: overview, architecture, domain, data, api, frontend, backend, cli, workflow, operations, security, testing, unknown.\",\n \"- Capture entities and relations that explain how the app is put together and where future work should look first.\",\n \"- Prefer summaries, repository-relative paths, short citations, tags, and freshness status over raw source excerpts.\",\n \"- Use only these exact freshness values for coverage.status and slices[].freshness: fresh, stale, partial, missing.\",\n \"- Use only these exact citation source values: projectBrain, localSource, runnerState, mixed. Approved project-brain records use projectBrain, not approvedBrain.\",\n \"- Mark stale or missing areas explicitly instead of guessing.\",\n \"- Keep coverage.missingAreas entries concise noun phrases under 160 characters.\",\n \"- Keep coverage.warnings and verificationPlan entries under 300 characters; keep top-level warnings under 600 characters.\",\n \"- Keep repoPaths repository-relative; never include /absolute paths or ../ traversal.\",\n \"- If local inspection prints a path inside this checkout, convert it to the repository-relative path before returning JSON.\",\n \"\",\n \"## Data Safety\",\n \"\",\n \"- Persist summaries, entities, relations, citations, and repository-relative paths only.\",\n \"- Do not include raw source dumps, secrets, env vars, process lists, absolute local paths, credential values, tokens, provider sessions, or destructive shell output.\",\n \"- Citation excerpts must be short evidence snippets, not code payloads.\",\n \"\",\n \"## Output Contract\",\n \"\",\n \"Print exactly one JSON object between the markers below. The CLI will submit only this structured refresh result back to Amistio.\",\n \"\",\n projectContextRefreshStart,\n '{\"summary\":\"The app uses docs/ as the orchestration control plane and a local runner for source-aware work.\",\"slices\":[{\"sliceId\":\"slice_control_plane\",\"kind\":\"architecture\",\"title\":\"Docs control plane\",\"summary\":\"ADRs, plans, prompts, context, and memory under docs/ guide implementation work.\",\"repoPaths\":[\"AGENTS.md\",\"docs/architecture/overview.md\"],\"tags\":[\"orchestrator\",\"docs\"],\"citations\":[{\"source\":\"localSource\",\"repoPath\":\"AGENTS.md\",\"excerpt\":\"docs/ control-plane folders are the source of truth.\"}],\"freshness\":\"fresh\",\"confidence\":0.9}],\"entities\":[{\"entityId\":\"entity_local_runner\",\"name\":\"Local runner\",\"entityType\":\"component\",\"summary\":\"Executes approved work locally and returns redacted structured results.\",\"sliceIds\":[\"slice_control_plane\"],\"confidence\":0.8}],\"relations\":[{\"relationId\":\"rel_runner_uses_docs\",\"relationType\":\"uses\",\"fromId\":\"entity_local_runner\",\"toId\":\"slice_control_plane\",\"summary\":\"The runner reads approved docs context before executing work.\",\"confidence\":0.8}],\"coverage\":{\"status\":\"partial\",\"sliceCount\":1,\"staleSliceCount\":0,\"missingAreas\":[\"runtime data flow\"],\"warnings\":[]},\"changedSliceIds\":[\"slice_control_plane\"],\"staleSliceIds\":[],\"verificationPlan\":[\"Review the proposed context map in Amistio\",\"Run focused checks for any stale areas\"]}',\n projectContextRefreshEnd,\n \"\",\n \"Do not put Markdown fences around the markers. Do not implement any changes.\"\n ].join(\"\\n\");\n}\n\nfunction createSecurityPostureScanPrompt(workItem: WorkItem, context: SecurityPosturePromptContext | undefined): string {\n const approvedContext = (context?.documents ?? [])\n .filter((document) => document.status === \"approved\" || document.syncState === \"approved\" || document.syncState === \"synced\")\n .slice(0, 20)\n .map((document) => [\n `### ${document.title}`,\n `documentId: ${document.documentId}`,\n `documentType: ${document.documentType}`,\n `repoPath: ${document.repoPath}`,\n `revision: ${document.revision}`,\n document.content.slice(0, 3000)\n ].join(\"\\n\"))\n .join(\"\\n\\n\");\n\n return [\n \"# Amistio Security Posture Scan\",\n \"\",\n \"You are running locally through the Amistio CLI inside the user's repository.\",\n \"Run a read-only security posture scan and produce approval-gated remediation findings.\",\n \"Do not modify files, create branches, commit, run implementation prompts, install packages, perform exploit attempts, call external services, or make unaudited network calls.\",\n \"Use only safe local inspection and focused diagnostic commands that do not expose secrets.\",\n \"\",\n \"## Work Item\",\n \"\",\n `Title: ${workItem.title}`,\n `Work item ID: ${workItem.workItemId}`,\n `Project ID: ${workItem.projectId}`,\n `Security scan ID: ${workItem.securityScanId ?? \"unknown\"}`,\n \"\",\n \"## Scan Request\",\n \"\",\n workItem.sourceWish ?? \"Run the Amistio security baseline.\",\n \"\",\n \"## Approved Project Brain Context\",\n \"\",\n approvedContext || \"No approved project-brain records were loaded. Inspect local repository files as needed and explain the gap in the summary.\",\n \"\",\n \"## Baseline Requirements\",\n \"\",\n \"- Cover OWASP Top 10 and OWASP ASVS Level 1 style controls.\",\n \"- Check dependency and supply-chain posture: audit advisories, lockfiles, CI verification, release provenance, and trusted publishing where applicable.\",\n \"- Check secret and credential hygiene using redacted evidence only.\",\n \"- Check authentication, authorization, tenant isolation, redirects/callbacks, CSRF, CORS, security headers, logging redaction, and rate limiting.\",\n \"- Check Amistio controls: local-runner-only execution, supported work-kind gates, approval gates, worktree isolation, runner credential binding, and redacted telemetry.\",\n \"\",\n \"## Data Safety\",\n \"\",\n \"- Persist summaries, controls, repository-relative paths, and redacted evidence only.\",\n \"- Do not include raw source, secrets, env vars, command lines, process lists, absolute local paths, credential values, tokens, provider sessions, or exploit payloads.\",\n \"- Use safePaths for repo-relative paths only; never include /absolute paths or ../ traversal.\",\n \"\",\n \"## Output Contract\",\n \"\",\n \"Print exactly one JSON object between the markers below. The CLI will submit only this structured scan result back to Amistio.\",\n \"Accepted category values: owasp, dependency, supplyChain, secretHygiene, authentication, authorization, tenantIsolation, headers, redirects, csrf, cors, ciCd, logging, rateLimiting, runnerBoundary, other.\",\n \"\",\n securityPostureStart,\n '{\"summary\":\"Security posture is mostly healthy, but dependency advisory review is not automated.\",\"baselineVersion\":\"amistio-security-baseline-v1\",\"postureScore\":82,\"postureGrade\":\"B\",\"categorySummaries\":[{\"category\":\"dependency\",\"status\":\"warning\",\"summary\":\"Dependency audit automation is incomplete.\"}],\"findings\":[{\"title\":\"Dependency audit is not enforced in CI\",\"category\":\"dependency\",\"severity\":\"medium\",\"confidence\":\"high\",\"summary\":\"The repository has a lockfile, but CI does not appear to fail on known vulnerable dependencies.\",\"standardReferences\":[{\"standard\":\"OWASP ASVS\",\"control\":\"V14.2 Dependency\"}],\"affectedSurfaces\":[\"CI verification\"],\"evidence\":[\"No dependency audit step was found in the CI verification summary.\"],\"recommendedRemediation\":\"Add a dependency advisory check to the existing verification pipeline and document how failures are handled.\",\"verificationPlan\":[\"Run the updated CI verification command locally\",\"Confirm a known advisory fails the check in a controlled test\"],\"safePaths\":[\"package.json\",\"pnpm-lock.yaml\"]}],\"verificationPlan\":[\"Run focused dependency and CI checks\",\"Review Security panel findings for approval\"]}',\n securityPostureEnd,\n \"\",\n \"Do not put Markdown fences around the markers. Do not implement remediation.\"\n ].join(\"\\n\");\n}\n\nfunction createAppEvaluationScanPrompt(workItem: WorkItem, context: AppEvaluationPromptContext | undefined): string {\n const approvedContext = (context?.documents ?? [])\n .filter((document) => document.status === \"approved\" || document.syncState === \"approved\" || document.syncState === \"synced\")\n .slice(0, 24)\n .map((document) => [\n `### ${document.title}`,\n `documentId: ${document.documentId}`,\n `documentType: ${document.documentType}`,\n `repoPath: ${document.repoPath}`,\n `revision: ${document.revision}`,\n document.content.slice(0, 3000)\n ].join(\"\\n\"))\n .join(\"\\n\\n\");\n\n return [\n \"# Amistio App Evaluation Scan\",\n \"\",\n \"You are running locally through the Amistio CLI inside the user's repository.\",\n \"Run a read-only app evaluation scan and produce approval-gated improvement and cleanup findings.\",\n \"Do not modify files, create branches, commit, install packages, run implementation prompts, delete or archive plans, call external services, or make unaudited network calls.\",\n \"Use only safe local inspection and focused diagnostic commands that do not expose secrets.\",\n \"\",\n \"## Work Item\",\n \"\",\n `Title: ${workItem.title}`,\n `Work item ID: ${workItem.workItemId}`,\n `Project ID: ${workItem.projectId}`,\n `App evaluation scan ID: ${workItem.appEvaluationScanId ?? \"unknown\"}`,\n \"\",\n \"## Scan Request\",\n \"\",\n workItem.sourceWish ?? \"Run the Amistio app evaluation baseline.\",\n \"\",\n \"## Approved Project Brain Context\",\n \"\",\n approvedContext || \"No approved project-brain records were loaded. Inspect local repository files as needed and explain the gap in the summary.\",\n \"\",\n \"## Baseline Requirements\",\n \"\",\n \"- Check app verification health: lint, typecheck, test, build, CI references, flaky or missing gates.\",\n \"- Check product and docs drift between approved context, plans, prompts, and current implementation.\",\n \"- Check old plans and prompts for lifecycle reconciliation, but only propose cleanup actions such as markCompleted, markSuperseded, or archive when direct controlling evidence shows they are completed, superseded, or obsolete.\",\n \"- Treat active proposed, approved, ready, or in-progress plans/prompts with accepted controlling ADRs, features, or work artifacts as active backlog. Do not classify them as cleanup material solely because they are older, unexecuted, or not yet fully implemented; use keepActive when they still describe valid pending or approved work.\",\n \"- Treat intentionally in-progress feature tracks as still-active work when their controlling plan/feature has unchecked requirements or explicit follow-up gaps. For example, a completed first implementation prompt does not make the broader feature stale if PLAN/FEAT evidence says remaining lifecycle work is still open; return proposedLifecycleAction keepActive with evidence instead of cleanup.\",\n \"- Treat prompt frontmatter status Ready as an active execution backlog state by default, not as stale review debt. Only flag a Ready prompt for metadata correction when its controlling plan, feature, prompt index, or verification evidence unambiguously proves the prompt has already completed or been superseded.\",\n \"- Treat implemented umbrella plans that explicitly label unchecked checklist items as deferred follow-ups, future candidates, roadmap backlog, or split-out hardening phases as valid deferred backlog. Do not mark the umbrella incomplete or stale solely because those deferred items remain unchecked; use keepActive or no cleanup, and recommend a fresh focused plan only when a concrete deferred slice has current evidence and approval.\",\n \"- Treat reusable hygiene tooling and recurring health-loop prompts/plans as active operational backlog when the one-time cleanup or prevention pass has executed but the repeatable utility or recurring workflow remains explicitly Ready, Proposed, or unchecked. Do not archive them just because the initial cleanup succeeded; use keepActive unless controlling evidence proves the reusable work was completed, superseded, or rejected.\",\n \"- When lifecycle metadata disagrees across indexes, frontmatter, feature specs, ADRs, and implementation evidence, cite the conflict and propose a metadata correction or verification step instead of archival/removal.\",\n \"- Check missing memory or workflow updates when repeated lessons or operational rules are visible.\",\n \"- Check release readiness, UX, accessibility, performance, reliability, and security-posture follow-through at a summary level.\",\n \"- Prefer repository-documented verification commands over ad hoc package-script inference.\",\n \"- For this Amistio monorepo, if plain Corepack pnpm fails before scripts with spawnSync pnpm ENOENT, retry the documented command corepack pnpm --config.verify-deps-before-run=false verify before declaring whole-app verification blocked.\",\n \"\",\n \"## Data Safety\",\n \"\",\n \"- Persist summaries, recommended actions, repository-relative paths, and redacted evidence only.\",\n \"- Do not include raw source dumps, secrets, env vars, process lists, absolute local paths, credential values, tokens, provider sessions, or destructive shell output.\",\n \"- Use safePaths for repo-relative paths only; never include /absolute paths or ../ traversal.\",\n \"\",\n \"## Output Contract\",\n \"\",\n \"Print exactly one JSON object between the markers below. The CLI will submit only this structured scan result back to Amistio.\",\n \"Accepted category values: verification, productDrift, planCleanup, promptRot, missingMemory, releaseReadiness, ux, accessibility, performance, reliability, securityPosture, other.\",\n \"Accepted severity values: info, low, medium, high, critical.\",\n \"Accepted confidence values: low, medium, high.\",\n \"Accepted proposedLifecycleAction values: createPlan, updatePlan, markCompleted, markImplemented, markSuperseded, markBlocked, archive, keepActive, none.\",\n \"Include a stable dedupeKey for each finding based on the underlying issue identity, not scan time, generated wording, or transient ordering.\",\n \"\",\n appEvaluationStart,\n '{\"summary\":\"The app is generally healthy, but one release-readiness plan needs cleanup and verification evidence should be refreshed.\",\"baselineVersion\":\"amistio-app-evaluation-v1\",\"findings\":[{\"title\":\"Stale release plan should be marked superseded\",\"category\":\"planCleanup\",\"severity\":\"low\",\"confidence\":\"high\",\"dedupeKey\":\"plan-cleanup-docs-plans-plan-example-superseded\",\"summary\":\"A release plan appears to describe a workflow that has since been replaced by a newer accepted plan.\",\"affectedSurfaces\":[\"docs/plans\"],\"evidence\":[\"A newer plan references the same scope and status, while the older plan remains proposed.\"],\"suggestedAction\":\"Prepare a cleanup update that marks the stale plan superseded and links to the newer plan.\",\"verificationPlan\":[\"Review both plan files\",\"Confirm the newer plan is accepted before changing lifecycle state\"],\"safePaths\":[\"docs/plans/PLAN-example.md\"],\"proposedLifecycleAction\":\"markSuperseded\",\"relatedArtifactIds\":[]}],\"verificationPlan\":[\"Review App Evaluation findings for approval\",\"Run the canonical verify gate before implementing approved actions\"]}',\n appEvaluationEnd,\n \"\",\n \"Do not put Markdown fences around the markers. Do not implement improvements or cleanup.\"\n ].join(\"\\n\");\n}\n\nfunction createBrainConsolidationScanPrompt(workItem: WorkItem, context: BrainConsolidationPromptContext | undefined): string {\n const documents = context?.documents ?? [];\n const activeReviewDocuments = documents.filter(isActiveReviewPromptDocument).slice(0, 160);\n const canonicalDocuments = documents.filter(isCanonicalPromptDocument).slice(0, 120);\n const activeReviewContext = activeReviewDocuments.map((document) => formatBrainConsolidationDocument(document)).join(\"\\n\\n\");\n const canonicalContext = canonicalDocuments.map((document) => formatBrainConsolidationDocument(document)).join(\"\\n\\n\");\n\n return [\n \"# Amistio Semantic Brain Consolidation Scan\",\n \"\",\n \"You are running locally through the Amistio CLI inside the user's repository.\",\n \"Run a read-only semantic duplicate and coverage scan for Project Brain review documents.\",\n \"Do not modify files, create branches, commit, push, archive documents, approve documents, or run implementation prompts.\",\n \"Return bounded recommendations only; the Amistio server decides what is safe to auto-archive.\",\n \"\",\n \"## Work Item\",\n \"\",\n `Title: ${workItem.title}`,\n `Work item ID: ${workItem.workItemId}`,\n `Project ID: ${workItem.projectId}`,\n `Brain consolidation scan ID: ${workItem.brainConsolidationScanId ?? \"unknown\"}`,\n \"\",\n \"## Scan Request\",\n \"\",\n workItem.sourceWish ?? \"Compare active generated review documents against approved or synced Project Brain documents and recommend safe consolidation actions.\",\n \"\",\n \"## Active Review Documents\",\n \"\",\n activeReviewContext || \"No active review documents were provided in the scan context.\",\n \"\",\n \"## Approved Or Synced Canonical Documents\",\n \"\",\n canonicalContext || \"No approved or synced canonical documents were provided in the scan context.\",\n \"\",\n \"## Requirements\",\n \"\",\n \"- Compare active review documents to approved or synced canonical documents by documentId, title, repoPath, documentType, source, syncState, frontmatter lineage, and content excerpt.\",\n \"- Recommend archiveDuplicate only when a generated draft is fully covered by a canonical approved/synced document and adds no distinct requirement, decision, plan step, or memory entry.\",\n \"- Use proposeArchive for partial, ambiguous, user-owned, repo-sourced, dirty, or medium-risk matches that need human review.\",\n \"- Use manualReview when the candidate appears related but may contain unique requirements or unresolved conflicts.\",\n \"- Use skip for documents that are not duplicates or cannot be evaluated safely from the available context.\",\n \"- Keep each recommendation focused on one canonical document and one or more candidate document IDs.\",\n \"\",\n \"## Data Safety\",\n \"\",\n \"- Persist only document IDs, short evidence, bounded summaries, and recommendations.\",\n \"- Do not include raw source dumps, secrets, env vars, process lists, absolute local paths, credential values, tokens, provider sessions, or destructive shell output.\",\n \"\",\n \"## Output Contract\",\n \"\",\n \"Print exactly one JSON object between the markers below. The CLI will submit only this structured consolidation result back to Amistio.\",\n \"Accepted coverage values: full, partial, notCovered, ambiguous.\",\n \"Accepted confidence values: low, medium, high.\",\n \"Accepted recommendedAction values: archiveDuplicate, proposeArchive, manualReview, skip.\",\n \"Accepted riskLevel values: low, medium, high, critical.\",\n \"\",\n brainConsolidationStart,\n '{\"summary\":\"Compared active generated review documents against approved canonical documents.\",\"recommendations\":[{\"canonicalDocumentId\":\"doc_approved\",\"candidateDocumentIds\":[\"doc_review_duplicate\"],\"coverage\":\"full\",\"confidence\":\"high\",\"recommendedAction\":\"archiveDuplicate\",\"riskLevel\":\"low\",\"evidence\":[\"The candidate repeats the accepted decision without adding requirements.\"],\"reason\":\"The generated review draft is fully covered by the approved canonical document.\"}],\"warnings\":[]}',\n brainConsolidationEnd,\n \"\",\n \"Do not put Markdown fences around the markers. Do not archive, approve, or edit documents.\"\n ].join(\"\\n\");\n}\n\nfunction formatBrainConsolidationDocument(document: BrainDocumentItem): string {\n return [\n `### ${document.title}`,\n `documentId: ${document.documentId}`,\n `documentType: ${document.documentType}`,\n `repoPath: ${document.repoPath}`,\n `contentFormat: ${document.contentFormat ?? \"markdown\"}`,\n `source: ${document.source}`,\n `status: ${document.status}`,\n `syncState: ${document.syncState}`,\n `revision: ${document.revision}`,\n `approvedRevision: ${document.approvedRevision ?? \"none\"}`,\n `contentHash: ${document.contentHash}`,\n `frontmatter: ${JSON.stringify(document.frontmatter)}`,\n document.content.slice(0, 1600)\n ].join(\"\\n\");\n}\n\nfunction isActiveReviewPromptDocument(document: BrainDocumentItem): boolean {\n return document.syncState === \"draft\" && [\"draft\", \"drafted\", \"reviewing\", \"changesRequested\"].includes(document.status);\n}\n\nfunction isCanonicalPromptDocument(document: BrainDocumentItem): boolean {\n return document.syncState === \"approved\" || document.syncState === \"synced\" || document.status === \"approved\";\n}\n\nfunction createIssueDiagnosisPrompt(workItem: WorkItem, context: IssueDiagnosisPromptContext | undefined): string {\n const issue = context?.issue;\n const approvedContext = (context?.documents ?? [])\n .filter((document) => document.status === \"approved\" || document.syncState === \"approved\" || document.syncState === \"synced\")\n .slice(0, 16)\n .map((document) => [\n `### ${document.title}`,\n `documentId: ${document.documentId}`,\n `documentType: ${document.documentType}`,\n `repoPath: ${document.repoPath}`,\n `revision: ${document.revision}`,\n document.content.slice(0, 3000)\n ].join(\"\\n\"))\n .join(\"\\n\\n\");\n\n return [\n \"# Amistio Issue Diagnosis\",\n \"\",\n \"You are running locally through the Amistio CLI inside the user's repository.\",\n \"Diagnose the submitted bug or operational issue and prepare the approval-gated fix analysis.\",\n \"This is a diagnosis-only task. Do not modify files, create branches, run implementation commands, or commit changes.\",\n \"\",\n \"## Submitted Issue\",\n \"\",\n `Issue ID: ${workItem.issueId ?? issue?.issueId ?? \"unknown\"}`,\n `Title: ${issue?.title ?? workItem.title}`,\n `Category: ${issue?.category ?? \"bug\"}`,\n `Severity: ${issue?.severity ?? \"medium\"}`,\n \"\",\n issue?.description ?? workItem.sourceWish ?? workItem.title,\n \"\",\n \"## Approved Project Brain Context\",\n \"\",\n approvedContext || \"No approved project-brain records were loaded. Inspect local repository files as needed and explain the gap in evidence.\",\n \"\",\n \"## Analysis Requirements\",\n \"\",\n \"- Document user-visible impact and concrete evidence or reproduction status.\",\n \"- Name affected surfaces and likely paths using concise path summaries only.\",\n \"- Provide rootCauseAnalysis. If unconfirmed, include falsifiableHypothesis and nextCheck.\",\n \"- Propose the fix and expected behavior, then provide a verification plan.\",\n \"- Keep repository source and secrets local. Do not include raw source dumps, credentials, local secret paths, or provider session references.\",\n \"- Leave approvalState as proposed. Implementation must wait for user approval in Amistio.\",\n \"\",\n \"## Output Contract\",\n \"\",\n \"Print exactly one JSON object between the markers below. The CLI will submit only this structured diagnosis back to Amistio.\",\n \"\",\n issueDiagnosisStart,\n '{\"summary\":\"The issue is caused by a missing state transition in the workspace action flow.\",\"impact\":\"Users see a submitted action but no follow-up analysis appears.\",\"evidence\":[\"Reproduced by submitting an issue from the workspace UI\"],\"affectedSurfaces\":[\"Workspace UI\",\"Runner claim API\"],\"rootCauseAnalysis\":\"The issue path queues normal implementation work instead of diagnosis work.\",\"falsifiableHypothesis\":\"Adding issueDiagnosis work and a dedicated result route will produce analysis without source mutation.\",\"nextCheck\":\"Run focused web and CLI typechecks after wiring the route.\",\"proposedFix\":\"Add a first-class issue diagnosis work kind, result parser, and approval-gated implementation queue.\",\"expectedBehavior\":\"Submitted issues show a complete analysis and only queue implementation after approval.\",\"verificationPlan\":[\"Run shared, web, and CLI typechecks\",\"Submit an issue with a compatible runner and verify analysis appears\"],\"riskLevel\":\"medium\",\"likelyPaths\":[{\"repoPath\":\"src/apps/web/legacy/api/projects/[projectId]/issues.ts\",\"reason\":\"Issue submission and approval route\"}],\"approvalState\":\"proposed\"}',\n issueDiagnosisEnd,\n \"\",\n \"Do not put Markdown fences around the markers. Do not implement the fix.\"\n ].join(\"\\n\");\n}\n\nfunction formatProjectContextMap(map: ProjectContextMapItem | undefined, query: string, contextPack?: ProjectContextPack): string {\n if ((!map || map.status !== \"approved\") && !contextPack) {\n return \"No approved living context map was loaded. Use approved brain records and inspect local source only where needed.\";\n }\n if (!map || map.status !== \"approved\") {\n return [\n `Context pack ID: ${contextPack?.packId ?? \"unknown\"}`,\n contextPack?.freshnessWarnings.length ? `Freshness warnings: ${contextPack.freshnessWarnings.join(\" | \")}` : \"Freshness warnings: none recorded\",\n \"No approved living context map was loaded. Use approved brain records and inspect local source only where needed.\"\n ].join(\"\\n\");\n }\n const tokens = tokenizeForContext(query);\n const candidateSlices = contextPack?.slices.length ? contextPack.slices : map.slices;\n const rankedSlices = [...candidateSlices]\n .map((slice) => ({ slice, score: scoreContextSlice(tokens, slice.title, slice.summary, [...slice.repoPaths, ...slice.tags, ...slice.ownerHints].join(\" \")) }))\n .sort((first, second) => second.score - first.score || first.slice.title.localeCompare(second.slice.title));\n const selectedSlices = rankedSlices.filter((entry) => entry.score > 0).map((entry) => entry.slice).slice(0, 8);\n const slices = (selectedSlices.length ? selectedSlices : candidateSlices.slice(0, 8)).map((slice) => [\n `### ${slice.title}`,\n `sliceId: ${slice.sliceId}`,\n `kind: ${slice.kind}`,\n `freshness: ${slice.freshness}`,\n `confidence: ${Math.round(slice.confidence * 100)}%`,\n slice.repoPaths.length ? `repoPaths: ${slice.repoPaths.slice(0, 12).join(\", \")}` : \"repoPaths: none recorded\",\n slice.summary\n ].join(\"\\n\")).join(\"\\n\\n\");\n const entities = (contextPack?.entities.length ? contextPack.entities : map.entities).slice(0, 12).map((entity) => `- ${entity.name} (${entity.entityType}): ${entity.summary ?? entity.entityId}`).join(\"\\n\");\n const relations = (contextPack?.relations.length ? contextPack.relations : map.relations).slice(0, 12).map((relation) => `- ${relation.fromId} ${relation.relationType} ${relation.toId}: ${relation.summary}`).join(\"\\n\");\n return [\n contextPack ? `Context pack ID: ${contextPack.packId}` : \"Context pack ID: not recorded\",\n `Map ID: ${map.projectContextMapId}`,\n `Version: ${map.version}`,\n contextPack?.tokenEstimate !== undefined ? `Pack token estimate: ${contextPack.tokenEstimate}` : \"Pack token estimate: not recorded\",\n `Coverage: ${map.coverage.status}; slices ${map.coverage.sliceCount}; stale ${map.coverage.staleSliceCount}`,\n contextPack?.freshnessWarnings.length ? `Freshness warnings: ${contextPack.freshnessWarnings.join(\" | \")}` : \"Freshness warnings: none recorded\",\n map.coverage.missingAreas.length ? `Missing areas: ${map.coverage.missingAreas.join(\", \")}` : \"Missing areas: none recorded\",\n map.coverage.warnings.length ? `Warnings: ${map.coverage.warnings.join(\" | \")}` : \"Warnings: none recorded\",\n \"\",\n map.summary,\n \"\",\n \"### Relevant Context Slices\",\n slices || \"No slices recorded.\",\n \"\",\n \"### Entities\",\n entities || \"No entities recorded.\",\n \"\",\n \"### Relations\",\n relations || \"No relations recorded.\"\n ].join(\"\\n\");\n}\n\nfunction tokenizeForContext(value: string): string[] {\n return [...new Set(value.toLowerCase().match(/[a-z0-9][a-z0-9_-]{2,}/g) ?? [])].slice(0, 24);\n}\n\nfunction scoreContextSlice(tokens: string[], title: string, summary: string, metadata: string): number {\n const haystackTitle = title.toLowerCase();\n const haystackSummary = summary.toLowerCase();\n const haystackMetadata = metadata.toLowerCase();\n return tokens.reduce((score, token) => score + (haystackTitle.includes(token) ? 5 : 0) + (haystackMetadata.includes(token) ? 3 : 0) + (haystackSummary.includes(token) ? 1 : 0), 0);\n}\n\nfunction createImpactPreviewPrompt(workItem: WorkItem, context: ImpactPreviewPromptContext | undefined): string {\n const implementationPrompt = context?.implementationPrompt;\n const livingContext = formatProjectContextMap(context?.activeMap, workItem.sourceWish ?? workItem.title, context?.contextPack);\n const approvedContext = (context?.documents ?? [])\n .filter((document) => document.status === \"approved\" || document.syncState === \"approved\" || document.syncState === \"synced\")\n .slice(0, 16)\n .map((document) => [\n `### ${document.title}`,\n `documentId: ${document.documentId}`,\n `documentType: ${document.documentType}`,\n `repoPath: ${document.repoPath}`,\n `revision: ${document.revision}`,\n document.content.slice(0, 3000)\n ].join(\"\\n\"))\n .join(\"\\n\\n\");\n\n return [\n \"# Amistio Implementation Impact Preview\",\n \"\",\n \"You are running locally through the Amistio CLI inside the user's repository.\",\n \"Analyze the likely impact of the approved implementation prompt. This is a preview-only task.\",\n \"Do not modify files, do not create branches, do not run implementation commands, and do not commit changes.\",\n \"\",\n \"## Work Item\",\n \"\",\n `Title: ${workItem.title}`,\n `Work item ID: ${workItem.workItemId}`,\n `Project ID: ${workItem.projectId}`,\n `Generated draft ID: ${workItem.generatedDraftId ?? \"unknown\"}`,\n `Impact report ID: ${workItem.impactReportId ?? \"unknown\"}`,\n `Analyzed repo revision: ${context?.analyzedRepoRevision ?? \"unknown\"}`,\n \"\",\n \"## Approved Implementation Prompt\",\n \"\",\n implementationPrompt ? implementationPrompt.content : workItem.sourceWish ?? workItem.title,\n \"\",\n \"## Approved Living Project Context Map\",\n \"\",\n livingContext,\n \"\",\n \"## Approved Project Brain Context\",\n \"\",\n approvedContext || \"No approved project-brain records were loaded. Inspect the local repository and explain the gap in the report.\",\n \"\",\n \"## Report Requirements\",\n \"\",\n \"- Identify affected product areas and likely modules/files using safe path summaries.\",\n \"- Assign riskLevel as low, medium, high, or critical with operational reasoning in summary.\",\n \"- Include data/schema/migration impact, security/privacy/access-control considerations, verification plan, and rollback plan.\",\n \"- Keep repository source and secrets local. Do not include raw source dumps, credentials, local secret paths, or provider session references.\",\n \"- If you inspect files, cite paths only through likelyPaths and concise reasons.\",\n \"\",\n \"## Output Contract\",\n \"\",\n \"Print exactly one JSON object between the markers below. The CLI will submit only this structured report back to Amistio.\",\n \"\",\n impactPreviewStart,\n '{\"riskLevel\":\"medium\",\"summary\":\"Touches the workspace command flow and runner claim gate.\",\"affectedAreas\":[{\"name\":\"Workspace UI\",\"description\":\"Shows impact before execution\"}],\"likelyPaths\":[{\"repoPath\":\"src/apps/web/components/workspace-client.tsx\",\"reason\":\"Workspace action wiring\"}],\"dependencies\":[\"local runner\"],\"dataSchemaImpact\":\"Adds an impact report project item.\",\"securityPrivacyImpact\":\"Source remains local; SaaS stores summaries and paths only.\",\"verificationPlan\":[\"Run shared, web, and CLI tests\",\"Run root verify\"],\"rollbackPlan\":\"Disable the impact gate and remove queued preview work if needed.\"}',\n impactPreviewEnd,\n \"\",\n \"Do not put Markdown fences around the markers. Do not implement the work.\"\n ].join(\"\\n\");\n}\n\nfunction createAssistantQuestionPrompt(workItem: WorkItem, context: AssistantQuestionPromptContext | undefined): string {\n const question = context?.question.content ?? workItem.sourceWish ?? workItem.title;\n const livingContext = formatProjectContextMap(context?.activeMap, question, context?.contextPack);\n const priorMessages = (context?.messages ?? [])\n .filter((message) => message.messageId !== context?.question.messageId)\n .slice(-12)\n .map((message) => `- ${message.role} / ${message.status}: ${message.content}`)\n .join(\"\\n\");\n const brainContext = (context?.documents ?? [])\n .filter((document) => document.status === \"approved\" || document.syncState === \"approved\" || document.syncState === \"synced\")\n .slice(0, 12)\n .map((document) => [\n `### ${document.title}`,\n `documentId: ${document.documentId}`,\n `repoPath: ${document.repoPath}`,\n `revision: ${document.revision}`,\n document.content.slice(0, 2400)\n ].join(\"\\n\"))\n .join(\"\\n\\n\");\n\n return [\n \"# Amistio Project Knowledge Assistant\",\n \"\",\n \"You are running locally through the Amistio CLI inside the user's repository.\",\n \"Answer the user's project question using approved project-brain context and local repository inspection when useful.\",\n \"This is an answer-only task. Do not modify files, do not create branches, and do not commit changes.\",\n \"\",\n \"## User Question\",\n \"\",\n question,\n \"\",\n \"## Work Item\",\n \"\",\n `Title: ${workItem.title}`,\n `Work item ID: ${workItem.workItemId}`,\n `Project ID: ${workItem.projectId}`,\n `Assistant message ID: ${workItem.assistantMessageId ?? context?.question.messageId ?? \"unknown\"}`,\n \"\",\n \"## Approved Living Project Context Map\",\n \"\",\n livingContext,\n \"\",\n \"## Approved Project Brain Context\",\n \"\",\n brainContext || \"No approved project-brain records were loaded. Say what you inspected locally and avoid pretending citations exist.\",\n \"\",\n \"## Recent Assistant Conversation\",\n \"\",\n priorMessages || \"No prior assistant messages were loaded.\",\n \"\",\n \"## Source Boundary Rules\",\n \"\",\n \"- Keep repository source, secrets, tokens, local credential paths, and provider session references local.\",\n \"- Summarize findings instead of dumping source code. Tiny identifiers, filenames, and short excerpts are acceptable when necessary.\",\n \"- Use sourceBoundary \\\"projectBrain\\\" when the answer only uses project-brain records.\",\n \"- Treat the approved living context map as project-brain context; use it to avoid broad repository rereads when it is fresh and relevant.\",\n \"- Use sourceBoundary \\\"localSource\\\" when you inspected local repository files.\",\n \"- Use sourceBoundary \\\"mixed\\\" when both project-brain records and local files shaped the answer.\",\n \"- Include citations for project-brain records with documentId/title/repoPath where relevant.\",\n \"- Include local file citations with repoPath only; do not include raw source dumps.\",\n \"\",\n \"## Output Contract\",\n \"\",\n \"Print exactly one JSON object between the markers below. The CLI will submit only this structured answer back to Amistio.\",\n \"\",\n assistantAnswerStart,\n '{\"answer\":\"Concise answer with concrete next steps.\",\"sourceBoundary\":\"mixed\",\"citations\":[{\"source\":\"projectBrain\",\"documentId\":\"doc_123\",\"title\":\"ADR-001\",\"repoPath\":\"docs/decisions/ADR-001.md\",\"excerpt\":\"Short supporting excerpt\"},{\"source\":\"localSource\",\"repoPath\":\"src/apps/web/example.ts\",\"excerpt\":\"Short local finding\"}]}',\n assistantAnswerEnd,\n \"\",\n \"Do not put Markdown fences around the markers. Do not include implementation diffs.\"\n ].join(\"\\n\");\n}\n\nfunction createPlanRevisionPrompt(workItem: WorkItem, context: PlanRevisionPromptContext | undefined): string {\n const messages = context?.messages ?? [];\n return [\n \"# Amistio Plan Revision\",\n \"\",\n \"You are running locally through the Amistio CLI inside the user's repository.\",\n \"Revise the selected generated plan using the user's conversation. Do not implement product/source code changes in this pass.\",\n \"\",\n \"## Work Item\",\n \"\",\n `Title: ${workItem.title}`,\n `Work item ID: ${workItem.workItemId}`,\n `Project ID: ${workItem.projectId}`,\n `Document ID: ${workItem.reviewDocumentId ?? \"unknown\"}`,\n `Document revision: ${workItem.reviewDocumentRevision ?? \"unknown\"}`,\n \"\",\n \"## Current Plan\",\n \"\",\n context?.planDocument.content ?? \"The current plan document could not be loaded. Explain the blocker in the result summary.\",\n \"\",\n \"## Conversation\",\n \"\",\n messages.length ? messages.map((message) => `- ${message.role} / ${message.intent} / ${message.status} / rev ${message.documentRevision}: ${message.content}`).join(\"\\n\") : \"No conversation messages were loaded.\",\n \"\",\n \"## Output Contract\",\n \"\",\n \"Print exactly one JSON object between the markers below with an artifacts array containing one revised plan artifact.\",\n \"The artifact must use documentType \\\"plan\\\", keep the plan under docs/plans/, and include the complete revised plan content.\",\n \"\",\n generationResultStart,\n '{\"artifacts\":[{\"documentType\":\"plan\",\"title\":\"Revised Plan\",\"repoPath\":\"docs/plans/PLAN-revised.md\",\"content\":\"# Revised Plan\\\\n\\\\n## Goal\\\\n...\"}]}',\n generationResultEnd,\n \"\",\n \"Do not put Markdown fences around the markers. Do not claim implementation is complete.\"\n ].join(\"\\n\");\n}\n\nexport function parseBrainGenerationArtifacts(output: string): GeneratedBrainArtifact[] {\n const start = output.indexOf(generationResultStart);\n const end = output.indexOf(generationResultEnd, start + generationResultStart.length);\n if (start === -1 || end === -1 || end <= start) {\n throw new Error(\"Local AI generation did not return an Amistio brain generation result block.\");\n }\n\n const payload = output.slice(start + generationResultStart.length, end).trim();\n const parsed = JSON.parse(stripJsonFence(payload)) as unknown;\n return brainGenerationResultSchema.parse(parsed).artifacts;\n}\n\nexport function parseAssistantAnswerResult(output: string): AssistantAnswerResult {\n const start = output.indexOf(assistantAnswerStart);\n const end = output.indexOf(assistantAnswerEnd, start + assistantAnswerStart.length);\n if (start === -1 || end === -1 || end <= start) {\n throw new Error(\"Local AI answer did not return an Amistio assistant answer block.\");\n }\n\n const payload = output.slice(start + assistantAnswerStart.length, end).trim();\n const parsed = JSON.parse(stripJsonFence(payload)) as unknown;\n return assistantAnswerResultSchema.parse(parsed);\n}\n\nexport function parseImpactPreviewResult(output: string): ImpactPreviewResult {\n const start = output.indexOf(impactPreviewStart);\n const end = output.indexOf(impactPreviewEnd, start + impactPreviewStart.length);\n if (start === -1 || end === -1 || end <= start) {\n throw new Error(\"Local AI preview did not return an Amistio impact preview block.\");\n }\n\n const payload = output.slice(start + impactPreviewStart.length, end).trim();\n const parsed = JSON.parse(stripJsonFence(payload)) as unknown;\n return impactPreviewResultSchema.parse(parsed);\n}\n\nexport function parseIssueDiagnosisResult(output: string): IssueDiagnosisResult {\n const start = output.indexOf(issueDiagnosisStart);\n const end = output.indexOf(issueDiagnosisEnd, start + issueDiagnosisStart.length);\n if (start === -1 || end === -1 || end <= start) {\n throw new Error(\"Local AI diagnosis did not return an Amistio issue diagnosis block.\");\n }\n\n const payload = output.slice(start + issueDiagnosisStart.length, end).trim();\n const parsed = JSON.parse(stripJsonFence(payload)) as unknown;\n return issueDiagnosisResultSchema.parse(parsed);\n}\n\nexport function parseSecurityPostureScanResult(output: string): SecurityPostureScanResult {\n const start = output.indexOf(securityPostureStart);\n const end = output.indexOf(securityPostureEnd, start + securityPostureStart.length);\n if (start === -1 || end === -1 || end <= start) {\n throw new Error(\"Local AI scan did not return an Amistio security posture block.\");\n }\n\n const payload = output.slice(start + securityPostureStart.length, end).trim();\n const parsed = JSON.parse(stripJsonFence(payload)) as unknown;\n return securityPostureScanResultSchema.parse(parsed);\n}\n\nexport function parseAppEvaluationScanResult(output: string): AppEvaluationScanResult {\n const start = output.indexOf(appEvaluationStart);\n const end = output.indexOf(appEvaluationEnd, start + appEvaluationStart.length);\n if (start === -1 || end === -1 || end <= start) {\n throw new Error(\"Local AI scan did not return an Amistio app evaluation block.\");\n }\n\n const payload = output.slice(start + appEvaluationStart.length, end).trim();\n const parsed = JSON.parse(stripJsonFence(payload)) as unknown;\n const normalized = normalizeAppEvaluationScanResultPaths(normalizeAppEvaluationScanResultEnums(parsed));\n return appEvaluationScanResultSchema.parse(normalized);\n}\n\nexport function parseBrainConsolidationScanResult(output: string): BrainConsolidationScanResult {\n const start = output.indexOf(brainConsolidationStart);\n const end = output.indexOf(brainConsolidationEnd, start + brainConsolidationStart.length);\n if (start === -1 || end === -1 || end <= start) {\n throw new Error(\"Local AI scan did not return an Amistio brain consolidation block.\");\n }\n\n const payload = output.slice(start + brainConsolidationStart.length, end).trim();\n const parsed = JSON.parse(stripJsonFence(payload)) as unknown;\n return brainConsolidationScanResultSchema.parse(parsed);\n}\n\nexport function parseProjectContextRefreshResult(output: string, options: ProjectContextRefreshParseOptions = {}): ProjectContextRefreshResult {\n const start = output.indexOf(projectContextRefreshStart);\n const end = output.indexOf(projectContextRefreshEnd, start + projectContextRefreshStart.length);\n if (start === -1 || end === -1 || end <= start) {\n throw new Error(\"Local AI refresh did not return an Amistio project context block.\");\n }\n\n const payload = output.slice(start + projectContextRefreshStart.length, end).trim();\n const parsed = JSON.parse(stripJsonFence(payload)) as unknown;\n const normalized = normalizeProjectContextRefreshBoundedText(normalizeProjectContextRefreshPaths(normalizeProjectContextRefreshEnums(parsed), options));\n return projectContextRefreshResultSchema.parse(normalized);\n}\n\nexport function parseImplementationVerificationResult(output: string): ImplementationVerificationResult {\n const start = output.indexOf(implementationVerificationStart);\n const end = output.indexOf(implementationVerificationEnd, start + implementationVerificationStart.length);\n if (start === -1 || end === -1 || end <= start) {\n throw new Error(\"Local AI verification did not return an Amistio implementation verification block.\");\n }\n\n const payload = output.slice(start + implementationVerificationStart.length, end).trim();\n const parsed = JSON.parse(stripJsonFence(payload)) as unknown;\n return implementationVerificationResultSchema.parse(parsed);\n}\n\nexport function parseTestQualityScanResult(output: string): TestQualityScanResult {\n const start = output.indexOf(testQualityStart);\n const end = output.indexOf(testQualityEnd, start + testQualityStart.length);\n if (start === -1 || end === -1 || end <= start) {\n throw new Error(\"Local AI scan did not return an Amistio test quality block.\");\n }\n\n const payload = output.slice(start + testQualityStart.length, end).trim();\n const parsed = JSON.parse(stripJsonFence(payload)) as unknown;\n return testQualityScanResultSchema.parse(normalizeTestQualityScanResult(parsed));\n}\n\nfunction normalizeTestQualityScanResult(value: unknown): unknown {\n if (!isObjectRecord(value)) {\n return value;\n }\n\n const normalized: Record<string, unknown> = { ...value };\n if (isObjectRecord(normalized.profile) && Array.isArray(normalized.profile.commands)) {\n normalized.profile = {\n ...normalized.profile,\n commands: normalized.profile.commands.map(normalizeTestCommandKindObject)\n };\n }\n\n if (Array.isArray(normalized.commandSummaries)) {\n normalized.commandSummaries = normalized.commandSummaries.map(normalizeTestCommandSummaryObject);\n }\n\n return normalized;\n}\n\nfunction normalizeImplementationTestGateResult(value: unknown): unknown {\n if (!isObjectRecord(value)) {\n return value;\n }\n\n const normalized: Record<string, unknown> = { ...value };\n if (Array.isArray(normalized.commandSummaries)) {\n normalized.commandSummaries = normalized.commandSummaries.map(normalizeTestCommandSummaryObject);\n }\n\n return normalized;\n}\n\nfunction normalizeTestCommandSummaryObject(value: unknown): unknown {\n if (!isObjectRecord(value)) {\n return value;\n }\n\n const normalized: Record<string, unknown> = { ...value, kind: normalizeTestCommandKind(value.kind) };\n for (const key of [\"commandId\", \"durationMs\", \"exitCode\", \"outputExcerpt\", \"safePaths\"]) {\n if (normalized[key] === null) {\n delete normalized[key];\n }\n }\n\n return normalized;\n}\n\nfunction normalizeTestCommandKindObject(value: unknown): unknown {\n if (!isObjectRecord(value)) {\n return value;\n }\n\n return { ...value, kind: normalizeTestCommandKind(value.kind) };\n}\n\nfunction normalizeTestCommandKind(value: unknown): unknown {\n if (typeof value !== \"string\") {\n return value;\n }\n\n const trimmed = value.trim();\n if (!trimmed) {\n return value;\n }\n\n const direct = canonicalTestCommandKinds.get(normalizeEnumKey(trimmed));\n if (direct) {\n return direct;\n }\n\n for (const segment of trimmed.split(/[\\/,|]+/)) {\n const segmentKind = canonicalTestCommandKinds.get(normalizeEnumKey(segment));\n if (segmentKind) {\n return segmentKind;\n }\n }\n\n return \"focused\";\n}\n\nexport function parseImplementationTestGateResult(output: string): ImplementationTestGateResult {\n const start = output.indexOf(implementationTestGateStart);\n const end = output.indexOf(implementationTestGateEnd, start + implementationTestGateStart.length);\n if (start === -1 || end === -1 || end <= start) {\n throw new Error(\"Local AI gate did not return an Amistio implementation test gate block.\");\n }\n\n const payload = output.slice(start + implementationTestGateStart.length, end).trim();\n const parsed = JSON.parse(stripJsonFence(payload)) as unknown;\n return implementationTestGateResultSchema.parse(normalizeImplementationTestGateResult(parsed));\n}\n\nexport function projectContextRefreshSubmissionFailureSummary(result: { refresh: ProjectContextRefreshItem; workItem: WorkItem }): string | undefined {\n if (result.refresh.status !== \"failed\" && result.workItem.status !== \"failed\") {\n return undefined;\n }\n const summary = result.refresh.error ?? result.workItem.lastStatusMessage ?? \"Server rejected the project context refresh result.\";\n const guidance = getWorkFailureGuidance({ message: summary, workKind: \"projectContextRefresh\" });\n return guidance ? `${summary} ${formatWorkFailureGuidanceDetail(guidance)}` : summary;\n}\n\nfunction createBrainGenerationPrompt(workItem: WorkItem): string {\n const wish = workItem.sourceWish ?? workItem.title;\n const artifactFormatPreference = workItem.artifactFormatPreference ?? \"markdown\";\n return [\n \"# Amistio Brain Generation\",\n \"\",\n \"You are running locally through the Amistio CLI inside the user's repository.\",\n \"Generate reviewable project-brain artifacts from the submitted wish. Do not implement product/source code changes in this pass.\",\n \"\",\n \"## Submitted Wish\",\n \"\",\n wish,\n \"\",\n \"## Work Item\",\n \"\",\n `Title: ${workItem.title}`,\n `Work item ID: ${workItem.workItemId}`,\n `Project ID: ${workItem.projectId}`,\n `Generated draft ID: ${workItem.generatedDraftId ?? \"unknown\"}`,\n `Artifact format preference: ${artifactFormatPreference}`,\n \"\",\n \"## Read First\",\n \"\",\n \"- Read AGENTS.md first when it exists.\",\n \"- Read relevant files under docs/architecture/, docs/context/, docs/decisions/, docs/features/, docs/memory/, docs/plans/, docs/prompts/, and docs/workflows/ before drafting.\",\n \"- Keep source code and secrets local. Do not include source-code payloads, access tokens, API keys, local credential paths, or provider session references in the result.\",\n \"\",\n \"## Generate Artifacts\",\n \"\",\n \"Return artifacts that should enter human review before implementation. Use only these document types and matching repo roots:\",\n \"\",\n \"- architecture -> docs/architecture/\",\n \"- context -> docs/context/\",\n \"- decision -> docs/decisions/\",\n \"- feature -> docs/features/\",\n \"- memory -> docs/memory/\",\n \"- plan -> docs/plans/\",\n \"- prompt -> docs/prompts/\",\n \"- workflow -> docs/workflows/\",\n \"- HTML artifacts -> docs/html/<same-folder>/ using .html, for example docs/html/plans/PLAN-example.html\",\n \"\",\n artifactFormatPreferenceInstructions(artifactFormatPreference),\n \"\",\n \"Each artifact needs documentType, contentFormat, title, repoPath, and content. contentFormat may be omitted only for Markdown. Include at least a plan and an implementation prompt when implementation work is implied. Use model-agnostic prompt wording.\",\n \"\",\n \"## Output Contract\",\n \"\",\n \"Print exactly one JSON object between the markers below. The CLI will submit only this structured result back to Amistio.\",\n \"\",\n generationResultStart,\n artifactFormatPreference === \"html\"\n ? '{\"artifacts\":[{\"documentType\":\"plan\",\"contentFormat\":\"html\",\"title\":\"Plan: Example\",\"repoPath\":\"docs/html/plans/PLAN-example.html\",\"content\":\"<!doctype html><html><body><h1>Plan: Example</h1></body></html>\"}]}'\n : '{\"artifacts\":[{\"documentType\":\"plan\",\"contentFormat\":\"markdown\",\"title\":\"Plan: Example\",\"repoPath\":\"docs/plans/PLAN-example.md\",\"content\":\"# Plan: Example\\\\n\\\\n## Goal\\\\n...\"}]}',\n generationResultEnd,\n \"\",\n \"Do not put Markdown fences around the markers. Do not claim implementation is complete.\"\n ].join(\"\\n\");\n}\n\nfunction normalizeProjectContextRefreshEnums(value: unknown): unknown {\n if (!isObjectRecord(value)) {\n return value;\n }\n\n const normalized: Record<string, unknown> = { ...value };\n\n if (isObjectRecord(normalized.coverage)) {\n const normalizedCoverage: Record<string, unknown> = { ...normalized.coverage };\n normalizedCoverage.status = normalizeProjectContextFreshness(normalizedCoverage.status);\n normalized.coverage = normalizedCoverage;\n }\n\n if (Array.isArray(normalized.slices)) {\n normalized.slices = normalized.slices.map((slice) => {\n if (!isObjectRecord(slice)) {\n return slice;\n }\n const normalizedSlice: Record<string, unknown> = { ...slice };\n normalizedSlice.kind = normalizeProjectContextSliceKind(slice.kind);\n normalizedSlice.freshness = normalizeProjectContextFreshness(slice.freshness);\n return normalizedSlice;\n });\n }\n\n if (Array.isArray(normalized.entities)) {\n normalized.entities = normalized.entities.map((entity) => {\n if (!isObjectRecord(entity)) {\n return entity;\n }\n const normalizedEntity: Record<string, unknown> = { ...entity };\n normalizedEntity.entityType = normalizeProjectContextEntityType(entity.entityType);\n return normalizedEntity;\n });\n }\n\n if (Array.isArray(normalized.relations)) {\n normalized.relations = normalized.relations.map((relation) => {\n if (!isObjectRecord(relation)) {\n return relation;\n }\n const normalizedRelation: Record<string, unknown> = { ...relation };\n normalizedRelation.relationType = normalizeProjectContextRelationType(relation.relationType);\n return normalizedRelation;\n });\n }\n\n return normalized;\n}\n\nfunction normalizeAppEvaluationScanResultEnums(value: unknown): unknown {\n if (!isObjectRecord(value)) {\n return value;\n }\n\n const normalized: Record<string, unknown> = { ...value };\n if (Array.isArray(normalized.findings)) {\n normalized.findings = normalized.findings.map((finding) => {\n if (!isObjectRecord(finding)) {\n return finding;\n }\n const normalizedFinding: Record<string, unknown> = { ...finding };\n normalizedFinding.category = normalizeAppEvaluationFindingCategory(finding.category);\n return normalizedFinding;\n });\n }\n return normalized;\n}\n\nfunction normalizeAppEvaluationFindingCategory(value: unknown): unknown {\n if (typeof value !== \"string\") {\n return value;\n }\n const trimmed = value.trim();\n if (!trimmed) {\n return \"other\";\n }\n\n const direct = canonicalAppEvaluationCategories.get(normalizeEnumKey(trimmed));\n if (direct) {\n return direct;\n }\n\n for (const segment of trimmed.split(/[\\/,|]+/)) {\n const segmentCategory = canonicalAppEvaluationCategories.get(normalizeEnumKey(segment));\n if (segmentCategory) {\n return segmentCategory;\n }\n }\n\n return \"other\";\n}\n\nfunction normalizeEnumKey(value: string): string {\n return value.trim().replace(/[^A-Za-z0-9]+/g, \"\").toLowerCase();\n}\n\nfunction normalizeAppEvaluationScanResultPaths(value: unknown): unknown {\n if (!isObjectRecord(value)) {\n return value;\n }\n\n const normalized: Record<string, unknown> = { ...value };\n if (Array.isArray(normalized.findings)) {\n normalized.findings = normalized.findings.map((finding) => {\n if (!isObjectRecord(finding)) {\n return finding;\n }\n const normalizedFinding: Record<string, unknown> = { ...finding };\n if (Array.isArray(normalizedFinding.safePaths)) {\n normalizedFinding.safePaths = normalizedFinding.safePaths.map((safePath) => typeof safePath === \"string\" ? normalizeAppEvaluationRepoPath(safePath) : safePath);\n }\n if (typeof normalizedFinding.proposedPlanRepoPath === \"string\") {\n normalizedFinding.proposedPlanRepoPath = normalizeAppEvaluationRepoPath(normalizedFinding.proposedPlanRepoPath);\n }\n return normalizedFinding;\n });\n }\n return normalized;\n}\n\nfunction normalizeAppEvaluationRepoPath(value: string): string {\n try {\n return normalizeRelativeProjectContextPath(value);\n } catch {\n throw new Error(\"App evaluation scan contains an unsafe repository path.\");\n }\n}\n\nfunction normalizeProjectContextSliceKind(value: unknown): string {\n if (typeof value !== \"string\") {\n return \"unknown\";\n }\n const normalized = value.trim().toLowerCase();\n if (validProjectContextSliceKinds.has(normalized)) {\n return normalized;\n }\n if (normalized.endsWith(\"s\")) {\n const singular = normalized.slice(0, -1);\n if (validProjectContextSliceKinds.has(singular)) {\n return singular;\n }\n }\n return \"unknown\";\n}\n\nfunction normalizeProjectContextFreshness(value: unknown): unknown {\n if (typeof value !== \"string\") {\n return value;\n }\n const trimmed = value.trim();\n if (!trimmed) {\n return value;\n }\n\n const direct = canonicalProjectContextFreshnessValues.get(normalizeEnumKey(trimmed));\n if (direct) {\n return direct;\n }\n\n for (const segment of trimmed.split(/[\\/,|]+/)) {\n const segmentFreshness = canonicalProjectContextFreshnessValues.get(normalizeEnumKey(segment));\n if (segmentFreshness) {\n return segmentFreshness;\n }\n }\n\n return \"partial\";\n}\n\nfunction normalizeProjectContextRefreshBoundedText(value: unknown): unknown {\n if (!isObjectRecord(value)) {\n return value;\n }\n\n const normalized: Record<string, unknown> = { ...value };\n\n if (isObjectRecord(normalized.coverage)) {\n const coverage: Record<string, unknown> = { ...normalized.coverage };\n coverage.missingAreas = normalizeBoundedStringArray(coverage.missingAreas, projectContextMissingAreaMaxLength);\n coverage.warnings = normalizeBoundedStringArray(coverage.warnings, projectContextCoverageWarningMaxLength);\n normalized.coverage = coverage;\n }\n\n normalized.verificationPlan = normalizeBoundedStringArray(normalized.verificationPlan, projectContextVerificationPlanMaxLength);\n normalized.warnings = normalizeBoundedStringArray(normalized.warnings, projectContextTopLevelWarningMaxLength);\n return normalized;\n}\n\nfunction normalizeBoundedStringArray(value: unknown, maxLength: number): unknown {\n if (!Array.isArray(value)) {\n return value;\n }\n return value.flatMap((entry) => {\n if (typeof entry !== \"string\") {\n return [entry];\n }\n const trimmed = entry.trim();\n return trimmed ? [shortenBoundedString(trimmed, maxLength)] : [];\n });\n}\n\nfunction shortenBoundedString(value: string, maxLength: number): string {\n if (value.length <= maxLength) {\n return value;\n }\n if (maxLength <= 3) {\n return value.slice(0, maxLength);\n }\n return `${value.slice(0, maxLength - 3).trimEnd()}...`;\n}\n\nfunction normalizeProjectContextRefreshPaths(value: unknown, options: ProjectContextRefreshParseOptions): unknown {\n if (!isObjectRecord(value)) {\n return value;\n }\n\n const normalized: Record<string, unknown> = { ...value };\n\n if (Array.isArray(normalized.slices)) {\n normalized.slices = normalized.slices.map((slice) => normalizeProjectContextSlicePaths(slice, options));\n }\n\n if (Array.isArray(normalized.entities)) {\n normalized.entities = normalized.entities.map((entity) => normalizeProjectContextCitationPaths(entity, options));\n }\n\n if (Array.isArray(normalized.relations)) {\n normalized.relations = normalized.relations.map((relation) => normalizeProjectContextCitationPaths(relation, options));\n }\n\n return normalized;\n}\n\nfunction normalizeProjectContextSlicePaths(value: unknown, options: ProjectContextRefreshParseOptions): unknown {\n if (!isObjectRecord(value)) {\n return value;\n }\n\n const normalized = normalizeProjectContextCitationPaths(value, options) as Record<string, unknown>;\n if (Array.isArray(normalized.repoPaths)) {\n normalized.repoPaths = normalized.repoPaths.map((repoPath) => typeof repoPath === \"string\" ? normalizeProjectContextRepoPath(repoPath, options) : repoPath);\n }\n return normalized;\n}\n\nfunction normalizeProjectContextCitationPaths(value: unknown, options: ProjectContextRefreshParseOptions): unknown {\n if (!isObjectRecord(value)) {\n return value;\n }\n\n const normalized: Record<string, unknown> = { ...value };\n if (Array.isArray(normalized.citations)) {\n normalized.citations = normalized.citations.map((citation) => {\n if (!isObjectRecord(citation)) {\n return citation;\n }\n const normalizedCitation: Record<string, unknown> = { ...citation };\n normalizedCitation.source = normalizeProjectContextCitationSource(normalizedCitation.source);\n if (typeof normalizedCitation.repoPath === \"string\") {\n normalizedCitation.repoPath = normalizeProjectContextRepoPath(normalizedCitation.repoPath, options);\n }\n return normalizedCitation;\n });\n }\n return normalized;\n}\n\nfunction normalizeProjectContextCitationSource(value: unknown): unknown {\n if (typeof value !== \"string\") {\n return value;\n }\n const sourceKey = value.trim().replace(/[\\s_-]+/g, \"\").toLowerCase();\n return canonicalProjectContextCitationSources.get(sourceKey) ?? value;\n}\n\nfunction normalizeProjectContextRepoPath(value: string, options: ProjectContextRefreshParseOptions): string {\n const trimmed = value.trim();\n if (!trimmed || /^[A-Za-z][A-Za-z0-9+.-]*:\\/\\//.test(trimmed) || /^file:/i.test(trimmed) || /^[A-Za-z]:($|[^\\\\/])/.test(trimmed)) {\n throwUnsafeProjectContextPath();\n }\n\n const absolute = trimmed.startsWith(\"/\") || trimmed.startsWith(\"\\\\\\\\\") || path.isAbsolute(trimmed) || path.win32.isAbsolute(trimmed);\n if (!absolute) {\n return normalizeRelativeProjectContextPath(trimmed);\n }\n\n if (!options.repositoryRoot) {\n throwUnsafeProjectContextPath();\n }\n\n const useWindowsPathRules = path.win32.isAbsolute(trimmed) && !trimmed.startsWith(\"/\");\n const relativePath = useWindowsPathRules\n ? path.win32.relative(path.win32.resolve(options.repositoryRoot), path.win32.resolve(trimmed))\n : path.relative(path.resolve(options.repositoryRoot), path.resolve(trimmed));\n return normalizeRelativeProjectContextPath(relativePath);\n}\n\nfunction normalizeRelativeProjectContextPath(value: string): string {\n const normalized = value.trim().replace(/\\\\/g, \"/\");\n const segments = normalized.split(\"/\").filter((segment) => segment.length > 0 && segment !== \".\");\n if (!segments.length || normalized.startsWith(\"/\") || normalized === \"~\" || normalized.startsWith(\"~/\") || /^[A-Za-z]:/.test(normalized) || segments.includes(\"..\")) {\n throwUnsafeProjectContextPath();\n }\n return segments.join(\"/\");\n}\n\nfunction throwUnsafeProjectContextPath(): never {\n throw new Error(\"Project context refresh contains an unsafe repository path.\");\n}\n\nfunction normalizeProjectContextEntityType(value: unknown): string {\n if (typeof value !== \"string\") {\n return \"unknown\";\n }\n const normalized = value.trim().toLowerCase();\n return validProjectContextEntityTypes.has(normalized) ? normalized : \"unknown\";\n}\n\nfunction normalizeProjectContextRelationType(value: unknown): string {\n if (typeof value !== \"string\") {\n return \"mentions\";\n }\n const normalized = value.trim().toLowerCase();\n return validProjectContextRelationTypes.has(normalized) ? normalized : \"mentions\";\n}\n\nfunction isObjectRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction artifactFormatPreferenceInstructions(preference: WorkItem[\"artifactFormatPreference\"]): string {\n if (preference === \"html\") {\n return \"The user chose HTML. Generate .html artifacts under docs/html/<folder>/ and set contentFormat to html.\";\n }\n if (preference === \"both\") {\n return \"The user chose both formats. Choose one format per artifact purpose; do not generate matching Markdown and HTML companion copies of the same document.\";\n }\n if (preference === \"auto\") {\n return \"Choose Markdown or HTML based on the artifact content. Use Markdown for text-first docs and HTML only for visual or layout-sensitive artifacts.\";\n }\n return \"The user chose Markdown. Generate Markdown artifacts under docs/<folder>/ and set contentFormat to markdown or omit it.\";\n}\n\nfunction stripJsonFence(value: string): string {\n const trimmed = value.trim();\n if (!trimmed.startsWith(\"```\")) {\n return trimmed;\n }\n\n return trimmed.replace(/^```(?:json)?\\s*/i, \"\").replace(/```$/i, \"\").trim();\n}\n", "import { createHash } from \"node:crypto\";\nimport { formatProjectNextAction, type ProjectNextAction } from \"@amistio/shared\";\n\nexport const watchStateReminderMs = 60 * 1000;\n\nexport interface WatchStateLog {\n key: string;\n printedAtMs: number;\n}\n\nexport function formatWatchStartupContext(input: { runnerId: string; projectId: string; repositoryLinkId: string; apiUrl: string; intervalSeconds: number }): string[] {\n return [\n `Runner ${input.runnerId} is watching project ${input.projectId}.`,\n `Repository link: ${input.repositoryLinkId}`,\n `API: ${input.apiUrl}`,\n `Polling interval: ${input.intervalSeconds}s. Press Ctrl+C to stop.`\n ];\n}\n\nexport function formatWatchIdleLine(action: ProjectNextAction, intervalSeconds: number): string {\n return `${formatProjectNextAction(action)} Checking again in ${intervalSeconds}s.`;\n}\n\nexport function shouldPrintWatchState(action: ProjectNextAction, previous: WatchStateLog | undefined, nowMs: number, reminderMs = watchStateReminderMs): boolean {\n const key = watchStateKey(action);\n if (!previous || previous.key !== key) {\n return true;\n }\n if (action.kind === \"workCompleted\") {\n return false;\n }\n return nowMs - previous.printedAtMs >= reminderMs;\n}\n\nexport function watchStateKey(action: ProjectNextAction): string {\n return [action.kind, action.message, action.workItemId, action.documentId, action.runnerId].filter(Boolean).join(\":\");\n}\n\nexport function stableRunnerId(input: { accountId: string; projectId: string; repositoryLinkId: string; machineId: string }): string {\n const digest = createHash(\"sha256\")\n .update(`${input.accountId}:${input.projectId}:${input.repositoryLinkId}:${input.machineId}`)\n .digest(\"hex\")\n .slice(0, 20);\n return `runner_${digest}`;\n}\n", "import os from \"node:os\";\nimport type { RunnerResourceUsage } from \"@amistio/shared\";\n\nexport interface RunnerResourceSampleState {\n sampledAtMs: number;\n processCpuUserMicros: number;\n processCpuSystemMicros: number;\n}\n\nexport interface RunnerResourceRuntime {\n nowMs: () => number;\n memoryUsage: () => { rss: number; heapUsed: number; heapTotal: number };\n uptime: () => number;\n cpuUsage: () => { user: number; system: number };\n totalmem: () => number;\n freemem: () => number;\n loadavg: () => number[];\n}\n\nconst defaultRuntime: RunnerResourceRuntime = {\n nowMs: () => Date.now(),\n memoryUsage: () => process.memoryUsage(),\n uptime: () => process.uptime(),\n cpuUsage: () => process.cpuUsage(),\n totalmem: () => os.totalmem(),\n freemem: () => os.freemem(),\n loadavg: () => os.loadavg()\n};\n\nlet previousRunnerResourceSample: RunnerResourceSampleState | undefined;\n\nexport function sampleCurrentRunnerResourceUsage(): RunnerResourceUsage {\n const sample = collectRunnerResourceUsage(previousRunnerResourceSample);\n previousRunnerResourceSample = sample.state;\n return sample.resourceUsage;\n}\n\nexport function collectRunnerResourceUsage(previous: RunnerResourceSampleState | undefined, runtime: RunnerResourceRuntime = defaultRuntime): { resourceUsage: RunnerResourceUsage; state: RunnerResourceSampleState } {\n const sampledAtMs = runtime.nowMs();\n const memory = runtime.memoryUsage();\n const cpu = runtime.cpuUsage();\n const load = runtime.loadavg();\n const totalMemory = runtime.totalmem();\n const freeMemory = runtime.freemem();\n\n const resourceUsage: RunnerResourceUsage = {\n sampledAt: new Date(sampledAtMs).toISOString(),\n processUptimeSeconds: roundNumber(runtime.uptime(), 3),\n processMemoryRssBytes: Math.round(memory.rss),\n processMemoryHeapUsedBytes: Math.round(memory.heapUsed),\n processMemoryHeapTotalBytes: Math.round(memory.heapTotal),\n processCpuUserMicros: Math.round(cpu.user),\n processCpuSystemMicros: Math.round(cpu.system),\n systemMemoryTotalBytes: Math.round(totalMemory),\n systemMemoryFreeBytes: Math.round(freeMemory)\n };\n\n const cpuPercent = processCpuPercent(previous, { sampledAtMs, processCpuUserMicros: cpu.user, processCpuSystemMicros: cpu.system });\n if (cpuPercent !== undefined) {\n resourceUsage.processCpuPercent = cpuPercent;\n }\n\n if (load.length >= 3) {\n resourceUsage.systemLoadAverage1m = roundNumber(load[0]!, 2);\n resourceUsage.systemLoadAverage5m = roundNumber(load[1]!, 2);\n resourceUsage.systemLoadAverage15m = roundNumber(load[2]!, 2);\n }\n\n return {\n resourceUsage,\n state: {\n sampledAtMs,\n processCpuUserMicros: cpu.user,\n processCpuSystemMicros: cpu.system\n }\n };\n}\n\nexport function formatRunnerResourceUsage(resourceUsage: RunnerResourceUsage | undefined): string {\n if (!resourceUsage) {\n return \"unavailable until this runner reports a sample.\";\n }\n\n const parts = [\n resourceUsage.processMemoryRssBytes !== undefined ? `RSS ${formatBytes(resourceUsage.processMemoryRssBytes)}` : undefined,\n heapSummary(resourceUsage),\n resourceUsage.processCpuPercent !== undefined ? `CPU ${formatPercent(resourceUsage.processCpuPercent)}` : \"CPU warming up\",\n systemMemorySummary(resourceUsage),\n loadSummary(resourceUsage),\n `sampled ${resourceUsage.sampledAt}`\n ].filter(Boolean);\n\n return parts.length ? parts.join(\"; \") : \"unavailable until this runner reports a complete sample.\";\n}\n\nexport function formatBytes(bytes: number | undefined): string {\n if (bytes === undefined || !Number.isFinite(bytes)) {\n return \"unknown\";\n }\n const units = [\"B\", \"KiB\", \"MiB\", \"GiB\", \"TiB\"];\n let value = Math.max(0, bytes);\n let unitIndex = 0;\n while (value >= 1024 && unitIndex < units.length - 1) {\n value /= 1024;\n unitIndex += 1;\n }\n const digits = Number.isInteger(value) || value >= 10 || unitIndex === 0 ? 0 : 1;\n return `${value.toFixed(digits)} ${units[unitIndex]}`;\n}\n\nexport function formatPercent(value: number | undefined): string {\n if (value === undefined || !Number.isFinite(value)) {\n return \"unknown\";\n }\n return `${roundNumber(value, 1).toFixed(1)}%`;\n}\n\nfunction processCpuPercent(previous: RunnerResourceSampleState | undefined, current: RunnerResourceSampleState): number | undefined {\n if (!previous) return undefined;\n const elapsedMicros = (current.sampledAtMs - previous.sampledAtMs) * 1000;\n const cpuDeltaMicros = current.processCpuUserMicros + current.processCpuSystemMicros - previous.processCpuUserMicros - previous.processCpuSystemMicros;\n if (elapsedMicros <= 0 || cpuDeltaMicros < 0) return undefined;\n return roundNumber((cpuDeltaMicros / elapsedMicros) * 100, 1);\n}\n\nfunction heapSummary(resourceUsage: RunnerResourceUsage): string | undefined {\n if (resourceUsage.processMemoryHeapUsedBytes === undefined && resourceUsage.processMemoryHeapTotalBytes === undefined) {\n return undefined;\n }\n return `heap ${formatBytes(resourceUsage.processMemoryHeapUsedBytes)} / ${formatBytes(resourceUsage.processMemoryHeapTotalBytes)}`;\n}\n\nfunction systemMemorySummary(resourceUsage: RunnerResourceUsage): string | undefined {\n if (resourceUsage.systemMemoryTotalBytes === undefined || resourceUsage.systemMemoryFreeBytes === undefined || resourceUsage.systemMemoryTotalBytes <= 0) {\n return undefined;\n }\n const usedBytes = Math.max(0, resourceUsage.systemMemoryTotalBytes - resourceUsage.systemMemoryFreeBytes);\n const usedPercent = (usedBytes / resourceUsage.systemMemoryTotalBytes) * 100;\n return `system memory ${formatBytes(usedBytes)} / ${formatBytes(resourceUsage.systemMemoryTotalBytes)} used (${formatPercent(usedPercent)})`;\n}\n\nfunction loadSummary(resourceUsage: RunnerResourceUsage): string | undefined {\n if (resourceUsage.systemLoadAverage1m === undefined || resourceUsage.systemLoadAverage5m === undefined || resourceUsage.systemLoadAverage15m === undefined) {\n return undefined;\n }\n return `load ${resourceUsage.systemLoadAverage1m.toFixed(2)} / ${resourceUsage.systemLoadAverage5m.toFixed(2)} / ${resourceUsage.systemLoadAverage15m.toFixed(2)}`;\n}\n\nfunction roundNumber(value: number, digits: number): number {\n const factor = 10 ** digits;\n return Math.round(value * factor) / factor;\n}", "import { execFile } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { readdir, readFile, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { inferContentFormatFromRepoPath, isControlPlaneTemplateRepoPath, parseRepositoryCloneUrl, sha256ContentHash, type BrainDocumentItem, type DocumentContentFormat, type DocumentType, type ParsedRepositoryCloneUrl } from \"@amistio/shared\";\nimport { parseFrontmatter } from \"./control-plane.js\";\n\nconst execFileAsync = promisify(execFile);\nconst defaultMaxFileKb = 256;\n\nconst controlPlaneRoots = [\"architecture\", \"context\", \"decisions\", \"features\", \"memory\", \"plans\", \"prompts\", \"workflows\"] as const;\nconst excludedDirectoryNames = new Set([\".git\", \"node_modules\", \".pnpm-store\", \".next\", \"dist\", \"build\", \"coverage\", \".cache\", \"cache\", \"tmp\", \"temp\", \"vendor\"]);\nconst excludedFileNames = new Set([\"docs/context/amistio-project.md\", \"context/amistio-project.md\"]);\nconst generatedPathSegments = new Set([\"generated\", \"__generated__\", \"vendor\", \"vendors\"]);\nconst rootAgentGuidanceFiles = new Set([\"agents.md\", \"claude.md\", \"gemini.md\", \"codex.md\"]);\nconst extensionlessInstructionFiles = new Set([\".cursorrules\", \".windsurfrules\", \".clinerules\"]);\n\nconst documentFolderByType: Record<DocumentType, string> = {\n architecture: \"docs/architecture\",\n context: \"docs/context\",\n decision: \"docs/decisions\",\n feature: \"docs/features\",\n memory: \"docs/memory\",\n plan: \"docs/plans\",\n prompt: \"docs/prompts/shared\",\n workflow: \"docs/workflows\"\n};\n\nexport interface LocalRepositoryMetadata {\n rootDir: string;\n repoName: string;\n defaultBranch: string;\n repoFingerprint: string;\n originRemoteWarning?: string;\n parsedCloneUrl?: ParsedRepositoryCloneUrl;\n}\n\nexport interface LegacyDocumentCandidate {\n sourcePath: string;\n repoPath: string;\n documentType: DocumentType;\n contentFormat: DocumentContentFormat;\n title: string;\n content: string;\n contentHash: string;\n}\n\nexport interface ImportSkippedDocument {\n repoPath: string;\n reason: \"notMarkdown\" | \"excluded\" | \"tooLarge\" | \"alreadyManaged\" | \"unreadable\";\n}\n\nexport interface LegacyDocumentScanResult {\n candidates: LegacyDocumentCandidate[];\n skipped: ImportSkippedDocument[];\n}\n\nexport interface ScanLegacyDocumentsOptions {\n rootDir: string;\n include?: string[];\n exclude?: string[];\n maxFileKb?: number;\n}\n\nexport interface BuildImportedDocumentsOptions {\n accountId: string;\n projectId: string;\n repositoryLinkId: string;\n candidates: LegacyDocumentCandidate[];\n existingDocuments?: BrainDocumentItem[];\n importedAt?: string;\n}\n\nexport async function inspectLocalRepository(rootDir: string, defaultBranch: string): Promise<LocalRepositoryMetadata> {\n const requestedRoot = path.resolve(rootDir);\n const root = await runGit([\"-C\", requestedRoot, \"rev-parse\", \"--show-toplevel\"]).catch(() => requestedRoot);\n const detectedBranch = await runGit([\"-C\", root, \"symbolic-ref\", \"--quiet\", \"--short\", \"HEAD\"]).catch(() => defaultBranch);\n const originUrl = await runGit([\"-C\", root, \"remote\", \"get-url\", \"origin\"]).catch(() => undefined);\n const parsedCloneUrl = originUrl ? parseOptionalOriginCloneUrl(originUrl) : undefined;\n const repoName = (parsedCloneUrl?.repoName ?? path.basename(root)) || \"repository\";\n const fingerprintSeed = parsedCloneUrl ? `origin:${parsedCloneUrl.normalizedKey}` : `repo:${repoName}:${detectedBranch || defaultBranch}`;\n\n return {\n rootDir: root,\n repoName,\n defaultBranch: detectedBranch || defaultBranch,\n repoFingerprint: `import_${hashText(fingerprintSeed, 24)}`,\n ...(parsedCloneUrl ? { parsedCloneUrl } : {}),\n ...(!parsedCloneUrl && originUrl ? { originRemoteWarning: \"Origin remote is not a supported hosted HTTPS or SSH clone URL, so no clone URL will be stored.\" } : {})\n };\n}\n\nexport async function scanLegacyDocuments(options: ScanLegacyDocumentsOptions): Promise<LegacyDocumentScanResult> {\n const rootDir = path.resolve(options.rootDir);\n const maxBytes = (options.maxFileKb ?? defaultMaxFileKb) * 1024;\n const skipped: ImportSkippedDocument[] = [];\n const candidates: LegacyDocumentCandidate[] = [];\n const usedDestinationPaths = new Set<string>();\n const repoPaths = (await listRepositoryPaths(rootDir)).sort((first, second) => first.localeCompare(second));\n\n for (const repoPath of repoPaths) {\n if (!matchesIncludeExclude(repoPath, options.include, options.exclude)) {\n skipped.push({ repoPath, reason: \"excluded\" });\n continue;\n }\n const contentFormat = importableContentFormatFromRepoPath(repoPath);\n if (!contentFormat) {\n skipped.push({ repoPath, reason: \"notMarkdown\" });\n continue;\n }\n if (isExcludedRepoPath(repoPath)) {\n skipped.push({ repoPath, reason: \"excluded\" });\n continue;\n }\n\n const fullPath = path.join(rootDir, ...repoPath.split(\"/\"));\n const fileStat = await stat(fullPath).catch(() => undefined);\n if (!fileStat?.isFile()) {\n skipped.push({ repoPath, reason: \"unreadable\" });\n continue;\n }\n if (fileStat.size > maxBytes) {\n skipped.push({ repoPath, reason: \"tooLarge\" });\n continue;\n }\n\n const content = await readFile(fullPath, \"utf8\").catch(() => undefined);\n if (content === undefined) {\n skipped.push({ repoPath, reason: \"unreadable\" });\n continue;\n }\n if (isAmistioManagedDocument(content)) {\n skipped.push({ repoPath, reason: \"alreadyManaged\" });\n continue;\n }\n\n const documentType = classifyLegacyDocument(repoPath, content);\n const destinationPath = uniqueDestinationPath(canonicalImportPath(repoPath, documentType, contentFormat), repoPath, usedDestinationPaths);\n candidates.push({\n sourcePath: repoPath,\n repoPath: destinationPath,\n documentType,\n contentFormat,\n title: inferTitle(content, repoPath),\n content,\n contentHash: sha256ContentHash(content)\n });\n }\n\n return { candidates, skipped };\n}\n\nexport function buildImportedBrainDocuments(options: BuildImportedDocumentsOptions): BrainDocumentItem[] {\n const importedAt = options.importedAt ?? new Date().toISOString();\n const existingById = new Map((options.existingDocuments ?? []).map((document) => [document.documentId, document]));\n\n return options.candidates.map((candidate) => {\n const documentId = stableImportDocumentId(options.accountId, options.projectId, options.repositoryLinkId, candidate.sourcePath);\n const existing = existingById.get(documentId);\n const revision = existing ? (existing.contentHash === candidate.contentHash ? existing.revision : existing.revision + 1) : 0;\n return {\n id: documentId,\n type: \"brainDocument\",\n schemaVersion: 1,\n accountId: options.accountId,\n projectId: options.projectId,\n documentId,\n documentType: candidate.documentType,\n contentFormat: candidate.contentFormat,\n title: candidate.title,\n status: \"approved\",\n repoPath: candidate.repoPath,\n content: candidate.content,\n contentHash: candidate.contentHash,\n frontmatter: {\n ...(existing?.frontmatter ?? {}),\n legacySourcePath: candidate.sourcePath,\n importedByCommand: \"amistio import\",\n importedAt,\n importedSourceHash: candidate.contentHash\n },\n revision,\n source: \"repo\",\n syncState: \"approved\",\n createdAt: existing?.createdAt ?? importedAt,\n updatedAt: importedAt,\n approvedRevision: revision\n } satisfies BrainDocumentItem;\n });\n}\n\nexport function importSkipCounts(skipped: ImportSkippedDocument[]): Record<ImportSkippedDocument[\"reason\"], number> {\n return {\n notMarkdown: skipped.filter((item) => item.reason === \"notMarkdown\").length,\n excluded: skipped.filter((item) => item.reason === \"excluded\").length,\n tooLarge: skipped.filter((item) => item.reason === \"tooLarge\").length,\n alreadyManaged: skipped.filter((item) => item.reason === \"alreadyManaged\").length,\n unreadable: skipped.filter((item) => item.reason === \"unreadable\").length\n };\n}\n\nfunction parseOptionalOriginCloneUrl(originUrl: string): ParsedRepositoryCloneUrl | undefined {\n try {\n return parseRepositoryCloneUrl(originUrl);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (message.toLowerCase().includes(\"credential\") || message.toLowerCase().includes(\"password\")) {\n throw new Error(\"Repository origin remote contains embedded credentials. Remove credentials from the remote URL before importing.\");\n }\n return undefined;\n }\n}\n\nasync function listRepositoryPaths(rootDir: string): Promise<string[]> {\n const gitFiles = await runGit([\"-C\", rootDir, \"ls-files\", \"--cached\", \"--others\", \"--exclude-standard\"]).catch(() => undefined);\n if (gitFiles !== undefined) {\n return gitFiles.split(\"\\n\").map((line) => normalizeRepoPath(line)).filter((line) => line.length > 0);\n }\n\n const files: string[] = [];\n await walkRepository(rootDir, rootDir, files);\n return files;\n}\n\nasync function walkRepository(rootDir: string, directory: string, files: string[]): Promise<void> {\n const entries = await readdir(directory, { withFileTypes: true }).catch(() => []);\n for (const entry of entries) {\n const fullPath = path.join(directory, entry.name);\n const repoPath = normalizeRepoPath(path.relative(rootDir, fullPath));\n if (entry.isDirectory()) {\n if (!excludedDirectoryNames.has(entry.name)) {\n await walkRepository(rootDir, fullPath, files);\n }\n } else if (entry.isFile() && !isExcludedRepoPath(repoPath)) {\n files.push(repoPath);\n }\n }\n}\n\nfunction matchesIncludeExclude(repoPath: string, include: string[] | undefined, exclude: string[] | undefined): boolean {\n if (include?.length && !include.some((pattern) => wildcardMatch(pattern, repoPath))) {\n return false;\n }\n if (exclude?.some((pattern) => wildcardMatch(pattern, repoPath))) {\n return false;\n }\n return true;\n}\n\nfunction wildcardMatch(pattern: string, repoPath: string): boolean {\n const normalizedPattern = normalizeRepoPath(pattern);\n const escaped = normalizedPattern.replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\").replace(/\\*\\*\\//g, \"::DOUBLE_STAR_SLASH::\").replace(/\\*\\*/g, \"::DOUBLE_STAR::\").replace(/\\?/g, \"[^/]\").replace(/\\*/g, \"[^/]*\").replace(/::DOUBLE_STAR_SLASH::/g, \"(?:.*/)?\").replace(/::DOUBLE_STAR::/g, \".*\");\n return new RegExp(`^${escaped}$`).test(repoPath);\n}\n\nfunction isExcludedRepoPath(repoPath: string): boolean {\n if (isControlPlaneTemplateRepoPath(repoPath)) return true;\n if (excludedFileNames.has(repoPath)) return true;\n const segments = repoPath.split(\"/\");\n if (segments.some((segment) => excludedDirectoryNames.has(segment) || generatedPathSegments.has(segment))) return true;\n const basename = segments[segments.length - 1]?.toLowerCase() ?? \"\";\n return basename.startsWith(\".env\") || basename.includes(\"secret\") || basename.includes(\"token\") || basename.includes(\"credential\") || basename.endsWith(\".lock\");\n}\n\nfunction isAmistioManagedDocument(content: string): boolean {\n const frontmatter = parseFrontmatter(content);\n if (typeof frontmatter.amistioDocumentId === \"string\" && frontmatter.amistioDocumentId.trim().length > 0) {\n return true;\n }\n return /^\\s*<!--[\\s\\S]*?amistioDocumentId\\s*:/i.test(content);\n}\n\nfunction classifyLegacyDocument(repoPath: string, content: string): DocumentType {\n const localMemoryDocumentType = classifyLocalMemoryDocument(repoPath, content);\n if (localMemoryDocumentType) return localMemoryDocumentType;\n\n const haystack = `${repoPath} ${inferTitle(content, repoPath)}`.toLowerCase();\n if (/\\b(prompt|prompts|instruction|instructions|copilot|agent|skill)\\b/.test(haystack)) return \"prompt\";\n if (/\\b(adr|decision|decisions|rfc)\\b/.test(haystack)) return \"decision\";\n if (/\\b(architecture|architectural|design|system|technical|tech-spec)\\b/.test(haystack)) return \"architecture\";\n if (/\\b(feature|features|spec|requirements|prd|story|stories)\\b/.test(haystack)) return \"feature\";\n if (/\\b(memory|memories|lesson|lessons|mistake|mistakes|learning|retro|retrospective)\\b/.test(haystack)) return \"memory\";\n if (/\\b(plan|plans|roadmap|milestone|todo|task|tasks)\\b/.test(haystack)) return \"plan\";\n if (/\\b(workflow|workflows|runbook|playbook|process|procedure|ops)\\b/.test(haystack)) return \"workflow\";\n return \"context\";\n}\n\nfunction canonicalImportPath(sourcePath: string, documentType: DocumentType, contentFormat: DocumentContentFormat): string {\n if (isCanonicalControlPlanePath(sourcePath) && inferContentFormatFromRepoPath(sourcePath)) {\n return sourcePath;\n }\n if (isLegacyControlPlanePath(sourcePath) && inferContentFormatFromRepoPath(sourcePath)) {\n return `docs/${sourcePath}`;\n }\n const baseSlug = slugFromPath(sourcePath);\n const extension = contentFormat === \"html\" ? \"html\" : \"md\";\n return `${documentFolderByType[documentType]}/imported/${baseSlug}.${extension}`;\n}\n\nfunction uniqueDestinationPath(basePath: string, sourcePath: string, usedPaths: Set<string>): string {\n if (!usedPaths.has(basePath)) {\n usedPaths.add(basePath);\n return basePath;\n }\n const extension = path.posix.extname(basePath) || \".md\";\n const directory = path.posix.dirname(basePath);\n const basename = path.posix.basename(basePath, extension);\n const uniquePath = `${directory}/${basename}-${hashText(sourcePath, 8)}${extension}`;\n usedPaths.add(uniquePath);\n return uniquePath;\n}\n\nfunction isControlPlanePath(repoPath: string): boolean {\n return isCanonicalControlPlanePath(repoPath) || isLegacyControlPlanePath(repoPath);\n}\n\nfunction importableContentFormatFromRepoPath(repoPath: string): DocumentContentFormat | undefined {\n return inferContentFormatFromRepoPath(repoPath) ?? localMemoryImportContentFormat(repoPath);\n}\n\nfunction localMemoryImportContentFormat(repoPath: string): DocumentContentFormat | undefined {\n const normalized = normalizeRepoPath(repoPath);\n const lowerPath = normalized.toLowerCase();\n const basename = lowerPath.split(\"/\").at(-1) ?? lowerPath;\n if (extensionlessInstructionFiles.has(basename)) return \"markdown\";\n if (/\\.mdc$/i.test(normalized) && isRepoLocalToolMemoryPath(normalized)) return \"markdown\";\n return undefined;\n}\n\nfunction classifyLocalMemoryDocument(repoPath: string, content: string): DocumentType | undefined {\n const normalized = normalizeRepoPath(repoPath);\n if (!isRepoLocalMemoryOrInstructionPath(normalized)) return undefined;\n\n if (isMemoryImportPath(normalized) || hasMemoryCue(normalized, content)) {\n return \"memory\";\n }\n if (isInstructionImportPath(normalized)) {\n return \"prompt\";\n }\n return undefined;\n}\n\nfunction isRepoLocalMemoryOrInstructionPath(repoPath: string): boolean {\n return isMemoryImportPath(repoPath) || isInstructionImportPath(repoPath);\n}\n\nfunction isRepoLocalToolMemoryPath(repoPath: string): boolean {\n return isRepoLocalMemoryOrInstructionPath(repoPath);\n}\n\nfunction isMemoryImportPath(repoPath: string): boolean {\n const lowerPath = normalizeRepoPath(repoPath).toLowerCase();\n return /^(docs\\/memory|memory|memories|\\.memory|\\.memories)(\\/|$)/.test(lowerPath);\n}\n\nfunction isInstructionImportPath(repoPath: string): boolean {\n const normalized = normalizeRepoPath(repoPath);\n const lowerPath = normalized.toLowerCase();\n const segments = lowerPath.split(\"/\");\n const basename = segments.at(-1) ?? lowerPath;\n if (segments.length === 1 && rootAgentGuidanceFiles.has(basename)) return true;\n if (extensionlessInstructionFiles.has(basename)) return true;\n if (lowerPath === \".github/copilot-instructions.md\") return true;\n if (lowerPath.startsWith(\".github/instructions/\") && lowerPath.endsWith(\".instructions.md\")) return true;\n if (lowerPath.startsWith(\".cursor/rules/\") && /\\.(md|mdc)$/i.test(lowerPath)) return true;\n if (lowerPath.startsWith(\".windsurf/rules/\") && lowerPath.endsWith(\".md\")) return true;\n if (lowerPath.startsWith(\".cline/\") && lowerPath.endsWith(\".md\")) return true;\n if (lowerPath.startsWith(\".roo/\") && lowerPath.endsWith(\".md\")) return true;\n if (lowerPath.startsWith(\".claude/\") && lowerPath.endsWith(\".md\")) return true;\n if (lowerPath.startsWith(\".gemini/\") && lowerPath.endsWith(\".md\")) return true;\n if (lowerPath.startsWith(\".vscode/\") && lowerPath.endsWith(\".instructions.md\")) return true;\n return false;\n}\n\nfunction hasMemoryCue(repoPath: string, content: string): boolean {\n const haystack = `${repoPath} ${inferTitle(content, repoPath)}`.toLowerCase();\n return /\\b(memory|memories|lesson|lessons|mistake|mistakes|learning|retro|retrospective|observation|observations)\\b/.test(haystack);\n}\n\nfunction isCanonicalControlPlanePath(repoPath: string): boolean {\n const [firstSegment, secondSegment, thirdSegment] = normalizeRepoPath(repoPath).split(\"/\");\n return firstSegment === \"docs\" && Boolean((secondSegment === \"html\" && thirdSegment && (controlPlaneRoots as readonly string[]).includes(thirdSegment)) || (secondSegment && (controlPlaneRoots as readonly string[]).includes(secondSegment)));\n}\n\nfunction isLegacyControlPlanePath(repoPath: string): boolean {\n const [firstSegment] = repoPath.split(\"/\");\n return Boolean(firstSegment && (controlPlaneRoots as readonly string[]).includes(firstSegment));\n}\n\nfunction inferTitle(content: string, repoPath: string): string {\n const body = stripFrontmatter(content);\n const heading = body.split(\"\\n\").find((line) => /^#\\s+/.test(line))?.replace(/^#\\s+/, \"\").trim();\n if (heading) return heading;\n const htmlHeading = body.match(/<h1\\b[^>]*>([\\s\\S]*?)<\\/h1>/i)?.[1]?.replace(/<[^>]+>/g, \"\").trim();\n if (htmlHeading) return htmlHeading;\n const basename = path.posix.basename(repoPath, path.posix.extname(repoPath)).replace(/[-_]+/g, \" \").trim();\n return titleCase(basename || \"Imported Document\");\n}\n\nfunction stripFrontmatter(content: string): string {\n if (!content.startsWith(\"---\\n\")) return content;\n const end = content.indexOf(\"\\n---\", 4);\n if (end === -1) return content;\n const closingLineEnd = content.indexOf(\"\\n\", end + 4);\n return closingLineEnd === -1 ? \"\" : content.slice(closingLineEnd + 1);\n}\n\nfunction slugFromPath(repoPath: string): string {\n const withoutExtension = repoPath.replace(/\\.(md|mdx|mdc|html?)$/i, \"\");\n const slug = withoutExtension.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\").slice(0, 90);\n return slug || \"imported-document\";\n}\n\nfunction titleCase(value: string): string {\n return value.replace(/\\b\\w/g, (match) => match.toUpperCase());\n}\n\nfunction stableImportDocumentId(accountId: string, projectId: string, repositoryLinkId: string, sourcePath: string): string {\n return `doc_import_${hashText(`${accountId}\\0${projectId}\\0${repositoryLinkId}\\0${sourcePath}`, 24)}`;\n}\n\nfunction hashText(value: string, length: number): string {\n return createHash(\"sha256\").update(value).digest(\"hex\").slice(0, length);\n}\n\nfunction normalizeRepoPath(value: string): string {\n return value.replace(/\\\\/g, \"/\").replace(/^\\.\\//, \"\").replace(/^\\/+/, \"\");\n}\n\nasync function runGit(args: string[]): Promise<string> {\n const { stdout } = await execFileAsync(\"git\", args, { maxBuffer: 10 * 1024 * 1024 });\n return stdout.trim();\n}", "import { spawn } from \"node:child_process\";\nimport path from \"node:path\";\nimport type { RunnerInvocationChannel, RunnerReasoningEffort } from \"@amistio/shared\";\nimport type { RunnerProcessMode } from \"./runner-daemon.js\";\n\nexport interface BackgroundRunnerArgsOptions {\n apiUrl: string;\n runnerId: string;\n root: string;\n tool?: string;\n invocationChannel?: RunnerInvocationChannel;\n toolCommand?: string;\n model?: string;\n provider?: string;\n providerId?: string;\n modelId?: string;\n modelVariant?: string;\n reasoningEffort?: RunnerReasoningEffort;\n session: string;\n intervalSeconds: number;\n maxIterations?: number;\n maxConcurrentWork: number;\n maxPreflightAttempts: number;\n toolTimeoutSeconds: number;\n stream: boolean;\n verbose?: boolean;\n}\n\nexport interface RunnerActionResult {\n succeeded: boolean;\n message: string;\n error?: string;\n stopRunner?: boolean;\n}\n\nexport interface RunnerUpdateRuntimeRefreshOptions {\n mode: RunnerProcessMode;\n restartBackgroundRunner?: () => Promise<RunnerActionResult>;\n runUpdate?: () => Promise<RunnerActionResult>;\n}\n\nexport function buildBackgroundRunnerArgs(options: BackgroundRunnerArgsOptions): string[] {\n const args = [\n \"run\",\n \"--watch\",\n \"--api-url\",\n options.apiUrl,\n \"--runner-id\",\n options.runnerId,\n \"--root\",\n path.resolve(options.root),\n \"--session\",\n options.session,\n \"--interval-seconds\",\n String(options.intervalSeconds)\n ];\n if (options.tool) {\n args.push(\"--tool\", options.tool);\n }\n if (options.invocationChannel) {\n args.push(\"--invocation-channel\", options.invocationChannel);\n }\n if (options.toolCommand) {\n args.push(\"--tool-command\", options.toolCommand);\n }\n if (options.model) {\n args.push(\"--model\", options.model);\n }\n const providerId = options.providerId ?? options.provider;\n if (providerId) {\n args.push(\"--provider\", providerId);\n }\n if (options.modelId) {\n args.push(\"--model-id\", options.modelId);\n }\n if (options.modelVariant) {\n args.push(\"--model-variant\", options.modelVariant);\n }\n if (options.reasoningEffort) {\n args.push(\"--reasoning-effort\", options.reasoningEffort);\n }\n if (options.maxIterations !== undefined) {\n args.push(\"--max-iterations\", String(options.maxIterations));\n }\n args.push(\"--max-concurrent-work\", String(options.maxConcurrentWork));\n args.push(\"--max-preflight-attempts\", String(options.maxPreflightAttempts));\n args.push(\"--tool-timeout-seconds\", String(options.toolTimeoutSeconds));\n if (!options.stream) {\n args.push(\"--no-stream\");\n }\n if (options.verbose) {\n args.push(\"--verbose\");\n }\n return args;\n}\n\nexport async function runOfficialCliUpdate(): Promise<RunnerActionResult> {\n const result = await runOfficialUpdateProcess(\"npm\", [\"install\", \"-g\", \"@amistio/cli\"], 120_000);\n if (result.exitCode === 0) {\n return { succeeded: true, message: \"Official Amistio CLI update command completed.\" };\n }\n return { succeeded: false, message: \"Official Amistio CLI update command failed.\", error: result.output || `npm exited with code ${result.exitCode}.` };\n}\n\nexport async function runOfficialCliUpdateWithRuntimeRefresh(options: RunnerUpdateRuntimeRefreshOptions): Promise<RunnerActionResult> {\n const updateResult = await (options.runUpdate ?? runOfficialCliUpdate)();\n if (!updateResult.succeeded) {\n return updateResult;\n }\n\n if (options.mode === \"foreground\") {\n return {\n succeeded: true,\n stopRunner: true,\n message: `${updateResult.message} Restart the local runner command to load the updated CLI version.`\n };\n }\n\n if (!options.restartBackgroundRunner) {\n return {\n succeeded: false,\n stopRunner: true,\n message: `${updateResult.message} Background runner restart was not available after update. Restart the runner manually to load the updated CLI version.`,\n error: \"Background runner restart hook was not provided.\"\n };\n }\n\n const restartResult = await options.restartBackgroundRunner();\n if (restartResult.succeeded) {\n return {\n succeeded: true,\n stopRunner: true,\n message: `${updateResult.message} ${restartResult.message}`\n };\n }\n\n return {\n succeeded: false,\n stopRunner: true,\n message: `${updateResult.message} Background runner restart failed after update. Restart the runner manually to load the updated CLI version.`,\n error: restartResult.error ?? restartResult.message\n };\n}\n\nexport function runOfficialUpdateProcess(command: string, args: string[], timeoutMs: number): Promise<{ exitCode: number; output: string }> {\n return new Promise((resolve) => {\n const child = spawn(command, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n let output = \"\";\n const updateTimeout = setTimeout(() => {\n output += \"Timed out while running official CLI update.\\n\";\n child.kill(\"SIGTERM\");\n }, timeoutMs);\n child.stdout?.on(\"data\", (chunk: Buffer) => { output += chunk.toString(\"utf8\"); });\n child.stderr?.on(\"data\", (chunk: Buffer) => { output += chunk.toString(\"utf8\"); });\n child.on(\"error\", (error) => {\n clearTimeout(updateTimeout);\n resolve({ exitCode: 1, output: error.message });\n });\n child.on(\"close\", (code) => {\n clearTimeout(updateTimeout);\n resolve({ exitCode: code ?? 1, output: truncateProcessOutput(output) });\n });\n });\n}\n\nfunction truncateProcessOutput(value: string): string {\n const trimmed = value.trim();\n return trimmed.length > 1200 ? `${trimmed.slice(0, 1200)}...` : trimmed;\n}", "import { execFile } from \"node:child_process\";\nimport { copyFile, lstat, mkdir, readdir, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { promisify } from \"node:util\";\nimport type { WorkItem } from \"@amistio/shared\";\n\nconst execFileAsync = promisify(execFile);\nconst exactLocalEnvironmentFiles = new Set([\".env\", \".env.local\", \".env.development\", \".env.development.local\", \".env.test\", \".env.test.local\", \".env.production\", \".env.production.local\"]);\nconst localEnvironmentFilePattern = /^\\.env\\.[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)*\\.local$/;\n\nexport interface GitWorktreeIsolation {\n branch: string;\n baseRevision: string;\n implementationScopeId: string;\n preparedLocalEnvironmentFileCount?: number;\n repositoryLockId?: string;\n worktreeKey: string;\n worktreePath: string;\n}\n\nexport function needsGitWorktreeIsolation(workItem: WorkItem): boolean {\n return (workItem.workKind ?? \"implementation\") === \"implementation\";\n}\n\nexport function resolveWorktreeIdentity(workItem: WorkItem): Pick<GitWorktreeIsolation, \"branch\" | \"implementationScopeId\" | \"repositoryLockId\" | \"worktreeKey\"> {\n const implementationScopeId = workItem.controllingAdrId ?? workItem.implementationScopeId ?? workItem.impactDocumentId ?? workItem.reviewDocumentId ?? workItem.generatedDraftId ?? workItem.workItemId;\n const slug = workIsolationSlug(implementationScopeId, workItem.title);\n return {\n implementationScopeId,\n branch: workItem.executionBranch ?? `amistio/work/${slug}`,\n worktreeKey: workItem.executionWorktreeKey ?? `amistio/worktrees/${slug}`,\n ...(workItem.repositoryLockId ? { repositoryLockId: workItem.repositoryLockId } : {})\n };\n}\n\nexport async function prepareGitWorktreeIsolation(rootDir: string, workItem: WorkItem): Promise<GitWorktreeIsolation> {\n const identity = resolveWorktreeIdentity(workItem);\n const repoRoot = await gitOutput(rootDir, [\"rev-parse\", \"--show-toplevel\"]).catch((error: unknown) => {\n throw new Error(`Git worktree isolation requires a paired Git checkout: ${errorMessage(error)}`);\n });\n const currentHead = await gitOutput(repoRoot, [\"rev-parse\", \"HEAD\"]);\n await assertBaseRevision(repoRoot, workItem.baseRevision, currentHead);\n const baseRevision = currentHead;\n const worktreePath = localWorktreePath(repoRoot, identity.worktreeKey);\n\n if (await pathExists(worktreePath)) {\n await assertExistingWorktree(worktreePath, identity.branch);\n const preparedLocalEnvironmentFileCount = await prepareLocalWorktreeEnvironment(repoRoot, worktreePath);\n return { ...identity, baseRevision, worktreePath, ...(preparedLocalEnvironmentFileCount ? { preparedLocalEnvironmentFileCount } : {}) };\n }\n\n await mkdir(path.dirname(worktreePath), { recursive: true });\n const branchExists = await gitCommandSucceeds(repoRoot, [\"show-ref\", \"--verify\", \"--quiet\", `refs/heads/${identity.branch}`]);\n const worktreeArgs = branchExists ? [\"worktree\", \"add\", worktreePath, identity.branch] : [\"worktree\", \"add\", \"-b\", identity.branch, worktreePath, baseRevision];\n await gitOutput(repoRoot, worktreeArgs).catch((error: unknown) => {\n throw new Error(`Could not create Git worktree ${identity.worktreeKey} on ${identity.branch}: ${errorMessage(error)}`);\n });\n\n const preparedLocalEnvironmentFileCount = await prepareLocalWorktreeEnvironment(repoRoot, worktreePath);\n return { ...identity, baseRevision, worktreePath, ...(preparedLocalEnvironmentFileCount ? { preparedLocalEnvironmentFileCount } : {}) };\n}\n\nexport async function resolveExistingGitWorktreeIsolation(rootDir: string, workItem: WorkItem): Promise<GitWorktreeIsolation> {\n const identity = resolveWorktreeIdentity(workItem);\n const repoRoot = await gitOutput(rootDir, [\"rev-parse\", \"--show-toplevel\"]);\n const baseRevision = await gitOutput(repoRoot, [\"rev-parse\", \"HEAD\"]);\n const worktreePath = localWorktreePath(repoRoot, identity.worktreeKey);\n await assertExistingWorktree(worktreePath, identity.branch);\n return { ...identity, baseRevision, worktreePath };\n}\n\nfunction localWorktreePath(repoRoot: string, worktreeKey: string): string {\n const repoName = path.basename(repoRoot);\n const worktreeSlug = worktreeKey.split(\"/\").filter(Boolean).pop() ?? \"work\";\n return path.join(path.dirname(repoRoot), `${repoName}.worktrees`, worktreeSlug);\n}\n\nasync function assertExistingWorktree(worktreePath: string, branch: string): Promise<void> {\n await gitOutput(worktreePath, [\"rev-parse\", \"--is-inside-work-tree\"]);\n const currentBranch = await gitOutput(worktreePath, [\"branch\", \"--show-current\"]);\n if (currentBranch && currentBranch !== branch) {\n throw new Error(`Existing worktree is on ${currentBranch}; expected ${branch}.`);\n }\n}\n\nasync function assertBaseRevision(repoRoot: string, baseRevision: string | undefined, currentHead: string): Promise<void> {\n if (!baseRevision || baseRevision === currentHead) {\n return;\n }\n\n const revisionExists = await gitCommandSucceeds(repoRoot, [\"cat-file\", \"-e\", `${baseRevision}^{commit}`]);\n if (!revisionExists) {\n throw new Error(`Work item base revision ${baseRevision} is not available in this checkout; sync the repository before running implementation work.`);\n }\n\n const isAncestor = await gitCommandSucceeds(repoRoot, [\"merge-base\", \"--is-ancestor\", baseRevision, currentHead]);\n if (!isAncestor) {\n throw new Error(`Work item base revision ${baseRevision} is not an ancestor of ${currentHead}; refresh the work item before implementation.`);\n }\n}\n\nasync function prepareLocalWorktreeEnvironment(repoRoot: string, worktreePath: string): Promise<number> {\n const candidates = await localEnvironmentFileCandidates(repoRoot);\n let preparedCount = 0;\n\n for (const candidate of candidates) {\n const sourcePath = path.join(repoRoot, candidate);\n const targetPath = path.join(worktreePath, candidate);\n if (await pathExists(targetPath)) {\n continue;\n }\n if (await gitCommandSucceeds(repoRoot, [\"ls-files\", \"--error-unmatch\", \"--\", candidate])) {\n continue;\n }\n if (!(await gitCommandSucceeds(worktreePath, [\"check-ignore\", \"--quiet\", \"--\", candidate]))) {\n continue;\n }\n\n try {\n await copyFile(sourcePath, targetPath);\n preparedCount += 1;\n } catch (error) {\n throw new Error(`Could not prepare local worktree environment files: ${safeFileError(error)}`);\n }\n }\n\n return preparedCount;\n}\n\nasync function localEnvironmentFileCandidates(repoRoot: string): Promise<string[]> {\n const names = new Set(exactLocalEnvironmentFiles);\n for (const entry of await readdir(repoRoot)) {\n if (isAllowedLocalEnvironmentFile(entry)) {\n names.add(entry);\n }\n }\n\n const candidates: string[] = [];\n for (const name of [...names].sort()) {\n if (!isRootFileName(name)) {\n continue;\n }\n const source = await lstat(path.join(repoRoot, name)).catch(() => undefined);\n if (source?.isFile()) {\n candidates.push(name);\n }\n }\n return candidates;\n}\n\nfunction isAllowedLocalEnvironmentFile(name: string): boolean {\n return exactLocalEnvironmentFiles.has(name) || localEnvironmentFilePattern.test(name);\n}\n\nfunction isRootFileName(name: string): boolean {\n return name === path.basename(name) && !name.includes(\"/\") && !name.includes(\"\\\\\");\n}\n\nasync function gitOutput(cwd: string, args: string[]): Promise<string> {\n const { stdout } = await execFileAsync(\"git\", args, { cwd, maxBuffer: 1024 * 1024 });\n return stdout.trim();\n}\n\nasync function gitCommandSucceeds(cwd: string, args: string[]): Promise<boolean> {\n return execFileAsync(\"git\", args, { cwd }).then(() => true, () => false);\n}\n\nasync function pathExists(value: string): Promise<boolean> {\n return stat(value).then(() => true, () => false);\n}\n\nfunction workIsolationSlug(scopeId: string, title: string): string {\n const scopeSlug = slugify(scopeId);\n const titleSlug = slugify(title).slice(0, 32);\n const combined = titleSlug && !scopeSlug.includes(titleSlug) ? `${scopeSlug}-${titleSlug}` : scopeSlug;\n return combined.slice(0, 96).replace(/-+$/g, \"\") || \"work\";\n}\n\nfunction slugify(value: string): string {\n return value.toLowerCase().replace(/[^a-z0-9]+/g, \"-\").replace(/^-+|-+$/g, \"\") || \"work\";\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction safeFileError(error: unknown): string {\n if (typeof error === \"object\" && error !== null && \"code\" in error && typeof (error as { code?: unknown }).code === \"string\") {\n return (error as { code: string }).code;\n }\n return error instanceof Error ? error.name : \"unknown file error\";\n}", "import { execFile } from \"node:child_process\";\nimport path from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { parseRepositoryCloneUrl, type BrainDocumentItem, type ImplementationHandoff, type ImplementationHandoffArtifact, type ImplementationHandoffArtifacts, type ImplementationHandoffRecovery, type RepositoryLinkItem, type WorkItem } from \"@amistio/shared\";\nimport type { GitWorktreeIsolation } from \"./git-worktree.js\";\nimport { materializeBrainDocuments, type MaterializeResult } from \"./sync.js\";\n\nconst execFileAsync = promisify(execFile);\n\ninterface CommandResult {\n stdout: string;\n stderr: string;\n}\n\nexport type ImplementationHandoffCommandRunner = (command: string, args: string[], options: { cwd: string }) => Promise<CommandResult>;\n\nexport interface CompleteImplementationHandoffInput {\n approvedArtifacts?: BrainDocumentItem[];\n baseBranch?: string;\n commandRunner?: ImplementationHandoffCommandRunner;\n primaryRepoRoot: string;\n repositoryLink?: RepositoryLinkItem;\n verificationSummary?: string;\n workItem: WorkItem;\n worktreeIsolation?: GitWorktreeIsolation;\n worktreePath: string;\n}\n\ninterface PullRequestMetadata {\n number: number;\n url: string;\n}\n\ntype HandoffRecoveryInput = Omit<ImplementationHandoffRecovery, \"worktreeKey\" | \"conflictFiles\"> & { conflictFiles?: string[] };\n\ntype HandoffCleanupResult = { status: \"completed\" | \"failed\" | \"notApplicable\"; message?: string };\n\nexport async function completeImplementationHandoff(input: CompleteImplementationHandoffInput): Promise<ImplementationHandoff> {\n const run = input.commandRunner ?? defaultCommandRunner;\n const headBranch = input.worktreeIsolation?.branch ?? input.workItem.executionBranch;\n const baseBranch = input.baseBranch ?? input.repositoryLink?.defaultBranch ?? \"main\";\n\n if (!headBranch) {\n return blockedHandoff({ baseBranch, message: \"Implementation handoff needs an execution branch before it can create a pull request.\" });\n }\n\n const common = {\n provider: input.repositoryLink?.provider ?? \"github\",\n baseBranch,\n headBranch\n };\n\n try {\n const artifactResult = await materializeApprovedArtifacts(input);\n if (artifactResult.blocked.length) {\n return blockedHandoff({\n ...common,\n artifacts: artifactResult,\n message: `Implementation handoff is blocked because ${artifactResult.blocked.length} approved artifact${artifactResult.blocked.length === 1 ? \"\" : \"s\"} could not be materialized safely.`\n });\n }\n\n const unmergedFiles = await gitOutput(run, input.worktreePath, [\"diff\", \"--name-only\", \"--diff-filter=U\"]);\n if (unmergedFiles.trim()) {\n return blockedHandoff({\n ...common,\n artifacts: artifactResult,\n message: \"Implementation handoff is blocked because the worktree has unresolved merge conflicts.\",\n recovery: handoffRecovery(input, {\n category: \"unresolvedConflicts\",\n availableActions: [\"requeueFreshAttempt\", \"keepForManualRepair\", \"exportHandoffDetails\"],\n cleanupEligible: false,\n conflictFiles: safeRepoPaths(unmergedFiles),\n rebaseAbortStatus: \"notApplicable\",\n summary: \"Resolve the local conflicts manually or requeue a fresh attempt after reviewing the preserved worktree.\"\n })\n });\n }\n\n const status = await gitOutput(run, input.worktreePath, [\"status\", \"--porcelain=v1\", \"-z\", \"--untracked-files=all\"]);\n if (!status) {\n const cleanup: HandoffCleanupResult = input.worktreeIsolation ? await cleanupWorktree(run, input) : { status: \"notApplicable\" };\n return {\n ...common,\n status: \"noChanges\",\n cleanupStatus: cleanup.status,\n ...(cleanup.message ? { cleanupMessage: cleanup.message } : {}),\n artifacts: artifactResult,\n recovery: handoffRecovery(input, {\n category: cleanup.status === \"completed\" ? \"noChangeCleaned\" : cleanup.status === \"failed\" ? \"cleanupRetryAvailable\" : \"manualReview\",\n availableActions: cleanup.status === \"failed\" ? [\"retryCleanup\", \"markSupersededNoChanges\", \"exportHandoffDetails\"] : [\"markSupersededNoChanges\", \"exportHandoffDetails\"],\n cleanupEligible: cleanup.status === \"failed\",\n rebaseAbortStatus: \"notApplicable\",\n summary: cleanup.status === \"completed\" ? \"No repository changes were found and the runner-created worktree was removed.\" : \"No repository changes were found for handoff.\"\n }),\n message: cleanup.status === \"completed\" ? \"Local execution completed with no repository changes to hand off and the local worktree was cleaned up.\" : \"Local execution completed with no repository changes to hand off.\"\n };\n }\n\n const remoteName = await resolveRemoteName(run, input.worktreePath);\n const remoteUrl = await gitOutput(run, input.worktreePath, [\"remote\", \"get-url\", remoteName]);\n const provider = input.repositoryLink?.provider ?? inferProvider(remoteUrl);\n\n if (provider !== \"github\") {\n return blockedHandoff({\n ...common,\n provider,\n remoteName,\n artifacts: artifactResult,\n message: \"Automated pull request handoff currently requires a GitHub remote. Commit and push manually, or link a GitHub repository.\",\n recovery: handoffRecovery(input, {\n category: \"nonGithubProvider\",\n availableActions: [\"requeueFreshAttempt\", \"keepForManualRepair\", \"exportHandoffDetails\"],\n cleanupEligible: false,\n rebaseAbortStatus: \"notApplicable\",\n summary: \"Automated retry is unavailable until this project uses a GitHub repository link.\"\n })\n });\n }\n\n await gitOutput(run, input.worktreePath, [\"add\", \"-A\"]);\n await gitOutput(run, input.worktreePath, [\"commit\", \"-m\", commitSubject(input.workItem), \"-m\", commitBody(input)]);\n const preRebaseCommitSha = await gitOutput(run, input.worktreePath, [\"rev-parse\", \"HEAD\"]);\n await fetchRemoteBase(run, input.worktreePath, { baseBranch, remoteName });\n try {\n await rebaseBranchFromRemoteBase(run, input.worktreePath);\n } catch (error) {\n return blockedRebaseHandoff({ artifactResult, baseBranch, error, headBranch, input, preRebaseCommitSha, remoteName, run });\n }\n const commitSha = await gitOutput(run, input.worktreePath, [\"rev-parse\", \"HEAD\"]);\n await gitOutput(run, input.worktreePath, [\"push\", \"--set-upstream\", remoteName, headBranch]);\n\n const pullRequest = await ensureGithubPullRequest(run, input.worktreePath, { artifacts: artifactResult, baseBranch, headBranch, workItem: input.workItem, ...(input.verificationSummary ? { verificationSummary: input.verificationSummary } : {}) });\n const cleanup = await cleanupWorktree(run, input);\n\n return {\n provider: \"github\",\n status: \"prReady\",\n baseBranch,\n headBranch,\n remoteName,\n commitSha,\n prNumber: pullRequest.number,\n prUrl: pullRequest.url,\n cleanupStatus: cleanup.status,\n ...(cleanup.message ? { cleanupMessage: cleanup.message } : {}),\n ...(cleanup.status === \"failed\" ? {\n recovery: handoffRecovery(input, {\n category: \"cleanupRetryAvailable\",\n availableActions: [\"retryCleanup\", \"exportHandoffDetails\"],\n cleanupEligible: true,\n rebaseAbortStatus: \"notApplicable\",\n summary: \"The pull request is durable, but local worktree cleanup needs another runner-local attempt.\"\n })\n } : {}),\n artifacts: artifactResult,\n message: cleanup.status === \"completed\" ? \"GitHub pull request is ready for review and the local worktree was cleaned up.\" : \"GitHub pull request is ready for review; local worktree cleanup needs attention.\"\n };\n } catch (error) {\n return blockedHandoff({\n ...common,\n message: \"Implementation handoff is blocked and the local worktree was preserved for recovery.\",\n error: safeErrorMessage(error),\n recovery: handoffRecovery(input, {\n category: \"providerBlocked\",\n availableActions: [\"retryHandoff\", \"requeueFreshAttempt\", \"keepForManualRepair\", \"exportHandoffDetails\"],\n cleanupEligible: false,\n rebaseAbortStatus: \"notAttempted\",\n summary: \"Retry handoff after fixing local Git, remote, or GitHub CLI access; requeue only if a fresh attempt is preferable.\"\n })\n });\n }\n}\n\nexport async function cleanupImplementationWorktree(input: Pick<CompleteImplementationHandoffInput, \"commandRunner\" | \"primaryRepoRoot\" | \"worktreePath\">): Promise<{ status: \"completed\" | \"failed\"; message?: string }> {\n const run = input.commandRunner ?? defaultCommandRunner;\n return cleanupWorktree(run, input);\n}\n\nasync function blockedRebaseHandoff(input: { artifactResult: ImplementationHandoffArtifacts; baseBranch: string; error: unknown; headBranch: string; input: CompleteImplementationHandoffInput; preRebaseCommitSha: string; remoteName: string; run: ImplementationHandoffCommandRunner }): Promise<ImplementationHandoff> {\n const conflictFiles = await safeConflictFiles(input.run, input.input.worktreePath);\n const rebaseAbortStatus = await abortRebaseForRecovery(input.run, input.input.worktreePath, input.preRebaseCommitSha);\n return blockedHandoff({\n provider: \"github\",\n status: \"blocked\",\n baseBranch: input.baseBranch,\n headBranch: input.headBranch,\n remoteName: input.remoteName,\n commitSha: input.preRebaseCommitSha,\n artifacts: input.artifactResult,\n message: rebaseAbortStatus === \"succeeded\" ? \"Implementation handoff hit a rebase conflict. Conflict files were captured and the branch was restored for recovery.\" : \"Implementation handoff hit a rebase conflict and the local worktree was preserved for recovery.\",\n error: safeErrorMessage(input.error),\n recovery: handoffRecovery(input.input, {\n category: \"rebaseConflict\",\n availableActions: [\"retryHandoff\", \"requeueFreshAttempt\", \"keepForManualRepair\", \"exportHandoffDetails\"],\n cleanupEligible: false,\n conflictFiles,\n rebaseAbortStatus,\n summary: rebaseAbortStatus === \"succeeded\" ? \"The failed rebase was aborted after conflict metadata was captured, so the implementation branch can be retried or reviewed manually.\" : \"The failed rebase could not be safely aborted; review the preserved worktree before retrying.\"\n })\n });\n}\n\nasync function materializeApprovedArtifacts(input: CompleteImplementationHandoffInput): Promise<ImplementationHandoffArtifacts> {\n const { selected: artifacts, skipped } = selectApprovedWorkArtifacts(input.workItem, input.approvedArtifacts ?? []);\n if (!artifacts.length) {\n return { included: [], skipped, blocked: [] };\n }\n\n let materialized: MaterializeResult;\n try {\n materialized = await materializeBrainDocuments(input.worktreePath, artifacts);\n } catch (error) {\n return { included: [], skipped, blocked: artifacts.map((artifact) => artifactStatus(artifact, \"blocked\", safeErrorMessage(error))) };\n }\n\n return {\n included: materialized.written.map((repoPath) => artifactStatus(findArtifactByPath(artifacts, repoPath), \"included\", \"Approved artifact materialized into the implementation worktree.\")),\n skipped: [...skipped, ...materialized.skipped.map((repoPath) => artifactStatus(findArtifactByPath(artifacts, repoPath), \"skipped\", \"Approved artifact was already current in the implementation worktree.\"))],\n blocked: materialized.conflicts.map((conflict) => artifactStatus(findArtifactByPath(artifacts, conflictRepoPath(conflict)), \"blocked\", conflict))\n };\n}\n\nfunction handoffRecovery(input: CompleteImplementationHandoffInput, recovery: HandoffRecoveryInput): ImplementationHandoffRecovery {\n const worktreeKey = input.worktreeIsolation?.worktreeKey ?? input.workItem.executionWorktreeKey;\n return {\n ...recovery,\n conflictFiles: recovery.conflictFiles ?? [],\n ...(worktreeKey ? { worktreeKey } : {})\n };\n}\n\nasync function safeConflictFiles(run: ImplementationHandoffCommandRunner, cwd: string): Promise<string[]> {\n const unmergedFiles = await gitOutput(run, cwd, [\"diff\", \"--name-only\", \"--diff-filter=U\"]).catch(() => \"\");\n return safeRepoPaths(unmergedFiles);\n}\n\nasync function abortRebaseForRecovery(run: ImplementationHandoffCommandRunner, cwd: string, expectedHead: string): Promise<ImplementationHandoffRecovery[\"rebaseAbortStatus\"]> {\n try {\n await gitOutput(run, cwd, [\"rebase\", \"--abort\"]);\n const currentHead = await gitOutput(run, cwd, [\"rev-parse\", \"HEAD\"]);\n return currentHead === expectedHead ? \"succeeded\" : \"failed\";\n } catch {\n return \"failed\";\n }\n}\n\nfunction safeRepoPaths(output: string): string[] {\n const seen = new Set<string>();\n for (const value of output.split(/\\0|\\r?\\n/g)) {\n const repoPath = value.trim();\n if (!repoPath || repoPath.startsWith(\"/\") || /^[A-Za-z]:[\\\\/]/.test(repoPath) || repoPath.split(/[\\\\/]+/).includes(\"..\")) {\n continue;\n }\n seen.add(repoPath);\n }\n return [...seen].slice(0, 25);\n}\n\nfunction selectApprovedWorkArtifacts(workItem: WorkItem, documents: BrainDocumentItem[]): { selected: BrainDocumentItem[]; skipped: ImplementationHandoffArtifact[] } {\n const draftId = workItem.generatedDraftId;\n const explicitDocumentIds = new Set([workItem.reviewDocumentId, workItem.impactDocumentId].filter((value): value is string => Boolean(value)));\n const scopeIds = new Set([workItem.workItemId, workItem.controllingAdrId, workItem.implementationScopeId].filter((value): value is string => Boolean(value)));\n const skipped: ImplementationHandoffArtifact[] = [];\n const selected = documents.filter((document) => {\n const inScope = Boolean((draftId && document.frontmatter.generatedDraftId === draftId)\n || explicitDocumentIds.has(document.documentId)\n || explicitDocumentIds.has(document.id)\n || [document.frontmatter.workItemId, document.frontmatter.generationWorkItemId, document.frontmatter.revisionWorkItemId, document.frontmatter.controllingAdrId, document.frontmatter.adrId, document.frontmatter.implementationScopeId]\n .some((value) => typeof value === \"string\" && scopeIds.has(value)));\n if (!inScope) return false;\n if (document.status !== \"approved\" && document.syncState !== \"approved\" && document.syncState !== \"synced\") {\n skipped.push(artifactStatus(document, \"skipped\", \"Artifact is not approved for repository inclusion.\"));\n return false;\n }\n if (![\"markdown\", \"html\", undefined].includes(document.contentFormat)) {\n skipped.push(artifactStatus(document, \"skipped\", \"Artifact format is not supported for implementation PR inclusion.\"));\n return false;\n }\n return true;\n });\n const byDocumentId = new Map<string, BrainDocumentItem>();\n for (const document of selected) {\n byDocumentId.set(document.documentId, document);\n }\n return { selected: [...byDocumentId.values()], skipped };\n}\n\nfunction findArtifactByPath(artifacts: BrainDocumentItem[], repoPath: string): BrainDocumentItem {\n return artifacts.find((artifact) => artifact.repoPath === repoPath) ?? artifacts[0]!;\n}\n\nfunction artifactStatus(artifact: BrainDocumentItem, status: ImplementationHandoffArtifact[\"status\"], message: string): ImplementationHandoffArtifact {\n return {\n documentId: artifact.documentId,\n title: truncate(artifact.title, 200),\n repoPath: artifact.repoPath,\n contentFormat: artifact.contentFormat ?? \"markdown\",\n status,\n message: truncate(message, 600)\n };\n}\n\nfunction conflictRepoPath(conflict: string): string {\n return conflict.split(\":\")[0]?.trim() ?? conflict;\n}\n\nasync function ensureGithubPullRequest(run: ImplementationHandoffCommandRunner, cwd: string, input: { artifacts?: ImplementationHandoffArtifacts; baseBranch: string; headBranch: string; verificationSummary?: string; workItem: WorkItem }): Promise<PullRequestMetadata> {\n const existing = await run(\"gh\", [\"pr\", \"list\", \"--head\", input.headBranch, \"--base\", input.baseBranch, \"--state\", \"open\", \"--json\", \"number,url\", \"--limit\", \"1\"], { cwd });\n const parsed = parsePullRequestList(existing.stdout);\n if (parsed) {\n return parsed;\n }\n\n const created = await run(\"gh\", [\"pr\", \"create\", \"--base\", input.baseBranch, \"--head\", input.headBranch, \"--title\", pullRequestTitle(input.workItem), \"--body\", pullRequestBody(input)], { cwd });\n const url = extractPullRequestUrl(created.stdout);\n if (!url) {\n throw new Error(\"GitHub CLI did not return a pull request URL.\");\n }\n const number = pullRequestNumber(url);\n if (!number) {\n throw new Error(\"GitHub CLI returned a pull request URL without a parseable number.\");\n }\n return { number, url };\n}\n\nasync function cleanupWorktree(run: ImplementationHandoffCommandRunner, input: Pick<CompleteImplementationHandoffInput, \"primaryRepoRoot\" | \"worktreePath\">): Promise<{ status: \"completed\" | \"failed\"; message?: string }> {\n const status = await gitOutput(run, input.worktreePath, [\"status\", \"--porcelain=v1\", \"-z\", \"--untracked-files=all\"]);\n if (status) {\n return { status: \"failed\", message: \"Cleanup skipped because the worktree is not clean after PR handoff.\" };\n }\n\n try {\n await gitOutput(run, input.primaryRepoRoot || path.dirname(input.worktreePath), [\"worktree\", \"remove\", input.worktreePath]);\n return { status: \"completed\" };\n } catch (error) {\n return { status: \"failed\", message: `Cleanup failed: ${safeErrorMessage(error)}` };\n }\n}\n\nasync function resolveRemoteName(run: ImplementationHandoffCommandRunner, cwd: string): Promise<string> {\n const remotes = (await gitOutput(run, cwd, [\"remote\"]))\n .split(/\\r?\\n/g)\n .map((remote) => remote.trim())\n .filter(Boolean);\n if (!remotes.length) {\n throw new Error(\"No Git remote is configured for PR handoff.\");\n }\n return remotes.includes(\"origin\") ? \"origin\" : remotes[0]!;\n}\n\nasync function fetchRemoteBase(run: ImplementationHandoffCommandRunner, cwd: string, input: { baseBranch: string; remoteName: string }): Promise<void> {\n await gitOutput(run, cwd, [\"fetch\", input.remoteName, input.baseBranch]);\n}\n\nasync function rebaseBranchFromRemoteBase(run: ImplementationHandoffCommandRunner, cwd: string): Promise<void> {\n await gitOutput(run, cwd, [\"rebase\", \"FETCH_HEAD\"]);\n}\n\nasync function gitOutput(run: ImplementationHandoffCommandRunner, cwd: string, args: string[]): Promise<string> {\n const result = await run(\"git\", args, { cwd });\n return result.stdout.trim();\n}\n\nfunction blockedHandoff(input: Partial<ImplementationHandoff> & Pick<ImplementationHandoff, \"message\">): ImplementationHandoff {\n return {\n status: \"blocked\",\n cleanupStatus: \"pending\",\n ...input\n };\n}\n\nfunction inferProvider(remoteUrl: string): string {\n try {\n return parseRepositoryCloneUrl(remoteUrl).provider ?? \"other\";\n } catch {\n return \"other\";\n }\n}\n\nfunction parsePullRequestList(stdout: string): PullRequestMetadata | undefined {\n const parsed = JSON.parse(stdout || \"[]\") as Array<{ number?: unknown; url?: unknown }>;\n const first = parsed[0];\n if (typeof first?.number === \"number\" && typeof first.url === \"string\" && first.url) {\n return { number: first.number, url: first.url };\n }\n return undefined;\n}\n\nfunction extractPullRequestUrl(stdout: string): string | undefined {\n return stdout.split(/\\s+/g).find((value) => /^https:\\/\\/github\\.com\\/[^\\s]+\\/pull\\/\\d+$/i.test(value));\n}\n\nfunction pullRequestNumber(url: string): number | undefined {\n const match = /\\/pull\\/(\\d+)(?:$|[?#])/.exec(url);\n return match ? Number.parseInt(match[1]!, 10) : undefined;\n}\n\nfunction commitSubject(workItem: WorkItem): string {\n return truncate(`Amistio: ${workItem.title}`, 72);\n}\n\nfunction commitBody(input: CompleteImplementationHandoffInput): string {\n return [\n `Work item: ${input.workItem.workItemId}`,\n `Implementation scope: ${input.workItem.controllingAdrId ?? input.workItem.implementationScopeId ?? \"unspecified\"}`,\n \"\",\n \"Generated by Amistio local runner.\",\n \"Do not include secrets or source patches in Amistio SaaS metadata.\"\n ].join(\"\\n\");\n}\n\nfunction pullRequestTitle(workItem: WorkItem): string {\n return truncate(workItem.title, 120);\n}\n\nfunction pullRequestBody(input: { artifacts?: ImplementationHandoffArtifacts; baseBranch: string; headBranch: string; verificationSummary?: string; workItem: WorkItem }): string {\n return [\n `Amistio work item: ${input.workItem.workItemId}`,\n `Implementation scope: ${input.workItem.controllingAdrId ?? input.workItem.implementationScopeId ?? \"unspecified\"}`,\n `Base branch: ${input.baseBranch}`,\n `Head branch: ${input.headBranch}`,\n \"\",\n ...artifactSummaryLines(input.artifacts),\n \"\",\n input.verificationSummary ?? \"Verification summary was not reported by the local runner.\"\n ].join(\"\\n\");\n}\n\nfunction artifactSummaryLines(artifacts: ImplementationHandoffArtifacts | undefined): string[] {\n if (!artifacts || (!artifacts.included.length && !artifacts.skipped.length && !artifacts.blocked.length)) {\n return [\"Approved artifacts: none materialized for this handoff.\"];\n }\n const lines = [\n `Approved artifacts: ${artifacts.included.length} included, ${artifacts.skipped.length} already current, ${artifacts.blocked.length} blocked.`\n ];\n for (const artifact of artifacts.included.slice(0, 12)) {\n lines.push(`- ${artifact.repoPath}${artifact.title ? ` (${artifact.title})` : \"\"}`);\n }\n return lines;\n}\n\nfunction truncate(value: string, maxLength: number): string {\n return value.length <= maxLength ? value : value.slice(0, maxLength - 1).trimEnd();\n}\n\nasync function defaultCommandRunner(command: string, args: string[], options: { cwd: string }): Promise<CommandResult> {\n const { stdout, stderr } = await execFileAsync(command, args, { cwd: options.cwd, maxBuffer: 1024 * 1024 });\n return { stdout, stderr };\n}\n\nfunction safeErrorMessage(error: unknown): string {\n const scrub = (value: string) => redactLocalPaths(value.replace(/^Command failed:[^\\n]*(\\n)?/i, \"\").trim() || value);\n if (typeof error === \"object\" && error && \"stderr\" in error && typeof (error as { stderr?: unknown }).stderr === \"string\" && (error as { stderr: string }).stderr.trim()) {\n return truncate(scrub((error as { stderr: string }).stderr.trim()), 600);\n }\n if (error instanceof Error) {\n return truncate(scrub(error.message), 600);\n }\n return truncate(scrub(String(error)), 600);\n}\n\nfunction redactLocalPaths(value: string): string {\n return value\n .replace(/(^|[\\s'\"`])(\\/{1,2}(?:Users|home|private|tmp|var|Volumes)\\/[^\\s'\"`]+)/g, \"$1<local-path>\")\n .replace(/(^|[\\s'\"`])([A-Za-z]:\\\\[^\\s'\"`]+)/g, \"$1<local-path>\");\n}\n", "import { readFileSync } from \"node:fs\";\n\ninterface CliPackageJson {\n version?: unknown;\n}\n\nexport function readCliPackageVersion(): string {\n const packageJson = JSON.parse(readFileSync(new URL(\"../package.json\", import.meta.url), \"utf8\")) as CliPackageJson;\n if (typeof packageJson.version !== \"string\" || !packageJson.version.trim()) {\n throw new Error(\"@amistio/cli package version is missing.\");\n }\n return packageJson.version.trim();\n}\n\nexport const CLI_VERSION = readCliPackageVersion();"],
5
- "mappings": ";;;AACA,SAAS,cAAAA,aAAY,kBAAkB;AACvC,SAAS,aAAAC,mBAAiB;AAC1B,OAAOC,SAAQ;AACf,OAAOC,YAAU;AACjB,SAAS,eAAe;;;ACLxB,SAAS,SAAS;AAEX,IAAM,oBAAoB,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,KAAK,CAAC;AAE9D,IAAM,iBAAiB,EAAE,KAAK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B,WAAW,OAAO,IAAI,CAAC;AAAA,IACpE,GAAI,YAAY,SAAS,EAAE,kBAAkB,WAAW,OAAO,IAAI,CAAC;AAAA,IACpE,GAAI,YAAY,UAAU,EAAE,mBAAmB,WAAW,QAAQ,IAAI,CAAC;AAAA,EAC3E;AACJ;AAEA,SAAS,kBAA0B;AAC/B,SAAOJ,YAAW,QAAQ,EAAE,OAAO,GAAGI,IAAG,SAAS,CAAC,IAAIA,IAAG,SAAS,CAAC,IAAIA,IAAG,KAAK,CAAC,EAAE,EAAE,OAAO,KAAK,EAAE,MAAM,GAAG,EAAE;AAClH;AAEA,eAAe,MAAM,cAAsB;AACvC,QAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,YAAY,CAAC;AACpE;AAEA,QAAQ,WAAW,EAAE,MAAM,CAAC,UAAmB;AAC3C,UAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AACpE,UAAQ,WAAW;AACvB,CAAC;",
6
- "names": ["createHash", "writeFile", "os", "path", "z", "normalizeRepoPath", "mkdir", "path", "execFile", "mkdir", "readFile", "stat", "writeFile", "path", "promisify", "execFileAsync", "promisify", "execFile", "path", "mkdir", "writeFile", "readFile", "stat", "z", "path", "mkdir", "writeFile", "path", "mkdir", "path", "writeFile", "createHash", "mkdir", "readdir", "readFile", "writeFile", "os", "path", "z", "path", "os", "mkdir", "writeFile", "readdir", "readFile", "createHash", "readFile", "rm", "writeFile", "os", "path", "path", "os", "writeFile", "runner", "rm", "readFile", "spawn", "createHash", "mkdir", "readdir", "readFile", "writeFile", "os", "path", "spawn", "createHash", "mkdir", "readFile", "rm", "writeFile", "os", "path", "os", "path", "mkdir", "writeFile", "rm", "readFile", "result", "createHash", "spawn", "execFile", "createHash", "mkdir", "readdir", "readFile", "stat", "writeFile", "path", "promisify", "execFileAsync", "promisify", "execFile", "readFile", "mkdir", "path", "writeFile", "readFile", "path", "exists", "readdir", "normalizeRepoPath", "stat", "execFileAsync", "createHash", "mkdir", "readFile", "writeFile", "os", "path", "path", "tokens", "path", "createHash", "createHash", "os", "execFile", "createHash", "readdir", "readFile", "stat", "path", "promisify", "execFileAsync", "promisify", "execFile", "controlPlaneRoots", "path", "runGit", "stat", "readFile", "inferTitle", "normalizeRepoPath", "readdir", "normalizeRepoPath", "inferTitle", "controlPlaneRoots", "path", "createHash", "runGit", "execFileAsync", "spawn", "path", "execFile", "mkdir", "readdir", "stat", "path", "promisify", "execFileAsync", "errorMessage", "preparedLocalEnvironmentFileCount", "execFile", "path", "promisify", "execFileAsync", "promisify", "execFile", "gitOutput", "cleanup", "path", "writeFile", "path", "record", "runner", "errorMessage", "message", "skippedCount", "durationMs", "autopilotWorkMetadata", "documents", "messages", "toolSession", "createHash", "modelConfig", "capability", "modelResolution", "os"]
7
- }