@zaip-ai/cli 3.0.0 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -5
- package/dist/commands/init.d.ts.map +1 -1
- package/dist/commands/init.js +16 -6
- package/dist/commands/init.js.map +1 -1
- package/dist/services/adapters.d.ts +1 -1
- package/dist/services/adapters.js +1 -1
- package/dist/services/github-setup-status.d.ts +12 -0
- package/dist/services/github-setup-status.d.ts.map +1 -0
- package/dist/services/github-setup-status.js +84 -0
- package/dist/services/github-setup-status.js.map +1 -0
- package/dist/services/github-setup-status.test.d.ts +2 -0
- package/dist/services/github-setup-status.test.d.ts.map +1 -0
- package/dist/services/github-setup-status.test.js +57 -0
- package/dist/services/github-setup-status.test.js.map +1 -0
- package/dist/services/logger.d.ts +10 -1
- package/dist/services/logger.d.ts.map +1 -1
- package/dist/services/logger.js +23 -6
- package/dist/services/logger.js.map +1 -1
- package/dist/services/logger.test.js +33 -5
- package/dist/services/logger.test.js.map +1 -1
- package/dist/types.d.ts +3 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/templates/.agents/README-ENG.md +5 -1
- package/templates/.agents/README.md +5 -1
- package/templates/.agents/config/agents/discovery.json +1 -1
- package/templates/.agents/dashboard/.zaip-managed.json +65 -41
- package/templates/.agents/dashboard/apps/frontend/dist/assets/{DashboardHelpDialog-TnrL1ZyZ.js → DashboardHelpDialog-BzaUTZDx.js} +27 -12
- package/templates/.agents/dashboard/apps/frontend/dist/assets/{PricingSettingsDialog-DjQpBqGU.js → PricingSettingsDialog-21cCJik-.js} +1 -1
- package/templates/.agents/dashboard/apps/frontend/dist/assets/{TraceabilityWorkspace-BQZXUnQu.js → TraceabilityWorkspace-wqW52uCx.js} +1 -1
- package/templates/.agents/dashboard/apps/frontend/dist/assets/{dashboard-localization-Basaw1NR.js → dashboard-localization-BkAm8-h4.js} +5 -1
- package/templates/.agents/dashboard/apps/frontend/dist/assets/{index-BQe3zTvL.js → index-DqZKJS8y.js} +2 -2
- package/templates/.agents/dashboard/apps/frontend/dist/index.html +1 -1
- package/templates/.agents/dashboard/apps/frontend/package.json +1 -1
- package/templates/.agents/dashboard/modules/cost-monitor/package.json +1 -1
- package/templates/.agents/dashboard/modules/operations/package.json +1 -1
- package/templates/.agents/dashboard/modules/traceability/package.json +1 -1
- package/templates/.agents/dashboard/packages/branding/package.json +1 -1
- package/templates/.agents/dashboard/packages/contracts/package.json +1 -1
- package/templates/.agents/dashboard/packages/data-export/package.json +1 -1
- package/templates/.agents/dashboard/packages/local-runtime/dist/server.cjs +182 -160
- package/templates/.agents/dashboard/packages/local-runtime/dist/sqlite-read-model.cjs +174 -152
- package/templates/.agents/dashboard/packages/local-runtime/package.json +1 -1
- package/templates/.agents/dashboard/packages/local-runtime/server.mjs +182 -160
- package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-calendar.ts +17 -0
- package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-cold-parse.test.ts +78 -0
- package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-cost-group-projection.test.ts +94 -0
- package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-cost-group-projection.ts +5 -5
- package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-duration-lookup.test.ts +59 -0
- package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-entity-label-views.test.ts +72 -0
- package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-materialize-runs.ts +3 -4
- package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-query-entity-group.test.ts +171 -0
- package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-query-entity-group.ts +36 -16
- package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-read-model-canonical-parsing.ts +7 -0
- package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-read-model-canonical.ts +5 -15
- package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-read-model-keeps-orphan-telemetry-out-kanban-without.test.ts +1 -1
- package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-read-model-rebuild.ts +2 -0
- package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-read-model-schema.ts +3 -2
- package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-read-model.test.ts +1 -1
- package/templates/.agents/dashboard/packages/local-runtime/src/sqlite-schema-base-views.ts +22 -14
- package/templates/.agents/dashboard/packages/ui/package.json +1 -1
- package/templates/.agents/dashboard/tests/e2e/package.json +1 -1
- package/templates/.agents/design/.zaip-managed.json +3 -3
- package/templates/.agents/design/apps/catalog/package.json +1 -1
- package/templates/.agents/design/packages/local-runtime/package.json +1 -1
- package/templates/.agents/requirements/autonomous-assurance.md +1 -1
- package/templates/.agents/requirements/cloud-hostinger-autonomy.md +1 -1
- package/templates/.agents/requirements/comparative-audit.md +1 -1
- package/templates/.agents/requirements/context-engine.md +1 -1
- package/templates/.agents/requirements/cost-observability.md +1 -1
- package/templates/.agents/requirements/dashboard-launch.md +1 -1
- package/templates/.agents/requirements/data-export.md +1 -1
- package/templates/.agents/requirements/design-system.md +1 -1
- package/templates/.agents/requirements/execution-engine.md +1 -1
- package/templates/.agents/requirements/kanban-dashboard.md +1 -1
- package/templates/.agents/requirements/model-orchestration.md +1 -1
- package/templates/.agents/requirements/public-distribution.md +9 -2
- package/templates/.agents/requirements/software-architecture.md +1 -1
- package/templates/.agents/requirements/strategic-improvements.md +1 -1
- package/templates/.agents/requirements/work-lifecycle.md +1 -1
- package/templates/.agents/requirements/zaip-strategic-95.md +1 -1
- package/templates/.agents/runtime/VERSION +1 -1
- package/templates/.agents/runtime/bin/zaip.mjs +5 -5
- package/templates/.agents/runtime/checksums.sha256 +5 -5
- package/templates/.agents/runtime/manifest.json +1 -1
- package/templates/.agents/runtime/provenance.json +4 -4
- package/templates/.agents/runtime/sbom.cdx.json +1 -1
- package/templates/.agents/skills/zaip-skill-config/SKILL.md +12 -0
- package/templates/.agents/skills/zaip-skill-github-deploy/references/release-identity.md +17 -12
- package/templates/.agents/skills/zaip-skill-github-setup/SKILL.md +7 -1
- package/templates/.agents/skills/zaip-skill-setup/SKILL.md +12 -0
- package/templates/.agents/zaip-aios/README.md +4 -3
- package/templates/.agents/zaip-aios/VERSION +1 -1
- package/templates/.agents/zaip-aios/guides/20-instalacao-detalhada.md +22 -1
- package/templates/.agents/zaip-aios/guides/26-qualidade-e-release.md +20 -9
- package/templates/template-manifest.json +105 -81
|
@@ -371,7 +371,7 @@ A preencher.`}var timestamp9,taskSchema2,TaskRepository;var init_src5=__esm({"..
|
|
|
371
371
|
`);return writerId}catch(error51){if(!isNodeError9(error51)||error51.code!=="EEXIST")throw error51;const marker=JSON.parse(await filesystem.readText(path));if(typeof marker!=="object"||marker===null||!("writer_id"in marker)||typeof marker.writer_id!=="string"||!/^writer-[0-9a-f-]{36}$/.test(marker.writer_id)){throw new Error("Invalid local telemetry writer marker")}return marker.writer_id}})();workspaceWriterIds.set(filesystem.root,created);try{return await created}catch(error51){if(workspaceWriterIds.get(filesystem.root)===created)workspaceWriterIds.delete(filesystem.root);throw error51}}function isNodeError9(error51){return typeof error51==="object"&&error51!==null&&"code"in error51}function unique(values){return[...new Set(values)].sort()}function digest4(value){return createHash34("sha256").update(value).digest("hex")}async function delay5(milliseconds){await new Promise(resolveDelay=>setTimeout(resolveDelay,milliseconds))}var workspaceCompactionQueues,workspaceWriterIds,COMPACTION_LOCK_ROOT,COMPACTION_LOCK_WAIT_MS,COMPACTION_LOCK_TIMEOUT_MS;var init_codex_telemetry_compaction=__esm({"src/codex-telemetry-compaction.ts"(){"use strict";init_src();init_src2();init_src3();workspaceCompactionQueues=new Map;workspaceWriterIds=new Map;COMPACTION_LOCK_ROOT=".local/telemetry-compaction-locks";COMPACTION_LOCK_WAIT_MS=25;COMPACTION_LOCK_TIMEOUT_MS=12e4}});function isCodexTelemetryClient(client){return["codex","codex-desktop","codex-subagent"].includes(client)}function telemetrySourceThreadId(current,allRuns){const runsById=new Map(allRuns.map(fold=>[fold.run.run_id,fold]));let run=current.run;const visited=new Set;while(run.parent_run_id!==null&&!visited.has(run.run_id)){visited.add(run.run_id);const parent=runsById.get(run.parent_run_id);if(parent===void 0)break;run=parent.run}return run.client_thread_id??current.run.client_thread_id??null}function telemetrySource(current,allRuns){const rootThreadId=telemetrySourceThreadId(current,allRuns);if(current.run.client==="codex-subagent"){const identity=current.run.client_thread_id??null;const nativeThread=identity!==null&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(identity);return{agentPath:nativeThread?null:identity,parentThreadId:null,threadId:nativeThread?identity:null,turnId:current.run.client_turn_id??null}}return{agentPath:null,parentThreadId:null,threadId:rootThreadId,turnId:current.run.client_turn_id??null}}var init_codex_telemetry_source=__esm({"src/codex-telemetry-source.ts"(){"use strict"}});import{createHash as createHash35}from"node:crypto";async function recordUnavailableCodexTelemetryToSpool(current,filesystem,status,capturedAt=new Date().toISOString()){if(!isCodexTelemetryClient(current.run.client))return null;const correlation=codexTelemetryCorrelationFromRun(current.run);if(correlation===null)return null;return appendCodexTelemetrySpoolEvent(filesystem,{correlation,event_kind:"terminal",source:"unavailable",source_event_key:`run:${current.run.run_id}:terminal:unavailable`,source_occurred_at:null,captured_at:capturedAt,coverage:"unavailable",tokens:{input:null,cached_input:null,cache_write_input:null,output:null,reasoning:null,total:null,source:"unavailable"},provider:null,model:null,runtime:{reasoning_effort:null,service_tier:null},status,latency_ms:null,context_stats:null,discarded_counts:{prompt:0,response_text:0,reasoning:0,secrets:0}})}function sumObservedUsage(values){const observed=values.filter(value=>value!==null);const sum=component=>{let total=0;for(const usage of observed){const value=usage[component];if(value===null||value===void 0)return null;total+=value}return total};return{input:sum("input"),cached_input:sum("cached_input"),cache_write_input:sum("cache_write_input"),output:sum("output"),reasoning:sum("reasoning"),total:sum("total"),source:"provider_reported"}}function commonObservedValue(values){const observed=[...new Set(values.filter(value=>value!==null))];return observed.length===1?observed[0]??null:null}function latestSourceTimestamp(events){return events.map(event=>event.event.source_occurred_at).filter(value=>value!==null).sort().at(-1)??null}function modelCallId(sourceCallKey){return`MCALL-${digest5(sourceCallKey)}`}function providerInvocationId(sourceCallKey){return`INV-CODEX-${digest5(sourceCallKey)}`}function elapsedMilliseconds(startedAt,finishedAt){const started=Date.parse(startedAt??"");const finished=Date.parse(finishedAt??"");return Number.isFinite(started)&&Number.isFinite(finished)?Math.max(0,finished-started):null}function hasObservedUsage(current){return current.effective_usage_records.some(record3=>record3.tokens.source!=="unavailable")}function unavailableUsageEventId(current){return current.effective_usage_records.findLast(record3=>record3.tokens.source==="unavailable")?.event_id??null}function observedUsageDelta(cumulative,previous){const previousTotal=component=>{let total=0;for(const usage of previous){const value=usage[component];if(value===null||value===void 0)return null;total+=value}return total};const delta=component=>{const observed=cumulative[component];if(observed===null||observed===void 0)return null;const attributed=previousTotal(component);return attributed===null?null:Math.max(0,observed-attributed)};return{input:delta("input"),cached_input:delta("cached_input"),cache_write_input:delta("cache_write_input"),output:delta("output"),reasoning:delta("reasoning"),total:delta("total"),source:cumulative.source}}function latestPhase(current){const latest=current.records.findLast(record3=>"phase"in record3);return latest?.phase??"conversation"}function digest5(sourceCallKey){return createHash35("sha256").update(sourceCallKey).digest("hex").slice(0,32)}var init_codex_telemetry_runtime=__esm({"src/codex-telemetry-runtime.ts"(){"use strict";init_src3();init_codex_telemetry_source()}});function shouldAppendFallbackModelCall(records,sourceCallKey){const callId=modelCallId(sourceCallKey);return!records.some(record3=>record3.source_call_key===sourceCallKey||record3.call_id===callId)}async function collectAvailableNativeUsage(current,composition,filesystem,recordNative){return withPreparedCodexTelemetry(filesystem,async(snapshot,compact)=>{const events=snapshot.filter(event=>event.event.source==="codex_app_server"&&event.event.correlation.run_id===current.run.run_id);if(events.some(event=>["response_completed","usage_updated","error","turn_completed"].includes(event.event.stream_boundary??""))){const recorded=await recordNative(current,composition,events);await compact();return recorded}return null})}async function exactTelemetrySource(current,composition){const ancestors=[current];if(current.run.client!=="codex-subagent"){const visited=new Set([current.run.run_id]);let parentId=current.run.parent_run_id;while(parentId!==null&&!visited.has(parentId)){visited.add(parentId);let parent;try{parent=await composition.runs.read(parentId)}catch(error51){if(error51 instanceof Error&&error51.message.startsWith("Run V2 not found:"))break;throw error51}ancestors.push(parent);parentId=parent.run.parent_run_id}}return telemetrySource(current,ancestors)}function rootCorrelationCandidates(correlations,threadId){const roots2=correlations.filter(item=>item.client!=="codex-subagent");const exact=roots2.filter(item=>item.thread_id===threadId);return exact.length>0?exact:roots2.filter(item=>item.thread_id===null)}function parseCodexAppServerNotificationStream(content){const normalized=content.trim();if(normalized.length===0)return[];if(normalized.startsWith("[")){const parsed=JSON.parse(normalized);if(!Array.isArray(parsed))throw new Error("Codex app-server event stream must be an array");return parsed}return normalized.split(/\r?\n/).map(line=>line.trim()).filter(Boolean).map(line=>JSON.parse(line))}var init_codex_telemetry_preparation=__esm({"src/codex-telemetry-preparation.ts"(){"use strict";init_codex_telemetry_compaction();init_codex_telemetry_runtime();init_codex_telemetry_source()}});import{createHash as createHash36}from"node:crypto";async function ingestCodexAppServerNotifications(filesystem,notifications,capturedAt=new Date().toISOString()){const persisted=[];for(const notification of notifications){const event=await ingestCodexAppServerNotification(filesystem,notification,capturedAt);if(event!==null)persisted.push(event)}await compactPendingCodexTelemetry(filesystem);return persisted}async function ingestCodexAppServerNotification(filesystem,notification,capturedAt=new Date().toISOString()){const sanitized=sanitizeAppServerNotification(notification,capturedAt);if(sanitized===null)return null;const correlations=await listCodexTelemetryCorrelations(filesystem);const sameTurn=correlations.filter(item=>item.turn_id===sanitized.turnId);const candidates=sanitized.agentPath===null?rootCorrelationCandidates(sameTurn,sanitized.threadId):sameTurn.filter(item=>item.client==="codex-subagent"&&item.agent_path===sanitized.agentPath);if(candidates.length>1){throw new Error(`Ambiguous Codex app-server correlation for turn ${sanitized.turnId}`)}if(candidates[0]===void 0){await quarantineCodexAppServerNotification(filesystem,sanitized);return null}return appendCodexTelemetrySpoolEvent(filesystem,{correlation:candidates[0],...sanitized.event})}async function quarantineCodexAppServerNotification(filesystem,input){const digest6=hostDigest(input.event.source_event_key);const unsigned={schema_version:1,event_id:`QEVT-${digest6}`,thread_id:input.threadId,turn_id:input.turnId,agent_path:input.agentPath,event:input.event};const serialized=`${JSON.stringify({...unsigned,checksum_sha256:hostDigest(JSON.stringify(unsigned))})}
|
|
372
372
|
`;if(Buffer.byteLength(serialized,"utf8")>64*1024)throw new Error("Unmatched Codex telemetry envelope exceeds the 64 KiB sanitized limit");try{await filesystem.writeTextAtomicExclusive(`.local/codex-telemetry-spool/v1/unmatched/${digest6.slice(0,2)}/${digest6}.json`,serialized)}catch(error51){if(!(error51 instanceof Error&&"code"in error51&&error51.code==="EEXIST"))throw error51}}function sanitizeAppServerNotification(input,capturedAt){const notification=hostObject(input,"Codex app-server notification");const method=String(notification.method);if(!["item/completed","rawResponse/completed","thread/tokenUsage/updated","error","turn/completed"].includes(method))return null;const params=hostObject(notification.params,`${method} params`);const threadId=hostString(params.threadId,`${method} threadId`);const rawAgentPath=params.agentPath??params.agent_path;const agentPath=rawAgentPath===void 0?null:hostString(rawAgentPath,`${method} agentPath`);const occurredAt=hostTimestamp(notification.emittedAtMs);const wrap=(turnId2,event)=>({threadId,turnId:turnId2,agentPath,event:{source:"codex_app_server",source_occurred_at:occurredAt,captured_at:capturedAt,coverage:"complete",provider:null,model:null,runtime:{reasoning_effort:null,service_tier:null},latency_ms:null,context_stats:null,...event}});if(method==="item/completed"){const turnId2=hostString(params.turnId,`${method} turnId`);const item=hostObject(params.item,`${method} item`);return wrap(turnId2,{event_kind:"response",source_method:method,stream_boundary:"item_completed",source_event_key:hostSourceKey(`${threadId}:${turnId2}:item:${hostString(item.id,`${method} item id`)}`,"item"),source_occurred_at:hostTimestamp(params.completedAtMs)??occurredAt,tokens:null,status:null,discarded_counts:discardedItem(String(item.type??""),item)})}if(method==="rawResponse/completed"){const turnId2=hostString(params.turnId,`${method} turnId`);return wrap(turnId2,{event_kind:"response",source_method:method,stream_boundary:"response_completed",source_event_key:hostSourceKey(`${threadId}:${turnId2}:raw-response:${hostString(params.responseId,`${method} responseId`)}`,"response"),tokens:params.usage===null?null:hostTokens(params.usage,method),status:null,discarded_counts:{...emptyDiscarded(),response_text:Number(typeof params.output==="string")}})}if(method==="thread/tokenUsage/updated"){const turnId2=hostString(params.turnId,`${method} turnId`);const tokens2=hostTokens(hostObject(params.tokenUsage,`${method} tokenUsage`).total,method);const suffix=notification.emittedAtMs===void 0?hostDigest(JSON.stringify(tokens2)).slice(0,24):String(notification.emittedAtMs);return wrap(turnId2,{event_kind:"usage",source_method:method,stream_boundary:"usage_updated",source_event_key:hostSourceKey(`${threadId}:${turnId2}:token-usage:${suffix}`,"usage"),tokens:tokens2,status:null,discarded_counts:emptyDiscarded()})}if(method==="error"){const turnId2=hostString(params.turnId,`${method} turnId`);const error52=isHostObject(params.error)?params.error:{};const suffix=notification.emittedAtMs===void 0?hostDigest(JSON.stringify([params.willRetry===true,error52.codexErrorInfo??null])).slice(0,24):String(notification.emittedAtMs);return wrap(turnId2,{event_kind:"error",source_method:method,stream_boundary:"error",source_event_key:hostSourceKey(`${threadId}:${turnId2}:error:${suffix}`,"error"),tokens:null,status:params.willRetry===true?null:"failed",will_retry:params.willRetry===true,discarded_counts:{...emptyDiscarded(),secrets:Number(typeof error52.message==="string")+Number(typeof error52.additionalDetails==="string")}})}const turn=hostObject(params.turn,"turn/completed turn");const turnId=hostString(turn.id,"turn/completed turn id");if(!["completed","failed","interrupted"].includes(String(turn.status)))throw new Error(`turn/completed has non-terminal status: ${String(turn.status)}`);const discarded=(Array.isArray(turn.items)?turn.items.filter(isHostObject):[]).map(item=>discardedItem(String(item.type??""),item)).reduce(addDiscarded,emptyDiscarded());const error51=isHostObject(turn.error)?turn.error:{};return wrap(turnId,{event_kind:"terminal",source_method:"turn/completed",stream_boundary:"turn_completed",source_event_key:hostSourceKey(`${threadId}:${turnId}:terminal`,"terminal"),source_occurred_at:hostTimestamp(typeof turn.completedAt==="number"?turn.completedAt*1e3:turn.completedAt)??occurredAt,tokens:null,status:turn.status==="interrupted"?"cancelled":turn.status,latency_ms:Number.isSafeInteger(turn.durationMs)&&Number(turn.durationMs)>=0?Number(turn.durationMs):null,discarded_counts:{...discarded,secrets:discarded.secrets+Number(typeof error51.message==="string")+Number(typeof error51.additionalDetails==="string")}})}function hostObject(value,label){if(!isHostObject(value))throw new Error(`${label} must be an object`);return value}function hostString(value,label){if(typeof value!=="string"||value.length===0)throw new Error(`${label} must be a non-empty string`);return value}function hostCount(value,label){if(!Number.isSafeInteger(value)||Number(value)<0)throw new Error(`${label} must be a non-negative safe integer`);return Number(value)}function hostTokens(value,label){const usage=hostObject(value,`${label} usage`);const input=hostCount(usage.inputTokens,`${label} inputTokens`);const cacheWriteInput=usage.cacheWriteInputTokens===void 0?null:hostCount(usage.cacheWriteInputTokens,`${label} cacheWriteInputTokens`);if(cacheWriteInput!==null&&cacheWriteInput>input){throw new Error(`${label} cacheWriteInputTokens cannot exceed inputTokens`)}return{input,cached_input:hostCount(usage.cachedInputTokens,`${label} cachedInputTokens`),cache_write_input:cacheWriteInput,output:hostCount(usage.outputTokens,`${label} outputTokens`),reasoning:hostCount(usage.reasoningOutputTokens,`${label} reasoningOutputTokens`),total:hostCount(usage.totalTokens,`${label} totalTokens`),source:"provider_reported"}}var emptyDiscarded,addDiscarded,discardedItem,isHostObject,hostTimestamp,hostDigest,hostSourceKey;var init_codex_app_server_notifications=__esm({"src/codex-app-server-notifications.ts"(){"use strict";init_src3();init_codex_telemetry_compaction();init_codex_telemetry_preparation();emptyDiscarded=()=>({prompt:0,response_text:0,reasoning:0,secrets:0});addDiscarded=(left,right)=>({prompt:left.prompt+right.prompt,response_text:left.response_text+right.response_text,reasoning:left.reasoning+right.reasoning,secrets:left.secrets+right.secrets});discardedItem=(type,item)=>({prompt:Number(["userMessage","hookPrompt","function_call","custom_tool_call"].includes(type)),response_text:Number(["agentMessage","plan","message","agent_message"].includes(type)),reasoning:Number(type==="reasoning"),secrets:Number(typeof item.encrypted_content==="string")+Number(item.internal_chat_message_metadata_passthrough!==void 0)});isHostObject=value=>typeof value==="object"&&value!==null&&!Array.isArray(value);hostTimestamp=value=>typeof value==="number"&&Number.isFinite(value)&&value>=0?new Date(value).toISOString():null;hostDigest=value=>createHash36("sha256").update(value).digest("hex");hostSourceKey=(value,prefix)=>value.length<=500?value:`${prefix}:${hostDigest(value)}`}});function aggregateEstimatedCallCosts(estimates,fxRate){const sum=values=>{const known2=values.filter(value=>value!==null);if(known2.length!==values.length)return null;return Math.round(known2.reduce((total,value)=>total+value,0)*1e6)/1e6};const usd=sum(estimates.map(estimate=>estimate.estimated_usd));return{usd,brl:usd===null||fxRate===null?null:Math.round(usd*fxRate.rate*1e6)/1e6,fx_rate:fxRate?.rate??null}}var init_codex_telemetry_call_costs=__esm({"src/codex-telemetry-call-costs.ts"(){"use strict"}});function fallbackCallIdentity(sourceCallKey){return[sourceCallKey,modelCallId(sourceCallKey)]}async function recordCodexTelemetryIfAvailable(current,composition,filesystem,sourceOverride=null,appServerNotifications=[],fallbackSegmentFinder=findLatestCodexSegment){if(!isCodexTelemetryClient(current.run.client)||current.run.client_thread_id===null&¤t.run.client_turn_id===null){return current}const transcriptPath=validatedTranscriptEnvironmentPath();const preparation=await composition.runs.withUsageAttributionLock(async()=>{const fresh=await composition.runs.read(current.run.run_id);if(appServerNotifications.length>0){await ingestCodexAppServerNotifications(filesystem,appServerNotifications)}const observed=await collectAvailableNativeUsage(fresh,composition,filesystem,recordNativeCodexUsage);if(observed!==null)return{kind:"done",fold:observed};if(sourceOverride===null&&fresh.run.client_turn_id===null){return{kind:"done",fold:fresh}}const source=sourceOverride??await exactTelemetrySource(fresh,composition);if(source.turnId===null)return{kind:"done",fold:fresh};return{kind:"fallback",fold:fresh,source}});if(preparation.kind==="done")return preparation.fold;const candidate=await fallbackSegmentFinder(filesystem.root,new Set,{startedAfter:preparation.fold.run.occurred_at,...preparation.source,...transcriptPath===null?{}:{transcriptPath,requireTaskComplete:true}});return composition.runs.withUsageAttributionLock(async()=>{const freshCurrent=await composition.runs.read(current.run.run_id);const observed=await collectAvailableNativeUsage(freshCurrent,composition,filesystem,recordNativeCodexUsage);if(observed!==null)return observed;const source=sourceOverride??await exactTelemetrySource(freshCurrent,composition);const exactTurn=source.turnId;const timestamp12=Date.parse(candidate?.finishedAt??candidate?.loops.at(-1)?.timestamp??"");if(candidate===null||!Number.isFinite(timestamp12)||exactTurn===null||candidate.turnId!==exactTurn||JSON.stringify(source)!==JSON.stringify(preparation.source))return freshCurrent;const postTerminalPhase=freshCurrent.finished?.phase??null;const postTerminal=postTerminalPhase!==null;const supersededUnavailableUsageId=unavailableUsageEventId(freshCurrent);if(postTerminal&&supersededUnavailableUsageId===null)return freshCurrent;const allRuns=await composition.runs.list();const candidateLoops=Array.from(new Map(candidate.loops.map(loop=>[`${candidate.segmentKey}:loop:${loop.cycleIndex}`,loop])).values());const newCandidateLoops=candidateLoops.filter(loop=>shouldAppendFallbackModelCall(freshCurrent.model_call_records,`${candidate.segmentKey}:loop:${loop.cycleIndex}`));const existingOwner=allRuns.find(fold=>fold.run.run_id!==freshCurrent.run.run_id&&fold.effective_usage_records.some(record3=>record3.source_segment_key===candidate.segmentKey||record3.source_segment_key?.startsWith(`${candidate.segmentKey}@`)===true));if(existingOwner!==void 0)return freshCurrent;const model=candidate.model??freshCurrent.run.model;const provider=inferProvider(model,freshCurrent.run.provider??freshCurrent.run.client,freshCurrent.run.agent);const correlation=codexTelemetryCorrelationFromRun(freshCurrent.run);if(correlation===null)return freshCurrent;const capturedAt=new Date().toISOString();const pricing=new PricingRepository(filesystem);const catalog=await pricing.readCatalog();const fxRate=await pricing.readLatestFxRate();const spooledLoops=[];for(const loop of candidateLoops){if(!shouldAppendFallbackModelCall(freshCurrent.model_call_records,`${candidate.segmentKey}:loop:${loop.cycleIndex}`))continue;const loopModel=loop.model??model;const loopProvider=inferProvider(loopModel,freshCurrent.run.provider??freshCurrent.run.client,freshCurrent.run.agent);const historical_cost=estimateUsageCost({provider:loopProvider,model:loopModel,usage:loop.usage,catalog,fxRate,serviceTier:candidate.serviceTier??null});spooledLoops.push(await appendCodexTelemetrySpoolEvent(filesystem,{correlation,event_kind:"usage",source:"codex_session_fallback",source_event_key:`${candidate.segmentKey}:loop:${loop.cycleIndex}`,source_occurred_at:loop.timestamp,captured_at:capturedAt,coverage:"partial",tokens:loop.usage,provider:loopProvider,model:loopModel,runtime:{reasoning_effort:candidate.reasoningEffort??null,service_tier:candidate.serviceTier??null},status:null,latency_ms:null,historical_cost,context_stats:null,discarded_counts:{prompt:0,response_text:0,reasoning:0,secrets:0}}))}if(candidate.finishedAt!==null){await appendCodexTelemetrySpoolEvent(filesystem,{correlation,event_kind:"terminal",source:"codex_session_fallback",source_event_key:`${candidate.segmentKey}:terminal`,source_occurred_at:candidate.finishedAt,captured_at:capturedAt,coverage:"partial",tokens:null,provider,model,runtime:{reasoning_effort:candidate.reasoningEffort??null,service_tier:candidate.serviceTier??null},status:"completed",latency_ms:elapsedMilliseconds(candidate.startedAt,candidate.finishedAt),context_stats:null,discarded_counts:{prompt:0,response_text:0,reasoning:0,secrets:0}})}const cumulative=aggregateSegmentUsage({...candidate,loops:candidateLoops});const previous=allRuns.filter(fold=>fold.run.run_id===freshCurrent.run.run_id||exactTurn!==null&&fold.run.client_turn_id===exactTurn).flatMap(fold=>fold.effective_usage_records).filter(record3=>record3.source_segment_key===candidate.segmentKey||record3.source_segment_key?.startsWith(`${candidate.segmentKey}@`)===true);const usageLoops=fallbackUsageLoops(candidate,candidateLoops,previous.map(record3=>record3.tokens));if(candidate.finishedAt!==null&&previous.some(record3=>record3.source_segment_key===candidate.segmentKey))return freshCurrent;const tokens2=observedUsageDelta(cumulative,previous.map(record3=>record3.tokens));const usageSourceSegmentKey=candidate.finishedAt===null?`${candidate.segmentKey}@active:${hostDigest(JSON.stringify(cumulative))}`:candidate.segmentKey;if(tokens2.input===0&&tokens2.cached_input===0&&tokens2.cache_write_input===0&&tokens2.output===0&&tokens2.reasoning===0&&tokens2.total===0){return freshCurrent}if(candidate.finishedAt===null&&usageLoops.length===0)return freshCurrent;const estimated=aggregateEstimatedCallCosts(usageLoops.map(loop=>{const loopModel=loop.model??model;return estimateUsageCost({provider:inferProvider(loopModel,freshCurrent.run.provider??freshCurrent.run.client,freshCurrent.run.agent),model:loopModel,usage:loop.usage,catalog,fxRate,serviceTier:candidate.serviceTier??null})}),fxRate);const agentInvocationId=freshCurrent.run.agent_invocation_id??`AINV-${freshCurrent.run.run_id.slice("RUN-".length)}`;let sequence=freshCurrent.records.length+1;const fallbackCallIdentities=new Set(freshCurrent.model_call_records.flatMap(record3=>[record3.source_call_key,record3.call_id].filter(value=>typeof value==="string")));for(const spooled of spooledLoops){const loop=spooled.event;if(loop.tokens===null)continue;const loopModel=loop.model??freshCurrent.run.model;const loopProvider=inferProvider(loopModel,loop.provider??freshCurrent.run.provider??freshCurrent.run.client,freshCurrent.run.agent);const loopEstimated=estimateUsageCost({provider:loopProvider,model:loopModel,usage:loop.tokens,catalog,fxRate,serviceTier:candidate.serviceTier??null});const sourceCallKey=loop.source_event_key;const identities=fallbackCallIdentity(sourceCallKey);if(postTerminal||!shouldAppendFallbackModelCall(freshCurrent.model_call_records,sourceCallKey)||identities.some(identity=>fallbackCallIdentities.has(identity))){continue}await composition.runs.appendRecord(modelCallObservedV3Schema.parse({schema_version:2,event_id:`${freshCurrent.run.run_id}:${String(sequence).padStart(6,"0")}`,run_id:freshCurrent.run.run_id,sequence:sequence++,occurred_at:new Date().toISOString(),type:"model.call.observed",call_id:modelCallId(sourceCallKey),agent_invocation_id:agentInvocationId,coverage:"partial",tokens:loop.tokens,cost:{usd:loopEstimated.estimated_usd,brl:loopEstimated.estimated_brl,fx_rate:loopEstimated.fx_rate},provider:loopProvider,model:loopModel,source_call_key:sourceCallKey,...loop.source_occurred_at===null?{}:{source_occurred_at:loop.source_occurred_at},runtime:loop.runtime}));for(const identity of identities)fallbackCallIdentities.add(identity)}const usage=usageRecordedV2Schema.parse({schema_version:2,event_id:`${freshCurrent.run.run_id}:${String(sequence).padStart(6,"0")}`,run_id:freshCurrent.run.run_id,sequence,occurred_at:new Date().toISOString(),type:"usage.recorded",phase:postTerminal?postTerminalPhase:latestPhase(freshCurrent),activity_kind:postTerminal?"retrospective_local_remeasurement":"implementation",classification_source:"current_context",tokens:tokens2,cost:{usd:estimated.usd,brl:estimated.brl,fx_rate:estimated.fx_rate},provider,model,source_segment_key:usageSourceSegmentKey,runtime:{reasoning_effort:candidate.reasoningEffort??null,service_tier:candidate.serviceTier??null},supersedes_event_id:supersededUnavailableUsageId,...postTerminal?{retrospective_correction:true}:{},source_occurred_at:candidate.finishedAt??candidate.startedAt??void 0,source_started_at:candidate.startedAt??void 0,source_finished_at:candidate.finishedAt??void 0});await composition.runs.appendRecord(usage);await compactPendingCodexTelemetry(filesystem);return composition.runs.read(freshCurrent.run.run_id)})}function fallbackUsageLoops(candidate,loops,previous){if(previous.length===0)return loops;const attributed=sumObservedUsage(previous);for(let index=0;index<=loops.length;index+=1){if(sameUsage(aggregateSegmentUsage({...candidate,loops:loops.slice(0,index)}),attributed))return loops.slice(index)}return[]}function sameUsage(left,right){return left.input===right.input&&left.cached_input===right.cached_input&&left.cache_write_input===right.cache_write_input&&left.output===right.output&&left.reasoning===right.reasoning&&left.total===right.total}function validatedTranscriptEnvironmentPath(){const value=process.env.CODEX_TRANSCRIPT_PATH;if(typeof value!=="string")return null;const normalized=value.trim();return normalized.length>0&&normalized.length<=4096?normalized:null}async function recordNativeCodexUsage(current,composition,events){const exactCalls=events.filter(event=>event.event.stream_boundary==="response_completed"&&event.event.tokens!==null);const latestCumulative=events.findLast(event=>event.event.stream_boundary==="usage_updated"&&event.event.tokens!==null);const terminal=events.findLast(event=>event.event.stream_boundary==="turn_completed"||event.event.stream_boundary==="error"&&event.event.will_retry!==true);const usageEvents=exactCalls.length>0?exactCalls:latestCumulative?[latestCumulative]:[];if(usageEvents.length===0&&terminal===void 0)return current;let fresh=current;let sequence=current.records.length+1;const agentInvocationId=current.run.agent_invocation_id??`AINV-${current.run.run_id.slice("RUN-".length)}`;for(const call of exactCalls){const event=call.event;if(event.tokens===null)continue;const coverage2=terminal===void 0?"partial":"complete";const existing=fresh.model_call_records.find(record3=>record3.source_call_key===event.source_event_key);if(existing===void 0||existing.coverage==="partial"&&coverage2==="complete"){await composition.runs.appendRecord(modelCallObservedV3Schema.parse({schema_version:2,event_id:`${current.run.run_id}:${String(sequence).padStart(6,"0")}`,run_id:current.run.run_id,sequence:sequence++,occurred_at:event.captured_at,type:"model.call.observed",call_id:modelCallId(event.source_event_key),agent_invocation_id:agentInvocationId,coverage:coverage2,tokens:event.tokens,cost:{usd:null,brl:null},provider:event.provider,model:event.model,source_call_key:event.source_event_key,...event.source_occurred_at===null?{}:{source_occurred_at:event.source_occurred_at},runtime:event.runtime}));fresh=await composition.runs.read(current.run.run_id)}}const sourceSegmentKey=`codex-app-server:${current.run.run_id}`;if(usageEvents.length>0&&!fresh.effective_usage_records.some(record3=>record3.source_segment_key===sourceSegmentKey)){const tokens2=sumObservedUsage(usageEvents.map(event=>event.event.tokens));await composition.runs.appendRecord(usageRecordedV2Schema.parse({schema_version:2,event_id:`${current.run.run_id}:${String(sequence).padStart(6,"0")}`,run_id:current.run.run_id,sequence:sequence++,occurred_at:new Date().toISOString(),type:"usage.recorded",phase:latestPhase(current),activity_kind:"implementation",classification_source:"current_context",tokens:tokens2,cost:{usd:null,brl:null},provider:commonObservedValue(usageEvents.map(event=>event.event.provider)),model:commonObservedValue(usageEvents.map(event=>event.event.model)),source_segment_key:sourceSegmentKey,runtime:{reasoning_effort:commonObservedValue(usageEvents.map(event=>event.event.runtime.reasoning_effort)),service_tier:commonObservedValue(usageEvents.map(event=>event.event.runtime.service_tier))},supersedes_event_id:unavailableUsageEventId(current),...latestSourceTimestamp(usageEvents)===null?{}:{source_occurred_at:latestSourceTimestamp(usageEvents)}}));fresh=await composition.runs.read(current.run.run_id)}if(terminal===void 0||terminal.event.status===null)return fresh;const callKeys=exactCalls.length>0?exactCalls.map(call=>call.event.source_event_key):[terminal.event.source_event_key];for(const callKey of callKeys){const invocationId2=providerInvocationId(callKey);if(!fresh.model_selection_records.some(record3=>record3.invocation_id===invocationId2)){await composition.runs.appendRecord(modelSelectionRecordedV2Schema.parse({schema_version:2,event_id:`${current.run.run_id}:${String(sequence).padStart(6,"0")}`,run_id:current.run.run_id,sequence:sequence++,occurred_at:terminal.event.captured_at,type:"model.selection.recorded",invocation_id:invocationId2,requested:{model:current.run.model,reasoning_effort:current.run.reasoning_effort??null,velocity:"standard"},selection:{source:"execution-override",policy_version:1,reasons:["host-run-header"]}}));fresh=await composition.runs.read(current.run.run_id)}if(!fresh.provider_invocation_records.some(record3=>record3.invocation_id===invocationId2)){await composition.runs.appendRecord(providerInvocationFinishedV2Schema.parse({schema_version:2,event_id:`${current.run.run_id}:${String(sequence).padStart(6,"0")}`,run_id:current.run.run_id,sequence:sequence++,occurred_at:terminal.event.captured_at,type:"provider.invocation.finished",invocation_id:invocationId2,status:terminal.event.status,effective:{provider:terminal.event.provider,model:terminal.event.model,reasoning_effort:terminal.event.runtime.reasoning_effort,service_tier:terminal.event.runtime.service_tier},latency_ms:terminal.event.latency_ms}));fresh=await composition.runs.read(current.run.run_id)}}return fresh}var init_record_codex_telemetry=__esm({"src/record-codex-telemetry.ts"(){"use strict";init_src2();init_src3();init_codex_app_server_notifications();init_codex_telemetry_call_costs();init_codex_telemetry_compaction();init_codex_app_server_notifications();init_codex_telemetry_preparation();init_codex_telemetry_runtime();init_codex_telemetry_source();init_codex_telemetry_preparation();init_codex_telemetry_runtime();init_codex_telemetry_source()}});async function openThreadIntakes(composition,client,clientThreadId,currentTurnId){if(clientThreadId===null)return[];const candidates=await composition.runs.list();return candidates.filter(fold=>fold.finished===null&&fold.run.client===client&&fold.run.client_thread_id===clientThreadId&&fold.run.parent_run_id===null&&fold.run.intake!=null&&!runV2RequiresFinalizer(fold.run)&&descendantRuns(fold.run.run_id,candidates).length===0&&fold.run.client_turn_id!==currentTurnId)}async function finishOpenThreadIntakes(openIntakes,composition,filesystem,parsed,lifecycle){const settled=[];for(const intake2 of openIntakes){const candidateRuns=await composition.runs.list();if(descendantRuns(intake2.run.run_id,candidateRuns).length>0||activeDescendantRuns(intake2.run.run_id,candidateRuns).length>0){continue}let current=intake2;current=await recordCodexTelemetryIfAvailable(current,composition,filesystem,null,await codexAppServerNotifications(parsed,filesystem));if(current.effective_usage_records.length===0){await recordUnavailableCodexTelemetryToSpool(current,filesystem,"completed");await composition.runs.appendRecord(unavailableUsageRecord(current,parsed,current.records.length+1));current=await composition.runs.read(current.run.run_id)}await composition.runs.appendRecord(runFinishedV2Schema.parse({schema_version:2,event_id:runV2EventId(current.run.run_id,current.records.length+1),run_id:current.run.run_id,sequence:current.records.length+1,occurred_at:new Date().toISOString(),type:"run.finished",phase:latestRunV2Phase(current.records),status:"completed"}));const run=await composition.runs.read(current.run.run_id);settled.push({run,reconciliation:await reconcileFinishedRunLifecycle(run,composition,lifecycle,{candidateRuns})})}return settled}function settledIntakesForView(settled,view){if(view==="full")return settled;return settled.map(({run,reconciliation})=>({run_id:run.run.run_id,status:run.status,phase:latestRunV2Phase(run.records),execution_id:run.run.execution_id,task_id:run.run.task_id,change_id:run.run.change_id,record_count:run.records.length,usage_record_count:run.effective_usage_records.length,model_call_count:run.model_call_records.length,reconciliation:{status:reconciliation.status,outcome:reconciliation.outcome,task_count:reconciliation.tasks.length,change_count:reconciliation.changes.length,execution_count:reconciliation.executions.length,spec_count:reconciliation.specs.length,prd_count:reconciliation.prds.length}}))}async function codexAppServerNotifications(parsed,filesystem){const path=parsed.options["codex-app-server-events"];return path===void 0?[]:parseCodexAppServerNotificationStream(await filesystem.readText(path))}function runMatchesTarget(fold,target){return target.taskId!==void 0&&fold.run.task_id===target.taskId||target.specId!==void 0&&fold.run.spec_id===target.specId||target.prdId!==void 0&&fold.run.prd_id===target.prdId}async function recordContextPackUsage(runId,initialPackTokens,composition){const current=await composition.runs.read(runId);if(current.finished!==null)throw new UsageError(`Run V2 is already finished: ${runId}`);const sequence=current.records.length+1;await composition.runs.appendRecord(usageRecordedV2Schema.parse({schema_version:2,event_id:runV2EventId(runId,sequence),run_id:runId,sequence,occurred_at:new Date().toISOString(),type:"usage.recorded",phase:latestRunV2Phase(current.records),activity_kind:"context_build",classification_source:"current_context",tokens:{input:null,cached_input:null,output:null,reasoning:null,total:null,source:"unavailable"},cost:{usd:null,brl:null},provider:current.run.provider,model:current.run.model,source_segment_key:`context-pack:${runId}:${sequence}`,supersedes_event_id:null,source_occurred_at:new Date().toISOString(),context_stats:{initial_pack_tokens:initialPackTokens,tool_output_tokens:null,files_opened:null,snippets_opened:null}}))}function unavailableUsageRecord(current,parsed,sequence){const occurredAt=new Date().toISOString();return usageRecordedV2Schema.parse({schema_version:2,event_id:runV2EventId(current.run.run_id,sequence),run_id:current.run.run_id,sequence,occurred_at:occurredAt,type:"usage.recorded",phase:latestRunV2Phase(current.records),activity_kind:"run_finalize",classification_source:"current_context",tokens:{input:null,cached_input:null,output:null,reasoning:null,total:null,source:"unavailable"},cost:{usd:null,brl:null},provider:current.run.provider,model:current.run.model,source_segment_key:null,supersedes_event_id:null,...runUsageMetadataOptions(parsed.options,occurredAt)})}function latestRunV2Phase(records){const latest=records.findLast(record3=>"phase"in record3);return latest?.phase??"conversation"}function runV2EventId(runId,sequence){return`${runId}:${String(sequence).padStart(6,"0")}`}var init_conversation_intake_settlement=__esm({"src/conversation-intake-settlement.ts"(){"use strict";init_src3();init_cli_arguments();init_record_codex_telemetry();init_run_hierarchy();init_run_lifecycle_reconciliation()}});import{execFile as execFileCallback}from"node:child_process";import{promisify as promisify7}from"node:util";async function runDeveloperIdentityCommand(action,parsed,filesystem){if(action==="identity")action=parsed.positionals[2];if(action==="show")return{identity:await readDeveloperIdentityCache(filesystem)};if(action==="set")action="bootstrap";if(action!=="bootstrap")throw new UsageError("developer identity requires show or bootstrap");return{identity:await resolveDeveloperIdentityForRoot(filesystem,{force:true})}}async function resolveDeveloperIdentityForRoot(filesystem,options={}){const now=options.now??new Date;const cached2=await readDeveloperIdentityCache(filesystem);if(cached2!==null&&!options.force&&!developerIdentityNeedsRevalidation(cached2,now)){return cached2}try{const account=await(options.lookup??authenticatedGithubAccount)();return writeDeveloperIdentityCache(filesystem,verifiedDeveloperIdentity(account,now))}catch(error51){if(cached2!==null)return cachedFallbackDeveloperIdentity(cached2);throw new UsageError(`GitHub bootstrap failed; authenticate with gh and retry (${error51 instanceof Error?error51.message:String(error51)})`)}}async function authenticatedGithubAccount(){try{const{stdout}=await execFile7("gh",["api","user"],{encoding:"utf8"});const parsed=JSON.parse(stdout);if(typeof parsed.id!=="number"||!Number.isSafeInteger(parsed.id)||typeof parsed.login!=="string"||parsed.login.length===0)throw new Error("GitHub user response lacks id/login");return{id:String(parsed.id),login:parsed.login}}catch(error51){throw new Error(`GitHub account lookup failed (${error51 instanceof Error?error51.message:String(error51)})`)}}var execFile7;var init_developer_identity_command=__esm({"src/developer-identity-command.ts"(){"use strict";init_src3();init_cli_arguments();execFile7=promisify7(execFileCallback)}});import{execFile as execFile8}from"node:child_process";import{promisify as promisify8}from"node:util";async function assertGitDeliveryReady(root){const git5=async(...args)=>(await exec2("git",args,{cwd:root,windowsHide:true,encoding:"utf8",timeout:1e4})).stdout.trim();await git5("--version").catch(()=>{throw new Error("git-unavailable: Install Git before starting delivery.")});const inside=await git5("rev-parse","--is-inside-work-tree").catch(()=>"");if(inside!=="true")throw new Error("git-repository-required: Initialize or open the selected Git repository before starting delivery.");const head=await git5("rev-parse","--verify","HEAD").catch(()=>"");if(!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(head))throw new Error("git-head-required: Create the initial repository commit before starting delivery.");await git5("var","GIT_AUTHOR_IDENT").catch(()=>{throw new Error("git-identity-required: Configure your Git commit name and email before starting delivery.")})}var exec2;var init_git_delivery_preflight=__esm({"src/git-delivery-preflight.ts"(){"use strict";exec2=promisify8(execFile8)}});function createTaskFirstPreparedPlan(input){const{task}=input;return createPreparedPlanV2({revision:1,source:{type:"task",task_id:task.id},execution_id:input.executionId,prepared_at:input.preparedAt,policy:input.policy,blueprints:{changes:[{key:"task-first-change",id:task.change_id,title:task.title,short_name:task.short_name,risk:task.risk,source:{type:"task",task_id:task.id},requirement_ids:task.requirement_ids,acceptance_ids:task.acceptance_ids,requirement_impact:taskFirstRequirementImpact(input)}],tasks:[{key:"task-first",id:task.id,change_id:task.change_id,title:task.title,short_name:task.short_name,objective:task.objective,risk:task.risk,priority:task.priority,owner:task.owner,requirement_ids:task.requirement_ids,acceptance_ids:task.acceptance_ids,write_scopes:task.write_scopes}]},dag:{nodes:[{task_id:task.id,depends_on:task.depends_on}]}})}async function runPlanV2Command(action,parsed,filesystem,layout){if(action==="build"){requireOptions(parsed.options,["draft"]);const input=JSON.parse(await filesystem.readText(parsed.options.draft));const plan=createPreparedPlanV2(input);await assertPreparedPlanReferences(filesystem,plan);const outputPath=parsed.options.output;if(outputPath!==void 0){await filesystem.writeTextAtomic(outputPath,`${JSON.stringify(plan,null,2)}
|
|
373
373
|
`);return{valid:true,plan:preparedPlanSummary(plan),artifact_path:outputPath}}return plan}if(action==="validate"){const plan=await readPreparedPlan(filesystem,parsed);await assertPreparedPlanReferences(filesystem,plan);return{valid:true,plan:preparedPlanSummary(plan)}}if(action==="normalize"){if(layout===void 0)throw new UsageError("plan normalize requires a modern workspace");const scopes=["task","spec","prd"].filter(scope2=>parsed.options[scope2]!==void 0);if(scopes.length!==1){throw new UsageError("plan normalize requires exactly one of --task, --spec, or --prd")}const scope=scopes[0];const id=parsed.options[scope];if(scope==="task"){const repository3=new TaskV2Repository(filesystem,layout);const current2=(await repository3.read(id)).task;if(current2.plan_ref!==void 0)return{plan_ref:current2.plan_ref};if(current2.prepared_plan===void 0)throw new UsageError(`Task has no plan: ${id}`);const task=await repository3.normalizePreparedPlan(id,current2.prepared_plan);return{plan_ref:task.plan_ref}}if(scope==="spec"){const repository3=new DeliverySpecV2Repository(filesystem,layout);const current2=(await repository3.read(id)).spec;if(current2.plan_ref!==null)return{plan_ref:current2.plan_ref};if(current2.prepared_plan===null)throw new UsageError(`SPEC has no plan: ${id}`);const spec=await repository3.normalizePreparedPlan(id,current2.prepared_plan);return{plan_ref:spec.plan_ref}}const repository2=new PrdV2Repository(filesystem,layout);const current=(await repository2.read(id)).prd;if(current.plan_ref!==null)return{plan_ref:current.plan_ref};if(current.prepared_plan===null)throw new UsageError(`PRD has no plan: ${id}`);const prd=await repository2.normalizePreparedPlan(id,current.prepared_plan);return{plan_ref:prd.plan_ref}}throw new UsageError(`Unknown V2 Plan action: ${action??""}`)}async function readPreparedPlan(filesystem,parsed){requireOptions(parsed.options,["plan"]);return preparedPlanV2Schema.parse(JSON.parse(await filesystem.readText(parsed.options.plan)))}async function assertPreparedPlanReferences(filesystem,plan){const paths=await filesystem.listFiles(".agents/requirements",".md");if(paths.length===0){throw new UsageError("PreparedPlan requires a non-empty .agents/requirements catalog")}const catalog=buildRequirementReferenceCatalog(await Promise.all(paths.map(path=>filesystem.readText(path))));const requirementIds=[...(plan.blueprints.specs??[]).flatMap(spec=>spec.requirement_ids),...plan.blueprints.changes.flatMap(change=>[...change.requirement_ids,...change.requirement_impact.type==="update"?change.requirement_impact.requirement_ids:[]]),...plan.blueprints.tasks.flatMap(task=>task.requirement_ids)];const acceptanceIds=[...(plan.blueprints.specs??[]).flatMap(spec=>spec.acceptance_ids),...plan.blueprints.changes.flatMap(change=>change.acceptance_ids),...plan.blueprints.tasks.flatMap(task=>task.acceptance_ids)];const findings=validateRequirementReferences(catalog,requirementIds,acceptanceIds);if(findings.length>0){throw new UsageError(`PreparedPlan contains unresolved governance references: ${findings.map(finding3=>finding3.id).join(", ")}`)}}async function preparedTaskPlan(tasks,materializer,id){const{task}=await tasks.read(id);if(task.status!=="planned")throw new UsageError(`Task is not prepared: ${id}`);if(task.prepared_plan!==void 0)return task.prepared_plan;if(task.plan_ref===void 0)throw new UsageError(`Task is not prepared: ${id}`);const plan=await materializer.readPreparedPlan(task.plan_ref.execution_id);if(plan.hash!==task.plan_ref.hash||plan.revision!==task.plan_ref.revision||plan.execution_id!==task.plan_ref.execution_id||plan.source.type!=="task"||plan.source.task_id!==task.id){throw new UsageError(`Task plan reference cannot be resolved canonically: ${id}`)}return plan}function taskFirstRequirementImpact(input){if(input.requirementImpact?.type==="update"){return{type:"update",requirement_ids:[...input.requirementImpact.requirement_ids]}}return{type:"none",reason:input.requirementImpact?.reason??input.requirementImpactReason??"Implements existing Requirements."}}function preparedPlanSummary(plan){return{schema_version:plan.schema_version,revision:plan.revision,source:plan.source,execution_id:plan.execution_id,prepared_at:plan.prepared_at,hash:plan.hash,change_count:plan.blueprints.changes.length,task_count:plan.blueprints.tasks.length,topological_order:plan.dag.topological_order}}var init_prepared_plan_v22=__esm({"src/prepared-plan-v2.ts"(){"use strict";init_src();init_src4();init_src5();init_cli_arguments()}});async function resolveRunClientInvocation(filesystem,client,options={}){if(!new Set(["codex","codex-desktop"]).has(client)){return{clientThreadId:null,clientTurnId:null,userMessage:null,observedModel:null,observedReasoningEffort:null,observedServiceTier:null}}const threadId=normalizedId(options.threadId??process.env.CODEX_THREAD_ID);const turnId=normalizedId(options.turnId??process.env.CODEX_TURN_ID);const transcriptPath=transcriptPathFromEnvironment();const active=await findActiveCodexInvocation(filesystem.root,{threadId,...transcriptPath===null?{}:{transcriptPath},...options.sessionsRoot===void 0?{}:{sessionsRoot:options.sessionsRoot},...options.now===void 0?{}:{now:options.now}});return{clientThreadId:threadId??active?.sessionId??null,clientTurnId:turnId??active?.turnId??null,userMessage:active?.userMessage??null,observedModel:active?.model??null,observedReasoningEffort:active?.reasoningEffort??null,observedServiceTier:active?.serviceTier??null}}function transcriptPathFromEnvironment(){const value=process.env.CODEX_TRANSCRIPT_PATH?.trim();return value===void 0||value.length===0||value.length>4096?null:value}function normalizedId(value){const normalized=value?.trim();return normalized===void 0||normalized.length===0?null:normalized}var init_run_client_invocation=__esm({"src/run-client-invocation.ts"(){"use strict";init_src2()}});function taskAssuranceRiskSignalsOption(value){if(value===void 0)return void 0;try{if(Buffer.byteLength(value,"utf8")>4096)throw new Error("size");return assuranceRiskSignalsSchema.parse(JSON.parse(value))}catch{throw new UsageError("--assurance-risk-signals requires a valid risk-signals JSON object (max 4 KiB)")}}var init_task_assurance_options=__esm({"src/task-assurance-options.ts"(){"use strict";init_src5();init_cli_arguments()}});async function createTaskAndChangeAtomically(filesystem,composition,taskInput){const created=new Map;try{const task=await composition.tasks.createDraft(taskInput);created.set(composition.tasks.path(task.id),composition.tasks.serialize(task));const change=await composition.changes.createDraft({id:task.change_id,title:task.title,risk:task.risk,taskId:task.id,requirementIds:task.requirement_ids,acceptanceIds:task.acceptance_ids});return{task,change}}catch(error51){await rollbackTaskChangeCreation(filesystem,created);throw error51}}async function rollbackTaskChangeCreation(filesystem,created){for(const[path,content]of[...created].reverse()){await filesystem.removeFileIfContentMatches(path,content)}}var init_task_change_creation=__esm({"src/task-change-creation.ts"(){"use strict"}});function compactRunAggregate(aggregate){const bucket=value=>({usage_event_count:value.usage_event_count,tokens:value.tokens,cost:value.cost,coverage:value.coverage});return{scope_id:aggregate.scope_id,run_count:aggregate.run_count,run_coverage:aggregate.run_coverage,attribution:aggregate.attribution,conversation:bucket(aggregate.conversation),planning:bucket(aggregate.planning),execution:bucket(aggregate.execution),total:bucket(aggregate.total),work_types:{new:bucket(aggregate.work_types.new),rework:bucket(aggregate.work_types.rework)}}}var init_run_conversation_summary=__esm({"src/run-conversation-summary.ts"(){"use strict"}});function assertFinalizationEvidenceInput(ids){if(ids.some(id=>!/^EVD-[A-Z0-9-]+$/.test(id))){throw new UsageError("Finalization --evidence accepts comma-separated EVD IDs only, not JSON, Decision IDs or file paths")}return ids}var init_finalization_evidence_input=__esm({"src/finalization-evidence-input.ts"(){"use strict";init_cli_arguments()}});function activeRunIds(value){if(typeof value!=="object"||value===null||value.schema_version!==1||!Array.isArray(value.items))return[];return value.items.flatMap(item=>{if(typeof item!=="object"||item===null)return[];const candidate=item;return candidate.kind==="run"&&candidate.status==="running"&&typeof candidate.id==="string"?[candidate.id]:[]})}function activeRunWindow(ids,now=Date.now(),limit=32){if(!Number.isSafeInteger(limit)||limit<1||limit>32)throw new Error("Active telemetry limit must be an integer between 1 and 32");if(ids.length===0)return ids;const minute=Math.floor(now/6e4);const start=minute*(ids.length<=limit?1:limit)%ids.length;return Array.from({length:Math.min(limit,ids.length)},(_value,index)=>ids[(start+index)%ids.length])}var init_v2_run_active_window=__esm({"src/source-size-cli/v2-run-active-window.ts"(){"use strict"}});async function settleInteractionExecutionForRun(run,composition,finalizationBlockReason){if(run.run.execution_id===null)return null;let execution=(await composition.executions.read(run.run.execution_id)).execution;if(execution.kind!=="interaction")return null;if(run.finished?.status==="cancelled"){return["running","paused","verifying"].includes(execution.status)?composition.executions.transition(execution.id,"cancelled","Run explicitly cancelled"):execution}if(finalizationBlockReason!==null){return["running","paused","verifying"].includes(execution.status)?composition.executions.transition(execution.id,"blocked",null,void 0,finalizationBlockReason):execution}if(execution.status==="running"){execution=await composition.executions.transition(execution.id,"verifying")}return execution.status==="verifying"?composition.executions.transition(execution.id,"completed","Interaction finalized"):execution}var init_v2_run_interaction_execution=__esm({"src/source-size-cli/v2-run-interaction-execution.ts"(){"use strict"}});async function cancelTaskRunsForHuman(taskId,composition,parsed){return composition.runs.withUsageAttributionLock(async()=>{const candidates=await composition.runs.list();const roots2=candidates.filter(fold=>fold.finished===null&&fold.run.parent_run_id===null&&fold.run.task_id===taskId);for(const root of roots2){await cancelActiveDescendantRuns(activeDescendantRuns(root.run.run_id,candidates),composition,parsed);await cancelActiveDescendantRuns([root],composition,parsed)}return roots2.map(root=>root.run.run_id)})}async function cancelActiveDescendantRuns(descendants,composition,parsed){for(const descendant of[...descendants].reverse()){let current=await composition.runs.read(descendant.run.run_id);if(current.finished!==null)continue;if(current.effective_usage_records.length===0){const usage=unavailableUsageRecord(current,parsed,current.records.length+1);await composition.runs.appendRecord(usage);current=foldRunV2Records([...current.records,usage])}const record3=runFinishedV2Schema.parse({schema_version:2,event_id:runV2EventId(current.run.run_id,current.records.length+1),run_id:current.run.run_id,sequence:current.records.length+1,occurred_at:new Date().toISOString(),type:"run.finished",phase:latestRunV2Phase(current.records),status:"cancelled"});foldRunV2Records([...current.records,record3]);await composition.runs.appendRecord(record3)}}var init_v2_run_cancellation_and_aggregate=__esm({"src/source-size-cli/v2-run-cancellation-and-aggregate.ts"(){"use strict";init_src2();init_src3();init_run_conversation_v2();init_run_hierarchy()}});function rootRunStartConflicts(existing,input,explicitConversationId,explicitRunId){const actual=existing.run;const candidates=[["phase",actual.phase,input.phase],["entrypoint",actual.entrypoint,input.entrypoint],["work-type",actual.work_type,input.workType],["agent",actual.agent,input.agent],["provider",actual.provider,input.provider],["model",actual.model,input.model],["reasoning-effort",actual.reasoning_effort??null,input.reasoningEffort??null],["execution",actual.execution_id,input.executionId??null],["task",actual.task_id,input.taskId??null],["spec",actual.spec_id,input.specId??null],["prd",actual.prd_id,input.prdId??null],["change",actual.change_id,input.changeId??null],["continuation",actual.continuation_of_run_id,input.continuationOfRunId??null],["retry",actual.retry_of_run_id,input.retryOfRunId??null],["purpose",actual.run_purpose??null,input.runPurpose??null],["execution-kind",actual.execution_kind??null,input.executionKind??null],["direct-authorization",actual.direct_execution_authorization??null,input.directExecutionAuthorization??null],["run-role",effectiveRunV2Role(actual),input.runRole??(input.phase==="execution"?"orchestrator":"intake")]];if(existing.finished!==null)candidates.push(["terminal",existing.finished.status,"running"]);if(explicitRunId!==void 0)candidates.push(["id",actual.run_id,explicitRunId]);if(explicitConversationId!==void 0){candidates.push(["conversation",actual.conversation_id,input.conversationId])}return candidates.filter(([,left,right])=>left!==right).map(([field])=>field)}async function assertTaskExecutionIntakeCompatibleBeforeMutation(filesystem,composition,taskId,executionId){const invocation=await resolveRunClientInvocation(filesystem,"codex");const intake2=await findIntakeForExactTurn(composition,"codex",invocation);if(intake2===null)return;if(intake2.run.task_id===taskId&&intake2.run.execution_id===executionId)return;throw new UsageError(`Exact client turn is already captured by intake Run ${intake2.run.run_id} (Task ${intake2.run.task_id??"none"}, Execution ${intake2.run.execution_id??"none"}); it cannot start delivery for Task ${taskId} and Execution ${executionId}. Start delivery from a new observed client turn.`)}var init_execution_intake_compatibility=__esm({"src/execution-intake-compatibility.ts"(){"use strict";init_src3();init_cli_arguments();init_conversation_intake();init_run_client_invocation()}});function activeCaptureRunIds(area,parsed,result2){return area==="run"&&parsed.positionals[1]==="usage"&&parsed.flags.has("active")?changedActiveCaptureRunIds(result2):null}function changedActiveCaptureRunIds(result2){const telemetry=result2?.telemetry;if(typeof telemetry!=="object"||telemetry===null||!("mode"in telemetry)||telemetry.mode!=="active_exact_session"||!("captured"in telemetry)||!Array.isArray(telemetry.captured))throw new UsageError("Active telemetry capture returned an invalid projection result");const ids=[];for(const item of telemetry.captured){if(typeof item!=="object"||item===null||typeof item.run_id!=="string"||typeof item.captured!=="boolean"){throw new UsageError("Active telemetry capture returned an invalid Run result")}if(item.captured)ids.push(item.run_id)}return ids}var init_lifecycle_manifest_active_capture=__esm({"src/lifecycle-manifest-active-capture.ts"(){"use strict";init_cli_arguments()}});function effectiveRunFinishedAt(fold){const recordedFinish=fold.finished?.occurred_at??null;if(recordedFinish===null)return null;const startedAtMs=Date.parse(fold.run.occurred_at);const recordedFinishMs=Date.parse(recordedFinish);const reconciledFinishMs=fold.records.filter(record3=>"activity_kind"in record3&&record3.activity_kind==="retrospective_local_reconciliation").map(record3=>"source_occurred_at"in record3?record3.source_occurred_at??null:null).map(value=>value===null?Number.NaN:Date.parse(value)).filter(value=>Number.isFinite(value)&&value>=startedAtMs&&value<=recordedFinishMs);if(reconciledFinishMs.length===0)return recordedFinish;return new Date(Math.max(...reconciledFinishMs)).toISOString()}function projectedSourceTiming(runStartedAt,effectiveRecords,allRecords){const startedAtMs=Date.parse(runStartedAt);const timestampOf=value=>{const timestamp12=value===null||value===void 0?Number.NaN:Date.parse(value);return Number.isFinite(timestamp12)?timestamp12:null};const candidates=[];for(const record4 of[...effectiveRecords,...allRecords]){const sourceStartedAt2=record4.source_started_at;const sourceFinishedAt2=record4.source_finished_at;const startMs=timestampOf(sourceStartedAt2);const finishMs=timestampOf(sourceFinishedAt2);if(startMs!==null&&finishMs!==null&&finishMs>=startMs&&finishMs>=startedAtMs){candidates.push(record4);continue}const sourceOccurredAt=timestampOf(record4.source_occurred_at);if(record4.activity_kind==="retrospective_local_reconciliation"&&sourceOccurredAt!==null&&sourceOccurredAt>=startedAtMs)candidates.push({...record4,source_started_at:runStartedAt,source_finished_at:record4.source_occurred_at??void 0})}candidates.sort((left,right)=>Date.parse(left.occurred_at)-Date.parse(right.occurred_at));const record3=candidates.at(-1);const sourceStartedAt=record3?.source_started_at??null;const sourceFinishedAt=record3?.source_finished_at??record3?.source_occurred_at??null;return{source_started_at:sourceStartedAt,source_finished_at:sourceFinishedAt,source_duration_ms:timestampDelta(sourceStartedAt,sourceFinishedAt),capture_lag_ms:timestampDelta(sourceFinishedAt,record3?.occurred_at??null)}}function timestampDelta(start,finish){if(start===null||finish===null)return null;const startMs=Date.parse(start);const finishMs=Date.parse(finish);return Number.isFinite(startMs)&&Number.isFinite(finishMs)?Math.max(0,finishMs-startMs):null}var init_lifecycle_manifest_run_projection=__esm({"src/lifecycle-manifest-run-projection.ts"(){"use strict"}});function modelCallCoverage(fold){if(fold.model_call_records.length===0)return"unavailable";return fold.model_call_records.every(record3=>record3.coverage==="complete")?"complete":"partial"}function runCostInput(fold){return{run:{run_id:fold.run.run_id,attribution_status:fold.run.attribution_status,conversation_id:fold.run.conversation_id,execution_id:fold.run.execution_id,task_id:fold.run.task_id,spec_id:fold.run.spec_id,prd_id:fold.run.prd_id,change_id:fold.run.change_id,work_type:fold.run.work_type},records:fold.records,effective_usage_records:fold.effective_usage_records}}var init_lifecycle_manifest_run_usage=__esm({"src/lifecycle-manifest-run-usage.ts"(){"use strict"}});function summarizeRunObservedTiming(fold){return summarizeObservedSourceTiming(fold.effective_usage_records.map(record3=>({phase:record3.phase,source_started_at:record3.source_started_at??null,source_finished_at:record3.source_finished_at??null})))}var init_observed_run_timing=__esm({"src/observed-run-timing.ts"(){"use strict";init_src2()}});async function runLifecycleManifestMaintenance(action,parsed,filesystem,composition){const store=new LifecycleManifestStore(filesystem);if(["neighbors","path","explain","gaps"].includes(action??"")){return runManifestGraphQuery(action,parsed,store)}if(action==="rebuild"){if(!parsed.flags.has("confirm-full-scan")){throw new UsageError("manifest rebuild requires --confirm-full-scan")}const events=await lifecycleManifestBootstrapEvents(composition,filesystem);return{snapshot:await store.replace(events),indexed:events.length}}if(action==="refresh")return store.refresh();if(action==="reconcile"){const id=parsed.options.id??parsed.positionals[2];if(id===void 0)throw new UsageError("manifest reconcile requires --id ID");const event=await lifecycleManifestEventForId(id,composition,filesystem);return{snapshot:await store.appendMany([event]),reconciled:[id]}}if(action==="show"){return parsed.flags.has("active")?store.readActiveWork():store.readSummary()}throw new UsageError("manifest requires rebuild, refresh, reconcile, show, neighbors, path, explain, or gaps")}async function runManifestGraphQuery(action,parsed,store){const entities=await store.readEntities();const byId2=new Map(entities.map(entity=>[entity.id,entity]));const id=parsed.options.id??parsed.positionals[2];if(action==="path"){const from=parsed.options.from??id;const to2=parsed.options.to??parsed.positionals[3];if(from===void 0||to2===void 0)throw new UsageError("manifest path requires --from ID --to ID");const queue=[[from]];const visited=new Set([from]);while(queue.length>0&&visited.size<=GRAPH_VISIT_LIMIT){const route=queue.shift();const current=route.at(-1);if(current===to2)return{path:route,bounded:true,limit:GRAPH_VISIT_LIMIT};for(const neighbor of graphNeighbors(entities,current)){if(!visited.has(neighbor.entity.id)){visited.add(neighbor.entity.id);queue.push([...route,neighbor.entity.id])}}}return{path:null,bounded:true,limit:GRAPH_VISIT_LIMIT}}if(id===void 0||!byId2.has(id))throw new UsageError("manifest graph query requires an existing --id ID");if(action==="neighbors"){const neighbors=graphNeighbors(entities,id);return{id,neighbors:neighbors.slice(0,GRAPH_RESULT_LIMIT),bounded:true,limit:GRAPH_RESULT_LIMIT,truncated:neighbors.length>GRAPH_RESULT_LIMIT}}if(action==="gaps"){const entity=byId2.get(id);if(entity===void 0)throw new UsageError("manifest graph query requires an existing --id ID");const gaps=relationEdgesFor(entity).filter(edge2=>!byId2.has(edge2.target_id));return{id,gaps:gaps.slice(0,GRAPH_RESULT_LIMIT),bounded:true,limit:GRAPH_RESULT_LIMIT,truncated:gaps.length>GRAPH_RESULT_LIMIT}}const to=parsed.options.to??parsed.positionals[3];if(to===void 0)throw new UsageError("manifest explain requires --id ID --to ID");const edge=graphNeighbors(entities,id).find(neighbor=>neighbor.entity.id===to)?.edge;return{id,to,relation:edge??null,bounded:true,limit:GRAPH_RESULT_LIMIT}}async function manifestList(area,parsed,filesystem){if(!["prd","spec","change","task","execution","run","decision"].includes(area)){throw new UsageError(`Lifecycle manifest does not support list area: ${area}`)}const store=new LifecycleManifestStore(filesystem);let entities=await store.readEntities(area);if(entities.length===0&&await store.readSummary()===null&&!await filesystem.exists(".agents/records/lifecycle/.gitkeep")){throw new UsageError("Lifecycle manifest is not initialized; run `zaip manifest rebuild --confirm-full-scan` once")}const statuses=new Set(csvOption(parsed.options.status));const from=dateBoundary(parsed.options.from,false);const to=dateBoundary(parsed.options.to,true);entities=entities.filter(entity=>statuses.size===0||entity.status!==null&&statuses.has(entity.status)).filter(entity=>parsed.options.prd===void 0||entity.relations.includes(parsed.options.prd)).filter(entity=>parsed.options.spec===void 0||entity.relations.includes(parsed.options.spec)).filter(entity=>parsed.options.change===void 0||entity.relations.includes(parsed.options.change)).filter(entity=>parsed.options.task===void 0||entity.relations.includes(parsed.options.task)).filter(entity=>parsed.options.execution===void 0||entity.relations.includes(parsed.options.execution)).filter(entity=>from===null||Date.parse(entity.updated_at)>=from).filter(entity=>to===null||Date.parse(entity.updated_at)<=to).sort((left,right)=>right.updated_at.localeCompare(left.updated_at)||right.id.localeCompare(left.id));const after=parsed.options.after;const start=after===void 0?0:entities.findIndex(entity=>entity.id===after)+1;if(after!==void 0&&start===0)throw new UsageError(`--after id not found: ${after}`);const limit=parsed.flags.has("all")?entities.length:numberOption(parsed.options.limit,20);if(limit>200&&!parsed.flags.has("all")){throw new UsageError("--limit must be at most 200; use --all explicitly")}const view=parsed.options.view??"index";if(view!=="index"&&view!=="summary"&&view!=="full")throw new UsageError("--view must be index, summary, or full");const page=entities.slice(start,start+limit);if(view==="full")return page;if(view==="summary"){return page.map(({data:_data,...entity})=>entity)}return{schema:["id","title","status","risk","priority","updated_at","work_relations"],rows:page.map(entity=>[entity.id,entity.title,entity.status,entity.risk,entity.priority,entity.updated_at,entity.relations.filter(relation=>/^(?:PRD|SPEC|CHG|TASK|EXEC|RUN)-/.test(relation)).slice(0,2)]),next_after:page.length===limit?page.at(-1)?.id??null:null}}function isLifecycleManifestMutation(action){return![void 0,"list","show","next","validate","aggregate"].includes(action)}async function syncLifecycleManifestResult(result2,area,parsed,composition,filesystem){const store=new LifecycleManifestStore(filesystem);if(area==="decision"){const decision=findDecision(result2);if(decision!==void 0)await store.append(lifecycleManifestEventFromDecision(decision));return}if(area==="run"||area==="subagent"){const capturedIds=activeCaptureRunIds(area,parsed,result2);const candidate=area==="run"&&capturedIds===null?findRunId(result2)??parsed.options.id??parsed.positionals[2]:void 0;const events2=collectLifecycleEntities(result2).map(lifecycleManifestEventFromEntity);const runIds=new Set(capturedIds??collectRunIds(result2));if(candidate!==void 0)runIds.add(candidate);for(const runId of runIds){events2.push(lifecycleManifestEventFromRun(await composition.runs.read(runId)))}if(events2.length>0)await store.appendMany(events2);return}if(area==="conversation"){const events2=collectLifecycleEntities(result2).map(lifecycleManifestEventFromEntity);for(const runId of collectRunIds(result2)){events2.push(lifecycleManifestEventFromRun(await composition.runs.read(runId)))}if(events2.length>0)await store.appendMany(events2);return}if(area==="validation"||area==="evidence"){const artifact=findArtifact(result2,area);if(artifact!==void 0)await store.append(lifecycleManifestEventFromEntity(artifact));return}const events=collectLifecycleEntities(result2).map(lifecycleManifestEventFromEntity);for(const runId of collectRunIds(result2)){events.push(lifecycleManifestEventFromRun(await composition.runs.read(runId)))}if(events.length>0)await store.appendMany(events)}function findArtifact(result2,area){if(typeof result2!=="object"||result2===null)return void 0;const artifact=result2[area];if(typeof artifact!=="object"||artifact===null)return void 0;const record3=artifact;const observedAt=area==="validation"?record3.executed_at:record3.observed_at;if(typeof record3.id!=="string"||typeof observedAt!=="string"||typeof record3.status!=="string"){return void 0}return{...record3,updated_at:observedAt}}async function lifecycleManifestEventForId(id,composition,filesystem){if(id.startsWith("PRD-"))return lifecycleManifestEventFromEntity((await composition.prds.read(id)).prd);if(id.startsWith("SPEC-"))return lifecycleManifestEventFromEntity((await composition.specs.read(id)).spec);if(id.startsWith("CHG-"))return lifecycleManifestEventFromEntity((await composition.changes.read(id)).change);if(id.startsWith("TASK-"))return lifecycleManifestEventFromEntity((await composition.tasks.read(id)).task);if(id.startsWith("EXEC-"))return lifecycleManifestEventFromEntity((await composition.executions.read(id)).execution);if(id.startsWith("RUN-"))return lifecycleManifestEventFromRun(await composition.runs.read(id));if(/^(?:TEST|EVAL|CHECK|REVIEW|MUT|INT|E2E)-/.test(id)||id.startsWith("EVD-")){const artifact=(await lifecycleAssuranceBootstrapEvents(filesystem)).find(event=>event.entity.id===id);if(artifact!==void 0)return artifact;throw new UsageError(`Typed assurance artifact not found: ${id}`)}throw new UsageError(`Unsupported lifecycle manifest reconciliation id: ${id}`)}function collectLifecycleEntities(value){const found=[];const seen=new Set;const visit=candidate=>{if(Array.isArray(candidate)){candidate.forEach(visit);return}if(typeof candidate!=="object"||candidate===null)return;const record3=candidate;if(typeof record3.id==="string"&&typeof record3.status==="string"&&typeof record3.updated_at==="string"&&/^(PRD|SPEC|CHG|TASK|EXEC)-/.test(record3.id)&&!seen.has(record3.id)){seen.add(record3.id);found.push(record3)}Object.values(record3).forEach(visit)};visit(value);return found}function lifecycleManifestEventFromEntity(entity){const id=entity.id;const kind=id.startsWith("PRD-")?"prd":id.startsWith("SPEC-")?"spec":id.startsWith("CHG-")?"change":id.startsWith("TASK-")?"task":id.startsWith("EVD-")?"evidence":id.startsWith("TEST-")||id.startsWith("EVAL-")||id.startsWith("CHECK-")||id.startsWith("REVIEW-")||id.startsWith("MUT-")||id.startsWith("INT-")||id.startsWith("E2E-")?"validation":"execution";const relations=new Set;collectRelationIds(entity,relations,id);for(const[key,value]of Object.entries(entity)){if(key.endsWith("_id")&&typeof value==="string")relations.add(value);if(key.endsWith("_ids")&&Array.isArray(value))value.filter(item=>typeof item==="string").forEach(item=>{relations.add(item)})}return{schema_version:1,event_id:`${id}:${String(entity.updated_at)}:${String(entity.status)}`,occurred_at:entity.updated_at,operation:"upsert",entity:{kind,id,title:typeof entity.title==="string"?entity.title:null,status:entity.status,risk:typeof entity.risk==="string"?entity.risk:null,priority:typeof entity.priority==="string"?entity.priority:null,updated_at:entity.updated_at,relations:[...relations],relation_edges:relationEdgesFromEntity(entity,[...relations]),usage:null,data:Object.fromEntries(Object.entries(entity).filter(([key])=>key!=="prepared_plan"))}}}function collectRelationIds(value,relations,ownId){if(typeof value==="string"){if(/^(?:PRD|SPEC|CHG|TASK|EXEC|RUN|REQ|AC)-/.test(value)&&value!==ownId){relations.add(value)}return}if(Array.isArray(value)){value.forEach(item=>{collectRelationIds(item,relations,ownId)});return}if(typeof value==="object"&&value!==null){Object.values(value).forEach(item=>{collectRelationIds(item,relations,ownId)})}}function lifecycleManifestEventFromRun(fold){const costInput=runCostInput(fold);const aggregate=aggregateRunV2Usage([costInput],fold.run.run_id);const usage=aggregate.total;const runtime=fold.effective_usage_records.findLast(record3=>record3.runtime)?.runtime;const observedRuntime=fold.effective_usage_records.at(-1);const sourceTiming=projectedSourceTiming(fold.run.occurred_at,fold.effective_usage_records,fold.records);return{schema_version:1,event_id:`${fold.run.run_id}:${fold.records.length}:${fold.status}`,occurred_at:fold.records.at(-1)?.occurred_at??fold.run.occurred_at,operation:"upsert",entity:{kind:"run",id:fold.run.run_id,title:null,status:fold.status,risk:null,priority:null,updated_at:fold.records.at(-1)?.occurred_at??fold.run.occurred_at,relations:[fold.run.parent_run_id,fold.run.prd_id,fold.run.spec_id,fold.run.change_id,fold.run.task_id,fold.run.execution_id].filter(item=>item!==null),relation_edges:[fold.run.parent_run_id,fold.run.prd_id,fold.run.spec_id,fold.run.change_id,fold.run.task_id,fold.run.execution_id].filter(item=>item!==null).map(target_id=>({target_id,type:target_id===fold.run.parent_run_id?"parent":"references",direction:"outbound",provenance:"explicit",source_locator:`run:${fold.run.run_id}`})),usage:{input_tokens:usage.tokens.input,output_tokens:usage.tokens.output,cached_input_tokens:usage.tokens.cached_input,total_tokens:usage.tokens.total,cost:usage.cost.brl??usage.cost.usd,currency:usage.cost.brl!==null?"BRL":usage.cost.usd!==null?"USD":null},data:{attribution_status:fold.run.attribution_status,phase:fold.records.findLast(record3=>"phase"in record3)?.phase??fold.run.phase,run_role:effectiveRunV2Role(fold.run),run_kind:effectiveRunV2Kind(fold.run),run_purpose:effectiveRunV2Purpose(fold.run),requires_finalizer:runV2RequiresFinalizer(fold.run),parent_run_id:fold.run.parent_run_id,entrypoint:fold.run.entrypoint,work_type:fold.run.work_type,client:fold.run.client,agent:fold.run.agent,agent_name:fold.run.agent==="codex"?"codex":fold.run.agent_name??canonicalAgentName(fold.run.agent),provider:observedRuntime?.provider??fold.run.provider,model:fold.run.model,reasoning_effort:fold.run.reasoning_effort??fold.model_selection_records[0]?.requested.reasoning_effort??null,...effectiveConfiguration(fold),...callSummary(fold),cli_agent_name:fold.run.agent_name??null,call_coverage:modelCallCoverage(fold),service_tier:runtime?.service_tier??null,client_thread_id:fold.run.client_thread_id??null,client_turn_id:fold.run.client_turn_id??null,zaip_execution_id:fold.run.execution_id,agent_invocation_id:fold.run.agent_invocation_id??`AINV-${fold.run.run_id.slice("RUN-".length)}`,root_agent_invocation_id:fold.run.root_agent_invocation_id??`AINV-${fold.run.run_id.slice("RUN-".length)}`,parent_agent_invocation_id:fold.run.parent_agent_invocation_id??null,agent_invocation_kind:fold.run.invocation_kind??(fold.run.parent_run_id===null?"orchestrator":"delegated"),delegation_depth:fold.run.delegation_depth??(fold.run.parent_run_id===null?0:null),conversation_id:fold.run.conversation_id,execution_id:fold.run.execution_id,task_id:fold.run.task_id,spec_id:fold.run.spec_id,prd_id:fold.run.prd_id,change_id:fold.run.change_id,intake:fold.run.intake??null,started_at:fold.run.occurred_at,terminal_finished_at:fold.finished?.occurred_at??null,finished_at:effectiveRunFinishedAt(fold),...sourceTiming,observed_source_timing:summarizeRunObservedTiming(fold),pricing_segments:fold.effective_usage_records.map(record3=>({event_id:record3.event_id,attributed_spec_id:record3.attributed_spec_id??null,phase:record3.phase,provider:record3.provider,model:record3.model,service_tier:record3.runtime?.service_tier??runtime?.service_tier??null,input_tokens:record3.tokens.input,cached_input_tokens:record3.tokens.cached_input,output_tokens:record3.tokens.output,reasoning_tokens:record3.tokens.reasoning,total_tokens:record3.tokens.total,recorded_usd:record3.cost.usd,recorded_brl:record3.cost.brl,recorded_fx_rate:record3.cost.fx_rate??null,source_started_at:record3.source_started_at??null,source_finished_at:record3.source_finished_at??null,duration_ms:record3.source_started_at&&record3.source_finished_at?Math.max(0,Date.parse(record3.source_finished_at)-Date.parse(record3.source_started_at)):null})),entrypoint_usage:{conversation:aggregate.conversation,planning:aggregate.planning,execution:aggregate.execution,total:usage}}}}}function canonicalAgentName(agent){return agent.startsWith("agent-")?`zaip-agent-${agent.slice("agent-".length)}`:agent}function effectiveConfiguration(fold){const models=new Set([...fold.provider_invocation_records.map(record3=>record3.effective.model),...fold.model_call_records.map(record3=>record3.model),...fold.effective_usage_records.map(record3=>record3.model)].filter(value=>value!==null));const efforts=new Set([...fold.provider_invocation_records.map(record3=>record3.effective.reasoning_effort),...fold.effective_usage_records.map(record3=>record3.runtime?.reasoning_effort??null),...fold.model_call_records.map(record3=>record3.runtime?.reasoning_effort??null)].filter(value=>value!==null));return{effective_model:models.size===1?[...models][0]??null:null,effective_reasoning_effort:efforts.size===1?[...efforts][0]??null:null,effective_config_mixed:models.size>1||efforts.size>1}}function callSummary(fold){const ids=new Set([...fold.model_selection_records.map(record3=>record3.invocation_id),...fold.provider_invocation_records.map(record3=>record3.invocation_id)]);const base={cli_call_count:ids.size===0?null:ids.size,call_count:null,terminal_call_count:null,failed_call_count:null,cancelled_call_count:null};if(fold.model_call_records.length>0)return{...base,call_count:fold.model_call_records.length};if(ids.size===0)return base;return{...base,call_count:ids.size,terminal_call_count:fold.provider_invocation_records.length,failed_call_count:fold.provider_invocation_records.filter(record3=>record3.status==="failed").length,cancelled_call_count:fold.provider_invocation_records.filter(record3=>record3.status==="cancelled").length}}function lifecycleManifestEventFromDecision(decision){return{schema_version:1,event_id:`${decision.id}:${decision.created_at}`,occurred_at:decision.created_at,operation:"upsert",entity:{kind:"decision",id:decision.id,title:decision.title,status:null,risk:null,priority:null,updated_at:decision.created_at,relations:[decision.scope_id],relation_edges:[{target_id:decision.scope_id,type:"references",direction:"outbound",provenance:"explicit",source_locator:`decision:${decision.id}`}],usage:null,data:{origin:decision.origin,scope_type:decision.scope_type,scope_id:decision.scope_id,category:decision.category,created_at:decision.created_at}}}}function relationEdgesFromEntity(entity,relations){return relations.map(target_id=>{const explicit=Object.entries(entity).some(([key,value])=>key.endsWith("_id")&&value===target_id||key.endsWith("_ids")&&Array.isArray(value)&&value.includes(target_id));return{target_id,type:target_id.startsWith("REQ-")||target_id.startsWith("AC-")?"requirement":"references",direction:"outbound",provenance:explicit?"explicit":"derived",source_locator:`record:${String(entity.id)}`}})}function findRunId(value){if(typeof value!=="object"||value===null)return void 0;const record3=value;if(typeof record3.run_id==="string")return record3.run_id;for(const child of Object.values(record3)){const result2=findRunId(child);if(result2!==void 0)return result2}return void 0}function collectRunIds(value){const found=new Set;const visit=candidate=>{if(Array.isArray(candidate)){candidate.forEach(visit);return}if(typeof candidate!=="object"||candidate===null)return;const record3=candidate;if(typeof record3.run_id==="string"&&record3.run_id.startsWith("RUN-")){found.add(record3.run_id)}Object.values(record3).forEach(visit)};visit(value);return[...found]}function findDecision(value){if(typeof value!=="object"||value===null)return void 0;const record3=value;if(typeof record3.id==="string"&&record3.id.startsWith("DEC-")&&typeof record3.created_at==="string"){return record3}for(const child of Object.values(record3)){const result2=findDecision(child);if(result2!==void 0)return result2}return void 0}async function lifecycleManifestBootstrapEvents(composition,filesystem){const[prds,specs,changes,tasks,executions,runs,decisions,assurance]=await Promise.all([composition.prds.list(),composition.specs.list(),composition.changes.list(),composition.tasks.list(),composition.executions.list(),composition.runs.list(),composition.decisions.list(),lifecycleAssuranceBootstrapEvents(filesystem)]);return[...[...prds,...specs,...changes,...tasks,...executions].map(entity=>lifecycleManifestEventFromEntity(entity)),...runs.map(lifecycleManifestEventFromRun),...decisions.map(lifecycleManifestEventFromDecision),...assurance]}async function lifecycleAssuranceBootstrapEvents(filesystem){const paths=await filesystem.listFiles(".agents/records/changes",".md");const events=[];for(const path of paths){const isEvidence=path.includes("/artifacts/evidence/");const isValidation=/\/artifacts\/(?:tests|evals|checks)\//.test(path);if(!isEvidence&&!isValidation)continue;try{const content=await filesystem.readText(path);const artifact=isEvidence?parseMarkdown(content,evidenceArtifactV2Schema).metadata:parseMarkdown(content,validationArtifactV2Schema).metadata;const timestamp12="observed_at"in artifact?artifact.observed_at:artifact.executed_at;events.push(lifecycleManifestEventFromEntity({...artifact,updated_at:timestamp12}))}catch{}}return events}var GRAPH_RESULT_LIMIT,GRAPH_VISIT_LIMIT;var init_lifecycle_manifest_commands=__esm({"src/lifecycle-manifest-commands.ts"(){"use strict";init_src();init_src2();init_src3();init_src6();init_src6();init_src4();init_cli_arguments();init_lifecycle_manifest_active_capture();init_lifecycle_manifest_run_projection();init_lifecycle_manifest_run_usage();init_observed_run_timing();GRAPH_RESULT_LIMIT=50;GRAPH_VISIT_LIMIT=200}});function assertChangedFilesInScope(task,changedFiles){const outside2=changedFilesOutsideTaskScopes(task.write_scopes,changedFiles);if(outside2.length>0){throw new LifecycleGateError(`Task ${task.id} changed files outside write scopes: ${outside2.join(", ")}`)}}var init_lifecycle_changed_files=__esm({"src/lifecycle-changed-files.ts"(){"use strict";init_lifecycle_assurance_v2();init_lifecycle_gate_helpers()}});import{posix as posix4}from"node:path";async function assertTaskEvidenceCoverage(context,task,result2){if(result2.evidence_ids.length===0){throw new LifecycleGateError(`Task ${task.id} requires at least one Evidence`)}const changeDirectory=posix4.dirname(context.layout.activePath("change",task.change_id));const mainDocuments=[await context.filesystem.readText(context.layout.activePath("change",task.change_id))];const executions=(await context.repositories.executions.list()).filter(execution=>execution.dag.nodes.some(node=>node.task_id===task.id));for(const execution of executions){mainDocuments.push(await context.filesystem.readText(context.layout.activePath("execution",execution.id)))}const documents=[];for(const evidenceId of result2.evidence_ids){const path=`${changeDirectory}/artifacts/evidence/${evidenceId}.md`;const candidates=mainDocuments.filter(document=>containsIdentifier(document,evidenceId)&&containsIdentifier(document,task.id));if(await context.filesystem.exists(path)){candidates.push(`${evidenceId}
|
|
374
|
-
${await context.filesystem.readText(path)}`)}const resolved=candidates.find(document=>containsIdentifier(document,task.id));if(resolved===void 0){throw new LifecycleGateError(`Evidence does not resolve for Task ${task.id}: ${evidenceId}`)}documents.push(resolved)}const evidence=documents.join("\n");const missing=task.acceptance_ids.filter(id=>!containsIdentifier(evidence,id));if(missing.length>0){throw new LifecycleGateError(`Task ${task.id} Evidence does not cover Acceptance Criteria: ${missing.join(", ")}`)}}async function assertTaskSixStageCoverage(context,task,result2,executionId,enforceLegacyRiskCounts=true,requireDecision=true){const decisions=[...await context.repositories.decisions.list({type:"change",id:task.change_id}),...await context.repositories.decisions.list({type:"execution",id:executionId})];if(requireDecision&&decisions.length===0){throw new LifecycleGateError(`Task ${task.id} requires at least one Decision for six-stage coverage`)}const changeDirectory=posix4.dirname(context.layout.activePath("change",task.change_id));const verificationPaths=(await Promise.all(["tests","evals","checks"].map(kind=>context.filesystem.listFiles(`${changeDirectory}/artifacts/${kind}`)))).flat();const relatedVerificationPaths=[];for(const path of verificationPaths){const content=await context.filesystem.readText(path);if(containsIdentifier(content,task.id)&&containsIsoTimestamp(content)){relatedVerificationPaths.push(path)}}if(relatedVerificationPaths.length===0){throw new LifecycleGateError(`Task ${task.id} requires at least one Test, Eval, or Check for six-stage coverage`)}const timestampedEvidence=[];for(const evidenceId of result2.evidence_ids){const path=`${changeDirectory}/artifacts/evidence/${evidenceId}.md`;if(!await context.filesystem.exists(path))continue;const content=await context.filesystem.readText(path);if(containsIdentifier(content,task.id)&&containsIsoTimestamp(content)){timestampedEvidence.push(path)}}if(timestampedEvidence.length===0){throw new LifecycleGateError(`Task ${task.id} requires an Evidence file with the Task id and an ISO date-time for six-stage coverage`)}if(enforceLegacyRiskCounts){assertRiskScaledArtifactCounts(task.id,task.risk,relatedVerificationPaths.length,result2.evidence_ids.length)}}var init_lifecycle_evidence_v2=__esm({"src/lifecycle-evidence-v2.ts"(){"use strict";init_lifecycle_assurance_v2();init_lifecycle_gate_helpers()}});async function activateTaskMacroParents(change,repositories){const specId=change.source.type==="task"?null:change.source.spec_id;const prdId=change.source.type==="prd"?change.source.prd_id:null;if(specId!==null){const{spec}=await repositories.specs.read(specId);if(spec.status==="ready"||spec.status==="blocked"){await repositories.specs.transition(spec.id,"active")}else if(spec.status!=="active"){throw new LifecycleGateError(`SPEC ${spec.id} must be ready, active, or blocked before Task start`)}}if(prdId!==null){const{prd}=await repositories.prds.read(prdId);if(prd.status==="ready"||prd.status==="blocked"){await repositories.prds.transition(prd.id,"active")}else if(prd.status!=="active"){throw new LifecycleGateError(`PRD ${prd.id} must be ready, active, or blocked before Task start`)}}}var init_lifecycle_parent_activation_v2=__esm({"src/lifecycle-parent-activation-v2.ts"(){"use strict";init_lifecycle_assurance_v2()}});async function executionForTask(task,repositories){const canonicalExecutionId=task.plan_ref?.execution_id??task.prepared_plan?.execution_id??null;if(canonicalExecutionId!==null){const{execution}=await repositories.executions.read(canonicalExecutionId);if(!execution.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===task.change_id)){throw new LifecycleGateError(`Execution ${canonicalExecutionId} does not contain Task/Change ${task.id}/${task.change_id}`)}return execution}const executions=(await repositories.executions.list()).filter(execution=>execution.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===task.change_id));if(executions.length!==1){throw new LifecycleGateError(`Task ${task.id} must resolve to exactly one Execution; found ${executions.length}`)}return executions[0]}async function executionForCompletionRun(task,canonicalExecution,run,repositories){if(run.run.execution_id===canonicalExecution.id)return canonicalExecution;if(run.run.continuation_of_run_id===null||run.run.execution_id===null){return canonicalExecution}const{execution}=await repositories.executions.read(run.run.execution_id);const ownsTask=execution.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===task.change_id);if(execution.kind!=="delivery"||execution.origin.type!=="task"||execution.origin.task_id!==task.id||!ownsTask){throw new LifecycleGateError(`Continuation Run ${run.run.run_id} Execution ${execution.id} does not own Task/Change ${task.id}/${task.change_id}`)}return execution}function assertCompletedRunAttribution(run,task,executionId){if(run.finished?.status!=="completed"){throw new LifecycleGateError(`Run ${run.run.run_id} must be completed`)}assertRunAttribution(run,task,executionId)}function assertRunAttribution(run,task,executionId){const mismatches=[(run.records?.findLast(record3=>"phase"in record3)?.phase??run.run.phase)==="execution"||run.run.phase==="planning"&&run.run.work_type==="rework"?null:"phase",run.run.execution_id===executionId?null:"execution_id",run.run.task_id===task.id?null:"task_id",run.run.change_id===task.change_id?null:"change_id"].filter(value=>value!==null);if(mismatches.length>0){throw new LifecycleGateError(`Run ${run.run.run_id} attribution mismatch: ${mismatches.join(", ")}`)}}var init_lifecycle_run_attribution=__esm({"src/lifecycle-run-attribution.ts"(){"use strict";init_lifecycle_assurance_v2()}});function assertAllTerminal(entities,label,terminal="completed"){const incomplete2=entities.filter(entity=>entity.status!==terminal);if(incomplete2.length>0){throw new LifecycleGateError(`${label} is not ${terminal}: ${incomplete2.map(formatLifecycleState).join(", ")}`)}}var init_lifecycle_terminal_state=__esm({"src/lifecycle-terminal-state.ts"(){"use strict";init_lifecycle_assurance_v2();init_lifecycle_gate_helpers()}});var LifecycleV2Gate;var init_lifecycle_v2=__esm({"src/lifecycle-v2.ts"(){"use strict";init_src4();init_editorial_delivery_assurance();init_git_delivery_preflight();init_lifecycle_assurance_v2();init_lifecycle_changed_files();init_lifecycle_evidence_v2();init_lifecycle_gate_helpers();init_lifecycle_parent_activation_v2();init_lifecycle_run_attribution();init_lifecycle_terminal_state();init_lifecycle_assurance_v2();init_lifecycle_gate_helpers();LifecycleV2Gate=class{constructor(filesystem,layout,repositories){this.filesystem=filesystem;this.layout=layout;this.repositories=repositories;if(layout.version===1)throw new TypeError("LifecycleV2Gate requires a modern layout")}filesystem;layout;repositories;async completeTask(id,result2){const{task}=await this.repositories.tasks.read(id);if(task.status!=="verifying"){throw new LifecycleGateError(`Task ${id} must be verifying before completion`)}try{return await this.completeVerifyingTask(task,result2)}catch(error51){if(error51 instanceof LifecycleGateError){await this.repositories.tasks.transition(id,"executing")}throw error51}}async verifyTask(id,evidenceIds){const{task}=await this.repositories.tasks.read(id);if(task.status!=="executing"&&task.status!=="verifying"){throw new LifecycleGateError(`Task ${id} must be executing or verifying before verification`)}const execution=await executionForTask(task,this.repositories);const result2=taskAssurancePreflightResult(evidenceIds);await this.assertEvidenceCoverage(task,result2);const assurance=this.assuranceConfig();await this.assertSixStageCoverage(task,result2,execution.id,assurance===null);if(assurance!==null){await assertTaskAssurancePreflightV1({filesystem:this.filesystem,layout:this.layout,task,evidence_ids:result2.evidence_ids,config:assurance})}return task.status==="verifying"?task:this.repositories.tasks.transition(id,"verifying")}async completeVerifyingTask(task,result2){for(const dependencyId of task.depends_on){const{task:dependency}=await this.repositories.tasks.read(dependencyId).catch(()=>{throw new LifecycleGateError(`Task dependency does not resolve: ${dependencyId}`)});if(dependency.status!=="completed"){throw new LifecycleGateError(`Task dependency must be completed: ${dependencyId} is ${dependency.status}`)}}const{change}=await this.repositories.changes.read(task.change_id);if(!change.task_ids.includes(task.id)){throw new LifecycleGateError(`Change ${change.id} does not own Task ${task.id}`)}if(!new Set(["executing","verifying"]).has(change.status)){throw new LifecycleGateError(`Change ${change.id} is not executing or verifying`)}if(result2.completed_run_id===null){throw new LifecycleGateError(`Completed Task ${task.id} requires a completed Run`)}const run=await this.readRequiredRun(result2.completed_run_id);const canonicalExecution=await executionForTask(task,this.repositories);if(!new Set(["running","verifying"]).has(canonicalExecution.status)){throw new LifecycleGateError(`Execution ${canonicalExecution.id} is not running or verifying`)}const execution=await executionForCompletionRun(task,canonicalExecution,run,this.repositories);if(!new Set(["running","verifying"]).has(execution.status)){throw new LifecycleGateError(`Execution ${execution.id} is not running or verifying`)}assertCompletedRunAttribution(run,task,execution.id);await this.assertEvidenceCoverage(task,result2);const assurance=this.assuranceConfig();await this.assertSixStageCoverage(task,result2,execution.id,assurance===null);if(assurance!==null){const bundle=await readAssuranceBundle(this.filesystem,this.layout,[task],result2.evidence_ids);const effectiveAssurance=effectiveTaskAssurance(task,assurance);const expectedCommit=effectiveAssurance.require_final_commit?await requireFinalProductCandidate(this.filesystem.root,bundle.validations,bundle.evidences,task.write_scopes,task.id,result2.changed_files):null;if(expectedCommit!==null){await assertEditorialCandidateDiff({root:this.filesystem.root,task,signals:effectiveTaskRiskSignals(task),commit:expectedCommit,changedFiles:result2.changed_files})}assertTaskAssuranceV1({config:assurance,task,risk:task.risk,risk_signals:effectiveTaskRiskSignals(task),write_scopes:task.write_scopes,acceptance_ids:task.acceptance_ids,validations:bundle.validations,evidences:bundle.evidences,verifier:verifierFrom(bundle.validations,run.run.agent,run.run.run_id),mutation:mutationFrom(bundle.metadata,task.id),rollback_evidence_id:bundle.evidences.find(evidence=>evidence.id.includes("ROLLBACK"))?.id??null,expected_commit_sha:expectedCommit})}assertChangedFilesInScope(task,result2.changed_files);return this.repositories.tasks.transition(task.id,"completed",result2)}async startTask(id,mode="start"){const{task}=await this.repositories.tasks.read(id);if(this.assuranceConfig()?.require_final_commit===true)await assertGitDeliveryReady(this.filesystem.root);const expected=mode==="resume"?"blocked":mode==="rework"?"failed":"planned";if(task.status!==expected){throw new LifecycleGateError(`Task ${id} must be ${expected} before ${mode}`)}for(const dependencyId of task.depends_on){const dependency=await this.repositories.tasks.read(dependencyId).catch(()=>null);if(dependency===null||dependency.task.status!=="completed"){throw new LifecycleGateError(`Task dependency is not completed: ${dependencyId}`)}}let{change}=await this.repositories.changes.read(task.change_id);const execution=await executionForTask(task,this.repositories);let latestExecution=execution;if(mode!=="start"){if(change.status==="blocked"||change.status==="failed"){change=await this.repositories.changes.transition(change.id,"executing")}if(latestExecution.status==="blocked"||latestExecution.status==="failed"){latestExecution=await this.repositories.executions.transition(latestExecution.id,"running")}}if(change.status!=="executing"){throw new LifecycleGateError(`Change ${change.id} must be executing before Task start`)}if(latestExecution.status!=="running"){throw new LifecycleGateError(`Execution ${latestExecution.id} must be running before Task start`)}await activateTaskMacroParents(change,this.repositories);return this.repositories.tasks.transition(id,"executing")}async failTask(id,result2){const{task}=await this.repositories.tasks.read(id);if(!new Set(["executing","verifying"]).has(task.status)){throw new LifecycleGateError(`Task ${id} must be executing or verifying before failure`)}if(result2.completed_run_id===null){throw new LifecycleGateError(`Failed Task ${id} requires a failed Run`)}const execution=await executionForTask(task,this.repositories);const run=await this.readRequiredRun(result2.completed_run_id);if(run.finished?.status!=="failed"){throw new LifecycleGateError(`Run ${result2.completed_run_id} must be failed`)}assertRunAttribution(run,task,execution.id);assertChangedFilesInScope(task,result2.changed_files);return this.repositories.tasks.transition(id,"failed",result2)}async verifyChange(id){const{change}=await this.repositories.changes.read(id);if(change.status!=="executing"){throw new LifecycleGateError(`Change ${id} must be executing before verification`)}const tasks=await this.tasksForChange(change.id,change.task_ids);const incomplete2=tasks.filter(task=>task.status!=="completed");if(incomplete2.length>0){throw new LifecycleGateError(`Change ${id} has incomplete Tasks: ${incomplete2.map(formatLifecycleState).join(", ")}`)}return this.repositories.changes.transition(id,"verifying")}async completeChange(id,result2){const{change}=await this.repositories.changes.read(id);if(change.status!=="verifying"){throw new LifecycleGateError(`Change ${id} must be verifying before completion`)}const tasks=await this.tasksForChange(change.id,change.task_ids);const incomplete2=tasks.filter(task=>task.status!=="completed");if(incomplete2.length>0){throw new LifecycleGateError(`Change ${id} has incomplete Tasks: ${incomplete2.map(formatLifecycleState).join(", ")}`)}const covered=new Set(tasks.flatMap(task=>task.acceptance_ids));const missing=change.acceptance_ids.filter(acceptanceId=>!covered.has(acceptanceId));if(missing.length>0){throw new LifecycleGateError(`Change ${id} has uncovered Acceptance Criteria: ${missing.join(", ")}`)}for(const task of tasks){if(task.result===null)throw new LifecycleGateError(`Task ${task.id} has no terminal result`);await this.assertEvidenceCoverage(task,task.result)}return this.repositories.changes.transition(id,"completed",result2)}async verifyExecution(id){const{execution}=await this.repositories.executions.read(id);if(execution.status!=="running"){throw new LifecycleGateError(`Execution ${id} must be running before verification`)}await this.assertExecutionDescendantsComplete(execution.id,execution.dag.nodes);return this.repositories.executions.transition(id,"verifying")}async completeExecution(id,result2){const{execution}=await this.repositories.executions.read(id);let completedExecution;if(execution.status==="verifying"){await this.assertExecutionDescendantsComplete(execution.id,execution.dag.nodes);const changeIds=[...new Set(execution.dag.nodes.map(node=>node.change_id))];for(const changeId of changeIds){const{change}=await this.repositories.changes.read(changeId);if(change.status!=="completed"){throw new LifecycleGateError(`Execution Change must be completed: ${formatLifecycleState(change)}`)}}completedExecution=await this.repositories.executions.transition(id,"completed",result2)}else if(execution.status==="completed"){completedExecution=execution}else{throw new LifecycleGateError(`Execution ${id} must be verifying before completion`)}await this.reconcileCompletedExecutionOrigin(completedExecution);return completedExecution}async reconcileCompletedExecutionOrigin(execution){if(execution.origin.type==="prd"){const{prd}=await this.repositories.prds.read(execution.origin.prd_id);if(prd.status==="active")await this.deliverPrd(prd.id);else if(prd.status!=="delivered"){throw new LifecycleGateError(`Completed Execution ${execution.id} has non-deliverable PRD ${prd.id}: ${prd.status}`)}}else if(execution.origin.type==="spec"){const{spec}=await this.repositories.specs.read(execution.origin.spec_id);if(spec.status==="active")await this.deliverSpec(spec.id);else if(spec.status!=="delivered"){throw new LifecycleGateError(`Completed Execution ${execution.id} has non-deliverable SPEC ${spec.id}: ${spec.status}`)}}}async deliverSpec(id){const{spec}=await this.repositories.specs.read(id);if(spec.status!=="active"){throw new LifecycleGateError(`SPEC ${id} must be active before delivery`)}const[changes,executions]=await Promise.all([this.repositories.changes.list(),this.repositories.executions.list()]);const descendants=changes.filter(change=>change.source.type==="spec"&&change.source.spec_id===id||change.source.type==="prd"&&change.source.spec_id===id);const descendantChangeIds=new Set(descendants.map(change=>change.id));const relatedExecutions=executions.filter(execution=>execution.origin.type==="spec"&&execution.origin.spec_id===id||execution.dag.nodes.some(node=>descendantChangeIds.has(node.change_id)));if(descendants.length===0||relatedExecutions.length===0){throw new LifecycleGateError(`SPEC ${id} has no materialized Change and Execution`)}assertAllTerminal(descendants,"SPEC Change");assertAllTerminal(relatedExecutions,"SPEC Execution");const assurance=this.assuranceConfig();if(assurance!==null){const tasks=await this.readTasks(relatedExecutions.flatMap(item=>item.dag.nodes.map(node=>node.task_id)));await this.assertDeliveryAssurance("spec",spec.acceptance_ids,[],tasks,assurance)}return this.repositories.specs.transition(id,"delivered")}async deliverPrd(id){const{prd}=await this.repositories.prds.read(id);if(prd.status!=="active"){throw new LifecycleGateError(`PRD ${id} must be active before delivery`)}const[specs,changes,executions]=await Promise.all([this.repositories.specs.list(),this.repositories.changes.list(),this.repositories.executions.list()]);const executionId=prd.prepared_plan?.execution_id??prd.plan_ref?.execution_id;if(executionId===void 0){throw new LifecycleGateError(`PRD ${id} has no prepared plan or plan reference`)}const selectedExecution=executions.find(execution=>execution.id===executionId&&execution.origin.type==="prd"&&execution.origin.prd_id===id);if(selectedExecution===void 0){throw new LifecycleGateError(`PRD ${id} plan Execution does not resolve: ${executionId}`)}const selectedChangeIds=new Set(selectedExecution.dag.nodes.map(node=>node.change_id));const directChanges=changes.filter(change=>selectedChangeIds.has(change.id));const selectedSpecIds=prd.prepared_plan===null?new Set(directChanges.flatMap(change=>change.source.type==="prd"&&change.source.prd_id===id?[change.source.spec_id]:[])):new Set(specIdsForPrdPlanV2(prd.prepared_plan,id));const childSpecs=specs.filter(spec=>spec.prd_id===id&&selectedSpecIds.has(spec.id));const directExecutions=[selectedExecution];if(childSpecs.length===0){throw new LifecycleGateError(`PRD ${id} requires at least one SPEC`)}for(const spec of childSpecs){if(spec.status==="active")await this.deliverSpec(spec.id)}const refreshedSpecs=(await this.repositories.specs.list()).filter(spec=>spec.prd_id===id&&selectedSpecIds.has(spec.id));assertAllTerminal(refreshedSpecs,"PRD SPEC","delivered");assertAllTerminal(directChanges,"PRD Change");assertAllTerminal(directExecutions,"PRD Execution");const assurance=this.assuranceConfig();if(assurance!==null){const tasks=await this.readTasks(selectedExecution.dag.nodes.map(node=>node.task_id));const metadata2=prd;await this.assertDeliveryAssurance("prd",metadata2.acceptance_ids??refreshedSpecs.flatMap(spec=>spec.acceptance_ids),prd.outcome_ids,tasks,assurance)}return this.repositories.prds.transition(id,"delivered")}async cancelTask(id,summary,completedRunId=null){const{task}=await this.repositories.tasks.read(id);this.assertCancellable([task],["draft","planned","executing","verifying","blocked"],"Task");const changes=(await this.repositories.changes.list()).filter(change=>change.id===task.change_id&&change.source.type==="task"&&change.source.task_id===id);const executions=(await this.repositories.executions.list()).filter(execution=>execution.origin.type==="task"&&execution.origin.task_id===id||execution.dag.nodes.some(node=>node.task_id===id&&node.change_id===task.change_id));const cascade=await this.cancelDescendants([],changes,executions,`Task ${id} was cancelled: ${summary}`,completedRunId);const cancelledTask=(await this.repositories.tasks.read(id)).task;return{task:cancelledTask,cascade}}async cancelPrd(id){const{prd}=await this.repositories.prds.read(id);this.assertCancellable([prd],["draft","ready","active","blocked"],"PRD");const specs=(await this.repositories.specs.list()).filter(spec=>spec.prd_id===id);const specIds=new Set(specs.map(spec=>spec.id));const changes=(await this.repositories.changes.list()).filter(change=>change.source.type==="prd"&&change.source.prd_id===id||change.source.type==="spec"&&specIds.has(change.source.spec_id));const cascade=await this.cancelDescendants(specs,changes,(await this.repositories.executions.list()).filter(execution=>execution.origin.type==="prd"&&execution.origin.prd_id===id||execution.origin.type==="spec"&&specIds.has(execution.origin.spec_id)),`PRD ${id}`);const cancelledPrd=prd.status==="cancelled"?prd:await this.repositories.prds.transition(id,"cancelled");return{prd:cancelledPrd,cascade}}async cancelSpec(id){const{spec}=await this.repositories.specs.read(id);this.assertCancellable([spec],["draft","ready","active","blocked"],"SPEC");const changes=(await this.repositories.changes.list()).filter(change=>change.source.type==="spec"&&change.source.spec_id===id||change.source.type==="prd"&&change.source.spec_id===id);const cascade=await this.cancelDescendants([],changes,(await this.repositories.executions.list()).filter(execution=>execution.origin.type==="spec"&&execution.origin.spec_id===id),`SPEC ${id}`);const cancelledSpec=spec.status==="cancelled"?spec:await this.repositories.specs.transition(id,"cancelled");return{spec:cancelledSpec,cascade}}async cancelDescendants(specs,changes,originExecutions,parent,completedRunId=null){const changeIds=new Set(changes.map(change=>change.id));const allExecutions=await this.repositories.executions.list();const executions=[...new Map([...originExecutions,...allExecutions.filter(execution=>execution.dag.nodes.some(node=>changeIds.has(node.change_id)))].map(execution=>[execution.id,execution])).values()];const taskIds=new Set([...changes.flatMap(change=>change.task_ids),...executions.flatMap(execution=>execution.dag.nodes.map(node=>node.task_id))]);const tasks=(await this.repositories.tasks.list()).filter(task=>taskIds.has(task.id));const reason=`Cancelled automatically because ${parent} was cancelled.`;this.assertCancellable(tasks.filter(task=>!isTerminalLifecycleStatus(task.status)),["draft","planned","executing","verifying","blocked"],"Task");this.assertCancellable(changes.filter(change=>!isTerminalLifecycleStatus(change.status)),["draft","planned","executing","verifying","blocked"],"Change");this.assertCancellable(executions.filter(execution=>!isTerminalLifecycleStatus(execution.status)),["planned","running","paused","verifying","blocked"],"Execution");this.assertCancellable(specs.filter(spec=>!isTerminalLifecycleStatus(spec.status)),["draft","ready","active","blocked"],"SPEC");const cancelledTasks=await Promise.all(tasks.filter(task=>!isTerminalLifecycleStatus(task.status)).map(task=>this.repositories.tasks.transition(task.id,"cancelled",{summary:reason,changed_files:[],evidence_ids:[],completed_run_id:completedRunId})));const cancelledChanges=await Promise.all(changes.filter(change=>!isTerminalLifecycleStatus(change.status)).map(change=>this.repositories.changes.transition(change.id,"cancelled",reason)));const cancelledExecutions=await Promise.all(executions.filter(execution=>!isTerminalLifecycleStatus(execution.status)).map(execution=>this.repositories.executions.transition(execution.id,"cancelled",reason)));const cancelledSpecs=await Promise.all(specs.filter(spec=>!isTerminalLifecycleStatus(spec.status)).map(spec=>this.repositories.specs.transition(spec.id,"cancelled")));return{specs:cancelledSpecs,tasks:cancelledTasks,changes:cancelledChanges,executions:cancelledExecutions}}assertCancellable(entities,cancellable,entity){for(const item of entities){if(item.status==="cancelled"||cancellable.includes(item.status))continue;throw new LifecycleGateError(`${entity} ${item.id} cannot be cancelled from status ${item.status}`)}}assuranceConfig(){const config2=this.layout.projectConfig?.assurance;return config2?.version===1?config2:null}async readTasks(ids){return Promise.all([...new Set(ids)].map(async id=>(await this.repositories.tasks.read(id)).task))}async assertDeliveryAssurance(origin,acceptanceIds,outcomeIds,tasks,config2){const bundle=await readAssuranceBundle(this.filesystem,this.layout,tasks);const expected=config2.require_final_commit?await resolveFinalProductCandidate(this.filesystem.root,bundle.validations,bundle.evidences):null;const validations=expected===null?bundle.validations:bundle.validations.filter(artifact=>artifact.commit_sha===expected);const evidences=expected===null?bundle.evidences:bundle.evidences.filter(artifact=>artifact.commit_sha===expected);const verifier=await this.deliveryVerifier(validations,tasks);assertDeliveryAssuranceV1({origin,config:config2,acceptance_ids:acceptanceIds,outcome_ids:outcomeIds,validations,evidences,verifier,mutation:deliveryMutationFrom(bundle.metadata,tasks.map(task=>task.id)),rollback_evidence_id:evidences.find(evidence=>evidence.id.includes("ROLLBACK"))?.id??null,expected_commit_sha:expected})}async deliveryVerifier(validations,tasks){for(const review of validations.filter(item=>isReviewKind(item.kind))){const task=tasks.find(item=>item.id===review.task_id);if(task?.result?.completed_run_id==null)continue;const run=await this.readRequiredRun(task.result.completed_run_id);const approval=verifierFrom([review],run.run.agent,run.run.run_id);if(approval!==null)return approval}return null}async tasksForChange(changeId,expectedIds){const tasks=await Promise.all(expectedIds.map(taskId=>this.repositories.tasks.read(taskId)));for(const{task}of tasks){if(task.change_id!==changeId){throw new LifecycleGateError(`Task ${task.id} does not belong to Change ${changeId}`)}}return tasks.map(({task})=>task)}async readRequiredRun(id){try{return await this.repositories.runs.read(id)}catch(error51){throw new LifecycleGateError(`Run ${id} does not resolve: ${error51 instanceof Error?error51.message:String(error51)}`)}}async assertEvidenceCoverage(task,result2){await assertTaskEvidenceCoverage({filesystem:this.filesystem,layout:this.layout,repositories:this.repositories},task,result2)}async assertSixStageCoverage(task,result2,executionId,enforceLegacyRiskCounts=true){const assurance=this.assuranceConfig();const signals=effectiveTaskRiskSignals(task);if(task.assurance_risk_signals_source==="explicit"&&task.assurance_risk_signals?.editorial_delivery===true&&assurance===null)throw new LifecycleGateError("Editorial delivery requires assurance.version: 1");await assertTaskSixStageCoverage({filesystem:this.filesystem,layout:this.layout,repositories:this.repositories},task,result2,executionId,enforceLegacyRiskCounts,assurance===null||!assertEditorialDeliveryEligibility(task,signals))}async assertExecutionDescendantsComplete(executionId,nodes){for(const node of nodes){const{task}=await this.repositories.tasks.read(node.task_id);if(task.change_id!==node.change_id){throw new LifecycleGateError(`Execution ${executionId} DAG ownership mismatch for ${task.id}`)}if(task.status!=="completed"){throw new LifecycleGateError(`Execution Task must be completed: ${formatLifecycleState(task)}`)}}}}}});function inferredOrphanFailureTask(fold,tasks){if(fold.finished?.status!=="failed"||fold.run.client_thread_id!==null||fold.run.client_turn_id!==null||fold.finalization_decision!=null||effectiveRunV2Role(fold.run)!=="orchestrator")return void 0;return tasks.find(task=>{const result2=task.result;return task.id===fold.run.task_id&&task.status==="failed"&&result2!=null&&result2.completed_run_id===fold.run.run_id&&result2.changed_files.length===0&&result2.evidence_ids.length===0&&task.status_reason===`Run ${fold.run.run_id} failed and closed its operational lifecycle.`})}var init_inferred_orphan_failure=__esm({"src/inferred-orphan-failure.ts"(){"use strict";init_src3()}});async function hostTerminalOnlyPreflight(composition,filesystem){let active;try{active=await new LifecycleManifestStore(filesystem).readActiveWork()}catch{return{kind:"full"}}const items=activeWorkItems(active);if(items===null)return{kind:"full"};const activeRuns=items.filter(item=>item.kind==="run"&&item.status==="running");const operationalOwners=items.filter(isOperationalOwner);if(operationalOwners.some(owner=>!activeRuns.some(run=>run.relations.includes(owner.id)))){return{kind:"full"}}let current;try{current=await Promise.all(activeRuns.map(item=>composition.runs.read(item.id)))}catch{return{kind:"full"}}const observedTerminalRunIds=current.filter(fold=>fold.finished!==null).map(fold=>fold.run.run_id);if(observedTerminalRunIds.length>0){return{kind:"full",observed_terminal_run_ids:observedTerminalRunIds}}const codex=current.filter(fold=>isCodexTelemetryClient(fold.run.client));if(codex.some(fold=>fold.run.client_thread_id===null||fold.run.client_turn_id===null)){return{kind:"full"}}if(codex.length>0){const activity=await listCodexInvocationReconciliationActivity(filesystem.root,{threadIds:codex.map(fold=>fold.run.client_thread_id),invocations:codex.map(fold=>({threadId:fold.run.client_thread_id,turnId:fold.run.client_turn_id}))});const terminal=new Set(activity.lifecycles.filter(item=>item.finishedAt!==null&&item.status!=="active").map(item=>`${item.sessionId}:${item.turnId}`));if(codex.some(fold=>terminal.has(`${fold.run.client_thread_id}:${fold.run.client_turn_id}`))){return{kind:"full"}}}return{kind:"no-op",result:{runs:[],orphaned_executions:[],orphaned_interaction_executions:[],orphaned_tasks:[],orphaned_execution_entities:[],orphaned_owner_entities:[],reconciliations:[],reconciliation_errors:[],unresolved_running_run_ids:current.map(fold=>fold.run.run_id)}}}function activeWorkItems(value){if(typeof value!=="object"||value===null||value.schema_version!==1||typeof value.updated_at!=="string"||!Number.isFinite(Date.parse(value.updated_at))||!Array.isArray(value.items))return null;const items=value.items;const parsed=[];for(const item of items){if(typeof item!=="object"||item===null)return null;const candidate=item;if(typeof candidate.kind!=="string"||candidate.kind.length===0||typeof candidate.id!=="string"||candidate.id.length===0||typeof candidate.status!=="string"||candidate.status.length===0||candidate.relations!==void 0&&(!Array.isArray(candidate.relations)||candidate.relations.some(id=>typeof id!=="string")))return null;parsed.push({kind:candidate.kind,id:candidate.id,status:candidate.status,relations:candidate.relations??[]})}return parsed}function isOperationalOwner(item){return item.kind==="task"&&["executing","verifying"].includes(item.status)||item.kind==="change"&&["executing","verifying"].includes(item.status)||item.kind==="execution"&&["running","paused","verifying"].includes(item.status)||item.kind==="spec"&&item.status==="active"||item.kind==="prd"&&item.status==="active"}var init_open_work_host_preflight=__esm({"src/open-work-host-preflight.ts"(){"use strict";init_src2();init_src6();init_record_codex_telemetry()}});function runDepth(fold,runs){const parentById=new Map(runs.map(candidate=>[candidate.run.run_id,candidate.run.parent_run_id]));let depth=0;let parent=fold.run.parent_run_id;const seen=new Set([fold.run.run_id]);while(parent!==null&&!seen.has(parent)){seen.add(parent);depth+=1;parent=parentById.get(parent)??null}return depth}function terminalSubjectIds(fold){const role=effectiveRunV2Role(fold.run);if(role==="orchestrator"&&fold.run.entrypoint==="task"){return fold.run.task_id===null?[]:[fold.run.task_id]}if(role==="orchestrator"){return[fold.run.spec_id,fold.run.prd_id].filter(id=>id!==null)}return[]}var init_open_work_run_topology=__esm({"src/open-work-run-topology.ts"(){"use strict";init_src3()}});async function reconcileOpenWork(parsed,composition,lifecycle,filesystem){const hostTerminalOnly=parsed.flags?.has("host-terminal-only")??false;let observedTerminalRunIds=[];if(hostTerminalOnly){const preflight=await hostTerminalOnlyPreflight(composition,filesystem);if(preflight.kind==="no-op")return preflight.result;observedTerminalRunIds=preflight.observed_terminal_run_ids??[];if(observedTerminalRunIds.length>0){await Promise.all(observedTerminalRunIds.map(async runId=>{const current=await composition.runs.read(runId);if(isReconcilableCodexClient(current.run.client,false)&¤t.run.client_thread_id!==null&¤t.run.client_turn_id!==null)await recordCodexTelemetryIfAvailable(current,composition,filesystem)}));return{runs:[],observed_terminal_runs:observedTerminalRunIds.map(run_id=>({run_id})),orphaned_executions:[],orphaned_interaction_executions:[],orphaned_tasks:[],orphaned_execution_entities:[],orphaned_owner_entities:[],reconciliations:[],reconciliation_errors:[],unresolved_running_run_ids:[]}}}let runs=await composition.runs.list();const orphanScope=authorizedOrphanScope(parsed);const runningCodex=runs.filter(fold=>[fold.finished===null,isReconcilableCodexClient(fold.run.client,orphanScope!==void 0),orphanScope===void 0?fold.run.client_thread_id!==null:orphanScope.matchesRun(fold)].every(Boolean)).sort((left,right)=>runDepth(right,runs)-runDepth(left,runs));const threadIds=runningCodex.flatMap(fold=>typeof fold.run.client_thread_id==="string"?[fold.run.client_thread_id]:[]);const invocations=runningCodex.flatMap(fold=>{const threadId=fold.run.client_thread_id;const turnId=fold.run.client_turn_id;return typeof threadId==="string"&&typeof turnId==="string"?[{threadId,turnId}]:[]});const{lifecycles:localLifecycles,activeInvocations}=threadIds.length===0?{lifecycles:[],activeInvocations:[]}:await listCodexInvocationReconciliationActivity(filesystem.root,{threadIds,invocations});const localByInvocation=new Map(localLifecycles.map(item=>[`${item.sessionId}:${item.turnId}`,item]));const closedRuns=[];const orphanedRootRunIds=new Set;const reconciliationStartedAt=new Date;for(const fold of runningCodex){if((await composition.runs.read(fold.run.run_id)).finished!==null)continue;const local=localByInvocation.get(`${fold.run.client_thread_id??""}:${fold.run.client_turn_id??""}`);const completedLocally=(local?.status==="completed"||local?.status==="cancelled"||local?.status==="interrupted"||local?.status==="failed")&&local.finishedAt!==null;const orphaned=!hostTerminalOnly&&(isOrphanedCodexRun(fold,activeInvocations,reconciliationStartedAt)||orphanScope!==void 0&&isExplicitLegacyNoHostOrphan(fold,reconciliationStartedAt));if(!completedLocally&&!orphaned)continue;if(orphaned)orphanedRootRunIds.add(fold.run.run_id);const role=effectiveRunV2Role(fold.run);const activeChildren=activeDescendantRuns(fold.run.run_id,runs);if(role==="orchestrator"&&activeChildren.length>0){if(local?.status!=="cancelled")continue;await cancelActiveDescendantRuns2(activeChildren,composition,parsed);runs=await composition.runs.list()}let current=completedLocally?await recordCodexTelemetryIfAvailable(fold,composition,filesystem):fold;if(current.effective_usage_records.length===0){await composition.runs.appendRecord(unavailableUsageRecord(current,parsed,current.records.length+1));current=await composition.runs.read(current.run.run_id)}const finished=runFinishedV2Schema.parse({schema_version:2,event_id:`${current.run.run_id}:${String(current.records.length+1).padStart(6,"0")}`,run_id:current.run.run_id,sequence:current.records.length+1,occurred_at:completedLocally?local.finishedAt:new Date().toISOString(),type:"run.finished",phase:latestRunV2Phase(current.records),status:completedLocally&&local?.status==="cancelled"?"cancelled":completedLocally&&local?.status==="failed"?"failed":completedLocally?"completed":"failed"});foldRunV2Records([...current.records,finished]);await composition.runs.appendRecord(finished);const refreshed=await composition.runs.read(current.run.run_id);closedRuns.push(refreshed);runs=replaceRunSnapshot(runs,refreshed)}let[tasks,changes,executions,specs,prds]=await Promise.all([composition.tasks.list(),composition.changes.list(),composition.executions.list(),composition.specs.list(),composition.prds.list()]);let catalog={tasks,changes,executions,specs,prds};const explicitlyCancelled=hostTerminalOnly?[]:await closeExplicitlyCancelledTaskRoots(runs,catalog,composition,parsed,orphanScope);if(explicitlyCancelled.length>0){closedRuns.push(...explicitlyCancelled);runs=await composition.runs.list()}const activeSubjectIds=activeLifecycleSubjectIds(runs.filter(item=>item.finished===null&&!(!hostTerminalOnly&&orphanScope?.matchesRun(item)&&isOrphanedCodexRun(item,activeInvocations,reconciliationStartedAt))),catalog);const operationalSubjectIds=terminalReconciliationSubjectIds(catalog);const inferredRepairIds=new Set;if(!hostTerminalOnly&&orphanScope!==void 0){for(const fold of runs){const task=inferredOrphanFailureTask(fold,catalog.tasks);if(task===void 0||!orphanScope.matchesRun(fold)||activeSubjectIds.has(task.id)||activeDescendantRuns(fold.run.run_id,runs).length>0)continue;inferredRepairIds.add(fold.run.run_id);orphanedRootRunIds.add(fold.run.run_id);operationalSubjectIds.add(task.id)}}const reconciliations=[];const reconciliationErrors=[];const reconciledSubjectIds=new Set;const terminal=runs.filter(fold=>fold.finished!==null&&terminalSubjectIds(fold).some(id=>operationalSubjectIds.has(id))&&(orphanScope===void 0||orphanScope.matchesRun(fold))).sort((left,right)=>(right.finished?.occurred_at??right.run.occurred_at).localeCompare(left.finished?.occurred_at??left.run.occurred_at));for(const fold of terminal){const subjects=terminalSubjectIds(fold);if(subjects.length===0||subjects.some(id=>activeSubjectIds.has(id))||subjects.every(id=>reconciledSubjectIds.has(id))){continue}try{if(inferredRepairIds.has(fold.run.run_id)){const task=inferredOrphanFailureTask(fold,catalog.tasks);if(task!==void 0)await lifecycle.startTask(task.id,"rework")}reconciliations.push(await reconcileFinishedRunLifecycle(fold,composition,lifecycle,{...inferredRepairIds.has(fold.run.run_id)?{}:{catalog},candidateRuns:runs,...orphanedRootRunIds.has(fold.run.run_id)?{requestedOutcome:"blocked",forceRequestedOutcome:true,summary:"Explicit orphan reconciliation found no active host invocation or terminal work outcome; repair is required before resuming"}:{}}))}catch(error51){const message=error51 instanceof Error?error51.message:String(error51);reconciliations.push({...await snapshotRunLifecycle(fold,composition,catalog),status:"deferred",error:message});reconciliationErrors.push({run_id:fold.run.run_id,error:message})}subjects.forEach(id=>{reconciledSubjectIds.add(id)})}[tasks,changes,executions,specs,prds]=await Promise.all([composition.tasks.list(),composition.changes.list(),composition.executions.list(),composition.specs.list(),composition.prds.list()]);catalog={tasks,changes,executions,specs,prds};const orphanedExecutions=hostTerminalOnly?[]:await blockOrphanedStandaloneExecutions(catalog,runs,composition,reconciliationStartedAt,orphanScope);const orphanedInteractionExecutions=hostTerminalOnly?[]:await blockOrphanedInteractionExecutions(catalog,runs,composition,reconciliationStartedAt,orphanScope);const orphanedOwnerEntities=await readOrphanedExecutionOwners(orphanedExecutions,composition);return{runs:closedRuns,observed_terminal_runs:observedTerminalRunIds.map(run_id=>({run_id})),orphaned_executions:orphanedExecutions.map(execution=>execution.id),orphaned_interaction_executions:orphanedInteractionExecutions.map(execution=>execution.id),orphaned_tasks:[],orphaned_execution_entities:[...orphanedExecutions,...orphanedInteractionExecutions],orphaned_owner_entities:orphanedOwnerEntities,reconciliations,reconciliation_errors:reconciliationErrors,unresolved_running_run_ids:runs.filter(fold=>fold.finished===null).map(fold=>fold.run.run_id)}}function replaceRunSnapshot(runs,refreshed){return runs.map(fold=>fold.run.run_id===refreshed.run.run_id?refreshed:fold)}async function readOrphanedExecutionOwners(executions,composition){const taskIds=new Set;const changeIds=new Set;for(const execution of executions){for(const node of execution.dag.nodes){taskIds.add(node.task_id);changeIds.add(node.change_id)}}return Promise.all([...[...taskIds].map(async id=>(await composition.tasks.read(id)).task),...[...changeIds].map(async id=>(await composition.changes.read(id)).change)])}async function closeExplicitlyCancelledTaskRoots(runs,catalog,composition,parsed,scope){const cancelledTaskIds=new Set(catalog.tasks.filter(task=>task.status==="cancelled").map(task=>task.id));const closed=[];for(const fold of runs){if(fold.finished!==null||effectiveRunV2Role(fold.run)!=="orchestrator"||fold.run.parent_run_id!==null||fold.run.entrypoint!=="task"||fold.run.task_id===null||!cancelledTaskIds.has(fold.run.task_id)||scope!==void 0&&!scope.matchesRun(fold)){continue}const current=await composition.runs.read(fold.run.run_id);if(current.finished!==null)continue;const activeChildren=activeDescendantRuns(current.run.run_id,runs);if(activeChildren.length>0)await cancelActiveDescendantRuns2(activeChildren,composition,parsed);let attributable=await composition.runs.read(current.run.run_id);if(attributable.effective_usage_records.length===0){await composition.runs.appendRecord(unavailableUsageRecord(attributable,parsed,attributable.records.length+1));attributable=await composition.runs.read(current.run.run_id)}await composition.runs.appendRecord(runFinishedV2Schema.parse({schema_version:2,event_id:`${attributable.run.run_id}:${String(attributable.records.length+1).padStart(6,"0")}`,run_id:attributable.run.run_id,sequence:attributable.records.length+1,occurred_at:new Date().toISOString(),type:"run.finished",phase:latestRunV2Phase(attributable.records),status:"cancelled"}));closed.push(await composition.runs.read(current.run.run_id))}return closed}async function cancelActiveDescendantRuns2(descendants,composition,parsed){for(const descendant of[...descendants].reverse()){let current=await composition.runs.read(descendant.run.run_id);if(current.finished!==null)continue;if(current.effective_usage_records.length===0){await composition.runs.appendRecord(unavailableUsageRecord(current,parsed,current.records.length+1));current=await composition.runs.read(current.run.run_id)}await composition.runs.appendRecord(runFinishedV2Schema.parse({schema_version:2,event_id:`${current.run.run_id}:${String(current.records.length+1).padStart(6,"0")}`,run_id:current.run.run_id,sequence:current.records.length+1,occurred_at:new Date().toISOString(),type:"run.finished",phase:latestRunV2Phase(current.records),status:"cancelled"}))}}async function blockOrphanedStandaloneExecutions(catalog,runs,composition,now,scope){const ids=new Set(orphanedStandaloneExecutionIds(catalog,runs,now).filter(id=>{const execution=catalog.executions.find(candidate=>candidate.id===id);return execution!==void 0&&(scope===void 0||scope.matchesExecution(execution))}));if(ids.size===0)return[];const clock=new SystemClock;const taskById=new Map(catalog.tasks.map(task=>[task.id,task]));const changeById=new Map(catalog.changes.map(change=>[change.id,change]));const blocked2=[];for(const id of ids){const execution=catalog.executions.find(item=>item.id===id);if(execution===void 0)continue;const reason=`Execution ${id} has no active orchestrator agent call after the reconciliation grace period.`;for(const node of execution.dag.nodes){const task=taskById.get(node.task_id);if(task!==void 0&&(scope===void 0||scope.matchesTask(task.id))&&["executing","verifying"].includes(task.status)){await composition.tasks.transition(task.id,"blocked",null,clock,reason)}const change=changeById.get(node.change_id);if(change!==void 0&&["executing","verifying"].includes(change.status)){const latestTasks=await Promise.all(change.task_ids.map(async taskId=>(await composition.tasks.read(taskId)).task));if(latestTasks.every(candidate=>["blocked","completed","failed","cancelled"].includes(candidate.status)))await composition.changes.transition(change.id,"blocked",null,clock,reason)}}if(execution.status!=="blocked")await composition.executions.transition(id,"blocked",null,clock,reason);blocked2.push((await composition.executions.read(id)).execution)}return blocked2}async function blockOrphanedInteractionExecutions(catalog,runs,composition,now,scope){const ids=orphanedInteractionExecutionIds(catalog,runs,now).filter(id=>{const execution=catalog.executions.find(candidate=>candidate.id===id);return execution!==void 0&&(scope===void 0||scope.matchesExecution(execution))});if(ids.length===0)return[];const clock=new SystemClock;const blocked2=[];for(const id of ids){await composition.executions.transition(id,"blocked",null,clock,`Interaction Execution ${id} has no active orchestrator Run after the reconciliation grace period.`);blocked2.push((await composition.executions.read(id)).execution)}return blocked2}function orphanedStandaloneExecutionIds(catalog,runs,now=new Date,includePlanned=false){return catalog.executions.flatMap(execution=>{if(execution.origin.type!=="task"||!["running","verifying",...includePlanned?["planned"]:[]].includes(execution.status)){return[]}const startedAt=Date.parse(execution.started_at??execution.updated_at??execution.created_at);if(!Number.isFinite(startedAt)||now.getTime()-startedAt<ORPHANED_EXECUTION_GRACE_MS){return[]}const taskIds=new Set(execution.dag.nodes.map(node=>node.task_id));const hasActiveOrchestratorRun=runs.some(run=>{const required2=[run.finished===null,effectiveRunV2Role(run.run)==="orchestrator",run.run.parent_run_id===null,run.run.entrypoint==="task"];if(!required2.every(Boolean))return false;return run.run.execution_id===execution.id||run.run.task_id!==null&&taskIds.has(run.run.task_id)});return hasActiveOrchestratorRun?[]:[execution.id]})}function orphanedInteractionExecutionIds(catalog,runs,now=new Date){return catalog.executions.flatMap(execution=>{if(execution.kind!=="interaction"||!["running","verifying"].includes(execution.status)){return[]}const startedAt=Date.parse(execution.started_at??execution.updated_at??execution.created_at);if(!Number.isFinite(startedAt)||now.getTime()-startedAt<ORPHANED_EXECUTION_GRACE_MS){return[]}const hasActiveRoot=runs.some(run=>run.finished===null&&effectiveRunV2Role(run.run)==="orchestrator"&&run.run.parent_run_id===null&&run.run.execution_id===execution.id);return hasActiveRoot?[]:[execution.id]})}function terminalReconciliationSubjectIds(catalog){const ids=new Set;const unsettledTaskIds=new Set(catalog.tasks.filter(task=>["executing","verifying"].includes(task.status)).map(task=>task.id));unsettledTaskIds.forEach(id=>{ids.add(id)});for(const change of catalog.changes){const unsettled=["planned","executing","verifying"].includes(change.status);const hasUnsettledTask=change.task_ids.some(id=>unsettledTaskIds.has(id));if(!unsettled&&!hasUnsettledTask)continue;change.task_ids.forEach(id=>{ids.add(id)});if(change.source.type==="spec")ids.add(change.source.spec_id);if(change.source.type==="prd"){ids.add(change.source.prd_id);if(change.source.spec_id!==null)ids.add(change.source.spec_id)}}for(const execution of catalog.executions){if(!["planned","running","paused","verifying"].includes(execution.status))continue;execution.dag.nodes.forEach(node=>{ids.add(node.task_id)})}catalog.specs.filter(spec=>spec.status==="active").forEach(spec=>{ids.add(spec.id)});catalog.prds.filter(prd=>prd.status==="active").forEach(prd=>{ids.add(prd.id)});return ids}function authorizedOrphanScope(parsed){const reason=parsed.options["orphan-reason"];const scope=parsed.options["orphan-scope"];if(reason===void 0&&scope===void 0)return void 0;if(reason!=="inactive_terminal_without_host_identity"){throw new Error("--orphan-reason must be inactive_terminal_without_host_identity for explicit orphan reconciliation")}if(scope===void 0||scope.trim().length===0){throw new Error("Explicit orphan reconciliation requires --orphan-scope all or comma-separated Run/Task/Execution IDs")}const ids=new Set(scope.split(",").map(value=>value.trim()).filter(Boolean));if(ids.size===0)throw new Error("--orphan-scope must name all or at least one canonical ID");return{matchesRun(fold){return ids.has("all")||ids.has(fold.run.run_id)||fold.run.task_id!==null&&ids.has(fold.run.task_id)||fold.run.execution_id!==null&&ids.has(fold.run.execution_id)},matchesTask(taskId){return ids.has("all")||ids.has(taskId)},matchesExecution(execution){return ids.has("all")||ids.has(execution.id)||execution.origin.type==="task"&&ids.has(execution.origin.task_id)||execution.dag.nodes.some(node=>ids.has(node.task_id))}}}function isOrphanedCodexRun(fold,activeInvocations,now=new Date){if(fold.finished!==null||!isCodexTelemetryClient(fold.run.client))return false;const startedAt=Date.parse(fold.run.occurred_at);if(!Number.isFinite(startedAt)||now.getTime()-startedAt<ORPHANED_RUN_GRACE_MS){return false}return!activeInvocations.some(active=>{if(active.sessionId!==fold.run.client_thread_id)return false;const activeObservedAt=Date.parse(active.observedAt??active.startedAt??"");if(!Number.isFinite(activeObservedAt)||now.getTime()-activeObservedAt>ORPHANED_RUN_GRACE_MS){return false}if(active.turnId===fold.run.client_turn_id)return true;const activeStartedAt=active.startedAt===null?Number.NaN:Date.parse(active.startedAt);return Number.isFinite(activeStartedAt)&&Math.abs(activeStartedAt-startedAt)<=ACTIVE_INVOCATION_START_TOLERANCE_MS})}function isReconcilableCodexClient(client,explicitScope){return isCodexTelemetryClient(client)||explicitScope&&EXPLICIT_LEGACY_CODEX_CLIENTS.has(client)}function isExplicitLegacyNoHostOrphan(fold,now){if(fold.finished!==null||!EXPLICIT_LEGACY_CODEX_CLIENTS.has(fold.run.client)||fold.run.client_thread_id!==null){return false}const startedAt=Date.parse(fold.run.occurred_at);return Number.isFinite(startedAt)&&now.getTime()-startedAt>=ORPHANED_RUN_GRACE_MS}function activeLifecycleSubjectIds(activeRuns,catalog){const ids=new Set;const taskById=new Map(catalog.tasks.map(task=>[task.id,task]));const changeById=new Map(catalog.changes.map(change=>[change.id,change]));const specById=new Map(catalog.specs.map(spec=>[spec.id,spec]));for(const fold of activeRuns){relatedWorkIds(fold).forEach(id=>{ids.add(id)});const task=fold.run.task_id===null?void 0:taskById.get(fold.run.task_id);const change=task===void 0?void 0:changeById.get(task.change_id);const specId=fold.run.spec_id??(change?.source.type==="spec"||change?.source.type==="prd"?change.source.spec_id:null);const prdId=fold.run.prd_id??(change?.source.type==="prd"?change.source.prd_id:null)??(specId===null?null:specById.get(specId)?.prd_id??null);if(change!==void 0)ids.add(change.id);if(specId!==null)ids.add(specId);if(prdId!==null)ids.add(prdId);for(const candidate of catalog.changes){const belongsToSpec=specId!==null&&candidate.source.type!=="task"&&candidate.source.spec_id===specId;const belongsToPrd=candidate.source.type==="prd"&&candidate.source.prd_id===prdId;if(!belongsToSpec&&!belongsToPrd)continue;ids.add(candidate.id);candidate.task_ids.forEach(id=>{ids.add(id)})}for(const execution of catalog.executions){if(execution.origin.type==="prd"&&execution.origin.prd_id===prdId||execution.origin.type==="spec"&&execution.origin.spec_id===specId){ids.add(execution.id);execution.dag.nodes.forEach(node=>{ids.add(node.task_id)})}}}return ids}function relatedWorkIds(fold){return[fold.run.task_id,fold.run.spec_id,fold.run.prd_id].filter(id=>id!==null)}var ORPHANED_RUN_GRACE_MS,ORPHANED_EXECUTION_GRACE_MS,ACTIVE_INVOCATION_START_TOLERANCE_MS,EXPLICIT_LEGACY_CODEX_CLIENTS;var init_open_work_reconciliation=__esm({"src/open-work-reconciliation.ts"(){"use strict";init_src();init_src2();init_src3();init_inferred_orphan_failure();init_open_work_host_preflight();init_open_work_run_topology();init_record_codex_telemetry();init_run_conversation_v2();init_run_hierarchy();init_run_lifecycle_reconciliation();ORPHANED_RUN_GRACE_MS=10*60*1e3;ORPHANED_EXECUTION_GRACE_MS=10*60*1e3;ACTIVE_INVOCATION_START_TOLERANCE_MS=2*60*1e3;EXPLICIT_LEGACY_CODEX_CLIENTS=new Set(["codex-prd-authoring","codex-prd-composite-authoring"])}});async function loadAgentCatalog(filesystem){if(!await filesystem.exists(AGENT_CATALOG_PATH2)){throw new UsageError(`Agent catalog not found at ${AGENT_CATALOG_PATH2}`)}const catalog=parseAgentCatalog(parseYaml(await filesystem.readText(AGENT_CATALOG_PATH2)));const findings=validateAgentCatalog(catalog);if(findings.length>0){throw new Error(`Invalid Agent catalog: ${findings[0]?.message??"unknown finding"}`)}return catalog}async function resolveRunAgentIdentityResult(filesystem,input){const client=input.client.trim();if(client.length===0)throw new UsageError("--client must not be empty");const fallback=client==="codex"||client.startsWith("codex-")?"codex":client;const requested=input.agent?.trim();if(requested===void 0||requested.length===0||requested===client||requested===fallback){return{agent_id:fallback,warning:null}}const catalog=await loadAgentCatalog(filesystem).catch(error51=>{if(error51 instanceof UsageError){throw new UsageError(`${error51.message}; omit --agent to use fallback "${fallback}"`)}throw error51});try{const selected=resolveAgentIdentity(catalog,requested);return{agent_id:selected.canonical_id,warning:selected.warning}}catch(error51){if(!(error51 instanceof Error)||!error51.message.startsWith("Unknown Agent identity:")){throw new UsageError(error51 instanceof Error?error51.message:String(error51))}}const available=catalog.agents.flatMap(agent=>[agent.id,agent.codex_name]).sort().join(", ");throw new UsageError(`Unknown Agent "${requested}". Use one of: ${available}; omit --agent to use fallback "${fallback}"`)}async function resolveRunAgentName(filesystem,agentId2){if(agentId2==="codex")return"codex";if(!agentId2.startsWith("agent-"))return agentId2;const catalog=await loadAgentCatalog(filesystem);return catalog.agents.find(agent=>agent.id===agentId2)?.codex_name??null}var AGENT_CATALOG_PATH2;var init_run_agent_identity=__esm({"src/run-agent-identity.ts"(){"use strict";init_src();init_cli_arguments();AGENT_CATALOG_PATH2=".agents/config/agents/catalog.yaml"}});function defaultExecutionPolicy(risk2,signals={}){const independentBranches=signals.independent_branches===true;return{failure_policy:"stop_on_terminal_failure",max_parallelism:risk2==="lite"?1:independentBranches?risk2==="critical"?3:2:1,max_operational_retries:risk2==="lite"?0:1,max_repair_cycles_per_task:risk2==="lite"?0:2,soft_model_cycle_budget:risk2==="lite"?4:risk2==="standard"?24:40,context_refresh_after_cycles:risk2==="lite"?4:8,verification_mode:risk2==="critical"?"full":"scoped",max_cost_usd:signals.max_cost_usd??null}}function completeObservedCostUsd(costs){if(costs.length===0||costs.some(cost3=>cost3===null))return null;return costs.reduce((sum,cost3)=>sum+cost3,0)}async function evaluateRunBudget(run,composition,filesystem){if(run.run.execution_id===null)return null;const execution=(await composition.executions.read(run.run.execution_id)).execution;const cycles=run.effective_usage_records.length;const providerInputTokens=run.effective_usage_records.reduce((sum,event)=>sum+Math.max(0,(event.tokens.input??0)-(event.tokens.cached_input??0)),0);const observedContextTokens=run.effective_usage_records.reduce((sum,event)=>sum+(event.context_stats?.initial_pack_tokens??0)+(event.context_stats?.tool_output_tokens??0),0);const measuredInputTokens=providerInputTokens>0?providerInputTokens:observedContextTokens;const cycleBudget=execution.policy.soft_model_cycle_budget??null;const refreshAfter=execution.policy.context_refresh_after_cycles??null;const checkpointRequired=cycleBudget!==null&&cycles>=cycleBudget;const contextRefreshRequired=refreshAfter!==null&&cycles>0&&cycles%refreshAfter===0;const costCapUsd=execution.policy.max_cost_usd??null;const observedCostUsd=completeObservedCostUsd(run.effective_usage_records.map(event=>event.cost.usd));const hasCompleteObservedCost=observedCostUsd!==null;const budget={schema_version:1,run_id:run.run.run_id,execution_id:execution.id,measured_at:new Date().toISOString(),cycles,provider_uncached_input_tokens:providerInputTokens,observed_context_tokens:observedContextTokens,measured_input_tokens:measuredInputTokens,measurement_source:providerInputTokens>0?"provider_uncached":"context_stats",soft_model_cycle_budget:cycleBudget,context_refresh_after_cycles:refreshAfter,max_cost_usd:costCapUsd,observed_cost_usd:observedCostUsd,cost_measurement_source:hasCompleteObservedCost?"observed":"unavailable",cost_checkpoint_required:costCapUsd!==null&&observedCostUsd!==null&&observedCostUsd>=costCapUsd,checkpoint_required:checkpointRequired,context_refresh_required:contextRefreshRequired};if(checkpointRequired||contextRefreshRequired||budget.cost_checkpoint_required){await filesystem.writeTextAtomic(`.local/checkpoints/${run.run.run_id}.json`,`${JSON.stringify(budget,null,2)}
|
|
374
|
+
${await context.filesystem.readText(path)}`)}const resolved=candidates.find(document=>containsIdentifier(document,task.id));if(resolved===void 0){throw new LifecycleGateError(`Evidence does not resolve for Task ${task.id}: ${evidenceId}`)}documents.push(resolved)}const evidence=documents.join("\n");const missing=task.acceptance_ids.filter(id=>!containsIdentifier(evidence,id));if(missing.length>0){throw new LifecycleGateError(`Task ${task.id} Evidence does not cover Acceptance Criteria: ${missing.join(", ")}`)}}async function assertTaskSixStageCoverage(context,task,result2,executionId,enforceLegacyRiskCounts=true,requireDecision=true){const decisions=[...await context.repositories.decisions.list({type:"change",id:task.change_id}),...await context.repositories.decisions.list({type:"execution",id:executionId})];if(requireDecision&&decisions.length===0){throw new LifecycleGateError(`Task ${task.id} requires at least one Decision for six-stage coverage`)}const changeDirectory=posix4.dirname(context.layout.activePath("change",task.change_id));const verificationPaths=(await Promise.all(["tests","evals","checks"].map(kind=>context.filesystem.listFiles(`${changeDirectory}/artifacts/${kind}`)))).flat();const relatedVerificationPaths=[];for(const path of verificationPaths){const content=await context.filesystem.readText(path);if(containsIdentifier(content,task.id)&&containsIsoTimestamp(content)){relatedVerificationPaths.push(path)}}if(relatedVerificationPaths.length===0){throw new LifecycleGateError(`Task ${task.id} requires at least one Test, Eval, or Check for six-stage coverage`)}const timestampedEvidence=[];for(const evidenceId of result2.evidence_ids){const path=`${changeDirectory}/artifacts/evidence/${evidenceId}.md`;if(!await context.filesystem.exists(path))continue;const content=await context.filesystem.readText(path);if(containsIdentifier(content,task.id)&&containsIsoTimestamp(content)){timestampedEvidence.push(path)}}if(timestampedEvidence.length===0){throw new LifecycleGateError(`Task ${task.id} requires an Evidence file with the Task id and an ISO date-time for six-stage coverage`)}if(enforceLegacyRiskCounts){assertRiskScaledArtifactCounts(task.id,task.risk,relatedVerificationPaths.length,result2.evidence_ids.length)}}var init_lifecycle_evidence_v2=__esm({"src/lifecycle-evidence-v2.ts"(){"use strict";init_lifecycle_assurance_v2();init_lifecycle_gate_helpers()}});async function activateTaskMacroParents(change,repositories){const specId=change.source.type==="task"?null:change.source.spec_id;const prdId=change.source.type==="prd"?change.source.prd_id:null;if(specId!==null){const{spec}=await repositories.specs.read(specId);if(spec.status==="ready"||spec.status==="blocked"){await repositories.specs.transition(spec.id,"active")}else if(spec.status!=="active"){throw new LifecycleGateError(`SPEC ${spec.id} must be ready, active, or blocked before Task start`)}}if(prdId!==null){const{prd}=await repositories.prds.read(prdId);if(prd.status==="ready"||prd.status==="blocked"){await repositories.prds.transition(prd.id,"active")}else if(prd.status!=="active"){throw new LifecycleGateError(`PRD ${prd.id} must be ready, active, or blocked before Task start`)}}}var init_lifecycle_parent_activation_v2=__esm({"src/lifecycle-parent-activation-v2.ts"(){"use strict";init_lifecycle_assurance_v2()}});async function executionForTask(task,repositories){const canonicalExecutionId=task.plan_ref?.execution_id??task.prepared_plan?.execution_id??null;if(canonicalExecutionId!==null){const{execution}=await repositories.executions.read(canonicalExecutionId);if(!execution.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===task.change_id)){throw new LifecycleGateError(`Execution ${canonicalExecutionId} does not contain Task/Change ${task.id}/${task.change_id}`)}return execution}const executions=(await repositories.executions.list()).filter(execution=>execution.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===task.change_id));if(executions.length!==1){throw new LifecycleGateError(`Task ${task.id} must resolve to exactly one Execution; found ${executions.length}`)}return executions[0]}async function executionForCompletionRun(task,canonicalExecution,run,repositories){if(run.run.execution_id===canonicalExecution.id)return canonicalExecution;if(run.run.continuation_of_run_id===null||run.run.execution_id===null){return canonicalExecution}const{execution}=await repositories.executions.read(run.run.execution_id);const ownsTask=execution.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===task.change_id);if(execution.kind!=="delivery"||execution.origin.type!=="task"||execution.origin.task_id!==task.id||!ownsTask){throw new LifecycleGateError(`Continuation Run ${run.run.run_id} Execution ${execution.id} does not own Task/Change ${task.id}/${task.change_id}`)}return execution}function assertCompletedRunAttribution(run,task,executionId){if(run.finished?.status!=="completed"){throw new LifecycleGateError(`Run ${run.run.run_id} must be completed`)}assertRunAttribution(run,task,executionId)}function assertRunAttribution(run,task,executionId){const mismatches=[(run.records?.findLast(record3=>"phase"in record3)?.phase??run.run.phase)==="execution"||run.run.phase==="planning"&&run.run.work_type==="rework"?null:"phase",run.run.execution_id===executionId?null:"execution_id",run.run.task_id===task.id?null:"task_id",run.run.change_id===task.change_id?null:"change_id"].filter(value=>value!==null);if(mismatches.length>0){throw new LifecycleGateError(`Run ${run.run.run_id} attribution mismatch: ${mismatches.join(", ")}`)}}var init_lifecycle_run_attribution=__esm({"src/lifecycle-run-attribution.ts"(){"use strict";init_lifecycle_assurance_v2()}});function assertAllTerminal(entities,label,terminal="completed"){const incomplete2=entities.filter(entity=>entity.status!==terminal);if(incomplete2.length>0){throw new LifecycleGateError(`${label} is not ${terminal}: ${incomplete2.map(formatLifecycleState).join(", ")}`)}}var init_lifecycle_terminal_state=__esm({"src/lifecycle-terminal-state.ts"(){"use strict";init_lifecycle_assurance_v2();init_lifecycle_gate_helpers()}});var LifecycleV2Gate;var init_lifecycle_v2=__esm({"src/lifecycle-v2.ts"(){"use strict";init_src4();init_editorial_delivery_assurance();init_git_delivery_preflight();init_lifecycle_assurance_v2();init_lifecycle_changed_files();init_lifecycle_evidence_v2();init_lifecycle_gate_helpers();init_lifecycle_parent_activation_v2();init_lifecycle_run_attribution();init_lifecycle_terminal_state();init_lifecycle_assurance_v2();init_lifecycle_gate_helpers();LifecycleV2Gate=class{constructor(filesystem,layout,repositories){this.filesystem=filesystem;this.layout=layout;this.repositories=repositories;if(layout.version===1)throw new TypeError("LifecycleV2Gate requires a modern layout")}filesystem;layout;repositories;async completeTask(id,result2){const{task}=await this.repositories.tasks.read(id);if(task.status!=="verifying"){throw new LifecycleGateError(`Task ${id} must be verifying before completion`)}try{return await this.completeVerifyingTask(task,result2)}catch(error51){if(error51 instanceof LifecycleGateError){await this.repositories.tasks.transition(id,"executing")}throw error51}}async verifyTask(id,evidenceIds){const{task}=await this.repositories.tasks.read(id);if(task.status!=="executing"&&task.status!=="verifying"){throw new LifecycleGateError(`Task ${id} must be executing or verifying before verification`)}const execution=await executionForTask(task,this.repositories);const result2=taskAssurancePreflightResult(evidenceIds);await this.assertEvidenceCoverage(task,result2);const assurance=this.assuranceConfig();await this.assertSixStageCoverage(task,result2,execution.id,assurance===null);if(assurance!==null){await assertTaskAssurancePreflightV1({filesystem:this.filesystem,layout:this.layout,task,evidence_ids:result2.evidence_ids,config:assurance})}return task.status==="verifying"?task:this.repositories.tasks.transition(id,"verifying")}async completeVerifyingTask(task,result2){for(const dependencyId of task.depends_on){const{task:dependency}=await this.repositories.tasks.read(dependencyId).catch(()=>{throw new LifecycleGateError(`Task dependency does not resolve: ${dependencyId}`)});if(dependency.status!=="completed"){throw new LifecycleGateError(`Task dependency must be completed: ${dependencyId} is ${dependency.status}`)}}const{change}=await this.repositories.changes.read(task.change_id);if(!change.task_ids.includes(task.id)){throw new LifecycleGateError(`Change ${change.id} does not own Task ${task.id}`)}if(!new Set(["executing","verifying"]).has(change.status)){throw new LifecycleGateError(`Change ${change.id} is not executing or verifying`)}if(result2.completed_run_id===null){throw new LifecycleGateError(`Completed Task ${task.id} requires a completed Run`)}const run=await this.readRequiredRun(result2.completed_run_id);const canonicalExecution=await executionForTask(task,this.repositories);if(!new Set(["running","verifying"]).has(canonicalExecution.status)){throw new LifecycleGateError(`Execution ${canonicalExecution.id} is not running or verifying`)}const execution=await executionForCompletionRun(task,canonicalExecution,run,this.repositories);if(!new Set(["running","verifying"]).has(execution.status)){throw new LifecycleGateError(`Execution ${execution.id} is not running or verifying`)}assertCompletedRunAttribution(run,task,execution.id);await this.assertEvidenceCoverage(task,result2);const assurance=this.assuranceConfig();await this.assertSixStageCoverage(task,result2,execution.id,assurance===null);if(assurance!==null){const bundle=await readAssuranceBundle(this.filesystem,this.layout,[task],result2.evidence_ids);const effectiveAssurance=effectiveTaskAssurance(task,assurance);const expectedCommit=effectiveAssurance.require_final_commit?await requireFinalProductCandidate(this.filesystem.root,bundle.validations,bundle.evidences,task.write_scopes,task.id,result2.changed_files):null;if(expectedCommit!==null){await assertEditorialCandidateDiff({root:this.filesystem.root,task,signals:effectiveTaskRiskSignals(task),commit:expectedCommit,changedFiles:result2.changed_files})}assertTaskAssuranceV1({config:assurance,task,risk:task.risk,risk_signals:effectiveTaskRiskSignals(task),write_scopes:task.write_scopes,acceptance_ids:task.acceptance_ids,validations:bundle.validations,evidences:bundle.evidences,verifier:verifierFrom(bundle.validations,run.run.agent,run.run.run_id),mutation:mutationFrom(bundle.metadata,task.id),rollback_evidence_id:bundle.evidences.find(evidence=>evidence.id.includes("ROLLBACK"))?.id??null,expected_commit_sha:expectedCommit})}assertChangedFilesInScope(task,result2.changed_files);return this.repositories.tasks.transition(task.id,"completed",result2)}async startTask(id,mode="start"){const{task}=await this.repositories.tasks.read(id);if(this.assuranceConfig()?.require_final_commit===true)await assertGitDeliveryReady(this.filesystem.root);const expected=mode==="resume"?"blocked":mode==="rework"?"failed":"planned";if(task.status!==expected){throw new LifecycleGateError(`Task ${id} must be ${expected} before ${mode}`)}for(const dependencyId of task.depends_on){const dependency=await this.repositories.tasks.read(dependencyId).catch(()=>null);if(dependency===null||dependency.task.status!=="completed"){throw new LifecycleGateError(`Task dependency is not completed: ${dependencyId}`)}}let{change}=await this.repositories.changes.read(task.change_id);const execution=await executionForTask(task,this.repositories);let latestExecution=execution;if(mode!=="start"){if(change.status==="blocked"||change.status==="failed"){change=await this.repositories.changes.transition(change.id,"executing")}if(latestExecution.status==="blocked"||latestExecution.status==="failed"){latestExecution=await this.repositories.executions.transition(latestExecution.id,"running")}}if(change.status!=="executing"){throw new LifecycleGateError(`Change ${change.id} must be executing before Task start`)}if(latestExecution.status!=="running"){throw new LifecycleGateError(`Execution ${latestExecution.id} must be running before Task start`)}await activateTaskMacroParents(change,this.repositories);return this.repositories.tasks.transition(id,"executing")}async failTask(id,result2){const{task}=await this.repositories.tasks.read(id);if(!new Set(["executing","verifying"]).has(task.status)){throw new LifecycleGateError(`Task ${id} must be executing or verifying before failure`)}if(result2.completed_run_id===null){throw new LifecycleGateError(`Failed Task ${id} requires a failed Run`)}const execution=await executionForTask(task,this.repositories);const run=await this.readRequiredRun(result2.completed_run_id);if(run.finished?.status!=="failed"){throw new LifecycleGateError(`Run ${result2.completed_run_id} must be failed`)}assertRunAttribution(run,task,execution.id);assertChangedFilesInScope(task,result2.changed_files);return this.repositories.tasks.transition(id,"failed",result2)}async verifyChange(id){const{change}=await this.repositories.changes.read(id);if(change.status!=="executing"){throw new LifecycleGateError(`Change ${id} must be executing before verification`)}const tasks=await this.tasksForChange(change.id,change.task_ids);const incomplete2=tasks.filter(task=>task.status!=="completed");if(incomplete2.length>0){throw new LifecycleGateError(`Change ${id} has incomplete Tasks: ${incomplete2.map(formatLifecycleState).join(", ")}`)}return this.repositories.changes.transition(id,"verifying")}async completeChange(id,result2){const{change}=await this.repositories.changes.read(id);if(change.status!=="verifying"){throw new LifecycleGateError(`Change ${id} must be verifying before completion`)}const tasks=await this.tasksForChange(change.id,change.task_ids);const incomplete2=tasks.filter(task=>task.status!=="completed");if(incomplete2.length>0){throw new LifecycleGateError(`Change ${id} has incomplete Tasks: ${incomplete2.map(formatLifecycleState).join(", ")}`)}const covered=new Set(tasks.flatMap(task=>task.acceptance_ids));const missing=change.acceptance_ids.filter(acceptanceId=>!covered.has(acceptanceId));if(missing.length>0){throw new LifecycleGateError(`Change ${id} has uncovered Acceptance Criteria: ${missing.join(", ")}`)}for(const task of tasks){if(task.result===null)throw new LifecycleGateError(`Task ${task.id} has no terminal result`);await this.assertEvidenceCoverage(task,task.result)}return this.repositories.changes.transition(id,"completed",result2)}async verifyExecution(id){const{execution}=await this.repositories.executions.read(id);if(execution.status!=="running"){throw new LifecycleGateError(`Execution ${id} must be running before verification`)}await this.assertExecutionDescendantsComplete(execution.id,execution.dag.nodes);return this.repositories.executions.transition(id,"verifying")}async completeExecution(id,result2){const{execution}=await this.repositories.executions.read(id);let completedExecution;if(execution.status==="verifying"){await this.assertExecutionDescendantsComplete(execution.id,execution.dag.nodes);const changeIds=[...new Set(execution.dag.nodes.map(node=>node.change_id))];for(const changeId of changeIds){const{change}=await this.repositories.changes.read(changeId);if(change.status!=="completed"){throw new LifecycleGateError(`Execution Change must be completed: ${formatLifecycleState(change)}`)}}completedExecution=await this.repositories.executions.transition(id,"completed",result2)}else if(execution.status==="completed"){completedExecution=execution}else{throw new LifecycleGateError(`Execution ${id} must be verifying before completion`)}await this.reconcileCompletedExecutionOrigin(completedExecution);return completedExecution}async reconcileCompletedExecutionOrigin(execution){if(execution.origin.type==="prd"){const{prd}=await this.repositories.prds.read(execution.origin.prd_id);if(prd.status==="active")await this.deliverPrd(prd.id);else if(prd.status!=="delivered"){throw new LifecycleGateError(`Completed Execution ${execution.id} has non-deliverable PRD ${prd.id}: ${prd.status}`)}}else if(execution.origin.type==="spec"){const{spec}=await this.repositories.specs.read(execution.origin.spec_id);if(spec.status==="active")await this.deliverSpec(spec.id);else if(spec.status!=="delivered"){throw new LifecycleGateError(`Completed Execution ${execution.id} has non-deliverable SPEC ${spec.id}: ${spec.status}`)}}}async deliverSpec(id){const{spec}=await this.repositories.specs.read(id);if(spec.status!=="active"){throw new LifecycleGateError(`SPEC ${id} must be active before delivery`)}const[changes,executions]=await Promise.all([this.repositories.changes.list(),this.repositories.executions.list()]);const descendants=changes.filter(change=>change.source.type==="spec"&&change.source.spec_id===id||change.source.type==="prd"&&change.source.spec_id===id);const descendantChangeIds=new Set(descendants.map(change=>change.id));const relatedExecutions=executions.filter(execution=>execution.origin.type==="spec"&&execution.origin.spec_id===id||execution.dag.nodes.some(node=>descendantChangeIds.has(node.change_id)));if(descendants.length===0||relatedExecutions.length===0){throw new LifecycleGateError(`SPEC ${id} has no materialized Change and Execution`)}assertAllTerminal(descendants,"SPEC Change");assertAllTerminal(relatedExecutions,"SPEC Execution");const assurance=this.assuranceConfig();if(assurance!==null){const tasks=await this.readTasks(relatedExecutions.flatMap(item=>item.dag.nodes.map(node=>node.task_id)));await this.assertDeliveryAssurance("spec",spec.acceptance_ids,[],tasks,assurance)}return this.repositories.specs.transition(id,"delivered")}async deliverPrd(id){const{prd}=await this.repositories.prds.read(id);if(prd.status!=="active"){throw new LifecycleGateError(`PRD ${id} must be active before delivery`)}const[specs,changes,executions]=await Promise.all([this.repositories.specs.list(),this.repositories.changes.list(),this.repositories.executions.list()]);const executionId=prd.prepared_plan?.execution_id??prd.plan_ref?.execution_id;if(executionId===void 0){throw new LifecycleGateError(`PRD ${id} has no prepared plan or plan reference`)}const selectedExecution=executions.find(execution=>execution.id===executionId&&execution.origin.type==="prd"&&execution.origin.prd_id===id);if(selectedExecution===void 0){throw new LifecycleGateError(`PRD ${id} plan Execution does not resolve: ${executionId}`)}const selectedChangeIds=new Set(selectedExecution.dag.nodes.map(node=>node.change_id));const directChanges=changes.filter(change=>selectedChangeIds.has(change.id));const selectedSpecIds=prd.prepared_plan===null?new Set(directChanges.flatMap(change=>change.source.type==="prd"&&change.source.prd_id===id?[change.source.spec_id]:[])):new Set(specIdsForPrdPlanV2(prd.prepared_plan,id));const childSpecs=specs.filter(spec=>spec.prd_id===id&&selectedSpecIds.has(spec.id));const directExecutions=[selectedExecution];if(childSpecs.length===0){throw new LifecycleGateError(`PRD ${id} requires at least one SPEC`)}for(const spec of childSpecs){if(spec.status==="active")await this.deliverSpec(spec.id)}const refreshedSpecs=(await this.repositories.specs.list()).filter(spec=>spec.prd_id===id&&selectedSpecIds.has(spec.id));assertAllTerminal(refreshedSpecs,"PRD SPEC","delivered");assertAllTerminal(directChanges,"PRD Change");assertAllTerminal(directExecutions,"PRD Execution");const assurance=this.assuranceConfig();if(assurance!==null){const tasks=await this.readTasks(selectedExecution.dag.nodes.map(node=>node.task_id));const metadata2=prd;await this.assertDeliveryAssurance("prd",metadata2.acceptance_ids??refreshedSpecs.flatMap(spec=>spec.acceptance_ids),prd.outcome_ids,tasks,assurance)}return this.repositories.prds.transition(id,"delivered")}async cancelTask(id,summary,completedRunId=null){const{task}=await this.repositories.tasks.read(id);this.assertCancellable([task],["draft","planned","executing","verifying","blocked"],"Task");const changes=(await this.repositories.changes.list()).filter(change=>change.id===task.change_id&&change.source.type==="task"&&change.source.task_id===id);const executions=(await this.repositories.executions.list()).filter(execution=>execution.origin.type==="task"&&execution.origin.task_id===id||execution.dag.nodes.some(node=>node.task_id===id&&node.change_id===task.change_id));const cascade=await this.cancelDescendants([],changes,executions,`Task ${id} was cancelled: ${summary}`,completedRunId);const cancelledTask=(await this.repositories.tasks.read(id)).task;return{task:cancelledTask,cascade}}async cancelPrd(id){const{prd}=await this.repositories.prds.read(id);this.assertCancellable([prd],["draft","ready","active","blocked"],"PRD");const specs=(await this.repositories.specs.list()).filter(spec=>spec.prd_id===id);const specIds=new Set(specs.map(spec=>spec.id));const changes=(await this.repositories.changes.list()).filter(change=>change.source.type==="prd"&&change.source.prd_id===id||change.source.type==="spec"&&specIds.has(change.source.spec_id));const cascade=await this.cancelDescendants(specs,changes,(await this.repositories.executions.list()).filter(execution=>execution.origin.type==="prd"&&execution.origin.prd_id===id||execution.origin.type==="spec"&&specIds.has(execution.origin.spec_id)),`PRD ${id}`);const cancelledPrd=prd.status==="cancelled"?prd:await this.repositories.prds.transition(id,"cancelled");return{prd:cancelledPrd,cascade}}async cancelSpec(id){const{spec}=await this.repositories.specs.read(id);this.assertCancellable([spec],["draft","ready","active","blocked"],"SPEC");const changes=(await this.repositories.changes.list()).filter(change=>change.source.type==="spec"&&change.source.spec_id===id||change.source.type==="prd"&&change.source.spec_id===id);const cascade=await this.cancelDescendants([],changes,(await this.repositories.executions.list()).filter(execution=>execution.origin.type==="spec"&&execution.origin.spec_id===id),`SPEC ${id}`);const cancelledSpec=spec.status==="cancelled"?spec:await this.repositories.specs.transition(id,"cancelled");return{spec:cancelledSpec,cascade}}async cancelDescendants(specs,changes,originExecutions,parent,completedRunId=null){const changeIds=new Set(changes.map(change=>change.id));const allExecutions=await this.repositories.executions.list();const executions=[...new Map([...originExecutions,...allExecutions.filter(execution=>execution.dag.nodes.some(node=>changeIds.has(node.change_id)))].map(execution=>[execution.id,execution])).values()];const taskIds=new Set([...changes.flatMap(change=>change.task_ids),...executions.flatMap(execution=>execution.dag.nodes.map(node=>node.task_id))]);const tasks=(await this.repositories.tasks.list()).filter(task=>taskIds.has(task.id));const reason=`Cancelled automatically because ${parent} was cancelled.`;this.assertCancellable(tasks.filter(task=>!isTerminalLifecycleStatus(task.status)),["draft","planned","executing","verifying","blocked"],"Task");this.assertCancellable(changes.filter(change=>!isTerminalLifecycleStatus(change.status)),["draft","planned","executing","verifying","blocked"],"Change");this.assertCancellable(executions.filter(execution=>!isTerminalLifecycleStatus(execution.status)),["planned","running","paused","verifying","blocked"],"Execution");this.assertCancellable(specs.filter(spec=>!isTerminalLifecycleStatus(spec.status)),["draft","ready","active","blocked"],"SPEC");const cancelledTasks=await Promise.all(tasks.filter(task=>!isTerminalLifecycleStatus(task.status)).map(task=>this.repositories.tasks.transition(task.id,"cancelled",{summary:reason,changed_files:[],evidence_ids:[],completed_run_id:completedRunId})));const cancelledChanges=await Promise.all(changes.filter(change=>!isTerminalLifecycleStatus(change.status)).map(change=>this.repositories.changes.transition(change.id,"cancelled",reason)));const cancelledExecutions=await Promise.all(executions.filter(execution=>!isTerminalLifecycleStatus(execution.status)).map(execution=>this.repositories.executions.transition(execution.id,"cancelled",reason)));const cancelledSpecs=await Promise.all(specs.filter(spec=>!isTerminalLifecycleStatus(spec.status)).map(spec=>this.repositories.specs.transition(spec.id,"cancelled")));return{specs:cancelledSpecs,tasks:cancelledTasks,changes:cancelledChanges,executions:cancelledExecutions}}assertCancellable(entities,cancellable,entity){for(const item of entities){if(item.status==="cancelled"||cancellable.includes(item.status))continue;throw new LifecycleGateError(`${entity} ${item.id} cannot be cancelled from status ${item.status}`)}}assuranceConfig(){const config2=this.layout.projectConfig?.assurance;return config2?.version===1?config2:null}async readTasks(ids){return Promise.all([...new Set(ids)].map(async id=>(await this.repositories.tasks.read(id)).task))}async assertDeliveryAssurance(origin,acceptanceIds,outcomeIds,tasks,config2){const bundle=await readAssuranceBundle(this.filesystem,this.layout,tasks);const expected=config2.require_final_commit?await resolveFinalProductCandidate(this.filesystem.root,bundle.validations,bundle.evidences):null;const validations=expected===null?bundle.validations:bundle.validations.filter(artifact=>artifact.commit_sha===expected);const evidences=expected===null?bundle.evidences:bundle.evidences.filter(artifact=>artifact.commit_sha===expected);const verifier=await this.deliveryVerifier(validations,tasks);assertDeliveryAssuranceV1({origin,config:config2,acceptance_ids:acceptanceIds,outcome_ids:outcomeIds,validations,evidences,verifier,mutation:deliveryMutationFrom(bundle.metadata,tasks.map(task=>task.id)),rollback_evidence_id:evidences.find(evidence=>evidence.id.includes("ROLLBACK"))?.id??null,expected_commit_sha:expected})}async deliveryVerifier(validations,tasks){for(const review of validations.filter(item=>isReviewKind(item.kind))){const task=tasks.find(item=>item.id===review.task_id);if(task?.result?.completed_run_id==null)continue;const run=await this.readRequiredRun(task.result.completed_run_id);const approval=verifierFrom([review],run.run.agent,run.run.run_id);if(approval!==null)return approval}return null}async tasksForChange(changeId,expectedIds){const tasks=await Promise.all(expectedIds.map(taskId=>this.repositories.tasks.read(taskId)));for(const{task}of tasks){if(task.change_id!==changeId){throw new LifecycleGateError(`Task ${task.id} does not belong to Change ${changeId}`)}}return tasks.map(({task})=>task)}async readRequiredRun(id){try{return await this.repositories.runs.read(id)}catch(error51){throw new LifecycleGateError(`Run ${id} does not resolve: ${error51 instanceof Error?error51.message:String(error51)}`)}}async assertEvidenceCoverage(task,result2){await assertTaskEvidenceCoverage({filesystem:this.filesystem,layout:this.layout,repositories:this.repositories},task,result2)}async assertSixStageCoverage(task,result2,executionId,enforceLegacyRiskCounts=true){const assurance=this.assuranceConfig();const signals=effectiveTaskRiskSignals(task);if(task.assurance_risk_signals_source==="explicit"&&task.assurance_risk_signals?.editorial_delivery===true&&assurance===null)throw new LifecycleGateError("Editorial delivery requires assurance.version: 1");await assertTaskSixStageCoverage({filesystem:this.filesystem,layout:this.layout,repositories:this.repositories},task,result2,executionId,enforceLegacyRiskCounts,assurance===null||!assertEditorialDeliveryEligibility(task,signals))}async assertExecutionDescendantsComplete(executionId,nodes){for(const node of nodes){const{task}=await this.repositories.tasks.read(node.task_id);if(task.change_id!==node.change_id){throw new LifecycleGateError(`Execution ${executionId} DAG ownership mismatch for ${task.id}`)}if(task.status!=="completed"){throw new LifecycleGateError(`Execution Task must be completed: ${formatLifecycleState(task)}`)}}}}}});function inferredOrphanFailureTask(fold,tasks){if(fold.finished?.status!=="failed"||fold.run.client_thread_id!==null||fold.run.client_turn_id!==null||fold.finalization_decision!=null||effectiveRunV2Role(fold.run)!=="orchestrator")return void 0;return tasks.find(task=>{const result2=task.result;return task.id===fold.run.task_id&&task.status==="failed"&&result2!=null&&result2.completed_run_id===fold.run.run_id&&result2.changed_files.length===0&&result2.evidence_ids.length===0&&task.status_reason===`Run ${fold.run.run_id} failed and closed its operational lifecycle.`})}var init_inferred_orphan_failure=__esm({"src/inferred-orphan-failure.ts"(){"use strict";init_src3()}});async function hostTerminalOnlyPreflight(composition,filesystem){let active;try{active=await new LifecycleManifestStore(filesystem).readActiveWork()}catch{return{kind:"full"}}const items=activeWorkItems(active);if(items===null)return{kind:"full"};const activeRuns=items.filter(item=>item.kind==="run"&&item.status==="running");const operationalOwners=items.filter(isOperationalOwner);if(operationalOwners.some(owner=>!activeRuns.some(run=>run.relations.includes(owner.id)))){return{kind:"full"}}let current;try{current=await Promise.all(activeRuns.map(item=>composition.runs.read(item.id)))}catch{return{kind:"full"}}const observedTerminalRunIds=current.filter(fold=>fold.finished!==null).map(fold=>fold.run.run_id);if(observedTerminalRunIds.length>0){return{kind:"full",observed_terminal_run_ids:observedTerminalRunIds}}const codex=current.filter(fold=>isCodexTelemetryClient(fold.run.client));if(codex.some(fold=>fold.run.client_thread_id===null||fold.run.client_turn_id===null)){return{kind:"full"}}if(codex.length>0){const activity=await listCodexInvocationReconciliationActivity(filesystem.root,{threadIds:codex.map(fold=>fold.run.client_thread_id),invocations:codex.map(fold=>({threadId:fold.run.client_thread_id,turnId:fold.run.client_turn_id}))});const terminal=new Set(activity.lifecycles.filter(item=>item.finishedAt!==null&&item.status!=="active").map(item=>`${item.sessionId}:${item.turnId}`));if(codex.some(fold=>terminal.has(`${fold.run.client_thread_id}:${fold.run.client_turn_id}`))){return{kind:"full"}}}return{kind:"no-op",result:{runs:[],orphaned_executions:[],orphaned_interaction_executions:[],orphaned_tasks:[],orphaned_execution_entities:[],orphaned_owner_entities:[],reconciliations:[],reconciliation_errors:[],unresolved_running_run_ids:current.map(fold=>fold.run.run_id)}}}function activeWorkItems(value){if(typeof value!=="object"||value===null||value.schema_version!==1||typeof value.updated_at!=="string"||!Number.isFinite(Date.parse(value.updated_at))||!Array.isArray(value.items))return null;const items=value.items;const parsed=[];for(const item of items){if(typeof item!=="object"||item===null)return null;const candidate=item;if(typeof candidate.kind!=="string"||candidate.kind.length===0||typeof candidate.id!=="string"||candidate.id.length===0||typeof candidate.status!=="string"||candidate.status.length===0||candidate.relations!==void 0&&(!Array.isArray(candidate.relations)||candidate.relations.some(id=>typeof id!=="string")))return null;parsed.push({kind:candidate.kind,id:candidate.id,status:candidate.status,relations:candidate.relations??[]})}return parsed}function isOperationalOwner(item){return item.kind==="task"&&["executing","verifying"].includes(item.status)||item.kind==="change"&&["executing","verifying"].includes(item.status)||item.kind==="execution"&&["running","paused","verifying"].includes(item.status)||item.kind==="spec"&&item.status==="active"||item.kind==="prd"&&item.status==="active"}var init_open_work_host_preflight=__esm({"src/open-work-host-preflight.ts"(){"use strict";init_src2();init_src6();init_record_codex_telemetry()}});function runDepth(fold,runs){const parentById=new Map(runs.map(candidate=>[candidate.run.run_id,candidate.run.parent_run_id]));let depth=0;let parent=fold.run.parent_run_id;const seen=new Set([fold.run.run_id]);while(parent!==null&&!seen.has(parent)){seen.add(parent);depth+=1;parent=parentById.get(parent)??null}return depth}function terminalSubjectIds(fold){const role=effectiveRunV2Role(fold.run);if(role==="orchestrator"&&fold.run.entrypoint==="task"){return fold.run.task_id===null?[]:[fold.run.task_id]}if(role==="orchestrator"){return[fold.run.spec_id,fold.run.prd_id].filter(id=>id!==null)}return[]}var init_open_work_run_topology=__esm({"src/open-work-run-topology.ts"(){"use strict";init_src3()}});function recoveryReason(id){return`Macro Execution ${id} has no unfinished Run or active descendant after the reconciliation grace period; terminal incomplete DAG work requires explicit recovery.`}async function reconcileExplicitOrphanedMacroExecution(catalog,runs,composition,now,executionId){if(executionId===void 0)return void 0;const execution=catalog.executions.find(candidate=>candidate.id===executionId);if(!isEligibleMacro(execution,catalog,runs,now))return void 0;const reason=recoveryReason(execution.id);const clock=new SystemClock;if(execution.status!=="blocked")await composition.executions.transition(execution.id,"blocked",null,clock,reason);const ancestors=await blockMacroAncestors(execution,catalog,composition,clock,reason);return{execution:(await composition.executions.read(execution.id)).execution,ancestors}}function isEligibleMacro(execution,catalog,runs,now){if(execution===void 0||execution.kind!=="delivery"||execution.origin.type==="task"||!(["running","verifying"].includes(execution.status)||execution.status==="blocked"&&execution.status_reason===recoveryReason(execution.id))||!overdue(execution,now))return false;const origin=execution.origin;if(origin.type==="prd"&&!catalog.prds.some(prd=>prd.id===origin.prd_id))return false;if(origin.type==="spec"&&!catalog.specs.some(spec=>spec.id===origin.spec_id))return false;const tasks=execution.dag.nodes.map(node=>catalog.tasks.find(task=>task.id===node.task_id));if(!tasks.every(task=>task!==void 0&&TERMINAL_TASK_STATUSES.has(task.status)))return false;if(!tasks.some(task=>task!==void 0&&["blocked","failed","cancelled"].includes(task.status)))return false;const taskIds=new Set(execution.dag.nodes.map(node=>node.task_id));const relatedRoots=runs.filter(run=>run.run.execution_id===execution.id||run.run.task_id!==null&&taskIds.has(run.run.task_id));return!relatedRoots.some(run=>run.finished===null||activeDescendantRuns(run.run.run_id,runs).length>0)}function overdue(execution,now){const startedAt=Date.parse(execution.started_at??execution.updated_at??execution.created_at);return Number.isFinite(startedAt)&&now.getTime()-startedAt>=ORPHANED_EXECUTION_GRACE_MS}async function blockMacroAncestors(execution,catalog,composition,clock,reason){const ancestors=[];const specIds=macroSpecIds(execution,catalog);for(const specId of specIds){const spec=catalog.specs.find(candidate=>candidate.id===specId);if(spec===void 0||ancestorHasOtherWork(execution,catalog,spec.id,void 0))continue;if(spec.status==="active")ancestors.push(await composition.specs.transition(spec.id,"blocked",clock,reason));else if(spec.status==="blocked"&&spec.status_reason===reason)ancestors.push(spec)}const prdId=macroPrdId(execution,catalog,specIds);const prd=prdId===void 0?void 0:catalog.prds.find(candidate=>candidate.id===prdId);if(prd!==void 0&&!ancestorHasOtherWork(execution,catalog,void 0,prd.id)){if(prd.status==="active")ancestors.push(await composition.prds.transition(prd.id,"blocked",clock,reason));else if(prd.status==="blocked"&&prd.status_reason===reason)ancestors.push(prd)}return ancestors}function ancestorHasOtherWork(selected,catalog,specId,prdId){const selectedTasks=new Set(selected.dag.nodes.map(node=>node.task_id));const linkedSpec=id=>specId===id||prdId!==void 0&&catalog.specs.some(spec=>spec.id===id&&spec.prd_id===prdId);const changes=catalog.changes.filter(change=>{const source=change.source;return(source.type==="spec"||source.type==="prd")&&(source.spec_id!==null?linkedSpec(source.spec_id):source.type==="prd"&&prdId!==void 0&&source.prd_id===prdId)});if(changes.some(change=>change.task_ids.some(id=>{const task=catalog.tasks.find(item=>item.id===id);return!selectedTasks.has(id)&&(task===void 0||!TERMINAL_TASK_STATUSES.has(task.status))})))return true;return catalog.executions.some(other=>{if(other.id===selected.id||!OPEN_EXECUTION_STATUSES.has(other.status))return false;const specs=macroSpecIds(other,catalog);if(specId!==void 0)return specs.includes(specId);return macroPrdId(other,catalog,specs)===prdId||other.dag.nodes.some(node=>changes.some(change=>change.id===node.change_id))})}function macroSpecIds(execution,catalog){const origin=execution.origin;if(origin.type==="spec")return[origin.spec_id];if(origin.type!=="prd")return[];const changes=new Map(catalog.changes.map(change=>[change.id,change]));const ids=execution.dag.nodes.flatMap(node=>{const source=node.change_id===void 0?void 0:changes.get(node.change_id)?.source;if(source===void 0||source.type!=="spec"&&source.type!=="prd"||source.spec_id===null)return[];return[source.spec_id]});return[...new Set(ids)].filter(id=>catalog.specs.some(spec=>spec.id===id&&spec.prd_id===origin.prd_id))}function macroPrdId(execution,catalog,specIds){if(execution.origin.type==="prd")return execution.origin.prd_id;if(execution.origin.type!=="spec")return void 0;const spec=catalog.specs.find(candidate=>candidate.id===specIds[0]);return spec?.prd_id??void 0}async function blockOrphanedStandaloneExecutions(catalog,runs,composition,now,scope){const ids=new Set(orphanedStandaloneExecutionIds(catalog,runs,now).filter(id=>{const execution=catalog.executions.find(candidate=>candidate.id===id);return execution!==void 0&&(scope===void 0||scope.matchesExecution(execution))}));if(ids.size===0)return[];const clock=new SystemClock;const taskById=new Map(catalog.tasks.map(task=>[task.id,task]));const changeById=new Map(catalog.changes.map(change=>[change.id,change]));const blocked2=[];for(const id of ids){const execution=catalog.executions.find(item=>item.id===id);if(execution===void 0)continue;const reason=`Execution ${id} has no active orchestrator agent call after the reconciliation grace period.`;for(const node of execution.dag.nodes){const task=taskById.get(node.task_id);if(task!==void 0&&(scope===void 0||scope.matchesTask(task.id))&&["executing","verifying"].includes(task.status)){await composition.tasks.transition(task.id,"blocked",null,clock,reason)}const change=changeById.get(node.change_id);if(change!==void 0&&["executing","verifying"].includes(change.status)){const latestTasks=await Promise.all(change.task_ids.map(async taskId=>(await composition.tasks.read(taskId)).task));if(latestTasks.every(candidate=>["blocked","completed","failed","cancelled"].includes(candidate.status)))await composition.changes.transition(change.id,"blocked",null,clock,reason)}}if(execution.status!=="blocked")await composition.executions.transition(id,"blocked",null,clock,reason);blocked2.push((await composition.executions.read(id)).execution)}return blocked2}function orphanedStandaloneExecutionIds(catalog,runs,now=new Date,includePlanned=false){return catalog.executions.flatMap(execution=>{if(execution.origin.type!=="task"||!["running","verifying",...includePlanned?["planned"]:[]].includes(execution.status)){return[]}const startedAt=Date.parse(execution.started_at??execution.updated_at??execution.created_at);if(!Number.isFinite(startedAt)||now.getTime()-startedAt<ORPHANED_EXECUTION_GRACE_MS){return[]}const taskIds=new Set(execution.dag.nodes.map(node=>node.task_id));const hasActiveOrchestratorRun=runs.some(run=>{const required2=[run.finished===null,effectiveRunV2Role(run.run)==="orchestrator",run.run.parent_run_id===null,run.run.entrypoint==="task"];if(!required2.every(Boolean))return false;return run.run.execution_id===execution.id||run.run.task_id!==null&&taskIds.has(run.run.task_id)});return hasActiveOrchestratorRun?[]:[execution.id]})}var ORPHANED_EXECUTION_GRACE_MS,TERMINAL_TASK_STATUSES,OPEN_EXECUTION_STATUSES;var init_orphaned_macro_reconciliation=__esm({"src/orphaned-macro-reconciliation.ts"(){"use strict";init_src();init_src3();init_run_hierarchy();ORPHANED_EXECUTION_GRACE_MS=10*60*1e3;TERMINAL_TASK_STATUSES=new Set(["blocked","completed","failed","cancelled"]);OPEN_EXECUTION_STATUSES=new Set(["planned","running","paused","verifying"])}});async function reconcileOpenWork(parsed,composition,lifecycle,filesystem){const hostTerminalOnly=parsed.flags?.has("host-terminal-only")??false;let observedTerminalRunIds=[];if(hostTerminalOnly){const preflight=await hostTerminalOnlyPreflight(composition,filesystem);if(preflight.kind==="no-op")return preflight.result;observedTerminalRunIds=preflight.observed_terminal_run_ids??[];if(observedTerminalRunIds.length>0){await Promise.all(observedTerminalRunIds.map(async runId=>{const current=await composition.runs.read(runId);if(isReconcilableCodexClient(current.run.client,false)&¤t.run.client_thread_id!==null&¤t.run.client_turn_id!==null)await recordCodexTelemetryIfAvailable(current,composition,filesystem)}));return{runs:[],observed_terminal_runs:observedTerminalRunIds.map(run_id=>({run_id})),orphaned_executions:[],orphaned_interaction_executions:[],orphaned_tasks:[],orphaned_execution_entities:[],orphaned_owner_entities:[],reconciliations:[],reconciliation_errors:[],unresolved_running_run_ids:[]}}}let runs=await composition.runs.list();const orphanScope=authorizedOrphanScope(parsed);if(!hostTerminalOnly&&orphanScope?.exactExecutionId!==void 0){const executions2=await composition.executions.list();const selected=executions2.find(item=>item.id===orphanScope.exactExecutionId);if(selected?.kind==="delivery"&&selected.origin.type!=="task"){const[tasks2,changes2,specs2,prds2]=await Promise.all([composition.tasks.list(),composition.changes.list(),composition.specs.list(),composition.prds.list()]);const recovered=await reconcileExplicitOrphanedMacroExecution({tasks:tasks2,changes:changes2,executions:executions2,specs:specs2,prds:prds2},runs,composition,new Date,selected.id);return{runs:[],observed_terminal_runs:[],orphaned_interaction_executions:[],orphaned_tasks:[],reconciliations:[],reconciliation_errors:[],orphaned_executions:recovered===void 0?[]:[recovered.execution.id],orphaned_execution_entities:recovered===void 0?[]:[recovered.execution],orphaned_owner_entities:recovered?.ancestors??[],unresolved_running_run_ids:runs.filter(run=>run.finished===null&&run.run.execution_id===selected.id).map(run=>run.run.run_id)}}}const runningCodex=runs.filter(fold=>[fold.finished===null,isReconcilableCodexClient(fold.run.client,orphanScope!==void 0),orphanScope===void 0?fold.run.client_thread_id!==null:orphanScope.matchesRun(fold)].every(Boolean)).sort((left,right)=>runDepth(right,runs)-runDepth(left,runs));const threadIds=runningCodex.flatMap(fold=>typeof fold.run.client_thread_id==="string"?[fold.run.client_thread_id]:[]);const invocations=runningCodex.flatMap(fold=>{const threadId=fold.run.client_thread_id;const turnId=fold.run.client_turn_id;return typeof threadId==="string"&&typeof turnId==="string"?[{threadId,turnId}]:[]});const{lifecycles:localLifecycles,activeInvocations}=threadIds.length===0?{lifecycles:[],activeInvocations:[]}:await listCodexInvocationReconciliationActivity(filesystem.root,{threadIds,invocations});const localByInvocation=new Map(localLifecycles.map(item=>[`${item.sessionId}:${item.turnId}`,item]));const closedRuns=[];const orphanedRootRunIds=new Set;const reconciliationStartedAt=new Date;for(const fold of runningCodex){if((await composition.runs.read(fold.run.run_id)).finished!==null)continue;const local=localByInvocation.get(`${fold.run.client_thread_id??""}:${fold.run.client_turn_id??""}`);const completedLocally=(local?.status==="completed"||local?.status==="cancelled"||local?.status==="interrupted"||local?.status==="failed")&&local.finishedAt!==null;const orphaned=!hostTerminalOnly&&(isOrphanedCodexRun(fold,activeInvocations,reconciliationStartedAt)||orphanScope!==void 0&&isExplicitLegacyNoHostOrphan(fold,reconciliationStartedAt));if(!completedLocally&&!orphaned)continue;if(orphaned)orphanedRootRunIds.add(fold.run.run_id);const role=effectiveRunV2Role(fold.run);const activeChildren=activeDescendantRuns(fold.run.run_id,runs);if(role==="orchestrator"&&activeChildren.length>0){if(local?.status!=="cancelled")continue;await cancelActiveDescendantRuns2(activeChildren,composition,parsed);runs=await composition.runs.list()}let current=completedLocally?await recordCodexTelemetryIfAvailable(fold,composition,filesystem):fold;if(current.effective_usage_records.length===0){await composition.runs.appendRecord(unavailableUsageRecord(current,parsed,current.records.length+1));current=await composition.runs.read(current.run.run_id)}const finished=runFinishedV2Schema.parse({schema_version:2,event_id:`${current.run.run_id}:${String(current.records.length+1).padStart(6,"0")}`,run_id:current.run.run_id,sequence:current.records.length+1,occurred_at:completedLocally?local.finishedAt:new Date().toISOString(),type:"run.finished",phase:latestRunV2Phase(current.records),status:completedLocally&&local?.status==="cancelled"?"cancelled":completedLocally&&local?.status==="failed"?"failed":completedLocally?"completed":"failed"});foldRunV2Records([...current.records,finished]);await composition.runs.appendRecord(finished);const refreshed=await composition.runs.read(current.run.run_id);closedRuns.push(refreshed);runs=replaceRunSnapshot(runs,refreshed)}let[tasks,changes,executions,specs,prds]=await Promise.all([composition.tasks.list(),composition.changes.list(),composition.executions.list(),composition.specs.list(),composition.prds.list()]);let catalog={tasks,changes,executions,specs,prds};const explicitlyCancelled=hostTerminalOnly?[]:await closeExplicitlyCancelledTaskRoots(runs,catalog,composition,parsed,orphanScope);if(explicitlyCancelled.length>0){closedRuns.push(...explicitlyCancelled);runs=await composition.runs.list()}const activeSubjectIds=activeLifecycleSubjectIds(runs.filter(item=>item.finished===null&&!(!hostTerminalOnly&&orphanScope?.matchesRun(item)&&isOrphanedCodexRun(item,activeInvocations,reconciliationStartedAt))),catalog);const operationalSubjectIds=terminalReconciliationSubjectIds(catalog);const inferredRepairIds=new Set;if(!hostTerminalOnly&&orphanScope!==void 0){for(const fold of runs){const task=inferredOrphanFailureTask(fold,catalog.tasks);if(task===void 0||!orphanScope.matchesRun(fold)||activeSubjectIds.has(task.id)||activeDescendantRuns(fold.run.run_id,runs).length>0)continue;inferredRepairIds.add(fold.run.run_id);orphanedRootRunIds.add(fold.run.run_id);operationalSubjectIds.add(task.id)}}const reconciliations=[];const reconciliationErrors=[];const reconciledSubjectIds=new Set;const terminal=runs.filter(fold=>fold.finished!==null&&terminalSubjectIds(fold).some(id=>operationalSubjectIds.has(id))&&(orphanScope===void 0||orphanScope.matchesRun(fold))).sort((left,right)=>(right.finished?.occurred_at??right.run.occurred_at).localeCompare(left.finished?.occurred_at??left.run.occurred_at));for(const fold of terminal){const subjects=terminalSubjectIds(fold);if(subjects.length===0||subjects.some(id=>activeSubjectIds.has(id))||subjects.every(id=>reconciledSubjectIds.has(id))){continue}try{if(inferredRepairIds.has(fold.run.run_id)){const task=inferredOrphanFailureTask(fold,catalog.tasks);if(task!==void 0)await lifecycle.startTask(task.id,"rework")}reconciliations.push(await reconcileFinishedRunLifecycle(fold,composition,lifecycle,{...inferredRepairIds.has(fold.run.run_id)?{}:{catalog},candidateRuns:runs,...orphanedRootRunIds.has(fold.run.run_id)?{requestedOutcome:"blocked",forceRequestedOutcome:true,summary:"Explicit orphan reconciliation found no active host invocation or terminal work outcome; repair is required before resuming"}:{}}))}catch(error51){const message=error51 instanceof Error?error51.message:String(error51);reconciliations.push({...await snapshotRunLifecycle(fold,composition,catalog),status:"deferred",error:message});reconciliationErrors.push({run_id:fold.run.run_id,error:message})}subjects.forEach(id=>{reconciledSubjectIds.add(id)})}[tasks,changes,executions,specs,prds]=await Promise.all([composition.tasks.list(),composition.changes.list(),composition.executions.list(),composition.specs.list(),composition.prds.list()]);catalog={tasks,changes,executions,specs,prds};const orphanedExecutions=hostTerminalOnly?[]:await blockOrphanedStandaloneExecutions(catalog,runs,composition,reconciliationStartedAt,orphanScope);const orphanedInteractionExecutions=hostTerminalOnly?[]:await blockOrphanedInteractionExecutions(catalog,runs,composition,reconciliationStartedAt,orphanScope);const orphanedMacro=hostTerminalOnly?void 0:await reconcileExplicitOrphanedMacroExecution(catalog,runs,composition,reconciliationStartedAt,orphanScope?.exactExecutionId);const orphanedOwnerEntities=await readOrphanedExecutionOwners([...orphanedExecutions,...orphanedInteractionExecutions],composition);return{runs:closedRuns,observed_terminal_runs:observedTerminalRunIds.map(run_id=>({run_id})),orphaned_executions:[...orphanedExecutions.map(execution=>execution.id),...orphanedMacro===void 0?[]:[orphanedMacro.execution.id]],orphaned_interaction_executions:orphanedInteractionExecutions.map(execution=>execution.id),orphaned_tasks:[],orphaned_execution_entities:[...orphanedExecutions,...orphanedInteractionExecutions,...orphanedMacro===void 0?[]:[orphanedMacro.execution]],orphaned_owner_entities:[...orphanedOwnerEntities,...orphanedMacro?.ancestors??[]],reconciliations,reconciliation_errors:reconciliationErrors,unresolved_running_run_ids:runs.filter(fold=>fold.finished===null).map(fold=>fold.run.run_id)}}function replaceRunSnapshot(runs,refreshed){return runs.map(fold=>fold.run.run_id===refreshed.run.run_id?refreshed:fold)}async function readOrphanedExecutionOwners(executions,composition){const taskIds=new Set;const changeIds=new Set;for(const execution of executions){for(const node of execution.dag.nodes){taskIds.add(node.task_id);if(node.change_id!==void 0)changeIds.add(node.change_id)}}return Promise.all([...[...taskIds].map(async id=>(await composition.tasks.read(id)).task),...[...changeIds].map(async id=>(await composition.changes.read(id)).change)])}async function closeExplicitlyCancelledTaskRoots(runs,catalog,composition,parsed,scope){const cancelledTaskIds=new Set(catalog.tasks.filter(task=>task.status==="cancelled").map(task=>task.id));const closed=[];for(const fold of runs){if(fold.finished!==null||effectiveRunV2Role(fold.run)!=="orchestrator"||fold.run.parent_run_id!==null||fold.run.entrypoint!=="task"||fold.run.task_id===null||!cancelledTaskIds.has(fold.run.task_id)||scope!==void 0&&!scope.matchesRun(fold)){continue}const current=await composition.runs.read(fold.run.run_id);if(current.finished!==null)continue;const activeChildren=activeDescendantRuns(current.run.run_id,runs);if(activeChildren.length>0)await cancelActiveDescendantRuns2(activeChildren,composition,parsed);let attributable=await composition.runs.read(current.run.run_id);if(attributable.effective_usage_records.length===0){await composition.runs.appendRecord(unavailableUsageRecord(attributable,parsed,attributable.records.length+1));attributable=await composition.runs.read(current.run.run_id)}await composition.runs.appendRecord(runFinishedV2Schema.parse({schema_version:2,event_id:`${attributable.run.run_id}:${String(attributable.records.length+1).padStart(6,"0")}`,run_id:attributable.run.run_id,sequence:attributable.records.length+1,occurred_at:new Date().toISOString(),type:"run.finished",phase:latestRunV2Phase(attributable.records),status:"cancelled"}));closed.push(await composition.runs.read(current.run.run_id))}return closed}async function cancelActiveDescendantRuns2(descendants,composition,parsed){for(const descendant of[...descendants].reverse()){let current=await composition.runs.read(descendant.run.run_id);if(current.finished!==null)continue;if(current.effective_usage_records.length===0){await composition.runs.appendRecord(unavailableUsageRecord(current,parsed,current.records.length+1));current=await composition.runs.read(current.run.run_id)}await composition.runs.appendRecord(runFinishedV2Schema.parse({schema_version:2,event_id:`${current.run.run_id}:${String(current.records.length+1).padStart(6,"0")}`,run_id:current.run.run_id,sequence:current.records.length+1,occurred_at:new Date().toISOString(),type:"run.finished",phase:latestRunV2Phase(current.records),status:"cancelled"}))}}async function blockOrphanedInteractionExecutions(catalog,runs,composition,now,scope){const ids=orphanedInteractionExecutionIds(catalog,runs,now).filter(id=>{const execution=catalog.executions.find(candidate=>candidate.id===id);return execution!==void 0&&(scope===void 0||scope.matchesExecution(execution))});if(ids.length===0)return[];const clock=new SystemClock;const blocked2=[];for(const id of ids){await composition.executions.transition(id,"blocked",null,clock,`Interaction Execution ${id} has no active orchestrator Run after the reconciliation grace period.`);blocked2.push((await composition.executions.read(id)).execution)}return blocked2}function orphanedInteractionExecutionIds(catalog,runs,now=new Date){return catalog.executions.flatMap(execution=>{if(execution.kind!=="interaction"||!["running","verifying"].includes(execution.status)){return[]}const startedAt=Date.parse(execution.started_at??execution.updated_at??execution.created_at);if(!Number.isFinite(startedAt)||now.getTime()-startedAt<ORPHANED_EXECUTION_GRACE_MS2){return[]}const hasActiveRoot=runs.some(run=>run.finished===null&&effectiveRunV2Role(run.run)==="orchestrator"&&run.run.parent_run_id===null&&run.run.execution_id===execution.id);return hasActiveRoot?[]:[execution.id]})}function terminalReconciliationSubjectIds(catalog){const ids=new Set;const unsettledTaskIds=new Set(catalog.tasks.filter(task=>["executing","verifying"].includes(task.status)).map(task=>task.id));unsettledTaskIds.forEach(id=>{ids.add(id)});for(const change of catalog.changes){const unsettled=["planned","executing","verifying"].includes(change.status);const hasUnsettledTask=change.task_ids.some(id=>unsettledTaskIds.has(id));if(!unsettled&&!hasUnsettledTask)continue;change.task_ids.forEach(id=>{ids.add(id)});if(change.source.type==="spec")ids.add(change.source.spec_id);if(change.source.type==="prd"){ids.add(change.source.prd_id);if(change.source.spec_id!==null)ids.add(change.source.spec_id)}}for(const execution of catalog.executions){if(!["planned","running","paused","verifying"].includes(execution.status))continue;execution.dag.nodes.forEach(node=>{ids.add(node.task_id)})}catalog.specs.filter(spec=>spec.status==="active").forEach(spec=>{ids.add(spec.id)});catalog.prds.filter(prd=>prd.status==="active").forEach(prd=>{ids.add(prd.id)});return ids}function authorizedOrphanScope(parsed){const reason=parsed.options["orphan-reason"];const scope=parsed.options["orphan-scope"];if(reason===void 0&&scope===void 0)return void 0;if(reason!=="inactive_terminal_without_host_identity"){throw new Error("--orphan-reason must be inactive_terminal_without_host_identity for explicit orphan reconciliation")}if(scope===void 0||scope.trim().length===0){throw new Error("Explicit orphan reconciliation requires --orphan-scope all or comma-separated Run/Task/Execution IDs")}const ids=new Set(scope.split(",").map(value=>value.trim()).filter(Boolean));if(ids.size===0)throw new Error("--orphan-scope must name all or at least one canonical ID");const[onlyId]=[...ids];const exactExecutionId=ids.size===1&&onlyId?.startsWith("EXEC-")?onlyId:void 0;return{...exactExecutionId===void 0?{}:{exactExecutionId},matchesRun(fold){return ids.has("all")||ids.has(fold.run.run_id)||fold.run.task_id!==null&&ids.has(fold.run.task_id)||fold.run.execution_id!==null&&ids.has(fold.run.execution_id)},matchesTask(taskId){return ids.has("all")||ids.has(taskId)},matchesExecution(execution){return ids.has("all")||ids.has(execution.id)||execution.origin.type==="task"&&ids.has(execution.origin.task_id)||execution.dag.nodes.some(node=>ids.has(node.task_id))}}}function isOrphanedCodexRun(fold,activeInvocations,now=new Date){if(fold.finished!==null||!isCodexTelemetryClient(fold.run.client))return false;const startedAt=Date.parse(fold.run.occurred_at);if(!Number.isFinite(startedAt)||now.getTime()-startedAt<ORPHANED_RUN_GRACE_MS){return false}return!activeInvocations.some(active=>{if(active.sessionId!==fold.run.client_thread_id)return false;const activeObservedAt=Date.parse(active.observedAt??active.startedAt??"");if(!Number.isFinite(activeObservedAt)||now.getTime()-activeObservedAt>ORPHANED_RUN_GRACE_MS){return false}if(active.turnId===fold.run.client_turn_id)return true;const activeStartedAt=active.startedAt===null?Number.NaN:Date.parse(active.startedAt);return Number.isFinite(activeStartedAt)&&Math.abs(activeStartedAt-startedAt)<=ACTIVE_INVOCATION_START_TOLERANCE_MS})}function isReconcilableCodexClient(client,explicitScope){return isCodexTelemetryClient(client)||explicitScope&&EXPLICIT_LEGACY_CODEX_CLIENTS.has(client)}function isExplicitLegacyNoHostOrphan(fold,now){if(fold.finished!==null||!EXPLICIT_LEGACY_CODEX_CLIENTS.has(fold.run.client)||fold.run.client_thread_id!==null){return false}const startedAt=Date.parse(fold.run.occurred_at);return Number.isFinite(startedAt)&&now.getTime()-startedAt>=ORPHANED_RUN_GRACE_MS}function activeLifecycleSubjectIds(activeRuns,catalog){const ids=new Set;const taskById=new Map(catalog.tasks.map(task=>[task.id,task]));const changeById=new Map(catalog.changes.map(change=>[change.id,change]));const specById=new Map(catalog.specs.map(spec=>[spec.id,spec]));for(const fold of activeRuns){relatedWorkIds(fold).forEach(id=>{ids.add(id)});const task=fold.run.task_id===null?void 0:taskById.get(fold.run.task_id);const change=task===void 0?void 0:changeById.get(task.change_id);const specId=fold.run.spec_id??(change?.source.type==="spec"||change?.source.type==="prd"?change.source.spec_id:null);const prdId=fold.run.prd_id??(change?.source.type==="prd"?change.source.prd_id:null)??(specId===null?null:specById.get(specId)?.prd_id??null);if(change!==void 0)ids.add(change.id);if(specId!==null)ids.add(specId);if(prdId!==null)ids.add(prdId);for(const candidate of catalog.changes){const belongsToSpec=specId!==null&&candidate.source.type!=="task"&&candidate.source.spec_id===specId;const belongsToPrd=candidate.source.type==="prd"&&candidate.source.prd_id===prdId;if(!belongsToSpec&&!belongsToPrd)continue;ids.add(candidate.id);candidate.task_ids.forEach(id=>{ids.add(id)})}for(const execution of catalog.executions){if(execution.origin.type==="prd"&&execution.origin.prd_id===prdId||execution.origin.type==="spec"&&execution.origin.spec_id===specId){ids.add(execution.id);execution.dag.nodes.forEach(node=>{ids.add(node.task_id)})}}}return ids}function relatedWorkIds(fold){return[fold.run.task_id,fold.run.spec_id,fold.run.prd_id].filter(id=>id!==null)}var ORPHANED_RUN_GRACE_MS,ORPHANED_EXECUTION_GRACE_MS2,ACTIVE_INVOCATION_START_TOLERANCE_MS,EXPLICIT_LEGACY_CODEX_CLIENTS;var init_open_work_reconciliation=__esm({"src/open-work-reconciliation.ts"(){"use strict";init_src();init_src2();init_src3();init_inferred_orphan_failure();init_open_work_host_preflight();init_open_work_run_topology();init_orphaned_macro_reconciliation();init_record_codex_telemetry();init_run_conversation_v2();init_run_hierarchy();init_run_lifecycle_reconciliation();init_orphaned_macro_reconciliation();ORPHANED_RUN_GRACE_MS=10*60*1e3;ORPHANED_EXECUTION_GRACE_MS2=10*60*1e3;ACTIVE_INVOCATION_START_TOLERANCE_MS=2*60*1e3;EXPLICIT_LEGACY_CODEX_CLIENTS=new Set(["codex-prd-authoring","codex-prd-composite-authoring"])}});async function loadAgentCatalog(filesystem){if(!await filesystem.exists(AGENT_CATALOG_PATH2)){throw new UsageError(`Agent catalog not found at ${AGENT_CATALOG_PATH2}`)}const catalog=parseAgentCatalog(parseYaml(await filesystem.readText(AGENT_CATALOG_PATH2)));const findings=validateAgentCatalog(catalog);if(findings.length>0){throw new Error(`Invalid Agent catalog: ${findings[0]?.message??"unknown finding"}`)}return catalog}async function resolveRunAgentIdentityResult(filesystem,input){const client=input.client.trim();if(client.length===0)throw new UsageError("--client must not be empty");const fallback=client==="codex"||client.startsWith("codex-")?"codex":client;const requested=input.agent?.trim();if(requested===void 0||requested.length===0||requested===client||requested===fallback){return{agent_id:fallback,warning:null}}const catalog=await loadAgentCatalog(filesystem).catch(error51=>{if(error51 instanceof UsageError){throw new UsageError(`${error51.message}; omit --agent to use fallback "${fallback}"`)}throw error51});try{const selected=resolveAgentIdentity(catalog,requested);return{agent_id:selected.canonical_id,warning:selected.warning}}catch(error51){if(!(error51 instanceof Error)||!error51.message.startsWith("Unknown Agent identity:")){throw new UsageError(error51 instanceof Error?error51.message:String(error51))}}const available=catalog.agents.flatMap(agent=>[agent.id,agent.codex_name]).sort().join(", ");throw new UsageError(`Unknown Agent "${requested}". Use one of: ${available}; omit --agent to use fallback "${fallback}"`)}async function resolveRunAgentName(filesystem,agentId2){if(agentId2==="codex")return"codex";if(!agentId2.startsWith("agent-"))return agentId2;const catalog=await loadAgentCatalog(filesystem);return catalog.agents.find(agent=>agent.id===agentId2)?.codex_name??null}var AGENT_CATALOG_PATH2;var init_run_agent_identity=__esm({"src/run-agent-identity.ts"(){"use strict";init_src();init_cli_arguments();AGENT_CATALOG_PATH2=".agents/config/agents/catalog.yaml"}});function defaultExecutionPolicy(risk2,signals={}){const independentBranches=signals.independent_branches===true;return{failure_policy:"stop_on_terminal_failure",max_parallelism:risk2==="lite"?1:independentBranches?risk2==="critical"?3:2:1,max_operational_retries:risk2==="lite"?0:1,max_repair_cycles_per_task:risk2==="lite"?0:2,soft_model_cycle_budget:risk2==="lite"?4:risk2==="standard"?24:40,context_refresh_after_cycles:risk2==="lite"?4:8,verification_mode:risk2==="critical"?"full":"scoped",max_cost_usd:signals.max_cost_usd??null}}function completeObservedCostUsd(costs){if(costs.length===0||costs.some(cost3=>cost3===null))return null;return costs.reduce((sum,cost3)=>sum+cost3,0)}async function evaluateRunBudget(run,composition,filesystem){if(run.run.execution_id===null)return null;const execution=(await composition.executions.read(run.run.execution_id)).execution;const cycles=run.effective_usage_records.length;const providerInputTokens=run.effective_usage_records.reduce((sum,event)=>sum+Math.max(0,(event.tokens.input??0)-(event.tokens.cached_input??0)),0);const observedContextTokens=run.effective_usage_records.reduce((sum,event)=>sum+(event.context_stats?.initial_pack_tokens??0)+(event.context_stats?.tool_output_tokens??0),0);const measuredInputTokens=providerInputTokens>0?providerInputTokens:observedContextTokens;const cycleBudget=execution.policy.soft_model_cycle_budget??null;const refreshAfter=execution.policy.context_refresh_after_cycles??null;const checkpointRequired=cycleBudget!==null&&cycles>=cycleBudget;const contextRefreshRequired=refreshAfter!==null&&cycles>0&&cycles%refreshAfter===0;const costCapUsd=execution.policy.max_cost_usd??null;const observedCostUsd=completeObservedCostUsd(run.effective_usage_records.map(event=>event.cost.usd));const hasCompleteObservedCost=observedCostUsd!==null;const budget={schema_version:1,run_id:run.run.run_id,execution_id:execution.id,measured_at:new Date().toISOString(),cycles,provider_uncached_input_tokens:providerInputTokens,observed_context_tokens:observedContextTokens,measured_input_tokens:measuredInputTokens,measurement_source:providerInputTokens>0?"provider_uncached":"context_stats",soft_model_cycle_budget:cycleBudget,context_refresh_after_cycles:refreshAfter,max_cost_usd:costCapUsd,observed_cost_usd:observedCostUsd,cost_measurement_source:hasCompleteObservedCost?"observed":"unavailable",cost_checkpoint_required:costCapUsd!==null&&observedCostUsd!==null&&observedCostUsd>=costCapUsd,checkpoint_required:checkpointRequired,context_refresh_required:contextRefreshRequired};if(checkpointRequired||contextRefreshRequired||budget.cost_checkpoint_required){await filesystem.writeTextAtomic(`.local/checkpoints/${run.run.run_id}.json`,`${JSON.stringify(budget,null,2)}
|
|
375
375
|
`)}return budget}var init_run_budget=__esm({"src/run-budget.ts"(){"use strict"}});function runClosureView(repository2,current,prospective){const next=prospective.records.at(-1);if(current.finished!==null||prospective.run.run_id!==current.run.run_id||JSON.stringify(prospective.run)!==JSON.stringify(current.run)||prospective.records.length!==current.records.length+1||next?.type!=="run.finished"||next.sequence!==current.records.length+1||current.records.some((record3,index)=>JSON.stringify(record3)!==JSON.stringify(prospective.records[index])))throw new Error("Closure view requires the exact next terminal event for the locked Run");return new Proxy(repository2,{get(target,key){if(["start","appendRecord"].includes(String(key)))return()=>{throw new Error("Closure view cannot persist Run events")};if(key==="read")return id=>id===current.run.run_id?Promise.resolve(prospective):target.read(id);if(key==="list")return async()=>(await target.list()).map(run=>run.run.run_id===current.run.run_id?prospective:run);const value=Reflect.get(target,key,target);return typeof value==="function"?value.bind(target):value}})}var init_run_closure_view=__esm({"src/run-closure-view.ts"(){"use strict"}});async function reconcileHistoricalCodexTiming(parsed,composition,filesystem,fallbackSegmentFinder=findLatestCodexSegment){return composition.runs.withUsageAttributionLock(async()=>{requireOptions(parsed.options,["id","session","turn"]);const id=parsed.options.id;const turnId=parsed.options.turn;const sessionPath=parsed.options.session;const current=await composition.runs.read(id);if(current.run.client_turn_id!==turnId){throw new UsageError(`Run ${id} is not correlated with the requested turn`)}const candidate=await fallbackSegmentFinder(filesystem.root,new Set,{turnId,sessionPaths:[sessionPath],...current.run.client_thread_id==null?{}:{threadId:current.run.client_thread_id}});if(candidate===null||candidate.startedAt===null||candidate.finishedAt===null||candidate.turnId!==turnId){throw new UsageError("No completed observed interval exists for the requested Run/session/turn")}const sourceSegmentKey=candidate.segmentKey;const sourceUsage=current.effective_usage_records.find(record3=>record3.source_segment_key===sourceSegmentKey);const timingOnly=sourceUsage===void 0;const remeasurement=sourceUsage===void 0?null:await remeasureObservedCalls(candidate,sourceUsage,filesystem);const sourceFinishedAt=remeasurement?.source_finished_at??candidate.finishedAt;const existing=current.records.find(record3=>record3.type==="usage.recorded"&&record3.source_segment_key===sourceSegmentKey&&"source_started_at"in record3&&record3.source_started_at===candidate.startedAt&&"source_finished_at"in record3&&record3.source_finished_at===sourceFinishedAt);const timing={run_id:id,session:sessionPath,turn_id:turnId,source_started_at:candidate.startedAt,source_finished_at:sourceFinishedAt,source_duration_ms:Date.parse(sourceFinishedAt)-Date.parse(candidate.startedAt),source_segment_key:sourceSegmentKey,supersedes_event_id:sourceUsage?.event_id??null,usage:timingOnly?"unavailable":"preserved",...remeasurement===null?{}:{remeasurement}};if(existing!==void 0)return{applied:false,reason:"already-reconciled",timing};const existingOwner=(await composition.runs.list()).find(fold=>fold.run.run_id!==id&&fold.effective_usage_records.some(record3=>record3.source_segment_key===sourceSegmentKey||record3.source_segment_key?.startsWith(`${sourceSegmentKey}@`)===true));if(existingOwner!==void 0){throw new UsageError(`Observed source segment is already attributed to ${existingOwner.run.run_id}`)}if(parsed.flags.has("dry-run"))return{applied:false,reason:"dry-run",timing};const sequence=current.records.length+1;await composition.runs.appendRecord(usageRecordedV2Schema.parse({schema_version:2,event_id:runV2EventId(id,sequence),run_id:id,sequence,occurred_at:new Date().toISOString(),type:"usage.recorded",phase:latestRunV2Phase(current.records),activity_kind:timingOnly?"retrospective_observed_timing":"retrospective_local_remeasurement",classification_source:sourceUsage?.classification_source??"current_context",tokens:remeasurement?.tokens??sourceUsage?.tokens??{input:null,cached_input:null,cache_write_input:null,output:null,reasoning:null,total:null,source:"unavailable"},cost:remeasurement?.cost??sourceUsage?.cost??{usd:null,brl:null,fx_rate:null},provider:sourceUsage?.provider??null,model:sourceUsage?.model??null,source_segment_key:sourceSegmentKey,supersedes_event_id:sourceUsage?.event_id??null,retrospective_correction:true,source_occurred_at:sourceFinishedAt,source_started_at:candidate.startedAt,source_finished_at:sourceFinishedAt}));return{applied:true,timing,artifact_path:composition.runs.path(id)}})}async function remeasureObservedCalls(candidate,sourceUsage,filesystem){const matchingLoops=observedCallPrefix(candidate,sourceUsage.tokens);if(matchingLoops===null){throw new UsageError("Observed Model Calls do not match the canonical usage record")}const observed=aggregateSegmentUsage({...candidate,loops:matchingLoops});if(observed.input!==sourceUsage.tokens.input||observed.cached_input!==sourceUsage.tokens.cached_input||observed.output!==sourceUsage.tokens.output||observed.reasoning!==sourceUsage.tokens.reasoning||observed.total!==sourceUsage.tokens.total){throw new UsageError("Observed Model Calls do not match the canonical usage record")}const pricing=new PricingRepository(filesystem);const[catalog,fxRate]=await Promise.all([pricing.readCatalog(),pricing.readLatestFxRate()]);const estimates=matchingLoops.map(loop=>{const model=loop.model??candidate.model??sourceUsage.model;const provider=inferProvider(model??"",sourceUsage.provider??"","");return estimateUsageCost({provider,model:model??"",usage:loop.usage,catalog,fxRate,serviceTier:candidate.serviceTier??null})});if(estimates.some(estimate=>estimate.estimated_usd===null)){throw new UsageError("Observed Model Calls cannot be priced by the current catalog")}const usd=estimates.reduce((total,estimate)=>total+(estimate.estimated_usd??0),0);return{source_call_count:matchingLoops.length,source_finished_at:matchingLoops.at(-1)?.timestamp??candidate.finishedAt,tokens:observed,cost:{usd,brl:fxRate===null?null:usd*fxRate.rate,fx_rate:fxRate?.rate??null}}}function observedCallPrefix(candidate,expected){for(let count=1;count<=candidate.loops.length;count+=1){const loops=candidate.loops.slice(0,count);const usage=aggregateSegmentUsage({...candidate,loops});if(usage.input===expected.input&&usage.cached_input===expected.cached_input&&usage.output===expected.output&&usage.reasoning===expected.reasoning&&usage.total===expected.total){return loops}}return null}var init_v2_run_historical_codex_timing=__esm({"src/source-size-cli/v2-run-historical-codex-timing.ts"(){"use strict";init_src2();init_src3();init_cli_arguments();init_run_conversation_v2()}});async function snapshotRuns(filesystem){const store=new LifecycleManifestStore(filesystem);const entities=await store.readEntities("run");if(entities.length===0&&await store.readSummary()===null)throw incomplete("run","snapshot");return entities.map(fromEntity)}function filterSnapshotRuns(runs,parsed){const statuses=new Set(csvOption(parsed.options.status));const from=dateBoundary(parsed.options.from,false);const to=dateBoundary(parsed.options.to,true);const phase2=parsed.options.phase===void 0?void 0:runV2PhaseOption(parsed.options.phase);const entry2=parsed.options.entrypoint===void 0?void 0:runV2EntrypointOption(parsed.options.entrypoint);const work2=parsed.options["work-type"]===void 0?void 0:runV2WorkTypeOption(parsed.options["work-type"]);return runs.filter(run=>{const at=Date.parse(run.created_at);if(statuses.size&&!statuses.has(run.status)||from!==null&&at<from||to!==null&&at>to||parsed.options.agent!==void 0&&parsed.options.agent!==run.agent&&parsed.options.agent!==run.agent_name)return false;return[[parsed.positionals[2],run.id],[parsed.options.id,run.id],[phase2,run.phase],[entry2,run.entrypoint],[work2,run.work_type],[parsed.options.conversation,run.conversation_id],[parsed.options.execution,run.execution_id],[parsed.options.task,run.task_id],[parsed.options.spec,run.spec_id],[parsed.options.prd,run.prd_id],[parsed.options.change,run.change_id]].every(([wanted,actual])=>wanted===void 0||wanted===actual)}).sort((a,b)=>b.created_at.localeCompare(a.created_at)||b.id.localeCompare(a.id))}function snapshotCostInput(run){return{run:{run_id:run.id,attribution_status:run.attribution_status,conversation_id:run.conversation_id,execution_id:run.execution_id,task_id:run.task_id,spec_id:run.spec_id,prd_id:run.prd_id,change_id:run.change_id,work_type:run.work_type},records:run.pricing_segments,effective_usage_records:run.pricing_segments}}function aggregateSnapshotRunsByAgent(runs){const groups=new Map;for(const run of runs){const key=run.agent_name??run.agent;groups.set(key,[...groups.get(key)??[],run])}return[...groups.entries()].sort(([a],[b])=>a.localeCompare(b)).map(([name,group])=>{const durations=group.flatMap(run=>run.terminal_finished_at===null?[]:duration3(run.created_at,run.terminal_finished_at));const aggregate=aggregateRunV2Usage(group.map(snapshotCostInput),name);const cycles=group.map(run=>run.pricing_segments.length);return{agent:group[0]?.agent??name,agent_name:name,run_count:group.length,rework_runs:group.filter(run=>run.work_type==="rework").length,duration:{known_runs:durations.length,unknown_runs:group.length-durations.length,total_ms:durations.reduce((a,b)=>a+b,0),average_ms:durations.length?Math.round(durations.reduce((a,b)=>a+b,0)/durations.length):null},observed_usage_cycles:{total:cycles.reduce((a,b)=>a+b,0),average:cycles.length?Number((cycles.reduce((a,b)=>a+b,0)/cycles.length).toFixed(2)):null},tokens:aggregate.total.tokens,cost:aggregate.total.cost,coverage:aggregate.run_coverage}})}function snapshotObservedSourceTiming(runs){return summarizeObservedSourceTiming(runs.flatMap(run=>run.pricing_segments).map(segment2=>({phase:segment2.phase,source_started_at:segment2.source_started_at,source_finished_at:segment2.source_finished_at})))}function filterRunV2Folds(runs,parsed){const snapshots=runs.map(fold=>({id:fold.run.run_id,status:fold.status,created_at:fold.run.occurred_at,phase:fold.records.findLast(record3=>"phase"in record3)?.phase??fold.run.phase,entrypoint:fold.run.entrypoint,work_type:fold.run.work_type,agent:fold.run.agent,agent_name:fold.run.agent_name??null,conversation_id:fold.run.conversation_id,execution_id:fold.run.execution_id,task_id:fold.run.task_id,spec_id:fold.run.spec_id,prd_id:fold.run.prd_id,change_id:fold.run.change_id}));const ids=new Set(filterSnapshotRuns(snapshots,parsed).map(run=>run.id));return runs.filter(run=>ids.has(run.run.run_id))}function fromEntity(entity){const d=data(entity);return{id:entity.id,status:string4(entity.status,"status"),created_at:string4(d.started_at,"started_at"),terminal_finished_at:nullable2(d.terminal_finished_at),effective_finished_at:nullable2(d.finished_at),phase:phase(d.phase),run_role:string4(d.run_role,"run_role"),parent_run_id:nullable2(d.parent_run_id),entrypoint:entry(d.entrypoint),work_type:work(d.work_type),intake:intake(d.intake),agent:string4(d.agent,"agent"),agent_name:nullable2(d.cli_agent_name),model:string4(d.model,"model"),reasoning_effort:nullable2(d.reasoning_effort),call_count:nullableNumber(d.cli_call_count,"cli_call_count"),client_thread_id:nullable2(d.client_thread_id),client_turn_id:nullable2(d.client_turn_id),conversation_id:string4(d.conversation_id,"conversation_id"),execution_id:nullable2(d.execution_id),task_id:nullable2(d.task_id),spec_id:nullable2(d.spec_id),prd_id:nullable2(d.prd_id),change_id:nullable2(d.change_id),attribution_status:attribution(d.attribution_status),pricing_segments:segments(d.pricing_segments)}}function data(entity){if(entity.data===null)throw incomplete(entity.id,"data");return entity.data}function string4(v,f){if(typeof v!=="string"||!v)throw incomplete("run",f);return v}function nullable2(v){if(v===null)return null;if(typeof v==="string")return v;throw incomplete("run","nullable")}function nullableNumber(v,f){if(v===null)return null;if(typeof v==="number"&&Number.isInteger(v)&&v>=0)return v;throw incomplete("run",f)}function phase(v){if(v==="conversation"||v==="planning"||v==="execution")return v;throw incomplete("run","phase")}function entry(v){if(v==="conversation"||v==="task"||v==="spec"||v==="prd")return v;throw incomplete("run","entrypoint")}function work(v){if(v==="new"||v==="rework")return v;throw incomplete("run","work_type")}function attribution(v){if(v==="attributed"||v==="legacy_unattributed")return v;throw incomplete("run","attribution_status")}function intake(v){if(v===null)return null;if(typeof v!=="object"||v===null)throw incomplete("run","intake");const x=v;if(typeof x.intent!=="string"||typeof x.classification_source!=="string"||typeof x.confidence!=="number"||!Array.isArray(x.reason_codes)||!x.reason_codes.every(item=>typeof item==="string"))throw incomplete("run","intake");return{intent:x.intent,classification_source:x.classification_source,confidence:x.confidence,reason_codes:x.reason_codes}}function segments(v){if(!Array.isArray(v))throw incomplete("run","pricing_segments");return v.map(item=>{if(typeof item!=="object"||item===null)throw incomplete("run","pricing_segments");const x=item;return{event_id:string4(x.event_id,"pricing_segments.event_id"),phase:phase(x.phase),tokens:tokens(x),cost:cost2(x),source_started_at:nullable2(x.source_started_at),source_finished_at:nullable2(x.source_finished_at),attributed_spec_id:nullable2(x.attributed_spec_id)}})}function tokens(x){return{input:metric4(x.input_tokens,"input_tokens"),cached_input:metric4(x.cached_input_tokens,"cached_input_tokens"),output:metric4(x.output_tokens,"output_tokens"),reasoning:metric4(x.reasoning_tokens,"reasoning_tokens"),total:metric4(x.total_tokens,"total_tokens")}}function cost2(x){return{usd:metric4(x.recorded_usd,"recorded_usd"),brl:metric4(x.recorded_brl,"recorded_brl")}}function metric4(v,f){if(v===null)return null;if(typeof v==="number"&&Number.isFinite(v)&&v>=0)return v;throw incomplete("run",f)}function duration3(a,b){const n=Date.parse(b)-Date.parse(a);return Number.isFinite(n)&&n>=0?[n]:[]}function incomplete(id,field){return new Error(`Run snapshot is incomplete (${id}: ${field}); run \`zaip manifest rebuild --confirm-full-scan\``)}var init_v2_run_snapshot=__esm({"src/commands/v2-run-snapshot.ts"(){"use strict";init_src2();init_src6();init_cli_arguments()}});function sameStringSet(left,right){return left.length===right.length&&left.every(value=>right.includes(value))}function runV2ScopeOption(parsed){return parsed.positionals[2]??parsed.options.id??parsed.options.conversation??parsed.options.execution??parsed.options.task??parsed.options.spec??parsed.options.prd??parsed.options.change??null}var init_v2_run_support=__esm({"src/commands/v2-run-support.ts"(){"use strict"}});var v2_run_exports={};__export(v2_run_exports,{activeRunWindow:()=>activeRunWindow,cancelTaskRunsForHuman:()=>cancelTaskRunsForHuman,filterRunV2Folds:()=>filterRunV2Folds,runRunV2Command:()=>runRunV2Command});async function runRunV2Command(action,parsed,composition,filesystem,lifecycle){if(action==="start"){requireOptions(parsed.options,["short-name","phase","entrypoint","work-type","client","model"]);const client=parsed.options.client;const phase2=runV2PhaseOption(parsed.options.phase);const parentRunId=parsed.options.parent??null;const clientInvocation=await resolveRunClientInvocation(filesystem,client);const agentResolution=await resolveRunAgentIdentityResult(filesystem,{agent:parsed.options.agent,client});const agent=agentResolution.agent_id;const runPurpose=parsed.options["run-purpose"]===void 0?phase2!=="execution"?"intake":agent==="agent-finalizer"?"finalization":agent==="agent-reviewer"?"review":agent==="agent-auditor"?"audit":parentRunId===null?"orchestration":"execution":runV2PurposeSchema.parse(parsed.options["run-purpose"]);const catalog=await loadAgentCatalog(filesystem).catch(()=>null);const catalogAgent=catalog?.agents.find(candidate=>candidate.id===agent);const parent=parentRunId===null?null:await composition.runs.read(parentRunId);const execution=parent===null&&parsed.options.execution!==void 0?await composition.executions.read(parsed.options.execution).catch(()=>null):null;const executionKind=parent?.run.execution_kind??execution?.execution.kind??void 0;const rootDeveloperIdentity=parentRunId===null?await resolveDeveloperIdentityForRoot(filesystem):void 0;const input={...parsed.options.id===void 0?{}:{id:parsed.options.id},shortName:parsed.options["short-name"],phase:phase2,...parsed.options["run-role"]===void 0?{}:{runRole:runV2RoleSchema.parse(parsed.options["run-role"])},runPurpose,...executionKind===void 0?{}:{executionKind},executionEligibility:catalogAgent?.execution_eligibility??[],...parsed.options["direct-authorization"]===void 0?{}:{directExecutionAuthorization:parsed.options["direct-authorization"]},entrypoint:runV2EntrypointOption(parsed.options.entrypoint),workType:runV2WorkTypeOption(parsed.options["work-type"]),client,agent,agentName:await resolveRunAgentName(filesystem,agent),...agentResolution.warning===null?{}:{agentIdentityWarning:agentResolution.warning},provider:parsed.options.provider??null,model:parsed.options.model,reasoningEffort:parsed.options["reasoning-effort"]===void 0?null:runV2ReasoningEffortSchema.parse(parsed.options["reasoning-effort"]),...clientInvocation,conversationId:parsed.options.conversation??createConversationId(parsed.options["short-name"]),executionId:parsed.options.execution??null,taskId:parsed.options.task??null,specId:parsed.options.spec??null,prdId:parsed.options.prd??null,changeId:parsed.options.change??null,parentRunId,continuationOfRunId:parsed.options.continuation??null,retryOfRunId:parsed.options.retry??null,...rootDeveloperIdentity===void 0?{}:{developerIdentity:rootDeveloperIdentity}};await validateRunV2Attribution(input,composition);if(parentRunId===null){const existing=await findRootRunForExactTurn(composition,client,clientInvocation);if(existing!==null){const conflicts=rootRunStartConflicts(existing,input,parsed.options.conversation,parsed.options.id);if(conflicts.length>0){throw new UsageError(`Exact client turn is already captured by root Run ${existing.run.run_id}; requested root Run conflicts on ${conflicts.join(", ")}. Reuse matching metadata or start the delivery from a new observed client turn.`)}return{run:existing.run,artifact_path:composition.runs.path(existing.run.run_id),warnings:agentResolution.warning===null?[]:[agentResolution.warning],reused:true}}}const start=async()=>{if(parentRunId!==null){const freshParent=await composition.runs.read(parentRunId);const candidates=await composition.runs.list();assertChildRunMayStart(freshParent,runPurpose,agent,candidates,catalogAgent?.execution_eligibility??[])}const writer=await composition.runs.start(input);return{run:writer.started,artifact_path:composition.runs.path(writer.started.run_id),warnings:agentResolution.warning===null?[]:[agentResolution.warning]}};return parentRunId===null?start():composition.runs.withUsageAttributionLock(start)}if(action==="list"||action==="aggregate"){const runs=filterSnapshotRuns(await snapshotRuns(filesystem),parsed);if(action==="aggregate"){const aggregate=aggregateRunV2Usage(runs.map(snapshotCostInput),runV2ScopeOption(parsed));const agents=aggregateSnapshotRunsByAgent(runs);const observed_source_timing=snapshotObservedSourceTiming(runs);return parsed.options.view==="full"?{...aggregate,agents,observed_source_timing}:{...compactRunAggregate(aggregate),agents,observed_source_timing}}const summaries=runs.map(run=>({id:run.id,status:run.status,created_at:run.created_at,finished_at:run.terminal_finished_at,phase:run.phase,run_role:run.run_role,parent_run_id:run.parent_run_id,entrypoint:run.entrypoint,work_type:run.work_type,intake:run.intake,agent:run.agent,agent_name:run.agent_name??(run.agent.startsWith("agent-")?`zaip-agent-${run.agent.slice("agent-".length)}`:run.agent),model:run.model,reasoning_effort:run.reasoning_effort,call_count:run.call_count,client_thread_id:run.client_thread_id,client_turn_id:run.client_turn_id,conversation_id:run.conversation_id,execution_id:run.execution_id,task_id:run.task_id,spec_id:run.spec_id,prd_id:run.prd_id,change_id:run.change_id,usage:(()=>{const usage=aggregateRunV2Usage([snapshotCostInput(run)],run.id).total;return{event_count:usage.usage_event_count,tokens:usage.tokens,cost:usage.cost,coverage:usage.coverage}})(),artifact_path:composition.runs.path(run.id)}));return listLifecyclePage(summaries,parsed)}if(action==="reconcile"){if(parsed.flags.has("open"))return reconcileOpenWork(parsed,composition,lifecycle,filesystem);return reconcileHistoricalCodexTiming(parsed,composition,filesystem)}if(action==="usage"&&parsed.flags.has("active")){if(!parsed.flags.has("disable-codex-raw"))throw new UsageError("run usage --active requires --disable-codex-raw");const activeIds=activeRunIds(await new LifecycleManifestStore(filesystem).readActiveWork());const captured=[];for(const runId of activeRunWindow(activeIds,Date.now(),numberOption(parsed.options.limit,32))){const fold=await composition.runs.read(runId);if(fold.finished===null&&isCodexTelemetryClient(fold.run.client)&&fold.run.client_turn_id!==null){const before=fold.records.length;const current=await recordCodexTelemetryIfAvailable(fold,composition,filesystem);captured.push({run_id:fold.run.run_id,captured:current.records.length>before})}}return{telemetry:{mode:"active_exact_session",captured},artifact_path:null}}const id=requiredEntityId(parsed,2,"Run V2 id");if(action==="show"){const run=await composition.runs.read(id);const includeEvents=parsed.flags.has("events")||parsed.options["event-id"]!==void 0||parsed.options["from-sequence"]!==void 0;return includeEvents?{run:{...run,records:run.records.filter(record3=>(parsed.options["event-id"]===void 0||record3.event_id===parsed.options["event-id"])&&(parsed.options["from-sequence"]===void 0||record3.sequence>=numberOption(parsed.options["from-sequence"],1)))},artifact_path:composition.runs.path(id)}:runV2Summary(run,composition)}if(action==="recover-attribution"){return composition.runs.withUsageAttributionLock(async()=>{const current=await composition.runs.read(id);const started=current.records[0];if(current.finished!==null)throw new UsageError(`Run V2 is already finished: ${id}`);if(started?.type!=="run.started")throw new UsageError(`Run V2 has no start record: ${id}`);if(current.attribution_recovery!==null){throw new UsageError(`Run V2 already has an attribution recovery: ${id}`)}if(current.run.entrypoint!=="task"||current.run.execution_id===null||current.run.task_id===null||current.run.change_id!==null){throw new UsageError(`Run ${id} is not an active task Run with an unclaimed Change attribution`)}const task=await composition.tasks.read(current.run.task_id);const changeId=task.task.change_id;if(changeId===null)throw new UsageError(`Task ${task.task.id} has no materialized Change`);await validateRunV2Attribution({shortName:current.run.run_id,phase:"execution",entrypoint:"task",workType:current.run.work_type,client:current.run.client,agent:current.run.agent,provider:current.run.provider,model:current.run.model,conversationId:current.run.conversation_id,executionId:current.run.execution_id,taskId:current.run.task_id,changeId,parentRunId:current.run.parent_run_id,continuationOfRunId:current.run.continuation_of_run_id,retryOfRunId:current.run.retry_of_run_id},composition);const record3=runAttributionRecoveredV2Schema.parse({schema_version:2,event_id:runV2EventId(id,current.records.length+1),run_id:id,sequence:current.records.length+1,occurred_at:new Date().toISOString(),type:"run.attribution.recovered",phase:"execution",execution_id:current.run.execution_id,task_id:current.run.task_id,change_id:changeId});await composition.runs.appendRecord(record3);return{recovery:record3,run:runV2Summary(await composition.runs.read(id),composition),artifact_path:composition.runs.path(id)}})}if(action==="closure"){const current=await composition.runs.read(id);if(current.finished===null)throw new UsageError(`Run V2 is still running: ${id}`);const closure=await assessRunLifecycleClosure(current,composition);if(closure.status==="action_required"){throw new UsageError(`Run ${id} left related work open: ${closure.open_subject_ids.join(", ")}. ${closure.guidance}`)}return{closure,artifact_path:composition.runs.path(id)}}if(action==="usage"){let current=await composition.runs.read(id);const appServerEventsPath=parsed.options["codex-app-server-events"];const rawCaptureDisabled=parsed.flags.has("disable-codex-raw");if(appServerEventsPath!==void 0&&!rawCaptureDisabled){const notifications=parseCodexAppServerNotificationStream(await filesystem.readText(appServerEventsPath));const persisted=await ingestCodexAppServerNotifications(filesystem,notifications);current=await recordCodexTelemetryIfAvailable(current,composition,filesystem);return{telemetry:{received_notifications:notifications.length,persisted_event_ids:persisted.map(event=>event.event_id)},run:runV2Summary(current,composition),artifact_path:composition.runs.path(id)}}if(rawCaptureDisabled){current=await recordCodexTelemetryIfAvailable(current,composition,filesystem);return{telemetry:{raw_capture:"disabled",fallback:"codex_session_fallback"},run:runV2Summary(current,composition),artifact_path:composition.runs.path(id)}}if(current.finished!==null)throw new UsageError(`Run V2 is already finished: ${id}`);const sequence=current.records.length+1;const input=nullableNumberOption(parsed.options["input-tokens"]);const cachedInput=nullableNumberOption(parsed.options["cached-input-tokens"]);const outputTokens=nullableNumberOption(parsed.options["output-tokens"]);const reasoning=nullableNumberOption(parsed.options["reasoning-tokens"]);const explicitTotal=nullableNumberOption(parsed.options["total-tokens"]);const occurredAt=new Date().toISOString();const tokens2={input,cached_input:cachedInput,output:outputTokens,reasoning,total:explicitTotal??(input===null||outputTokens===null?null:input+outputTokens),source:tokenSourceOption(parsed.options["token-source"])};const provider=inferProvider(parsed.options.model??current.run.model,parsed.options.provider??current.run.provider??current.run.client,current.run.agent);const pricing=new PricingRepository(filesystem);const estimated=estimateUsageCost({provider,model:parsed.options.model??current.run.model,usage:tokens2,catalog:await pricing.readCatalog(),fxRate:await pricing.readLatestFxRate()});const record3=usageRecordedV2Schema.parse({schema_version:2,event_id:parsed.options["event-id"]??runV2EventId(id,sequence),run_id:id,sequence,occurred_at:occurredAt,type:"usage.recorded",phase:runV2PhaseOption(parsed.options.phase??latestRunV2Phase(current.records)),activity_kind:parsed.options.activity??"implementation",classification_source:runV2ClassificationOption(parsed.options.classification),tokens:tokens2,cost:{usd:nullableCurrencyOption(parsed.options["cost-usd"])??estimated.estimated_usd,brl:nullableCurrencyOption(parsed.options["cost-brl"])??estimated.estimated_brl,fx_rate:parsed.options["cost-brl"]===void 0?estimated.fx_rate:null},provider,model:parsed.options.model??current.run.model,source_segment_key:parsed.options["source-segment"]??null,supersedes_event_id:parsed.options.supersedes??null,...runUsageMetadataOptions(parsed.options,occurredAt)});const folded=foldRunV2Records([...current.records,record3]);await composition.runs.appendRecord(record3);const budget=await evaluateRunBudget(folded,composition,filesystem);return{usage:record3,budget,artifact_path:composition.runs.path(id)}}if(action==="finish"){const telemetryCandidate=await composition.runs.read(id);await recordCodexTelemetryIfAvailable(telemetryCandidate,composition,filesystem);return composition.runs.withUsageAttributionLock(async()=>{let current=await composition.runs.read(id);const status=runV2FinishStatusOption(parsed.options.status);const candidateRuns=await composition.runs.list();const suppliedEvidenceIds=csvOption(parsed.options.evidence);const finalizationDecision=current.finalization_decision??null;if(finalizationDecision!==null&&suppliedEvidenceIds.length>0&&!sameStringSet(suppliedEvidenceIds,finalizationDecision.evidence_ids)){throw new UsageError("--evidence must match the persisted Gui finalization decision")}const evidenceIds=finalizationDecision?.evidence_ids??suppliedEvidenceIds;const suppliedChangedFiles=csvOption(parsed.options["changed-files"]);if(finalizationDecision!==null&&suppliedChangedFiles.length>0&&!sameStringSet(suppliedChangedFiles,finalizationDecision.changed_files)){throw new UsageError("--changed-files must match the persisted Gui finalization decision")}const changedFiles=finalizationDecision?.changed_files??suppliedChangedFiles;const finalizationBarrier=assessRunFinalizationBarrier(current,candidateRuns,await hasPassedTypedEvidenceForRun(current,evidenceIds,composition,candidateRuns));const barrierBlockReason=finalizationBarrierBlockReason(finalizationBarrier);const finalizationBlockReason=finalizationDecision!==null&&finalizationDecision.outcome!=="completed"?null:barrierBlockReason;const suppliedOutcome=lifecycleOutcomeOption(parsed.options);const missingFinalizationDecision=ownsLifecycleAttempt(current)&&finalizationBarrier.required&&finalizationDecision===null;if(finalizationDecision!==null&&suppliedOutcome!==void 0&&suppliedOutcome!==finalizationDecision.outcome){throw new UsageError(`--task-outcome must match the persisted Gui decision (${finalizationDecision.outcome})`)}if(finalizationDecision!==null&&parsed.options.summary!==void 0&&parsed.options.summary!==finalizationDecision.summary){throw new UsageError("--summary must match the persisted Gui finalization decision")}const mustFailClosed=finalizationBlockReason!==null||missingFinalizationDecision;const requestedOutcome=mustFailClosed?"blocked":finalizationDecision?.outcome??suppliedOutcome;const reconciliationSummary=finalizationBlockReason??(missingFinalizationDecision?"Orchestrator stopped without a persisted Gui finalization decision; lifecycle was fail-closed as blocked.":finalizationDecision?.summary??parsed.options.summary);if(current.finished===null&&ownsLifecycleAttempt(current)){const activeChildren=activeDescendantRuns(id,candidateRuns);if(activeChildren.length>0){throw new UsageError(`Run ${id} cannot finish while descendant Runs are active: ${activeChildren.map(child=>child.run.run_id).join(", ")}`)}}if(!mustFailClosed&&parsed.flags.has("defer-orchestrator-closure")&&ownsLifecycleAttempt(current)){throw new UsageError(`Orchestrator Run closure cannot be deferred for Run ${id}`)}const deferClosure=!mustFailClosed&&parsed.flags.has("defer-orchestrator-closure");if(current.finished!==null){if(current.finished.status!==status){throw new UsageError(`Run V2 is already ${current.finished.status}: ${id}`)}const reconciliation2=await reconcileFinishedRunLifecycle(current,composition,lifecycle,{requestedOutcome,forceRequestedOutcome:mustFailClosed,summary:reconciliationSummary,changedFiles,evidenceIds,defer:deferClosure,candidateRuns});const interactionExecution2=await settleInteractionExecutionForRun(current,composition,mustFailClosed?reconciliationSummary??null:finalizationBlockReason);return{run:parsed.flags.has("events")||parsed.options.view==="full"?current:runV2Summary(current,composition),reconciliation:reconciliation2,execution:interactionExecution2,finalization_barrier:finalizationBarrier,closure:await assessRunLifecycleClosure(current,composition,candidateRuns),artifact_path:composition.runs.path(id)}}if(current.effective_usage_records.length===0){const usage=unavailableUsageRecord(current,parsed,current.records.length+1);await composition.runs.appendRecord(usage);current=foldRunV2Records([...current.records,usage])}const sequence=current.records.length+1;const record3=runFinishedV2Schema.parse({schema_version:2,event_id:runV2EventId(id,sequence),run_id:id,sequence,occurred_at:new Date().toISOString(),type:"run.finished",phase:latestRunV2Phase(current.records),status});const prospectiveRun=foldRunV2Records([...current.records,record3]);const closureGate=new LifecycleV2Gate(filesystem,composition.layout,{...composition,runs:runClosureView(composition.runs,current,prospectiveRun)});const reconciliation=await reconcileFinishedRunLifecycle(prospectiveRun,composition,closureGate,{requestedOutcome,forceRequestedOutcome:mustFailClosed,summary:reconciliationSummary,changedFiles,evidenceIds,defer:deferClosure,candidateRuns});const interactionExecution=await settleInteractionExecutionForRun(prospectiveRun,composition,mustFailClosed?reconciliationSummary??null:finalizationBlockReason);await syncLifecycleManifestResult({reconciliation,execution:interactionExecution},"execution",parsed,composition,filesystem);await composition.runs.appendRecord(record3);const run=await composition.runs.read(id);const closure=await assessRunLifecycleClosure(run,composition,candidateRuns);return{run:parsed.flags.has("events")||parsed.options.view==="full"?run:runV2Summary(run,composition),reconciliation,execution:interactionExecution,finalization_barrier:finalizationBarrier,closure,artifact_path:composition.runs.path(id)}})}if(action==="finalization"){const current=await composition.runs.read(id);if(!ownsLifecycleAttempt(current)){throw new UsageError(`Run ${id} is not an orchestrator Run`)}const outcome=lifecycleOutcomeOption(parsed.options);if(outcome===void 0)throw new UsageError("Missing options: --task-outcome");const summary=parsed.options.summary?.trim();if(summary===void 0||summary.length===0)throw new UsageError("Missing options: --summary");const evidenceIds=csvOption(parsed.options.evidence);assertFinalizationEvidenceInput(evidenceIds);const changedFiles=csvOption(parsed.options["changed-files"]);const requestedFinalizerRunId=parsed.options["finalizer-run-id"]?.trim();return composition.runs.withUsageAttributionLock(async()=>{const fresh=await composition.runs.read(id);const existing=fresh.finalization_decision??null;if(existing!==null){if(requestedFinalizerRunId!==void 0&&requestedFinalizerRunId.length>0&&existing.finalizer_run_id!==requestedFinalizerRunId||existing.outcome!==outcome||existing.summary!==summary||!sameStringSet(existing.evidence_ids,evidenceIds)||!sameStringSet(existing.changed_files,changedFiles)){throw new UsageError(`Run ${id} already has a different Gui finalization decision`)}return{finalization:existing,reused:true,artifact_path:composition.runs.path(id)}}const lockedCandidates=await composition.runs.list();const finalizers=lockedCandidates.filter(candidate=>candidate.run.parent_run_id===id&&effectiveRunV2Purpose(candidate.run)==="finalization"&&candidate.run.agent==="agent-finalizer");const activeFinalizers=finalizers.filter(candidate=>candidate.finished===null);const terminalFallbackFinalizers=finalizers.filter(candidate=>candidate.finished!==null&&candidate.run.client==="codex-subagent"&&candidate.run.client_turn_id===null&&candidate.run.provider===null&&candidate.run.model==="unavailable");const candidatesForDecision=fresh.finished===null?activeFinalizers:terminalFallbackFinalizers;const lockedFinalizer=requestedFinalizerRunId===void 0||requestedFinalizerRunId.length===0?candidatesForDecision.length===1?candidatesForDecision[0]:void 0:candidatesForDecision.find(candidate=>candidate.run.run_id===requestedFinalizerRunId);if(lockedFinalizer===void 0){if(fresh.finished!==null){throw new UsageError(`Run ${id} requires its exact terminal fallback Gui finalizer to record a post-close decision`)}throw new UsageError(`Run ${id} requires an active Gui finalizer to record its decision`)}if(fresh.finished!==null&&fresh.finished.status!=="completed"){throw new UsageError(`Run V2 is already ${fresh.finished.status}: ${id}`)}const lockedActiveElsewhere=activeDescendantRuns(id,lockedCandidates).filter(candidate=>candidate.run.run_id!==lockedFinalizer.run.run_id);if(lockedActiveElsewhere.length>0){throw new UsageError(`Gui finalization for Run ${id} requires every other descendant to be terminal: ${lockedActiveElsewhere.map(run=>run.run.run_id).join(", ")}`)}const record3=runFinalizationDecidedV2Schema.parse({schema_version:2,event_id:runV2EventId(id,fresh.records.length+1),run_id:id,sequence:fresh.records.length+1,occurred_at:new Date().toISOString(),type:"run.finalization.decided",finalizer_run_id:lockedFinalizer.run.run_id,outcome,summary,evidence_ids:evidenceIds,changed_files:changedFiles});await composition.runs.appendRecord(record3);return{finalization:record3,reused:false,artifact_path:composition.runs.path(id)}})}throw new UsageError(`Unknown Run V2 action: ${action??""}`)}var init_v2_run=__esm({"src/commands/v2-run.ts"(){"use strict";init_src2();init_finalization_evidence_input();init_task_attempt();init_v2_run_active_window();init_v2_run_interaction_execution();init_v2_run_cancellation_and_aggregate();init_src3();init_src6();init_attribution_v2();init_cli_arguments();init_conversation_intake();init_developer_identity_command();init_execution_intake_compatibility();init_lifecycle_manifest_commands();init_lifecycle_v2();init_open_work_reconciliation();init_record_codex_telemetry();init_run_agent_identity();init_run_budget();init_run_client_invocation();init_run_closure_view();init_run_conversation_v2();init_run_finalization_barrier();init_run_finalization_evidence_v2();init_run_hierarchy();init_run_lifecycle_closure();init_run_lifecycle_reconciliation();init_v2_run_historical_codex_timing();init_v2_run_snapshot();init_v2_run_support();init_v2_run_active_window();init_v2_run_snapshot()}});async function runConversationV2Command(action,parsed,composition,filesystem,lifecycle){if(action==="start"){const client=parsed.options.client??"codex";const clientInvocation=await resolveRunClientInvocation(filesystem,client);const requestedIntent=resolveConversationIntent(parsed,clientInvocation.userMessage);assertDefinitionConversationIntake(parsed,requestedIntent);if(requestedIntent==="git_only"||isImplicitConversationCapture(parsed)&&isGitOnlyPublicationRequest(clientInvocation.userMessage)){return{skipped:true,reason:"git-only-publication",message:"Explicit deploy, push, and publication requests do not create ZAIP lifecycle records"}}const request=conversationRequestOptions(clientInvocation.userMessage);const threadContext=await latestThreadContext(composition,client,clientInvocation.clientThreadId);let intent=requestedIntent;const newWorkMetadata=intent==="new_work"?requireSemanticNewWorkMetadata(parsed):null;let target=intent==="continue"||intent==="refine"||intent==="rework"?explicitIntakeTarget(parsed)??threadContext.implicitTarget:null;let decision=intakeDecision(parsed,intent);if(intent==="new_work"&&newWorkMetadata!==null&&decision.classification_source!=="explicit"&&threadContext.implicitTarget?.taskId!==void 0){const focusedTask=(await composition.tasks.read(threadContext.implicitTarget.taskId)).task;if((focusedTask.status==="draft"||focusedTask.status==="planned")&&focusedTask.started_at===null&&describesEquivalentWork(newWorkMetadata,focusedTask)){intent="continue";target=threadContext.implicitTarget;decision={intent:"continue",classification_source:"fallback",confidence:1,reason_codes:["equivalent-thread-work-reused"]}}}if((intent==="continue"||intent==="refine"||intent==="rework")&&target===null){intent="conversation";target=null;decision={intent:"conversation",classification_source:"fallback",confidence:0,reason_codes:["target-not-resolved"]}}const existing=await findIntakeForExactTurn(composition,client,clientInvocation);if(existing!==null){assertExactIntakeRequestCompatible(existing,parsed,intent);const task2=existing.run.task_id===null?null:(await composition.tasks.read(existing.run.task_id)).task;return{task:task2,run:existing.run,task_path:task2===null?null:composition.tasks.path(task2.id),run_path:composition.runs.path(existing.run.run_id),reused:true}}const model=resolveConversationModel(parsed.options.model,clientInvocation.observedModel);const reasoningEffort=resolveConversationReasoningEffort(parsed.options["reasoning-effort"],clientInvocation.observedReasoningEffort);const timeZone=composition.layout.project.timezone;const conversationId2=parsed.options.conversation??threadContext.conversationId??createConversationId(intent==="new_work"?"new-work":"conversation");const clientTurnId=clientInvocation.clientTurnId??`local-${Date.now()}-${createCollisionCode(16)}`;const executionPolicy={failure_policy:"stop_on_terminal_failure",max_parallelism:1,max_operational_retries:1,max_repair_cycles_per_task:0,verification_mode:"scoped"};let activeTaskContinuation=false;const directAuthorization=parsed.options["direct-authorization"];const commonInput=(executionId,executionKind)=>({...parsed.options.run===void 0?{}:{id:parsed.options.run},phase:conversationCapturePhase(intent,activeTaskContinuation),workType:runV2WorkTypeOption(intent==="rework"?"rework":parsed.options["work-type"]??"new"),client,runRole:"orchestrator",runPurpose:"orchestration",requiresFinalizer:executionKind==="delivery",executionKind,executionEligibility:[],...directAuthorization===void 0||executionKind!=="delivery"?{}:{directExecutionAuthorization:directAuthorization},agent:"agent-orchestrator",agentName:"zaip-agent-orchestrator",provider:parsed.options.provider??null,model,reasoningEffort,clientThreadId:clientInvocation.clientThreadId,clientTurnId,conversationId:conversationId2,executionId,intake:decision});if(intent==="new_work"&&composition.layout.projectConfig?.assurance?.require_final_commit===true)await assertGitDeliveryReady(filesystem.root);const rootDeveloperIdentity=await resolveDeveloperIdentityForRoot(filesystem);const openIntakes=await openThreadIntakes(composition,client,clientInvocation.clientThreadId,clientInvocation.clientTurnId);const continuationOfRunId=target===null?null:openIntakes.find(fold=>runMatchesTarget(fold,target))?.run.run_id??null;if(intent!=="new_work"){if(intent==="continue"&&target?.taskId!==void 0){const targetedTask=(await composition.tasks.read(target.taskId)).task;if(targetedTask.status==="blocked"){await lifecycle.startTask(targetedTask.id,"resume")}}const canonicalTaskExecution=target?.taskId===void 0?null:await activeCanonicalTaskExecution(target.taskId,composition);const canonicalMacroExecution=intent==="continue"&&target?.taskId===void 0&&(target?.specId!==void 0||target?.prdId!==void 0)?await resolveCanonicalMacroExecution(target,composition,parsed.options.execution):null;let execution=target===null?await composition.executions.createInteraction({id:parsed.options.execution??createId("EXEC",`interaction-${intent}`,{timeZone}),clientTurnId,conversationId:conversationId2,policy:executionPolicy}):canonicalTaskExecution??canonicalMacroExecution??await composition.executions.createDeliveryIntake({id:parsed.options.execution??createId("EXEC",`delivery-${intent}`,{timeZone}),clientTurnId,origin:target.taskId!==void 0?{type:"task",task_id:target.taskId}:target.specId!==void 0?{type:"spec",spec_id:target.specId}:{type:"prd",prd_id:target.prdId},policy:executionPolicy});const targetTask=target?.taskId===void 0?null:(await composition.tasks.read(target.taskId)).task;activeTaskContinuation=intent==="continue"&&(canonicalTaskExecution!==null&&targetTask!==null&&(targetTask.status==="executing"||targetTask.status==="verifying")||canonicalMacroExecution!==null);if(canonicalMacroExecution?.status==="planned"){execution=await composition.executions.transition(canonicalMacroExecution.id,"running")}const input={...commonInput(execution.id,execution.kind??"delivery"),developerIdentity:rootDeveloperIdentity,shortName:parsed.options["short-name"]??intent.replaceAll("_","-"),entrypoint:target?.entrypoint??"conversation",...target?.taskId===void 0?{}:{taskId:target.taskId},...targetTask===null?{}:{changeId:targetTask.change_id},...target?.specId===void 0?{}:{specId:target.specId},...target?.prdId===void 0?{}:{prdId:target.prdId},continuationOfRunId};await validateRunV2Attribution(input,composition);const writer=await composition.runs.start(input);const settledIntakes=await finishOpenThreadIntakes(openIntakes,composition,filesystem,parsed,lifecycle);const task2=input.taskId==null?null:(await composition.tasks.read(input.taskId)).task;return{task:task2,run:writer.started,settled_intakes:settledIntakesForView(settledIntakes,parsed.options.view),task_path:task2===null?null:composition.tasks.path(task2.id),run_path:composition.runs.path(writer.started.run_id)}}const metadata2=newWorkMetadata??requireSemanticNewWorkMetadata(parsed);const taskId=parsed.options.task??createId("TASK",metadata2.shortName,{timeZone});const changeId=parsed.options.change??createId("CHG",metadata2.shortName,{timeZone});const{task,change}=await createTaskAndChangeAtomically(filesystem,composition,{id:taskId,changeId,title:metadata2.title,shortName:metadata2.shortName,objective:metadata2.objective,risk:riskOption(parsed.options.risk??request.risk),priority:priorityOption(parsed.options.priority),owner:parsed.options.owner??null,requirementIds:csvOption(parsed.options.requirements??"REQ-WORK-001"),acceptanceIds:csvOption(parsed.options.acceptance??"AC-WORK-001-09"),dependsOn:[],writeScopes:csvOption(parsed.options["write-scopes"]),assuranceRiskSignals:taskAssuranceRiskSignalsOption(parsed.options["assurance-risk-signals"])});const createdArtifacts=new Map([[composition.tasks.path(task.id),composition.tasks.serialize(task)],[composition.changes.path(change.id),composition.changes.serialize(change)]]);let deliveryExecution;try{deliveryExecution=await composition.executions.createDeliveryIntake({id:parsed.options.execution??createId("EXEC",`delivery-${intent}`,{timeZone}),clientTurnId,origin:{type:"task",task_id:task.id},policy:executionPolicy})}catch(error51){await rollbackTaskChangeCreation(filesystem,createdArtifacts);throw error51}try{const plan=createTaskFirstPreparedPlan({task,executionId:deliveryExecution.id,preparedAt:new Date().toISOString(),policy:executionPolicy});await composition.tasks.setPreparedPlan(task.id,plan);await composition.materializer.execute(plan);await composition.executions.transition(deliveryExecution.id,"running");await composition.changes.transition(changeId,"executing");const activeTask=await lifecycle.startTask(task.id);const input={...commonInput(deliveryExecution.id,"delivery"),developerIdentity:rootDeveloperIdentity,shortName:metadata2.shortName,entrypoint:"task",taskId,changeId};await validateRunV2Attribution(input,composition);const writer=await composition.runs.start(input);const settledIntakes=await finishOpenThreadIntakes(openIntakes,composition,filesystem,parsed,lifecycle);return{task:activeTask,run:writer.started,settled_intakes:settledIntakesForView(settledIntakes,parsed.options.view),task_path:composition.tasks.path(task.id),run_path:composition.runs.path(writer.started.run_id)}}catch(error51){const message=error51 instanceof Error?error51.message:String(error51);await composition.tasks.transition(taskId,"cancelled",{summary:`Conversation Run was not created: ${message}`,changed_files:[],evidence_ids:[],completed_run_id:null});await composition.changes.transition(changeId,"cancelled",`Conversation Run was not created: ${message}`);const currentExecution=(await composition.executions.read(deliveryExecution.id)).execution;if(currentExecution.status==="planned"||currentExecution.status==="running"){await composition.executions.transition(deliveryExecution.id,"cancelled",`Conversation Run was not created: ${message}`)}throw error51}}if(action==="finish"){requireOptions(parsed.options,["run","summary"]);const runId=parsed.options.run;const current=await composition.runs.read(runId);if(parsed.options.task!==void 0&¤t.run.task_id!==parsed.options.task)throw new UsageError(`Run ${runId} is not attributed to Task ${parsed.options.task}`);if(parsed.flags.has("cancel-task"))throw new UsageError("--cancel-task cannot bypass Gui; finish the delivery Run after Gui finalization");const{runRunV2Command:runRunV2Command2}=await Promise.resolve().then(()=>(init_v2_run(),v2_run_exports));const result2=await runRunV2Command2("finish",{...parsed,positionals:["run","finish",runId]},composition,filesystem,lifecycle);const task=current.run.task_id===null?null:(await composition.tasks.read(current.run.task_id)).task;return{...result2,task,summary:parsed.options.summary,task_path:task===null?null:composition.tasks.path(task.id),run_path:composition.runs.path(runId)}}throw new UsageError(`Unknown Conversation action: ${action??""}`)}async function activeCanonicalTaskExecution(taskId,composition){const task=(await composition.tasks.read(taskId)).task;if(task.status==="draft"||task.status==="planned")return null;const executionId=task.plan_ref?.execution_id??task.prepared_plan?.execution_id??null;if(executionId===null)return null;const execution=(await composition.executions.read(executionId)).execution;const terminal=new Set(["completed","failed","cancelled"]);return!terminal.has(execution.status)&&execution.dag.nodes.some(node=>node.task_id===task.id&&node.change_id===task.change_id)?execution:null}async function resolveCanonicalMacroExecution(target,composition,explicitExecutionId){const scope=target.specId===void 0?target.prdId===void 0?null:{type:"prd",id:target.prdId}:target.prdId===void 0?{type:"spec",id:target.specId}:null;if(scope===null){throw new UsageError("Macro continuation requires exactly one of SPEC or PRD")}const entity=scope.type==="spec"?(await composition.specs.read(scope.id)).spec:(await composition.prds.read(scope.id)).prd;const executionIds=[entity.prepared_plan?.execution_id,entity.plan_ref?.execution_id].filter(id=>typeof id==="string");const distinctExecutionIds=[...new Set(executionIds)];if(distinctExecutionIds.length!==1){throw new UsageError(distinctExecutionIds.length===0?`${scope.type.toUpperCase()} ${scope.id} has no prepared Execution for continuation`:`${scope.type.toUpperCase()} ${scope.id} has ambiguous prepared Executions`)}const executionId=distinctExecutionIds[0];if(executionId===void 0){throw new UsageError(`Prepared Execution cannot be resolved for ${scope.type.toUpperCase()} ${scope.id}`)}const execution=(await composition.executions.read(executionId)).execution;if(explicitExecutionId!==void 0&&explicitExecutionId!==execution.id){throw new UsageError(`Explicit Execution ${explicitExecutionId} conflicts with prepared Execution ${execution.id}`)}const originMatches=scope.type==="spec"?execution.origin.type==="spec"&&execution.origin.spec_id===scope.id:execution.origin.type==="prd"&&execution.origin.prd_id===scope.id;if(execution.kind!=="delivery"||execution.plan_hash===null||execution.dag.nodes.length===0||!originMatches){throw new UsageError(`Prepared Execution ${execution.id} is incompatible with ${scope.type.toUpperCase()} ${scope.id}`)}if(!new Set(["planned","running","verifying"]).has(execution.status)){throw new UsageError(`Prepared Execution ${execution.id} cannot continue from status ${execution.status}`)}return execution}function conversationCapturePhase(intent,isActiveTaskContinuation=false){if(intent==="new_work"||intent==="continue"&&isActiveTaskContinuation)return"execution";return intent==="refine"||intent==="rework"?"planning":"conversation"}function resolveConversationModel(explicitModel,observedModel=null){return explicitModel??observedModel??"unknown"}function resolveConversationReasoningEffort(explicitEffort,observedEffort){if(explicitEffort!==void 0)return runV2ReasoningEffortSchema.parse(explicitEffort);const observed=runV2ReasoningEffortSchema.safeParse(observedEffort);return observed.success?observed.data:null}function runV2CostInput2(fold){return{run:{run_id:fold.run.run_id,attribution_status:fold.run.attribution_status,conversation_id:fold.run.conversation_id,execution_id:fold.run.execution_id,task_id:fold.run.task_id,spec_id:fold.run.spec_id,prd_id:fold.run.prd_id,change_id:fold.run.change_id,work_type:fold.run.work_type},records:fold.records,effective_usage_records:fold.effective_usage_records}}function runV2Summary(fold,composition){const usage=aggregateRunV2Usage([runV2CostInput2(fold)],fold.run.run_id).total;const callIds=new Set([...fold.model_selection_records.map(record3=>record3.invocation_id),...fold.provider_invocation_records.map(record3=>record3.invocation_id)]);return{id:fold.run.run_id,status:fold.status,created_at:fold.run.occurred_at,finished_at:fold.finished?.occurred_at??null,phase:latestRunV2Phase(fold.records),run_role:effectiveRunV2Role(fold.run),parent_run_id:fold.run.parent_run_id,entrypoint:fold.run.entrypoint,work_type:fold.run.work_type,intake:fold.run.intake??null,agent:fold.run.agent,agent_name:fold.run.agent_name??(fold.run.agent.startsWith("agent-")?`zaip-agent-${fold.run.agent.slice("agent-".length)}`:fold.run.agent),model:fold.run.model,reasoning_effort:fold.run.reasoning_effort??fold.model_selection_records[0]?.requested.reasoning_effort??null,call_count:callIds.size===0?null:callIds.size,client_thread_id:fold.run.client_thread_id??null,client_turn_id:fold.run.client_turn_id??null,conversation_id:fold.run.conversation_id,execution_id:fold.run.execution_id,task_id:fold.run.task_id,spec_id:fold.run.spec_id,prd_id:fold.run.prd_id,change_id:fold.run.change_id,usage:{event_count:usage.usage_event_count,tokens:usage.tokens,cost:usage.cost,coverage:usage.coverage},artifact_path:composition.runs.path(fold.run.run_id)}}var init_run_conversation_v2=__esm({"src/run-conversation-v2.ts"(){"use strict";init_src();init_src2();init_src3();init_attribution_v2();init_cli_arguments();init_conversation_intake();init_conversation_intake_settlement();init_developer_identity_command();init_git_delivery_preflight();init_prepared_plan_v22();init_run_client_invocation();init_task_assurance_options();init_task_change_creation();init_run_conversation_summary();init_conversation_intake_settlement()}});import{basename as basename6,dirname as dirname16,resolve as resolve19}from"node:path";import{pathToFileURL}from"node:url";import{resolve as resolve3}from"node:path";init_src();import{createHash}from"node:crypto";var NATIVE_SUBAGENT_POLICY="For Codex delegation, a ZAIP Sub-Run exists only when started with the native collaboration subagent mechanism (`spawn_agent`). `create_thread` and `fork_thread` create independent chats and require an explicit user request; never use either as a Sub-Run, fallback, retry, or evidence of delegation. If native delegation is unavailable, report the limitation rather than create an independent chat. A catalog name, task_name, title, or prompt never proves native ancestry. Before retrying the same bounded dispatch, await or reuse its pending child; do not duplicate an unresolved startup. Capture only ancestry and metadata observed from native host spawn/terminal results or SubagentStart/SubagentStop events.";function agentGuidanceFiles(catalog){validateGuidanceCatalog(catalog);const files=[];for(const agent of[...catalog.agents].sort(byId)){const payload=stableJson({kind:"agent",schema_version:1,definition:agent});const semanticHash=digest(payload);files.push({client:"codex",subject:agent.id,projection:"canonical",path:`.agents/config/clients/codex/agents/${agent.codex_name}.toml`,content:renderCodexAgent(agent,catalog,payload),semantic_hash:semanticHash});for(const alias of agent.compatibility?.aliases??[]){const shim=stableJson({kind:"agent-alias",schema_version:1,alias,canonical:{id:agent.id,codex_name:agent.codex_name,codex_task_name:agent.codex_task_name}});const subject2=`alias:${alias.kind}:${alias.value}`;if(alias.kind==="id"){files.push({client:"claude",subject:subject2,projection:"compatibility-shim",path:`.claude/agents/${alias.value}.md`,content:renderGuidance(alias.value,`Deprecated alias for ${agent.id}. Use ${agent.id}. Removal deadline: ${alias.remove_after}.`,shim),semantic_hash:digest(shim)})}if(alias.kind==="codex_name"){files.push({client:"codex",subject:subject2,projection:"compatibility-shim",path:`.agents/config/clients/codex/agents/${alias.value}.toml`,content:renderCodexAlias(agent,alias.value,alias.remove_after,shim),semantic_hash:digest(shim)})}}files.push({client:"claude",subject:agent.id,projection:"canonical",path:`.claude/agents/${agent.id}.md`,content:renderGuidance(agent.id,claudeAgentPurpose(agent),payload),semantic_hash:semanticHash})}for(const squad of[...catalog.squads].sort(byId)){const payload=stableJson({kind:"squad",schema_version:1,definition:squad});files.push(...clientFiles("squads",squad.id,renderGuidance(squad.id,squad.purpose,payload),digest(payload)))}return files}function compareAgentGuidance(files){const drifted=[];const paths=new Set;const bySubject=new Map;for(const file2 of files){if(paths.has(file2.path))drifted.push(`${file2.path}:duplicate-path`);paths.add(file2.path);if(file2.projection!=="canonical")continue;const entry2=bySubject.get(file2.subject)??{};if(entry2[file2.client]!==void 0)drifted.push(`${file2.subject}:${file2.client}:duplicate`);entry2[file2.client]=file2;bySubject.set(file2.subject,entry2)}for(const[subject2,entry2]of[...bySubject].sort(([left],[right])=>left.localeCompare(right))){if(entry2.codex===void 0||entry2.claude===void 0){drifted.push(`${subject2}:missing-client`);continue}if(entry2.codex.semantic_hash!==entry2.claude.semantic_hash){drifted.push(`${subject2}:semantic-drift`)}}const manifest=[...files].sort((left,right)=>left.path.localeCompare(right.path)).map(({client,subject:subject2,projection,semantic_hash})=>({client,subject:subject2,projection,semantic_hash}));return{valid:drifted.length===0,drifted,semantic_hash:digest(stableJson(manifest))}}async function buildAgentGuidance(filesystem,catalog){const files=agentGuidanceFiles(catalog);const parity=compareAgentGuidance(files);if(!parity.valid)throw new Error(`Agent guidance parity failed: ${parity.drifted.join(", ")}`);for(const file2 of files){if(await filesystem.exists(file2.path)){const current=await filesystem.readText(file2.path);if(!isManagedGuidance(current)){throw new Error(`Refusing to overwrite user-owned agent guidance: ${file2.path}`)}}}const expectedPaths=new Set(files.map(file2=>file2.path));for(const path of await staleManagedAgentGuidancePaths(filesystem,expectedPaths)){await filesystem.removeFile(path)}for(const file2 of files)await filesystem.writeTextAtomic(file2.path,file2.content);return parity}async function checkAgentGuidance(filesystem,catalog){const files=agentGuidanceFiles(catalog);const parity=compareAgentGuidance(files);const drifted=[...parity.drifted];const findings=[];for(const file2 of files){if(!await filesystem.exists(file2.path)){drifted.push(file2.path);findings.push({classification:"missing",path:file2.path});continue}if(await filesystem.readText(file2.path)!==file2.content){drifted.push(file2.path);findings.push({classification:"content-drift",path:file2.path})}}const inventory2=await agentGuidanceInventory(filesystem,new Set(files.map(file2=>file2.path)));for(const path of inventory2.staleManaged){drifted.push(path);findings.push({classification:"stale-managed",path})}for(const path of inventory2.unknownUnmanaged){findings.push({classification:"unknown-unmanaged",path})}return{...parity,valid:drifted.length===0,drifted:[...new Set(drifted)].sort(),findings:findings.sort((left,right)=>left.classification.localeCompare(right.classification)||left.path.localeCompare(right.path))}}function validateGuidanceCatalog(catalog){const agents=new Map(catalog.agents.map(agent=>[agent.id,agent]));if(agents.size!==catalog.agents.length)throw new Error("Agent ids must be unique");const squadIds=new Set(catalog.squads.map(squad=>squad.id));if(squadIds.size!==catalog.squads.length)throw new Error("Squad ids must be unique");for(const agent of catalog.agents){if(!agent.codex_name.startsWith("zaip-agent-")){throw new Error(`${agent.id} codex_name must start with zaip-agent-`)}const expectedTaskName=agent.nickname_candidates[0];if(agent.codex_task_name!==expectedTaskName){throw new Error(`${agent.id} codex_task_name must equal ${expectedTaskName}`)}const expectedNickname=`${agent.persona.nome}_${agent.persona.cargo}_zaip_agent`;if(agent.nickname_candidates.length!==1||agent.nickname_candidates[0]!==expectedNickname){throw new Error(`${agent.id} nickname_candidates must contain only the derived persona nickname`)}}for(const squad of catalog.squads){if(!squad.review_policy.independent)throw new Error(`${squad.id} requires independent review`);const unresolvedMembers=squad.members.map(id=>agents.get(id));if(unresolvedMembers.some(agent=>agent===void 0)){throw new Error(`${squad.id} has unknown members`)}const members=unresolvedMembers.filter(isDefined);const executorIds=new Set(members.filter(agent=>agent!==void 0&&squad.review_policy.executor_roles.includes(agent.role)).map(agent=>agent.id));const reviewerIds=new Set(members.filter(agent=>agent!==void 0&&squad.review_policy.reviewer_roles.includes(agent.role)).map(agent=>agent.id));if(executorIds.size===0||reviewerIds.size===0){throw new Error(`${squad.id} must contain executor and reviewer roles`)}if([...executorIds].some(id=>reviewerIds.has(id))){throw new Error(`${squad.id} cannot assign self-review`)}}}function clientFiles(group,subject2,content,semanticHash){return["codex","claude"].map(client=>({client,subject:subject2,projection:"canonical",path:`.${client}/${group}/${subject2}.md`,content,semantic_hash:semanticHash}))}function renderCodexAgent(agent,catalog,payload){const hash4=digest(payload);const name=agent.codex_name;const finalizer=catalog.agents.find(candidate=>candidate.id==="agent-finalizer");if(agent.role==="orchestrator"&&finalizer===void 0){throw new Error("Agent catalog must define agent-finalizer")}const instructions=[`Operate as Codex agent ${name} (ZAIP catalog id ${agent.id}) with role ${agent.role}.`,agent.purpose,`Capabilities: ${agent.capabilities.join(", ")}.`,`Allowed tools: ${agent.tools.join(", ")||"none"}.`,`Available skills: ${agent.skills.join(", ")||"none"}; load matching skills only. Change/execution skills apply to persistent delivery; Meta Ads applies only to Meta work.`,"Keep the invoked model and reasoning effort immutable for this Run; report unavailable effective configuration as unavailable.",`Write scopes: ${agent.write_scopes.join(", ")||"read-only"}.`,agent.write_scopes.length===0?"This role is read-only. Do not create, modify, move, or delete workspace files.":"The Codex host grants workspace-write at the workspace boundary, not per-path. Treat the declared write scopes as mandatory: do not modify files outside them; report any required expansion to the parent before writing.",`Inputs: ${agent.contract.inputs.join(", ")}.`,`Outputs: ${agent.contract.outputs.join(", ")}.`,`Evidence: ${agent.contract.evidence.join(", ")}.`,`Use when: ${agent.use_when.join("; ")}.`,`Do not use when: ${agent.do_not_use.join("; ")}.`,...remoteCloudBoundary(agent),...remoteAwsBoundary(agent),...specialistBoundaries(agent),...agent.role==="orchestrator"?["You are the dispatcher for your Task attempt. If the physical root already owns exactly this Task, it is the responsible orchestrator: it dispatches executors/reviewers and Gui directly, without an extra Dave child. A macro root dispatches one Task orchestrator per eligible Task and must not dispatch that Task's workers itself. Never create two responsible orchestrators or require two Guis for the same Task attempt. Never reassign your invocation to another Task.","Tool names in the catalog are capability labels, not literal host tool names. Native collaboration permits spawn_agent, send_input, wait_agent and close_agent for authorized descendants. Discover deferred native tools through the host tool registry before declaring them unavailable. Read-only filesystem permissions do not prohibit native delegation or waiting; do not use discovery to run persistence commands, bypass permissions or create independent chats.","Report child IDs and intermediate results as non-terminal progress, not a final response. Keep your native invocation open until the executor/reviewer and last Gui child have terminated. If you cannot remain active or complete that sequence, report an explicit blocked interruption; do not claim the attempt is finalized.","Identify the requested output and its domain. Under autonomy-v1, standalone Tasks prefer direct work with the user's selected principal model/effort; delegate only for a concrete specialist, isolation, review or finalization need. Before delegation disclose that ZAIP policy may select different child models/efforts. Otherwise preserve the legacy specialist routing contract. References and titles never select an executor or justify escalation.","Default to one domain executor per bounded result. Bring a secondary specialist only when its unresolved domain decision is necessary to the primary output; split independent outputs into sequential Tasks and preserve a true mixed-output conflict instead of codispatching.","Subagent lifecycle hooks are best-effort. You are read-only: relay observed session/thread/turn metadata and events to the authorized host; do not invoke CLI persistence. Canonical order is start -> actual Gui decision -> stop -> finish. The rich stop capture accepts the exact decision in task-outcome/summary/evidence/changed-files and persists it before Stop; Gui need not wait alive for a receipt. Never infer decisions from completed status. Preserve observed ancestry/model/effort; unavailable stays unavailable. UUID is not agent_path and cannot authorize path-only fallback.","Reviewer, auditor, and integrator Sub-Runs are permitted when their capabilities match the work.",`After all other descendants finish, delegate one real final direct Sub-Run to ${finalizer?.codex_name}. Use its cataloged agent_type; pass task_name ${finalizer?.codex_task_name} only when the native tool schema supports that argument. Do not finish the responsible Run or report a terminal Execution outcome before that Sub-Run has completed.`,"Give Gui the real responsible Run ID and exact candidate proof. It returns one immutable outcome, reason, evidence references and owned changed files. Do not require receipt polling or an active-turn handshake. The host persists the real decision through rich stop capture before closing the responsible Run. A terminal rich Gui with open parent is eligible; a closed parent without decision requires an authorized new attempt. Never invent approval or reuse another attempt's decision."]:[],...agent.role==="execution-finalizer"?["Evaluate closure evidence without writing product or lifecycle files. Return exactly one real terminal decision: outcome (completed, blocked, failed, cancelled), observed reason, evidence references, summary, owned changed files and responsible Run ID. Do not poll start/decision receipts or wait to stay active: the authorized host persists your actual decision with rich stop capture before closing the responsible Run. Capture latency is not a product defect or a reason to invent a blocked technical judgment. Missing proof remains blocked; cancelled requires explicit human intent. A native completed status is not persisted Task approval. Never invent metadata or convert UUID into agent_path."]:[],...agent.role==="orchestrator"?[]:["You are a worker selected by zaip-agent-orchestrator. Do not dispatch peer catalog roles; return your bounded result to the orchestrator, which exclusively controls further delegation."],`Escalate only to catalog identities: ${agent.escalation.map(id=>catalogCodexName(id)).join(", ")||"root agent"}.`,...agent.role==="orchestrator"?["Delegate only registered catalog identities: agent_type uses codex_name. Send task_name equal to codex_task_name only if the native tool schema exposes task_name; otherwise omit it. nickname_candidates belongs to the generated profile, not a substitute spawn argument. Do not require an exact nickname because the host may add a generated suffix.","Own exactly one Task attempt when Task-scoped. Dispatch executors and reviewers, then Gui as your last direct child; never ask a worker to spawn its own finalizer. Macro coordinators dispatch Task orchestrators and retain separate integration gates. Preserve actual native ancestry, depth and global budgets.",NATIVE_SUBAGENT_POLICY]:["Do not spawn children or create independent chats. Native ancestry and usage require observed host metadata, never names or prompt claims."],`When this agent is delegated, require the cataloged agent_type ${agent.codex_name}. If the native tool exposes task_name use ${agent.codex_task_name}; otherwise omit it and preserve the observed host identity.`,"Accept only concrete bounded delegated work. Preserve parent requirements and return a concise result with evidence locators.",agent.role==="execution-finalizer"?"You do not grant product approval; your sole approval-like action is the restricted terminal outcome above.":agent.review.can_approve?`You may approve only roles outside: ${agent.review.cannot_review_roles.join(", ")||"none"}.`:"You cannot approve your own work or issue final approval."].join("\n");const sandboxMode=agent.write_scopes.length===0?"read-only":"workspace-write";const reasoningEffort=agent.model.reasoning_effort;const preferredModel=agent.model.preferred[0];const modelConfig=agent.model.preferred.length===1&&preferredModel!==void 0&&preferredModel!=="policy-selected"?`model = ${tomlString(preferredModel)}
|
|
376
376
|
${reasoningEffort===void 0?"":`model_reasoning_effort = ${tomlString(reasoningEffort)}
|
|
377
377
|
`}`:"";return`# zaip-managed generated-do-not-edit source=agent-catalog schema=1 sha256=${hash4}
|
|
@@ -1839,7 +1839,7 @@ ${message.content}`).join("\n\n");const contract=[`Agent: ${invocation.agent_id}
|
|
|
1839
1839
|
|
|
1840
1840
|
${messages}
|
|
1841
1841
|
`}function resumeId(token2,provider){if(token2===null)return null;const prefix=`${provider}:`;if(!token2.startsWith(prefix)||token2.length===prefix.length){throw new Error(`Invalid ${provider} checkpoint token`)}return token2.slice(prefix.length)}function checkpointId(provider,sessionId){const normalized=sessionId.toUpperCase().replace(/[^A-Z0-9-]/g,"-");return`CHK-${provider.toUpperCase()}-${normalized}`}function unavailableUsage(){return{input_tokens:0,cached_input_tokens:0,output_tokens:0,reasoning_tokens:0,source:"unavailable"}}function nonnegativeInteger(value){return typeof value==="number"&&Number.isInteger(value)&&value>=0?value:0}function asOptionalRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)?value:null}var ClaudeRuntimeProtocol=class{constructor(now=()=>new Date().toISOString()){this.now=now}now;prepare(invocation){const sessionId=resumeId(invocation.resume_from,"claude");const args=["--print","--output-format","stream-json","--verbose","--model",invocation.model,"--effort",invocation.reasoning_effort,...sessionId===null?[]:["--resume",sessionId]];const translator=new ClaudeEventTranslator(invocation,this.now);return{args,stdin:renderInvocationPrompt(invocation),translate:value=>translator.translate(value),finish:()=>[]}}};var ClaudeEventTranslator=class extends NativeProtocolEmitter{#assistantUsage=null;translate(value){const passthrough=this.passthrough(value);if(passthrough!==null)return passthrough;const record3=asRecord(value,"Claude event");const type=requiredString(record3,"type");if(type==="system")return this.system(record3);if(type==="assistant")return this.assistant(record3);if(type==="user")return this.user(record3);if(type==="result")return this.result(record3);if(type==="stream_event")return[];return[]}system(record3){if(record3.subtype!=="init")return[];return this.start("claude",requiredString(record3,"session_id"))}assistant(record3){const message=asRecord(record3.message,"Claude assistant message");const content=contentBlocks(message.content,"Claude assistant content");const events=[];for(const block2 of content){const type=requiredString(block2,"type");if(type==="text")events.push(...this.output(requiredString(block2,"text")));if(type==="tool_use"){events.push(...this.toolRequested(requiredString(block2,"id"),requiredString(block2,"name"),block2.input??{}))}}if(message.usage!==void 0){this.#assistantUsage=addUsage(this.#assistantUsage,runtimeUsage(message.usage,"cache_read_input_tokens"));events.push(...this.updateUsage(this.#assistantUsage))}return events}user(record3){const message=asRecord(record3.message,"Claude user message");const events=[];for(const block2 of contentBlocks(message.content,"Claude user content")){if(block2.type==="tool_result"){events.push(...this.toolCompleted(requiredString(block2,"tool_use_id"),block2.content??null))}}return events}result(record3){const isError=record3.is_error===true||record3.subtype!=="success";if(isError){const message=optionalString(record3.result)??errorMessage(record3.errors);return this.fail(message,optionalString(record3.subtype))}const providerUsage=record3.usage===void 0?null:runtimeUsage(record3.usage,"cache_read_input_tokens");return this.complete(optionalString(record3.result),maximumUsage(this.#assistantUsage,providerUsage))}};function contentBlocks(value,label){if(!Array.isArray(value))throw new Error(`${label} must be an array`);return value.map(block2=>asRecord(block2,label))}function errorMessage(value){if(!Array.isArray(value))return"Claude reported an unknown error";const messages=value.map(item=>optionalString(item)).filter(item=>item!==null);return messages.join("; ")||"Claude reported an unknown error"}function addUsage(previous,current){if(previous===null)return current;return{input_tokens:previous.input_tokens+current.input_tokens,cached_input_tokens:previous.cached_input_tokens+current.cached_input_tokens,output_tokens:previous.output_tokens+current.output_tokens,reasoning_tokens:previous.reasoning_tokens+current.reasoning_tokens,source:"provider"}}function maximumUsage(left,right){if(left===null)return right;if(right===null)return left;return{input_tokens:Math.max(left.input_tokens,right.input_tokens),cached_input_tokens:Math.max(left.cached_input_tokens,right.cached_input_tokens),output_tokens:Math.max(left.output_tokens,right.output_tokens),reasoning_tokens:Math.max(left.reasoning_tokens,right.reasoning_tokens),source:"provider"}}var CodexRuntimeProtocol=class{constructor(now=()=>new Date().toISOString()){this.now=now}now;prepare(invocation){const threadId=resumeId(invocation.resume_from,"codex");const args=threadId===null?["exec","--json","--model",invocation.model,"--config",`model_reasoning_effort=${JSON.stringify(invocation.reasoning_effort)}`,"-"]:["exec","resume",threadId,"--json","--model",invocation.model,"--config",`model_reasoning_effort=${JSON.stringify(invocation.reasoning_effort)}`,"-"];const translator=new CodexEventTranslator(invocation,this.now);return{args,stdin:renderInvocationPrompt(invocation),translate:value=>translator.translate(value),finish:()=>translator.finish()}}};var CodexEventTranslator=class extends NativeProtocolEmitter{#pendingError=null;#requestedTools=new Set;translate(value){const passthrough=this.passthrough(value);if(passthrough!==null)return passthrough;const record3=asRecord(value,"Codex event");const type=requiredString(record3,"type");if(type==="thread.started"){return this.start("codex",requiredString(record3,"thread_id"))}if(type==="turn.started")return[];if(type==="item.started")return this.itemStarted(asRecord(record3.item,"Codex item"));if(type==="item.completed")return this.itemCompleted(asRecord(record3.item,"Codex item"));if(type==="item.updated")return[];if(type==="turn.completed"){return this.complete(null,runtimeUsage(record3.usage,"cached_input_tokens"))}if(type==="turn.failed"){const error51=asRecord(record3.error,"Codex turn error");return this.fail(requiredString(error51,"message"),optionalString(error51.code))}if(type==="error"){this.#pendingError=optionalString(record3.message)??"Codex reported an unknown error";return[]}return[]}finish(){if(this.#pendingError!==null&&this.started&&!this.terminal){return this.fail(this.#pendingError)}return[]}itemStarted(item){const kind=requiredString(item,"type");if(!isToolItem(kind))return[];const callId=requiredString(item,"id");this.#requestedTools.add(callId);return this.toolRequested(callId,toolName(kind,item),toolArguments(kind,item))}itemCompleted(item){const kind=requiredString(item,"type");if(kind==="agent_message")return this.output(requiredString(item,"text"));if(!isToolItem(kind))return[];const callId=requiredString(item,"id");const events=this.#requestedTools.delete(callId)?[]:this.toolRequested(callId,toolName(kind,item),toolArguments(kind,item));events.push(...this.toolCompleted(callId,toolOutput(kind,item)));return events}};function isToolItem(kind){return kind==="command_execution"||kind==="file_change"||kind==="mcp_tool_call"||kind==="web_search"}function toolName(kind,item){if(kind==="command_execution")return"command_execution";if(kind==="file_change")return"file_change";if(kind==="web_search")return"web_search";const server=optionalString(item.server);const tool=optionalString(item.tool)??optionalString(item.name)??"unknown";return server===null?tool:`${server}.${tool}`}function toolArguments(kind,item){if(kind==="command_execution")return{command:item.command};if(kind==="file_change")return{changes:item.changes??item.files??[]};if(kind==="web_search")return{query:item.query};return item.arguments??item.input??{}}function toolOutput(kind,item){if(kind==="command_execution"){return{output:item.aggregated_output??item.output??"",exit_code:item.exit_code??null,status:item.status??null}}if(kind==="file_change")return item.changes??item.files??item.status??null;return item.result??item.output??item.error??null}init_agent_runtime();import{spawn}from"node:child_process";import{realpath as realpath3}from"node:fs/promises";import{isAbsolute as isAbsolute2,relative as relative2}from"node:path";import{createInterface}from"node:readline";var secretKey=/(?:authorization|password|secret|token|api[_-]?key|credential)/i;var secretValue=/(?:Bearer\s+[A-Za-z0-9._~+/-]+=*|sk-[A-Za-z0-9_-]{8,}|gh[opsu]_[A-Za-z0-9_]{8,})/g;function redactInvocation(invocation){return{...invocation,input:{...invocation.input,messages:invocation.input.messages.map(message=>({...message,content:redactText(message.content)}))},metadata:Object.fromEntries(Object.entries(invocation.metadata).map(([key,value])=>[key,secretKey.test(key)?"[REDACTED]":redactText(value)]))}}function redactText(value){return value.replace(secretValue,"[REDACTED]")}var NodeRuntimeProcessFactory=class{constructor(options){this.options=options;this.#commands=new Set(options.allowedCommands.map(normalizeCommand));this.#environmentKeys=new Set(options.allowedEnvironmentKeys)}options;#commands;#environmentKeys;async start(request,signal){if(!this.#commands.has(normalizeCommand(request.command))){throw new Error(`Runtime command is not allowlisted: ${request.command}`)}for(const key of Object.keys(request.environment)){if(!this.#environmentKeys.has(key)){throw new Error(`Runtime environment key is not allowlisted: ${key}`)}}const cwd=await this.#workingDirectory(request.cwd);const child=spawn(request.command,[...request.args],{cwd,env:{...this.options.baseEnvironment,...request.environment},shell:false,windowsHide:true,stdio:["pipe","pipe","pipe"]});const cancel=async()=>{if(child.exitCode===null&&child.signalCode===null)child.kill()};const abort=()=>void cancel();signal?.addEventListener("abort",abort,{once:true});if(signal?.aborted===true)await cancel();child.stdin.on("error",()=>void 0);child.stdin.end(request.stdin);const maxStderrBytes=this.options.maxStderrBytes??65536;let stderr="";child.stderr.setEncoding("utf8");child.stderr.on("data",chunk=>{if(stderr.length<maxStderrBytes){stderr+=chunk.slice(0,maxStderrBytes-stderr.length)}});const lines=this.#lines(child,signal,abort,()=>stderr);return{lines,cancel:async()=>cancel()}}async#workingDirectory(candidate){if(candidate===void 0){throw new Error("Runtime working root must be explicit")}const cwd=await realpath3(candidate);const roots2=await Promise.all(this.options.allowedWorkingRoots.map(root=>realpath3(root)));if(!roots2.some(root=>isWithin(root,cwd))){throw new Error(`Runtime working root is not allowlisted: ${cwd}`)}return cwd}async*#lines(child,signal,abort,stderr){const reader=createInterface({input:child.stdout,crlfDelay:Infinity});const maxLineBytes=this.options.maxLineBytes??1048576;try{for await(const line of reader){if(Buffer.byteLength(line,"utf8")>maxLineBytes){child.kill();throw new Error(`Runtime output line exceeds ${maxLineBytes} bytes`)}yield line}const{code,childSignal}=await childExit(child);if(code!==0){const detail=redactText(stderr().trim());throw new Error(`Runtime process failed (${childSignal??String(code)})${detail===""?"":`: ${detail}`}`)}}finally{reader.close();signal?.removeEventListener("abort",abort)}}};function childExit(child){if(child.exitCode!==null||child.signalCode!==null){return Promise.resolve({code:child.exitCode,childSignal:child.signalCode})}return new Promise((resolve20,reject)=>{child.once("error",reject);child.once("close",(code,childSignal)=>resolve20({code,childSignal}))})}function isWithin(root,candidate){const path=relative2(root,candidate);return path===""||!isAbsolute2(path)&&path!==".."&&!path.startsWith(`..\\`)&&!path.startsWith("../")}function normalizeCommand(command){return process.platform==="win32"?command.toLowerCase():command}init_agent_runtime();var DISABLED_FEATURES=["shell_tool","unified_exec","code_mode_host","apps","plugins","multi_agent","browser_use","browser_use_external","in_app_browser","computer_use","image_generation","workspace_dependencies","artifact","hooks","goals","skill_search","skill_mcp_dependency_install"];function assertAstraDiagnosticEnvelope(invocation){if(invocation.model!=="gpt-6-astra")return;if(invocation.metadata.astra_mode!=="diagnostic"||invocation.metadata.role!=="diagnostic"||invocation.agent_id!=="agent-orchestrator"||!/^TASK-[A-Z0-9-]+$/.test(invocation.metadata.task_id??"")||!/^[1-3]$/.test(invocation.metadata.astra_cycle??"")||invocation.reasoning_effort!=="high"||invocation.resume_from!==null||invocation.input.tools.length!==0||invocation.input.response_format!=="json"||invocation.budget.max_tool_calls!==0||invocation.budget.timeout_ms===null||invocation.budget.timeout_ms>18e4||invocation.budget.max_output_tokens>8e3){throw new Error("Astra requires a reserved, fresh, high-only diagnostic envelope")}if(Buffer.byteLength(JSON.stringify(invocation.input),"utf8")>48e3){throw new Error("Astra diagnostic evidence exceeds the 48000-byte input envelope")}}async function constrainAstraCodexRequest(factory,request,signal){const disabled=DISABLED_FEATURES.flatMap(feature=>["--disable",feature]);const inspection=await factory.start({...request,args:["--disable","plugins","--disable","apps","mcp","list","--json"],stdin:""},signal);const cancel=()=>{void inspection.cancel("timeout").catch(()=>void 0)};signal.addEventListener("abort",cancel,{once:true});let raw="";try{if(signal.aborted){await inspection.cancel("timeout");throw new Error("Astra configuration inspection aborted")}for await(const line of inspection.lines){raw+=`${line}
|
|
1842
|
-
`;if(Buffer.byteLength(raw,"utf8")>1048576){await inspection.cancel("budget");throw new Error("Astra configuration inspection exceeded its size limit")}}}finally{signal.removeEventListener("abort",cancel)}if(signal.aborted)throw new Error("Astra configuration inspection aborted");let parsed;try{parsed=JSON.parse(raw)}catch{throw new Error("Astra configuration inspection could not verify MCP isolation")}if(!Array.isArray(parsed)){throw new Error("Astra configuration inspection returned an unsupported schema")}const names=[];for(const server of parsed){if(typeof server!=="object"||server===null||typeof server.name!=="string"||!/^[A-Za-z0-9_.-]{1,200}$/.test(server.name))throw new Error("Astra configuration inspection returned an invalid MCP identity");names.push(server.name)}const mcpOverrides=[...new Set(names)].flatMap(name=>["--config",`mcp_servers.${JSON.stringify(name)}.enabled=false`]);return{...request,args:[...request.args.slice(0,-1),"--strict-config","--sandbox","read-only","--ephemeral","--config",'approval_policy="never"',"--config",'web_search="disabled"',"--config","tools.view_image=false","--config","project_doc_max_bytes=0",...disabled,...mcpOverrides,"-"]}}init_src();function isAutonomyInvocation(invocation){return invocation.metadata.autonomy_policy==="autonomy-v1"}function assertAutonomyEnvelope(invocation){const preset=autonomyPresetSchema.parse(invocation.metadata.autonomy_preset);const source=invocation.metadata.source;const role=invocation.metadata.role;if(!["task","spec","prd"].includes(source??"")||!["builder","verifier","finalizer","diagnostic"].includes(role??""))throw new Error("Invalid autonomy process identity");const ordinal=Number(invocation.metadata.replan);assertAutonomyModel({preset,source,role:role==="diagnostic"?"replanner":role==="builder"?"executor":role==="verifier"?"reviewer":"finalizer",model:invocation.model,reasoning_effort:invocation.reasoning_effort,manual_selection:false,replan:ordinal});if(invocation.budget.timeout_ms!==null)throw new Error("Autonomy-v1 does not abandon attempts by elapsed time");if(role!=="diagnostic")return;const expected=replanModel(preset,ordinal);if(invocation.model!==expected.model||invocation.reasoning_effort!==expected.reasoning_effort||invocation.agent_id!=="agent-orchestrator"||!/^TASK-[A-Z0-9-]+$/.test(invocation.metadata.task_id??"")||invocation.resume_from!==null||invocation.input.tools.length!==0||invocation.budget.max_tool_calls!==0||invocation.input.response_format!=="json"||invocation.budget.max_output_tokens>8e3||Buffer.byteLength(JSON.stringify(invocation.input),"utf8")>48e3)throw new Error("Invalid fresh read-only autonomy replan envelope")}var RuntimeCapabilityError=class extends Error{constructor(capability,requested){super(`Runtime does not support requested ${capability}: ${requested}`);this.capability=capability;this.requested=requested;this.name="RuntimeCapabilityError"}capability;requested;code="RUNTIME_CAPABILITY_UNSUPPORTED"};var ProcessAgentRuntime=class{constructor(processFactory,options){this.processFactory=processFactory;this.options=options;this.#capabilities=runtimeCapabilitiesSchema.parse(options.capabilities)}processFactory;options;#sessions=new Map;#capabilities;async capabilities(){return this.#capabilities}async*invoke(candidate,signal){const invocation=agentInvocationSchema.parse(candidate);this.#negotiate(invocation,false);yield*this.#execute(invocation,signal)}async*resume(candidate,signal){const invocation=agentInvocationSchema.parse(candidate);this.#negotiate(invocation,true);yield*this.#execute(invocation,signal)}async cancel(candidate){const cancellation=runtimeCancellationSchema.parse(candidate);if(!this.#capabilities.cancellation)throw new Error("Runtime does not support cancellation");const session=this.#sessions.get(cancellation.invocation_id);if(session!==void 0)await session.cancel(cancellation.reason)}async*#execute(invocation,signal){throwIfRuntimeAborted(signal);if(this.#sessions.has(invocation.invocation_id)){throw new Error(`Invocation already active: ${invocation.invocation_id}`)}const controller=new AbortController;let cancellationReason="user";const relayAbort=()=>controller.abort(signal?.reason??new Error("Runtime aborted"));signal?.addEventListener("abort",relayAbort,{once:true});const timeout=invocation.budget.timeout_ms===null?null:setTimeout(()=>{cancellationReason="timeout";controller.abort(new Error(`Runtime timeout exceeded: ${invocation.budget.timeout_ms}ms`))},invocation.budget.timeout_ms);const aborted2=abortRejection(controller.signal);const redacted=redactInvocation(invocation);const protocol=(this.options.protocol??zaipJsonlProtocol).prepare(redacted,this.options.args);let request={command:this.options.command,args:protocol.args,stdin:protocol.stdin,environment:{...this.options.environment},...this.options.workingDirectory===void 0?{}:{cwd:typeof this.options.workingDirectory==="function"?this.options.workingDirectory(invocation):this.options.workingDirectory}};let session;let iterator;try{if(isAutonomyInvocation(invocation)&&invocation.metadata.role!=="diagnostic"){request={...request,args:[...request.args.slice(0,-1),"--disable","multi_agent","-"]}}if(isAutonomyInvocation(invocation)?invocation.metadata.role==="diagnostic":invocation.model==="gpt-6-astra"){request=await Promise.race([constrainAstraCodexRequest(this.processFactory,request,controller.signal),aborted2])}session=await Promise.race([this.processFactory.start(request,controller.signal),aborted2]);this.#sessions.set(invocation.invocation_id,session);controller.signal.addEventListener("abort",()=>void session?.cancel(cancellationReason),{once:true});if(controller.signal.aborted)await session.cancel(cancellationReason);const events=[];let toolCalls=0;iterator=session.lines[Symbol.asyncIterator]();while(true){const next=await Promise.race([iterator.next(),aborted2]);if(next.done===true)break;for(const translated of protocol.translate(JSON.parse(next.value))){const event=agentRuntimeEventSchema.parse(translated);toolCalls=await enforceRuntimeBudget(invocation,event,toolCalls,session);events.push(event);yield event}}for(const translated of protocol.finish()){const event=agentRuntimeEventSchema.parse(translated);toolCalls=await enforceRuntimeBudget(invocation,event,toolCalls,session);events.push(event);yield event}validateRuntimeEventStream(invocation,events)}finally{if(timeout!==null)clearTimeout(timeout);signal?.removeEventListener("abort",relayAbort);await iterator?.return?.();this.#sessions.delete(invocation.invocation_id)}}#negotiate(invocation,resuming){if(isAutonomyInvocation(invocation))assertAutonomyEnvelope(invocation);else assertAstraDiagnosticEnvelope(invocation);if(isAutonomyInvocation(invocation)&&!(this.options.protocol instanceof CodexRuntimeProtocol)){throw new Error("AUTONOMY_PROVIDER_UNSUPPORTED: autonomy-v1 requires the Codex process protocol")}if(invocation.model==="gpt-6-astra"&&!(this.options.protocol instanceof CodexRuntimeProtocol)){throw new Error("Astra requires the constrained Codex diagnostic process protocol")}if(!this.#capabilities.models.includes(invocation.model)){throw new RuntimeCapabilityError("model",invocation.model)}if(!this.#capabilities.reasoning_efforts.includes(invocation.reasoning_effort)){throw new RuntimeCapabilityError("reasoning_effort",invocation.reasoning_effort)}if(!this.#capabilities.velocities.includes(invocation.velocity)){throw new RuntimeCapabilityError("velocity",invocation.velocity)}if(invocation.input.tools.length>0&&!this.#capabilities.tool_calls){throw new RuntimeCapabilityError("tool_calls","enabled")}if(invocation.input.response_format==="json"&&!this.#capabilities.structured_output){throw new RuntimeCapabilityError("structured_output","json")}if(resuming&&(!this.#capabilities.resume||invocation.resume_from===null)){throw new RuntimeCapabilityError("resume",invocation.resume_from??"missing-checkpoint")}}};function abortRejection(signal){return new Promise((_,reject)=>{const fail=()=>reject(signal.reason??new Error("Runtime aborted"));if(signal.aborted)fail();else signal.addEventListener("abort",fail,{once:true})})}async function enforceRuntimeBudget(invocation,event,currentToolCalls,session){const toolCalls=currentToolCalls+(event.type==="tool.requested"?1:0);if(toolCalls>invocation.budget.max_tool_calls){await session.cancel("budget");throw new Error(`Runtime tool-call budget exceeded: ${toolCalls}/${invocation.budget.max_tool_calls}`)}if((event.type==="usage.updated"||event.type==="invocation.completed")&&event.usage.output_tokens>invocation.budget.max_output_tokens){await session.cancel("budget");throw new Error(`Runtime output-token budget exceeded: ${event.usage.output_tokens}/${invocation.budget.max_output_tokens}`)}return toolCalls}function codexRuntime(factory,command,models,processOptions={}){return new ProcessAgentRuntime(factory,{command,args:[],protocol:new CodexRuntimeProtocol,capabilities:providerCapabilities("codex",models),...processOptions.environment===void 0?{}:{environment:processOptions.environment},...processOptions.workingDirectory===void 0?{}:{workingDirectory:processOptions.workingDirectory}})}function claudeRuntime(factory,command,models,processOptions={}){return new ProcessAgentRuntime(factory,{command,args:[],protocol:new ClaudeRuntimeProtocol,capabilities:providerCapabilities("claude",models),...processOptions.environment===void 0?{}:{environment:processOptions.environment},...processOptions.workingDirectory===void 0?{}:{workingDirectory:processOptions.workingDirectory}})}function providerCapabilities(provider,models){return{provider,models:[...models],reasoning_efforts:provider==="codex"?["low","medium","high","xhigh"]:["low","medium","high"],velocities:["standard"],streaming:true,cancellation:true,checkpointing:true,resume:true,tool_calls:true,structured_output:true,max_parallel_invocations:4}}init_src();import{execFile as execFile2}from"node:child_process";import{promisify as promisify2}from"node:util";import{createHash as createHash5}from"node:crypto";var REQUIRED_PROFILE_CAPABILITIES=["explicit-lifecycle-ids","context-budget","independent-review","mcp-stdio","deny-by-default"];var APPLICABLE_AGENT_PATHS={codex:".agents/config/clients/codex/agents",claude:".claude/agents",antigravity:".antigravity/agents",gemini:".gemini/agents",cursor:".cursor/agents",copilot:".github/agents",generic:".zaip/agents"};var APPLICABLE_AGENT_SUFFIXES={codex:".toml",claude:".md"};function validateProfileCatalog(catalog){const findings=[];const ids=new Set;for(const profile of catalog.profiles){if(ids.has(profile.id))findings.push(`duplicate:${profile.id}`);ids.add(profile.id);for(const capability of REQUIRED_PROFILE_CAPABILITIES){if(!["native","emulated","unsupported"].includes(profile.capabilities[capability])){findings.push(`missing:${profile.id}:${capability}`)}}for(const path of[profile.guidance_path,profile.agent_path,profile.mcp_config_path]){if(path.length===0||path.includes(".."))findings.push(`unsafe-path:${profile.id}`)}if(profile.agent_path!==APPLICABLE_AGENT_PATHS[profile.id]){findings.push(`inapplicable-agent-path:${profile.id}:${profile.agent_path}`)}}for(const client of["codex","claude","antigravity","gemini","cursor","copilot","generic"]){if(!ids.has(client))findings.push(`missing-client:${client}`)}const semantic=catalog.profiles.map(profile=>({id:profile.id,capabilities:profile.capabilities})).sort((left,right)=>left.id.localeCompare(right.id));return{valid:findings.length===0,findings:findings.sort(),semantic_hash:digest2(stableJson2(semantic))}}async function validateConfiguredProfileAgentPaths(catalog,enabledClients,filesystem){const parity=validateProfileCatalog(catalog);const findings=[...parity.findings];for(const client of["codex","claude"]){if(!enabledClients[client])continue;const profile=catalog.profiles.find(candidate=>candidate.id===client);if(profile===void 0){findings.push(`missing-client:${client}`);continue}try{if(!await filesystem.exists(profile.agent_path)){findings.push(`missing-agent-path:${client}:${profile.agent_path}`);continue}const profiles=await filesystem.listFiles(profile.agent_path,APPLICABLE_AGENT_SUFFIXES[client]);if(profiles.length===0){findings.push(`empty-agent-path:${client}:${profile.agent_path}`)}}catch{findings.push(`inapplicable-agent-path:${client}:${profile.agent_path}`)}}return{valid:findings.length===0,findings:[...new Set(findings)].sort(),semantic_hash:parity.semantic_hash}}function stableJson2(value){return JSON.stringify(sortValue3(value),null,2)}function sortValue3(value){if(Array.isArray(value))return value.map(sortValue3);if(value!==null&&typeof value==="object"){return Object.fromEntries(Object.entries(value).sort(([left],[right])=>left.localeCompare(right)).map(([key,item])=>[key,sortValue3(item)]))}return value}function digest2(value){return createHash5("sha256").update(value).digest("hex")}var execFileAsync2=promisify2(execFile2);import{execFile as execFile3}from"node:child_process";import{promisify as promisify3}from"node:util";var execFileAsync3=promisify3(execFile3);var ADAPTERS_VERSION="3.0.0";var USER_OWNED_ADAPTER_OVERLAYS=new Set([".codex/config.toml"]);var CLAUDE_SETTINGS=`{
|
|
1842
|
+
`;if(Buffer.byteLength(raw,"utf8")>1048576){await inspection.cancel("budget");throw new Error("Astra configuration inspection exceeded its size limit")}}}finally{signal.removeEventListener("abort",cancel)}if(signal.aborted)throw new Error("Astra configuration inspection aborted");let parsed;try{parsed=JSON.parse(raw)}catch{throw new Error("Astra configuration inspection could not verify MCP isolation")}if(!Array.isArray(parsed)){throw new Error("Astra configuration inspection returned an unsupported schema")}const names=[];for(const server of parsed){if(typeof server!=="object"||server===null||typeof server.name!=="string"||!/^[A-Za-z0-9_.-]{1,200}$/.test(server.name))throw new Error("Astra configuration inspection returned an invalid MCP identity");names.push(server.name)}const mcpOverrides=[...new Set(names)].flatMap(name=>["--config",`mcp_servers.${JSON.stringify(name)}.enabled=false`]);return{...request,args:[...request.args.slice(0,-1),"--strict-config","--sandbox","read-only","--ephemeral","--config",'approval_policy="never"',"--config",'web_search="disabled"',"--config","tools.view_image=false","--config","project_doc_max_bytes=0",...disabled,...mcpOverrides,"-"]}}init_src();function isAutonomyInvocation(invocation){return invocation.metadata.autonomy_policy==="autonomy-v1"}function assertAutonomyEnvelope(invocation){const preset=autonomyPresetSchema.parse(invocation.metadata.autonomy_preset);const source=invocation.metadata.source;const role=invocation.metadata.role;if(!["task","spec","prd"].includes(source??"")||!["builder","verifier","finalizer","diagnostic"].includes(role??""))throw new Error("Invalid autonomy process identity");const ordinal=Number(invocation.metadata.replan);assertAutonomyModel({preset,source,role:role==="diagnostic"?"replanner":role==="builder"?"executor":role==="verifier"?"reviewer":"finalizer",model:invocation.model,reasoning_effort:invocation.reasoning_effort,manual_selection:false,replan:ordinal});if(invocation.budget.timeout_ms!==null)throw new Error("Autonomy-v1 does not abandon attempts by elapsed time");if(role!=="diagnostic")return;const expected=replanModel(preset,ordinal);if(invocation.model!==expected.model||invocation.reasoning_effort!==expected.reasoning_effort||invocation.agent_id!=="agent-orchestrator"||!/^TASK-[A-Z0-9-]+$/.test(invocation.metadata.task_id??"")||invocation.resume_from!==null||invocation.input.tools.length!==0||invocation.budget.max_tool_calls!==0||invocation.input.response_format!=="json"||invocation.budget.max_output_tokens>8e3||Buffer.byteLength(JSON.stringify(invocation.input),"utf8")>48e3)throw new Error("Invalid fresh read-only autonomy replan envelope")}var RuntimeCapabilityError=class extends Error{constructor(capability,requested){super(`Runtime does not support requested ${capability}: ${requested}`);this.capability=capability;this.requested=requested;this.name="RuntimeCapabilityError"}capability;requested;code="RUNTIME_CAPABILITY_UNSUPPORTED"};var ProcessAgentRuntime=class{constructor(processFactory,options){this.processFactory=processFactory;this.options=options;this.#capabilities=runtimeCapabilitiesSchema.parse(options.capabilities)}processFactory;options;#sessions=new Map;#capabilities;async capabilities(){return this.#capabilities}async*invoke(candidate,signal){const invocation=agentInvocationSchema.parse(candidate);this.#negotiate(invocation,false);yield*this.#execute(invocation,signal)}async*resume(candidate,signal){const invocation=agentInvocationSchema.parse(candidate);this.#negotiate(invocation,true);yield*this.#execute(invocation,signal)}async cancel(candidate){const cancellation=runtimeCancellationSchema.parse(candidate);if(!this.#capabilities.cancellation)throw new Error("Runtime does not support cancellation");const session=this.#sessions.get(cancellation.invocation_id);if(session!==void 0)await session.cancel(cancellation.reason)}async*#execute(invocation,signal){throwIfRuntimeAborted(signal);if(this.#sessions.has(invocation.invocation_id)){throw new Error(`Invocation already active: ${invocation.invocation_id}`)}const controller=new AbortController;let cancellationReason="user";const relayAbort=()=>controller.abort(signal?.reason??new Error("Runtime aborted"));signal?.addEventListener("abort",relayAbort,{once:true});const timeout=invocation.budget.timeout_ms===null?null:setTimeout(()=>{cancellationReason="timeout";controller.abort(new Error(`Runtime timeout exceeded: ${invocation.budget.timeout_ms}ms`))},invocation.budget.timeout_ms);const aborted2=abortRejection(controller.signal);const redacted=redactInvocation(invocation);const protocol=(this.options.protocol??zaipJsonlProtocol).prepare(redacted,this.options.args);let request={command:this.options.command,args:protocol.args,stdin:protocol.stdin,environment:{...this.options.environment},...this.options.workingDirectory===void 0?{}:{cwd:typeof this.options.workingDirectory==="function"?this.options.workingDirectory(invocation):this.options.workingDirectory}};let session;let iterator;try{if(isAutonomyInvocation(invocation)&&invocation.metadata.role!=="diagnostic"){request={...request,args:[...request.args.slice(0,-1),"--disable","multi_agent","-"]}}if(isAutonomyInvocation(invocation)?invocation.metadata.role==="diagnostic":invocation.model==="gpt-6-astra"){request=await Promise.race([constrainAstraCodexRequest(this.processFactory,request,controller.signal),aborted2])}session=await Promise.race([this.processFactory.start(request,controller.signal),aborted2]);this.#sessions.set(invocation.invocation_id,session);controller.signal.addEventListener("abort",()=>void session?.cancel(cancellationReason),{once:true});if(controller.signal.aborted)await session.cancel(cancellationReason);const events=[];let toolCalls=0;iterator=session.lines[Symbol.asyncIterator]();while(true){const next=await Promise.race([iterator.next(),aborted2]);if(next.done===true)break;for(const translated of protocol.translate(JSON.parse(next.value))){const event=agentRuntimeEventSchema.parse(translated);toolCalls=await enforceRuntimeBudget(invocation,event,toolCalls,session);events.push(event);yield event}}for(const translated of protocol.finish()){const event=agentRuntimeEventSchema.parse(translated);toolCalls=await enforceRuntimeBudget(invocation,event,toolCalls,session);events.push(event);yield event}validateRuntimeEventStream(invocation,events)}finally{if(timeout!==null)clearTimeout(timeout);signal?.removeEventListener("abort",relayAbort);await iterator?.return?.();this.#sessions.delete(invocation.invocation_id)}}#negotiate(invocation,resuming){if(isAutonomyInvocation(invocation))assertAutonomyEnvelope(invocation);else assertAstraDiagnosticEnvelope(invocation);if(isAutonomyInvocation(invocation)&&!(this.options.protocol instanceof CodexRuntimeProtocol)){throw new Error("AUTONOMY_PROVIDER_UNSUPPORTED: autonomy-v1 requires the Codex process protocol")}if(invocation.model==="gpt-6-astra"&&!(this.options.protocol instanceof CodexRuntimeProtocol)){throw new Error("Astra requires the constrained Codex diagnostic process protocol")}if(!this.#capabilities.models.includes(invocation.model)){throw new RuntimeCapabilityError("model",invocation.model)}if(!this.#capabilities.reasoning_efforts.includes(invocation.reasoning_effort)){throw new RuntimeCapabilityError("reasoning_effort",invocation.reasoning_effort)}if(!this.#capabilities.velocities.includes(invocation.velocity)){throw new RuntimeCapabilityError("velocity",invocation.velocity)}if(invocation.input.tools.length>0&&!this.#capabilities.tool_calls){throw new RuntimeCapabilityError("tool_calls","enabled")}if(invocation.input.response_format==="json"&&!this.#capabilities.structured_output){throw new RuntimeCapabilityError("structured_output","json")}if(resuming&&(!this.#capabilities.resume||invocation.resume_from===null)){throw new RuntimeCapabilityError("resume",invocation.resume_from??"missing-checkpoint")}}};function abortRejection(signal){return new Promise((_,reject)=>{const fail=()=>reject(signal.reason??new Error("Runtime aborted"));if(signal.aborted)fail();else signal.addEventListener("abort",fail,{once:true})})}async function enforceRuntimeBudget(invocation,event,currentToolCalls,session){const toolCalls=currentToolCalls+(event.type==="tool.requested"?1:0);if(toolCalls>invocation.budget.max_tool_calls){await session.cancel("budget");throw new Error(`Runtime tool-call budget exceeded: ${toolCalls}/${invocation.budget.max_tool_calls}`)}if((event.type==="usage.updated"||event.type==="invocation.completed")&&event.usage.output_tokens>invocation.budget.max_output_tokens){await session.cancel("budget");throw new Error(`Runtime output-token budget exceeded: ${event.usage.output_tokens}/${invocation.budget.max_output_tokens}`)}return toolCalls}function codexRuntime(factory,command,models,processOptions={}){return new ProcessAgentRuntime(factory,{command,args:[],protocol:new CodexRuntimeProtocol,capabilities:providerCapabilities("codex",models),...processOptions.environment===void 0?{}:{environment:processOptions.environment},...processOptions.workingDirectory===void 0?{}:{workingDirectory:processOptions.workingDirectory}})}function claudeRuntime(factory,command,models,processOptions={}){return new ProcessAgentRuntime(factory,{command,args:[],protocol:new ClaudeRuntimeProtocol,capabilities:providerCapabilities("claude",models),...processOptions.environment===void 0?{}:{environment:processOptions.environment},...processOptions.workingDirectory===void 0?{}:{workingDirectory:processOptions.workingDirectory}})}function providerCapabilities(provider,models){return{provider,models:[...models],reasoning_efforts:provider==="codex"?["low","medium","high","xhigh"]:["low","medium","high"],velocities:["standard"],streaming:true,cancellation:true,checkpointing:true,resume:true,tool_calls:true,structured_output:true,max_parallel_invocations:4}}init_src();import{execFile as execFile2}from"node:child_process";import{promisify as promisify2}from"node:util";import{createHash as createHash5}from"node:crypto";var REQUIRED_PROFILE_CAPABILITIES=["explicit-lifecycle-ids","context-budget","independent-review","mcp-stdio","deny-by-default"];var APPLICABLE_AGENT_PATHS={codex:".agents/config/clients/codex/agents",claude:".claude/agents",antigravity:".antigravity/agents",gemini:".gemini/agents",cursor:".cursor/agents",copilot:".github/agents",generic:".zaip/agents"};var APPLICABLE_AGENT_SUFFIXES={codex:".toml",claude:".md"};function validateProfileCatalog(catalog){const findings=[];const ids=new Set;for(const profile of catalog.profiles){if(ids.has(profile.id))findings.push(`duplicate:${profile.id}`);ids.add(profile.id);for(const capability of REQUIRED_PROFILE_CAPABILITIES){if(!["native","emulated","unsupported"].includes(profile.capabilities[capability])){findings.push(`missing:${profile.id}:${capability}`)}}for(const path of[profile.guidance_path,profile.agent_path,profile.mcp_config_path]){if(path.length===0||path.includes(".."))findings.push(`unsafe-path:${profile.id}`)}if(profile.agent_path!==APPLICABLE_AGENT_PATHS[profile.id]){findings.push(`inapplicable-agent-path:${profile.id}:${profile.agent_path}`)}}for(const client of["codex","claude","antigravity","gemini","cursor","copilot","generic"]){if(!ids.has(client))findings.push(`missing-client:${client}`)}const semantic=catalog.profiles.map(profile=>({id:profile.id,capabilities:profile.capabilities})).sort((left,right)=>left.id.localeCompare(right.id));return{valid:findings.length===0,findings:findings.sort(),semantic_hash:digest2(stableJson2(semantic))}}async function validateConfiguredProfileAgentPaths(catalog,enabledClients,filesystem){const parity=validateProfileCatalog(catalog);const findings=[...parity.findings];for(const client of["codex","claude"]){if(!enabledClients[client])continue;const profile=catalog.profiles.find(candidate=>candidate.id===client);if(profile===void 0){findings.push(`missing-client:${client}`);continue}try{if(!await filesystem.exists(profile.agent_path)){findings.push(`missing-agent-path:${client}:${profile.agent_path}`);continue}const profiles=await filesystem.listFiles(profile.agent_path,APPLICABLE_AGENT_SUFFIXES[client]);if(profiles.length===0){findings.push(`empty-agent-path:${client}:${profile.agent_path}`)}}catch{findings.push(`inapplicable-agent-path:${client}:${profile.agent_path}`)}}return{valid:findings.length===0,findings:[...new Set(findings)].sort(),semantic_hash:parity.semantic_hash}}function stableJson2(value){return JSON.stringify(sortValue3(value),null,2)}function sortValue3(value){if(Array.isArray(value))return value.map(sortValue3);if(value!==null&&typeof value==="object"){return Object.fromEntries(Object.entries(value).sort(([left],[right])=>left.localeCompare(right)).map(([key,item])=>[key,sortValue3(item)]))}return value}function digest2(value){return createHash5("sha256").update(value).digest("hex")}var execFileAsync2=promisify2(execFile2);import{execFile as execFile3}from"node:child_process";import{promisify as promisify3}from"node:util";var execFileAsync3=promisify3(execFile3);var ADAPTERS_VERSION="3.2.0";var USER_OWNED_ADAPTER_OVERLAYS=new Set([".codex/config.toml"]);var CLAUDE_SETTINGS=`{
|
|
1843
1843
|
"permissions": {
|
|
1844
1844
|
"allow": [],
|
|
1845
1845
|
"deny": []
|
|
@@ -2013,7 +2013,7 @@ statusMessage = "Finalizing ZAIP subagent Run"
|
|
|
2013
2013
|
`," catalysts","\u0643\u0631\u0647","\uB0BC","=z","\xE8h","\u0412\u0421"," \u0AAB\u0AC7\u0AB0"," \u5927\u91D1"," conocidas"," Vold"," #-}\n\n"," \u5929\u5929\u4E2D\u5F69\u7968\u817E\u8BAF"," Kyiv"," \u06AB\u0631"," \u0632\u0627\u0626\u062F","ipsoid","brightness","*>(&"," \u0C95\u0CBE\u0CAE"," Federaalka"," \u0436\u044B\u0446\u0446\u0451"," santos","\u2018zbekiston","roog"," Lourdes"," claridad"," occasione"," \u4E3E\u62A5","\u044A\u044F\u0441","gross"," \u5E0C","\u05D9\u05D9\u05E2\u05DF"," \u0561\u0580\u0587","\u0435\u0447\u043D\u044B\u0445","\u5A31\u4E50\u5F69\u7968\u6CE8\u518C"," torsdag"," k\xE9o"," kisim","buyers","\u043F\u0430\u043B",".Merge"," Cursos"," \uB300\uC2E0"," \u0645\u0627\u064A"," jur\xEDdicas","\u6A21\u677F","\u0438\u043B\u0430\u043A","muy","\u03BD\u03BF\u03BC\u03B1"," cuadros"," \u0AA6\u0AC7\u0AB6\u0AAE\u0ABE\u0A82","\u0441\u0442\u0440\u0438"," \u062F\u0648\u062F","niejszych","Renderable"," \u670B\u514B","\u03C3\u03B1\u03B9"," Promotional",".Completed"," \u043A\u0430\u043D\u0446"," d\xE9ten"," m\xF5ned","(goal"," hugging"," L\xEBtz"," yaba"," enigmatic"," \u041A\u0440\u0430\u0441\u043D\u043E\u0434\u0430\u0440"," v\xE4nt"," \xE9l\xE9gant"," europeu"," Shelton"," Hombre","aher","exclusive",'">%'," gabi","visional"," est\xE9s"," ge\xEFntegre"," \u043F\u043E\u043B\u0443\u0447\u0438\u043B\u043E\u0441\u044C"," RIS","\u30CB\u30F3\u30B0","\u09BF\u09DF\u09BE\u09A8","Covered"," letos"," \u043A\u0430\u0442\u0430\u043B\u043E\u0433","\u0301s"," Garfield","Generators","(vc","\u0C46\u0C02\u0C2C\u0C30\u0C4D","\u09BE\u09B0\u09CD\u09B8"," \u06CB\u0627\u0642\u062A\u0649","\u1E63i\u1E63\u1EB9",`']?>"`," taamatut",".poster"," \u043F\u0440\u044B\u043C"," enlever","edf"," \u10D9\u10D8\u10D7\u10EE\u10D5"," \u043F\u0438\u0442\u043E\u043C","?>\n\n\n","/banner","\u093F\u0930\u0939\u0947\u0915\u093E"," contrari",".discovery"," gui",".false","\u3055\u308C\u3066\u3044\u307E\u3059"," Lettre"," percentual"," ibn","\u4E0D\u4EC5"," storyteller","Ontario","maks","\u03BB\u03B5\u03C2"," tett"," kapcsolat"," \u043C\u0443\u0430\u0439"," \u056F\u0578\u0582\u0576\u0565\u0576"," Warp","\u8A2D\u5099","\u2019aider","Indice"," \u7406","ituen",";TZID"," kusema"," Slick","\u05E0\u05D9\u05D4\u05D5"," inhale"," umgehen"," \u06A9\u0627\u0628"," przeci"," \u0493\u0430\u0441\u044B\u0440"," adn"," wardrobes"," Tg","_linux"," pm"," \u0433\u043B\u0430\u0432\u043D\u044B\u043C"," \u0441\u0430\u049B\u0442\u0430\u0443"," \u0631\u062D\u0644\u0629",'"]],\n'," par\xE7"," \u0437\u0430\u0435\u043C"," {/",".tell","\u03C3\u03B1\u03BC\u03B5"," Reveal","\u092C\u0948"," belirt"," wholeheartedly","nostic","k\xE9ho","lika","\\Traits"," kalor","Worst","\u0432\u0430\u044E\u0446\u0446\u0430",".gold","PIRED"," gratifying","(IService"," vuod"," hv\xF8r"," lichaams","rack"," discriminator"," \u0C35\u0C1A\u0C4D\u0C1A\u0C47","Eles"," inhibitory"," \u043F\u0440\u043E\u0441\u043C\u043E\u0442\u0440"," leute","-Friday","Servidor",".PUBLIC"," \u09A6\u09BF\u09A8\u09C7"," \u0434\u04E9\u0440"," kleurr"," \u0440\u0430\u04B3"," F\xE9lix"," Burmese"," jahr",[158,225,131,152,225,131,160,225,131,152,225,131,161,225,131,158],"\u0941\u0915\u094B","Healing"," zahtev","ptable","\u0437\u0432"," \u0643\u064A\u0644\u0648"," \u5929\u5929\u4E2D\u5F69\u7968\u5145\u503C"," trovato","%);\n"," \u062A\u0634\u064A\u0631"," gamut","\u7238\u7238"," \u0645\u0642\u0627\u0644","\u2019artiste","-nowrap","-readable"," virar","Yer","Hasher","}}],\n","(mt"," izraz","Gir"," haum","\u0435\u043C\u043E\u043D"," \u10D6\u10DD\u10D2\u10D8"," Debido"," ctrl",".office","servo","-visible"," \u05EA\u05D5\u05D3\u05D4"," remorse","amiin","Kaz"," BOR"," Airports"," postagem"," saha","Kurz"," Einkaufs"," schlech"," sedation"," leaflet","tris"," pitk\xE4","\u5362"," aj\xE1n","\u0632\u064A\u0627\u0621"," \u0438\u043D\u0441\u0442\u0440\u0443\u043A\u0446\u0438\u044F"," cognit","\u0430\u043D\u0430\u043C","/About"," \u0447\u0435\u0441\u0442\u044C","\u0161ni"," Process"," Pkw"," Vap","\u5BB9\u91CF",' }}"><'," (!["," Burgundy"," taws"," Bays"," langleb","pret\xE9"," strenuous"," Ebenso","\xE1vamos","\u2019esper"," \u044F\u0441\u043D\u043E"," \u092A\u0941\u0923"," \u067E\u0631\u0645\u062E\u062A"," \u624B\u673A\u7248\u5929\u5929\u4E2D\u5F69\u7968","-mouth","(Route"," precej"," \u063A\u0630\u0627\u06CC\u06CC","riffe"," \uC81C\uC8FC","ancis"," AGR"," \u0440\u0435\u0437\u043A\u043E"," teatral",[32,230,166]," shortening"," \u05D5\u05D4\u05E8"," Raising"," "," traurig","\u0259zi","persoon"," bygger"," exerce"," PDE"," Skilled"," k\xE6r","\u0438\u0440\u043E\u0432\u043A\u0443"," WOR"," Tepp","bakan"," Reactor"," reuni\xF3"," SBM"," nasil"," \u4E07\u5229","_Invalid"," uygulan"," vider"," \u0C2A\u0C4D\u0C30\u0C1A"," \u0438\u043D\u0434\u0435\u043A\u0441"," contatos"," \u0441\u0442\u0435\u043F\u0435\u043D\u044C","_you","ordinateur","\u4E0A\u7EBF"," couvrir"," ruso",".softmax"," \u0628\u0631\u0634\u0644\u0648\u0646\u0629","\u0D24\u0D4D\u0D24\u0D3F\u0D28\u0D41"," \u0AB5\u0ABF\u0A97\u0AA4\u0ACB"," Pixabay"," phi\xEAn"," BENEF","\u0637\u0627"," wyj\u0105tk","resar"," nabi"," podp"," \u09B6\u09BE\u09B9"," saavad"," Equivalent"," etree","\u6276\u8D2B","Cuda","\u06CC\u06A9\u0627\u0631"," ballast"," SAE","trizes"," detaine","\u2019ir"," ta\xFDdan","\u0413\u0410","\u04AD\u0435\u0438"," \u05D5\u05DC\u05E2","-With","ARRIER"," meek"," \u067E\u0631\u0648\u0646","'autant","posti","_reserved","\u0430\u043A\u0441","\uC564"," NICE"," \u0627\u0644\u062C\u0645\u0647\u0648\u0631"," erzielt"," gecontrole","\u0561\u0581\u0578\u0582\u0574\u0568"," \u043E\u043C\u0430","\u300B\u3002\n\n","ADVERTISEMENT"," curricula"," Au\xDF","LEGE"," \u0440\u0456\u0448\u0435\u043D\u043D\u044F"," comandos"," \u05DC\u05D4\u05DB","\u0431\u0440\u0435","osive","Fond"," aislamiento","_relu"," TSR"," Linien"," rame"," Envelope"," injectable","licenses"," drehen","Dak","f\xF8rer"," \u043F\u043E\u0432\u0435\u0434\u0435\u043D\u0438\u044F"," Numerical"," myaka"," vzt"," whakata"," St\xE4rke","gha"," \u05DC\u05E4\u05EA"," pomme"," daa","-painted","\u6765\u4E5F","IRIT","-ang"," trhu","!important","Faq"," B\xFCnd","\u0CBF\u0CB8\u0CC1\u0CA4\u0CCD\u0CA4\u0CA6\u0CC6"," Spitz"," taky","Decompiler",")':","liegenden"," at\u1EB9","\uFF0C\u4F8B\u5982","\xF6hnt"," \u0907\u0932\u093E\u0915\u0947"," tiltak"," tangu"," \u0CAC\u0CB0\u0CC1\u0CA4\u0CCD\u0CA4","nske"," \u0635\u0646\u0627\u06CC\u0639"," \u092A\u0941\u0930\u093E\u0928\u0947","getwijfeld"," Accredited","\u2019nde","\u043B\u043E\u0433\u043E"," microp"," svog","_due","\u043B\u043E\u0449\u0430\u0434"," Dorn"," \u0C9A\u0CBF\u0C95\u0CBF\u0CA4\u0CCD\u0CB8\u0CC6"," \u0A28\u0A3E"," \u05E4\u05E0\u05D9"," ger\xE7ekten"," \u0440\u0430\u0437\u0432\u0435\u0434","\xE9pe"," hsv"," Clearwater"," naq","\u62C9\u7279"," d\xE9tour","_Length"," Zodra"," casualty"," zusammensch"," mandi"," \u10E8\u10D4\u10E1\u10D0\u10EB\u10DA\u10D4\u10D1\u10D4\u10DA\u10D8\u10D0"," Travels","atika"," \u0BA8\u0BC0\u0BA4","\u092E\u0924\u0940"," presentamos"," hinged"," Rotor"," \u10EC\u10E7\u10D0\u10DA","N\xED"," sexvideo"," \u043A\u0440\u0438\u0442\u0435\u0440","-Shabaab"," \uACF5\uC5F0","_population"," Aziz","\u7089"," \u05D9\u05DC\u05D3"," kaban"," d\xE9put\xE9"," trembling","\u3001\u7B2C"," \u0639\u0627\u0645\u0627\u064B"," Bayesian"," \u9875\u9762","\u09BE\u0981\u0993"," Etat"," ge\xE7irmek"," \u0411\u04B1",".effects","APK"," gwamnatin"," sujeitos"," \u0CB8\u0CBE\u0C97"," \u092C\u091C\u093E\u092F",[32,240,159,141]," \u0628\u062F\u0627"," Racer","zky"," \u6E58","argando"," \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0439"," Christensen"," \u0576\u0577\u0565\u0581"," Emery",".ber"," \u043E\u0493\u043E\u0437"," \u0633\u0644\u0637\u0627\u0646","pt\u0103m"," \u0627\u0644\u0631\u062D\u064A\u0645"," \u05D7\u05D5\u05D1\u05D4","\u10D0\u10E1\u10D0"," neuze"," \u10E1\u10D8\u10E7\u10D5\u10D0\u10E0\u10E3\u10DA"," aeroport","servez"," neug"," \u0D2A\u0D30\u0D3F\u0D36\u0D40\u0D32"," responsabilit\xE9s","\u0131kl\u0131"," \u10D0\u10DC\u10D2\u10D0\u10E0\u10D8\u10E8",".Then","_annotations"," \u092E\u093E\u0924\u094D\u0930\u0948"," Normandy"," zusamment","/render"," participaram","gemeinschaft"," maayo",".Attach",".Mag"," \u0441\u043E\u043B\u04B3\u043E\u0438","Cartesian",".Pull"," articulation"," tair","_Surface","ptious"," \u4F01\u4E1A","int\xE4\xE4n"," \u056A\u0578\u0572\u0578\u057E\u0580\u0564\u056B","_coupon","\u03B9\u03BA\u03B7"," egingo"," p\u016Bnaewele","\uCC0D"," CDL",'"|'," \u0633\u0631\u0686"," item's"," chronology"," facelift"," sturd"," Mathieu","occur","jubl",' ".\n',"\u0639\u062F\u0644"," "," PIT"," \u0627\u0644\u062C\u0648"," \u091A\u0932\u0940","_Master","Treas","UPLOAD"," publicou"," Devin"," categorize"," Rik"," proqram"," \u043E\u0442\u0432\u0435\u0442\u0430"," \u10E1\u10D0\u10DA"," \u0E21\u0E01\u0E23\u0E32\u0E04\u0E21"," simplifying"," \u5A01\u5C3C\u65AF\u4EBA"," \u0413\u0430\u0433\u0440\u0430"," \u0B8E\u0BA9\u0BCD\u0BB1\u0BC1\u0BAE\u0BCD"," \u0AAE\u0A82","/\r\n\r\n"," pagando"," murderous",".Workflow","ietan","\u0CAD\u0CCD\u0CAF","\u0108","(anim","?!?!",'\\"");\n'," !!!!!"," Calibration"," \n",'("-");\n',"\u0430\u043B\u0430\u0440\u0430"," Pian","\u10D0\u10DB\u10EA"," intl"," \u0645\u06AA\u0645\u0644","######"," taifa"," \u0634\u0647\u0627\u062F"," elevados","i\xF0is","whose"," dhim"," peripherals","\u0E24\u0E28\u0E08\u0E34\u0E01\u0E32\u0E22\u0E19",".party"," kreative","igeach","Batis"," Cem"," symmetrical"," \u0628\u0631\u0627\u064A","TEAM"," sess\xF5es"," \u0443\u0447\u0430\u0441\u0442\u0432"," CANCEL"," mowing"," \u0412\u0438\u043A\u0438\u043F",' ?>">\r\n'," odmah","_HINT"," erstaun"," nachhaltig","\u10D0\u10E0\u10DD\u10D3","imende","\u0E17\u0E35\u0E48\u0E08\u0E30"," Meetup"," \u0639\u0644\u0627\u0642\u0648\u06BA","angaje","_angles"," \u0C0F\u0C30\u0C4D\u0C2A\u0C3E\u0C1F\u0C41"," metodolog\xEDa","'https"," orgullo","\u0BBF\u0BA9\u0BBF\u0BAE"," sredstva"," geringer"," \u0443\u0439\u0493\u0443\u0440\u043B\u0430\u0440\u0493\u0430","\\[","\u30AB\u30EB"," \u05E7\u05D0\u05B7"," glossary"," manifesta\xE7\xF5es","\u10D4\u10DC\u10E2\u10D4\u10D1\u10D8"," agricoles"," stuffs"," \u0998\u099F\u09A8\u09BE\u09DF"," \u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0435\u0442","\u17B6\u179C"," \u0420\u0430\u0439","\u05D5\u05D2\u05DE\u05D0"," h\xF3n"," \u0939\u093F\u0930","zins"," speelgoed","\uD55C\uB2E4\uACE0","\u0D41\u0D15\u0D4D\u0D24"," Persia","\uFF20\u304A\u30FC\u3077\u3093","lygyny\u0148"," nida"," austral","\u04EF\u0437\u0438"," Residency"," \u0444\u043E\u043D\u0434\u0430"," jurk","\\CMS"," dermatologist","\u8B77\u58EB","Namun"," Territories"," \u0635\u0627\u062F\u0631\u0627\u062A","Tours"," \u043E\u043A\u0430\u0437\u044B\u0432\u0430\u0435\u0442\u0441\u044F"," bambino"," robustness"," secondly"," \u80A1\u7968"," guestrooms"," \u0642\u0628\u0636","\u0D4D\u0D30\u0D2E"," sonucu"," h\u01A1i"," consiga"," schneiden","Adults","anggih","ERTA","akty","PRISE"," \u043A\u0440\u0430\u0441\u0438\u0432\u043E"," JL"," aaqqissu"," \u0686\u06CC\u0641","\u0CA3\u0CA6\u0CB2\u0CCD\u0CB2\u0CBF","Subdivision","\u05D9\u05E6\u05D8"," Vorstellungen"," \u043C\u0443\u0437\u044B\u043A\u0443"," dr\xFCcken","\u043E\u0440\u0432"," swimmer","\u043D\u0435\u0441\u0442"," tr\xE4n","Dennis"," yerde","ioiga"," m\xFCq"," onderhand"," \uBD84\uC704"," \u0161koly","\u5929\u5929\u4E2D\u5956","cuando","(Storage","teriors"," chills"," prossimo","_shuffle",".MINUTE"," \u0561\u057C\u0561\u057B\u0576\u0578\u0580\u0564","\uC790\uB9AC","\uB8F8","\u0446\u0438\u0434"," uruh","sjed"," \u0444\u0438\u0437\u0438\u0447\u0435\u0441\u043A\u0438\u0445","ijakan"," seguem","Locks","-elles","\u6F58"," forl","#aa"," Aka"," \u0E40\u0E01\u0E2D\u0E23\u0E4C"," zviri"," \u057D\u056B\u0580\u0578\u0582\u0574"," Analytical","idro","\u0627\u0626\u0646\u0627","\u05E0\u05E2\u05E8","Exercises",",np"," AUS","INET","\u7A81\u51FA"," pr\xE9sentant"," \u0D0E\u0D1F\u0D41\u0D24\u0D4D\u0D24"," \u0D2C\u0D46"," \u0442\u044F\u0445"," urspr\xFCnglich","richter"," Proverbs"," szk"," Worked"," \uC5C6\uC5B4"," zbir"," aanu"," Erotiske"," luctus","\u043B\u0438\u043C\u0438","chapper"," Myself","\u2014even"," Showtime","\u300F\uFF08"," impedit","\u4E3B\u4F53",".firebaseio"," \u0628\u0631\u062F\u0627\u0634\u062A","Acad"," \u0627\u0644\u0625\u0631\u0647\u0627\u0628","avirus","\u10D4\u10D8\u10DA"," Stellar"," sobrem","ofanira","Kommentare"," completas"," ouverts",".them"," rigidity"," \u098F\u09B8\u09C7\u099B\u09C7"," \u0430\u0434\u0430\u043C\u043D\u044B\u04A3"," \u591A\u4E50"," Ilha"," \u05E8\u05E4\u05D5\u05D0"," c\xE9n","(categories"," \xFAdaj","\u0A3F\u0A17","chtung"," caop","uleke"," \u0628\u0631\u0642\u0631\u0627\u0631"," \u0648\u0642\u0648\u0639"," muv","\u043D\u0456\u0448"," Staffing"," Palavra"," PARAMETERS"," gallwch"," Auteur"," frivol"," settimane"," enclave"," osvoj","leszt"," \u0648\u0627\u0636\u062D\u0629","\u05D5\u05D1\u05D9"," PRESIDENT","amam","\u6A79","\u0E2A\u0E39\u0E15\u0E23"," \u0C35\u0C47\u0C32","-chave"," qu\u1EA3ng","\u4E08\u592B"," PCP","Drops","Sucursal","MOQ"," \u043E\u0441\u0432\u0456"," \u043A\u04AF\u0442\u04D9\u0440","mouseenter"," Diving","n\xE1v"," \u0497\u04D9\u0440"," ====","ismet","straight"," \u0438\u0434\u0430\u0440"," mniej","\u03A0\u03B1"," \u0906\u0932\u094B",'(".");\n'," balt","verschluss"," \u0939\u093E\u0932\u0924","insp","_HEADERS"," \u043F\u0440\u0438\u0445\u043E\u0434\u0438\u0442","\u0161kega","ussions","Booked"," fudge","bbc"," grasas"," \u0432\u0430\u04A1\u044B\u0442\u0442\u0430"," \u10D8\u10D2\u10D8\u10D5\u10D4"," tablo"," TIG"," \u0995\u09AE\u09BF\u09B6"," Ajust"," devas"," aktiviert"," \u04B3\u0430\u043B"," \u0635\u0646\u0627","-mailadres","-reading"," \uD0C0\uC785"," hainbat"," pot\u0159","\u0909\u0924\u094D\u0924\u0930"," \u0681\u0644"," \u0986\u09AB"," \u0569\u0565\u056F","Automatically"," \u05D3\u05D0\u05B7\u05E8","Caches"," pulsa"," TOT","\u6700\u65B0\u8BC4\u8BBA","umsum"," bich","etop"," \u0A86\u0AAA\u0AA3","myp"," \u092C\u094B\u0932\u0947"," Ruhr","Pinned","\u064A\u064B\u0627","\u66FE\u9053\u4EBA"," \u0E0B\u0E37\u0E49\u0E2D"," \xFCcret"," \u049B\u043E\u0493\u0430\u043C\u0434\u044B\u049B"," eyelashes","-PCR"," \u0645\u0627\u062F\u0631"," inil"," nwany\u1ECB"," syringe"," Avent"," \u0633\u064A\u0627\u0633\u0629"," wyposa\u017C","_www",">d",".Emp"," s\xF2nraichte",".future","\u8D8A\u6765\u8D8A"," thair","izungumza"," \u0441\u043E\u0432\u0440\u0435\u043C\u0435\u043D\u043D\u044B\u0435"," dictatorship","(Change"," hikers","\u0CBE\u0C82\u0CA4\u0CB0"," \u0431\u0438\u043B\u0434\u04AF\u0440\u0433\u04D9\u043D","\u10DB\u10E7\u10DD\u10E4"," \u0458\u0430\u0432","edent"," disproportionately","\u0CBE\u0CA6\u0CCD"," newfound","\u70ED\u4E45\u4E45\u7CBE\u54C1"," Accordion"," \u062E\u0628\u0631\u064A"," Wesen","\u2019eo"," cortical","\u88C5\u5907"," Weiterbildung","Unnamed"," Pach"," collaborator","Kansas"," \u0648\u0645\u0633\u062A"," conscientious"," \u043C\u0430\u049B\u043E\u043C\u043E\u0442\u0438"," \u0633\u0647\u0644\u0629","|required","ploit","Carga"," \u0433\u0430\u0437\u0440\u044B\u043D","_take"," schild"," tides","/lounge"," \u043F\u0435\u0440\u0432\u043E\u043D\u0430\u0447","invalidate",".Creator"," deilige","\u221E","ramin"," WRONG"," \u0A97\u0ACD\u0AB0\u0ABE\u0AAE"," \u0570\u0561\u0574\u0578\u0566"," karde"," \u015Bred","pakken","\u3011!\u3010"," \u03C0\u03B1\u03C1\u03BF\u03C5\u03C3\u03B9\u03AC","\u09C1\u09B7\u09CD\u099F"," broom","\u091C\u094D\u091C"," \u0AAC\u0AA8\u0ABE\u0AB5\u0AB5\u0ABE","\u043F\u0435\u0440\u0430\u0442\u043E\u0440"," \u092C\u094D\u0932\u0949\u0917","\u09C7\u09B0\u09C7","Quartz","felder"," tests"," \u0441\u0443\u0440\u0433"," curate","ULSE"," shida","uitary"," \uC774\uC0C1\uC758"," vell"," ored"," amado","_hdl","(sync"," \u0646\u06A9\u0631\u062F","\uFF45"," Valuable"," nh\u1ECDr\u1ECD"," Brokerage","\u05E1\u05D8\u05DF"," \u0930\u094B\u0932"," boleto","\u3002\u3053\u306E","\u09B9\u09A8"," malaman"," egentligen","\u04AF\u0433\u04AF","\uFF0C\u5168\u56FD","<arr"," broadcasters","\u300C\u3042"," \u1ECDw\u1ECD"," wijs","identify"," maduras"," \u0915\u0930\u094D\u092E\u091A\u093E\u0930"," pitanju"," paligid"," Ergo"," bancada"," smarty"," damu","\u0113ji","f\xF6rder","disposed","<Usuario"," \u10D2\u10DB"," s\xE4l","-stars"," garoto","ANGLES"," \u0CAA\u0CB0\u0CBF\u0CB6"," \u0D38\u0D4D\u0D35\u0D3E\u0D17\u0D24"," ingev","gled"," gha"," Gug","VOC"," \u067E\u0648\u0681"," ethically","\u05D9\u05D9\u05D8\u05E2\u05E8"," \u10EA\u10D4\u10DC\u10E2\u10E0"," \u043E\u0431\u0440"," \u09A4\u09BE\u0981\u09A6\u09C7\u09B0"," \u0417\u0435\u043B\u0435\u043D"," symptomatic"," piz","penetr"," \u0627\u0644\u0645\u0633\u0631","lir","\u041F\u041E","\u5367"," \u05D2\u05E2\u05D2"," \u0C38\u0C3F\u0C26\u0C4D\u0C27"," Mahjong","azelo"," r\xE9alisateur","oboye","ykes","\uFF1F\uFF01"," caros"," LIS","alar\u0131n\u0131n"," ozbil","tekij"," \u05E9\u05D9\u05E0\u05D5\u05D9"," absurdo"," m\xFC\u0259ll"," hopped"," \u05D4\u05D7\u05E8"," \u044F\u0439\u0446\u0430"," buttery"," Worse"," HALF"," tiap","\u0A28\u0A4D\u0A39\u0A3E\u0A02"," attirer"," anledning","abing"," Converted"," feugiat"," \u0D06\u0D24\u0D4D\u0D2E","onesa","oghi"," \u0447\u044B\u043D\u0430\u043C","=center"," tch"," bem\xFC"," Empfang","/span"," piccoli","ecos"," \u043B\u0435\u0447\u0435\u043D\u0438\u0438"," ireland","Bref","\u6C27","agext","\u65E5\u306B"," \u042F\u043A\u0449\u043E"," Yoo"," ohnehin","\u6C11\u4E3B"," wohnen"," \u0433\u043E\u0440\u043E\u0434\u0441\u043A\u043E\u0439"," \u043E\u043A\u0435"," \u03B5\u03B2\u03B4\u03BF"," \u041F\u0440\u043E\u0432"," epo","\u0578\u0582\u0562"," BUF"," \u0909\u0928\u092E\u0947\u0902"," fot\xF3grafo"," M\xE9dico"," tider","ffin","_visibility"," \u0645\u0635\u0637\u0641"," Thunderbird"," \u0C89\u0CB3"," Bello"," k\xFCnst"," compet\xEAncias"," \u064A\u0634\u0639\u0631"," \u0627\u0644\u0628\u0648\u0644","\u0E2A\u0E27\u0E19"," fscanf","\xEDdios"," \uC608\uBC29"," \u06AF\u0632\u06CC\u0646\u0647","Loved"," igbesi"," \u0421\u043E\u0444"," \u092E\u0941\u0938\u094D\u0932\u093F\u092E",'"\u05D5',"\u{1F495}","\u05D9\u05DE\u05D5\u05DD",".dem","warna","cri"," \u062A\u0635\u0628\u062D","'effet"," handlebars"," Diretor","ditch","\u06A9\u0631\u0627"," \u4F17\u946B","\u0631\u0628\u064A\u0646"," gereal","/octet"," coroutine"," kindje","-Key"," \u0627\u0644\u062A\u0646\u0641\u064A\u0630\u064A"," miesi\u0119","\u30B7\u30EA\u30FC\u30BA","\u0E32\u0E23\u0E35","orados"," brzo","\u064A\u0645\u064A\u0646"," verwerking"," \u092D\u092F","cree"," Naughty"," ISC","\u0E31\u0E08\u0E08","\u0435\u043B\u0434\u0435"," chaleureux"," tieto"," Ger\xE4ten"," \u0440\u04D9\u0445"," ktor\xED","\xC1rea"," \u062C\u0644\u0648\u06AF\u06CC\u0631\u06CC"," \u0430\u0442\u0430\u043A","\u05D1\u05E8\u05D9\u05E7","\xED\u0161","_RPC"," abaz","hipster"," ansatte"," foret","komfort"," Disponible"," FOREIGN","\u03B4\u03AC"," sensitiv","Zj","\u10D0\u10E8\u10D0\u10E3\u10DA"," Adviser","_secure","(album"," forcibly"," Adsense"," Authenticate"," \u0CB5\u0CC8\u0CB0","]]]","\u2219"," confirma\xE7\xE3o"," hierzu","(Symbol"," Nadia"," marki"," \u5E97","\u5904\u5206"," itlog"," shughuli","\u5A31\u4E50\u5E73\u53F0\u4E3B\u7BA1","Dorm","()},\n"," m\u1EF9"," \u0642\u0648\u0645\u064A"," fili"," gebeurtenissen"," considere"," descubre","omod","\u066C"," Einladung","TIN"," ganhos",".gv"," distrik","Masc","-feed","\xE7iligi"," nnyo"," \u043C\u04AF\u0448"," Concello"," \u092C\u093F\u0932\u094D\u0915\u0941\u0932","_pas","\u0CC3\u0CB9"," weich","acor","\u10DD\u10D1\u10D0\u10D6\u10D4","career","_xlim"," \u0445\u043E\u0447\u0430"," saludables"," Sobald","\u0BCD\u0B95\u0BC1"," runaway"," civilized","ANTI"," hatta","\u0648\u0627\u0644\u06CC","\xD1A"," mmol","bane","innu"," glaubt"," c\u1EA5u"," Wannan"," \u056C\u0561\u0575\u0576"," \u0441\u0430\u0431\u0430\u049B","atawag"," commercialization"," kuele","hik"," \u043F\u0440\u043E\u0448\u043B\u043E"," seules","_trait","obyl","iiii","shirts","-IV","\u0947\u0930\u0940","polar","\u011Fiz","(friend"," crip"," \u5929\u5929\u4E2D\u5F69\u7968\u4E0D\u80FD\u4E70"," appreciating","@n"," sensores","\u09BE\u099E\u09CD\u099A","instantiate","_nv","ulnerability","\u0165a\u017E"," prosecute","\xE9in"," scrapbook","\u2019innovation"," faigofie"," DOB","vrije","\u0D19\u0D4D\u0D19\u0D3F","\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u043C"," marquee"," complains"," \u0576\u0577\u0561\u0576\u0561\u056F\u0578\u0582\u0574"," papir","]]\r\n","R\xE9sum\xE9"," \u0628\u0627\u0644\u0631\u064A\u0627\u0636"," \u5F35"," \u0627\u0644\u0639\u0645\u064A\u0644","addons"," Damian"," \u0D38\u0D28\u0D4D\u0D24"," motorway","\u0BB0\u0BBF\u0BB2\u0BCD"," uppsk"," industriais"," impregn","Hence"," wasm","\u03C4\u03AE\u03BC\u03B1\u03C4\u03B1"," uile"," eiser"," heutzutage"," \u0440\u0443\u0441\u0438\u0439\u04D9","ocannabino"," \u0916\u0941\u0932\u0947"," "," poka",".xxx"," regione"," \u0CAE\u0C9F\u0CCD\u0C9F"," Boxer","addition"," \u09B8\u09AC\u099A\u09C7\u09DF\u09C7","Cheque"," \u0448\u043E","Topo","datatable"," \u0437\u0438\u0434"," schaut"," h\u1EE5"," vesz"," adhart"," \u0441\u043B\u043E\u0432\u043D\u043E","(authentication"," \uB178\uB3D9"," Calabria","av\u4E0D\u5361\u514D\u8D39\u64AD\u653E"," wcze\u015Bniej"," grenade"," GBR"," \u06AF\u0633\u062A"," itk"," \u0907\u0932\u0947\u0915\u094D\u091F\u094D\u0930"," rady","(exchange"," aerodynamic"," kuo","ademic","yly"," \u6EE1\u5802","Privileges","\u04AD\u0430\u043A","\u603B\u4F53",".shader"," parent's","\u0434\u0430\u0440\u0430"," dn\xED"," Feiert"," graphi"," auge","\uFFFC"," Lisp","apatalk","_rooms"," \u0986\u099A"," Arbitration"," luxuri"," \u0438\u0440\u0430"," Konzentr"," CRS","amalama"," Proton","Appartement"," \u09AA\u09BE\u09B9"," aliquet"," eksister","\u09C0\u09A6"," alapj\xE1n","Medication","donald","\u03C1\u03B3\u03AC\u03BD","\u10D4\u10DC\u10D8\u10DA\u10D8"," atrak"," Suppressant"," \xE1udio"," dipercaya","\u516C\u7F51"," m\u011Bs"," \u043F\u0440\u0438\u0447\u0438\u043D\u0430\u043C","killer"," \u0431\u0435\u0439\u0497\u0438\u04A3","_ros"," Haitian","-Produ"," \u7F8E\u570B","toq"," kolem"," determina\xE7\xE3o"," karto"," \u0434\u043E\u0441\u0442\u0443\u043F\u043D\u044B"," \u0AAD\u0ABE\u0AB0\u0AA4\u0AAE\u0ABE\u0A82"," \u043C\u0443\u0441\u0443\u043B\u043C\u0430\u043D","etsk"," \u0645\u0627\u0643\u064A\u0646\u0629"," \u0924\u0901","imur",'()=="'," \u0C38\u0C02\u0C16\u0C4D\u0C2F"," detectable","\u093F\u092E\u093E\u0917"," \uC9C0\uB3C4"," erhe","retweeted"," constitui"," turista",'("");'," ')\r\n","\u0435\u0441\u0442\u0456"," chocolade","}!","\u0A15\u0A40"," \u0440\u0438\u0441\u043A\u0430","QObject"," \u062C\u0631\u0645"," mesmerizing",")...\n\n"," \u0D1A\u0D30\u0D3F\u0D24\u0D4D\u0D30","\u0E40\u0E0A\u0E35\u0E22\u0E07","\u043B\u0430\u0442\u0443","-\u1ECD","[]={"," \u0906\u0908\u092A\u0940"," meubels"," notif"," basiert"," Bangor"," N\u011B"," \u0C85\u0CA8\u0CCD\u0CA8"," thu\xEA"," yap\u0131","falz"," Documento","\u3001\u526F"," \u043F\u0440\u0438\u043D\u0438\u043C","\u0442\u04AF\u0441\u0442\u0456\u043A","\u0E40\u0E02\u0E49\u0E32\u0E2A"," Purchased"," \u0442\u04E9\u0440\u04E9\u043B"," Camper"," \u05DC\u05DE\u05E1"," \u0635\u0627\u062D"," ELF"," Mariners"," startled"," relentlessly"," \u718A","SNS","-Euro","\u043D\u0430\u043A\u0438","?.."," Clap",":J"," valable","=(-"," \u0630\u0627\u062A\u0647"," faili","\u0442\u0435\u0440\u0430"," \u043D\u0430\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435","\u672C\u91D1"," Secretario"," \u04E9\u043A\u04AF\u043B"," \u0A85\u0AAD\u0ABF\u0AA8\u0AC7","\u0443\u043C\u0435\u043D\u0442\u044B"," partik","Inclus","\xEDvio","\u0E42\u0E0A","\u0CA4\u0CBF\u0CAF","\u062E\u0648\u0627\u0647\u062F"," Filmes"," Yusuf","\u307E\u3041"," melhorias"," storico","richment"," entret"," \u062C\u0645\u0639\u064A\u0629","\u0646\u062F\u0631\u064A\u0629","-Claude"," el\xE4","\u043F\u0440\u043E\u0441\u0442","Slices","\u0AAA\u0A95\u0AA1","\u05DB\u05E0\u05D5\u05DF"," \u0391\u03B8\u03AE",":start","meh"," cracker","\u5728\u7EBF\u7CBE\u54C1\u89C6\u9891"," g\xEAn"," \u064A\u0639\u0637\u064A"," Schulter","listas","QRCode","IFUL"," \u0434\u043E\u0447\u044C","_signup"," Sunni"," \u10E3\u10EE",".hyper"," solides"," \u0D07\u0D02\u0D17\u0D4D\u0D32"," Bisa"," \u0CB0\u0CBE\u0CB7\u0CCD\u0C9F\u0CCD\u0CB0\u0CC0\u0CAF","\u30B9\u30BF\u30C3\u30D5","icont","Millions","bulas","yzda","\u30C6\u30FC\u30DE","\u0D31\u0D23","\u0178","ZU","\u0ABE\u0AA8\u0ACD\u0AB8","\u0131s\u0131yla"," intervju","\uFF09,","Graw"," causada"," conveyors","\u0446\u0438\u044F\u0442\u0430"," roulant"," \u0C2A\u0C30\u0C41\u0C17"," Boga","(inplace","SEMB"," \u0E23\u0E30\u0E1A\u0E1A"," assuring","achael"," t\xE1mogat"," eleitor"," \u057A\u0561\u057F\u0565\u0580\u0561\u0566\u0574\u056B"," ulim","\u05D5\u05E8\u05D0"," \u017Eivljenje","igia"," Gers"," \u062A\u0635\u0627\u0648\u06CC\u0631","Loans"," \u0445\u0443\u0441\u0443\u0441","\u0B1B","izacja","Puerto","\u3001\u5B89\u5168"," ;\n//",".euler",".Vehicle"," isit"," Britannica","_perf"," connective"," nitorinaa"," MUL",'")+"',"embo"," Reck"," Redes"," Kontext","hpp"," reply"," glaucoma","issani"," \u0648\u0631\u0681\u06D0","\u0635\u0631\u064A","garh","ovan\xFDch","determ"," \u0430\u0499"," \u0C24\u0C2F"," })\r\n\r\n","\u0D15\u0D4D\u0D15\u0D41\u0D28\u0D4D\u0D28"," baton","\u0430\u049B\u04D9\u0435\u0438"," \u10D4\u10E0\u10D7\u10DB\u10D0\u10DC\u10D4\u10D7\u10E1","####\n","H\xE4r"," \u041C\u0435\u043C","-CON"," Resurrection"," \u041A\u0440"," llegar\xE1"," Europe's"," Melo"," cherchent"," prawa"," clustered"," \u09B8\u09BE\u0995\u09CD\u09B7"," lounging"," \u0565\u0580\u056F\u0580\u0576\u0565\u0580\u056B"," \u0441\u043E\u0440\u0442\u0430","(flat"," blockade"," \u0445\u04E9\u0433\u0436"," \u0E41\u0E19"," kruis"," \u0644\u0645\u0633","\u0D2A\u0D4D\u0D2A\u0D46\u0D1F\u0D41\u0D24\u0D4D\u0D24\u0D3F\u0D2F"," odz"," \u4E45\u4E45\u70ED","hava"," Flesh"," l\u1EC5"," dilute"," unfor"," Attempts","decltype","ambisa"," gedeelt"," mangas"," kojeg"," jaunes"," JNI","\u05DE\u05E2\u05D8"," masculin","qqaat"," pll","alphabet"," \u0B8E\u0BA9\u0BCD\u0BAA\u0BA4\u0BC8"," geringe"," \u0633\u0648\u0631\u06CC"," Inspirations","aviest"," relata"," nack"," tejidos"," indikator","dop"," Schwanz","owani"," terasa","\u0651\u0649"," FMI"," kusho"," \u0D2A\u0D34"," \u6052\u4E00"," \u017Eene"," skb","adwy"," agencias","\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD"," intersects"," emoz"," royaume"," (),\n"," \u6A2A","BCC"," eof",":grid","\u0C97\u0CBE\u0C97\u0CBF","\u0D3E\u0D2F\u0D4D","Pret"," incre\xEDbles","ulto"," overlijden","(relative"," bbq"," ac\xFAst",":file"," Moran"," \u0442\u0430\u0440\u0438","uentes"," vorgenommen"," gegarande"," refurbishment","Ficha","\u045B\u0443"," DOJ","_CITY","\u0434\u04E3"," \u0622\u0634","\u043A\u0443\u043D\u0430\u043D\u0434\u0430"," cando"," izquierdo"," \u062D\u06CC"," aparat"," hamster"," \u0A9B\u0ACB\u0AA1","amphetamine"," \u0985\u09B8\u09CD\u09A4","itera"," \u4E9A\u6D32\u65E5\u97E9","(Html","\u8BA4\u8BC6"," Invisalign"," fasilitas","\u0637\u0648\u0631\u0629","\u1010\u1031\u102C\u1037"," \u0D15\u0D25\u0D3E\u0D2A\u0D3E\u0D24\u0D4D\u0D30"," localisation"," \u0443\u0431\u0440\u0430\u0442\u044C","omsnitt"," \u0CAE\u0CBE\u0CA1\u0CBF\u0C95\u0CCA\u0C82\u0CA1"," \u0448\u0430\u0430\u0440\u0434"," \u043F\u0440\u0438\u0431\u044B\u043B\u0438"," \uC624\uB978"," bpm","\u52D5\u756B"," luncheon"," \u043A\u0438\u0442\u043E\u0431",".exercise","'effect"," bezwaar","ovania"," \u091B\u094B\u095C","acyjne","oglio","\u5085"," quake"," zata"," remuneration"," onderzoekers","_IMETHOD"," disagreements"," handi","Hm","Acceptance"," entwickelte"," ndim"," doctrina","\u0443\u0440\u044B\u0441"," \u092D\u093E\u0935\u0928\u093E"," \u043A\u043E\u043C\u043F\u0430\u043D\u0438\u0435\u0439"," homofile","\u043C\u044B\u0439"," izgled","qml","<il"," novella","\u0E15\u0E2D\u0E1A"," thi\u1EC7u"," beheren"," \u03C0\u03BB\u03B5\u03C5"," esigenze","\u0BCA\u0B9F"," crot"," \u0645\u0639\u062A\u0628\u0631","\uC624\uAE30","itiers","Thirty"," rano"," \u0D21\u0D4D\u0D30"," recombinant","_EST","\u0561\u0576\u0577","[result","Christine","\u4E0D\u5361\u65E0\u7801"," \u0437\u0430\u0447\u0430\u0441\u0442"," \u0437\u0430\u0445\u043E\u0442","\u0561\u0576\u0564\u0561\u056F","\u1010\u103D\u1000\u103A"," dialogs","_AI"," \u5E02","lisi","-highlight"," stun","\u0111ena"," adoptar"," wanem"," halde"," bigint"," Adu"," profesjonal"," Wondershare"," murdering","ASHION"," instalada"," laborat\xF3rio","airport","(Logger"," aangeven"," Bahkan","cutta","\xF3viles"," pilares","\u0441\u0435\u043D\u0434\u0456"," \u0D1C\u0D3F\u0D32\u0D4D\u0D32\u0D2F\u0D3F\u0D32\u0D46"," \uC624\uB798","ADORES"," motivatie",".EMAIL","$temp","\u6B27\u7F8E\u65E5\u97E9","erms","\u03BB\u03C9\u03C3\u03B7"," hoofdstad","A\xF1"," spokoj","/accounts"," crates"," Verpflicht"," fant\xE1stica"," fracaso"," \u0627\u0644\u0631\u0627\u0628\u0639\u0629"," vacunas","brates","PRIMARY"," conforms","\u03BA\u03C5"," \u043F\u043B\u0430\u043D\u044B","acd"," \u0123"," rohe"," conserving","\u0628\u06BE","\u0442\u0438\u043B\u0438"," \u062D\u06CC\u0631","\u0BBF\u0BAF\u0BC7"," \uC624\uB958"," \u03C0\u03BF\u03C3"," \u0AB8\u0A82\u0AAA\u0AB0\u0ACD\u0A95"," \uBBFC\uC8FC"," \u043A\u0435\u043D\u04D9",":web"," subterr","processors","tensorflow"," confirmou","Horas","\u0561\u0563\u0561\u0570"," Formatting","_similarity","(Movie"," assimilation","\u80FD\u4E70\u5417"," \u03C0\u03BF\u03C4\u03AD"," Duarte"," kurulu\u015F","STANDARD"," HERO"," blinded","-------------------------------------------------------------------------\n"," So"," sonidos"," \uC788\uC74C"," JSP"," Tcx"," Castelo"," Linking"," enquire","amano","Feet","Walter"," \u0633\u0648\u0621","hooter"," Fabian","ungele","\u0648\u0645\u062A\u0631"," \u0B8F\u0BB1\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F"," creativo","OGA"," Apro","endidos","cris"," FARM"," Goldco",",{\n"," N\xF3"," natus"," \u03C0\u03C1\u03CC\u03B3\u03C1\u03B1\u03BC\u03BC\u03B1","Plano","\u17B6\u1798\u17BD\u1799","thawi","\u0928\u093F\u0915"," \u0C28\u0C3F\u0C30\u0C4D\u0C2E\u0C3E\u0C24","hetseng","\u636E\u4E86\u89E3"," constamment","ew\u0121"," Atari"," \u06AA\u0627"," g\xF6sterm","\u529B\u5EA6","\xE9ralement"," \u0445\u0430\u043B\u044B\u049B\u0430\u0440\u0430\u043B\u044B\u049B"," \u0443\u0434\u043E\u0432\u043E\u043B\u044C\u0441\u0442\u0432\u0438\u0435\u043C","-too"," Kartoff"," \u03B3\u03BD\u03CE","\u2019ay"," \u09B8\u0995\u09CD\u09B7\u09AE"," ponu"," shoved"," \u0433\u0435\u043A\u0442"," lefatsheng"," \u0BA8\u0B9F\u0BB5\u0B9F"," \u0441\u0442\u0440\u0430\u0442\u0435\u0433\u0438\u0438","BEC"," interesser"," JMS","\u0936\u094D\u0930\u0947\u0937\u094D\u0920","\u4E92\u52A8"," QUESTIONS"," marts"," Appreciation","Linejoin"," \uB4F1\uC7A5"," Mileage"," Tuna"," escreve","Fizz"," uya"," \u0A86\u0A82\u0AA4","\u09AF\u09BC\u09C7\u09B0"," record\xF3"," olje"," sitere","ymmen"," diaphragm"," etdiyi"," \u05D3\u05D5\u05DC\u05E8"," ')'"," Cassidy","\u09BE\u09A8\u09CD\u09A1","ulados","\uFF09\n\n\n"," Beaumont","\u044C\u044B\u0440"," zhv"," DASH","\u044B\u0432\u0430\u0435\u0442"," hoid"," entertainers"," Texto","advies"," kezel\xE9s"," papill"," \u0639\u0628\u0627\u0631\u062A"," \u0627\u0644\u0648\u062B"," \u0432\u0430\u0436\u043D\u044B\u0445"," \u0623\u062D\u062F\u0627\u062B","-budget"," \u05D8\u05D5\u05D8",".scalar"," \u0631\u0633\u0645\u06CC"," Waxaan","@\\","\u03BA\u03CC\u03C3"," levi"," \u043F\u043E\u043A\u0430\u0437\u0430\u0442\u0435\u043B\u044C"," boq","\u1789\u17D2\u1787"," perig"," afwijk"," Parma","etem"," regelgeving","\uC774\uBA74"," ausgesprochen","('.');\n","_written","(toggle"," aumentado"," jornais","\u5C24\u7269"," \u043D\u0430\u043C\u043E\u044F\u043D","\u0648\u062F\u0631","Whit"," livelli",".PNG"," Ignite"," IIS","ajen"," letten"," shoppen"," \u0907\u0924\u0928\u0947","markup"," bsp"," promessa"," \u0CAA\u0CCD\u0CB0\u0CB6\u0CCD\u0CA8"," Sabah"," Com\xE9rcio","amanzi"," Ausbau",".Dto","\u0446\u0438\u043D"," multaj"," historii"," orale"," \u0639\u0627\u0644\u0645\u064A","\u0415\u0421"," liest"," afzonder"," compacto"," \u092C\u0940\u092E\u093E\u0930\u0940"," \u043E\u043F\u0446\u0438"," \u0441\u043A\u043B\u0430\u0434\u044B"," usamos"," \u0635\u0641\u0631","_Email"," \uBC18\uB4DC\uC2DC","\u05D9\u05E4\u05D5\u05E9"," \u0917\u0941\u091C\u0930\u093E\u0924"," \u03B4\u03B7\u03BC\u03CC"," Shrine",".claim"," \u0441\u043B\u043E\u0442"," ak\u0101"," \u062E\u0648\u0627\u0647\u06CC\u062F","wiritsidwa","utinut"," r\xE9tro"," iter"," TALK"," \u05D4\u05DB\u05E8","ziemy"," \u0442\u0443\u0443","\u0E1E\u0E23\u0E49\u0E2D\u0E21"," Sparrow","orium"," kaikke"," \u0648\u0627\u062E"," \u0437\u0440\u0430\u0431\u0456\u0446\u044C"," \u0436\u04D9","-Mit","\u10E1\u10D8"," produkt\xF3w","UIC"," n\xE1\xE0","-growth"," trolling","neqarpoq","_mapper","Delimited"," \u0438\u043D\u0442\u0435\u043B\u043B\u0435\u043A\u0442\u0443","cerias"," Nour","\u514D\u8D39\u65E0\u7801","\u0628\u0627\u0639\u0629"," center"," Teenage"," Entwicklungen"," transt","usche"," interoperability"," \u0E40\u0E2A\u0E37\u0E49\u0E2D"," Daphne"," Finest"," Silverado","Laundry"," o\u011F"," Lis\xE4\xE4"," Harding"," \u0437\u0443\u0440\u0430\u0433"," exploratory"," weerstand"," newsroom","\u0C3E\u0C32\u0C40\u0C35\u0C41\u0C21\u0C4D"," coriander"," \u0CAA\u0CCD\u0CB0\u0CAE"," Formel"," comrades","Praise","\u09CD\u09AF\u09BE\u09B8","-launch","'\xE9volution"," \u0627\u0644\u0643\u0634\u0641","ippaa"," \u0637\u0641\u0644","\u0E23\u0E31\u0E48\u0E07\u0E40\u0E28"," Wilaya"," atentos",".rdf","designation","_USED","[ip"," criticizing"," legitimately"," \u578B"," succulent","zerano","\uB044"," gu\xE9r"," \u043F\u0440\u043E\u0445\u043E\u0434\u044F\u0442"," CALLBACK"," ressembl"," uncontrolled","-floating"," Auctions"," predictors"," t\xF3c"," \u0B8E\u0B9F\u0BC1\u0BA4\u0BCD\u0BA4"," \u043C\u044B\u043D\u0434\u0430\u0439"," glatt","aturbate"," differed"," panes"," \u0438\u043C\u0440\u04EF\u0437"," \u0627\u062F\u0628","FIELDS","shock","\u0627\u0639\u064A"," wrongdoing","\u092A\u094D\u0930\u0926\u0947\u0936"," degelijk"," funcs"," \u05D0\u05D2","/location","(gs"," ogled","\u044F\u043B\u043E","Chez"," fede","-ounce"," rhyw"," \u0644\u0642\u0628","\u043E\u0445\u043E\u0436\u0438\u0435"," trzy"," veoma","=o"," brook"," OCI"," \u062A\u0628\u062F\u06CC\u0644\u06CC"," \uC548\uC815"," crackdown","tweets","\u53EA\u6709\u7CBE\u54C1","ippage"," versos","wijze"," ki\u015Filer"," deoarece"," tilfred"," \u0627\u0644\u0645\u0646\u0627\u0641\u0633"," propensity","!!)\n","OLVE"," \u044D\u0441\u0435\u043F","\u0CBF\u0CAE\u0CBE\u0CA8","_submission"," Hoc"," \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u0438\u0435"," sjed"," \u0C35\u0C46\u0C02\u0C15","\u0631\u0648\u0628\u0627\u062A","b\xE9s"," \uC6D0\uD558\uB294"," Switching"," experimented","uoja","IODevice"," \u041B\u0443\u0447\u0448\u0435"," przyk\u0142ad"," \uBAA8\uC2B5\uC744"," \u91CD\u5E86\u65F6\u65F6\u5F69\u5F69"," Peyton"," \u0916\u0947\u0924\u0940"," confeccion","(shell"," \u0438\u0433\u0440\u043E\u0432\u044B\u0445"," \u05D4\u05D2\u05D5\u05E3"," \u043E\u0431\u0449\u0438\u0439","_languages","emask"," hitters","kamera"," acreage"," `_","<Device","\u010Dkom"," \u0CA6\u0CC7\u0CB5\u0CB8\u0CCD\u0CA5"," potrebe"," sonras\u0131"," b\xE4st"," jornalistas","ussing"," laboris"," Reconstruction","\u0ABE\u0AA3\u0ABE"," \u0130nsan"," \u03C7\u03B1\u03C1\u03B1\u03BA\u03C4\u03B7\u03C1\u03B9\u03C3","/MS","arczy"," PPO","illuunniit","Titel"," uchel"," p\xE9trole"," \u0639\u0627\u062C"," caafima","\u0ABE\u0AB3\u0ACB"," \u05D4\u05DE\u05E9\u05EA"," VARIABLES","\u0161oant\u0161o"," \u057E\u0565\u0580\u0561\u0570","-awareness"," poseen"," \u043C\u0438\u0441\u0442"," Deutschmark"," \u0C2E\u0C40\u0C21\u0C3F\u0C2F\u0C3E\u0C32\u0C4B","\u06D5\u062A\u0643"," estaduais"," vertu","Investor","mmert"," supervising"," Rect",'":[],\r\n',"arnermik","BURG"," O\xF9"," \u0625\u0644\u0643\u062A\u0631","ddangos",'"${'," Wehr"," pr\xEDpade"," \u0421\u043E\u043D\u044B\u043C\u0435\u043D"," inuiaqatigi"," \u5317\u4EAC\u8D5B\u8F66\u6295\u6CE8"," \u041C\u0412\u0414"," s\xE9paration","Interestingly"," \u0414\u041E","\u0438\u043D\u0430\u0439","setzt"," praxis"," \u0430\u0440\u043C\u0438\u0438","ccd","\u0440\u0438\u0441\u0442\u0430","\u0C95\u0CCD\u0CA4\u0CBF"," g\xE2"," Reglamento","Detroit"," Kendrick"," \u09A6\u09C7\u0996\u09BF","\u5B98\u7F51\u767B\u5F55"," h\xFCk\xFC","Dose","vura"," TInt"," Khr"," \u0432\u0430\u0442",".creation"," \u0642\u0644\u064A\u0644\u0629"," mgbanwe"," il\u1ECD","\u0435\u043D\u0437\u0438","bfd","\uFF0C\u4F1A"," diverted","cristo"," \u0441\u0442\u0435\u0440","ospels","(_('",".checkout"," \uC800\uB294","\u7E8C"," \u0AAC\u0ABF\u0AB2","(Security","usalema"," \u624E"," CTS"," refrigerated"," \u0998\u09F0",'=?",'," reflector","continuous"," gepland","\u0924\u093F\u0939\u093E\u0938"," ba\u015Flan","\u0E20\u0E32\u0E1E\u0E31\u0E19\u0E18\u0E4C"," preocupado"," unum","st\u0101"," \u0434\u0430\u04BD\u0430"," Deve"," Novi"," gr\xE9","\u5173\u8054","awed"," elliptical"," kras"," \u05D1\u05D0\u05B7\u05E7\u05D5\u05DE\u05E2\u05DF","kep","\u0AB5\u0ACD\u0AAF"," eyewitness"," \u0627\u0644\u062F\u0631\u0627\u0633\u064A","abee"," \u043E\u0433\u0440\u0430\u043D\u0438\u0447\u0435\u043D\u0438\u044F"," Ortalama"," estabelece"," \u6210\u90FD"," sariling"," strapped"," \u0644\u062A\u0639"," quelcon","\u041F\u043E\u0437"," \u0540\u0561\u0575\u0561\u057D\u057F\u0561\u0576\u0568",")var","ltf"," }):"," \u0437\u043D\u0430\u0439"," H\u1EA3i",".Hex"," obdob\xED","pham","[module"," zette","\u5F69\u7968\u5A31\u4E50\u6CE8\u518C"," desean"," habia"," vissen"," \u041F\u043B\u0430\u043D"," resolveu",'"display',"\u094D\u092F\u093E\u0915"," \u05E9\u05E1","elerinde","\u4E09\u7801","onomies"," GEL","anfan","m\xFCr"," voorbereid"," empiez"," \u064A\u062C\u062F"," \u03C0\u03B5\u03C1\u03AF\u03C0\u03BF\u03C5"," \u0938\u0942\u0930\u094D\u092F"," Cliquez"," \u30AC","neider","\u5A31\u4E50\u5E73\u53F0\u5F00\u6237"," Ony"," Maaari"," aufreg"," \u0A9A\u0AC1\u0A95"," TYPO","weist"," \u0909\u0926\u094D\u0927","\u0BC1\u0BAE\u0BBE\u0BA9","roepen"," \u0441\u0441\u044B\u043B\u043A\u0430"," \u0BAE\u0B9F\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"," vady"," onderzocht","\u0ABF\u0AAF\u0AB0","Entreprise"," hashmap","\u0493\u043E\u043D\u0438"," Wilkinson","\u3000\u672C","/right"," \u043F\u0440\u044B\u0439",'."_'," hormona","hebb","Romans"," \u092E\u0941\u0926\u093E"," \u0938\u094D\u091F\u094D\u0930"," aet","\u3000\u4E09","\xB4\u30FB"," keyed"," anim\xE9"," Patti","_sampling","kx","ardige","\u0438\u0440\u0443\u044F"," argentinos"," \xFAd","hunter"," Dalka","\u0561\u0576\u0575\u0578\u0582\u0569"," \u0907\u0902\u0938\u094D\u091F","_IMAGES","\u010Dn\xFDch"," serif","shim",".):"," Griechen"," sheen",".tagext","Cadastrar"," leedahay"," \u043A\u0430\u043C\u0441\u044B\u0437"," Shemale","\u103B\u1016\u1005\u1039","Dropbox",".billing","\u0432\u0438\u0437"," \u0920\u093E\u0915"," membri","oodu","anyisa","lur"," \u0630\u06C1"," Afurika"," sexuels"," podpis"," \u0C9F\u0CC6"," kerajaan","beras","=session"," \u0E2B\u0E19\u0E49\u0E32"," Bung"," Jumat","_dense"," \u0689\u0644\u06D0","\u0443\u0449\u0438\u0439"," \u0D39\u0D46",";)\n"," Joke"," \u05D4\u05E1\u05EA"," \u0915\u0930\u0947\u0917\u0940"," \u0C2A\u0C4D\u0C30\u0C35","\u3001\u65E5\u672C"," Aver","\xE4v\xE4\xE4","PLI"," Fiverr","ilyen"," \u10E7\u10DD\u10D5\u10D4\u10DA\u10D3\u10E6"," violences","amisesta"," hablado"," \u0928\u093F\u0930\u0940"," ASIC"," \u0C35\u0C3E\u0C30\u0C3F\u0C15\u0C3F","aka\u02BBi","{}\\"," -->\r\n\r\n"," molestie"," m\xF5\xF5","\u4E8B\u52A1","\u0442\u0435\u0440\u0434\u0456\u04A3"," yaliy"," reverted"," capaciteit","wedstrijd"," vsebuje"," \u0C24\u0C4A\u0C32\u0C3F","g\u0259r","_secondary"," psicol\xF3gico","\xE1rn\xED"," iechyd","icatie","iversaire"," \u10E4\u10DD\u10E2\u10DD"," met\xE0"," Terraria"," teklifler",");\r\n\r\n/"," best\xE4tigen"," luy\u1EC7n"," iib","\u0442\u0443\u0440\u0430\u0442\u04D9","indx","Reconnect","\u0C42\u0C1C"," presentada"," veres","\u016Fst"," kugirango","\u5EF7","Mons"," \uAD00\uB9AC\uC790"," \u0433\u0430\u0441\u0442",".wave"," \u05D4\u05E1\u05E8\u05D8","uzzo"," \u0441\u043E\u0431\u0441\u0442\u0432\u0435\u043D\u043D\u043E\u0433\u043E"," \u0627\u0644\u0645\u0639\u0627\u0631\u0636\u0629"," misura","\u0443\u043C\u0435\u043D"," Clermont"," parmesan","(Paths"," gereden","drawable"," fiables"," Regione","-\u05D4"," Ii"," Koe"," yaran","-look","adag","apay"," nab\xEDz\xED"," bester"," \u0627\u0632\u062F","istorical"," \u6842"," \u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u043E\u0441\u0442\u044C","\u0561\u056F\u0578\u0582\u0574\u0562","\u0958"," \u4F5B"," \u06AA\u0646\u062F\u0627"," riveting","\u0AC7\u0AB2\u0AC1\u0A82"," finca"," \u09B6\u09CD\u09B0\u09AE","\u10DD\u10E0\u10EC"," crossings","__.'/"," warped"," Mar\xE7o"," Civilization"," \u0648\u0627\u0644\u0645\u062F","\u0627\u0636\u0629"," bancaria"," h\u1EADu","amiut","_AUTHOR"," JQuery"," riport","Usd","sko",".AD"," araba"," lecturers","cand","COMING"," ymlaen","\u0E02\u0E49\u0E2D\u0E07"," Palestina"," Ukw"," asters"," Aucun",'"For',"\xE0ries"," forage"," \u0CB8\u0C82\u0C96\u0CCD\u0CAF\u0CC6","Joel"," yata"," habituales"," \u03BC\u03BF\u03C1","\u09CC\u09B6","\u547B\u541F","stede"," fabricar"," \u057D\u057A\u0561\u0576","ONTO","!*\\\n","ficie","\u2019annonce"," \uAF43"," \u043A\u0438\u04A3","\u1021\u1005"," diminution","\u062B\u0645\u0627\u0631\u0627\u062A"," H\xE9r","\u0451\u043D\u043D\u044B\u0445"," Gouvernement","TOK"," \u0A26\u0A30"," d\xE9cennies","\u043A\u043E\u043D\u0442"," Hrvatskoj"," \u044D\u043C\u043D\u0435"," JAM"," \u092E\u0917","\u06AB\u064A"," braided","Rainbow","stake","ij\xE3o"," favoris"," DHS"," \u09AA\u09BE\u09A8\u09BF"," rapproche","\u0643\u0634\u0641","\u0627\u0641\u0627\u062A","+\u5929\u5929\u4E2D\u5F69\u7968"," stoi"," zwi\u0119ks"," y\u0131l\u0131","\u2019abandi","_executor",".randrange"," LDS","_TM"," \u1ECDl\u1ECD","r\xE9tiens","}}\\"," Zwecke"," \u0627\u0646\u062A\u06C1\u0627\u0626\u06CC","\u0AA4\u0ABF\u0A95","\u094C\u0924"," mo\u017Eemo"," pr\xE9l"," verticale"," Adem","\u8FDB\u884C\u4E86"," salarios"," veu"," apareci\xF3"," \u10D5\u10D8\u10E7\u10D0\u10D5\u10D8","\u062A\u0648\u0631"," Papel"," \u057A\u0561\u0570\u056B\u0576"," \u0414\u0443\u043C\u0430"," \u0644\u0628\u0639\u0636",' ?"'," gosh","Donnell","ljive"," \uACBD\uCC30","joins","heated","/poly"," \u0458\u0435\u0440","Rtc"," dauern","\u094D\u0932\u0947"," \u0628\u062F\u0627\u0646","eyen"," spool","_sta","_TILE","\xE9diteur","Spike","wandle"," m\xE9id"," incentivar"," deelnemen"," lim\xF3n"," prendra","\u0412\u044B\u0441"," muddo"," \u0562\u0561\u0576\u0561\u056F\u0581"," DZ"," \u0D24\u0D40\u0D2F"," operator","\u6703\u54E1"," \u0623\u0639\u0631\u0641"," Wherever"," \u0425\u043E\u043B","\u0932\u094B\u0915"," Risks"," \u05D7\u05D2"," d\xFCzg\xFCn"," przeb"," \u0AAB\u0ACD\u0AB2"," cringe"," klient\xF3w"," smrti","arpa","\u0ABE\u0AAF\u0AA4"," d\xE9bats","titor"," \u0E40\u0E23\u0E37\u0E48\u0E2D\u0E07","\u0438\u0440\u044B"," \u041F\u0430\u043B","ellaan"," flwyddyn"," \u041E\u0433"," Tron"," fwrite"," philanthrop","trate"," \u0627\u0644\u0643\u0627\u0645\u0644","Publicidade"," roommates"," adulta","\u9A6C\u514B"," \u092B\u093E\u092F\u0926\u093E"," silhouettes","\u79D1\u5B66\u9662"," p\xE1s","\u0C30\u0C15\u0C41","urlijke"," engine"," \u0444\u0430\u0440\u0437",' ",\r\n'," HGH"," \u0431\u0440\u044E"," aangen"," haem","-serving"," rosas"," Dowladda","!/"," correspondente"," \u0627\u0644\u0623\u062F\u0627\u0621","\u0986\u0997"," pokra\u010D","functie"," possiamo",".jfree"," endlaka","sg\xE1l"," spezialisiert"," guzti"," forklift"," nofoaga"," Bartlett","-debug"," feina","\u0631\u0648\u0642"," \u05D1\u05D4\u05D7\u05DC\u05D8"," nascer"," geeks","iliy","_seek","_IRQHandler","\u05DE\u05E6\u05D0"," chinhu"," understandably"," k\xE4y"," Darth"," \uC81C\uACF5\uD569\uB2C8\uB2E4"," \u090F\u0915\u094D\u091F"," \u0633\u0643"," \u06CC\u0627\u0641\u062A\u0647"," totalit\xE9"," nens"," CROSS","_trials","\u0441\u0442\u044D\u0440"," wnd","\u535A\u5F69\u516C\u53F8"," okuf"," verdwenen","\u05D9\u05D3\u05D6\u05E9","/Templates"," \u091A\u0932\u0924\u093E"," aangekond"," beschermd","gevoel"," \u0438\u0447\u0438\u043D\u0434\u0435"," d\xE9licieux","?|","_SIDE","estat"," multas","eig"," \u043C\u0430\u043A\u0441\u0438\u043C\u0443\u043C"," Satell","varna",".transforms"," Surveys"," impetus"," nakita"," auditions","xiang"," mjini","Shortest","(ord"," \u10DE\u10E0\u10D0\u10E5\u10E2","artuss","\u043F\u0440\u043E","umpulan"," aqu\xF2"," \u10D4\u10D7","owatt","Putting","\u663C","Cambio"," duration","_frac","_plate","Buenas","\xF8ring"," disseram","Customized"," \u0448\u0443\u0434\u0430\u043D\u0438"," consequ\xEAncia"," unloaded",".\u0B8E"," \u7235\u58EB"," prefere"," apparition"," vermijden","\u0AC0\u0AA0","\u7ECF\u5178\u4E09\u7EA7"," \u0938\u0947\u0915\u094D\u0938"," T\u0101",",'.","_aug","\\Array","Readonly","Applicants"," capelli","prd"," captar"," \u0627\u0644\u062A\u0636","rosi","Gob"," \u015Bwiata","nelly"," Conde"," bijk"," \u5929\u5929\u4E50\u8D2D\u5F69\u7968","Chen"," Gaelic"," cuentos"," \u0627\u06CC\u0645\u0627\u0646","-independent","GAR"," \u0432\u0456\u0439\u0441\u044C"," concili","(.)","sels"," \u043A\u04AF\u0440\u04D9"," solte","Phen"," zuz"," quandu","UMIN"," \u056F\u0561\u056D"," Supra","\u3001\u540D\u7121\u3057"," \u05D7\u05D9\u05DC"," masquer"," \u043D\u043E\u0432\u0438\u0447"," augment\xE9","\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u043E\u0439",".practice"," pasien"," \u015Bwiad"," caretaker","army"," inspiraci\xF3n"," \u0C89\u0CA4\u0CCD\u0CAA","\u10EC\u10E3\u10EE"," aktivitas","_PLAN"," bhaineann","ugbo","\u0995\u09CD\u09B8"," \u0626\u0627\u062F","bier"," protested"," \u0935\u093F\u0930\u093E\u091F"," \u0440\u0430\u0441\u0445\u043E\u0434\u043E\u0432"," ...\n\n\n"," ffur","-All","Constru","Retrieved"," incr\xEDveis"," \u0438\u043C\u043A\u043E"," foliga"," Balanced","\u1021\u101E"," schlechten"," \u03B1\u03BB\u03BB\u03B1\u03B3"," \u0436\u0430\u0441\u0430\u043F"," S\u01A1n","\u0438\u0440\u0430\u0438","\u10D8\u10DC\u10D4"," milioane","EMU","\u2019\xE9viter"," hyr"," encontre"," hallar"," tablas","_Long","<Cell"," interacted"," figsize"," \u10D6\u10E6"," \u0447\u043E\u0432\u0435\u043A"," Codigo"," dedica\xE7\xE3o"," stolet"," Orten","Philip"," \xE9mission","\u0E32\u0E2B\u0E25\u0E35"," bearbeiten"," mierda","holde","\u0443\u0432\u0430\u0432","<Component"," WPA","\u05E6\u05D9\u05DC\u05D5\u05DD","SSA"," Allies"," B\xE1r","_mer","_SMS"," \u0918\u0942\u092E"," Fixtures"," Bask"," \u5F90"," tradu\xE7\xE3o","blicke"," hammered"," \u0441\u04AF\u043F"," \u0431\u0438\u0433","olu\xE7\xE3o"," electricians","\u0631\u06CC\u0634\u0646"," pitsaaner"," cier"," Receita","\u9EBB\u5C06"," \u0437\u0430\u043A\u043E\u043D\u043E\u0434\u0430\u0442\u0435\u043B\u044C\u0441\u0442\u0432\u0430"," \u10DE\u10D0\u10E1\u10E3\u10EE\u10D8\u10E1\u10DB\u10D2","-operated","\u0D4A\u0D2A\u0D4D\u0D2A\u0D02"," hassles","\u093E\u0924\u0930","\u0430\u043D\u0430\u0433\u0430\u0440\u0430","\u05E0\u05D8\u05E8","Japgolly"," doeleinden"," \u043F\u0435\u0440\u0435\u0439\u0442\u0438"," temsil"," ol\xEDmp"," Spazier"," \u0627\u0644\u0633\u0645\u0627"," pressione"," fiscais","l\u0259rini"," abode"," tantric","()],","rello"," \u0437\u0430\u0447\u0430\u0441\u0442\u0443\u044E","\u5FAE\u8F6F\u96C5\u9ED1","\u0633\u0631\u0627\u0626\u064A\u0644\u064A\u0629"," uitzending","flok"," escult"," Cerro"," is\xE6r"," kobiet","uree","\u0C95\u0CCA","encha"," adhesives"," paura","\u30C3\u30D4\u30F3\u30B0","\u0E27\u0E31\u0E22"," names"," slimmer","milk"," \u0A95\u0AB0\u0AA4\u0AC0"," Cim"," \u0441\u0432\u044F\u0437\u0430\u043D","\u200C\u0C28\u0C4D"," Chauff"," vingers","\u0430\u0446\u0430\u0440\u0442"," webcast",".notice"," m\u1EB7c","Passengers"," \u05E4\u05BC\u05E8\u05D0\u05B8\u05D3\u05D5\u05E7\u05D8\u05DF","\u0430\u043C\u0435\u0442\u0440"," VBA"," \u0440\u0430\u0437\u0432\u0438\u0432\u0430\u0435\u0442\u0441\u044F","])));\n"," surfers"," \u05DE\u05EA\u05D0\u05D9\u05DD","')):\n",".apk","\u1EDBm"," \u05D4\u05DE\u05D6"," brincar"," AMOLED"," nate"," ayaan"," phosphorylation"," \u0985\u09AA\u09C7\u0995\u09CD\u09B7"," Eats"," Converse","\u094D\u092F\u0942\u091F\u0930","Traveler","inggi","\u05D5\u05E8\u05D2"," almoh"," \u0625\u0641\u0631\u064A\u0642\u064A\u0627"," Magazin"," Arme","\u0E23\u0E01\u0E34\u0E08"," a\u015Fk","-lines"," \u0627\u0644\u0623\u0645\u0627\u0643\u0646","\u516C\u5E73"," kv\xE4ll"," mlx"," \u092E\u0928\u094D\u0924\u094D\u0930\u0940","\u10D0\u10D5\u10D8\u10D0"," teks"," lumea"," legyen"," zwing"," boost"," J\xFA","\u5F69\u7968\u8BBA\u575B"," \u0434\u044D"," \u043E\u0448\u0438\u0431\u043E\u043A","\u0561\u056F\u0561\u0576\u056B","\u0E24\u0E29\u0E20\u0E32\u0E04\u0E21","ebwa"," tipu"," domini"," Gurgaon","combat"," Resist"," \u0930\u094B\u091C\u0917\u093E\u0930","strategie","\u0A17\u0A40","(locator","MONTH"," atlik"," \uB79C","\u0627\u0644\u0633\u064A"," rzecz"," W\xE4"," deportivos"," Facilit","-able"," evitare"," thong"," \u6D3B","\uBB34\uB8CC"," mace"," Extraordinary","\u0927\u093E"," konflik"," livelihoods"," \u043A\u043E\u043C\u043F\u043E\u043D\u0435\u043D\u0442\u043E\u0432"," kuitenkaan","\u5E78\u8FD0\u98DE\u8247","Corpus"," besch\xE4d"," \u05D3\u05D5\u05D3"," dentant"," nweta"," heath"," \u0936\u0941\u0915\u094D\u0930\u092C\u093E\u0930"," mnemonic",".Filters",`','".$`," \u0905\u0938\u094D\u0924","isite"," asawa","\u5E74\u6708"," gotas"," \u0C2A\u0C28\u0C3F\u0C1A","Dek"," Pact","'agence","fei\xE7o"," B\xF6yle","venteen","notif"," \u0410\u043D\u0434\u0440\u0435\u0439","\u591A\u5E74","mittedly","\u8CA1\u5E03"," \u043A\u043E\u043C\u043F\u0430\u043A\u0442","trk","\u0928\u094D\u0926\u094D\u0930\u0940\u092F"," miesto"," Kait"," \u0CAC\u0CB8"," spec"," Injector"," logarith","entions"," \u0447\u0435\u043B","Collateral"," confes","\u093F\u0939\u0930"," sufri\xF3","CRI"," tuge","urllib"," k\u013C"," verpleeg"," application's","(Constructor","\u09BE\u09B2\u09BE"," vulputate"," \u043E\u043F\u0443\u0445"," Nordrhein","allage","\xEDsimas","ornado","\u0438\u0434\u0435\u0440","m\xE9nyek","Qua"," pelicula","\uC131\uACFC","\u3011-"," hemi"," touristes"," absentee"," Nether",".PAGE"," i\u015Fg\xE4r"," efectivos"," saav"," ","flashdata"," sembler"," ikuku"," \u099F\u09BE\u0987"," \u201D\n","\u5F69\u7968\u5E73\u53F0\u5F00\u6237","\u65C1",".\u0413","uckles"," \u0627\u0644\u062E\u0627\u0631","\u0432\u043E\u043B\u044C"," \u043D\u0435\u0432\u043E\u0437\u043C\u043E\u0436",".gradient"," ebile"," Athlete"," \u0442\u04B1\u0440\u0493\u0430\u043D"," Syrie",".processing"," Consultancy"," thrills","\u0642\u0631\u0627\u0621","(varargin","k\xFCnfte"," \u5F6D","-knit","riedenheit"," t\xE4nka","']//","udies","hacer"," Th\xE9\xE2tre","av\u7535\u5F71"," Armada","-techn","ibris","veli"," razloga","-Hop"," \u05DE\u05D7\u05D3\u05E9"," Bloggers"," controversies"," \u0C1A\u0C30\u0C4D\u0C2F"," \u0D2A\u0D4D\u0D30\u0D2E\u0D41\u0D16","_unc","werfen"," \u043B\u043E\u043C"," \u043F\u043E\u043A\u0443\u043F\u0430\u0442\u0435\u043B\u0435\u0439"," \u0433\u043B\u0430\u0437\u0430\u043C\u0438"," \u05D1\u05E2\u05D5\u05D3"," nanot"," ws"," \u043A\u0435\u0437\u0434\u0435\u0441","):("," Produit","Aircraft","iffen"," patrones"," par\xE2metros","Cursos"," cocos"];var bpe=c0.concat(c1);c0.length=0;c1.length=0;var o200k_base_default=bpe;var ALL_SPECIAL_TOKENS="all";var DEFAULT_MERGE_CACHE_SIZE=1e5;var isAscii=codePoint=>codePoint<=127;var HIGH_SURROGATE_START=55296;var HIGH_SURROGATE_END=56319;function endsWithIncompleteUtfPairSurrogate(string5){if(string5.length===0)return false;const lastCharCode=string5.charCodeAt(string5.length-1);return lastCharCode>=HIGH_SURROGATE_START&&lastCharCode<=HIGH_SURROGATE_END}function isValidUTF8(bytes){let i=0;while(i<bytes.length){const byte1=bytes[i];let numBytes=0;let codePoint=0;if(byte1<=127){numBytes=1;codePoint=byte1}else if((byte1&224)===192){numBytes=2;codePoint=byte1&31;if(byte1<=193)return false}else if((byte1&240)===224){numBytes=3;codePoint=byte1&15}else if((byte1&248)===240){numBytes=4;codePoint=byte1&7;if(byte1>244)return false}else{return false}if(i+numBytes>bytes.length)return false;for(let j=1;j<numBytes;j++){const byte=bytes[i+j];if(byte===void 0||(byte&192)!==128)return false;codePoint=codePoint<<6|byte&63}if(numBytes===2&&codePoint<128)return false;if(numBytes===3&&codePoint<2048)return false;if(numBytes===4&&codePoint<65536)return false;if(codePoint>=55296&&codePoint<=57343)return false;if(codePoint>1114111)return false;i+=numBytes}return true}var textDecoder=new TextDecoder("utf8",{fatal:false});function tryConvertToString(arr){if(!isValidUTF8(arr)){return void 0}return textDecoder.decode(arr)}function compareUint8Arrays(a,b){const len=Math.min(a.length,b.length);for(let i=0;i<len;i++){if(a[i]!==b[i]){return a[i]-b[i]}}return a.length-b.length}function getMaxValueFromMap(map2){let max=0;map2.forEach(val=>{max=Math.max(max,val)});return max}function escapeRegExp2(string5){return string5.replace(/[$()*+.?[\\\]^{|}]/g,"\\$&")}function getSpecialTokenRegex(tokens2){const escapedTokens=[...tokens2].map(escapeRegExp2);const inner=escapedTokens.join("|");return new RegExp(`(${inner})`)}var emptyBuffer=new Uint8Array(0);var decoder=new TextDecoder("utf8");var BytePairEncodingCore=class{mergeableBytePairRankCount;bytePairRankDecoder;bytePairNonUtfRankDecoder=new Map;bytePairNonUtfSortedEncoder;bytePairStringRankEncoder;tokenSplitRegex;specialTokensEncoder;specialTokensDecoder;specialTokenPatternRegex;textEncoder=new TextEncoder;mergeCache;mergeCacheSize;constructor({bytePairRankDecoder,specialTokensEncoder,tokenSplitRegex,mergeCacheSize=DEFAULT_MERGE_CACHE_SIZE}){this.bytePairRankDecoder=bytePairRankDecoder;this.bytePairStringRankEncoder=new Map;this.mergeCacheSize=mergeCacheSize;if(mergeCacheSize>0){this.mergeCache=new Map}this.mergeableBytePairRankCount=Object.keys(bytePairRankDecoder).length;const binaryLookup=[];bytePairRankDecoder.forEach((value,rank)=>{if(typeof value==="string"){this.bytePairStringRankEncoder.set(value,rank);return}const byteArray=new Uint8Array(value);binaryLookup.push([byteArray,rank]);this.bytePairNonUtfRankDecoder.set(rank,byteArray)});this.bytePairNonUtfSortedEncoder=binaryLookup.sort((a,b)=>compareUint8Arrays(a[0],b[0]));this.specialTokensEncoder=specialTokensEncoder??new Map;this.specialTokensDecoder=specialTokensEncoder?new Map([...specialTokensEncoder].map(([key,value])=>[value,key])):new Map;this.tokenSplitRegex=tokenSplitRegex;const escapedSpecialTokens=[...this.specialTokensEncoder.keys()].map(escapeRegExp2);const allSpecialTokensRegex=escapedSpecialTokens.join("|");try{this.specialTokenPatternRegex=new RegExp(allSpecialTokensRegex,"y")}catch{throw new Error("Invalid regular expression pattern.")}}setMergeCacheSize(newSize){if(this.mergeCacheSize===0&&newSize>0){this.mergeCache=new Map}this.mergeCacheSize=newSize;if(newSize===0){this.mergeCache=void 0}}clearMergeCache(){this.mergeCache?.clear()}*encodeNativeGenerator(text,allowedSpecial){let startIndex=0;let lastTokenLength=0;while(true){const nextSpecialMatch=this.findNextSpecialToken(text,allowedSpecial,startIndex);const nextSpecialStartIndex=nextSpecialMatch?.[0];const endIndex=nextSpecialStartIndex??text.length;const textBeforeSpecial=startIndex===0&&endIndex===text.length?text:text.slice(startIndex,endIndex);for(const[match]of textBeforeSpecial.matchAll(this.tokenSplitRegex)){const token2=this.getBpeRankFromString(match);if(token2!==void 0){lastTokenLength=1;yield[token2];continue}const tokens2=this.bytePairEncode(match);lastTokenLength=tokens2.length;yield tokens2}if(nextSpecialStartIndex!==void 0){const specialToken=nextSpecialMatch[1];const specialTokenValue=this.specialTokensEncoder.get(specialToken);if(specialTokenValue===void 0){throw new Error(`Special token "${specialToken}" is not in the special token encoder.`)}yield[specialTokenValue];startIndex=nextSpecialStartIndex+specialToken.length;lastTokenLength=1}else{break}}return lastTokenLength}encodeNative(text,allowedSpecial){let startIndex=0;const tokensArray=[];while(true){const nextSpecialMatch=this.findNextSpecialToken(text,allowedSpecial,startIndex);const nextSpecialStartIndex=nextSpecialMatch?.[0];const endIndex=nextSpecialStartIndex??text.length;const textBeforeSpecial=startIndex===0&&endIndex===text.length?text:text.slice(startIndex,endIndex);for(const[match]of textBeforeSpecial.matchAll(this.tokenSplitRegex)){const token2=this.getBpeRankFromString(match);if(token2!==void 0){tokensArray.push(token2);continue}const tokens2=this.bytePairEncode(match);tokensArray.push(...tokens2)}if(nextSpecialStartIndex!==void 0){const specialToken=nextSpecialMatch[1];const specialTokenValue=this.specialTokensEncoder.get(specialToken);if(specialTokenValue===void 0){throw new Error(`Special token "${specialToken}" is not in the special token encoder.`)}tokensArray.push(specialTokenValue);startIndex=nextSpecialStartIndex+specialToken.length}else{break}}return tokensArray}countNative(text,allowedSpecial){let startIndex=0;let tokensCount=0;while(true){const nextSpecialMatch=this.findNextSpecialToken(text,allowedSpecial,startIndex);const nextSpecialStartIndex=nextSpecialMatch?.[0];const endIndex=nextSpecialStartIndex??text.length;const textBeforeSpecial=startIndex===0&&endIndex===text.length?text:text.slice(startIndex,endIndex);for(const[match]of textBeforeSpecial.matchAll(this.tokenSplitRegex)){const token2=this.getBpeRankFromString(match);if(token2!==void 0){tokensCount++;continue}const tokens2=this.bytePairEncode(match);tokensCount+=tokens2.length}if(nextSpecialStartIndex!==void 0){const specialToken=nextSpecialMatch[1];const specialTokenValue=this.specialTokensEncoder.get(specialToken);if(specialTokenValue===void 0){throw new Error(`Special token "${specialToken}" is not in the special token encoder.`)}tokensCount++;startIndex=nextSpecialStartIndex+specialToken.length}else{break}}return tokensCount}*decodeNativeGenerator(tokens2){for(const token2 of tokens2){const tokenBytes=this.tryDecodeToken(token2);if(tokenBytes){yield tokenBytes}}}decodeNative(tokens2){let decoded="";let intBuffer=emptyBuffer;for(const token2 of tokens2){const tokenBytes=this.tryDecodeToken(token2);if(tokenBytes===void 0){throw new Error(`Token ${token2} is not in the byte pair encoder.`)}if(typeof tokenBytes==="string"){if(intBuffer!==emptyBuffer){decoded+=decoder.decode(intBuffer,{stream:true});intBuffer=emptyBuffer}decoded+=tokenBytes}else{const newBuffer=new Uint8Array(intBuffer.length+tokenBytes.length);newBuffer.set(intBuffer);newBuffer.set(tokenBytes,intBuffer.length);intBuffer=newBuffer}}if(intBuffer!==emptyBuffer){decoded+=decoder.decode(intBuffer,{stream:true})}return decoded}async*decodeNativeAsyncIterable(tokens2){for await(const token2 of tokens2){const tokenBytesOrString=this.tryDecodeToken(token2);if(tokenBytesOrString){yield tokenBytesOrString}}}getBpeRankFromString(key){return this.bytePairStringRankEncoder.get(key)}getBpeRankFromStringOrThrow(key){const value=this.getBpeRankFromString(key);if(value===void 0){throw new Error(`The byte-pair encoding does not contain a value for: ${key}`)}return value}getBpeRankFromBytes(key){const keyAsString=tryConvertToString(key);if(keyAsString!==void 0){return this.getBpeRankFromString(keyAsString)}const index=this.binarySearch(key);if(index!==-1){return this.bytePairNonUtfSortedEncoder[index][1]}return void 0}getBpeRankFromBytesOrThrow(key){const value=this.getBpeRankFromBytes(key);if(value===void 0){throw new Error(`The byte-pair encoding does not contain a value for: ${key.toString()}`)}return value}binarySearch(key){let low=0;let high=this.bytePairNonUtfSortedEncoder.length-1;while(low<=high){const mid=low+high>>>1;const midKey=this.bytePairNonUtfSortedEncoder[mid][0];let cmp=0;const maxLength=Math.min(midKey.length,key.length);for(let i=0;i<maxLength;i++){cmp=midKey[i]-key[i];if(cmp!==0)break}if(cmp===0){cmp=midKey.length-key.length}if(cmp===0){return mid}if(cmp<0){low=mid+1}else{high=mid-1}}return-1}findNextSpecialToken(text,allowedSpecial,startIndex){let searchIndex=startIndex;while(true){this.specialTokenPatternRegex.lastIndex=searchIndex;const nextSpecialMatch=this.specialTokenPatternRegex.exec(text);if(!nextSpecialMatch){return void 0}const specialToken=nextSpecialMatch[0];if(allowedSpecial?.has(specialToken)){const specialTokenStartIndex=nextSpecialMatch.index+searchIndex;return[specialTokenStartIndex,specialToken]}searchIndex=nextSpecialMatch.index+searchIndex+1}}tryDecodeToken(tokenRank){const value=this.bytePairRankDecoder[tokenRank];if(typeof value==="string"){return value}if(typeof value==="object"){const fromBinary=this.bytePairNonUtfRankDecoder.get(tokenRank);if(fromBinary){return fromBinary}}return this.specialTokensDecoder.get(tokenRank)}addToMergeCache(key,value){if(!this.mergeCache)return;if(this.mergeCache.size>=this.mergeCacheSize){const firstKey=this.mergeCache.keys().next().value;this.mergeCache.delete(firstKey)}this.mergeCache.set(key,value)}bytePairEncode(input){if(input.length===1&&isAscii(input.codePointAt(0))){return[this.getBpeRankFromStringOrThrow(input)]}if(this.mergeCache?.has(input)){const result3=this.mergeCache.get(input);this.mergeCache.delete(input);this.mergeCache.set(input,result3);return result3}const inputBytes=this.textEncoder.encode(input);const result2=this.bytePairMerge(inputBytes);this.addToMergeCache(input,result2);return result2}bytePairMerge(piece){const starts=[];const ranks=[];const getRank=(startIndex,pairStart=starts[startIndex],pairEnd=starts[startIndex+2])=>{if(pairEnd===void 0){return Number.POSITIVE_INFINITY}const key=piece.subarray(pairStart,pairEnd);const rank=this.getBpeRankFromBytes(key);return rank??Number.POSITIVE_INFINITY};for(let i=0;i<=piece.length;i++){starts.push(i);if(i<piece.length-1){ranks.push(getRank(i,i,i+2))}else{ranks.push(Number.POSITIVE_INFINITY)}}while(starts.length>1){let lowestRank=Number.POSITIVE_INFINITY;let lowestPartitionIndex=-1;for(let i=0;i<ranks.length-1;i++){const rank=ranks[i];if(rank<lowestRank){lowestRank=rank;lowestPartitionIndex=i}}if(lowestRank===Number.POSITIVE_INFINITY||lowestPartitionIndex===-1){break}starts.splice(lowestPartitionIndex+1,1);ranks.splice(lowestPartitionIndex,1);ranks[lowestPartitionIndex]=getRank(lowestPartitionIndex);if(lowestPartitionIndex>0){ranks[lowestPartitionIndex-1]=getRank(lowestPartitionIndex-1)}}const output2=[];for(let i=0;i<starts.length-1;i++){const pairStart=starts[i];const pairEnd=starts[i+1];const bpeValue=this.getBpeRankFromBytesOrThrow(piece.subarray(pairStart,pairEnd));output2.push(bpeValue)}return output2}};var MESSAGE_TOKEN_OVERHEAD=3;var MESSAGE_NAME_TOKEN_OVERHEAD=1;var FUNCTION_ROLE_TOKEN_DISCOUNT=2;var FUNCTION_CALL_METADATA_TOKEN_OVERHEAD=3;var FUNCTION_DEFINITION_TOKEN_OVERHEAD=9;var COMPLETION_REQUEST_TOKEN_OVERHEAD=3;var FUNCTION_CALL_NAME_TOKEN_OVERHEAD=4;var FUNCTION_CALL_NONE_TOKEN_OVERHEAD=1;var SYSTEM_FUNCTION_TOKEN_DEDUCTION=4;var NEWLINE="\n";function countMessageTokens(message,countStringTokens){let tokens2=0;if(message.role){tokens2+=countStringTokens(message.role)}if(message.content){tokens2+=countStringTokens(message.content)}if(message.name){tokens2+=countStringTokens(message.name)+MESSAGE_NAME_TOKEN_OVERHEAD}if(message.function_call){const{name,arguments:args}=message.function_call;if(name){tokens2+=countStringTokens(name)}if(args){tokens2+=countStringTokens(args)}tokens2+=FUNCTION_CALL_METADATA_TOKEN_OVERHEAD}tokens2+=MESSAGE_TOKEN_OVERHEAD;if(message.role==="function"){tokens2-=FUNCTION_ROLE_TOKEN_DISCOUNT}return tokens2}function formatObjectProperties(obj,indent,formatType){if(!obj.properties){return""}const lines=[];const requiredParams=new Set(obj.required??[]);const indentString=" ".repeat(indent);for(const[name,param]of Object.entries(obj.properties)){if(param.description&&indent<2){lines.push(`${indentString}// ${param.description}`)}const isRequired=requiredParams.has(name);const formattedType=formatType(param,indent);lines.push(`${indentString}${name}${isRequired?"":"?"}: ${formattedType},`)}return lines.join("\n")}function formatFunctionType(param,indent){switch(param.type){case"string":return param.enum?.map(value=>JSON.stringify(value)).join(" | ")??"string";case"integer":case"number":return param.enum?.map(value=>`${value}`).join(" | ")??"number";case"boolean":return"boolean";case"null":return"null";case"array":return param.items?`${formatFunctionType(param.items,indent)}[]`:"any[]";case"object":{const inner=formatObjectProperties(param,indent+2,formatFunctionType);const closingIndent=" ".repeat(indent);return`{
|
|
2014
2014
|
${inner}
|
|
2015
2015
|
${closingIndent}}`}default:return"any"}}function formatFunctionDefinitions(functions){const lines=["namespace functions {",""];for(const fn of functions){if(fn.description){lines.push(`// ${fn.description}`)}const{parameters}=fn;const properties=parameters?.properties;if(!parameters||!properties||Object.keys(properties).length===0){lines.push(`type ${fn.name} = () => any;`)}else{lines.push(`type ${fn.name} = (_: {`);const formattedProperties=formatObjectProperties(parameters,0,formatFunctionType);if(formattedProperties.length>0){lines.push(formattedProperties)}lines.push("}) => any;")}lines.push("")}lines.push("} // namespace functions");return lines.join("\n")}function estimateTokensInFunctions(functions,countStringTokens){const formatted=formatFunctionDefinitions(functions);let tokens2=countStringTokens(formatted);tokens2+=FUNCTION_DEFINITION_TOKEN_OVERHEAD;return tokens2}function padSystemMessage(message,hasFunctions,isSystemPadded){if(!hasFunctions||isSystemPadded||message.role!=="system"){return message}if(!message.content||message.content.endsWith(NEWLINE)){return message}return{...message,content:`${message.content}${NEWLINE}`}}function computeChatCompletionTokenCount(request,countStringTokens){const{messages,functions,function_call:functionCall}=request;const hasFunctions=Boolean(functions&&functions.length>0);let paddedSystem=false;let total=0;for(const message of messages){const messageToCount=padSystemMessage(message,hasFunctions,paddedSystem);if(messageToCount!==message&&message.role==="system"){paddedSystem=true}else if(message.role==="system"&&hasFunctions&&!paddedSystem){paddedSystem=true}total+=countMessageTokens(messageToCount,countStringTokens)}total+=COMPLETION_REQUEST_TOKEN_OVERHEAD;if(hasFunctions&&functions){total+=estimateTokensInFunctions(functions,countStringTokens);if(messages.some(message=>message.role==="system")){total-=SYSTEM_FUNCTION_TOKEN_DEDUCTION}}if(functionCall&&functionCall!=="auto"){if(functionCall==="none"){total+=FUNCTION_CALL_NONE_TOKEN_OVERHEAD}else if(typeof functionCall==="object"&&functionCall.name){total+=countStringTokens(functionCall.name)+FUNCTION_CALL_NAME_TOKEN_OVERHEAD}}return total}var chatEnabledModels=["chatgpt-4o-latest","codex-mini-latest","computer-use-preview","computer-use-preview-2025-03-11","gpt-3.5","gpt-3.5-0301","gpt-3.5-turbo","gpt-3.5-turbo-0125","gpt-3.5-turbo-0613","gpt-3.5-turbo-1106","gpt-3.5-turbo-16k-0613","gpt-3.5-turbo-instruct","gpt-4","gpt-4-0125-preview","gpt-4-0314","gpt-4-0613","gpt-4-1106-preview","gpt-4-1106-vision-preview","gpt-4-32k","gpt-4-turbo","gpt-4-turbo-2024-04-09","gpt-4-turbo-preview","gpt-4.1","gpt-4.1-2025-04-14","gpt-4.1-mini","gpt-4.1-mini-2025-04-14","gpt-4.1-nano","gpt-4.1-nano-2025-04-14","gpt-4.5-preview","gpt-4.5-preview-2025-02-27","gpt-4o","gpt-4o-2024-05-13","gpt-4o-2024-08-06","gpt-4o-2024-11-20","gpt-4o-audio-preview","gpt-4o-audio-preview-2024-10-01","gpt-4o-audio-preview-2024-12-17","gpt-4o-audio-preview-2025-06-03","gpt-4o-mini","gpt-4o-mini-2024-07-18","gpt-4o-mini-audio-preview","gpt-4o-mini-audio-preview-2024-12-17","gpt-4o-mini-search-preview","gpt-4o-mini-search-preview-2025-03-11","gpt-4o-search-preview","gpt-4o-search-preview-2025-03-11","gpt-5","gpt-5-2025-08-07","gpt-5-chat-latest","gpt-5-codex","gpt-5-mini","gpt-5-mini-2025-08-07","gpt-5-nano","gpt-5-nano-2025-08-07","gpt-5-pro","gpt-5-pro-2025-10-06","gpt-audio","gpt-audio-2025-08-28","gpt-audio-mini","gpt-audio-mini-2025-10-06","gpt-oss-120b","gpt-oss-20b","o1","o1-2024-12-17","o1-mini","o1-mini-2024-09-12","o1-preview","o1-preview-2024-09-12","o1-pro","o1-pro-2025-03-19","o3","o3-2025-04-16","o3-deep-research","o3-deep-research-2025-06-26","o3-mini","o3-mini-2025-01-31","o3-pro","o3-pro-2025-06-10","o4-mini","o4-mini-2025-04-16","o4-mini-deep-research","o4-mini-deep-research-2025-06-26"];var modelsMap_exports={};__export(modelsMap_exports,{cl100k_base:()=>cl100k_base,o200k_base:()=>o200k_base,o200k_harmony:()=>o200k_harmony,p50k_base:()=>p50k_base,p50k_edit:()=>p50k_edit,r50k_base:()=>r50k_base});var p50k_base=["text-davinci-002","text-davinci-003","code-davinci-001","code-davinci-002","davinci-codex","code-cushman-001","code-cushman-002","cushman-codex"];var r50k_base=["text-ada-001","text-babbage-001","text-curie-001","text-davinci-001","ada","babbage","curie","davinci","code-search-ada-code-001","code-search-ada-text-001","text-similarity-ada-001","text-search-ada-doc-001","text-search-ada-query-001","text-similarity-babbage-001","text-search-babbage-doc-001","text-search-babbage-query-001","code-search-babbage-code-001","code-search-babbage-text-001","text-similarity-curie-001","text-search-curie-doc-001","text-search-curie-query-001","text-similarity-davinci-001","text-search-davinci-doc-001","text-search-davinci-query-001"];var p50k_edit=["code-davinci-edit-001","text-davinci-edit-001"];var cl100k_base=["gpt-3.5","gpt-3.5-0301","gpt-3.5-turbo","gpt-3.5-turbo-0125","gpt-3.5-turbo-0613","gpt-3.5-turbo-1106","gpt-3.5-turbo-16k-0613","gpt-3.5-turbo-instruct","gpt-4","gpt-4-0125-preview","gpt-4-0314","gpt-4-0613","gpt-4-1106-preview","gpt-4-1106-vision-preview","gpt-4-32k","gpt-4-turbo","gpt-4-turbo-2024-04-09","gpt-4-turbo-preview","text-embedding-3-large","text-embedding-3-small","text-embedding-ada-002","babbage-002","davinci-002"];var o200k_base=[];var o200k_harmony=["gpt-oss-20b","gpt-oss-120b"];var EndOfText="<|endoftext|>";var FimPrefix="<|fim_prefix|>";var FimMiddle="<|fim_middle|>";var FimSuffix="<|fim_suffix|>";var ImStart="<|im_start|>";var ImEnd="<|im_end|>";var ImSep="<|im_sep|>";var EndOfPrompt="<|endofprompt|>";var HarmonyStartOfText="<|startoftext|>";var HarmonyStart="<|start|>";var HarmonyEnd="<|end|>";var HarmonyMessage="<|message|>";var HarmonyChannel="<|channel|>";var HarmonyReturn="<|return|>";var HarmonyConstrain="<|constrain|>";var HarmonyCall="<|call|>";var o200k_base2="o200k_base";var DEFAULT_ENCODING=o200k_base2;var modelToEncodingMap=Object.fromEntries(Object.entries(modelsMap_exports).flatMap(([encodingName,models])=>models.map(modelName=>[modelName,encodingName])));var gpt3params={messageSeparator:"\n",roleSeparator:"\n"};var gpt4params={messageSeparator:"",roleSeparator:ImSep};var chatModelParams=Object.fromEntries(chatEnabledModels.flatMap(modelName=>modelName.startsWith("gpt-3.5")?[[modelName,gpt3params]]:[[modelName,gpt4params]]));var R50K_TOKEN_SPLIT_REGEX=new RegExp("'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+","gu");var CONTRACTION_SUFFIX_PATTERN=String.raw`'(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])`;var OPTIONAL_CONTRACTION_SUFFIX=String.raw`(?:${CONTRACTION_SUFFIX_PATTERN})?`;var CL100K_TOKEN_SPLIT_PATTERN=String.raw`${CONTRACTION_SUFFIX_PATTERN}|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s+$|\s*[\r\n]|\s+(?!\S)|\s`;var CL100K_TOKEN_SPLIT_REGEX=new RegExp(CL100K_TOKEN_SPLIT_PATTERN,"gu");var O200K_TOKEN_SPLIT_PATTERN=String.raw`[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]*[\p{Ll}\p{Lm}\p{Lo}\p{M}]+${OPTIONAL_CONTRACTION_SUFFIX}|[^\r\n\p{L}\p{N}]?[\p{Lu}\p{Lt}\p{Lm}\p{Lo}\p{M}]+[\p{Ll}\p{Lm}\p{Lo}\p{M}]*${OPTIONAL_CONTRACTION_SUFFIX}|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n/]*|\s*[\r\n]+|\s+(?!\S)|\s+`;var O200K_TOKEN_SPLIT_REGEX=new RegExp(O200K_TOKEN_SPLIT_PATTERN,"gu");function Cl100KBase(bytePairRankDecoder){const specialTokenMapping=new Map([[EndOfText,100257],[FimPrefix,100258],[FimMiddle,100259],[FimSuffix,100260],[ImStart,100264],[ImEnd,100265],[ImSep,100266],[EndOfPrompt,100276]]);return{tokenSplitRegex:CL100K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder:specialTokenMapping}}var O200K_BASE_SPECIAL_TOKEN_ENTRIES=[[EndOfText,199999],[FimPrefix,2e5],[FimMiddle,200001],[FimSuffix,200002],[ImStart,200003],[ImEnd,200004],[ImSep,200005],[EndOfPrompt,200006]];var createO200KSpecialTokenMap=()=>new Map(O200K_BASE_SPECIAL_TOKEN_ENTRIES);function O200KBase(bytePairRankDecoder){return{tokenSplitRegex:O200K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder:createO200KSpecialTokenMap()}}var RESERVED_TOKEN_RANGE_START=200013;var RESERVED_TOKEN_RANGE_END=201088;var STATIC_SPECIAL_TOKEN_ENTRIES=[[HarmonyStartOfText,199998],[EndOfText,199999],["<|reserved_200000|>",2e5],["<|reserved_200001|>",200001],[HarmonyReturn,200002],[HarmonyConstrain,200003],["<|reserved_200004|>",200004],[HarmonyChannel,200005],[HarmonyStart,200006],[HarmonyEnd,200007],[HarmonyMessage,200008],["<|reserved_200009|>",200009],["<|reserved_200010|>",200010],["<|reserved_200011|>",200011],[HarmonyCall,200012]];function O200KHarmony(bytePairRankDecoder){const specialTokensEncoder=new Map(STATIC_SPECIAL_TOKEN_ENTRIES);for(let tokenId=RESERVED_TOKEN_RANGE_START;tokenId<RESERVED_TOKEN_RANGE_END;tokenId+=1){specialTokensEncoder.set(`<|reserved_${tokenId}|>`,tokenId)}specialTokensEncoder.set(EndOfPrompt,200018);return{tokenSplitRegex:O200K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder,chatFormatter:"harmony"}}function P50KBase(bytePairRankDecoder){return{expectedVocabularySize:50281,tokenSplitRegex:R50K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder:new Map([[EndOfText,50256]])}}function P50KEdit(bytePairRankDecoder){const specialTokenMapping=new Map([[EndOfText,50256],[FimPrefix,50281],[FimMiddle,50282],[FimSuffix,50283]]);return{tokenSplitRegex:R50K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder:specialTokenMapping}}function R50KBase(bytePairRankDecoder){return{expectedVocabularySize:50257,tokenSplitRegex:R50K_TOKEN_SPLIT_REGEX,bytePairRankDecoder,specialTokensEncoder:new Map([[EndOfText,50256]])}}function getEncodingParams(encodingName,getMergeableRanks){const mergeableBytePairRanks=getMergeableRanks(encodingName);switch(encodingName.toLowerCase()){case"r50k_base":return R50KBase(mergeableBytePairRanks);case"p50k_base":return P50KBase(mergeableBytePairRanks);case"p50k_edit":return P50KEdit(mergeableBytePairRanks);case"cl100k_base":return Cl100KBase(mergeableBytePairRanks);case"o200k_base":return O200KBase(mergeableBytePairRanks);case"o200k_harmony":return O200KHarmony(mergeableBytePairRanks);default:throw new Error(`Unknown encoding name: ${encodingName}`)}}var GptEncoding=class _GptEncoding{static EndOfPrompt=EndOfPrompt;static EndOfText=EndOfText;static FimMiddle=FimMiddle;static FimPrefix=FimPrefix;static FimSuffix=FimSuffix;modelName;modelSpec;bytePairEncodingCoreProcessor;specialTokensEncoder;specialTokensSet;allSpecialTokenRegex;defaultSpecialTokenConfig;chatFormatter;countChatCompletionTokens;vocabularySize;constructor({bytePairRankDecoder:mergeableBytePairRanks,specialTokensEncoder,expectedVocabularySize,modelName,modelSpec,chatFormatter,...rest}){this.specialTokensEncoder=specialTokensEncoder;this.specialTokensSet=new Set(this.specialTokensEncoder.keys());this.allSpecialTokenRegex=getSpecialTokenRegex(this.specialTokensSet);this.bytePairEncodingCoreProcessor=new BytePairEncodingCore({bytePairRankDecoder:mergeableBytePairRanks,specialTokensEncoder,...rest});this.defaultSpecialTokenConfig=this.processSpecialTokens();const maxTokenValue=Math.max(mergeableBytePairRanks.length-1,getMaxValueFromMap(specialTokensEncoder));this.vocabularySize=this.bytePairEncodingCoreProcessor.mergeableBytePairRankCount+specialTokensEncoder.size;if(expectedVocabularySize!==void 0){if(this.vocabularySize!==expectedVocabularySize){throw new Error("The number of mergeable tokens and special tokens must be equal to expectedVocabularySize.")}if(maxTokenValue!==expectedVocabularySize-1){throw new Error(`The model encodings are invalid. The maximum token value must be equal to expectedVocabularySize - 1. Currently ${maxTokenValue}, expected ${expectedVocabularySize-1}`)}}this.encode=this.encode.bind(this);this.decode=this.decode.bind(this);this.encodeGenerator=this.encodeGenerator.bind(this);this.decodeGenerator=this.decodeGenerator.bind(this);this.decodeAsyncGenerator=this.decodeAsyncGenerator.bind(this);this.decodeAsync=this.decodeAsync.bind(this);this.isWithinTokenLimit=this.isWithinTokenLimit.bind(this);this.encodeChat=this.encodeChat.bind(this);this.encodeChatGenerator=this.encodeChatGenerator.bind(this);this.countTokens=this.countTokens.bind(this);this.setMergeCacheSize=this.setMergeCacheSize.bind(this);this.clearMergeCache=this.clearMergeCache.bind(this);this.estimateCost=this.estimateCost.bind(this);if(modelSpec?.supported_features?.includes("function_calling")){this.countChatCompletionTokens=this.countChatCompletionTokensInternal.bind(this)}this.modelName=modelName;this.modelSpec=modelSpec;this.chatFormatter=chatFormatter??"chatml"}*encodeHarmonyChatGenerator(chat,encodeOptions){const harmonyStart=this.specialTokensEncoder.get(HarmonyStart);const harmonyMessage=this.specialTokensEncoder.get(HarmonyMessage);const harmonyEnd=this.specialTokensEncoder.get(HarmonyEnd);const harmonyReturn=this.specialTokensEncoder.get(HarmonyReturn);const harmonyCall=this.specialTokensEncoder.get(HarmonyCall);const harmonyChannel=this.specialTokensEncoder.get(HarmonyChannel);const harmonyConstrain=this.specialTokensEncoder.get(HarmonyConstrain);if(harmonyStart===void 0||harmonyMessage===void 0||harmonyEnd===void 0||harmonyReturn===void 0||harmonyCall===void 0||harmonyChannel===void 0||harmonyConstrain===void 0){throw new Error("Harmony chat format requires dedicated special tokens.")}const encodeHeaderText=text=>text.length>0?this.encode(text):[];const resolveTerminatorToken=terminator=>{switch(terminator){case"<|return|>":return harmonyReturn;case"<|call|>":return harmonyCall;case"<|end|>":default:return harmonyEnd}};for(const message of chat){if(message.content===void 0){throw new Error("Content must be defined for all messages.")}const roleOrName=message.name??message.role??"user";yield[harmonyStart];yield encodeHeaderText(roleOrName);const recipientInRole=message.recipient&&(message.recipientPlacement==="role"||!message.channel);const recipientInChannel=message.recipient&&!recipientInRole;if(recipientInRole){yield encodeHeaderText(` to=${message.recipient}`)}if(message.channel){yield[harmonyChannel];yield encodeHeaderText(message.channel);if(recipientInChannel){yield encodeHeaderText(` to=${message.recipient}`)}}if(message.constraint){yield[harmonyConstrain];yield encodeHeaderText(message.constraint)}yield[harmonyMessage];yield*this.encodeGenerator(message.content,encodeOptions);yield[resolveTerminatorToken(message.terminator)]}const assistantPrime=encodeOptions?.primeWithAssistantResponse??"assistant";if(assistantPrime.length>0){yield[harmonyStart];yield encodeHeaderText(assistantPrime)}}static getEncodingApi(encodingName,getMergeableRanks){const modelParams=getEncodingParams(encodingName,getMergeableRanks);return new _GptEncoding(modelParams)}static getEncodingApiForModel(modelName,getMergeableRanks,modelSpec){const encodingName=modelToEncodingMap[modelName]??DEFAULT_ENCODING;const modelParams=getEncodingParams(encodingName,getMergeableRanks);return new _GptEncoding({...modelParams,modelName,modelSpec})}processSpecialTokens({allowedSpecial,disallowedSpecial}={}){let regexPattern;if(allowedSpecial===ALL_SPECIAL_TOKENS||allowedSpecial?.has(ALL_SPECIAL_TOKENS)){allowedSpecial=new Set(this.specialTokensSet);const allowedSpecialSet=allowedSpecial;if(disallowedSpecial===ALL_SPECIAL_TOKENS){throw new Error('allowedSpecial and disallowedSpecial cannot both be set to "all".')}if(typeof disallowedSpecial==="object"){disallowedSpecial.forEach(val=>allowedSpecialSet.delete(val))}else{disallowedSpecial=new Set}}if(!disallowedSpecial||disallowedSpecial===ALL_SPECIAL_TOKENS||disallowedSpecial.has(ALL_SPECIAL_TOKENS)){disallowedSpecial=new Set(this.specialTokensSet);const disallowedSpecialSet=disallowedSpecial;if(allowedSpecial?.size){allowedSpecial.forEach(val=>disallowedSpecialSet.delete(val));disallowedSpecial.forEach(val=>allowedSpecial.delete(val));if(disallowedSpecial.size>0){regexPattern=getSpecialTokenRegex(disallowedSpecial)}}else{regexPattern=this.allSpecialTokenRegex}}return{allowedSpecial,regexPattern}}encodeGenerator(lineToEncode,encodeOptions){const specialTokenConfig=encodeOptions?this.processSpecialTokens(encodeOptions):this.defaultSpecialTokenConfig;if(specialTokenConfig.regexPattern){const match=lineToEncode.match(specialTokenConfig.regexPattern);if(match!==null){throw new Error(`Disallowed special token found: ${match[0]}`)}}return this.bytePairEncodingCoreProcessor.encodeNativeGenerator(lineToEncode,specialTokenConfig.allowedSpecial)}encode(lineToEncode,encodeOptions){const specialTokenConfig=encodeOptions?this.processSpecialTokens(encodeOptions):this.defaultSpecialTokenConfig;if(specialTokenConfig.regexPattern){const match=lineToEncode.match(specialTokenConfig.regexPattern);if(match!==null){throw new Error(`Disallowed special token found: ${match[0]}`)}}return this.bytePairEncodingCoreProcessor.encodeNative(lineToEncode,specialTokenConfig.allowedSpecial)}*encodeChatGenerator(chat,model=this.modelName,encodeOptions){if(!model){throw new Error("Model name must be provided either during initialization or passed in to the method.")}const params=chatModelParams[model];if(!params){throw new Error(`Model '${model}' does not support chat.`)}if(this.chatFormatter==="harmony"){yield*this.encodeHarmonyChatGenerator(chat,encodeOptions);return}const chatStartToken=this.specialTokensEncoder.get(ImStart);const chatEndToken=this.specialTokensEncoder.get(ImEnd);if(chatStartToken===void 0||chatEndToken===void 0){throw new Error(`Model '${model}' does not support chat.`)}const allowedSpecial=new Set([ImSep]);const{messageSeparator,roleSeparator}=params;const encodedMessageSeparator=messageSeparator.length>0?this.encode(messageSeparator):[];const encodedRoleSeparator=roleSeparator.length>0?this.encode(roleSeparator,{allowedSpecial}):[];const nameCache=new Map;for(const{role="system",name=role,content}of chat){if(content===void 0){throw new Error("Content must be defined for all messages.")}yield[chatStartToken];const encodedName=nameCache.get(name)??this.encode(name);nameCache.set(name,encodedName);yield encodedName;if(encodedRoleSeparator.length>0){yield encodedRoleSeparator}yield*this.encodeGenerator(content,encodeOptions);yield[chatEndToken];yield encodedMessageSeparator}const assistantPrime=encodeOptions?.primeWithAssistantResponse??"assistant";if(assistantPrime.length>0){yield[chatStartToken];yield*this.encodeGenerator(assistantPrime,encodeOptions)}if(encodedRoleSeparator.length>0){yield encodedRoleSeparator}}encodeChat(chat,model=this.modelName,encodeOptions){return[...this.encodeChatGenerator(chat,model,encodeOptions)].flat()}isWithinTokenLimit(input,tokenLimit,encodeOptions){const tokenGenerator=typeof input==="string"?this.encodeGenerator(input,encodeOptions):this.encodeChatGenerator(input,void 0,encodeOptions);let count=0;for(const tokens2 of tokenGenerator){count+=tokens2.length;if(count>tokenLimit){return false}}return count}countTokens(input,encodeOptions){if(typeof input==="string"){const specialTokenConfig=encodeOptions?this.processSpecialTokens(encodeOptions):this.defaultSpecialTokenConfig;if(specialTokenConfig.regexPattern){const match=input.match(specialTokenConfig.regexPattern);if(match!==null){throw new Error(`Disallowed special token found: ${match[0]}`)}}return this.bytePairEncodingCoreProcessor.countNative(input,specialTokenConfig.allowedSpecial)}const tokenGenerator=this.encodeChatGenerator(input,void 0,encodeOptions);let count=0;for(const tokens2 of tokenGenerator){count+=tokens2.length}return count}countStringTokens(text){if(!text){return 0}return this.bytePairEncodingCoreProcessor.countNative(text)}countChatCompletionTokensInternal(request){return computeChatCompletionTokenCount(request,text=>this.countStringTokens(text))}setMergeCacheSize(size){this.bytePairEncodingCoreProcessor.setMergeCacheSize(size)}clearMergeCache(){this.bytePairEncodingCoreProcessor.clearMergeCache()}decode(inputTokensToDecode){return this.bytePairEncodingCoreProcessor.decodeNative(inputTokensToDecode)}*decodeGenerator(inputTokensToDecode){const decodedByteGenerator=this.bytePairEncodingCoreProcessor.decodeNativeGenerator(inputTokensToDecode);let buffer="";for(const decodedPart of decodedByteGenerator){buffer+=typeof decodedPart==="string"?decodedPart:decoder.decode(decodedPart,{stream:true});if(buffer.length===0||endsWithIncompleteUtfPairSurrogate(buffer)){continue}else{yield buffer;buffer=""}}if(buffer.length>0){yield buffer}}async*decodeAsyncGenerator(inputTokensToDecode){const decodedByteGenerator=this.bytePairEncodingCoreProcessor.decodeNativeAsyncIterable(inputTokensToDecode);let buffer="";for await(const decodedPart of decodedByteGenerator){buffer+=typeof decodedPart==="string"?decodedPart:decoder.decode(decodedPart,{stream:true});if(buffer.length===0||endsWithIncompleteUtfPairSurrogate(buffer)){continue}else{yield buffer;buffer=""}}if(buffer.length>0){yield buffer}}async decodeAsync(inputTokensToDecode){const decodedByteGenerator=this.bytePairEncodingCoreProcessor.decodeNativeAsyncIterable(inputTokensToDecode);let buffer="";for await(const decodedPart of decodedByteGenerator){buffer+=typeof decodedPart==="string"?decodedPart:decoder.decode(decodedPart,{stream:true})}return buffer}estimateCost(tokenCount,modelSpec=this.modelSpec){if(!modelSpec){throw new Error("Model spec must be provided either during initialization or passed in to the method.")}if(!modelSpec.price_data){throw new Error(`No cost information available for model: ${modelSpec.name}`)}const priceDataPerMillion=modelSpec.price_data;const result2={};const millionTokens=tokenCount/1e6;if(priceDataPerMillion.main){result2.main={input:priceDataPerMillion.main.input&&priceDataPerMillion.main.input*millionTokens,output:priceDataPerMillion.main.output&&priceDataPerMillion.main.output*millionTokens,cached_input:priceDataPerMillion.main.cached_input&&priceDataPerMillion.main.cached_input*millionTokens,cached_output:priceDataPerMillion.main.cached_output&&priceDataPerMillion.main.cached_output*millionTokens}}if(priceDataPerMillion.batch){result2.batch={input:priceDataPerMillion.batch.input&&priceDataPerMillion.batch.input*millionTokens,output:priceDataPerMillion.batch.output&&priceDataPerMillion.batch.output*millionTokens,cached_input:priceDataPerMillion.batch.cached_input&&priceDataPerMillion.batch.cached_input*millionTokens,cached_output:priceDataPerMillion.batch.cached_output&&priceDataPerMillion.batch.cached_output*millionTokens}}return result2}};var api=GptEncoding.getEncodingApi("o200k_base",()=>o200k_base_default);var{decode:decode3,decodeAsyncGenerator,decodeGenerator,encode:encode3,encodeGenerator,isWithinTokenLimit,countTokens,encodeChat,encodeChatGenerator,vocabularySize,setMergeCacheSize,clearMergeCache,estimateCost}=api;function scanSecrets(path,content){const patterns=[["private-key",/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/],["aws-access-key",/\bAKIA[0-9A-Z]{16}\b/],["github-token",/\bgh[ps]_[A-Za-z0-9]{30,}\b/],["generic-secret",/(?:api[_-]?key|secret|token|password)\s*[:=]\s*["'][^"'\s]{12,}["']/i]];const findings=[];for(const[kind,pattern]of patterns){const match=content.match(pattern);if(match?.index!==void 0){findings.push({path,line:content.slice(0,match.index).split("\n").length,kind})}}return findings}var ContextPackBuildError=class extends Error{constructor(findings){super(`Context pack rejected: ${findings.map(finding3=>`${finding3.rule}:${finding3.path}`).join(", ")}`);this.findings=findings}findings;name="ContextPackBuildError"};function validateContextPack(pack){const findings=[];if(pack.estimatedTokens>pack.budget){findings.push({rule:"budget",path:"context-pack",message:"Token budget exceeded"})}const included=new Set(pack.items.map(item=>item.path));const criticalMissing=new Set(pack.diagnostics.filter(diagnostic=>diagnostic.code==="critical-missing").map(diagnostic=>diagnostic.path));for(const diagnostic of pack.diagnostics){if(diagnostic.code==="critical-missing"){findings.push({rule:"critical-missing",path:diagnostic.path,message:diagnostic.message})}}for(const reference of pack.unresolvedRequiredReferences){findings.push({rule:"required-reference-missing",path:reference,message:"Lifecycle Requirement or Acceptance Criterion does not resolve in the selected Requirements"})}for(const path of pack.requiredFiles){if(!included.has(path)&&!criticalMissing.has(path)){const omission=pack.omissions.find(candidate=>candidate.path===path);findings.push({rule:"critical-omitted",path,message:omission?.reason==="required-budget-exceeded"?"Required context does not fit the pack budget; increase the budget or reduce required context.":"Required context invariant was omitted"})}}for(const item of pack.items){for(const secret of scanSecrets(item.path,item.content)){findings.push({rule:"secret",path:item.path,message:`${secret.kind}:${secret.line}`})}}return findings}function assertNoSecrets(path,content){const findings=scanSecrets(path,content);if(findings.length>0){throw new ContextPackBuildError(findings.map(finding3=>({rule:"secret",path:finding3.path,message:`${finding3.kind}:${finding3.line}`})))}}var CONTEXT_ROLES=["orchestrator","builder","reviewer","integrator","auditor"];var CONTEXT_PHASES=["conversation","definition","planning","execution","verification","evidence"];function inferContextPhase(query){const normalized=query.replace(/\b(?:AC|REQ|RULE)-[A-Z0-9-]+\b/gi," ").toLowerCase();if(/(?<![A-Z0-9_-])(?:PRD|SPEC|CHG|TASK|EXEC|RUN)-[A-Z0-9-]+\b/i.test(query))return"execution";if(/^\s*(?:(?:por favor|please)[,\s]+)?(?:(?:pode|quero|preciso)\s+)?(?:crie|criar|create)\b/.test(normalized)){return"execution"}if(/\b(?:implement|implemente|implementar|c[oó]digo|code|codificar|corrija|corrigir|desenvolva|desenvolver)\b/.test(normalized)){return"execution"}if(/(?:^|\s)(?:[\w.-]+\/)+[\w.-]+\.[a-z0-9]+\b/i.test(query))return"definition";if(/\b(evidence|evidencia|evidencias|audit|auditoria)\b/.test(normalized))return"evidence";if(/\b(verify|verification|review|test|verificar|revisao|teste)\b/.test(normalized)){return"verification"}if(/\b(execute|execution|run|executar|execucao)\b/.test(normalized))return"execution";if(/\b(plan|planning|spec|planeje|planejar|planejamento)\b/.test(normalized))return"planning";return"conversation"}function contextProfileReason(path,role,phase2){const normalized=path.toLowerCase();const rolePatterns={orchestrator:/(?:project\.yaml|agents\/catalog|tasks|executions|specs|prds)/,builder:/(?:\/src\/|\.test\.|requirements|rules|task|change)/,reviewer:/(?:\.test\.|review|evidence|requirements|task|change)/,integrator:/(?:package\.json|lock|integration|e2e|execution|change)/,auditor:/(?:evidence|decision|run|audit|requirement|test|review)/};const phasePatterns={conversation:/^$/,definition:/(?:prd|requirement|project\.yaml)/,planning:/(?:spec|change|architecture|plan)/,execution:/(?:task|execution|\/src\/|command)/,verification:/(?:test|review|eval|check)/,evidence:/(?:evidence|decision|run|result|trace)/};const matchesRole=rolePatterns[role].test(normalized);const matchesPhase=phasePatterns[phase2].test(normalized);if(matchesRole&&matchesPhase)return`role:${role}+phase:${phase2}`;if(matchesRole)return`role:${role}`;if(matchesPhase)return`phase:${phase2}`;return null}init_src();function parseRuleMetadata(content){const raw=parseRuleDocument(content).metadata;return{id:raw.id,load:raw.load,globs:raw.globs,priority:raw.priority,maxContextTokens:raw.max_context_tokens,requires:raw.requires,triggers:raw.triggers,phases:raw.phases,domains:raw.domains}}function selectRulePaths(entries,targetPaths,query,phase2){const rules=entries.filter(entry2=>entry2.path.startsWith(".agents/rules/")&&entry2.path.endsWith(".md")).map(entry2=>({path:entry2.path,metadata:parseRuleMetadata(entry2.content)}));assertUniqueRuleIds(rules);assertRuleDependencies(rules);const selected=new Set;const requiredByPhase=phase2==="execution"?new Set(["RULE-WORKFLOW","RULE-RUN-LIFECYCLE-CLOSURE"]):phase2==="planning"?new Set(["RULE-WORKFLOW"]):new Set;const conversational=phase2==="conversation";const normalizedQuery=normalizeRuleText(query);for(const rule of rules){const metadata2=rule.metadata;const applies=matchesRuleId(metadata2.id,normalizedQuery)||metadata2.load==="always"||requiredByPhase.has(metadata2.id)||metadata2.load==="file_match"&&metadata2.globs.some(glob=>targetPaths.some(path=>globMatches(glob,path)))||metadata2.load==="auto"&&appliesRuleMetadata(metadata2,normalizedQuery,phase2,conversational);if(applies)selected.add(rule.path)}let changed=true;while(changed){changed=false;for(const rule of rules.filter(candidate=>selected.has(candidate.path))){for(const requirement of rule.metadata.requires){const required2=rules.find(candidate=>candidate.metadata.id===requirement);if(required2===void 0){throw new Error(`Rule ${rule.metadata.id} requires missing Rule ${requirement}`)}if(!selected.has(required2.path)){selected.add(required2.path);changed=true}}}}return[...selected].sort(comparePaths2)}function normalizeRuleText(value){return` ${value.toLowerCase().normalize("NFKD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g," ").trim()} `}function hasWholePhrase(query,phrase){const normalized=normalizeRuleText(phrase).trim();return normalized.length>0&&query.includes(` ${normalized} `)}function matchesRuleId(id,query){return hasWholePhrase(query,id)}function appliesRuleMetadata(metadata2,normalizedQuery,phase2,conversational){if(metadata2.phases.length>0&&(phase2===void 0||!metadata2.phases.includes(phase2))){return false}const domainMatches=metadata2.domains.length===0||metadata2.domains.some(domain2=>hasWholePhrase(normalizedQuery,domain2));if(metadata2.triggers.length>0){return domainMatches&&metadata2.triggers.some(trigger=>hasWholePhrase(normalizedQuery,trigger))}if(metadata2.domains.length>0)return domainMatches;return!conversational&&metadata2.id.replace(/^RULE-/,"").split("-").some(term=>term.length>3&&hasWholePhrase(normalizedQuery,term))}function assertUniqueRuleIds(rules){const pathsById=new Map;for(const rule of rules){const existing=pathsById.get(rule.metadata.id);if(existing!==void 0){throw new Error(`Duplicate Rule id ${rule.metadata.id}: ${existing}, ${rule.path}`)}pathsById.set(rule.metadata.id,rule.path)}}function assertRuleDependencies(rules){const byId2=new Map(rules.map(rule=>[rule.metadata.id,rule]));for(const rule of rules){for(const required2 of rule.metadata.requires){if(!byId2.has(required2))throw new Error(`Rule ${rule.metadata.id} requires missing Rule ${required2}`)}}const visiting=new Set;const visited=new Set;const visit=(id,trail)=>{if(visiting.has(id))throw new Error(`Rule prerequisite cycle: ${[...trail,id].join(" -> ")}`);if(visited.has(id))return;visiting.add(id);for(const required2 of byId2.get(id)?.metadata.requires??[])visit(required2,[...trail,id]);visiting.delete(id);visited.add(id)};for(const id of byId2.keys())visit(id,[])}function globMatches(glob,path){const expression=glob.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"__ZAIP_GLOBSTAR__").replace(/\*/g,"[^/]*").replace(/__ZAIP_GLOBSTAR__/g,".*");return new RegExp(`^${expression}$`).test(path)}function comparePaths2(left,right){if(left<right)return-1;if(left>right)return 1;return 0}init_src();import{createHash as createHash6}from"node:crypto";function contextRoleForAgent(agent){const value=agent.toLowerCase();if(/(?:finalizer|reviewer|verifier)/.test(value))return"reviewer";if(/(?:auditor|security)/.test(value))return"auditor";if(/(?:integrator)/.test(value))return"integrator";if(/(?:builder|backend|frontend|developer|executor)/.test(value))return"builder";return"orchestrator"}function projectConfigForContext(source,role,phase2){const value=parseYaml(source);const config2=value!==null&&typeof value==="object"?value:{};const record3=key=>{const candidate=config2[key];return candidate!==null&&typeof candidate==="object"?candidate:{}};const zaip=record3("zaip");const execution=record3("execution");const model=record3("model_orchestration");const assurance=record3("assurance");const includeStack=phase2==="planning"||phase2==="execution"||role==="builder";return{source:{path:".agents/config/project.yaml",sha256:createHash6("sha256").update(source).digest("hex"),schema_version:typeof config2.schema_version==="number"?config2.schema_version:null},projection:true,role,phase:phase2,zaip_enabled:typeof zaip.enabled==="boolean"?zaip.enabled:null,authority:{execution:Object.keys(execution).length?execution:null,model_orchestration:Object.keys(model).length?model:null},lifecycle:{assurance:Object.keys(assurance).length?assurance:null},stack:includeStack?config2.stack??null:null}}import{createHash as createHash7}from"node:crypto";var contextHandoffSchema={parse(value){assertHandoffStructure(value);return value}};function validateContextHandoff(handoff){contextHandoffSchema.parse(handoff);const findings=[];const selected=handoff.context.reduce((sum,item)=>sum+item.estimated_tokens,0);if(selected!==handoff.budget.selected_tokens||selected>handoff.budget.max_tokens){findings.push({code:"budget",message:"Selected context does not match the declared budget"})}const expectedSource=handoff.budget.observed_input_tokens!==null?"provider-uncached-input":handoff.budget.observable_context_tokens!==null?"observable-context-fallback":"unavailable";if(handoff.budget.measurement_source!==expectedSource){findings.push({code:"measurement",message:`Measurement source must be ${expectedSource}`})}for(const value of[...handoff.invariants,...handoff.decisions,...handoff.evidence,...handoff.progress.completed,...handoff.progress.pending,handoff.progress.next_action,handoff.progress.blocker??""]){if(containsSecret(value)){findings.push({code:"secret",message:"Secret-like content is forbidden in handoff"});break}}return findings}function handoffHash(handoff){return createHash7("sha256").update(stableJson3(handoff)).digest("hex")}function compactContextHandoff(input){const handoff={...input,requirements:[...new Set(input.requirements)].sort(),acceptance_criteria:[...new Set(input.acceptance_criteria)].sort(),invariants:[...new Set(input.invariants)].sort(),context:[...input.context].sort((left,right)=>left.path.localeCompare(right.path)),compaction:input.compaction};contextHandoffSchema.parse(handoff);const findings=validateContextHandoff(handoff);if(findings.length>0)throw new Error(`Invalid ContextHandoff: ${findings.map(item=>item.code).join(",")}`);return handoff}function verifyCompactionHandshake(previous,next){const findings=[...validateContextHandoff(next)];if(next.revision!==previous.revision+1||next.compaction.previous_hash!==handoffHash(previous)){findings.push({code:"compaction",message:"Compaction revision/hash handshake is invalid"})}if(stableJson3(next.anchors)!==stableJson3(previous.anchors)){findings.push({code:"anchor",message:"Compaction cannot change lifecycle anchors"})}for(const[label,required2,present]of[["requirement",previous.requirements,next.requirements],["acceptance criterion",previous.acceptance_criteria,next.acceptance_criteria],["invariant",previous.invariants,next.invariants],["evidence",previous.evidence,next.evidence]]){const omitted=required2.filter(value=>!present.includes(value));if(omitted.length>0){findings.push({code:"required-context",message:`Compaction omitted ${label}: ${omitted.join(", ")}`})}}const preserved=new Set(next.compaction.preserved_invariants);if(previous.invariants.some(invariant=>!preserved.has(invariant))){findings.push({code:"compaction",message:"Preserved invariant acknowledgement is incomplete"})}return findings}function containsSecret(value){return/(?:-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|\bAKIA[0-9A-Z]{16}\b|\bgh[ps]_[A-Za-z0-9]{20,}\b|\bsk-[A-Za-z0-9_-]{8,}\b)/.test(value)}function assertHandoffStructure(value){if(!isRecord4(value)||value.schema_version!==1)throw new Error("Invalid handoff schema");if(!isString(value.handoff_id)||!/^HANDOFF-[A-Z0-9-]+$/.test(value.handoff_id)){throw new Error("Invalid handoff id")}if(!isPositiveInteger(value.revision)||!isDateTime(value.created_at)){throw new Error("Invalid handoff revision or timestamp")}if(!isRecord4(value.anchors))throw new Error("Invalid handoff anchors");for(const key of["change_id","task_id","execution_id","run_id"]){if(!isLifecycleId(value.anchors[key]))throw new Error(`Invalid anchor: ${key}`)}for(const key of["prd_id","spec_id"]){if(value.anchors[key]!==null&&!isLifecycleId(value.anchors[key])){throw new Error(`Invalid anchor: ${key}`)}}for(const[label,candidate,required2]of[["requirements",value.requirements,true],["acceptance_criteria",value.acceptance_criteria,true],["invariants",value.invariants,true],["decisions",value.decisions,false],["evidence",value.evidence,false]]){if(!isUniqueStringArray(candidate,required2))throw new Error(`Invalid ${label}`)}if(!isRecord4(value.progress)||!isUniqueStringArray(value.progress.completed,false)||!isUniqueStringArray(value.progress.pending,false)||!isString(value.progress.next_action)||value.progress.blocker!==null&&!isString(value.progress.blocker)){throw new Error("Invalid handoff progress")}if(!Array.isArray(value.context)||value.context.some(item=>!isRecord4(item)||!isString(item.path)||!isString(item.sha256)||!/^[a-f0-9]{64}$/.test(item.sha256)||!isNonNegativeInteger(item.estimated_tokens)||!isString(item.reason))){throw new Error("Invalid selected context")}if(!isRecord4(value.budget)||!isPositiveInteger(value.budget.max_tokens)||!isNonNegativeInteger(value.budget.selected_tokens)||!isNullableNonNegativeInteger(value.budget.observed_input_tokens)||!isNullableNonNegativeInteger(value.budget.observable_context_tokens)||!["provider-uncached-input","observable-context-fallback","unavailable"].includes(String(value.budget.measurement_source))){throw new Error("Invalid handoff budget")}if(!isRecord4(value.compaction)||value.compaction.previous_hash!==null&&(!isString(value.compaction.previous_hash)||!/^[a-f0-9]{64}$/.test(value.compaction.previous_hash))||!isUniqueStringArray(value.compaction.preserved_invariants,false)){throw new Error("Invalid compaction handshake")}}function isRecord4(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}function isString(value){return typeof value==="string"&&value.length>0}function isDateTime(value){return isString(value)&&Number.isFinite(Date.parse(value))}function isLifecycleId(value){return isString(value)&&/^(?:PRD|SPEC|CHG|TASK|EXEC|RUN)-[A-Z0-9-]+$/.test(value)}function isPositiveInteger(value){return typeof value==="number"&&Number.isInteger(value)&&value>0}function isNonNegativeInteger(value){return typeof value==="number"&&Number.isInteger(value)&&value>=0}function isNullableNonNegativeInteger(value){return value===null||isNonNegativeInteger(value)}function isUniqueStringArray(value,required2){return Array.isArray(value)&&(!required2||value.length>0)&&value.every(isString)&&new Set(value).size===value.length}function stableJson3(value){return JSON.stringify(sortValue4(value))}function sortValue4(value){if(Array.isArray(value))return value.map(sortValue4);if(value!==null&&typeof value==="object"){return Object.fromEntries(Object.entries(value).sort(([left],[right])=>left.localeCompare(right)).map(([key,item])=>[key,sortValue4(item)]))}return value}var IGNORED_SEGMENTS=[".git","node_modules","dist","coverage","examples","fixtures","local",".local","release","_ref",".turbo"];var TEXT_EXTENSIONS=[".ts",".tsx",".js",".jsx",".json",".yaml",".yml",".md",".css",".html",".mjs",".toml",".ps1"];var V2_CRITICAL_FILES=[".agents/config/project.yaml",".agents/rules/core.md"];var V1_CRITICAL_FILES=[".agents/manifest.yaml",".agents/constitution.md"];async function inventory(filesystem){return(await inventoryWithDiagnostics(filesystem)).entries}async function inventoryWithDiagnostics(filesystem){const snapshot=await createInventorySnapshot(filesystem);return{entries:snapshot.entries.map(toInventoryEntry),diagnostics:snapshot.diagnostics}}async function createInventorySnapshot(filesystem,query=""){const discovery=await discoverInventoryPaths(filesystem,query);return readInventoryPaths(filesystem,discovery.paths,discovery.criticalFiles)}async function discoverInventoryPaths(filesystem,query=""){const criticalFiles=await resolveCriticalFiles(filesystem);const git5=new ShellGit(filesystem.root);let gitPaths=[];if(await git5.isRepository()){const[tracked,status]=await Promise.all([git5.trackedFiles(),git5.status()]);gitPaths=[...tracked,...status.map(entry2=>entry2.path)]}const sourcePaths=gitPaths.length>0?gitPaths:await filesystem.listFiles(".");const relationPaths=await resolveRelationPaths(filesystem,query);const paths=[...new Set([...sourcePaths,...criticalFiles,...relationPaths])].filter(path=>!IGNORED_SEGMENTS.some(segment2=>path.split("/").includes(segment2))).filter(path=>relationPaths.includes(path)||!isTransientContextPath(path,query)).filter(path=>TEXT_EXTENSIONS.some(extension=>path.endsWith(extension))).sort(comparePaths3);return{paths,criticalFiles,relationPaths}}async function readInventoryPaths(filesystem,paths,criticalFiles){const scanned=await Promise.all(paths.map(async path=>{try{const content=await filesystem.readText(path);return{...inventoryEntry(path,content),content}}catch(error51){if(!isNodeError2(error51)||error51.code!=="ENOENT")throw error51;const critical=criticalFiles.includes(path);return{code:critical?"critical-missing":"missing-file",path,message:critical?"Required context invariant is missing from the working tree":"Git path is absent from the working tree and was skipped"}}}));return{entries:scanned.filter(isInventorySnapshotEntry),diagnostics:scanned.filter(isInventoryDiagnostic),criticalFiles}}async function buildRepositoryMap(filesystem){const snapshot=await createInventorySnapshot(filesystem);return snapshot.entries.map(entry2=>{const content=entry2.content;return{path:entry2.path,module:entry2.path.match(/(?:^|\/)modules\/([^/]+)/)?.[1]??null,imports:importMap(entry2.path,content),symbols:exportedSymbols(content),sddLinks:[...new Set(content.match(/\b(?:SPEC|CHG|TASK|RUN|REQ|AC|EVIDENCE|DEC-(?:HUMAN|AI))-[A-Z0-9-]+/g)??[])].sort()}})}async function buildContextPack(filesystem,query,budget=8e3,options={}){if(!Number.isSafeInteger(budget)||budget<=0){throw new ContextPackBuildError([{rule:"budget",path:"context-pack",message:"Token budget must be a positive integer"}])}const role=options.role??"orchestrator";const phase2=options.phase??inferContextPhase(query);const conversational=phase2==="conversation";const terms=tokenize(query);const discovery=await discoverInventoryPaths(filesystem,query);const candidatePaths=discovery.paths.filter(path=>discovery.criticalFiles.includes(path)||discovery.relationPaths.includes(path)||path.startsWith(".agents/rules/")||path.startsWith(".agents/requirements/")||terms.some(term=>path.toLowerCase().includes(term)));const snapshot=await readInventoryPaths(filesystem,candidatePaths,discovery.criticalFiles);const entries=snapshot.entries;const relationIds=entries.filter(entry2=>discovery.relationPaths.includes(entry2.path)).flatMap(entry2=>entry2.content.match(/\b(?:REQ|AC)-[A-Z0-9-]+/g)??[]);const relationalQuery=[query,...new Set(relationIds)].join(" ");const likelyPaths=entries.filter(entry2=>terms.some(term=>entry2.path.toLowerCase().includes(term))).map(entry2=>entry2.path);const selectedRules=selectRulePaths(entries,conversational?[]:likelyPaths,query,phase2);const selectedRequirements=selectRequirementsFromSnapshot(entries,relationalQuery,conversational);const requiredReferences=[...new Set(relationIds)].sort();const resolvedReferences=new Set(entries.filter(entry2=>selectedRequirements.includes(entry2.path)).flatMap(entry2=>entry2.content.match(/\b(?:REQ|AC)-[A-Z0-9-]+/g)??[]));const unresolvedRequiredReferences=requiredReferences.filter(reference=>!resolvedReferences.has(reference));const requiredFiles=[...new Set([...snapshot.criticalFiles,...discovery.relationPaths,...selectedRules,...selectedRequirements])].sort(comparePaths3);const ruleBudgetFindings=entries.filter(entry2=>selectedRules.includes(entry2.path)).flatMap(entry2=>{const metadata2=parseRuleMetadata(entry2.content);const tokens2=estimateTokens(entry2.content);return tokens2<=metadata2.maxContextTokens?[]:[{rule:"rule-budget",path:entry2.path,message:`Rule needs ${tokens2} tokens but declares ${metadata2.maxContextTokens}; increase its declared budget with headroom or shorten the Rule.`}]});if(ruleBudgetFindings.length>0)throw new ContextPackBuildError(ruleBudgetFindings);const eligibleEntries=entries.filter(entry2=>snapshot.criticalFiles.includes(entry2.path)||discovery.relationPaths.includes(entry2.path)||selectedRules.includes(entry2.path)||selectedRequirements.includes(entry2.path)||!conversational&&!entry2.path.startsWith(".agents/rules/")&&!entry2.path.startsWith(".agents/requirements/")&&isDomainPathAllowed(entry2.path,terms));const candidates=eligibleEntries.map(entry2=>{const content=entry2.content;const reasons=[];let score=0;if(snapshot.criticalFiles.includes(entry2.path)||selectedRules.includes(entry2.path)||selectedRequirements.includes(entry2.path)){score+=1e4;reasons.push("critical-rule")}if(discovery.relationPaths.includes(entry2.path)){score+=9e3;reasons.push("active-relation")}const profileReason=contextProfileReason(entry2.path,role,phase2);if(profileReason!==null){score+=200;reasons.push(profileReason)}const searchable=`${entry2.path}
|
|
2016
|
-
${content}`.toLowerCase();for(const term of terms){if(entry2.path.toLowerCase().includes(term)){score+=25;reasons.push(`path:${term}`)}const matches=searchable.split(term).length-1;if(matches>0){score+=Math.min(20,matches);reasons.push(`content:${term}`)}}const sddMatches=content.match(/\b(?:SPEC|CHG|TASK|REQ|AC|DEC-(?:HUMAN|AI))-[A-Z0-9-]+/g)??[];if(sddMatches.some(id=>query.toUpperCase().includes(id))){score+=500;reasons.push("sdd-link")}return{...entry2,content,score,estimatedTokens:estimateTokens(content),reasons}});candidates.sort((left,right)=>{const requiredDelta=Number(requiredFiles.includes(right.path))-Number(requiredFiles.includes(left.path));return requiredDelta||right.score-left.score||comparePaths3(left.path,right.path)});const items=[];const omissions=discovery.paths.filter(path=>!candidatePaths.includes(path)).map(path=>({path,reason:"not-candidate",required:requiredFiles.includes(path)}));let used=0;for(const candidate of candidates){if(candidate.score===0){omissions.push({path:candidate.path,reason:"zero-score",required:requiredFiles.includes(candidate.path)});continue}if(used+candidate.estimatedTokens>budget){omissions.push({path:candidate.path,reason:requiredFiles.includes(candidate.path)?"required-budget-exceeded":"budget-exceeded",required:requiredFiles.includes(candidate.path)});continue}assertNoSecrets(candidate.path,candidate.content);items.push(candidate);used+=candidate.estimatedTokens}const pack={query,role,phase:phase2,budget,estimatedTokens:used,discoveredFiles:discovery.paths.length,readFiles:candidatePaths.length,tokenSource:"estimated",layers:measureContextLayers(items),items,omitted:omissions.map(omission=>omission.path),omissions,criticalFiles:snapshot.criticalFiles,requiredFiles,requiredReferences,unresolvedRequiredReferences,selectedRules,selectedRequirements,diagnostics:snapshot.diagnostics};const findings=validateContextPack(pack);if((options.failClosed??true)&&findings.length>0){throw new ContextPackBuildError(findings)}return pack}function measureContextLayers(items){const totals={framework:0,product:0,lifecycle:0};for(const item of items)totals[contextLayer(item.path)]+=item.estimatedTokens;return Object.keys(totals).map(layer=>({layer,estimatedTokens:totals[layer]}))}function selectRequirementsFromSnapshot(entries,query,conversational=false){const terms=tokenize(query);const queryUpper=query.toUpperCase();if(conversational){return entries.filter(entry2=>entry2.path.startsWith(".agents/requirements/")&&entry2.path.endsWith(".md")).filter(entry2=>(entry2.content.match(/\b(?:REQ|AC)-[A-Z0-9-]+/g)??[]).some(id=>queryUpper.includes(id))).map(entry2=>entry2.path).sort(comparePaths3)}const scored=entries.filter(entry2=>entry2.path.startsWith(".agents/requirements/")&&entry2.path.endsWith(".md")).map(entry2=>{const path=entry2.path.toLowerCase();const header=entry2.content.split(/\r?\n/).filter(line=>/^(?:id|area|title):|^#\s/.test(line)).join("\n").toLowerCase();const searchable=entry2.content.toLowerCase();const ids=entry2.content.match(/\b(?:REQ|AC)-[A-Z0-9-]+/g)??[];const explicitMatches=ids.filter(id=>queryUpper.includes(id)).length;const pathMatches=terms.filter(term=>path.includes(term)).length;const headerMatches=terms.filter(term=>header.includes(term)).length;const contentMatches=terms.reduce((total,term)=>total+Math.min(5,searchable.split(term).length-1),0);const structuralScore=explicitMatches*1e3+pathMatches*100+headerMatches*30;return{entry:entry2,structuralScore,score:structuralScore+contentMatches}}).filter(({score})=>score>0).sort((left,right)=>right.score-left.score||comparePaths3(left.entry.path,right.entry.path));const explicit=scored.filter(({entry:entry2})=>{const ids=entry2.content.match(/\b(?:REQ|AC)-[A-Z0-9-]+/g)??[];return ids.some(id=>queryUpper.includes(id))});if(explicit.length>0)return explicit.map(({entry:entry2})=>entry2.path);const structural=scored.filter(({structuralScore})=>structuralScore>0);return(structural.length>0?structural.slice(0,3):scored.slice(0,1)).map(({entry:entry2})=>entry2.path)}function importMap(path,content){if(!/\.[cm]?[jt]sx?$/.test(path))return[];const pattern=/(?:^|\n)\s*import\s+(?:type\s+)?(?:[^"'\n]*?\s+from\s+)?["']([^"']+)["']/g;return[...content.matchAll(pattern)].map(match=>match[1]).filter(value=>value!==void 0).sort()}function estimateTokens(content){return encode3(content,{disallowedSpecial:new Set}).length}function exportedSymbols(content){return[...content.matchAll(/\bexport\s+(?:default\s+)?(?:async\s+)?(?:class|function|interface|type|const|let|var|enum)\s+([A-Za-z_$][\w$]*)/g)].map(match=>match[1]).filter(value=>value!==void 0).sort()}function inventoryEntry(path,content){return{path,bytes:Buffer.byteLength(content),lines:content.length===0?0:content.split("\n").length,sha256:createHash8("sha256").update(content).digest("hex")}}function toInventoryEntry(entry2){return{path:entry2.path,bytes:entry2.bytes,lines:entry2.lines,sha256:entry2.sha256}}function isInventorySnapshotEntry(value){return"content"in value}function isInventoryDiagnostic(value){return"code"in value}async function resolveCriticalFiles(filesystem){const hasV2=await filesystem.exists(V2_CRITICAL_FILES[0])||await filesystem.exists(V2_CRITICAL_FILES[1]);if(hasV2)return V2_CRITICAL_FILES;const hasV1=await filesystem.exists(V1_CRITICAL_FILES[0])||await filesystem.exists(V1_CRITICAL_FILES[1]);return hasV1?V1_CRITICAL_FILES:V2_CRITICAL_FILES}function isTransientContextPath(path,query=""){if(isExplicitProjectionRequest(path,query))return false;return path.startsWith(".local/")||path.startsWith(".agents/generated/")||path.startsWith(".agents/records/")||path.startsWith(".agents/data/")||path.startsWith(".codex/")||path.startsWith(".claude/")||path.startsWith("public-cli/")||path.startsWith("public-cli/packages/cli/templates/")||/(?:^|\/)(?:pnpm-lock\.yaml|package-lock\.json|yarn\.lock)$/.test(path)}function isExplicitProjectionRequest(path,query){const projectionRoot=[".codex/",".claude/","public-cli/"].find(root=>path.startsWith(root));if(projectionRoot===void 0)return false;const normalized=query.replace(/\\/g,"/").toLowerCase();return normalized.includes(path.toLowerCase())||normalized.includes(projectionRoot)}function contextLayer(path){if(path.startsWith(".agents/records/"))return"lifecycle";if(path.startsWith(".agents/"))return"framework";return"product"}async function resolveRelationPaths(filesystem,query){const explicitIds=new Set(query.toUpperCase().match(/(?<![A-Z0-9_-])(?:PRD|SPEC|CHG|TASK|EXEC|RUN)-[A-Z0-9-]+/g)??[]);if(explicitIds.size===0)return[];let layout=null;try{layout=await loadWorkspaceLayout(filesystem)}catch{layout=null}const paths=[];for(const id of explicitIds){const kind=kindFromId(id);if(kind===null)continue;if(layout?.supports(kind)){const path=await resolveArtifactReadPath(filesystem,layout,kind,id);if(path!==null){paths.push(path);continue}}const fallback=v3RelationPath(kind,id);if(fallback!==null&&await filesystem.exists(fallback)){paths.push(fallback);continue}if(explicitIds.has(id)){throw new Error(`Explicit lifecycle context path does not resolve: ${id}`)}}return paths}function v3RelationPath(kind,id){const match=id.match(/^[A-Z]+-(\d{4})-(\d{2})-/);if(match===null)return null;const[,year,month]=match;const roots2={prd:"prds",spec:"specs",change:"changes",task:"tasks",execution:"executions",run:"runs"};const base=`.agents/records/${roots2[kind]}/${year}/${month}`;if(kind==="change")return`${base}/${id}/change.md`;if(kind==="execution")return`${base}/${id}/execution.md`;if(kind==="run")return`${base}/${id}.jsonl`;return`${base}/${id}.md`}function kindFromId(id){if(id.startsWith("PRD-"))return"prd";if(id.startsWith("SPEC-"))return"spec";if(id.startsWith("CHG-"))return"change";if(id.startsWith("TASK-"))return"task";if(id.startsWith("EXEC-"))return"execution";if(id.startsWith("RUN-"))return"run";return null}function isNodeError2(error51){return error51 instanceof Error&&"code"in error51}function comparePaths3(left,right){if(left<right)return-1;if(left>right)return 1;return 0}function tokenize(query){const stopWords=new Set(["active"]);const lexicalQuery=query.replace(/(?<![A-Z0-9_-])(?:PRD|SPEC|CHG|TASK|EXEC|RUN)-[A-Z0-9-]+\b/gi," ");return[...new Set(lexicalQuery.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g," ").split(/\s+/).filter(term=>term.length>2&&!stopWords.has(term)))]}function isDomainPathAllowed(path,terms){if(path.startsWith("analysis/")){const analysisTerms=new Set(["audit","auditoria","analise","analysis","verificacao","relatorio"]);return terms.some(term=>analysisTerms.has(term))}if(!path.startsWith(".agents/design/"))return true;const designTerms=new Set(["design","visual","interface","frontend","catalog","storybook"]);return terms.some(term=>designTerms.has(term))}init_src();init_src2();init_src3();init_src();var EVAL_VERSION="3.
|
|
2016
|
+
${content}`.toLowerCase();for(const term of terms){if(entry2.path.toLowerCase().includes(term)){score+=25;reasons.push(`path:${term}`)}const matches=searchable.split(term).length-1;if(matches>0){score+=Math.min(20,matches);reasons.push(`content:${term}`)}}const sddMatches=content.match(/\b(?:SPEC|CHG|TASK|REQ|AC|DEC-(?:HUMAN|AI))-[A-Z0-9-]+/g)??[];if(sddMatches.some(id=>query.toUpperCase().includes(id))){score+=500;reasons.push("sdd-link")}return{...entry2,content,score,estimatedTokens:estimateTokens(content),reasons}});candidates.sort((left,right)=>{const requiredDelta=Number(requiredFiles.includes(right.path))-Number(requiredFiles.includes(left.path));return requiredDelta||right.score-left.score||comparePaths3(left.path,right.path)});const items=[];const omissions=discovery.paths.filter(path=>!candidatePaths.includes(path)).map(path=>({path,reason:"not-candidate",required:requiredFiles.includes(path)}));let used=0;for(const candidate of candidates){if(candidate.score===0){omissions.push({path:candidate.path,reason:"zero-score",required:requiredFiles.includes(candidate.path)});continue}if(used+candidate.estimatedTokens>budget){omissions.push({path:candidate.path,reason:requiredFiles.includes(candidate.path)?"required-budget-exceeded":"budget-exceeded",required:requiredFiles.includes(candidate.path)});continue}assertNoSecrets(candidate.path,candidate.content);items.push(candidate);used+=candidate.estimatedTokens}const pack={query,role,phase:phase2,budget,estimatedTokens:used,discoveredFiles:discovery.paths.length,readFiles:candidatePaths.length,tokenSource:"estimated",layers:measureContextLayers(items),items,omitted:omissions.map(omission=>omission.path),omissions,criticalFiles:snapshot.criticalFiles,requiredFiles,requiredReferences,unresolvedRequiredReferences,selectedRules,selectedRequirements,diagnostics:snapshot.diagnostics};const findings=validateContextPack(pack);if((options.failClosed??true)&&findings.length>0){throw new ContextPackBuildError(findings)}return pack}function measureContextLayers(items){const totals={framework:0,product:0,lifecycle:0};for(const item of items)totals[contextLayer(item.path)]+=item.estimatedTokens;return Object.keys(totals).map(layer=>({layer,estimatedTokens:totals[layer]}))}function selectRequirementsFromSnapshot(entries,query,conversational=false){const terms=tokenize(query);const queryUpper=query.toUpperCase();if(conversational){return entries.filter(entry2=>entry2.path.startsWith(".agents/requirements/")&&entry2.path.endsWith(".md")).filter(entry2=>(entry2.content.match(/\b(?:REQ|AC)-[A-Z0-9-]+/g)??[]).some(id=>queryUpper.includes(id))).map(entry2=>entry2.path).sort(comparePaths3)}const scored=entries.filter(entry2=>entry2.path.startsWith(".agents/requirements/")&&entry2.path.endsWith(".md")).map(entry2=>{const path=entry2.path.toLowerCase();const header=entry2.content.split(/\r?\n/).filter(line=>/^(?:id|area|title):|^#\s/.test(line)).join("\n").toLowerCase();const searchable=entry2.content.toLowerCase();const ids=entry2.content.match(/\b(?:REQ|AC)-[A-Z0-9-]+/g)??[];const explicitMatches=ids.filter(id=>queryUpper.includes(id)).length;const pathMatches=terms.filter(term=>path.includes(term)).length;const headerMatches=terms.filter(term=>header.includes(term)).length;const contentMatches=terms.reduce((total,term)=>total+Math.min(5,searchable.split(term).length-1),0);const structuralScore=explicitMatches*1e3+pathMatches*100+headerMatches*30;return{entry:entry2,structuralScore,score:structuralScore+contentMatches}}).filter(({score})=>score>0).sort((left,right)=>right.score-left.score||comparePaths3(left.entry.path,right.entry.path));const explicit=scored.filter(({entry:entry2})=>{const ids=entry2.content.match(/\b(?:REQ|AC)-[A-Z0-9-]+/g)??[];return ids.some(id=>queryUpper.includes(id))});if(explicit.length>0)return explicit.map(({entry:entry2})=>entry2.path);const structural=scored.filter(({structuralScore})=>structuralScore>0);return(structural.length>0?structural.slice(0,3):scored.slice(0,1)).map(({entry:entry2})=>entry2.path)}function importMap(path,content){if(!/\.[cm]?[jt]sx?$/.test(path))return[];const pattern=/(?:^|\n)\s*import\s+(?:type\s+)?(?:[^"'\n]*?\s+from\s+)?["']([^"']+)["']/g;return[...content.matchAll(pattern)].map(match=>match[1]).filter(value=>value!==void 0).sort()}function estimateTokens(content){return encode3(content,{disallowedSpecial:new Set}).length}function exportedSymbols(content){return[...content.matchAll(/\bexport\s+(?:default\s+)?(?:async\s+)?(?:class|function|interface|type|const|let|var|enum)\s+([A-Za-z_$][\w$]*)/g)].map(match=>match[1]).filter(value=>value!==void 0).sort()}function inventoryEntry(path,content){return{path,bytes:Buffer.byteLength(content),lines:content.length===0?0:content.split("\n").length,sha256:createHash8("sha256").update(content).digest("hex")}}function toInventoryEntry(entry2){return{path:entry2.path,bytes:entry2.bytes,lines:entry2.lines,sha256:entry2.sha256}}function isInventorySnapshotEntry(value){return"content"in value}function isInventoryDiagnostic(value){return"code"in value}async function resolveCriticalFiles(filesystem){const hasV2=await filesystem.exists(V2_CRITICAL_FILES[0])||await filesystem.exists(V2_CRITICAL_FILES[1]);if(hasV2)return V2_CRITICAL_FILES;const hasV1=await filesystem.exists(V1_CRITICAL_FILES[0])||await filesystem.exists(V1_CRITICAL_FILES[1]);return hasV1?V1_CRITICAL_FILES:V2_CRITICAL_FILES}function isTransientContextPath(path,query=""){if(isExplicitProjectionRequest(path,query))return false;return path.startsWith(".local/")||path.startsWith(".agents/generated/")||path.startsWith(".agents/records/")||path.startsWith(".agents/data/")||path.startsWith(".codex/")||path.startsWith(".claude/")||path.startsWith("public-cli/")||path.startsWith("public-cli/packages/cli/templates/")||/(?:^|\/)(?:pnpm-lock\.yaml|package-lock\.json|yarn\.lock)$/.test(path)}function isExplicitProjectionRequest(path,query){const projectionRoot=[".codex/",".claude/","public-cli/"].find(root=>path.startsWith(root));if(projectionRoot===void 0)return false;const normalized=query.replace(/\\/g,"/").toLowerCase();return normalized.includes(path.toLowerCase())||normalized.includes(projectionRoot)}function contextLayer(path){if(path.startsWith(".agents/records/"))return"lifecycle";if(path.startsWith(".agents/"))return"framework";return"product"}async function resolveRelationPaths(filesystem,query){const explicitIds=new Set(query.toUpperCase().match(/(?<![A-Z0-9_-])(?:PRD|SPEC|CHG|TASK|EXEC|RUN)-[A-Z0-9-]+/g)??[]);if(explicitIds.size===0)return[];let layout=null;try{layout=await loadWorkspaceLayout(filesystem)}catch{layout=null}const paths=[];for(const id of explicitIds){const kind=kindFromId(id);if(kind===null)continue;if(layout?.supports(kind)){const path=await resolveArtifactReadPath(filesystem,layout,kind,id);if(path!==null){paths.push(path);continue}}const fallback=v3RelationPath(kind,id);if(fallback!==null&&await filesystem.exists(fallback)){paths.push(fallback);continue}if(explicitIds.has(id)){throw new Error(`Explicit lifecycle context path does not resolve: ${id}`)}}return paths}function v3RelationPath(kind,id){const match=id.match(/^[A-Z]+-(\d{4})-(\d{2})-/);if(match===null)return null;const[,year,month]=match;const roots2={prd:"prds",spec:"specs",change:"changes",task:"tasks",execution:"executions",run:"runs"};const base=`.agents/records/${roots2[kind]}/${year}/${month}`;if(kind==="change")return`${base}/${id}/change.md`;if(kind==="execution")return`${base}/${id}/execution.md`;if(kind==="run")return`${base}/${id}.jsonl`;return`${base}/${id}.md`}function kindFromId(id){if(id.startsWith("PRD-"))return"prd";if(id.startsWith("SPEC-"))return"spec";if(id.startsWith("CHG-"))return"change";if(id.startsWith("TASK-"))return"task";if(id.startsWith("EXEC-"))return"execution";if(id.startsWith("RUN-"))return"run";return null}function isNodeError2(error51){return error51 instanceof Error&&"code"in error51}function comparePaths3(left,right){if(left<right)return-1;if(left>right)return 1;return 0}function tokenize(query){const stopWords=new Set(["active"]);const lexicalQuery=query.replace(/(?<![A-Z0-9_-])(?:PRD|SPEC|CHG|TASK|EXEC|RUN)-[A-Z0-9-]+\b/gi," ");return[...new Set(lexicalQuery.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g," ").split(/\s+/).filter(term=>term.length>2&&!stopWords.has(term)))]}function isDomainPathAllowed(path,terms){if(path.startsWith("analysis/")){const analysisTerms=new Set(["audit","auditoria","analise","analysis","verificacao","relatorio"]);return terms.some(term=>analysisTerms.has(term))}if(!path.startsWith(".agents/design/"))return true;const designTerms=new Set(["design","visual","interface","frontend","catalog","storybook"]);return terms.some(term=>designTerms.has(term))}init_src();init_src2();init_src3();init_src();var EVAL_VERSION="3.2.0";async function persistEvalReport(filesystem,report,shortName="offline-suite"){const id=createId("EVAL",shortName);const{year,month}=datedIdParts(id);const path=`.agents/evals/results/${year}/${month}/${id}.json`;const persisted={id,version:EVAL_VERSION,generated_at:new Date().toISOString(),report};await filesystem.writeTextAtomic(path,`${JSON.stringify(persisted,null,2)}
|
|
2017
2017
|
`);return{id,path}}function runEvalSuite(cases,profile){const results=cases.map(testCase=>{const startedAt=performance.now();const findings=testCase.validator==="cqrs"?validateCqrs(testCase.units,profile):validateArchitecture(testCase.units,profile);const actualRules=[...new Set(findings.map(item=>item.rule))].sort();const expectedRules=[...testCase.expectedRules].sort();return{id:testCase.id,passed:JSON.stringify(actualRules)===JSON.stringify(expectedRules),expectedRules,actualRules,durationMs:Math.max(0,performance.now()-startedAt)}});return{passed:results.every(result2=>result2.passed),offline:true,cases:results}}function guardDiff(changedFiles,ledgerFiles){const canonicalChanges=changedFiles.filter(path=>!path.startsWith(".agents/"));return canonicalChanges.filter(path=>!ledgerFiles.includes(path)).map(path=>({rule:"untracked-diff",message:`${path} is not present in the active task ledger`}))}var BUILTIN_EVAL_CASES=[{id:"domain-rejects-framework",units:[{path:"src/modules/a/domain/entity.ts",content:'import { Hono } from "hono";'}],expectedRules:["domain-framework-dependency"]},{id:"query-rejects-write",units:[{path:"src/modules/a/application/queries/get.query.ts",content:"export const get = (port: WritePort) => port.save({});"}],expectedRules:["query-side-effect","query-write-port"],validator:"cqrs"},{id:"pure-query-passes",units:[{path:"src/modules/a/application/queries/get.query.ts",content:"export const get = (port: ReadPort) => port.find();"}],expectedRules:[],validator:"cqrs"}];function scanInfrastructureSecurity(path,content){const findings=[];if(/\.ya?ml$/.test(path)&&/(?:privileged:\s*true|network_mode:\s*["']?host)/i.test(content)){findings.push({rule:"docker-unsafe-isolation",path})}if(/\.tf$/.test(path)&&/(?:cidr_blocks|source_ranges)\s*=\s*\[[^\]]*["']0\.0\.0\.0\/0/i.test(content)){findings.push({rule:"terraform-public-ingress",path})}if(/\.sql$/.test(path)&&/GRANT\s+ALL(?:\s+PRIVILEGES)?[\s\S]*\sTO\s+(?:PUBLIC|\w+)/i.test(content)){findings.push({rule:"sql-overprivileged-grant",path})}return findings}function runCategoryEval(category){if(category==="architecture"){return runEvalSuite(BUILTIN_EVAL_CASES.filter(item=>item.id.includes("domain")))}if(category==="cqrs"){return runEvalSuite(BUILTIN_EVAL_CASES.filter(item=>!item.id.includes("domain")))}const startedAt=performance.now();let passed=false;let actualRules=[];let expectedRules=[];if(category==="specs"){expectedRules=["untracked-diff"];actualRules=guardDiff(["src/new.ts"],[]).map(item=>item.rule);passed=expectedRules.every(rule=>actualRules.includes(rule))}else if(category==="security"){expectedRules=["generic-secret"];actualRules=scanSecrets("fixture.ts",'const token = "definitely-not-a-real-secret"').map(item=>item.kind);passed=expectedRules.every(rule=>actualRules.includes(rule))}else if(category==="infrastructure"){expectedRules=["docker-unsafe-isolation","terraform-public-ingress","sql-overprivileged-grant"];actualRules=[...scanInfrastructureSecurity("compose.yaml","services:\n app:\n privileged: true"),...scanInfrastructureSecurity("main.tf",'ingress { cidr_blocks = ["0.0.0.0/0"] }'),...scanInfrastructureSecurity("grant.sql","GRANT ALL PRIVILEGES ON app TO PUBLIC;")].map(item=>item.rule);passed=expectedRules.every(rule=>actualRules.includes(rule))}else if(category==="adapters"){const files=adapterFiles(process.cwd());actualRules=files.map(file2=>file2.path);expectedRules=[...actualRules];passed=files.length>0&&new Set(files.map(file2=>file2.path)).size===files.length&&files.every(file2=>file2.content.includes("zaip-managed"))}else if(category==="context"){actualRules=[String(estimateTokens("12345678"))];expectedRules=[...actualRules];passed=Number(actualRules[0])>0}return{passed,offline:true,cases:[{id:`${category}-builtin`,passed,expectedRules,actualRules,durationMs:performance.now()-startedAt}]}}function runAllCategoryEvals(){const categories=["specs","architecture","cqrs","security","infrastructure","adapters","context"];const reports=categories.map(runCategoryEval);return{passed:reports.every(report=>report.passed),offline:true,cases:reports.flatMap(report=>report.cases)}}init_src4();init_src5();init_src();function output(value,json2,error51=false){const text=json2||typeof value!=="string"?`${JSON.stringify(value,null,2)}
|
|
2018
2018
|
`:`${value}
|
|
2019
2019
|
`;(error51?process.stderr:process.stdout).write(text)}var ACTIVATION_COMMANDS=new Set(["enable","disable","status"]);var DISABLED_MAINTENANCE_COMMANDS=new Set(["setup","upgrade","doctor","adapters","architecture","cqrs","modules","profile","migrate","version"]);function isActivationCommand(area){return ACTIVATION_COMMANDS.has(area)}async function runActivationCommand(area,filesystem,json2){if(!await filesystem.exists(PROJECT_CONFIG_PATH)){const result2={installed:false,enabled:null,config_path:PROJECT_CONFIG_PATH,message:"ZAIP-AIOS project configuration was not found."};output(result2,json2,area!=="status");return area==="status"?0:6}const repository2=new ProjectConfigRepository(filesystem);const config2=await repository2.read();if(area==="status"){output({installed:true,enabled:isZaipEnabled(config2),configured:config2.zaip?.enabled??null,config_path:PROJECT_CONFIG_PATH},json2);return 0}const enabled=area==="enable";await repository2.write({...config2,zaip:{enabled}});output({installed:true,enabled,config_path:PROJECT_CONFIG_PATH,message:enabled?"ZAIP-AIOS enabled.":"ZAIP-AIOS disabled."},json2);return 0}async function isZaipCliDisabled(filesystem){if(!await filesystem.exists(PROJECT_CONFIG_PATH))return false;return!isZaipEnabled(await new ProjectConfigRepository(filesystem).read())}function isDisabledMaintenanceCommand(area){return DISABLED_MAINTENANCE_COMMANDS.has(area)}async function handleZaipActivation(area,filesystem,json2){if(isActivationCommand(area))return runActivationCommand(area,filesystem,json2);if(isDisabledMaintenanceCommand(area)||!await isZaipCliDisabled(filesystem))return null;output({enabled:false,error:"ZAIP-AIOS is disabled for this project. Run `zaip enable` to reactivate it."},json2,true);return 6}init_cli_arguments();async function sourceUnits(filesystem){const frameworkSource=await filesystem.exists("package.json")&&JSON.parse(await filesystem.readText("package.json")).name==="@zaip-ai/aios";const entries=(await inventory(filesystem)).filter(({path})=>frameworkSource||!/^\.agents\/(?:dashboard|design)\//.test(path));const aliasesForSource2=workspaceImportAliases(await Promise.all(entries.filter(({path})=>/(?:^|\/)(?:package|tsconfig(?:\.[^/]+)?)\.json$/.test(path)&&!isGeneratedSourcePath(path)).map(async({path})=>({path,content:await filesystem.readText(path)}))));const files=entries.filter(entry2=>/\.[cm]?[jt]sx?$/.test(entry2.path));const productionFiles=files.filter(entry2=>!/(?:^|\/)(?:tests?|__tests__)(?:\/|$)|\.(?:test|spec)(?:-support)?\.[cm]?[jt]sx?$/.test(entry2.path)&&!/(?:^|\/)scripts\/test-[^/]+\.[cm]?[jt]s$/.test(entry2.path)&&!isGeneratedSourcePath(entry2.path));return Promise.all(productionFiles.map(async({path})=>{const aliases=aliasesForSource2(path);return{path,content:await filesystem.readText(path),...aliases.length>0?{importAliases:aliases}:{}}}))}function configuredArchitectureProfile(projectConfig2){const architecture=projectConfig2?.stack.overrides.architecture;const aliases=isRecord5(architecture)?architecture.import_aliases:void 0;if(aliases!==void 0&&!Array.isArray(aliases))throw new Error("Invalid architecture import_aliases: expected an array");const configured=(aliases??[]).map((value,index)=>parseImportAlias(value,index));for(const[index,{prefix}]of configured.entries()){if(configured.some((alias,other)=>other!==index&&alias.prefix.startsWith(prefix))){throw new Error(`Invalid architecture import_aliases: ambiguous prefix ${prefix}`)}}if(projectConfig2?.stack.id!==SUPABASE_EDGE_PROFILE.id)return{...TYPESCRIPT_PROFILE,importAliases:configured};const resolution=resolveSupabaseProfile({id:SUPABASE_EDGE_PROFILE.id,...isRecord5(architecture)&&architecture.deno_json!==void 0?{deno_json:architecture.deno_json}:isRecord5(architecture)&&architecture.deno_import_map!==void 0?{deno_import_map:architecture.deno_import_map}:{}});if(!resolution.profile.supported){throw new Error(`Invalid Supabase architecture profile: ${resolution.diagnostics.join("; ")}`)}return{...resolution.profile,importAliases:configured}}function parseImportAlias(value,index){if(!isRecord5(value)||typeof value.prefix!=="string"||typeof value.target!=="string"){throw new Error(`Invalid architecture import_aliases[${index}]: expected prefix and target strings`)}if(value.prefix.length===0||value.target.length===0){throw new Error(`Invalid architecture import_aliases[${index}]: prefix and target must not be empty`)}if(!value.prefix.endsWith("/")||!value.target.endsWith("/")){throw new Error(`Invalid architecture import_aliases[${index}]: prefix and target must end with /`)}if(/\s/.test(value.prefix)||/\s/.test(value.target)){throw new Error(`Invalid architecture import_aliases[${index}]: prefix and target must not contain whitespace`)}if(value.target.startsWith("/")||value.target.startsWith("\\")||/^[A-Za-z]:/.test(value.target)||/^[A-Za-z][A-Za-z0-9+.-]*:/.test(value.target)||value.target.split(/[\\/]/).includes("..")){throw new Error(`Invalid architecture import_aliases[${index}]: target must be a workspace-relative path`)}return{prefix:value.prefix,target:value.target}}function isGeneratedSourcePath(path){return/(?:^|\/)dist\//.test(path)||path.startsWith(".agents/runtime/bin/")||path.startsWith("public-cli/")||path===".agents/dashboard/packages/local-runtime/server.mjs"}function isRecord5(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function generateBoard(tasks){const states=["planned","executing","verifying","blocked","completed"];return`# Task board
|
|
@@ -2074,7 +2074,7 @@ V1 state converted to V2 with source fingerprint \`${fingerprint.sha256}\`.`})),
|
|
|
2074
2074
|
`));let archivedCapabilities=0;let promotedSpecs=0;for(const capability of capabilities){const legacyId=requiredString2(capability.metadata.id,`${capability.path}:id`);const promotion=promotions.find(candidate=>candidate.legacy_spec_id===legacyId);if(promotion===void 0){archivedCapabilities+=1;const relative14=capability.path.replace(/^\.agents\/specs\/capabilities\//,"");operations.push(bytesOperation("archive","capability",capability.path,capability.sha256,`${executionDirectory}/${migrationExecutionId}/artifacts/legacy/capabilities/${relative14}`,capability.bytes));findings.push({severity:"info",code:"capability-archived-not-promoted",path:capability.path,message:`${legacyId} remains legacy evidence; no DeliverySpec was created.`});continue}promotedSpecs+=1;const promotedRequirementIds=requirementIdsFromCapability(capability.body);const promotedStatus=deliverySpecStatus(capability.metadata.status);const promoted={schema_version:2,id:promotion.delivery_spec_id,prd_id:null,revision:1,title:stringOr(capability.metadata.title,legacyId),status:promotedStatus,objective:bodySection(capability.body,"Purpose")||bodySection(capability.body,"Prop\xF3sito")||stringOr(capability.metadata.title,legacyId),included_scope:[],excluded_scope:[],requirement_ids:promotedRequirementIds,acceptance_ids:promotedRequirementIds.map(id=>`AC-${id.replace(/^REQ-/,"")}`),prepared_plan:null,created_at:migrationTimestamp,updated_at:migrationTimestamp};operations.push(textOperation("convert","spec",capability.path,capability.sha256,v2EntityPath2("specs",promotion.delivery_spec_id,`${promotion.delivery_spec_id}.md`),serializeMarkdown({metadata:promoted,body:`${provenanceBody(capability.body,capability.path,capability.sha256)}
|
|
2075
2075
|
- Promotion authorized by: \`${promotion.authorized_by}\``})))}const project=asRecord2(manifest.project,"manifest.project");const profile=asRecord2(manifest.profile,"manifest.profile");const agents=Array.isArray(manifest.agents)?manifest.agents:[];const managedEmptyPaths=[".agents/requirements/.gitkeep",".agents/skills/.gitkeep",".agents/data/prds/.gitkeep",".agents/data/specs/.gitkeep",".agents/data/changes/.gitkeep",".agents/data/tasks/.gitkeep",".agents/data/executions/.gitkeep",".agents/data/runs/.gitkeep"];const legacyManagedPaths=await readLegacyManagedPaths(filesystem);const v2RuleIds=new Set(DEFAULT_V2_MANAGED_FILES.filter(file2=>file2.path.startsWith(".agents/rules/")).map(file2=>parseRuleDocument(file2.content).metadata.id));for(const source of fingerprint.files.filter(file2=>/^\.agents\/rules\/[^/]+\.md$/.test(file2.path))){if(legacyManagedPaths.has(source.path))continue;const content=await filesystem.readText(source.path);const rule=parseRuleDocument(content);if(v2RuleIds.has(rule.metadata.id)){throw new Error(`Project Rule id collides with a ZAIP Rule during migration: ${rule.metadata.id}`)}v2RuleIds.add(rule.metadata.id)}const existingManagedFiles=await readManagedFiles(filesystem);const managedFiles={...Object.fromEntries(Object.entries(existingManagedFiles).filter(([path])=>!path.startsWith(".agents/rules/"))),...Object.fromEntries(managedEmptyPaths.map(path=>[path,sha2562("")]))};for(const file2 of DEFAULT_V2_MANAGED_FILES){if(await filesystem.exists(file2.path)){const current=await filesystem.readText(file2.path);try{if(file2.path.startsWith(".agents/rules/"))parseRuleDocument(current);else parseRequirementDocument(current);continue}catch{const source=fingerprint.files.find(candidate=>candidate.path===file2.path);if(source===void 0)throw new Error(`Governance source missing: ${file2.path}`);managedFiles[file2.path]=sha2562(file2.content);operations.push(textOperation("convert","config",file2.path,source.sha256,file2.path,file2.content));continue}}managedFiles[file2.path]=sha2562(file2.content);operations.push(textOperation("convert","config",null,null,file2.path,file2.content))}for(const path of managedEmptyPaths){operations.push(textOperation("convert","config",null,null,path,""))}const cleanupPaths=fingerprint.files.map(file2=>file2.path).filter(path=>!path.startsWith(".agents/rules/")&&!path.startsWith(".agents/rules/project/")&&!path.startsWith(".agents/requirements/")&&!path.startsWith(".agents/skills/")).sort();const cleanupRoots=[".agents/specs",".agents/changes",".agents/tasks",".agents/decisions",".agents/runs",".agents/telemetry",".agents/evidence",".agents/generated",".agents/context",".agents/managed",".agents/project",".agents/evals",".agents/profiles",".agents/files"];const handledPaths=new Set(operations.filter(operation=>operation.source_path!==null).map(operation=>operation.source_path));for(const path of consumedTelemetryPaths)handledPaths.add(path);for(const path of cleanupPaths){if(handledPaths.has(path)||path.startsWith(".agents/generated/")||path.startsWith(".agents/context/")){continue}const source=fingerprint.files.find(file2=>file2.path===path);if(source===void 0)throw new Error(`Source disappeared while planning: ${path}`);const bytes=await readFile4(filesystem.resolve(path));operations.push(bytesOperation("archive","legacy",path,source.sha256,`${executionDirectory}/${migrationExecutionId}/artifacts/legacy/${sha2562(path).slice(0,24)}.archive`,bytes))}operations.push(textOperation("activate-config","config",".agents/manifest.yaml",manifestFile.sha256,".agents/config/project.yaml",serializeYaml({schema_version:1,zaip:{enabled:true},project:{id:requiredString2(project.id,"manifest.project.id"),name:requiredString2(project.name,"manifest.project.name"),timezone:stringOr(project.timezone,"America/Sao_Paulo")},stack:{id:stringOr(profile.id,"zaip-aios-stack"),overrides:{}},clients:{codex:agents.includes("codex"),claude:agents.includes("claude")},tracking:{enabled:true,currency:"BRL",storage_mode:"tracked_sanitized"}})),textOperation("activate-config","config",".agents/managed/files.json",fingerprint.files.find(file2=>file2.path===".agents/managed/files.json")?.sha256??null,".agents/config/framework.lock.yaml",serializeYaml({lock_version:2,framework:{version:stringOr(asRecord2(manifest.framework,"manifest.framework").version,"0.1.0"),distribution_sha256:null},layout:{version:2},resolved_profile:{id:stringOr(profile.id,"zaip-aios-stack"),sha256:null},managed_files:managedFiles})));const orderedOperations=operations.sort(operationOrder);const duplicateTarget=firstDuplicate(orderedOperations.map(operation=>operation.target_path));if(duplicateTarget!==null){throw new Error(`Migration plan contains duplicate target: ${duplicateTarget}`)}const withoutHash={schema_version:1,migration_id:migrationId,from_layout:1,to_layout:2,source_fingerprint:fingerprint,promotions,operations:orderedOperations,cleanup_paths:cleanupPaths,cleanup_roots:cleanupRoots,counts:{source_files:fingerprint.files.length,operations:orderedOperations.length,converted_changes:convertedChangeCount,converted_tasks:convertedTaskIds.size,converted_decisions:convertedDecisions,relocated_evidence:relocatedEvidence,converted_runs:convertedRuns,usage_records:usageRecords,archived_capabilities:archivedCapabilities,promoted_specs:promotedSpecs},findings};return{...withoutHash,plan_sha256:hashCanonical(withoutHash)}}import{createHash as createHash28}from"node:crypto";import{mkdir as mkdir2,readFile as readFile5,rename as rename2,rm as rm2,writeFile as writeFile2}from"node:fs/promises";import{dirname as dirname4}from"node:path";var MigrationPlanHashError=class extends Error{name="MigrationPlanHashError"};var MigrationSourceDivergenceError=class extends Error{name="MigrationSourceDivergenceError"};var MigrationCollisionError=class extends Error{name="MigrationCollisionError"};async function applyV1ToV2Migration(filesystem,plan,expectedHash){assertPlanHash(plan,expectedHash);const stateRoot=`.local/migrations/${plan.migration_id}`;const journalPath=`${stateRoot}/journal.json`;const inspected=await inspectTargets(filesystem,plan.operations);const journal=await readJournal(filesystem,journalPath);if(inspected.missing.length===0&&journal?.state==="completed"&&!await anyPathExists(filesystem,[...plan.cleanup_paths,...plan.cleanup_roots])){await persistMigrationPlan(filesystem,stateRoot,plan);return{migration_id:plan.migration_id,status:"noop",created:[],reused:inspected.identical,journal_path:journalPath}}if(journal?.state==="cleanup"||journal?.state==="completed"){await assertBackups(filesystem,stateRoot,plan.source_fingerprint);if(inspected.missing.length>0){throw new MigrationCollisionError(`Migration ${plan.migration_id} reached cleanup with missing V2 targets`)}for(const path of plan.cleanup_paths){await rm2(filesystem.resolve(path),{force:true})}for(const path of plan.cleanup_roots){await rm2(filesystem.resolve(path),{recursive:true,force:true})}await writeJournal(filesystem,journalPath,plan,"completed",journal.created,journal.reused);return{migration_id:plan.migration_id,status:"applied",created:[],reused:inspected.identical,journal_path:journalPath}}else{await assertSourceFingerprint(filesystem,plan.source_fingerprint)}const ownedCreated=journal===null?inspected.missing:[...journal.created];const ownedReused=journal===null?inspected.identical:[...journal.reused];await persistMigrationPlan(filesystem,stateRoot,plan);await writeJournal(filesystem,journalPath,plan,"backing_up",ownedCreated,ownedReused);for(const source of plan.source_fingerprint.files){const sourceBytes=await readFile5(filesystem.resolve(source.path));const backupPath=`${stateRoot}/backup/${source.path}`;if(await filesystem.exists(backupPath)){const backupBytes=await readFile5(filesystem.resolve(backupPath));if(sha2565(backupBytes)!==source.sha256){throw new MigrationCollisionError(`Divergent migration backup: ${backupPath}`)}}else{await writeBytesAtomic(filesystem,backupPath,sourceBytes)}}await writeJournal(filesystem,journalPath,plan,"staging",ownedCreated,ownedReused);for(const operation of plan.operations){const stagePath=`${stateRoot}/staging/${operation.target_path}`;const bytes=Buffer.from(operation.content_base64,"base64");if(sha2565(bytes)!==operation.target_sha256){throw new MigrationPlanHashError(`Operation content hash does not match: ${operation.target_path}`)}if(await filesystem.exists(stagePath)){const staged=await readFile5(filesystem.resolve(stagePath));if(sha2565(staged)!==operation.target_sha256){throw new MigrationCollisionError(`Divergent staged target: ${stagePath}`)}}else{await writeBytesAtomic(filesystem,stagePath,bytes)}}await writeJournal(filesystem,journalPath,plan,"staged",ownedCreated,ownedReused);const created=[];const reused=new Set(inspected.identical);const ordinary=plan.operations.filter(operation=>operation.kind!=="activate-config");for(const operation of ordinary){const result2=await commitOperation(filesystem,stateRoot,operation);if(result2==="created")created.push(operation.target_path);else reused.add(operation.target_path)}await writeJournal(filesystem,journalPath,plan,"commit_started",ownedCreated,ownedReused);const configs=plan.operations.filter(operation=>operation.kind==="activate-config").sort((left,right)=>configOrder2(left.target_path)-configOrder2(right.target_path));if(configs.map(operation=>operation.target_path).join("|")!==".agents/config/project.yaml|.agents/config/framework.lock.yaml"){throw new MigrationPlanHashError("Migration activation must contain exactly both V2 config files")}for(const operation of configs){const result2=await commitOperation(filesystem,stateRoot,operation);if(result2==="created")created.push(operation.target_path);else reused.add(operation.target_path)}await writeJournal(filesystem,journalPath,plan,"cleanup",ownedCreated,ownedReused);for(const path of plan.cleanup_paths){await rm2(filesystem.resolve(path),{force:true})}for(const path of plan.cleanup_roots){await rm2(filesystem.resolve(path),{recursive:true,force:true})}await writeJournal(filesystem,journalPath,plan,"completed",ownedCreated,ownedReused);return{migration_id:plan.migration_id,status:created.length===0?"noop":"applied",created:created.sort(),reused:[...reused].sort(),journal_path:journalPath}}async function readPersistedMigrationPlan(filesystem,migrationId){if(!/^MIG-[A-Z0-9]+$/.test(migrationId))throw new Error(`Invalid migration id: ${migrationId}`);const path=`.local/migrations/${migrationId}/plan.json`;if(!await filesystem.exists(path))return null;const parsed=JSON.parse(await filesystem.readText(path));if(parsed.migration_id!==migrationId){throw new MigrationPlanHashError(`Persisted migration id does not match ${migrationId}`)}assertPlanHash(parsed,parsed.plan_sha256);return parsed}async function inspectV1ToV2Migration(filesystem,plan){assertPlanHash(plan,plan.plan_sha256);const stateRoot=`.local/migrations/${plan.migration_id}`;const journalPath=`${stateRoot}/journal.json`;const[journal,targets]=await Promise.all([readJournal(filesystem,journalPath),inspectTargets(filesystem,plan.operations,true)]);let presentBackups=0;for(const source of plan.source_fingerprint.files){if(await filesystem.exists(`${stateRoot}/backup/${source.path}`))presentBackups+=1}let cleanupRemaining=0;for(const path of[...plan.cleanup_paths,...plan.cleanup_roots]){if(await filesystem.exists(path))cleanupRemaining+=1}return{migration_id:plan.migration_id,state:journal?.state??"not_started",journal_path:journalPath,targets:{identical:targets.identical.length,missing:targets.missing.length},backups:{present:presentBackups,expected:plan.source_fingerprint.files.length},cleanup_remaining:cleanupRemaining}}async function rollbackV1ToV2Migration(filesystem,plan,expectedHash=plan.plan_sha256){assertPlanHash(plan,expectedHash);const stateRoot=`.local/migrations/${plan.migration_id}`;const journalPath=`${stateRoot}/journal.json`;const journal=await readJournal(filesystem,journalPath);if(journal===null)throw new Error(`Migration journal not found: ${journalPath}`);const targetInspection=await inspectTargets(filesystem,plan.operations,true);const backups=new Map;for(const source of plan.source_fingerprint.files){const backupPath=`${stateRoot}/backup/${source.path}`;if(!await filesystem.exists(backupPath))throw new Error(`Migration backup is missing: ${backupPath}`);const backup=await readFile5(filesystem.resolve(backupPath));if(sha2565(backup)!==source.sha256){throw new MigrationSourceDivergenceError(`Migration backup diverged: ${backupPath}`)}if(plan.cleanup_paths.includes(source.path)&&await filesystem.exists(source.path)){const current=await readFile5(filesystem.resolve(source.path));if(sha2565(current)!==source.sha256){throw new MigrationSourceDivergenceError(`V1 source changed after migration: ${source.path}`)}}backups.set(source.path,backup)}if(targetInspection.identical.length===0&&journal.state==="rolled_back"){return{migration_id:plan.migration_id,status:"noop",removed:[],restored:[],journal_path:journalPath}}await writeJournal(filesystem,journalPath,plan,"rolling_back",journal.created,journal.reused);const removed=[];const createdTargets=new Set(journal.created);for(const operation of[...plan.operations].sort((left,right)=>{const leftConfig=left.kind==="activate-config"?0:1;const rightConfig=right.kind==="activate-config"?0:1;return leftConfig-rightConfig||right.target_path.localeCompare(left.target_path)})){if(createdTargets.has(operation.target_path)&&await filesystem.exists(operation.target_path)){await rm2(filesystem.resolve(operation.target_path),{force:true});removed.push(operation.target_path)}}const restored=[];for(const[path,backup]of backups){if(plan.cleanup_paths.includes(path)&&!await filesystem.exists(path)){await writeBytesAtomic(filesystem,path,backup);restored.push(path)}}await writeJournal(filesystem,journalPath,plan,"rolled_back",journal.created,journal.reused);return{migration_id:plan.migration_id,status:"rolled-back",removed:removed.sort(),restored:restored.sort(),journal_path:journalPath}}async function fingerprintV1Source2(filesystem){const paths=(await filesystem.listFiles(".agents")).filter(path=>!path.startsWith(".agents/config/")&&!path.startsWith(".agents/data/")).sort();const files=[];for(const path of paths){const bytes=await readFile5(filesystem.resolve(path));files.push({path,sha256:sha2565(bytes),size:bytes.byteLength})}return{sha256:hashCanonical3(files),files}}async function assertSourceFingerprint(filesystem,expected){const actual=await fingerprintV1Source2(filesystem);if(actual.sha256!==expected.sha256||JSON.stringify(actual.files)!==JSON.stringify(expected.files)){throw new MigrationSourceDivergenceError(`V1 source fingerprint changed: expected ${expected.sha256}, received ${actual.sha256}`)}}async function persistMigrationPlan(filesystem,stateRoot,plan){const path=`${stateRoot}/plan.json`;const existing=await readPersistedMigrationPlan(filesystem,plan.migration_id);if(existing!==null){if(existing.plan_sha256!==plan.plan_sha256||JSON.stringify(canonicalize4(existing))!==JSON.stringify(canonicalize4(plan))){throw new MigrationPlanHashError(`Persisted migration plan diverges: ${path}`)}return}await writeBytesAtomic(filesystem,path,Buffer.from(`${JSON.stringify(plan,null,2)}
|
|
2076
2076
|
`,"utf8"))}function assertPlanHash(plan,expectedHash){const{plan_sha256:actualHash,...withoutHash}=plan;const calculated=hashCanonical3(withoutHash);if(actualHash!==calculated||actualHash!==expectedHash){throw new MigrationPlanHashError(`Migration plan hash mismatch: expected ${expectedHash}, calculated ${calculated}`)}}async function inspectTargets(filesystem,operations,allowMissing=false){const identical=[];const missing=[];for(const operation of operations){if(!await filesystem.exists(operation.target_path)){missing.push(operation.target_path);continue}const target=await readFile5(filesystem.resolve(operation.target_path));const targetHash=sha2565(target);if(targetHash!==operation.target_sha256&&operation.source_path===operation.target_path&&targetHash===operation.source_sha256){missing.push(operation.target_path);continue}if(targetHash!==operation.target_sha256){throw new MigrationCollisionError(`Divergent migration target: ${operation.target_path}`)}identical.push(operation.target_path)}if(!allowMissing&&identical.length+missing.length!==operations.length){throw new MigrationCollisionError("Unable to inspect every migration target")}return{identical:identical.sort(),missing:missing.sort()}}async function commitOperation(filesystem,stateRoot,operation){const stagePath=`${stateRoot}/staging/${operation.target_path}`;if(await filesystem.exists(operation.target_path)){const existing=await readFile5(filesystem.resolve(operation.target_path));const existingHash=sha2565(existing);if(existingHash===operation.target_sha256){await rm2(filesystem.resolve(stagePath),{force:true});return"reused"}if(operation.source_path===operation.target_path&&existingHash===operation.source_sha256){const staged2=await readFile5(filesystem.resolve(stagePath));if(sha2565(staged2)!==operation.target_sha256){throw new MigrationCollisionError(`Divergent staged target: ${stagePath}`)}await rm2(filesystem.resolve(operation.target_path),{force:true});await rename2(filesystem.resolve(stagePath),filesystem.resolve(operation.target_path));return"created"}if(existingHash!==operation.target_sha256){throw new MigrationCollisionError(`Divergent migration target: ${operation.target_path}`)}}const staged=await readFile5(filesystem.resolve(stagePath));if(sha2565(staged)!==operation.target_sha256){throw new MigrationCollisionError(`Divergent staged target: ${stagePath}`)}const target=filesystem.resolve(operation.target_path);await mkdir2(dirname4(target),{recursive:true});if(await filesystem.exists(operation.target_path)){throw new MigrationCollisionError(`Migration target appeared during commit: ${operation.target_path}`)}await rename2(filesystem.resolve(stagePath),target);return"created"}async function readJournal(filesystem,path){if(!await filesystem.exists(path))return null;const parsed=JSON.parse(await filesystem.readText(path));return{...parsed,created:parsed.created??[],reused:parsed.reused??[]}}async function writeJournal(filesystem,path,plan,state,created=[],reused=[]){const journal={schema_version:1,migration_id:plan.migration_id,plan_sha256:plan.plan_sha256,source_sha256:plan.source_fingerprint.sha256,state,created:[...created].sort(),reused:[...reused].sort()};await writeBytesAtomic(filesystem,path,Buffer.from(`${JSON.stringify(journal,null,2)}
|
|
2077
|
-
`,"utf8"))}async function assertBackups(filesystem,stateRoot,fingerprint){for(const source of fingerprint.files){const path=`${stateRoot}/backup/${source.path}`;if(!await filesystem.exists(path)){throw new MigrationSourceDivergenceError(`Migration backup is missing: ${path}`)}const bytes=await readFile5(filesystem.resolve(path));if(sha2565(bytes)!==source.sha256){throw new MigrationSourceDivergenceError(`Migration backup diverged: ${path}`)}}}async function anyPathExists(filesystem,paths){for(const path of paths)if(await filesystem.exists(path))return true;return false}async function writeBytesAtomic(filesystem,path,bytes){const target=filesystem.resolve(path);await mkdir2(dirname4(target),{recursive:true});const temporary=`${target}.${process.pid}.${sha2565(bytes).slice(0,12)}.tmp`;await rm2(temporary,{force:true});await writeFile2(temporary,bytes,{flag:"wx"});if(await filesystem.exists(path))await rm2(target,{force:true});await rename2(temporary,target)}function configOrder2(path){if(path===".agents/config/project.yaml")return 0;if(path===".agents/config/framework.lock.yaml")return 1;return 2}function sha2565(value){return createHash28("sha256").update(value).digest("hex")}function hashCanonical3(value){return sha2565(JSON.stringify(canonicalize4(value)))}function canonicalize4(value){if(Array.isArray(value))return value.map(canonicalize4);if(value!==null&&typeof value==="object"){return Object.fromEntries(Object.entries(value).sort(([left],[right])=>left.localeCompare(right)).map(([key,nested])=>[key,canonicalize4(nested)]))}return value}var DISTRIBUTION_VERSION="3.0.0";async function verifyDistribution(filesystem){const checksumPath="checksums.sha256";if(!await filesystem.exists(checksumPath)){return{valid:false,invalid:[checksumPath]}}const lines=(await filesystem.readText(checksumPath)).split(/\r?\n/).filter(Boolean);const invalid=[];for(const line of lines){const match=line.match(/^([a-f0-9]{64}) {2}(.+)$/);if(!match?.[1]||!match[2]||!await filesystem.exists(match[2])){invalid.push(match?.[2]??line);continue}const actual=createHash29("sha256").update(await filesystem.readBytes(match[2])).digest("hex");if(actual!==match[1])invalid.push(match[2])}return{valid:invalid.length===0,invalid}}async function migrateProject(filesystem,dryRun=false){const path=".agents/manifest.yaml";const raw=parseYaml(await filesystem.readText(path));if(typeof raw==="object"&&raw!==null&&"schema_version"in raw){await new ManifestRepository(filesystem).read();return{from:1,to:1,changed:[],dryRun}}if(typeof raw!=="object"||raw===null||!("version"in raw)||!("project"in raw)){throw new Error("Unsupported legacy manifest; automatic migration is unsafe")}const legacy2=raw;if(legacy2.version!==1||typeof legacy2.project.name!=="string"){throw new Error("Unsupported legacy manifest version")}const migrated={schema_version:1,project:{id:typeof legacy2.project.id==="string"?legacy2.project.id:normalizeShortName(legacy2.project.name).toLowerCase(),name:legacy2.project.name,timezone:"America/Sao_Paulo"},framework:{version:DISTRIBUTION_VERSION},layout:{version:1,managed_namespace:".agents/managed",project_namespace:".agents/project"},profile:{id:"zaip-aios-stack"},agents:["codex","claude"],paths:{specs:".agents/specs",changes:".agents/changes",tasks:".agents/tasks",decisions:".agents/decisions",runs:".agents/runs"}};if(!dryRun)await filesystem.writeTextAtomic(path,serializeYaml(migrated));return{from:0,to:1,changed:[path],dryRun}}async function upgradeDistribution(workspaceRoot,sourcePath,dryRun=false){const root=resolve5(workspaceRoot);const source=resolve5(root,sourcePath);const target=resolve5(root,".agents/runtime");const backup=resolve5(root,".local/rollback/runtime");const fromRoot=relative5(root,source);if(fromRoot===".."||fromRoot.startsWith("../")||fromRoot.startsWith("..\\")||isAbsolute5(fromRoot)){throw new Error("Upgrade source escapes workspace")}if(source===target||source.startsWith(`${target}\\`)||source.startsWith(`${target}/`)){throw new Error("Upgrade source must not be inside the active distribution")}const verification=await verifyDistribution(new WorkspaceFileSystem(source));if(!verification.valid){throw new Error(`Upgrade source checksum failed: ${verification.invalid.join(", ")}`)}if(dryRun)return{changed:[".agents/runtime"],backup:".local/rollback/runtime",dryRun:true};await mkdir3(resolve5(root,".local/rollback"),{recursive:true});await rm3(backup,{recursive:true,force:true});const hadTarget=await new WorkspaceFileSystem(root).exists(".agents/runtime");if(hadTarget)await rename3(target,backup);try{await cp(source,target,{recursive:true,force:false,errorOnExist:true})}catch(error51){await rm3(target,{recursive:true,force:true});if(hadTarget)await rename3(backup,target);throw error51}return{changed:[".agents/runtime"],backup:".local/rollback/runtime",dryRun:false}}async function rollbackDistribution(workspaceRoot){const root=resolve5(workspaceRoot);const target=resolve5(root,".agents/runtime");const backup=resolve5(root,".local/rollback/runtime");await rm3(target,{recursive:true,force:true});await rename3(backup,target)}async function doctorProject(filesystem){const findings=[];for(const path of[".agents/manifest.yaml",".agents/constitution.md","AGENTS.md","CLAUDE.md"]){if(!await filesystem.exists(path)){findings.push({severity:"error",path,message:"Required ZAIP-AIOS file is missing"})}}if(!await filesystem.exists(".git")){findings.push({severity:"warning",path:".git",message:"Git-native audit requires a Git repository"})}return findings}init_cli_arguments();import{createHash as createHash30}from"node:crypto";import{cp as cp2,lstat as lstat3,mkdir as mkdir4,readdir as readdir2,readFile as readFile6,rename as rename4,rm as rm4}from"node:fs/promises";import{dirname as dirname5,relative as relative6,resolve as resolve6,sep as sep4}from"node:path";var MANIFEST=".zaip-managed.json";async function planManagedAssetInstalls(distributionRoot,workspaceRoot){const[dashboard,design]=await Promise.all([planDashboardInstall(distributionRoot,workspaceRoot),planDesignInstall(distributionRoot,workspaceRoot)]);return{dashboard,design}}async function applyManagedAssetInstalls(plans){const[dashboard,design]=await Promise.all([applyDashboardInstall(plans.dashboard),applyDesignInstall(plans.design)]);return{dashboard,design}}async function planDashboardInstall(distributionRoot,workspaceRoot){return planManagedAssetInstall(distributionRoot,workspaceRoot,"dashboard")}async function planDesignInstall(distributionRoot,workspaceRoot){return planManagedAssetInstall(distributionRoot,workspaceRoot,"design")}async function planManagedAssetInstall(distributionRoot,workspaceRoot,asset){const source=resolve6(distributionRoot,asset);const destination=resolve6(workspaceRoot,`.agents/${asset}`);const sourceManifest=await readAndValidateManifest(source,asset);await assertManifestFiles(source,sourceManifest,asset);const sourceFiles=new Map(sourceManifest.files.map(file2=>[file2.path,file2.sha256]));const sourcePaths=[...sourceFiles.keys(),MANIFEST].sort();if(!await exists(destination)){return result(asset,source,destination,sourcePaths.map(path=>`.agents/${asset}/${path}`),[],[],[],false)}const currentManifestPath=resolve6(destination,MANIFEST);if(!await exists(currentManifestPath)){return result(asset,source,destination,[],[],[],[`.agents/${asset}`],false)}let currentManifest;try{currentManifest=await readAndValidateManifest(destination,asset)}catch{return result(asset,source,destination,[],[],[],[`.agents/${asset}/${MANIFEST}`],false)}const currentFiles=new Map(currentManifest.files.map(file2=>[file2.path,file2.sha256]));const conflicts=[];const actual=await relativeFiles(destination);const known2=new Set([...currentFiles.keys(),MANIFEST]);for(const path of actual){if(!known2.has(path))conflicts.push(`.agents/${asset}/${path}`)}for(const[path,expected]of currentFiles){const absolute=safeResolve(destination,path);if(!await exists(absolute)||await hashFile(absolute)!==expected){conflicts.push(`.agents/${asset}/${path}`)}}if(conflicts.length>0){return result(asset,source,destination,[],[],[],[...new Set(conflicts)].sort(),false)}const created=[];const updated=[];const existing=[];for(const[path,expected]of sourceFiles){const portable=`.agents/${asset}/${path}`;const current=currentFiles.get(path);if(current===void 0)created.push(portable);else if(current===expected)existing.push(portable);else updated.push(portable)}for(const path of currentFiles.keys()){if(!sourceFiles.has(path))updated.push(`.agents/${asset}/${path}`)}updated.push(`.agents/${asset}/${MANIFEST}`);return result(asset,source,destination,created,updated,existing,[],false)}async function applyDashboardInstall(plan){return applyManagedAssetInstall(plan)}async function applyDesignInstall(plan){return applyManagedAssetInstall(plan)}async function applyManagedAssetInstall(plan){if(plan.conflicts.length>0)throw new Error(`${plan.asset} install has unresolved conflicts`);const parent=dirname5(plan.destination);const nonce=`${process.pid}-${Date.now()}`;const staging=resolve6(parent,`.${plan.asset}.zaip-new-${nonce}`);const backup=resolve6(parent,`.${plan.asset}.zaip-old-${nonce}`);await mkdir4(parent,{recursive:true});await cp2(plan.source,staging,{recursive:true,errorOnExist:true,force:false});const hadDestination=await exists(plan.destination);try{if(hadDestination)await rename4(plan.destination,backup);await rename4(staging,plan.destination);if(hadDestination)await rm4(backup,{recursive:true,force:true})}catch(error51){await rm4(staging,{recursive:true,force:true});if(hadDestination&&await exists(backup)&&!await exists(plan.destination)){await rename4(backup,plan.destination)}throw error51}return{...plan,applied:true}}async function validateInstalledDashboard(workspaceRoot){return validateInstalledManagedAsset(workspaceRoot,"dashboard")}async function validateInstalledDesign(workspaceRoot){return validateInstalledManagedAsset(workspaceRoot,"design")}async function validateInstalledManagedAsset(workspaceRoot,asset){const root=resolve6(workspaceRoot,`.agents/${asset}`);if(!await exists(root)){return[{path:`.agents/${asset}`,message:`Managed ZAIP ${asset} is missing`}]}let manifest;try{manifest=await readAndValidateManifest(root,asset)}catch(error51){return[{path:`.agents/${asset}/${MANIFEST}`,message:error51 instanceof Error?error51.message:String(error51)}]}const findings=[];for(const file2 of manifest.files){const absolute=safeResolve(root,file2.path);if(!await exists(absolute)){findings.push({path:`.agents/${asset}/${file2.path}`,message:"Managed file is missing"})}else if(await hashFile(absolute)!==file2.sha256){findings.push({path:`.agents/${asset}/${file2.path}`,message:"Managed file checksum drift"})}}return findings}async function readAndValidateManifest(root,asset){const parsed=JSON.parse(await readFile6(resolve6(root,MANIFEST),"utf8"));if(typeof parsed!=="object"||parsed===null)throw new Error(`Invalid ${asset} manifest`);const value=parsed;if(value.schemaVersion!==1||typeof value.version!=="string"||!Array.isArray(value.files)){throw new Error(`Invalid ${asset} manifest fields`)}const seen=new Set;const files=value.files.map(entry2=>{if(typeof entry2!=="object"||entry2===null)throw new Error(`Invalid ${asset} file`);const file2=entry2;if(typeof file2.path!=="string"||typeof file2.sha256!=="string"||!/^[a-f0-9]{64}$/.test(file2.sha256)){throw new Error(`Invalid ${asset} file fields`)}safeResolve(root,file2.path);if(seen.has(file2.path))throw new Error(`Duplicate ${asset} path: ${file2.path}`);seen.add(file2.path);return{path:file2.path,sha256:file2.sha256}});return{schemaVersion:1,version:value.version,files}}async function assertManifestFiles(root,manifest,asset){const actual=await relativeFiles(root);const expected=new Set([...manifest.files.map(file2=>file2.path),MANIFEST]);const extra=actual.filter(path=>!expected.has(path));if(extra.length>0)throw new Error(`Unmanaged ${asset} release files: ${extra.join(", ")}`);for(const file2 of manifest.files){const absolute=safeResolve(root,file2.path);if(!await exists(absolute))throw new Error(`${asset} release file missing: ${file2.path}`);if(await hashFile(absolute)!==file2.sha256){throw new Error(`${asset} release checksum mismatch: ${file2.path}`)}}}async function relativeFiles(root){const entries=await readdir2(root,{recursive:true,withFileTypes:true});return entries.filter(entry2=>entry2.isFile()).map(entry2=>relative6(root,resolve6(entry2.parentPath,entry2.name)).replaceAll("\\","/")).sort()}function safeResolve(root,portable){if(portable.length===0||portable.includes("\\")||portable.includes("\0")||portable.startsWith("/")||/^[A-Za-z]:/.test(portable)||portable.split("/").some(part=>part.length===0||part==="."||part==="..")){throw new Error(`Unsafe managed asset path: ${portable}`)}const destination=resolve6(root,portable);if(!destination.startsWith(`${resolve6(root)}${sep4}`)){throw new Error(`Managed asset path escapes root: ${portable}`)}return destination}async function hashFile(path){return createHash30("sha256").update(await readFile6(path)).digest("hex")}async function exists(path){return lstat3(path).then(()=>true,error51=>{if(error51 instanceof Error&&"code"in error51&&error51.code==="ENOENT")return false;throw error51})}function result(asset,source,destination,created,updated,existing,conflicts,applied){return{asset,source,destination,created:[...created].sort(),updated:[...new Set(updated)].sort(),existing:[...existing].sort(),conflicts:[...conflicts].sort(),applied}}import{basename,dirname as dirname6,resolve as resolve7}from"node:path";async function dashboardDoctorFindings(executable,workspaceRoot){if(executable===void 0)return[];const executableRoot=resolve7(dirname6(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve7(executableRoot,"..");if(basename(distributionRoot)!==".agents")return[];return(await validateInstalledDashboard(workspaceRoot)).map(finding3=>({severity:"error",code:"dashboard-drift",...finding3,state:"active"}))}async function designDoctorFindings(executable,workspaceRoot){if(executable===void 0)return[];const executableRoot=resolve7(dirname6(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve7(executableRoot,"..");if(basename(distributionRoot)!==".agents")return[];return(await validateInstalledDesign(workspaceRoot)).map(finding3=>({severity:"error",code:"design-drift",...finding3,state:"active"}))}async function managedAssetDoctorFindings(executable,workspaceRoot,filesystem){if(executable!==void 0&&filesystem!==void 0){const executableRoot=resolve7(dirname6(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve7(executableRoot,"..");if(await isFrameworkSourceWorkspace(filesystem,workspaceRoot,distributionRoot))return[]}return(await Promise.all([dashboardDoctorFindings(executable,workspaceRoot),designDoctorFindings(executable,workspaceRoot)])).flat()}async function isFrameworkSourceWorkspace(filesystem,root,distributionRoot){if(resolve7(root,".agents")!==distributionRoot||!await filesystem.exists("package.json")){return false}try{const manifest=JSON.parse(await filesystem.readText("package.json"));return manifest.name==="@zaip-ai/aios"}catch{return false}}async function frameworkSourceTemplateFiles(filesystem){const packagedAgentsRoot=basename(filesystem.root)===".agents";const roots2=packagedAgentsRoot?["config/agents","rules","requirements","skills","zaip-aios","tools"]:[".agents/rules",".agents/requirements",".agents/skills",".agents/zaip-aios",".agents/tools"];const paths=(await Promise.all(roots2.map(path=>filesystem.listFiles(path)))).flat().filter(path=>!path.endsWith("/.gitkeep")).sort();return Promise.all(paths.map(async path=>({path:packagedAgentsRoot?`.agents/${path}`:path,content:await filesystem.readText(path)})))}init_cli_arguments();async function readMigrationOptions(filesystem,parsed){const path=parsed.options.promotions;if(path===void 0)return{};const decoded=JSON.parse(await filesystem.readText(path));const promotions=Array.isArray(decoded)?decoded:typeof decoded==="object"&&decoded!==null&&"promotions"in decoded?decoded.promotions:void 0;if(!Array.isArray(promotions)){throw new UsageError("--promotions must point to a JSON array or an object containing a promotions array")}return{promotions}}function migrationPlanOutput(plan,verbose){const operationCounts=Object.fromEntries([...new Set(plan.operations.map(operation=>operation.category))].sort().map(category=>[category,plan.operations.filter(operation=>operation.category===category).length]));return{schema_version:plan.schema_version,migration_id:plan.migration_id,from_layout:plan.from_layout,to_layout:plan.to_layout,source_fingerprint:{sha256:plan.source_fingerprint.sha256,file_count:plan.source_fingerprint.files.length,total_bytes:plan.source_fingerprint.files.reduce((total,file2)=>total+file2.size,0)},promotions:plan.promotions,counts:plan.counts,operation_counts:operationCounts,findings:plan.findings,cleanup:{path_count:plan.cleanup_paths.length,roots:plan.cleanup_roots},plan_sha256:plan.plan_sha256,...verbose?{operations:plan.operations.map(({content_base64:_,...operation})=>operation),source_files:plan.source_fingerprint.files,cleanup_paths:plan.cleanup_paths}:{}}}var EXIT={success:0,error:1,conformity:3,security:5,prerequisite:6};async function runDistributionCommand(context){const{area,action,parsed,filesystem,root,json:json2}=context;if(area==="setup"){const executable=process.argv[1];let templateFiles=[];let assetPlans=null;if(executable!==void 0){const executableRoot=resolve8(dirname7(executable),"..");const distributionRoot=basename2(executableRoot)===".agents"?executableRoot:resolve8(executableRoot,"..");if(basename2(distributionRoot)===".agents"){const distributionFilesystem=new WorkspaceFileSystem(distributionRoot);const runtimeFilesystem=new WorkspaceFileSystem(basename2(executableRoot)===".agents"?distributionRoot:executableRoot);const verification=await verifyDistribution(runtimeFilesystem);if(!verification.valid){output(verification,json2,true);return EXIT.security}const frameworkSource=await isFrameworkSourceWorkspace(filesystem,root,distributionRoot);templateFiles=frameworkSource?await frameworkSourceTemplateFiles(filesystem):await frameworkSourceTemplateFiles(distributionFilesystem);if(!frameworkSource)assetPlans=await planManagedAssetInstalls(distributionRoot,root)}}const hasLegacyManifest=await filesystem.exists(".agents/manifest.yaml");const hasV2Config=await filesystem.exists(".agents/config/project.yaml")||await filesystem.exists(".agents/config/framework.lock.yaml");if(hasLegacyManifest&&!hasV2Config){throw new UsageError("V1 workspace is read-only: review `migrate plan`, then run `migrate apply`")}const options={projectName:parsed.options.name??basename2(root),bootstrapTask:parsed.flags.has("bootstrap-task"),templateFiles:templateFiles.filter(file2=>/^(?:\.agents\/config\/agents\/catalog\.yaml|\.agents\/(?:rules|requirements|skills)\/)/.test(file2.path))};const dryRun=parsed.flags.has("dry-run");if(assetPlans!==null){const preflight=await setupProjectV2(filesystem,{...options,dryRun:true});const conflicts=[...preflight.conflicts,...Object.values(assetPlans).flatMap(plan=>plan.conflicts)].sort();if(dryRun||conflicts.length>0){const result3={...preflight,conflicts,...assetPlans};output(result3,json2);return conflicts.length>0?EXIT.conformity:EXIT.success}}const setup=await setupProjectV2(filesystem,{...options,dryRun});const installedAssets=assetPlans!==null&&setup.applied?await applyManagedAssetInstalls(assetPlans):assetPlans;const result2=installedAssets===null?setup:{...setup,...installedAssets};output(result2,json2);return setup.conflicts.length>0||!setup.dryRun&&!setup.applied?EXIT.conformity:EXIT.success}if(area==="doctor"){const hasV2Config=await filesystem.exists(".agents/config/project.yaml")||await filesystem.exists(".agents/config/framework.lock.yaml");const findings=hasV2Config?await doctorProjectV2(filesystem):await doctorProject(filesystem);const assetFindings=await managedAssetDoctorFindings(process.argv[1],root,filesystem);const combinedFindings=[...findings,...assetFindings];output({valid:combinedFindings.every(item=>item.severity!=="error"),findings:combinedFindings},json2);return combinedFindings.some(item=>item.severity==="error")?EXIT.prerequisite:EXIT.success}if(area==="migrate"){if(action==="legacy-manifest"){if(await filesystem.exists(".agents/config/project.yaml")||await filesystem.exists(".agents/config/framework.lock.yaml")){throw new UsageError("legacy-manifest is disabled after V2 activation")}output(await migrateProject(filesystem,parsed.flags.has("dry-run")),json2);return EXIT.success}const migrationOptions=await readMigrationOptions(filesystem,parsed);if(action==="plan"||action===void 0&&parsed.flags.has("dry-run")){const plan=await planV1ToV2Migration(filesystem,migrationOptions);output(migrationPlanOutput(plan,parsed.flags.has("verbose")),json2);return EXIT.success}if(action==="apply"){requireOptions(parsed.options,["plan-hash"]);const plan=parsed.options.migration===void 0?await planV1ToV2Migration(filesystem,migrationOptions):await readPersistedMigrationPlan(filesystem,parsed.options.migration);if(plan===null){throw new UsageError(`Migration plan not found: ${parsed.options.migration}`)}output(await applyV1ToV2Migration(filesystem,plan,parsed.options["plan-hash"]),json2);return EXIT.success}if(action==="status"||action==="rollback"){requireOptions(parsed.options,["migration"]);const migrationId=parsed.options.migration;const plan=await readPersistedMigrationPlan(filesystem,migrationId);if(plan===null)throw new UsageError(`Migration plan not found: ${migrationId}`);if(action==="rollback"){output(await rollbackV1ToV2Migration(filesystem,plan,parsed.options["plan-hash"]??plan.plan_sha256),json2)}else{output({migration_id:migrationId,plan_hash:plan.plan_sha256,status:await inspectV1ToV2Migration(filesystem,plan),plan:migrationPlanOutput(plan,parsed.flags.has("verbose"))},json2)}return EXIT.success}throw new UsageError("migrate requires plan, apply --plan-hash HASH, status --migration ID, or rollback --migration ID")}if(area==="upgrade"){if(parsed.flags.has("rollback")){await rollbackDistribution(root);output({rolledBack:true},json2);return EXIT.success}const source=parsed.options.from;if(source===void 0)throw new UsageError("upgrade requires --from PATH or --rollback");output(await upgradeDistribution(root,source,parsed.flags.has("dry-run")),json2);return EXIT.success}return null}init_src();init_cli_arguments();import{dirname as dirname8}from"node:path";async function persistEvalReportV2(filesystem,layout,report,shortName,parsed){const scope=decisionV2ScopeOption(parsed);if(scope===void 0){throw new UsageError("V2 eval persistence requires --change or --execution (or use --no-write)")}const ownerPath=layout.activePath(scope.type,scope.id);if(!await filesystem.exists(ownerPath)){throw new UsageError(`${scope.type} not found for eval evidence: ${scope.id}`)}const id=createId("EVAL",shortName,{timeZone:layout.project.timezone});const path=`${dirname8(ownerPath)}/artifacts/evals/${id}.json`;await filesystem.writeTextExclusive(path,`${JSON.stringify({schema_version:2,id,generated_at:new Date().toISOString(),report},null,2)}
|
|
2077
|
+
`,"utf8"))}async function assertBackups(filesystem,stateRoot,fingerprint){for(const source of fingerprint.files){const path=`${stateRoot}/backup/${source.path}`;if(!await filesystem.exists(path)){throw new MigrationSourceDivergenceError(`Migration backup is missing: ${path}`)}const bytes=await readFile5(filesystem.resolve(path));if(sha2565(bytes)!==source.sha256){throw new MigrationSourceDivergenceError(`Migration backup diverged: ${path}`)}}}async function anyPathExists(filesystem,paths){for(const path of paths)if(await filesystem.exists(path))return true;return false}async function writeBytesAtomic(filesystem,path,bytes){const target=filesystem.resolve(path);await mkdir2(dirname4(target),{recursive:true});const temporary=`${target}.${process.pid}.${sha2565(bytes).slice(0,12)}.tmp`;await rm2(temporary,{force:true});await writeFile2(temporary,bytes,{flag:"wx"});if(await filesystem.exists(path))await rm2(target,{force:true});await rename2(temporary,target)}function configOrder2(path){if(path===".agents/config/project.yaml")return 0;if(path===".agents/config/framework.lock.yaml")return 1;return 2}function sha2565(value){return createHash28("sha256").update(value).digest("hex")}function hashCanonical3(value){return sha2565(JSON.stringify(canonicalize4(value)))}function canonicalize4(value){if(Array.isArray(value))return value.map(canonicalize4);if(value!==null&&typeof value==="object"){return Object.fromEntries(Object.entries(value).sort(([left],[right])=>left.localeCompare(right)).map(([key,nested])=>[key,canonicalize4(nested)]))}return value}var DISTRIBUTION_VERSION="3.2.0";async function verifyDistribution(filesystem){const checksumPath="checksums.sha256";if(!await filesystem.exists(checksumPath)){return{valid:false,invalid:[checksumPath]}}const lines=(await filesystem.readText(checksumPath)).split(/\r?\n/).filter(Boolean);const invalid=[];for(const line of lines){const match=line.match(/^([a-f0-9]{64}) {2}(.+)$/);if(!match?.[1]||!match[2]||!await filesystem.exists(match[2])){invalid.push(match?.[2]??line);continue}const actual=createHash29("sha256").update(await filesystem.readBytes(match[2])).digest("hex");if(actual!==match[1])invalid.push(match[2])}return{valid:invalid.length===0,invalid}}async function migrateProject(filesystem,dryRun=false){const path=".agents/manifest.yaml";const raw=parseYaml(await filesystem.readText(path));if(typeof raw==="object"&&raw!==null&&"schema_version"in raw){await new ManifestRepository(filesystem).read();return{from:1,to:1,changed:[],dryRun}}if(typeof raw!=="object"||raw===null||!("version"in raw)||!("project"in raw)){throw new Error("Unsupported legacy manifest; automatic migration is unsafe")}const legacy2=raw;if(legacy2.version!==1||typeof legacy2.project.name!=="string"){throw new Error("Unsupported legacy manifest version")}const migrated={schema_version:1,project:{id:typeof legacy2.project.id==="string"?legacy2.project.id:normalizeShortName(legacy2.project.name).toLowerCase(),name:legacy2.project.name,timezone:"America/Sao_Paulo"},framework:{version:DISTRIBUTION_VERSION},layout:{version:1,managed_namespace:".agents/managed",project_namespace:".agents/project"},profile:{id:"zaip-aios-stack"},agents:["codex","claude"],paths:{specs:".agents/specs",changes:".agents/changes",tasks:".agents/tasks",decisions:".agents/decisions",runs:".agents/runs"}};if(!dryRun)await filesystem.writeTextAtomic(path,serializeYaml(migrated));return{from:0,to:1,changed:[path],dryRun}}async function upgradeDistribution(workspaceRoot,sourcePath,dryRun=false){const root=resolve5(workspaceRoot);const source=resolve5(root,sourcePath);const target=resolve5(root,".agents/runtime");const backup=resolve5(root,".local/rollback/runtime");const fromRoot=relative5(root,source);if(fromRoot===".."||fromRoot.startsWith("../")||fromRoot.startsWith("..\\")||isAbsolute5(fromRoot)){throw new Error("Upgrade source escapes workspace")}if(source===target||source.startsWith(`${target}\\`)||source.startsWith(`${target}/`)){throw new Error("Upgrade source must not be inside the active distribution")}const verification=await verifyDistribution(new WorkspaceFileSystem(source));if(!verification.valid){throw new Error(`Upgrade source checksum failed: ${verification.invalid.join(", ")}`)}if(dryRun)return{changed:[".agents/runtime"],backup:".local/rollback/runtime",dryRun:true};await mkdir3(resolve5(root,".local/rollback"),{recursive:true});await rm3(backup,{recursive:true,force:true});const hadTarget=await new WorkspaceFileSystem(root).exists(".agents/runtime");if(hadTarget)await rename3(target,backup);try{await cp(source,target,{recursive:true,force:false,errorOnExist:true})}catch(error51){await rm3(target,{recursive:true,force:true});if(hadTarget)await rename3(backup,target);throw error51}return{changed:[".agents/runtime"],backup:".local/rollback/runtime",dryRun:false}}async function rollbackDistribution(workspaceRoot){const root=resolve5(workspaceRoot);const target=resolve5(root,".agents/runtime");const backup=resolve5(root,".local/rollback/runtime");await rm3(target,{recursive:true,force:true});await rename3(backup,target)}async function doctorProject(filesystem){const findings=[];for(const path of[".agents/manifest.yaml",".agents/constitution.md","AGENTS.md","CLAUDE.md"]){if(!await filesystem.exists(path)){findings.push({severity:"error",path,message:"Required ZAIP-AIOS file is missing"})}}if(!await filesystem.exists(".git")){findings.push({severity:"warning",path:".git",message:"Git-native audit requires a Git repository"})}return findings}init_cli_arguments();import{createHash as createHash30}from"node:crypto";import{cp as cp2,lstat as lstat3,mkdir as mkdir4,readdir as readdir2,readFile as readFile6,rename as rename4,rm as rm4}from"node:fs/promises";import{dirname as dirname5,relative as relative6,resolve as resolve6,sep as sep4}from"node:path";var MANIFEST=".zaip-managed.json";async function planManagedAssetInstalls(distributionRoot,workspaceRoot){const[dashboard,design]=await Promise.all([planDashboardInstall(distributionRoot,workspaceRoot),planDesignInstall(distributionRoot,workspaceRoot)]);return{dashboard,design}}async function applyManagedAssetInstalls(plans){const[dashboard,design]=await Promise.all([applyDashboardInstall(plans.dashboard),applyDesignInstall(plans.design)]);return{dashboard,design}}async function planDashboardInstall(distributionRoot,workspaceRoot){return planManagedAssetInstall(distributionRoot,workspaceRoot,"dashboard")}async function planDesignInstall(distributionRoot,workspaceRoot){return planManagedAssetInstall(distributionRoot,workspaceRoot,"design")}async function planManagedAssetInstall(distributionRoot,workspaceRoot,asset){const source=resolve6(distributionRoot,asset);const destination=resolve6(workspaceRoot,`.agents/${asset}`);const sourceManifest=await readAndValidateManifest(source,asset);await assertManifestFiles(source,sourceManifest,asset);const sourceFiles=new Map(sourceManifest.files.map(file2=>[file2.path,file2.sha256]));const sourcePaths=[...sourceFiles.keys(),MANIFEST].sort();if(!await exists(destination)){return result(asset,source,destination,sourcePaths.map(path=>`.agents/${asset}/${path}`),[],[],[],false)}const currentManifestPath=resolve6(destination,MANIFEST);if(!await exists(currentManifestPath)){return result(asset,source,destination,[],[],[],[`.agents/${asset}`],false)}let currentManifest;try{currentManifest=await readAndValidateManifest(destination,asset)}catch{return result(asset,source,destination,[],[],[],[`.agents/${asset}/${MANIFEST}`],false)}const currentFiles=new Map(currentManifest.files.map(file2=>[file2.path,file2.sha256]));const conflicts=[];const actual=await relativeFiles(destination);const known2=new Set([...currentFiles.keys(),MANIFEST]);for(const path of actual){if(!known2.has(path))conflicts.push(`.agents/${asset}/${path}`)}for(const[path,expected]of currentFiles){const absolute=safeResolve(destination,path);if(!await exists(absolute)||await hashFile(absolute)!==expected){conflicts.push(`.agents/${asset}/${path}`)}}if(conflicts.length>0){return result(asset,source,destination,[],[],[],[...new Set(conflicts)].sort(),false)}const created=[];const updated=[];const existing=[];for(const[path,expected]of sourceFiles){const portable=`.agents/${asset}/${path}`;const current=currentFiles.get(path);if(current===void 0)created.push(portable);else if(current===expected)existing.push(portable);else updated.push(portable)}for(const path of currentFiles.keys()){if(!sourceFiles.has(path))updated.push(`.agents/${asset}/${path}`)}updated.push(`.agents/${asset}/${MANIFEST}`);return result(asset,source,destination,created,updated,existing,[],false)}async function applyDashboardInstall(plan){return applyManagedAssetInstall(plan)}async function applyDesignInstall(plan){return applyManagedAssetInstall(plan)}async function applyManagedAssetInstall(plan){if(plan.conflicts.length>0)throw new Error(`${plan.asset} install has unresolved conflicts`);const parent=dirname5(plan.destination);const nonce=`${process.pid}-${Date.now()}`;const staging=resolve6(parent,`.${plan.asset}.zaip-new-${nonce}`);const backup=resolve6(parent,`.${plan.asset}.zaip-old-${nonce}`);await mkdir4(parent,{recursive:true});await cp2(plan.source,staging,{recursive:true,errorOnExist:true,force:false});const hadDestination=await exists(plan.destination);try{if(hadDestination)await rename4(plan.destination,backup);await rename4(staging,plan.destination);if(hadDestination)await rm4(backup,{recursive:true,force:true})}catch(error51){await rm4(staging,{recursive:true,force:true});if(hadDestination&&await exists(backup)&&!await exists(plan.destination)){await rename4(backup,plan.destination)}throw error51}return{...plan,applied:true}}async function validateInstalledDashboard(workspaceRoot){return validateInstalledManagedAsset(workspaceRoot,"dashboard")}async function validateInstalledDesign(workspaceRoot){return validateInstalledManagedAsset(workspaceRoot,"design")}async function validateInstalledManagedAsset(workspaceRoot,asset){const root=resolve6(workspaceRoot,`.agents/${asset}`);if(!await exists(root)){return[{path:`.agents/${asset}`,message:`Managed ZAIP ${asset} is missing`}]}let manifest;try{manifest=await readAndValidateManifest(root,asset)}catch(error51){return[{path:`.agents/${asset}/${MANIFEST}`,message:error51 instanceof Error?error51.message:String(error51)}]}const findings=[];for(const file2 of manifest.files){const absolute=safeResolve(root,file2.path);if(!await exists(absolute)){findings.push({path:`.agents/${asset}/${file2.path}`,message:"Managed file is missing"})}else if(await hashFile(absolute)!==file2.sha256){findings.push({path:`.agents/${asset}/${file2.path}`,message:"Managed file checksum drift"})}}return findings}async function readAndValidateManifest(root,asset){const parsed=JSON.parse(await readFile6(resolve6(root,MANIFEST),"utf8"));if(typeof parsed!=="object"||parsed===null)throw new Error(`Invalid ${asset} manifest`);const value=parsed;if(value.schemaVersion!==1||typeof value.version!=="string"||!Array.isArray(value.files)){throw new Error(`Invalid ${asset} manifest fields`)}const seen=new Set;const files=value.files.map(entry2=>{if(typeof entry2!=="object"||entry2===null)throw new Error(`Invalid ${asset} file`);const file2=entry2;if(typeof file2.path!=="string"||typeof file2.sha256!=="string"||!/^[a-f0-9]{64}$/.test(file2.sha256)){throw new Error(`Invalid ${asset} file fields`)}safeResolve(root,file2.path);if(seen.has(file2.path))throw new Error(`Duplicate ${asset} path: ${file2.path}`);seen.add(file2.path);return{path:file2.path,sha256:file2.sha256}});return{schemaVersion:1,version:value.version,files}}async function assertManifestFiles(root,manifest,asset){const actual=await relativeFiles(root);const expected=new Set([...manifest.files.map(file2=>file2.path),MANIFEST]);const extra=actual.filter(path=>!expected.has(path));if(extra.length>0)throw new Error(`Unmanaged ${asset} release files: ${extra.join(", ")}`);for(const file2 of manifest.files){const absolute=safeResolve(root,file2.path);if(!await exists(absolute))throw new Error(`${asset} release file missing: ${file2.path}`);if(await hashFile(absolute)!==file2.sha256){throw new Error(`${asset} release checksum mismatch: ${file2.path}`)}}}async function relativeFiles(root){const entries=await readdir2(root,{recursive:true,withFileTypes:true});return entries.filter(entry2=>entry2.isFile()).map(entry2=>relative6(root,resolve6(entry2.parentPath,entry2.name)).replaceAll("\\","/")).sort()}function safeResolve(root,portable){if(portable.length===0||portable.includes("\\")||portable.includes("\0")||portable.startsWith("/")||/^[A-Za-z]:/.test(portable)||portable.split("/").some(part=>part.length===0||part==="."||part==="..")){throw new Error(`Unsafe managed asset path: ${portable}`)}const destination=resolve6(root,portable);if(!destination.startsWith(`${resolve6(root)}${sep4}`)){throw new Error(`Managed asset path escapes root: ${portable}`)}return destination}async function hashFile(path){return createHash30("sha256").update(await readFile6(path)).digest("hex")}async function exists(path){return lstat3(path).then(()=>true,error51=>{if(error51 instanceof Error&&"code"in error51&&error51.code==="ENOENT")return false;throw error51})}function result(asset,source,destination,created,updated,existing,conflicts,applied){return{asset,source,destination,created:[...created].sort(),updated:[...new Set(updated)].sort(),existing:[...existing].sort(),conflicts:[...conflicts].sort(),applied}}import{basename,dirname as dirname6,resolve as resolve7}from"node:path";async function dashboardDoctorFindings(executable,workspaceRoot){if(executable===void 0)return[];const executableRoot=resolve7(dirname6(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve7(executableRoot,"..");if(basename(distributionRoot)!==".agents")return[];return(await validateInstalledDashboard(workspaceRoot)).map(finding3=>({severity:"error",code:"dashboard-drift",...finding3,state:"active"}))}async function designDoctorFindings(executable,workspaceRoot){if(executable===void 0)return[];const executableRoot=resolve7(dirname6(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve7(executableRoot,"..");if(basename(distributionRoot)!==".agents")return[];return(await validateInstalledDesign(workspaceRoot)).map(finding3=>({severity:"error",code:"design-drift",...finding3,state:"active"}))}async function managedAssetDoctorFindings(executable,workspaceRoot,filesystem){if(executable!==void 0&&filesystem!==void 0){const executableRoot=resolve7(dirname6(executable),"..");const distributionRoot=basename(executableRoot)===".agents"?executableRoot:resolve7(executableRoot,"..");if(await isFrameworkSourceWorkspace(filesystem,workspaceRoot,distributionRoot))return[]}return(await Promise.all([dashboardDoctorFindings(executable,workspaceRoot),designDoctorFindings(executable,workspaceRoot)])).flat()}async function isFrameworkSourceWorkspace(filesystem,root,distributionRoot){if(resolve7(root,".agents")!==distributionRoot||!await filesystem.exists("package.json")){return false}try{const manifest=JSON.parse(await filesystem.readText("package.json"));return manifest.name==="@zaip-ai/aios"}catch{return false}}async function frameworkSourceTemplateFiles(filesystem){const packagedAgentsRoot=basename(filesystem.root)===".agents";const roots2=packagedAgentsRoot?["config/agents","rules","requirements","skills","zaip-aios","tools"]:[".agents/rules",".agents/requirements",".agents/skills",".agents/zaip-aios",".agents/tools"];const paths=(await Promise.all(roots2.map(path=>filesystem.listFiles(path)))).flat().filter(path=>!path.endsWith("/.gitkeep")).sort();return Promise.all(paths.map(async path=>({path:packagedAgentsRoot?`.agents/${path}`:path,content:await filesystem.readText(path)})))}init_cli_arguments();async function readMigrationOptions(filesystem,parsed){const path=parsed.options.promotions;if(path===void 0)return{};const decoded=JSON.parse(await filesystem.readText(path));const promotions=Array.isArray(decoded)?decoded:typeof decoded==="object"&&decoded!==null&&"promotions"in decoded?decoded.promotions:void 0;if(!Array.isArray(promotions)){throw new UsageError("--promotions must point to a JSON array or an object containing a promotions array")}return{promotions}}function migrationPlanOutput(plan,verbose){const operationCounts=Object.fromEntries([...new Set(plan.operations.map(operation=>operation.category))].sort().map(category=>[category,plan.operations.filter(operation=>operation.category===category).length]));return{schema_version:plan.schema_version,migration_id:plan.migration_id,from_layout:plan.from_layout,to_layout:plan.to_layout,source_fingerprint:{sha256:plan.source_fingerprint.sha256,file_count:plan.source_fingerprint.files.length,total_bytes:plan.source_fingerprint.files.reduce((total,file2)=>total+file2.size,0)},promotions:plan.promotions,counts:plan.counts,operation_counts:operationCounts,findings:plan.findings,cleanup:{path_count:plan.cleanup_paths.length,roots:plan.cleanup_roots},plan_sha256:plan.plan_sha256,...verbose?{operations:plan.operations.map(({content_base64:_,...operation})=>operation),source_files:plan.source_fingerprint.files,cleanup_paths:plan.cleanup_paths}:{}}}var EXIT={success:0,error:1,conformity:3,security:5,prerequisite:6};async function runDistributionCommand(context){const{area,action,parsed,filesystem,root,json:json2}=context;if(area==="setup"){const executable=process.argv[1];let templateFiles=[];let assetPlans=null;if(executable!==void 0){const executableRoot=resolve8(dirname7(executable),"..");const distributionRoot=basename2(executableRoot)===".agents"?executableRoot:resolve8(executableRoot,"..");if(basename2(distributionRoot)===".agents"){const distributionFilesystem=new WorkspaceFileSystem(distributionRoot);const runtimeFilesystem=new WorkspaceFileSystem(basename2(executableRoot)===".agents"?distributionRoot:executableRoot);const verification=await verifyDistribution(runtimeFilesystem);if(!verification.valid){output(verification,json2,true);return EXIT.security}const frameworkSource=await isFrameworkSourceWorkspace(filesystem,root,distributionRoot);templateFiles=frameworkSource?await frameworkSourceTemplateFiles(filesystem):await frameworkSourceTemplateFiles(distributionFilesystem);if(!frameworkSource)assetPlans=await planManagedAssetInstalls(distributionRoot,root)}}const hasLegacyManifest=await filesystem.exists(".agents/manifest.yaml");const hasV2Config=await filesystem.exists(".agents/config/project.yaml")||await filesystem.exists(".agents/config/framework.lock.yaml");if(hasLegacyManifest&&!hasV2Config){throw new UsageError("V1 workspace is read-only: review `migrate plan`, then run `migrate apply`")}const options={projectName:parsed.options.name??basename2(root),bootstrapTask:parsed.flags.has("bootstrap-task"),templateFiles:templateFiles.filter(file2=>/^(?:\.agents\/config\/agents\/catalog\.yaml|\.agents\/(?:rules|requirements|skills)\/)/.test(file2.path))};const dryRun=parsed.flags.has("dry-run");if(assetPlans!==null){const preflight=await setupProjectV2(filesystem,{...options,dryRun:true});const conflicts=[...preflight.conflicts,...Object.values(assetPlans).flatMap(plan=>plan.conflicts)].sort();if(dryRun||conflicts.length>0){const result3={...preflight,conflicts,...assetPlans};output(result3,json2);return conflicts.length>0?EXIT.conformity:EXIT.success}}const setup=await setupProjectV2(filesystem,{...options,dryRun});const installedAssets=assetPlans!==null&&setup.applied?await applyManagedAssetInstalls(assetPlans):assetPlans;const result2=installedAssets===null?setup:{...setup,...installedAssets};output(result2,json2);return setup.conflicts.length>0||!setup.dryRun&&!setup.applied?EXIT.conformity:EXIT.success}if(area==="doctor"){const hasV2Config=await filesystem.exists(".agents/config/project.yaml")||await filesystem.exists(".agents/config/framework.lock.yaml");const findings=hasV2Config?await doctorProjectV2(filesystem):await doctorProject(filesystem);const assetFindings=await managedAssetDoctorFindings(process.argv[1],root,filesystem);const combinedFindings=[...findings,...assetFindings];output({valid:combinedFindings.every(item=>item.severity!=="error"),findings:combinedFindings},json2);return combinedFindings.some(item=>item.severity==="error")?EXIT.prerequisite:EXIT.success}if(area==="migrate"){if(action==="legacy-manifest"){if(await filesystem.exists(".agents/config/project.yaml")||await filesystem.exists(".agents/config/framework.lock.yaml")){throw new UsageError("legacy-manifest is disabled after V2 activation")}output(await migrateProject(filesystem,parsed.flags.has("dry-run")),json2);return EXIT.success}const migrationOptions=await readMigrationOptions(filesystem,parsed);if(action==="plan"||action===void 0&&parsed.flags.has("dry-run")){const plan=await planV1ToV2Migration(filesystem,migrationOptions);output(migrationPlanOutput(plan,parsed.flags.has("verbose")),json2);return EXIT.success}if(action==="apply"){requireOptions(parsed.options,["plan-hash"]);const plan=parsed.options.migration===void 0?await planV1ToV2Migration(filesystem,migrationOptions):await readPersistedMigrationPlan(filesystem,parsed.options.migration);if(plan===null){throw new UsageError(`Migration plan not found: ${parsed.options.migration}`)}output(await applyV1ToV2Migration(filesystem,plan,parsed.options["plan-hash"]),json2);return EXIT.success}if(action==="status"||action==="rollback"){requireOptions(parsed.options,["migration"]);const migrationId=parsed.options.migration;const plan=await readPersistedMigrationPlan(filesystem,migrationId);if(plan===null)throw new UsageError(`Migration plan not found: ${migrationId}`);if(action==="rollback"){output(await rollbackV1ToV2Migration(filesystem,plan,parsed.options["plan-hash"]??plan.plan_sha256),json2)}else{output({migration_id:migrationId,plan_hash:plan.plan_sha256,status:await inspectV1ToV2Migration(filesystem,plan),plan:migrationPlanOutput(plan,parsed.flags.has("verbose"))},json2)}return EXIT.success}throw new UsageError("migrate requires plan, apply --plan-hash HASH, status --migration ID, or rollback --migration ID")}if(area==="upgrade"){if(parsed.flags.has("rollback")){await rollbackDistribution(root);output({rolledBack:true},json2);return EXIT.success}const source=parsed.options.from;if(source===void 0)throw new UsageError("upgrade requires --from PATH or --rollback");output(await upgradeDistribution(root,source,parsed.flags.has("dry-run")),json2);return EXIT.success}return null}init_src();init_cli_arguments();import{dirname as dirname8}from"node:path";async function persistEvalReportV2(filesystem,layout,report,shortName,parsed){const scope=decisionV2ScopeOption(parsed);if(scope===void 0){throw new UsageError("V2 eval persistence requires --change or --execution (or use --no-write)")}const ownerPath=layout.activePath(scope.type,scope.id);if(!await filesystem.exists(ownerPath)){throw new UsageError(`${scope.type} not found for eval evidence: ${scope.id}`)}const id=createId("EVAL",shortName,{timeZone:layout.project.timezone});const path=`${dirname8(ownerPath)}/artifacts/evals/${id}.json`;await filesystem.writeTextExclusive(path,`${JSON.stringify({schema_version:2,id,generated_at:new Date().toISOString(),report},null,2)}
|
|
2078
2078
|
`);return{id,path}}init_src3();init_src4();init_src5();init_src();init_src5();import{createHash as createHash32}from"node:crypto";init_cli_arguments();function allocateInvocationBudget(input,children){if(input.policy.autonomy)return new Map(children.map(child=>[child.id,null]));const total=input.policy.max_total_invocations;const explicit=new Map(children.flatMap(child=>{const max=input.spec_execution_policies[child.spec_id]?.max_total_invocations;return max===void 0?[]:[[child.id,max]]}));if(total===null){return new Map(children.map(child=>[child.id,explicit.get(child.id)??null]))}const taskCountByChild=new Map;for(const task of input.tasks){if(task.child_execution_id===void 0)continue;taskCountByChild.set(task.child_execution_id,(taskCountByChild.get(task.child_execution_id)??0)+1)}const parentWeight=1+input.tasks.filter(task=>task.child_execution_id===void 0).length;const weights=children.filter(child=>!explicit.has(child.id)).map(child=>({id:child.id,weight:1+(taskCountByChild.get(child.id)??0)}));const reserved=[...explicit.values()].reduce((sum,value)=>sum+(value??0),0);if(total<parentWeight+children.length+reserved){throw new UsageError(`Global invocation budget ${total} cannot fund isolated SPEC budgets and the parent finalizer`)}const distributable=total-parentWeight-children.length-reserved;const totalWeight=parentWeight+weights.reduce((sum,item)=>sum+item.weight,0);return new Map([...children.filter(child=>explicit.has(child.id)).map(child=>[child.id,explicit.get(child.id)??null]),...weights.map(item=>[item.id,1+Math.floor(distributable*item.weight/totalWeight)])])}init_cli_arguments();function resolveExecutionRuntime(config2,limits={plan:1,provider:1,squad:1},source="task"){if(!config2.execution||config2.execution.runtime==="manual"||source==="interaction"||config2.execution.runtime==="managed"&&source==="task")return{runtime:"manual"};const autonomous=config2.execution.autonomous;if(config2.autonomy?.version===1&&autonomous.provider!=="codex"){throw new Error("AUTONOMY_PROVIDER_UNSUPPORTED: autonomy-v1 requires Codex for managed execution. Select Codex; direct conversations remain available with the selected provider.")}const effectiveParallelism=Math.min(autonomous.max_parallelism,positiveLimit(limits.plan,"plan"),positiveLimit(limits.provider,"provider"),positiveLimit(limits.squad,"squad"));return{runtime:"autonomous",provider:autonomous.provider,model:autonomous.model,lease_ms:autonomous.lease_ms,effective_parallelism:effectiveParallelism,max_phase_attempts:autonomous.max_phase_attempts,max_total_invocations:autonomous.max_total_invocations}}function positiveLimit(value,label){if(!Number.isInteger(value)||value<1){throw new TypeError(`${label} parallelism must be a positive integer`)}return value}init_lifecycle_assurance_v2();init_src5();init_cli_arguments();init_run_hierarchy();import{createHash as createHash31}from"node:crypto";async function amendTaskScopes(parsed,filesystem,composition){requireOptions(parsed.options,["run","add-scopes","reason","expected-revision"]);const id=parsed.positionals[2];if(!id)throw new UsageError("task amend-scopes requires a Task id");const{task}=await composition.tasks.read(id);const run=await composition.runs.read(parsed.options.run);if(run.status!=="running"||run.run.task_id!==id||run.run.change_id!==task.change_id||run.run.execution_kind!=="delivery"||run.run.agent!=="agent-orchestrator"||!["blocked","executing"].includes(task.status))throw new UsageError("Scope amendment requires this Task's active delivery orchestrator");const additions=[...new Set(csvOption(parsed.options["add-scopes"]))].sort();if(!additions.length||additions.some(scope=>scope.includes("\\")||scope.startsWith("/")||scope.includes(":")||scope.split("/").some(part=>part===".."||part==="."||part==="")||scope==="**"||scope==="*"))throw new UsageError("Scope amendments require explicit workspace-relative paths");const reason=parsed.options.reason?.trim();if(!reason)throw new UsageError("Scope amendment requires the authorized rework reason");const key=createHash31("sha256").update(JSON.stringify({task:id,run:run.run.run_id,additions,reason})).digest("hex").slice(0,24);const path=`${composition.changes.path(task.change_id).replace(/\/change\.md$/,"")}/artifacts/rework/scopes-${key}.json`;const exists3=await filesystem.exists(path);const receipt=exists3?JSON.parse(await filesystem.readText(path)):null;if(receipt?.next_scopes.every(scope=>task.write_scopes.includes(scope)))return{task,amendment_path:path,reused:true};if(activeDescendantRuns(run.run.run_id,await composition.runs.list()).length>0)throw new UsageError("Finish active descendants before changing the Task's write scopes");if(task.revision!==Number(parsed.options["expected-revision"])||receipt&&receipt.previous_revision!==task.revision)throw new UsageError("Task revision changed; inspect the current Task before amending scopes");const nextScopes=[...new Set([...task.write_scopes,...additions])];const next=taskV2Schema.parse({...task,revision:task.revision+1,write_scopes:nextScopes,updated_at:new Date().toISOString()});if(!exists3)await filesystem.writeTextExclusive(path,`${JSON.stringify({schema_version:1,task_id:id,run_id:run.run.run_id,execution_id:run.run.execution_id,plan_hash:task.plan_hash,previous_revision:task.revision,previous_scopes:task.write_scopes,next_scopes:nextScopes,reason,occurred_at:next.updated_at},null,2)}
|
|
2079
2079
|
`);await composition.tasks.write(next);return{task:next,amendment_path:path,reused:false}}async function assertRecordedTaskScopeDelta(task,baseline,composition){if(JSON.stringify(task.write_scopes)===JSON.stringify(baseline))return;const directory2=`${composition.changes.path(task.change_id).replace(/\/change\.md$/,"")}/artifacts/rework`;const paths=await composition.filesystem.listFiles(directory2,".json");if(paths.length>128)throw new UsageError("Scope rework history requires explicit compaction review");const receipts=await Promise.all(paths.filter(path=>/\/scopes-[a-f0-9]+\.json$/.test(path)).map(async path=>JSON.parse(await composition.filesystem.readText(path))));let scopes=[...baseline];for(const receipt of receipts.sort((a,b)=>a.previous_revision-b.previous_revision)){if(receipt.schema_version!==1||receipt.task_id!==task.id||receipt.plan_hash!==task.plan_hash||!Number.isInteger(receipt.previous_revision)||receipt.previous_revision>=task.revision||JSON.stringify(receipt.previous_scopes)!==JSON.stringify(scopes)||!Array.isArray(receipt.next_scopes)||!scopes.every(scope=>receipt.next_scopes.includes(scope)))continue;const run=await composition.runs.read(receipt.run_id);if(run.run.task_id!==task.id||run.run.change_id!==task.change_id||run.run.execution_id!==receipt.execution_id||run.run.agent!=="agent-orchestrator")throw new UsageError("Scope rework receipt has incompatible ownership");scopes=receipt.next_scopes}if(JSON.stringify(task.write_scopes)!==JSON.stringify(scopes))throw new UsageError(`Native Task ${task.id} drifted from its PreparedPlan without a recorded scope rework`)}async function runAutonomousExecutionCommand(executionId,parsed,composition,driver,agentCatalog){const config2=composition.layout.projectConfig;if(config2===null)throw new UsageError("Autonomous execution requires project.yaml");const{execution}=await composition.executions.read(executionId);const configured=resolveExecutionRuntime(config2,void 0,execution.origin.type);if(configured.runtime==="manual"||parsed.flags.has("materialize-only")){return{mode:"manual",status:"materialized",execution,side_effects:false,artifact_path:composition.executions.path?.(executionId)}}if(driver===void 0){throw new UsageError("Autonomous provider protocol is not qualified; keep execution.runtime manual until clean-room qualification")}const capabilities=await driver.capabilities();const hostAuthenticationAvailable=configured.provider==="codex"?await driver.hostAuthenticationAttestation?.():false;if(configured.provider==="codex"&&hostAuthenticationAvailable!==true){throw new UsageError("Codex host authentication attestation is unavailable")}if(capabilities.provider!==configured.provider){throw new UsageError(`Configured provider ${configured.provider} does not match runtime ${capabilities.provider}`)}if(!capabilities.models.includes(configured.model)){throw new UsageError(`Configured model is not supported by runtime: ${configured.model}`)}let input=await buildAutonomousExecutionInput(composition,execution,{providerParallelism:capabilities.max_parallel_invocations,capabilities:{models:capabilities.models,reasoning_efforts:capabilities.reasoning_efforts,velocities:capabilities.velocities}},agentCatalog,{failurePolicy:parsed.flags.has("continue-independent")?"continue_independent":void 0,restartFailedState:parsed.flags.has("restart-failed-state"),recheckBlockedState:parsed.flags.has("recheck-blocked-state"),operationalContext:{host_authentication_available:hostAuthenticationAvailable===true,requires_remote_operation:parsed.flags.has("requires-remote-operation")}});const childExecutions=await materializePrdChildExecutions(composition,execution,input);if(childExecutions.length>0){const childBySpec=new Map(childExecutions.map(child=>[child.spec_id,child.id]));input={...input,tasks:input.tasks.map(task=>({...task,...task.commit?.spec_id===null||task.commit?.spec_id===void 0?{}:{child_execution_id:childBySpec.get(task.commit.spec_id)}}))};const budgetAllocation=allocateInvocationBudget(input,childExecutions);const candidates=await mapWithConcurrency(childExecutions,input.policy.max_parallelism,async child=>{const childExecution=(await composition.executions.read(child.id)).execution;const childInput=await buildAutonomousExecutionInput(composition,childExecution,{providerParallelism:capabilities.max_parallel_invocations,capabilities:{models:capabilities.models,reasoning_efforts:capabilities.reasoning_efforts,velocities:capabilities.velocities}},agentCatalog,{recheckBlockedState:parsed.flags.has("recheck-blocked-state")});const policy=input.spec_execution_policies[child.spec_id];if(policy?.cancelled===true){await composition.executions.transition(child.id,"cancelled","SPEC execution cancelled by its persisted policy");return{child_execution_id:child.id,spec_id:child.spec_id,status:"cancelled",handoff_worktree_path:null,handoff_commit:null,max_total_invocations:budgetAllocation.get(child.id)??null,finalizer_scope:policy.finalizer_scope,invocation_count:0}}const result3=await driver.execute({...childInput,spec_execution_policies:policy===void 0?{}:{[child.spec_id]:policy},policy:{...childInput.policy,max_parallelism:1,max_total_invocations:budgetAllocation.get(child.id)??null}});const status=result3.status==="completed"?"completed":result3.status==="failed"?"failed":"blocked";await composition.executions.transition(child.id,status,`Autonomous child ${status}`);return{child_execution_id:child.id,spec_id:child.spec_id,status,handoff_worktree_path:result3.state?.handoff_worktree_path??null,handoff_commit:result3.state?.handoff_commit??null,max_total_invocations:budgetAllocation.get(child.id)??null,finalizer_scope:policy?.finalizer_scope??"spec",invocation_count:result3.state?.invocation_count??0}});const consumedByChildren=candidates.reduce((total,candidate)=>total+candidate.invocation_count,0);input={...input,child_candidates:candidates.map(({invocation_count:_count,...candidate})=>candidate),policy:{...input.policy,max_total_invocations:input.policy.max_total_invocations===null?null:Math.max(1,input.policy.max_total_invocations-consumedByChildren)}}}const result2=await driver.execute(input);return{...result2,dependency_plan:dependencyPlan(input),child_executions:childExecutions}}async function materializePrdChildExecutions(composition,parent,input){if(parent.origin.type!=="prd")return[];const taskById=new Map(input.tasks.map(task=>[task.id,task]));const grouped=new Map;for(const task of input.tasks){const specId=task.commit?.spec_id??null;if(specId===null)continue;grouped.set(specId,[...grouped.get(specId)??[],task])}const children=[];for(const[specId,tasks]of[...grouped].sort(([left],[right])=>left.localeCompare(right))){const ids=new Set(tasks.map(task=>task.id));if(tasks.some(task=>task.depends_on.some(dependency=>!ids.has(dependency)||!taskById.has(dependency))))continue;const outsideTasks=input.tasks.filter(task=>!ids.has(task.id));if(tasks.some(task=>outsideTasks.some(outside2=>writeScopesOverlap(task.write_scopes,outside2.write_scopes)))){continue}const id=childExecutionId(parent.id,specId);const existing=await composition.executions.read(id).catch(()=>null);if(existing===null){const dag={nodes:parent.dag.nodes.filter(node=>ids.has(node.task_id)),topological_order:parent.dag.topological_order.filter(taskId=>ids.has(taskId))};await composition.executions.write({...parent,id,parent_execution_id:parent.id,client_turn_id:parent.client_turn_id??id,revision:1,origin:{type:"spec",spec_id:specId},status:"planned",status_reason:null,started_at:null,finished_at:null,result:null,dag,spec_execution_policies:input.spec_execution_policies[specId]===void 0?{}:{[specId]:input.spec_execution_policies[specId]}});await composition.executions.transition(id,"running")}await composition.executions.linkChildExecution(id,parent.id);children.push({id,spec_id:specId})}return children}function childExecutionId(parentExecutionId,specId){return`EXEC-CHILD-${createHash32("sha256").update(`${parentExecutionId}:${specId}`).digest("hex").slice(0,16).toUpperCase()}`}function writeScopesOverlap(left,right){return left.some(leftScope=>right.some(rightScope=>pathsOverlap(scopePrefix(leftScope),scopePrefix(rightScope))))}function scopePrefix(scope){const wildcard=scope.search(/[?*]/);return(wildcard<0?scope:scope.slice(0,wildcard)).replace(/\/+$/,"")}function pathsOverlap(left,right){return left.length===0||right.length===0||left===right||left.startsWith(`${right}/`)||right.startsWith(`${left}/`)}async function mapWithConcurrency(items,limit,worker){const results=new Array(items.length);let cursor=0;const runners=Array.from({length:Math.min(limit,items.length)},async()=>{while(cursor<items.length){const index=cursor++;const item=items[index];if(item!==void 0)results[index]=await worker(item)}});await Promise.all(runners);return results}async function buildAutonomousExecutionInput(composition,execution,limits,agentCatalog,overrides={}){const config2=composition.layout.projectConfig;if(config2===null)throw new UsageError("Autonomous execution requires project.yaml");const taskRecords=await Promise.all(execution.dag.topological_order.map(async taskId=>{const{task}=await composition.tasks.read(taskId);return task}));const preparedPlan=await composition.materializer.readPreparedPlan(execution.parent_execution_id??execution.id);const canonicalTasks=new Map(preparedPlan.blueprints.tasks.map(task=>[task.id,task]));const changes=await Promise.all([...new Set(execution.dag.nodes.map(node=>node.change_id))].map(async changeId=>(await composition.changes.read(changeId)).change));const referencedSpecIds=changes.flatMap(change=>change.source.type==="spec"?[change.source.spec_id]:change.source.type==="prd"&&change.source.spec_id!==null?[change.source.spec_id]:[]);const changeById=new Map(changes.map(change=>[change.id,change]));const manualOrder=await readManualWorkOrder(composition.filesystem);const runtime=resolveExecutionRuntime(config2,{plan:Math.min(execution.policy.max_parallelism,independentBranchLimit(taskRecords)),provider:limits.providerParallelism,squad:agentCatalog===void 0?1:Math.max(1,...agentCatalog.squads.map(squad=>squad.max_parallelism))},execution.origin.type);if(runtime.runtime!=="autonomous")throw new UsageError("Autonomous runtime is not enabled");const tasks=await Promise.all(taskRecords.map(async task=>{const ledger=composition.filesystem?await new FileRecoveryLedger(composition.filesystem).read(task.id):null;if(ledger&&!config2.autonomy&&!["completed","cancelled"].includes(task.status))throw new UsageError(`Task ${task.id} has a frozen autonomy ledger; restore project autonomy configuration before managed dispatch`);if(config2.autonomy&&(task.attempt_count??(task.started_at?1:0))>0&&!ledger&&!["completed","cancelled"].includes(task.status))throw new UsageError(`Task ${task.id} requires explicit task migrate-autonomy before managed dispatch; historical attempts cannot reset`);const baseline=canonicalTasks.get(task.id);if(baseline===void 0)throw new UsageError(`PreparedPlan is missing Task ${task.id}`);const change=changeById.get(task.change_id);if(change===void 0)throw new Error(`Task ${task.id} references an unreadable Change`);const source=change.source;return{id:task.id,...ledger?{autonomy:ledger}:{},change_id:task.change_id,title:task.title,objective:task.objective,risk:task.risk,priority:priorityNumber(task.priority),manual_order:manualOrderForTask(task.id,change.source,manualOrder),depends_on:[...task.depends_on],acceptance_ids:[...task.acceptance_ids],write_scopes:[...task.write_scopes],scope_receipt:await canonicalScopeReceipt(task,baseline.write_scopes,composition),assurance_contract:effectiveTaskAssurance(task,config2.assurance?.version===1?config2.assurance:{standard_depth:"auto",require_final_commit:false}).contract,...agentCatalog===void 0?{}:{builder:autonomousBuilderForTask(runtime.model,agentCatalog,task.write_scopes),...requiresAutonomousAudit(task)?{verifier:autonomousAuditorForTask(runtime.model,agentCatalog,task)}:{}},commit:{agent:runtime.provider.toUpperCase(),execution_id:execution.id,change_id:task.change_id,task_id:task.id,title:task.title,prd_id:source.type==="prd"?source.prd_id:null,spec_id:source.type==="spec"?source.spec_id:source.type==="prd"?source.spec_id:null},...task.runtime===void 0?{}:{runtime:task.runtime},...task.model_profile===void 0?{}:{model_profile:task.model_profile}}}));if(execution.origin.type==="interaction"){throw new Error(`Interaction Execution ${execution.id} cannot use the delivery runtime`)}return{mode:"autonomous",execution_id:execution.id,source:execution.origin.type,source_identity:{spec_id:execution.origin.type==="spec"?execution.origin.spec_id:null,prd_id:execution.origin.type==="prd"?execution.origin.prd_id:null},created_at:new Date(execution.created_at).toISOString(),...overrides.restartFailedState===true?{restart_failed_state:true}:{},...overrides.recheckBlockedState===true?{recheck_blocked_state:true}:{},host_capabilities:{models:[...limits.capabilities.models],reasoning_efforts:[...limits.capabilities.reasoning_efforts],velocities:[...limits.capabilities.velocities]},operational_context:{provider:runtime.provider,host_authentication_available:false,requires_external_provider:runtime.provider!=="codex",requires_remote_operation:false,...overrides.operationalContext},handoff_seed_paths:[...new Set([composition.layout.activePath("execution",execution.id),...execution.dag.nodes.flatMap(node=>[composition.layout.activePath("task",node.task_id),composition.layout.activePath("change",node.change_id)]),...execution.origin.type==="prd"?[composition.layout.activePath("prd",execution.origin.prd_id)]:execution.origin.type==="spec"?[composition.layout.activePath("spec",execution.origin.spec_id)]:[],...referencedSpecIds.map(specId=>composition.layout.activePath("spec",specId))])].sort(),policy:{...config2.autonomy?{autonomy:config2.autonomy}:{},failure_policy:overrides.failurePolicy??(config2.autonomy?"continue_independent":execution.policy.failure_policy),lease_ms:runtime.lease_ms,max_parallelism:runtime.effective_parallelism,max_operational_retries:execution.policy.max_operational_retries,max_repair_cycles_per_task:Math.min(3,execution.policy.max_repair_cycles_per_task),soft_cycles:execution.policy.soft_model_cycle_budget??24,...runtime.max_phase_attempts===void 0?{}:{max_phase_attempts:runtime.max_phase_attempts},max_execution_ms:null,max_invocation_ms:null,max_total_invocations:config2.autonomy?null:runtime.max_total_invocations===void 0?Math.max(1,tasks.length*30):runtime.max_total_invocations,max_stalled_cycles:3,...isAutomaticModelSource(execution,config2.model_orchestration)?{model_orchestration:config2.model_orchestration}:{},...execution.policy.runtime_defaults===void 0?{}:{execution_override:{model:execution.policy.runtime_defaults.model,reasoning_effort:execution.policy.runtime_defaults.reasoning_effort,velocity:execution.policy.runtime_defaults.velocity??"standard"}}},spec_execution_policies:execution.spec_execution_policies??{},agents:autonomousAgents(runtime.provider,runtime.model,agentCatalog),tasks}}async function readManualWorkOrder(filesystem){try{const parsed=JSON.parse(await filesystem.readText(".agents/dashboard/work-priority.json"));const ids=typeof parsed==="object"&&parsed!==null&&Array.isArray(parsed.item_ids)?parsed.item_ids:[];return new Map(ids.filter(id=>typeof id==="string").map((id,index)=>[id,index]))}catch{return new Map}}function manualOrderForTask(taskId,source,order2){return order2.get(taskId)??(source.spec_id?order2.get(source.spec_id):void 0)??(source.prd_id?order2.get(source.prd_id):void 0)??null}function independentBranchLimit(tasks){const selected=[];for(const task of tasks){if(task.depends_on.length>0||task.risk==="critical")continue;if(selected.some(candidate=>scopesOverlap2(candidate.write_scopes,task.write_scopes)))continue;selected.push(task)}return Math.max(1,selected.length)}function scopesOverlap2(left,right){return left.some(leftScope=>right.some(rightScope=>{const leftPrefix=leftScope.replace(/[?*].*$/,"").replace(/\/$/,"");const rightPrefix=rightScope.replace(/[?*].*$/,"").replace(/\/$/,"");return leftPrefix===""||rightPrefix===""||leftPrefix.startsWith(rightPrefix)||rightPrefix.startsWith(leftPrefix)}))}async function canonicalScopeReceipt(task,baseline,composition){await assertRecordedTaskScopeDelta(task,baseline,composition);const current=[...task.write_scopes];return{receipt_id:createHash32("sha256").update(JSON.stringify({task_id:task.id,plan_hash:task.plan_hash,revision:task.revision,scopes:current})).digest("hex"),current_scopes:current,delta_scopes:current.filter(scope=>!baseline.includes(scope))}}function dependencyPlan(input){return{failure_policy:input.policy.failure_policy,unconditioned:input.tasks.filter(task=>task.depends_on.length===0).map(task=>({task_id:task.id})),conditioned:input.tasks.filter(task=>task.depends_on.length>0).map(task=>({task_id:task.id,depends_on:[...task.depends_on]}))}}function isAutomaticModelSource(execution,config2){return config2?.mode==="auto"&&config2.automatic_sources.some(source=>source===execution.origin.type)}function autonomousAgents(provider,model,catalog){if(catalog===void 0){return{orchestrator:{id:`${provider}-orchestrator`,model},builder:{id:`${provider}-task-executor`,model,execution_eligibility:["delivery"]},verifier:{id:`${provider}-verifier`,model,tools:[]},finalizer:{id:`${provider}-execution-finalizer`,model}}}const orchestratorSelection=selectAgent(catalog,{role:"orchestrator",capability:"dag-orchestration"});const orchestrator=orchestratorSelection.agent;const builderSelection=selectAgentForWork(catalog,{role:"task-executor",capability:"task-delivery",scopes:[]});const builder=builderSelection.agent;const verifierSelection=selectAgent(catalog,{role:"reviewer",capability:"independent-review"});const verifier=verifierSelection.agent;const finalizerSelection=selectAgent(catalog,{role:"execution-finalizer",capability:"lifecycle-finalization"});const finalizer=finalizerSelection.agent;return{orchestrator:{id:orchestrator.id,model,capability:"dag-orchestration",selection_reasons:orchestratorSelection.reasons,soft_cycles:orchestrator.budget.soft_cycles,tools:orchestrator.tools,execution_eligibility:orchestrator.execution_eligibility},builder:{id:builder.id,model,capability:selectionCapability(builderSelection.reasons),selection_reasons:builderSelection.reasons,soft_cycles:builder.budget.soft_cycles,tools:builder.tools,execution_eligibility:builder.execution_eligibility},verifier:{id:verifier.id,model,capability:"independent-review",selection_reasons:verifierSelection.reasons,soft_cycles:verifier.budget.soft_cycles,tools:verifier.tools,execution_eligibility:verifier.execution_eligibility},finalizer:{id:finalizer.id,model,capability:"lifecycle-finalization",selection_reasons:finalizerSelection.reasons,soft_cycles:finalizer.budget.soft_cycles,tools:finalizer.tools,execution_eligibility:finalizer.execution_eligibility}}}function autonomousAuditorForTask(model,catalog,task){const capability=task.model_profile?.risk_signals.security_or_critical_data===true?"security-audit":"release-audit";const selection2=selectAgent(catalog,{role:"auditor",capability});const agent=selection2.agent;return{id:agent.id,model,capability,selection_reasons:selection2.reasons,soft_cycles:agent.budget.soft_cycles,tools:agent.tools,execution_eligibility:agent.execution_eligibility}}function requiresAutonomousAudit(task){const signals=task.model_profile?.risk_signals;return task.risk==="critical"||signals?.security_or_critical_data===true||signals?.broad_audit===true}function autonomousBuilderForTask(model,catalog,writeScopes){const selection2=selectAgentForWork(catalog,{role:"task-executor",capability:"task-delivery",scopes:writeScopes});const agent=selection2.agent;return{id:agent.id,model,capability:selectionCapability(selection2.reasons),selection_reasons:selection2.reasons,soft_cycles:agent.budget.soft_cycles,tools:agent.tools,execution_eligibility:agent.execution_eligibility}}function priorityNumber(priority2){return{low:1,medium:2,high:3,urgent:4}[priority2]}function selectionCapability(reasons){return reasons.find(reason=>reason.startsWith("capability:"))?.slice("capability:".length)??""}import{readdirSync,realpathSync,statSync}from"node:fs";import{homedir as homedir3}from"node:os";import{join as join3}from"node:path";init_src();init_src5();function astraDiagnosticContext(filesystem,build=buildContextPack){return async task=>{const query=["RULE-ASTRA-DIAGNOSTIC",...task.acceptance_ids].join(" ");const pack=await build(filesystem,query,16e3,{role:"orchestrator",phase:"planning",failClosed:true});const items=pack.items.filter(item=>pack.requiredFiles.includes(item.path));if(!items.some(item=>item.path===".agents/rules/astra-diagnostic.md"&&/\bRULE-ASTRA-DIAGNOSTIC\b/.test(item.content))){throw new Error("Astra diagnostic context is missing the canonical diagnostic Rule")}const present=new Set(items.flatMap(item=>item.content.match(/\b(?:AC|REQ)-[A-Z0-9-]+/g)??[]));if(!task.acceptance_ids.every(id=>present.has(id))){throw new Error("Astra diagnostic context is missing a governing Acceptance Criterion")}return items.map(({path,content})=>({path,content:path.startsWith(".agents/requirements/")?governingRequirementSections(content,task.acceptance_ids):content}))}}function governingRequirementSections(content,acceptanceIds){const sections=content.split(/(?=^## REQ-)/m);const governing=sections.slice(1).filter(section=>acceptanceIds.some(id=>new Set(section.match(/\bAC-[A-Z0-9-]+\b/g)??[]).has(id)));return governing.length===0?content:[sections[0],...governing].join("")}init_src();init_src3();init_src4();init_src();init_src3();init_src6();import{createHash as createHash38}from"node:crypto";init_src3();import{createHash as createHash37}from"node:crypto";init_run_finalization_barrier();init_run_finalization_evidence_v2();init_run_lifecycle_reconciliation();async function reconcileTerminalOrchestratorRoot(root,candidates,composition,lifecycle){const decision=root.finalization_decision??null;const evidenceIds=decision===null?await passedTypedEvidenceIdsForRun(root,composition,candidates):decision.evidence_ids;const evidenceSatisfied=await hasPassedTypedEvidenceForRun(root,evidenceIds,composition,candidates);const barrier=assessRunFinalizationBarrier(root,candidates,evidenceSatisfied);const blockReason=finalizationBarrierBlockReason(barrier);const decisionEligible=decision!==null&&(decision.outcome!=="completed"||barrier.satisfied);const reconciliation=await reconcileFinishedRunLifecycle(root,composition,lifecycle,{requestedOutcome:decisionEligible?decision.outcome:"blocked",forceRequestedOutcome:!decisionEligible,summary:decisionEligible?decision.summary:blockReason??"Orchestrator stopped without a persisted Gui finalization decision; lifecycle was fail-closed as blocked.",evidenceIds:decision?.evidence_ids??evidenceIds,changedFiles:decision?.changed_files??[],candidateRuns:candidates});return{status:"closed",parent_run_id:root.run.run_id,finalization_barrier:barrier,finalization_decision:decision,reconciliation}}init_run_conversation_v2();init_run_hierarchy();init_task_attempt();function closureReceiptPath(runId){return`.local/lifecycle-closure/${createHash37("sha256").update(runId).digest("hex")}.json`}async function reconcilePendingAncestorStops(child,composition,lifecycle){let parentId=child.run.parent_run_id;const seen=new Set;while(parentId!==null&&!seen.has(parentId)){seen.add(parentId);const parent=await composition.runs.read(parentId);const path=closureReceiptPath(parentId);if(await composition.filesystem.exists(path)){const receipt=JSON.parse(await composition.filesystem.readText(path));if(receipt.schema_version===1&&receipt.run_id===parentId&&receipt.task_id===parent.run.task_id&&receipt.execution_id===parent.run.execution_id&&receipt.state==="pending"&&["completed","failed","cancelled"].includes(receipt.terminal_status))await reconcileOrchestratorStop(parent,composition,lifecycle,receipt.terminal_status)}parentId=parent.run.parent_run_id}}async function reconcileOrchestratorStop(current,composition,lifecycle,terminalStatus2="completed"){return composition.runs.withUsageAttributionLock(async()=>{const fresh=await composition.runs.read(current.run.run_id);const candidates=await composition.runs.list();if(candidates.some(candidate=>candidate.run.run_id!==fresh.run.run_id&&ownsLifecycleAttempt(candidate)&&candidate.run.task_id===fresh.run.task_id&&(fresh.run.task_id!==null||fresh.run.execution_id!==null&&candidate.run.execution_id===fresh.run.execution_id)&&Date.parse(candidate.run.occurred_at)>Date.parse(fresh.run.occurred_at)))return{status:"pending_newer_attempt",parent_run_id:fresh.run.run_id};const receiptPath=closureReceiptPath(fresh.run.run_id);const receipt={schema_version:1,run_id:fresh.run.run_id,task_id:fresh.run.task_id,execution_id:fresh.run.execution_id,terminal_status:fresh.finished?.status??terminalStatus2,state:"pending",recovery:"Replay the exact observed subagent stop; never reconcile unrelated open work"};await composition.filesystem.writeTextAtomic(receiptPath,`${JSON.stringify(receipt)}
|
|
2080
2080
|
`);const active=activeDescendantRuns(fresh.run.run_id,candidates);if(active.length>0){return{status:"pending_descendants",parent_run_id:fresh.run.run_id,active_run_ids:active.map(candidate=>candidate.run.run_id)}}const settle=async(finished,all)=>{const result2=await reconcileTerminalOrchestratorRoot(finished,all,composition,lifecycle);await composition.filesystem.writeTextAtomic(receiptPath,`${JSON.stringify({...receipt,state:"reconciled"})}
|
|
@@ -2152,4 +2152,4 @@ Autonomous execution: execution run ID [--materialize-only] [--continue-independ
|
|
|
2152
2152
|
Direct delivery: conversation start or run start --direct-authorization HUMAN-REFERENCE; only an observed Task-scoped root, no fake executor; Gui and Evidence still required
|
|
2153
2153
|
Explicit migration: task migrate-autonomy TASK --execution EXEC --expected-revision N --legacy-attempts N --legacy-replans N|unknown [--future-replans N|unlimited] --reason TEXT [--confirm]; unknown requires an explicit future grant; preview by default, preserves history and quota`}init_lifecycle_v2();import{spawn as spawn2}from"node:child_process";import{dirname as dirname15}from"node:path";async function taskLedger(repository2){const allTasks=await repository2.list();const activeChangeIds=new Set(allTasks.filter(task=>["executing","verifying"].includes(task.status)).map(task=>task.change));const tasks=allTasks.filter(task=>activeChangeIds.has(task.change)&&task.status!=="planned");const paths=new Set;for(const task of tasks){const{body}=await repository2.read(task.id);const section=body.match(/## Arquivos alterados\s+([\s\S]*?)(?=\n## |$)/)?.[1]??"";for(const match of section.matchAll(/^\s*-\s+`?([^`\n]+?)`?\s*$/gm)){if(match[1])paths.add(match[1].replace(/\\/g,"/"))}}return[...paths].sort()}async function taskLedgerV2(repository2,changed){const allTasks=await repository2.list();const activeChangeIds=new Set(allTasks.filter(task=>["executing","verifying","blocked"].includes(task.status)).map(task=>task.change_id));const changeTasks=allTasks.filter(task=>activeChangeIds.has(task.change_id)&&!["draft","planned","cancelled"].includes(task.status));const completedTasks=allTasks.filter(task=>task.result!==null);const paths=new Set([...changeTasks,...completedTasks].flatMap(task=>task.result?.changed_files??[]));const authorizedScopes=[...changeTasks.filter(task=>["executing","verifying","blocked"].includes(task.status)).flatMap(task=>task.write_scopes),...completedTasks.flatMap(task=>task.result?.changed_files??[])];for(const path of changed){if(authorizedScopes.some(scope=>workspaceScopeMatches(scope,path)))paths.add(path)}return[...paths].sort()}function runUiServer(serverPath,workspace){const child=spawn2(process.execPath,[serverPath],{cwd:dirname15(serverPath),env:{...process.env,ZAIP_WORKSPACE:workspace},stdio:"inherit",windowsHide:true});return new Promise((resolveExit,reject)=>{child.once("error",reject);child.once("exit",code=>resolveExit(code??1))})}init_lifecycle_manifest_commands();init_run_conversation_v2();init_cli_arguments();import{execFile as execFile18}from"node:child_process";import{lstat as lstat8,realpath as realpath9}from"node:fs/promises";import{basename as basename5,isAbsolute as isAbsolute10,relative as relative12,resolve as resolve17,sep as sep6}from"node:path";import{promisify as promisify18}from"node:util";var execFileAsync8=promisify18(execFile18);var shaPattern=/^[a-f0-9]{40}$/i;var canonicalMigrationPath=/^supabase\/migrations\/[A-Za-z0-9][A-Za-z0-9_.-]*\.sql$/;async function runSupabaseMigrationCommand(input){if(input.action!=="plan"&&input.action!=="validate"){throw new UsageError("supabase migration requires plan or validate")}const target=input.config?.supabase_migrations;if(target===void 0){throw new UsageError("supabase migration requires supabase_migrations in .agents/config/project.yaml")}const findings=await validateTarget(target.repository);const plan={repository_id:target.repository.id,configured_path:target.repository.path,required_branch:target.repository.branch,required_origin:target.repository.origin,hosted_applicator:target.hosted_applicator,applies_hosted_schema:false,required_evidence:["migration catalog entry","candidate SHA on beta","passed candidate checks","Supabase migration-history observation showing the same migration applied"]};if(input.action==="plan")return{valid:findings.length===0,mode:"plan",target:plan,findings};const evidencePath=input.parsed.options.evidence;if(evidencePath===void 0)throw new UsageError("supabase migration validate requires --evidence PATH");let evidence=null;try{evidence=parseEvidence(JSON.parse(await input.filesystem.readText(evidencePath)))}catch(error51){findings.push({code:"evidence-invalid",message:error51 instanceof Error?error51.message:"Migration evidence is invalid"})}if(evidence!==null&&findings.length===0){findings.push(...await validateEvidence(target.repository.path,evidence))}return{valid:findings.length===0,mode:"validate",target:plan,findings}}async function validateTarget(repository2){const findings=[];if(!isAbsolute10(repository2.path)||repository2.path.includes("\0")){return[{code:"target-path-invalid",message:"Migration target path must be absolute"}]}let target;try{target=await realpath9(repository2.path)}catch{return[{code:"target-path-unavailable",message:"Configured migration target is unavailable"}]}if(target.split(/[\\/]/).at(-1)!==repository2.id){findings.push({code:"target-identity-mismatch",message:"Target path basename does not match the configured repository id"})}const[branch,origin]=await Promise.all([git4(target,["branch","--show-current"]),git4(target,["remote","get-url","origin"])]);if(branch!==repository2.branch){findings.push({code:"target-branch-mismatch",message:"Migration target must be on branch beta"})}if(origin!==repository2.origin){findings.push({code:"target-origin-mismatch",message:"Migration target origin does not match configuration"})}return findings}async function validateEvidence(targetPath,evidence){const findings=[];if(!canonicalMigrationPath.test(evidence.migration.path)){return[{code:"migration-path-invalid",message:"Migration path must be a canonical supabase/migrations/*.sql path"}]}if(!basename5(evidence.migration.path).startsWith(evidence.migration.id)){findings.push({code:"migration-id-filename-mismatch",message:"Migration id must be the filename prefix"})}if(!shaPattern.test(evidence.candidate.sha)){findings.push({code:"candidate-sha-invalid",message:"Candidate SHA must be a full Git commit SHA"})}if(evidence.candidate.checks.length===0||evidence.candidate.checks.some(check2=>check2.status!=="passed")){findings.push({code:"candidate-checks-missing",message:"Candidate evidence requires one or more passed checks"})}if(evidence.applied.migration_id!==evidence.migration.id){findings.push({code:"applied-migration-mismatch",message:"Applied migration evidence must name the catalogued migration id"})}if(!Number.isFinite(Date.parse(evidence.applied.observed_at))){findings.push({code:"applied-observation-invalid",message:"Applied migration observation requires an ISO timestamp"})}if(findings.length>0)return findings;const target=await realpath9(targetPath);const migrationFile=resolve17(target,evidence.migration.path);if(!within(target,migrationFile)){return[{code:"migration-path-escape",message:"Migration path escapes the configured target"}]}try{const physicalMigrationFile=await realpath9(migrationFile);const status=await lstat8(migrationFile);if(status.isSymbolicLink()||!status.isFile()||!within(target,physicalMigrationFile)){findings.push({code:"migration-file-unsafe",message:"Migration file must be a regular non-symlink file inside the target"})}await git4(target,["ls-files","--error-unmatch","--",evidence.migration.path])}catch{findings.push({code:"migration-not-catalogued",message:"Migration file is absent from the target catalog"})}const head=await git4(target,["rev-parse","HEAD"]);if(head!==evidence.candidate.sha){findings.push({code:"candidate-sha-mismatch",message:"Candidate SHA must equal the current beta HEAD"})}try{const observedOriginBeta=await git4(target,["rev-parse","refs/remotes/origin/beta"]);if(observedOriginBeta!==evidence.candidate.sha){findings.push({code:"origin-beta-sha-mismatch",message:"Observed refs/remotes/origin/beta does not match the candidate SHA"})}else{findings.push({code:"origin-beta-unverified",message:"Observed origin/beta is local ref evidence only; fetch freshness and remote publication remain unverified"})}}catch{findings.push({code:"origin-beta-ref-unavailable",message:"refs/remotes/origin/beta is unavailable; remote publication is pending"})}try{const type=await git4(target,["cat-file","-t",`${evidence.candidate.sha}:${evidence.migration.path}`]);if(type!=="blob")throw new Error("candidate object is not a blob");await git4(target,["diff","--quiet","--",evidence.migration.path]);await git4(target,["diff","--cached","--quiet","--",evidence.migration.path])}catch{findings.push({code:"candidate-migration-unverified",message:"Candidate migration must be a tracked clean blob at the candidate SHA"})}return findings}function parseEvidence(value){if(typeof value!=="object"||value===null)throw new Error("Migration evidence must be an object");const record3=value;const migration=record3.migration;const candidate=record3.candidate;const applied=record3.applied;if(record3.schema_version!==1||migration===void 0||candidate===void 0||applied===void 0){throw new Error("Migration evidence must use schema_version 1 with migration, candidate and applied sections")}if(typeof migration.id!=="string"||typeof migration.path!=="string"||typeof candidate.sha!=="string"||!Array.isArray(candidate.checks)||typeof applied.migration_id!=="string"||applied.status!=="applied"||applied.source!=="supabase-migration-history"||applied.trust!=="unverified"||typeof applied.observed_at!=="string"){throw new Error("Migration evidence fields are incomplete or invalid; local observations are unverified")}if(!candidate.checks.every(check2=>typeof check2==="object"&&check2!==null&&typeof check2.id==="string"&&["passed","failed"].includes(String(check2.status)))){throw new Error("Candidate checks must each have id and passed or failed status")}return value}async function git4(cwd,args){const result2=await execFileAsync8("git",[...args],{cwd,windowsHide:true,encoding:"utf8"});return result2.stdout.trim()}function within(root,candidate){const path=relative12(root,candidate);return path===""||!path.startsWith(`..${sep6}`)&&path!==".."&&!isAbsolute10(path)}init_cli_arguments();import{lstat as lstat9,realpath as realpath10}from"node:fs/promises";import{isAbsolute as isAbsolute11,relative as relative13,resolve as resolve18,sep as sep7}from"node:path";async function assertToolWriteScope(root,scopes,requestedPath){if(!isCanonicalRelativePath(requestedPath)){throw new UsageError("Tool write path must be canonical and workspace-relative")}if(scopes.length===0||!scopes.some(scope=>scopeMatches2(scope,requestedPath))){throw new UsageError(`Tool write path is outside declared write scopes: ${requestedPath}`)}const physicalRoot=await realpath10(root);const target=resolve18(root,requestedPath);if(!within2(physicalRoot,target))throw new UsageError("Tool write path escapes workspace root");let ancestor=target;while(true){try{const status=await lstat9(ancestor);const physicalAncestor=await realpath10(ancestor);if(status.isSymbolicLink()||!within2(physicalRoot,physicalAncestor)){throw new UsageError("Tool write path escapes workspace through a symlink")}return}catch(error51){if(error51 instanceof UsageError)throw error51;if(!(error51 instanceof Error&&"code"in error51&&error51.code==="ENOENT"))throw error51;const parent=resolve18(ancestor,"..");if(parent===ancestor||!within2(resolve18(root),parent)){throw new UsageError("Tool write path has no contained existing ancestor")}ancestor=parent}}}async function copyWithinToolWriteScope(input){await assertToolWriteScope(input.root,input.scopes,input.to);await input.filesystem.writeTextAtomic(input.to,await input.filesystem.readText(input.from))}function isCanonicalRelativePath(value){return value.length>0&&!value.includes("\\")&&!value.includes(":")&&!value.includes("\0")&&!isAbsolute11(value)&&!value.startsWith("./")&&value.split("/").every(part=>part!==""&&part!=="."&&part!==".."&&!/^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\..*)?$/i.test(part))}function scopeMatches2(scope,path){if(!isCanonicalRelativePath(scope.replace(/\*+$/g,"placeholder")))return false;const normalized=scope.replace(/\/+$/,"");if(!normalized.includes("*"))return path===normalized||path.startsWith(`${normalized}/`);const expression=normalized.split("**").map(part=>part.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^/]*")).join(".*");return new RegExp(`^${expression}$`).test(path)}function within2(root,candidate){const fromRoot=relative13(root,candidate);return fromRoot===""||!fromRoot.startsWith(`..${sep7}`)&&fromRoot!==".."&&!isAbsolute11(fromRoot)}init_src();import{spawn as spawn3}from"node:child_process";async function runScopedVerification(filesystem,risk2){const changed=await new ShellGit(filesystem.root).status();const packageRoots=new Set;for(const entry2 of changed){const path=entry2.path.replace(/\\/g,"/");const match=path.match(/^(packages\/[^/]+|\.agents\/dashboard\/(?:apps|modules|packages|tests)\/[^/]+)/);if(match?.[1]!==void 0)packageRoots.add(`./${match[1]}`)}const commands=[];if(risk2==="critical")commands.push({name:"full-verify",command:"pnpm",args:["verify"]});else if(risk2==="standard"){commands.push({name:"encoding",command:"node",args:["scripts/validate-text-encoding.mjs"]},{name:"source-size",command:"node",args:["scripts/validate-source-size.mjs"]});for(const root of[...packageRoots].sort()){commands.push({name:`${root}:typecheck`,command:"pnpm",args:["--filter",root,"typecheck"]});commands.push({name:`${root}:test`,command:"pnpm",args:["--filter",root,"test"]})}}const lines=[];const checks=risk2==="lite"?[{name:"diff-only",passed:true,exit_code:0}]:[];const expectedChecks=checks.length+commands.length;for(const check2 of commands){const outcome=await runProcess2(check2.command,check2.args,filesystem.root);lines.push(`$ ${check2.command} ${check2.args.join(" ")}
|
|
2154
2154
|
${outcome.output}`);checks.push({name:check2.name,passed:outcome.code===0,exit_code:outcome.code});if(outcome.code!==0)break}const logPath=`.local/verify/${new Date().toISOString().replace(/[:.]/g,"-")}.log`;await filesystem.writeTextAtomic(logPath,`${lines.join("\n\n")}
|
|
2155
|
-
`);return{passed:checks.length===expectedChecks&&checks.every(check2=>check2.passed),risk:risk2,changed_files:changed.length,checks,log_path:logPath}}async function runProcess2(command,args,cwd){return new Promise((resolveProcess,reject)=>{const executable=process.platform==="win32"&&command==="pnpm"?"pnpm.cmd":command;const child=spawn3(executable,args,{cwd,shell:process.platform==="win32",windowsHide:true});let output2="";child.stdout?.on("data",chunk=>output2+=String(chunk));child.stderr?.on("data",chunk=>output2+=String(chunk));child.once("error",reject);child.once("close",code=>resolveProcess({code:code??1,output:output2}))})}var CLI_VERSION="3.0.0";var CLI_DISPLAY_VERSION=CLI_VERSION.replace(/\.0$/,"");var EXIT2={success:0,error:1,usage:2,conformity:3,lifecycle:4,security:5,prerequisite:6};var execFileAsync9=promisify19(execFile19);async function runCli(arguments_,cwd=process.cwd()){const parsed=parseArguments(arguments_);const requestedRoot=resolve19(parsed.options.workspace??cwd);const root=parsed.options.workspace===void 0?await new ShellGit(requestedRoot).repositoryRoot()??requestedRoot:requestedRoot;const filesystem=new WorkspaceFileSystem(root);const json2=parsed.flags.has("json");try{const[area,action]=parsed.positionals;if(area==="hook"&&action==="recover-stop"){requireOptions(parsed.options,["session","turn"]);const result2=await replayStopReceipt(filesystem,parsed.options.session,parsed.options.turn);output(result2,json2);return result2.state==="persisted"?EXIT2.success:EXIT2.lifecycle}if(area==="commit"){output(await runCommitPolicyCommand(root,parsed),json2);return EXIT2.success}if(area==="version"||parsed.flags.has("version")){output(json2?{version:CLI_VERSION}:CLI_DISPLAY_VERSION,json2);return EXIT2.success}if(area===void 0||area==="help"||parsed.flags.has("help")){output(HELP,json2);return area===void 0&&!parsed.flags.has("help")?EXIT2.usage:EXIT2.success}const activationExit=await handleZaipActivation(area,filesystem,json2);if(activationExit!==null)return activationExit;const distributionExit=await runDistributionCommand({area,action,parsed,filesystem,root,json:json2});if(distributionExit!==null)return distributionExit;if(area==="supabase"&&action==="migration"){const result2=await runSupabaseMigrationCommand({action:parsed.positionals[2],parsed,filesystem,config:(await loadWorkspaceLayout(filesystem)).projectConfig});output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}if(area==="database"&&action==="migration"){const mode=parsed.positionals[2];if(mode!=="prepare"&&mode!=="submit")throw new UsageError("database migration requires prepare or submit");requireOptions(parsed.options,["database-repository","migration-path","description","tests","risk"]);if(!["compatible","destructive","permissions","incompatible"].includes(parsed.options.risk??""))throw new UsageError("--risk must be compatible, destructive, permissions, or incompatible");const migrationPath=parsed.options["migration-path"];const[source,sql,layout]=await Promise.all([verifiedMigrationSource(root),filesystem.readText(migrationPath),loadWorkspaceLayout(filesystem)]);const actualHash=createHash48("sha256").update(sql,"utf8").digest("hex");if(parsed.options["migration-sha256"]!==void 0&&parsed.options["migration-sha256"].toLowerCase()!==actualHash)throw new UsageError("--migration-sha256 does not match the migration file");const request=prepareMigrationRequest(layout.projectConfig,{source_repository:source.repository,source_sha:source.sha,source_identity_verified:true,database_repository:parsed.options["database-repository"],migration_path:migrationPath,migration_content_sha256:actualHash,description:parsed.options.description,sql,tests:parsed.options.tests.split(",").filter(Boolean),risk:parsed.options.risk});if(mode==="submit"){requireOptions(parsed.options,["request-head","database-worktree"]);const databaseWorktree=parsed.options["database-worktree"];const requestHead=parsed.options["request-head"];const[dbOrigin,headCommit]=await Promise.all([execFileAsync9("git",["remote","get-url","origin"],{cwd:databaseWorktree,encoding:"utf8",windowsHide:true}),execFileAsync9("git",["rev-parse",requestHead],{cwd:databaseWorktree,encoding:"utf8",windowsHide:true})]);const capturedHeadSha=headCommit.stdout.trim();if(!/^[a-f0-9]{40,64}$/i.test(capturedHeadSha))throw new UsageError("request head must resolve to a commit SHA");const blob=await execFileAsync9("git",["cat-file","blob",`${capturedHeadSha}:${migrationPath}`],{cwd:databaseWorktree,encoding:"buffer",windowsHide:true});const expectedDatabase=parsed.options["database-repository"];const originMatch=/^(?:git@github\.com:|https:\/\/github\.com\/)([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?\s*$/i.exec(dbOrigin.stdout.toString());if(originMatch?.[1]?.toLowerCase()!==expectedDatabase.toLowerCase())throw new UsageError("Database worktree origin does not exactly match --database-repository");if(createHash48("sha256").update(blob.stdout).digest("hex")!==actualHash)throw new UsageError("Request head migration blob does not match local migration SQL");const migrationConfig=layout.projectConfig?.supabase_migrations;if(migrationConfig===void 0)throw new UsageError("submit requires persisted supabase_migrations configuration");if(migrationConfig.repository.id!==expectedDatabase||migrationConfig.repository.path!==databaseWorktree||migrationConfig.repository.origin!==dbOrigin.stdout.trim())throw new UsageError("submit target and database worktree must exactly match persisted supabase_migrations.repository");assertMigrationRemoteSubmission({beta_integration_verified:migrationConfig.beta_integration_verified??false,paid_beta_provisioning_confirmed:migrationConfig.paid_beta_provisioning_confirmed??false,preview_policy:migrationConfig.preview_policy??"disabled"});const submission=await submitMigrationRequest(new GhMigrationPullRequestAdapter(databaseWorktree,requestHead,capturedHeadSha),expectedDatabase,request);output({mode,request,submission,hosted_migrator:"supabase-github-integration"},json2);return EXIT2.success}output({mode,request,remote_submitted:false,hosted_migrator:"supabase-github-integration"},json2);return EXIT2.success}if(area==="adapters"&&action==="build"){await buildAdapters(filesystem);output({built:true},json2);return EXIT2.success}if(area==="adapters"&&action==="check"){const result2=await checkAdapters(filesystem);output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}if(area==="context"&&action==="inventory"){output(await inventory(filesystem),json2);return EXIT2.success}if(area==="context"&&["build","inspect"].includes(action??"")){const pack=await buildContextForCommand(filesystem,parsed,contextQuery(parsed,parsed.options.query??parsed.positionals.slice(2).join(" ")),numberOption(parsed.options.budget,8e3));if(parsed.options.run!==void 0){const layout=await loadWorkspaceLayout(filesystem);if(layout.version===1)throw new UsageError("context --run requires a modern workspace");await recordContextPackUsage(parsed.options.run,pack.estimatedTokens,createV2Composition(filesystem,layout))}output(contextPackView(parsed)==="compact"?compactContextPack(pack):pack,json2);return EXIT2.success}if(area==="context"&&action==="map"){output(await buildRepositoryMap(filesystem),json2);return EXIT2.success}if(area==="context"&&action==="agents"){try{const discovery=await resolveAgentDiscovery(filesystem,{...parsed.options.agent===void 0?{}:{agentId:parsed.options.agent}});output(parsed.options.agent===void 0?discovery:{source:discovery.source,provenance:discovery.provenance,selected:discovery.selected},json2);return EXIT2.success}catch(error51){if(error51 instanceof Error&&/agent/i.test(error51.message))throw new UsageError(error51.message);throw error51}}if(area==="context"&&action==="handoff"){output(contextHandoffForCommand(parsed),json2);return EXIT2.success}if(area==="context"&&action==="validate"){const pack=await buildContextForCommand(filesystem,parsed,contextQuery(parsed,parsed.options.query??"active task"),numberOption(parsed.options.budget,8e3));const findings=validateContextPack(pack);output({valid:findings.length===0,estimatedTokens:pack.estimatedTokens,budget:pack.budget,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}if(area==="manifest"){const layout=await loadWorkspaceLayout(filesystem);if(layout.version===1)throw new UsageError("lifecycle manifests require a modern workspace");output(await runLifecycleManifestMaintenance(action,parsed,filesystem,createV2Composition(filesystem,layout)),json2);return EXIT2.success}if(area==="cost"&&action==="cohort"){requireOptions(parsed.options,["input"]);output(await readCostCohortInput(filesystem,parsed.options.input),json2);return EXIT2.success}if(area==="verify"){if(!parsed.flags.has("changed")&&riskOption(parsed.options.risk)!=="critical"){throw new UsageError("verify requires --changed or --risk critical")}const result2=await runScopedVerification(filesystem,riskOption(parsed.options.risk));output(result2,json2);return result2.passed?EXIT2.success:EXIT2.conformity}if(area==="supabase"&&action==="migration"){const result2=await runSupabaseMigrationCommand({action:parsed.positionals[2],parsed,filesystem,config:(await loadWorkspaceLayout(filesystem)).projectConfig});output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}if(area==="tool"&&action==="copy"){if(parsed.options.task===void 0||parsed.options.run===void 0){throw new UsageError("tool copy requires --task TASK --run RUN")}const layout=await loadWorkspaceLayout(filesystem);if(layout.version===1)throw new UsageError("tool copy requires a V2 workspace");const composition=createV2Composition(filesystem,layout);const{task}=await composition.tasks.read(parsed.options.task);const{run,status}=await composition.runs.read(parsed.options.run);const executionId=resolveTaskExecutionIdV2(task,await composition.executions.list());if(!["executing","verifying"].includes(task.status)||status!=="running"||run.task_id!==task.id||run.change_id!==task.change_id||run.execution_id!==executionId){throw new UsageError("tool copy requires an active Run linked to the declared Task")}const scopes=task.write_scopes;if(parsed.options.from===void 0||parsed.options.to===void 0||scopes.length===0){throw new UsageError("tool copy requires --from PATH --to PATH and Task write scopes")}await copyWithinToolWriteScope({filesystem,root,scopes,from:parsed.options.from,to:parsed.options.to});output({copied:true,to:parsed.options.to,scopes},json2);return EXIT2.success}if(["architecture","cqrs","modules"].includes(area)&&action==="validate"){const layout=await loadWorkspaceLayout(filesystem);const profile=configuredArchitectureProfile(layout.projectConfig);const units=await sourceUnits(filesystem);const findings=area==="cqrs"?validateCqrs(units,profile):area==="modules"?validateModules(units,profile):validateArchitecture(units,profile);output({valid:findings.length===0,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}if(area==="profile"&&action==="validate"){if(parsed.options.path!==void 0){throw new UsageError("profile validate reads the configured stack in .agents/config/project.yaml; --path is no longer supported")}const configured=await loadWorkspaceLayout(filesystem);const projectConfig2=configured.projectConfig;const stack=projectConfig2?.stack;if(projectConfig2===null||stack===void 0){throw new UsageError("profile validate requires .agents/config/project.yaml")}const profile={id:stack.id,status:"supported",extensions:stack.extensions??[],defaults:{language:stack.language,api:stack.api,queryBuilder:stack.query_builder},workspaceLayout:2,conventions:{apps:stack.layout===void 0?void 0:{frontend:stack.layout.frontend,backend:stack.layout.backend,site:stack.layout.site},modules:stack.layout?.modules,packages:stack.layout?.packages,e2e:stack.layout?.e2e,source_limits:stack.source_limits},invariants:stack.invariants??[],commands:stack.commands};configuredArchitectureProfile(projectConfig2);const findings=[...validateProfileContract(profile)];const clientCatalog=parseYaml(await filesystem.readText(".agents/config/clients.yaml"));const clientPaths=await validateConfiguredProfileAgentPaths(clientCatalog,projectConfig2.clients,filesystem);findings.push(...clientPaths.findings.map(message=>({field:"clients",message})));output({valid:findings.length===0,profile:PROJECT_CONFIG_PATH,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}if(area==="eval"&&["run","specs","architecture","cqrs","security","infrastructure","adapters","context"].includes(action??"")){const report=action==="run"?runAllCategoryEvals():runCategoryEval(action);const layout=await loadWorkspaceLayout(filesystem);const persisted=parsed.flags.has("no-write")?null:layout.version!==1?await persistEvalReportV2(filesystem,layout,report,action??"run",parsed):await persistEvalReport(filesystem,report,action??"run");output({...report,persisted},json2);return report.passed?EXIT2.success:EXIT2.conformity}if(V2_COMMAND_AREAS.has(area)){const layout=await loadWorkspaceLayout(filesystem);if(layout.version!==1){output(await runV2Command(area,action,parsed,filesystem,layout),json2);return EXIT2.success}if(["prd","execution","run-v2","plan"].includes(area)){throw new UsageError(`${area} requires a V2 workspace`)}if(!isLegacyReadOnlyCommand(area,action)){throw new UsageError("V1 lifecycle is read-only; use `migrate plan` and `migrate apply` before mutation")}}if(area==="change"&&action==="show"){output(await new ChangeRepository(filesystem).read(requiredPosition(parsed.positionals,2,"change id")),json2);return EXIT2.success}if(area==="change"&&action==="validate"){const result2=await new ChangeRepository(filesystem).validate(requiredPosition(parsed.positionals,2,"change id"));output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}if(area==="spec"&&action==="show"){output(await new LegacyCapabilitySpecRepository(filesystem).read(requiredPosition(parsed.positionals,2,"capability")),json2);return EXIT2.success}if(area==="spec"&&action==="validate"){const result2=await new LegacyCapabilitySpecRepository(filesystem).read(requiredPosition(parsed.positionals,2,"capability"));output({valid:true,spec:result2.spec},json2);return EXIT2.success}if(area==="task"&&action==="list"){output(await new TaskRepository(filesystem).list(),json2);return EXIT2.success}if(area==="task"&&action==="next"){output(nextExecutableTasks(await new TaskRepository(filesystem).list()),json2);return EXIT2.success}if(area==="task"&&action==="show"){output(await new TaskRepository(filesystem).read(requiredEntityId(parsed,2,"task id")),json2);return EXIT2.success}if(area==="decision"&&action==="list"){output(await new DecisionRepository(filesystem).list(),json2);return EXIT2.success}if(area==="decision"&&action==="show"){const id=requiredPosition(parsed.positionals,2,"decision id");output(await new DecisionRepository(filesystem).read(id,id.startsWith("DEC-HUMAN-")?"human":"agent"),json2);return EXIT2.success}if(area==="run"&&action==="show"){output(await new RunRepository(filesystem).read(requiredPosition(parsed.positionals,2,"run id")),json2);return EXIT2.success}if(area==="generate"){const layout=await loadWorkspaceLayout(filesystem);if(layout.version!==1){const tasks2=await new TaskV2Repository(filesystem,layout).list();output({generated:null,storage:"stdout",board:tasks2.map(task=>({id:task.id,title:task.title,status:task.status,priority:task.priority,artifact_path:layout.activePath("task",task.id)}))},json2);return EXIT2.success}const tasks=await new TaskRepository(filesystem).list();const board=generateBoard(tasks);output({generated:null,storage:"stdout",board},json2);return EXIT2.success}if(area==="guard"&&action==="diff"){const changed=await new ShellGit(root).changedFiles();const layout=await loadWorkspaceLayout(filesystem);const ledger=layout.version!==1?await taskLedgerV2(new TaskV2Repository(filesystem,layout),changed):await taskLedger(new TaskRepository(filesystem));const findings=guardDiff(changed,ledger);output({valid:findings.length===0,changed,ledger,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}if(area==="ui"){const executable=process.argv[1];if(executable!==void 0){const executableRoot=resolve19(dirname16(executable),"..");const distributionRoot=basename6(executableRoot)===".agents"?executableRoot:resolve19(executableRoot,"..");const _distributionFilesystem=new WorkspaceFileSystem(distributionRoot);if(basename6(distributionRoot)===".agents"&&await new WorkspaceFileSystem(root).exists(".agents/dashboard/packages/local-runtime/start-dashboard.mjs")){output({url:"http://127.0.0.1:4317",security:"loopback-only"},json2);const code=await runUiServer(resolve19(root,".agents/dashboard/packages/local-runtime/start-dashboard.mjs"),root);return code}}output({command:"corepack pnpm dashboard:dev",sourceMode:true},json2);return EXIT2.success}throw new UsageError(`Unknown command: ${parsed.positionals.join(" ")}`)}catch(error51){const message=error51 instanceof Error?error51.message:String(error51);output({error:message},json2,true);return error51 instanceof UsageError?EXIT2.usage:EXIT2.error}}function isLegacyReadOnlyCommand(area,action){const actions={spec:["show","validate"],change:["show","validate"],task:["list","next","show"],decision:["list","show"],run:["show"]};return actions[area]?.includes(action)??false}var HELP=helpText(CLI_DISPLAY_VERSION);var isMain=process.argv[1]!==void 0&&pathToFileURL(resolve19(process.argv[1])).href===import.meta.url;if(isMain)process.exitCode=await runCli(process.argv.slice(2));export{CLI_DISPLAY_VERSION,CLI_VERSION,EXIT2 as EXIT,runCli};
|
|
2155
|
+
`);return{passed:checks.length===expectedChecks&&checks.every(check2=>check2.passed),risk:risk2,changed_files:changed.length,checks,log_path:logPath}}async function runProcess2(command,args,cwd){return new Promise((resolveProcess,reject)=>{const executable=process.platform==="win32"&&command==="pnpm"?"pnpm.cmd":command;const child=spawn3(executable,args,{cwd,shell:process.platform==="win32",windowsHide:true});let output2="";child.stdout?.on("data",chunk=>output2+=String(chunk));child.stderr?.on("data",chunk=>output2+=String(chunk));child.once("error",reject);child.once("close",code=>resolveProcess({code:code??1,output:output2}))})}var CLI_VERSION="3.2.0";var CLI_DISPLAY_VERSION=CLI_VERSION.replace(/\.0$/,"");var EXIT2={success:0,error:1,usage:2,conformity:3,lifecycle:4,security:5,prerequisite:6};var execFileAsync9=promisify19(execFile19);async function runCli(arguments_,cwd=process.cwd()){const parsed=parseArguments(arguments_);const requestedRoot=resolve19(parsed.options.workspace??cwd);const root=parsed.options.workspace===void 0?await new ShellGit(requestedRoot).repositoryRoot()??requestedRoot:requestedRoot;const filesystem=new WorkspaceFileSystem(root);const json2=parsed.flags.has("json");try{const[area,action]=parsed.positionals;if(area==="hook"&&action==="recover-stop"){requireOptions(parsed.options,["session","turn"]);const result2=await replayStopReceipt(filesystem,parsed.options.session,parsed.options.turn);output(result2,json2);return result2.state==="persisted"?EXIT2.success:EXIT2.lifecycle}if(area==="commit"){output(await runCommitPolicyCommand(root,parsed),json2);return EXIT2.success}if(area==="version"||parsed.flags.has("version")){output(json2?{version:CLI_VERSION}:CLI_DISPLAY_VERSION,json2);return EXIT2.success}if(area===void 0||area==="help"||parsed.flags.has("help")){output(HELP,json2);return area===void 0&&!parsed.flags.has("help")?EXIT2.usage:EXIT2.success}const activationExit=await handleZaipActivation(area,filesystem,json2);if(activationExit!==null)return activationExit;const distributionExit=await runDistributionCommand({area,action,parsed,filesystem,root,json:json2});if(distributionExit!==null)return distributionExit;if(area==="supabase"&&action==="migration"){const result2=await runSupabaseMigrationCommand({action:parsed.positionals[2],parsed,filesystem,config:(await loadWorkspaceLayout(filesystem)).projectConfig});output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}if(area==="database"&&action==="migration"){const mode=parsed.positionals[2];if(mode!=="prepare"&&mode!=="submit")throw new UsageError("database migration requires prepare or submit");requireOptions(parsed.options,["database-repository","migration-path","description","tests","risk"]);if(!["compatible","destructive","permissions","incompatible"].includes(parsed.options.risk??""))throw new UsageError("--risk must be compatible, destructive, permissions, or incompatible");const migrationPath=parsed.options["migration-path"];const[source,sql,layout]=await Promise.all([verifiedMigrationSource(root),filesystem.readText(migrationPath),loadWorkspaceLayout(filesystem)]);const actualHash=createHash48("sha256").update(sql,"utf8").digest("hex");if(parsed.options["migration-sha256"]!==void 0&&parsed.options["migration-sha256"].toLowerCase()!==actualHash)throw new UsageError("--migration-sha256 does not match the migration file");const request=prepareMigrationRequest(layout.projectConfig,{source_repository:source.repository,source_sha:source.sha,source_identity_verified:true,database_repository:parsed.options["database-repository"],migration_path:migrationPath,migration_content_sha256:actualHash,description:parsed.options.description,sql,tests:parsed.options.tests.split(",").filter(Boolean),risk:parsed.options.risk});if(mode==="submit"){requireOptions(parsed.options,["request-head","database-worktree"]);const databaseWorktree=parsed.options["database-worktree"];const requestHead=parsed.options["request-head"];const[dbOrigin,headCommit]=await Promise.all([execFileAsync9("git",["remote","get-url","origin"],{cwd:databaseWorktree,encoding:"utf8",windowsHide:true}),execFileAsync9("git",["rev-parse",requestHead],{cwd:databaseWorktree,encoding:"utf8",windowsHide:true})]);const capturedHeadSha=headCommit.stdout.trim();if(!/^[a-f0-9]{40,64}$/i.test(capturedHeadSha))throw new UsageError("request head must resolve to a commit SHA");const blob=await execFileAsync9("git",["cat-file","blob",`${capturedHeadSha}:${migrationPath}`],{cwd:databaseWorktree,encoding:"buffer",windowsHide:true});const expectedDatabase=parsed.options["database-repository"];const originMatch=/^(?:git@github\.com:|https:\/\/github\.com\/)([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?\s*$/i.exec(dbOrigin.stdout.toString());if(originMatch?.[1]?.toLowerCase()!==expectedDatabase.toLowerCase())throw new UsageError("Database worktree origin does not exactly match --database-repository");if(createHash48("sha256").update(blob.stdout).digest("hex")!==actualHash)throw new UsageError("Request head migration blob does not match local migration SQL");const migrationConfig=layout.projectConfig?.supabase_migrations;if(migrationConfig===void 0)throw new UsageError("submit requires persisted supabase_migrations configuration");if(migrationConfig.repository.id!==expectedDatabase||migrationConfig.repository.path!==databaseWorktree||migrationConfig.repository.origin!==dbOrigin.stdout.trim())throw new UsageError("submit target and database worktree must exactly match persisted supabase_migrations.repository");assertMigrationRemoteSubmission({beta_integration_verified:migrationConfig.beta_integration_verified??false,paid_beta_provisioning_confirmed:migrationConfig.paid_beta_provisioning_confirmed??false,preview_policy:migrationConfig.preview_policy??"disabled"});const submission=await submitMigrationRequest(new GhMigrationPullRequestAdapter(databaseWorktree,requestHead,capturedHeadSha),expectedDatabase,request);output({mode,request,submission,hosted_migrator:"supabase-github-integration"},json2);return EXIT2.success}output({mode,request,remote_submitted:false,hosted_migrator:"supabase-github-integration"},json2);return EXIT2.success}if(area==="adapters"&&action==="build"){await buildAdapters(filesystem);output({built:true},json2);return EXIT2.success}if(area==="adapters"&&action==="check"){const result2=await checkAdapters(filesystem);output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}if(area==="context"&&action==="inventory"){output(await inventory(filesystem),json2);return EXIT2.success}if(area==="context"&&["build","inspect"].includes(action??"")){const pack=await buildContextForCommand(filesystem,parsed,contextQuery(parsed,parsed.options.query??parsed.positionals.slice(2).join(" ")),numberOption(parsed.options.budget,8e3));if(parsed.options.run!==void 0){const layout=await loadWorkspaceLayout(filesystem);if(layout.version===1)throw new UsageError("context --run requires a modern workspace");await recordContextPackUsage(parsed.options.run,pack.estimatedTokens,createV2Composition(filesystem,layout))}output(contextPackView(parsed)==="compact"?compactContextPack(pack):pack,json2);return EXIT2.success}if(area==="context"&&action==="map"){output(await buildRepositoryMap(filesystem),json2);return EXIT2.success}if(area==="context"&&action==="agents"){try{const discovery=await resolveAgentDiscovery(filesystem,{...parsed.options.agent===void 0?{}:{agentId:parsed.options.agent}});output(parsed.options.agent===void 0?discovery:{source:discovery.source,provenance:discovery.provenance,selected:discovery.selected},json2);return EXIT2.success}catch(error51){if(error51 instanceof Error&&/agent/i.test(error51.message))throw new UsageError(error51.message);throw error51}}if(area==="context"&&action==="handoff"){output(contextHandoffForCommand(parsed),json2);return EXIT2.success}if(area==="context"&&action==="validate"){const pack=await buildContextForCommand(filesystem,parsed,contextQuery(parsed,parsed.options.query??"active task"),numberOption(parsed.options.budget,8e3));const findings=validateContextPack(pack);output({valid:findings.length===0,estimatedTokens:pack.estimatedTokens,budget:pack.budget,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}if(area==="manifest"){const layout=await loadWorkspaceLayout(filesystem);if(layout.version===1)throw new UsageError("lifecycle manifests require a modern workspace");output(await runLifecycleManifestMaintenance(action,parsed,filesystem,createV2Composition(filesystem,layout)),json2);return EXIT2.success}if(area==="cost"&&action==="cohort"){requireOptions(parsed.options,["input"]);output(await readCostCohortInput(filesystem,parsed.options.input),json2);return EXIT2.success}if(area==="verify"){if(!parsed.flags.has("changed")&&riskOption(parsed.options.risk)!=="critical"){throw new UsageError("verify requires --changed or --risk critical")}const result2=await runScopedVerification(filesystem,riskOption(parsed.options.risk));output(result2,json2);return result2.passed?EXIT2.success:EXIT2.conformity}if(area==="supabase"&&action==="migration"){const result2=await runSupabaseMigrationCommand({action:parsed.positionals[2],parsed,filesystem,config:(await loadWorkspaceLayout(filesystem)).projectConfig});output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}if(area==="tool"&&action==="copy"){if(parsed.options.task===void 0||parsed.options.run===void 0){throw new UsageError("tool copy requires --task TASK --run RUN")}const layout=await loadWorkspaceLayout(filesystem);if(layout.version===1)throw new UsageError("tool copy requires a V2 workspace");const composition=createV2Composition(filesystem,layout);const{task}=await composition.tasks.read(parsed.options.task);const{run,status}=await composition.runs.read(parsed.options.run);const executionId=resolveTaskExecutionIdV2(task,await composition.executions.list());if(!["executing","verifying"].includes(task.status)||status!=="running"||run.task_id!==task.id||run.change_id!==task.change_id||run.execution_id!==executionId){throw new UsageError("tool copy requires an active Run linked to the declared Task")}const scopes=task.write_scopes;if(parsed.options.from===void 0||parsed.options.to===void 0||scopes.length===0){throw new UsageError("tool copy requires --from PATH --to PATH and Task write scopes")}await copyWithinToolWriteScope({filesystem,root,scopes,from:parsed.options.from,to:parsed.options.to});output({copied:true,to:parsed.options.to,scopes},json2);return EXIT2.success}if(["architecture","cqrs","modules"].includes(area)&&action==="validate"){const layout=await loadWorkspaceLayout(filesystem);const profile=configuredArchitectureProfile(layout.projectConfig);const units=await sourceUnits(filesystem);const findings=area==="cqrs"?validateCqrs(units,profile):area==="modules"?validateModules(units,profile):validateArchitecture(units,profile);output({valid:findings.length===0,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}if(area==="profile"&&action==="validate"){if(parsed.options.path!==void 0){throw new UsageError("profile validate reads the configured stack in .agents/config/project.yaml; --path is no longer supported")}const configured=await loadWorkspaceLayout(filesystem);const projectConfig2=configured.projectConfig;const stack=projectConfig2?.stack;if(projectConfig2===null||stack===void 0){throw new UsageError("profile validate requires .agents/config/project.yaml")}const profile={id:stack.id,status:"supported",extensions:stack.extensions??[],defaults:{language:stack.language,api:stack.api,queryBuilder:stack.query_builder},workspaceLayout:2,conventions:{apps:stack.layout===void 0?void 0:{frontend:stack.layout.frontend,backend:stack.layout.backend,site:stack.layout.site},modules:stack.layout?.modules,packages:stack.layout?.packages,e2e:stack.layout?.e2e,source_limits:stack.source_limits},invariants:stack.invariants??[],commands:stack.commands};configuredArchitectureProfile(projectConfig2);const findings=[...validateProfileContract(profile)];const clientCatalog=parseYaml(await filesystem.readText(".agents/config/clients.yaml"));const clientPaths=await validateConfiguredProfileAgentPaths(clientCatalog,projectConfig2.clients,filesystem);findings.push(...clientPaths.findings.map(message=>({field:"clients",message})));output({valid:findings.length===0,profile:PROJECT_CONFIG_PATH,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}if(area==="eval"&&["run","specs","architecture","cqrs","security","infrastructure","adapters","context"].includes(action??"")){const report=action==="run"?runAllCategoryEvals():runCategoryEval(action);const layout=await loadWorkspaceLayout(filesystem);const persisted=parsed.flags.has("no-write")?null:layout.version!==1?await persistEvalReportV2(filesystem,layout,report,action??"run",parsed):await persistEvalReport(filesystem,report,action??"run");output({...report,persisted},json2);return report.passed?EXIT2.success:EXIT2.conformity}if(V2_COMMAND_AREAS.has(area)){const layout=await loadWorkspaceLayout(filesystem);if(layout.version!==1){output(await runV2Command(area,action,parsed,filesystem,layout),json2);return EXIT2.success}if(["prd","execution","run-v2","plan"].includes(area)){throw new UsageError(`${area} requires a V2 workspace`)}if(!isLegacyReadOnlyCommand(area,action)){throw new UsageError("V1 lifecycle is read-only; use `migrate plan` and `migrate apply` before mutation")}}if(area==="change"&&action==="show"){output(await new ChangeRepository(filesystem).read(requiredPosition(parsed.positionals,2,"change id")),json2);return EXIT2.success}if(area==="change"&&action==="validate"){const result2=await new ChangeRepository(filesystem).validate(requiredPosition(parsed.positionals,2,"change id"));output(result2,json2);return result2.valid?EXIT2.success:EXIT2.conformity}if(area==="spec"&&action==="show"){output(await new LegacyCapabilitySpecRepository(filesystem).read(requiredPosition(parsed.positionals,2,"capability")),json2);return EXIT2.success}if(area==="spec"&&action==="validate"){const result2=await new LegacyCapabilitySpecRepository(filesystem).read(requiredPosition(parsed.positionals,2,"capability"));output({valid:true,spec:result2.spec},json2);return EXIT2.success}if(area==="task"&&action==="list"){output(await new TaskRepository(filesystem).list(),json2);return EXIT2.success}if(area==="task"&&action==="next"){output(nextExecutableTasks(await new TaskRepository(filesystem).list()),json2);return EXIT2.success}if(area==="task"&&action==="show"){output(await new TaskRepository(filesystem).read(requiredEntityId(parsed,2,"task id")),json2);return EXIT2.success}if(area==="decision"&&action==="list"){output(await new DecisionRepository(filesystem).list(),json2);return EXIT2.success}if(area==="decision"&&action==="show"){const id=requiredPosition(parsed.positionals,2,"decision id");output(await new DecisionRepository(filesystem).read(id,id.startsWith("DEC-HUMAN-")?"human":"agent"),json2);return EXIT2.success}if(area==="run"&&action==="show"){output(await new RunRepository(filesystem).read(requiredPosition(parsed.positionals,2,"run id")),json2);return EXIT2.success}if(area==="generate"){const layout=await loadWorkspaceLayout(filesystem);if(layout.version!==1){const tasks2=await new TaskV2Repository(filesystem,layout).list();output({generated:null,storage:"stdout",board:tasks2.map(task=>({id:task.id,title:task.title,status:task.status,priority:task.priority,artifact_path:layout.activePath("task",task.id)}))},json2);return EXIT2.success}const tasks=await new TaskRepository(filesystem).list();const board=generateBoard(tasks);output({generated:null,storage:"stdout",board},json2);return EXIT2.success}if(area==="guard"&&action==="diff"){const changed=await new ShellGit(root).changedFiles();const layout=await loadWorkspaceLayout(filesystem);const ledger=layout.version!==1?await taskLedgerV2(new TaskV2Repository(filesystem,layout),changed):await taskLedger(new TaskRepository(filesystem));const findings=guardDiff(changed,ledger);output({valid:findings.length===0,changed,ledger,findings},json2);return findings.length===0?EXIT2.success:EXIT2.conformity}if(area==="ui"){const executable=process.argv[1];if(executable!==void 0){const executableRoot=resolve19(dirname16(executable),"..");const distributionRoot=basename6(executableRoot)===".agents"?executableRoot:resolve19(executableRoot,"..");const _distributionFilesystem=new WorkspaceFileSystem(distributionRoot);if(basename6(distributionRoot)===".agents"&&await new WorkspaceFileSystem(root).exists(".agents/dashboard/packages/local-runtime/start-dashboard.mjs")){output({url:"http://127.0.0.1:4317",security:"loopback-only"},json2);const code=await runUiServer(resolve19(root,".agents/dashboard/packages/local-runtime/start-dashboard.mjs"),root);return code}}output({command:"corepack pnpm dashboard:dev",sourceMode:true},json2);return EXIT2.success}throw new UsageError(`Unknown command: ${parsed.positionals.join(" ")}`)}catch(error51){const message=error51 instanceof Error?error51.message:String(error51);output({error:message},json2,true);return error51 instanceof UsageError?EXIT2.usage:EXIT2.error}}function isLegacyReadOnlyCommand(area,action){const actions={spec:["show","validate"],change:["show","validate"],task:["list","next","show"],decision:["list","show"],run:["show"]};return actions[area]?.includes(action)??false}var HELP=helpText(CLI_DISPLAY_VERSION);var isMain=process.argv[1]!==void 0&&pathToFileURL(resolve19(process.argv[1])).href===import.meta.url;if(isMain)process.exitCode=await runCli(process.argv.slice(2));export{CLI_DISPLAY_VERSION,CLI_VERSION,EXIT2 as EXIT,runCli};
|