diff --git a/.github/workflows/dsh-plugin-publish.yml b/.github/workflows/dsh-plugin-publish.yml index d0b662415f..6029397d9d 100644 --- a/.github/workflows/dsh-plugin-publish.yml +++ b/.github/workflows/dsh-plugin-publish.yml @@ -70,8 +70,38 @@ jobs: const exists = response.ok && !!(await response.json()).versions?.[source.version] appendFileSync(process.env.GITHUB_ENV, `DSH_ALREADY_PUBLISHED=${exists}\n`) NODE + node --input-type=module <<'NODE' + import { appendFileSync, readFileSync } from 'node:fs' + const source = JSON.parse(readFileSync('package.json', 'utf8')) + const response = await fetch(`https://registry.npmjs.org/${encodeURIComponent(source.name)}`, { + signal: AbortSignal.timeout(15_000), + }) + const missing = response.status === 404 + const body = response.ok ? await response.json() : null + const versions = Object.keys(body?.versions ?? {}) + const stagingOnly = versions.length > 0 && versions.every(v => v === '0.0.0-stage') && !versions.includes(source.version) + appendFileSync(process.env.GITHUB_ENV, `DSH_NPM_PACKAGE_MISSING=${missing}\nDSH_NPM_STAGING_PLACEHOLDER=${stagingOnly}\n`) + NODE - name: Publish the same bytes with npm trusted publishing if: env.DSH_ALREADY_PUBLISHED != 'true' - run: npm publish "$DSH_ARTIFACT" --access public --tag latest --ignore-scripts --provenance + run: | + set +e + npm publish "$DSH_ARTIFACT" --access public --tag latest --ignore-scripts --provenance + rc=$? + set -e + if [ "$rc" -ne 0 ]; then + if [ "${DSH_NPM_PACKAGE_MISSING:-false}" = "true" ]; then + echo "::error title=npm package bootstrap required::dsh-loopx-plugin returns HTTP 404 on registry.npmjs.org. npm OIDC Trusted Publishing cannot create a brand-new package: enable 2FA (auth-and-writes), run one-time web-auth 'npm publish --access public --tag latest --ignore-scripts', run 'npm logout', then bind Trusted Publisher (loopx-project / loopx / dsh-plugin-publish.yml / blank Environment name / Allow npm publish checked)." + elif [ "${DSH_NPM_STAGING_PLACEHOLDER:-false}" = "true" ]; then + echo "::error title=npm package staging scan active::registry.npmjs.org still holds 0.0.0-stage from initial publish scan; wait 1-3 minutes for the target version to activate and re-dispatch." + else + echo "::error title=npm Trusted Publisher failed::Verify npmjs Trusted Publisher settings on https://www.npmjs.com/package/dsh-loopx-plugin/access (Provider: GitHub Actions, Organization or user: loopx-project, Repository: loopx, Workflow filename: dsh-plugin-publish.yml, Environment name: empty, Allow npm publish: checked)." + fi + exit "$rc" + fi - name: Read back npm bytes, latest, and marketplace repository discovery - run: node scripts/verify-distribution.mjs --tarball "$DSH_ARTIFACT" + run: | + if git cat-file -e origin/main:packages/dsh-loopx-plugin/scripts/verify-distribution.mjs 2>/dev/null; then + git show origin/main:packages/dsh-loopx-plugin/scripts/verify-distribution.mjs > scripts/verify-distribution.mjs + fi + node scripts/verify-distribution.mjs --tarball "$DSH_ARTIFACT" diff --git a/apps/workbench/README.md b/apps/workbench/README.md index 45528115b7..c1d37dd8a7 100644 --- a/apps/workbench/README.md +++ b/apps/workbench/README.md @@ -35,7 +35,7 @@ LooChat 不动 agent 本身的目录、配置和会话,装好即用。LooChat |---|---|---|---|---| | Claude Code | ACP(`@agentclientprotocol/claude-agent-acp`,随项目安装) | 有 | 有 | 有 | | pi | `pi --mode rpc` | 无(pi 本身没有) | 有。纯文本模型需要装 pi 扩展 `pi-aux-vision` | 有 | -| Antigravity | `agy` 的无界面 stream-json 模式 | 无(不能询问,只有"自动改文件"和"完全访问"两档) | 有(按文件路径交给它) | 暂无 | +| Antigravity | `agy acp`(ACP 1) | 有 | 有(原生 ACP 图片) | 暂无 | | Codex | `codex app-server` | 有 | 有 | 有 | | TRAE CLI | app-server 执行,ACP 模型与历史接口 | 有 | 有 | 有 | | zcode | `zcode app-server` 精简接入 | 有 | 按原生模型能力 | 暂无 | @@ -67,6 +67,20 @@ LooChat 不动 agent 本身的目录、配置和会话,装好即用。LooChat 认证识别遵循原生协议:[ACP 的认证错误](https://agentclientprotocol.com/protocol/v1/authentication)、Codex 的 `account/read`(仅在 `requiresOpenaiAuth` 为真且账号为空时判断未登录),以及 CLI 明确的登录或缺失凭据诊断。Codex 自定义服务和旧版账号协议保留原有目录行为。 +### Antigravity 模型与思考强度 + +需要支持 `agy acp` 的原生 CLI。同一模型的多种强度合并为一个模型选项,在输入框的模型控件中打开「思考强度」滑块即可调整。可选档位来自该账号的模型目录;只有一个固定强度的模型保留原 ID,不显示可调滑块。模型列表中可手动刷新,其他客户端刷新的结果也会同步到打开的列表。 + +模型和强度通过 ACP 在当前会话内切换;调整后继续发送即可。旧的 `模型-high` 等选择在目录可识别时转换为模型与强度,当前会话、归档会话和该账号的已保存偏好保留原强度。明确设置的强度优先,目录读取失败不会重置选择。 + +Agy 的权限请求使用现有审批入口;已有「完全访问」默认值保留。图片通过原生 ACP 图片块传入,上下文占用使用 ACP 用量事件;`/compact` 在当前会话内执行,并显示成功、失败或取消。旧的原生会话 ID 通过 `session/resume` 恢复。登录和 `/usage` 等账号查询继续走已有原生 CLI 入口。 + +下图使用隔离测试目录与假 Agent,展示实际构建页面中的模型分组和强度选择: + +![按模型归并的目录](docs/images/antigravity-model-families.png) + +手机中调整 Antigravity 思考强度,当前会话保留 + ### Antigravity 登录 若读取模型时尚未登录,当前页面会显示「Antigravity 尚未登录」和「去登录」。点击后在原位置展开授权面板;登录验证成功后自动加载模型列表,无需刷新页面。若此时模型读取暂时失败,可以重试读取,不必重复授权。网络或 CLI 故障仍单独显示为错误。 diff --git a/apps/workbench/THIRD_PARTY_NOTICES.md b/apps/workbench/THIRD_PARTY_NOTICES.md index 790db1a6d5..12613d13f5 100644 --- a/apps/workbench/THIRD_PARTY_NOTICES.md +++ b/apps/workbench/THIRD_PARTY_NOTICES.md @@ -38,6 +38,11 @@ quoted side-chat model selection from `80eb16edbd3e2cc3e2a3c887a2560fe39b6ab209` including the current local SideChat preference/catalog refinements. Existing Loochat message-draft protections and machine-scoped provenance are retained. +Antigravity model-family/effort selection and legacy preference compatibility are adapted from +Calli `d89d2656d707ba9b152178be4343f9112fd87c72`; the ACP conversation transport and +its protocol fixtures from `96f3dade4c603778d48a494f53753b888b5e1c26`. The port retains +Loochat's typed login recovery and prompt-submission lifecycle. + Collaboration mail batching and progress semantics are adapted from Calli `edf2708` and `2ee2853`; member composer controls from `26ad76d`; the shared conversation panel from `556dc46`; collaboration handover diagnostics from diff --git a/apps/workbench/docs/images/antigravity-effort-phone.png b/apps/workbench/docs/images/antigravity-effort-phone.png new file mode 100644 index 0000000000..aa9a114c15 Binary files /dev/null and b/apps/workbench/docs/images/antigravity-effort-phone.png differ diff --git a/apps/workbench/docs/images/antigravity-model-families.png b/apps/workbench/docs/images/antigravity-model-families.png new file mode 100644 index 0000000000..4a13d8ad55 Binary files /dev/null and b/apps/workbench/docs/images/antigravity-model-families.png differ diff --git a/apps/workbench/packages/daemon/src/adapters/agy.ts b/apps/workbench/packages/daemon/src/adapters/agy.ts index 199604394f..90f62c1eb0 100644 --- a/apps/workbench/packages/daemon/src/adapters/agy.ts +++ b/apps/workbench/packages/daemon/src/adapters/agy.ts @@ -1,24 +1,22 @@ -import { HttpError } from '../errors.js'; -import { AGY_AUTH_ENV, copyAgyAccount, startAgyLogin } from './agy-account.js'; import type { WorkMode } from './types.js'; -import { cliDiagnostic } from './diagnostics.js'; +import { AcpAdapter, type AcpSession } from './acp.js'; +import type { UsageSample } from '../telemetry.js'; +import { isCompaction } from './compaction.js'; +import { AGY_AUTH_ENV, copyAgyAccount, startAgyLogin } from './agy-account.js'; +import { HttpError } from '../errors.js'; import { PlanReply } from './plan-reply.js'; -import { sessionEnvironment } from './types.js'; -import { execFile, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'; +import { execFile } from 'node:child_process'; import { homedir } from 'node:os'; import { basename, dirname, join } from 'node:path'; import { access, copyFile, cp, mkdir, readdir } from 'node:fs/promises'; -import type { EmittedEvent } from '../events.js'; -import { imagePathNote } from '../attachments.js'; -import { commandExists } from '../util.js'; import { ANTIGRAVITY_ICON } from './icons.js'; import { configDirectory, findSessionFile, quoteArg } from './session-location.js'; import { agyLiveUsage } from './session-usage.js'; import { agyImageTool } from './agy-image.js'; import { agyBrowserTool, agySearchTool } from './agy-web.js'; import type { - AgentAdapter, AgentSession, + EffortLevel, ModelOption, PermissionMode, PlanQuota, @@ -26,37 +24,12 @@ import type { SkillDir, SlashCommand, StartOptions, - TurnHooks, - TurnInput, - TurnResult, } from './types.js'; -/** - * Antigravity CLI ("agy"), driven through its headless print mode with one JSON object per line - * in both directions: - * - * agy --input-format stream-json --output-format stream-json [flags] -p= - * - * The process announces its conversation with an `init` event as soon as it starts, then runs one - * turn per input line: `step_update` events while it works and a `result` event at the end. - * - * What headless mode cannot do shapes this adapter: - * - It cannot ask for permission. Anything that needs approval is refused, so there are two levels - * only: edits approved automatically, or everything approved. - * - Permission level and model are command-line flags, so changing one restarts the process on the - * same conversation. - * - Input is text only, so pictures are passed as file paths; agy looks at them with its own file - * viewer. The stream carries neither thinking text nor file contents. - */ +/** Antigravity uses ACP for conversations; print mode remains for account queries only. */ /** How long the command list is reused. Reading it takes two short agy runs. */ const COMMANDS_TTL_MS = 10 * 60_000; -/** - * Commands agy lists but that make no sense here: the model and effort are flags of the session's - * process (the hub's own pickers set them), so a one-off run could not change them. - */ -const AGY_SKIPPED_COMMANDS = new Set(['model', 'effort']); - /** A command agy answers itself, as `agy -p /help` lists it: "/usage (quota)View model quota usage". */ export interface AgyCliCommand { name: string; @@ -131,335 +104,70 @@ export function formatAgyOutput(stdout: string): string { return [header, rule, ...rows.map((r) => `|${pad(r).map(cell).join('|')}|`)].join('\n'); } -/** How long a new process may take to announce its conversation. Startup is normally about two seconds. */ -const INIT_TIMEOUT_MS = 30_000; -/** How long a cancelled turn may take to stop before the process is killed outright. */ -const CANCEL_GRACE_MS = 5_000; -/** How long the model list is reused. Asking agy for it takes a network round trip. */ const MODELS_TTL_MS = 10 * 60_000; -const AGY_TOOL_KIND: Record = { - run_command: 'execute', - command_status: 'execute', - send_command_input: 'execute', - view_file: 'read', - list_dir: 'read', - read_url_content: 'read', - write_to_file: 'edit', - replace_file_content: 'edit', - multi_replace_file_content: 'edit', - sed_file: 'edit', - notebook_edit: 'edit', - grep_search: 'search', - find_by_name: 'search', - search_web: 'search', -}; - -const AGY_VERB: Record = { write_to_file: 'Write', view_file: 'Read', list_dir: 'List' }; - -/** A short line for the step list, such as the command or the file being touched. */ -function agyToolTitle(name: string, params: any): string { - if (name === 'run_command') return String(params?.CommandLine ?? name).split('\n')[0]; - const path = params?.TargetFile ?? params?.AbsolutePath ?? params?.DirectoryPath; - if (typeof path === 'string' && path) { - const verb = AGY_VERB[name] ?? (AGY_TOOL_KIND[name] === 'edit' ? 'Edit' : name); - return `${verb} ${path}`; - } - const target = params?.Query ?? params?.Pattern ?? params?.Url; - return typeof target === 'string' && target ? `${name} ${target}` : name; -} +/** Reasoning effort levels accepted by `agy --effort`. */ +export const AGY_EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'] as const; +const AGY_EFFORT_SUFFIX = /^(.+)-(low|medium|high|xhigh|max)$/; +const AGY_EFFORT_LABEL = /\s*\((?:low|medium|high|xhigh|max)\)\s*$/i; /** - * Maps one `step_update` to unified events. Pure, so it can be tested without a process. - * `started` holds the steps already announced, so a step that finishes without having been seen - * active still gets its start. + * The model list as `agy models` prints it: one `idlabel` per line. Variants of one model + * family (`gemini-4-argon-low`, `-medium`, `-high`) fold into a single family entry with its + * ordered `efforts`, matching `agy`'s own model/effort picker; single-variant models stay fixed. */ -export function mapAgyStep(step: any, started: Set): EmittedEvent[] { - const type = step?.step_type; - if (type === 'agent_response') { - return typeof step.text_delta === 'string' && step.text_delta ? [{ type: 'message.delta', data: { text: step.text_delta } }] : []; - } - if (type !== 'tool' && type !== 'subagent') return []; // user_input, system_message - - const index = Number(step.step_index); - const id = `agy-step-${index}`; - const out: EmittedEvent[] = []; - if (!started.has(index)) { - started.add(index); - const name = String(step.tool_name ?? step.tool_info?.name ?? 'tool'); - const sub = step.subagent_info?.subagents?.[0]; - out.push({ - type: 'tool.start', - data: { - id, - title: sub ? `${sub.role ?? sub.type_name ?? 'Subagent'}: ${String(sub.initial_prompt ?? '').split('\n')[0]}` : agyToolTitle(name, step.tool_info?.parameters), - kind: AGY_TOOL_KIND[name] ?? 'other', - status: 'in_progress', - // The name the model called, kept for the activity page. - ...(name ? { tool: name } : {}), - ...(sub?.type_name ? { subagentType: sub.type_name } : {}), - input: sub ? { prompt: sub.initial_prompt } : step.tool_info?.parameters, - }, - }); - } - if (step.state === 'DONE' || step.state === 'ERROR') { - const failed = step.state === 'ERROR' || Boolean(step.tool_info?.error); - out.push({ - type: 'tool.end', - data: { id, status: failed ? 'failed' : 'completed', output: String(step.tool_info?.error?.message ?? step.tool_info?.output ?? '') }, - }); - } - return out; -} - -/** How a turn ended, from agy's `result` event. `cancelled` says whether the hub asked it to stop. */ -export function agyTurnResult(result: any, cancelled: boolean): TurnResult { - if (result?.status !== 'SUCCESS') { - if (cancelled || result?.error === 'interrupted') return { stopReason: 'cancelled' }; - return { stopReason: 'error', error: String(result?.error ?? 'agy reported an error') }; - } - const denied = Array.isArray(result.denied_actions) ? result.denied_actions : []; - if (denied.length > 0) { - const refused = [...new Set(denied.map((d: any) => String(d?.display_name ?? d?.action ?? 'an action')))]; - return { - stopReason: 'error', - error: `Antigravity refused ${refused.join(', ')}: without a terminal it cannot ask for permission, so the turn stopped there. Switch this thread to full access and send the message again.`, - errorCode: 'permission_refused', - refused, - }; - } - return { stopReason: 'end_turn' }; -} - -/** The model list as `agy models` prints it: one `idlabel` per line. Anything else is ignored. */ export function parseAgyModels(stdout: string): ModelOption[] { - const models: ModelOption[] = []; + const rows: Array<{ id: string; label: string; baseId?: string; effort?: EffortLevel }> = []; + const familyEfforts = new Map>(); for (const line of stdout.split('\n')) { const tab = line.indexOf('\t'); if (tab <= 0) continue; const id = line.slice(0, tab).trim(); const label = line.slice(tab + 1).trim(); - // Effort is part of the model id here ("…-high", "…-low"). Images go in as paths, for every model. - if (id && !/\s/.test(id)) models.push({ id, label: label || id, efforts: [] }); - } - return models; -} - -/** Flags for one process. Exported so the mapping from the hub's settings is tested directly. */ -export function agyArgs(opts: { conversationId?: string; permissionMode?: PermissionMode; model?: string; workMode?: WorkMode }): string[] { - return [ - '--input-format', - 'stream-json', - '--output-format', - 'stream-json', - ...(opts.workMode === 'plan' ? ['--mode', 'plan'] : opts.permissionMode === 'full_access' ? ['--dangerously-skip-permissions'] : ['--mode', 'accept-edits']), - ...(opts.model ? ['--model', opts.model] : []), - ...(opts.conversationId ? ['--conversation', opts.conversationId] : []), - '-p=', // print mode with no prompt of its own: prompts arrive on stdin - ]; -} - -interface Turn { - hooks: TurnHooks; - resolve(result: TurnResult): void; - started: Set; - cancelled: boolean; - /** In plan mode, the reply held back until it is known whether it is the plan. */ - plan?: PlanReply; -} - -class AgySession implements AgentSession { - private preparing: Promise = Promise.resolve(); - agentSessionId = ''; - private child: ChildProcessWithoutNullStreams | null = null; - private buffer = ''; - private stderrTail = ''; - private ready: { resolve(): void; reject(err: Error): void } | null = null; - private turn: Turn | null = null; - /** A setting changed: the next turn needs a fresh process. */ - private stale = false; - private permissionMode: PermissionMode | undefined; - - constructor( - private readonly command: string[], - private readonly opts: StartOptions, - /** Answers a command agy handles itself (such as /usage), or resolves to null for anything else. */ - private readonly answerCommand: (text: string) => Promise, - /** Environment overrides of the agent instance this session belongs to. */ - private readonly env: Record = {}, - ) { - this.agentSessionId = opts.resumeId ?? ''; - this.permissionMode = opts.permissionMode; - } - - /** Starts a process on this session's conversation and waits until it has announced itself. */ - async launch(): Promise { - const [bin, ...base] = this.command; - const args = agyArgs({ conversationId: this.agentSessionId || undefined, permissionMode: this.permissionMode, model: this.opts.model, workMode: this.opts.workMode }); - const child = spawn(bin, [...base, ...args], { cwd: this.opts.cwd, stdio: ['pipe', 'pipe', 'pipe'], env: sessionEnvironment(this.env, this.opts.coordinationEnv) }); - this.child = child; - this.buffer = ''; - this.stderrTail = ''; - this.stale = false; - - child.stdin.on('error', () => undefined); // a write to a process that just died; its exit is what gets reported - child.stdout.setEncoding('utf8'); - child.stdout.on('data', (chunk: string) => this.onData(child, chunk)); - child.stderr.setEncoding('utf8'); - child.stderr.on('data', (chunk: string) => { - this.stderrTail = (this.stderrTail + chunk).slice(-600); - for (const line of chunk.split('\n')) if (line.trim()) console.error(`[agy] ${line}`); - }); - child.on('exit', (code, signal) => this.onExit(child, `agy exited (code=${code}, signal=${signal})`)); - child.on('error', (err) => this.onExit(child, `agy could not be started: ${err.message}`)); - - let timer: NodeJS.Timeout | undefined; - try { - await new Promise((resolve, reject) => { - this.ready = { resolve, reject }; - timer = setTimeout(() => reject(new Error('agy did not start in time')), INIT_TIMEOUT_MS); - }); - } catch (err) { - await this.close(); - throw err; - } finally { - clearTimeout(timer); - this.ready = null; - } - } - - private onData(child: ChildProcessWithoutNullStreams, chunk: string): void { - if (child !== this.child) return; // a process that has been replaced - this.buffer += chunk; - let idx: number; - while ((idx = this.buffer.indexOf('\n')) >= 0) { - const line = this.buffer.slice(0, idx).trim(); - this.buffer = this.buffer.slice(idx + 1); - if (line) this.onRecord(line); - } - } - - private onRecord(line: string): void { - let record: any; - try { - record = JSON.parse(line); - } catch { - console.error(`[agy] non-JSON line on stdout: ${line.slice(0, 200)}`); - return; - } - if (record.event === 'init') { - if (record.conversation_id) this.agentSessionId = String(record.conversation_id); - this.ready?.resolve(); - } else if (record.event === 'step_update' && this.turn) { - const { hooks, plan } = this.turn; - for (const ev of mapAgyStep(record.step_update, this.turn.started)) { - if (plan && ev.type === 'message.delta') plan.add(String(ev.data.text ?? '')); - else { - if (plan && ev.type === 'tool.start') plan.aside(); - hooks.emit(ev); - } + if (!id || /\s/.test(id)) continue; + const m = AGY_EFFORT_SUFFIX.exec(id); + if (m) { + const baseId = m[1]; + const effort = m[2] as EffortLevel; + let set = familyEfforts.get(baseId); + if (!set) { + set = new Set(); + familyEfforts.set(baseId, set); } - } else if (record.event === 'result' && this.turn) { - // After an interrupted or failed turn the process is on its way out; the next turn gets a new one. - if (record.result?.status !== 'SUCCESS') this.stale = true; - this.finishTurn(agyTurnResult(record.result, this.turn.cancelled)); + set.add(effort); + rows.push({ id, label: label || id, baseId, effort }); + } else { + rows.push({ id, label: label || id }); } } - - private finishTurn(result: TurnResult): void { - const turn = this.turn; - if (!turn) return; - turn.plan?.finish(result.stopReason === 'end_turn'); - this.turn = null; - turn.resolve(result); - } - - private onExit(child: ChildProcessWithoutNullStreams, reason: string): void { - if (child !== this.child) return; - this.child = null; - const detail = this.stderrTail.trim().split('\n').pop(); - const message = detail ? `${reason}: ${detail}` : reason; - this.ready?.reject(new Error(message)); - if (this.turn) this.finishTurn(this.turn.cancelled ? { stopReason: 'cancelled' } : { stopReason: 'error', error: message }); - } - - async prompt(input: TurnInput, hooks: TurnHooks): Promise { - let prepared!: () => void; - this.preparing = new Promise(resolve => { prepared = resolve; }); - try { return await this.promptInternal(input, hooks, prepared); } - finally { prepared(); } - } - - private async promptInternal(input: TurnInput, hooks: TurnHooks, prepared: () => void): Promise { - if (this.turn) throw new Error('a turn is already running'); - // Commands agy answers itself never reach the model, and do not work in stream mode at all. - if (input.text.startsWith('/') && input.images.length === 0) { - try { - const answer = await this.answerCommand(input.text); - if (answer !== null) { - hooks.emit({ type: 'message.delta', data: { text: answer } }); - return { stopReason: 'end_turn' }; - } - } catch (err) { - return { stopReason: 'error', error: err instanceof Error ? err.message : String(err) }; - } + const models: ModelOption[] = []; + const seen = new Set(); + for (const row of rows) { + const efforts = row.baseId ? familyEfforts.get(row.baseId) : undefined; + if (row.baseId && efforts && efforts.size > 1) { + if (seen.has(row.baseId)) continue; + seen.add(row.baseId); + const label = row.label.replace(AGY_EFFORT_LABEL, '').trim() || row.baseId; + models.push({ + id: row.baseId, + label, + efforts: AGY_EFFORTS.filter((e) => efforts.has(e)), + ...(models.length === 0 ? { isDefault: true } : {}), + }); + } else { + if (seen.has(row.id)) continue; + seen.add(row.id); + models.push({ + id: row.id, + label: row.label, + efforts: [], + ...(models.length === 0 ? { isDefault: true } : {}), + }); } - // The process is gone after a cancel, and out of date after a settings change. - if (this.child && this.stale) await this.close(); - if (!this.child) await this.launch(); - const child = this.child!; - const live = agyLiveUsage(this.agentSessionId, this.opts.cwd, this.env, sample => hooks.emit({ type: 'usage.sample', data: { ...sample } })); - await live.start(); - if (this.child !== child) { await live.stop(); return { stopReason: 'error', error: 'agy 已退出' }; } - try { return await new Promise((resolve) => { - // agy's plan mode has no plan of its own to send: what it answers with is the plan. - const plan = this.opts.workMode === 'plan' ? new PlanReply((ev) => hooks.emit(ev), 'plan') : undefined; - this.turn = { hooks, resolve, started: new Set(), cancelled: false, plan }; - child.stdin.write(JSON.stringify({ event: 'user', message: { content: input.text + imagePathNote(input.images) } }) + '\n'); - prepared(); - }); } finally { await live.stop(); } - } - - /** Takes effect on the next turn: the level is a flag of the process. */ - async setWorkMode(mode: WorkMode): Promise { - if ((this.opts.workMode ?? 'execute') === mode) return; - this.opts.workMode = mode; - this.stale = true; - } - - async setPermissionMode(mode: PermissionMode): Promise { - if (mode === this.permissionMode) return; - this.permissionMode = mode; - this.stale = true; - } - - /** agy stops a turn on SIGINT, reports it as interrupted and exits; the conversation stays usable. */ - async cancel(): Promise { - await this.preparing; - const child = this.child; - if (!this.turn || !child) return; - this.turn.cancelled = true; - child.kill('SIGINT'); - setTimeout(() => { - if (this.child === child && this.turn?.cancelled) child.kill('SIGKILL'); - }, CANCEL_GRACE_MS).unref(); - } - - async close(): Promise { - const child = this.child; - if (!child) return; - this.child = null; - if (this.turn) this.finishTurn({ stopReason: 'cancelled' }); - child.stdin.end(); - child.kill(); } + return models; } -/** - * Copies a directory's files from one listing of it: a live conversation rotates its newest chunk - * away while it is being read, and one entry gone is no reason to lose the rest, let alone to hang - * a recursive copy on a folder that keeps changing under it. - */ export async function copyDirectorySnapshot(from: string, to: string): Promise { const entries = await readdir(from, { withFileTypes: true }); await mkdir(to, { recursive: true }); @@ -478,7 +186,8 @@ export const AGY_METADATA = { }; /** Adapter for the Antigravity CLI. `command` is the argv prefix, normally just the executable. */ -export class AgyAdapter implements AgentAdapter { +export class AgyAdapter extends AcpAdapter { + readonly prewarm = true; readonly borrowedTools = [agyImageTool, agySearchTool, agyBrowserTool]; readonly id = 'agy'; readonly label = AGY_METADATA.label; @@ -488,36 +197,40 @@ export class AgyAdapter implements AgentAdapter { coordination: true, resume: true, modelSwitch: true, - approvals: false, - permissionModes: ['auto_edit', 'full_access'] as const, - // It cannot ask, so at the lower level every command is refused and the turn stops; new threads - // start where it can actually work. + approvals: true, + compact: true, + permissionModes: ['ask', 'auto_edit', 'full_access'] as const, + // Preserve the existing default; ACP permission requests are approved by the client in this mode. defaultPermissionMode: 'full_access' as const, - effortLevels: [] as const, + effortLevels: AGY_EFFORTS, images: true, deleteSession: false, history: false, fork: false, forkAt: false, multiAccount: false, + createAccount: true, forkInto: false, quota: true, }; - onModelsChanged?: (models: ModelOption[]) => void; - private modelGeneration = 0; private modelCache: { at: number; models: ModelOption[] } | null = null; + private modelGeneration = 0; + onModelsChanged?: (models: ModelOption[]) => void; private readonly commandCache = new Map }>(); constructor( - private readonly command: string[] = ['agy'], + private readonly cliCommand: string[] = ['agy'], /** Extra environment for this agent instance, such as a second account's home. */ - private readonly env: Record = {}, - ) {} + env: Record = {}, + ) { super([...cliCommand, 'acp'], env); } - diagnose() { return cliDiagnostic(this.command, this.env, 'stream-json'); } + protected readonly modeIds = { ask: ['default'], auto_edit: ['accept-edits'], full_access: ['auto'] }; + protected override resumeVia = 'session/resume' as const; - async available(): Promise { - return commandExists(this.command[0]); + protected override liveUsage(id: string, cwd: string, emit: (sample: UsageSample) => void) { + // Per-request telemetry still comes from the transcript; ACP supplies context occupancy and + // a per-turn total. AcpSession's ledger subtracts the already reported requests from that total. + return agyLiveUsage(id, cwd, this.env, emit); } createAccount(directory: string): Promise> { @@ -526,11 +239,14 @@ export class AgyAdapter implements AgentAdapter { } startLogin(onSuccess: (account?: string) => Promise) { - return startAgyLogin(this.command, this.env, async account => { + return startAgyLogin(this.cliCommand, this.env, async account => { this.modelCache = null; this.modelGeneration++; this.commandCache.clear(); + this.commandsByCwd.clear(); + this.latestCommands = []; await onSuccess(account); + // Catalog propagation can lag behind OAuth. Do not turn a model lookup failure into a login failure. void this.models(true).catch(() => {}); }); } @@ -556,7 +272,7 @@ export class AgyAdapter implements AgentAdapter { if (refresh) { this.modelCache = null; this.modelGeneration++; } if (this.modelCache && Date.now() - this.modelCache.at < MODELS_TTL_MS) return this.modelCache.models; const generation = this.modelGeneration; - const [bin, ...base] = this.command; + const [bin, ...base] = this.cliCommand; const stdout = await new Promise((resolve, reject) => { execFile(bin, [...base, 'models'], { timeout: 30_000, env: { ...process.env, ...this.env } }, (err, out, stderr) => { if (!err) { resolve(out); return; } @@ -576,7 +292,7 @@ export class AgyAdapter implements AgentAdapter { /** One `agy -p ` run, for the commands agy answers itself. Resolves to what it printed. */ private runPrint(cwd: string, text: string): Promise { - const [bin, ...base] = this.command; + const [bin, ...base] = this.cliCommand; return new Promise((resolve, reject) => { execFile(bin, [...base, '-p', text], { cwd, timeout: 60_000, maxBuffer: 4 * 1024 * 1024, env: { ...process.env, ...this.env } }, (err, stdout, stderr) => { if (!err) return resolve(stdout); @@ -594,7 +310,7 @@ export class AgyAdapter implements AgentAdapter { const hit = this.commandCache.get(cwd); if (hit && Date.now() - hit.at < COMMANDS_TTL_MS) return hit.value; const value = Promise.all([this.runPrint(cwd, '/help'), this.runPrint(cwd, '/skills').catch(() => '')]).then(([help, skills]) => { - const cli = parseAgyHelp(help).filter((c) => !AGY_SKIPPED_COMMANDS.has(c.name)); + const cli = parseAgyHelp(help).filter((c) => ['usage', 'help', 'skills', 'changelog'].includes(c.name)); const list: SlashCommand[] = [ ...cli.map((c): SlashCommand => ({ name: c.name, description: c.description, kind: 'command' })), ...parseAgySkills(skills), @@ -607,10 +323,12 @@ export class AgyAdapter implements AgentAdapter { } async commands(cwd?: string): Promise { + const native = await super.commands(cwd); try { - return (await this.loadCommands(cwd ?? process.cwd())).list; + const queries = (await this.loadCommands(cwd ?? process.cwd())).list; + return [...native, ...queries.filter(c => !native.some(n => n.name === c.name))]; } catch { - return []; + return native; } } @@ -619,7 +337,7 @@ export class AgyAdapter implements AgentAdapter { const name = /^\/([\w:-]+)/.exec(text.trim())?.[1]; if (!name) return null; // A native goal belongs to the current conversation, never the short-lived query process. - if (name === 'goal') return null; + if (!['usage', 'quota', 'help', 'skills', 'changelog'].includes(name)) return null; let cli: AgyCliCommand[]; try { cli = (await this.loadCommands(cwd)).cli; @@ -633,7 +351,7 @@ export class AgyAdapter implements AgentAdapter { resumeCommand(agentSessionId: string): string { const prefix = Object.entries(this.env).filter(([key, value]) => ['HOME', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_CACHE_HOME'].includes(key) || (AGY_AUTH_ENV.includes(key) && value === '')) .map(([key, value]) => `${key}=${quoteArg(value)}`).join(' '); - return `${prefix ? `env ${prefix} ` : ''}${this.command.map(quoteArg).join(' ')} --conversation ${quoteArg(agentSessionId)}`; + return `${prefix ? `env ${prefix} ` : ''}${this.cliCommand.map(quoteArg).join(' ')} --conversation ${quoteArg(agentSessionId)}`; } async sessionLocation(agentSessionId: string | null, cwd: string) { @@ -686,13 +404,51 @@ export class AgyAdapter implements AgentAdapter { return [join(home, 'brain', agentSessionId)]; } - async start(opts: StartOptions): Promise { - const session = new AgySession(this.command, opts, (text) => this.answer(opts.cwd, text), this.env); - await session.launch(); - if (!session.agentSessionId) { - await session.close(); - throw new Error('agy did not report a conversation id'); - } + override async start(opts: StartOptions): Promise { + const session = await super.start({ ...opts, permissionMode: opts.permissionMode ?? this.capabilities.defaultPermissionMode }); + const prompt = session.prompt.bind(session); + session.prompt = async (input, hooks) => { + if (!input.images.length && /^\/(?:usage|quota|help|skills|changelog)(?:\s|$)/.test(input.text.trim())) { + try { + const answer = await this.answer(opts.cwd, input.text); + if (answer !== null) { hooks.emit({ type: 'turn.phase', data: { phase: 'prompt_sent' } }); hooks.emit({ type: 'message.delta', data: { text: answer } }); return { stopReason: 'end_turn' }; } + } catch (err) { return { stopReason: 'error', error: String(err instanceof Error ? err.message : err) }; } + } + return prompt(input, hooks); + }; return session; } + + protected override configureSession(session: AcpSession): void { + let mode: WorkMode = 'execute'; + let permission: PermissionMode = this.capabilities.defaultPermissionMode; + const setMode = session.setWorkMode.bind(session); + session.setWorkMode = async value => { await setMode(value); mode = value; }; + const setPermission = session.setPermissionMode.bind(session); + session.setPermissionMode = async value => { await setPermission(value); permission = value; }; + const update = session.onUpdate.bind(session); + session.onUpdate = value => { + const u = value as { sessionUpdate?: string; currentModeId?: string }; + if (u?.sessionUpdate === 'current_mode_update') mode = u.currentModeId === 'plan' ? 'plan' : 'execute'; + update(value); + }; + const prompt = session.prompt.bind(session); + session.prompt = async (input, hooks) => { + const plan = mode === 'plan' && !isCompaction(input.text) ? new PlanReply(hooks.emit, `agy-plan-${Date.now()}`) : null; + const result = await prompt(input, { + ...hooks, + requestApproval: req => { + const allow = permission === 'full_access' && mode !== 'plan' + ? req.options.find(o => o.kind === 'allow_once') ?? req.options.find(o => o.kind === 'allow_always') : undefined; + return allow ? Promise.resolve({ optionId: allow.optionId }) : hooks.requestApproval(req); + }, + emit: ev => { + if (plan && ev.type === 'message.delta') plan.add(String(ev.data.text ?? '')); + else { if (ev.type === 'tool.start') plan?.aside(); hooks.emit(ev); } + }, + }); + plan?.finish(result.stopReason === 'end_turn'); + return result; + }; + } } diff --git a/apps/workbench/packages/daemon/src/threads.ts b/apps/workbench/packages/daemon/src/threads.ts index 70021db9d2..dc498aaa40 100644 --- a/apps/workbench/packages/daemon/src/threads.ts +++ b/apps/workbench/packages/daemon/src/threads.ts @@ -1088,16 +1088,45 @@ export class ThreadManager { return entry.value; } + private splitCombinedModel(models: ModelOption[], model: string | null | undefined): { option: ModelOption; effort: EffortLevel } | null { + if (!model || models.some((m) => m.id === model)) return null; + for (const option of models) { + for (const effort of option.efforts ?? []) { + if (model === `${option.id}-${effort}`) return { option, effort }; + } + } + return null; + } + + private migrateCombinedModels(agent: string, models: ModelOption[]): void { + if (!models.length) return; + for (const thread of [...this.store.listThreads(), ...this.store.listThreads({ archived: true })]) { + if (thread.agent !== agent || !thread.model) continue; + const split = this.splitCombinedModel(models, thread.model); + if (!split) continue; + this.store.updateThread(thread.id, { model: split.option.id, effort: (thread.effort as EffortLevel | null) ?? split.effort }); + this.emitThreadEvent(thread.id, null, 'thread.updated', {}); + } + const saved = readModelPreferences(this.store.hubSetting(DRAFT_MODEL_PREFERENCES_KEY, {}))[agent]; + const split = this.splitCombinedModel(models, saved?.model); + if (split) this.rememberModelPreference(agent, { model: split.option.id, effort: (saved?.effort as EffortLevel | null) ?? split.effort }); + } + private adapterModels(adapter: AgentAdapter, refresh = false): Promise { + const agent = [...this.adapters].find(([, current]) => current === adapter)?.[0]; adapter.onModelsChanged = models => { // Instance ids can differ from adapter ids; removed/replaced instances must not publish. - const agent = [...this.adapters].find(([, current]) => current === adapter)?.[0]; - if (!agent) return; + const id = [...this.adapters].find(([, current]) => current === adapter)?.[0]; + if (!id) return; + this.migrateCombinedModels(id, models); const event: StoredEvent = { threadId: '', seq: 0, turnId: null, type: 'agent.modelsChanged', - ts: new Date().toISOString(), data: { agent, models } }; + ts: new Date().toISOString(), data: { agent: id, models } }; for (const listener of this.listeners) listener(event); }; - return adapter.models(refresh).catch(error => { throw modelLoginFailure(error, adapter.label); }); + return adapter.models(refresh).then(models => { + if (agent && this.adapters.get(agent) === adapter) this.migrateCombinedModels(agent, models); + return models; + }).catch(error => { throw modelLoginFailure(error, adapter.label); }); } async listModels(agent: string, refresh = false): Promise { @@ -1852,7 +1881,7 @@ export class ThreadManager { if (updates.model === null) { // Back to the agent's own default: only a restart can do that. patch.model = null; - await this.restartForChange(thread, 'model'); + if (thread.model !== null) await this.restartForChange(thread, 'model'); } else { const model = await this.validateModel(thread.agent, updates.model); patch.model = model; @@ -1864,7 +1893,7 @@ export class ThreadManager { if (updates.effort !== undefined) { if (updates.effort === null) { patch.effort = null; - await this.restartForChange(thread, 'effort'); + if (thread.effort !== null) await this.restartForChange(thread, 'effort'); } else { const effort = await this.validateEffort(thread.agent, nextModel, updates.effort); patch.effort = effort; @@ -2007,7 +2036,7 @@ export class ThreadManager { */ private async modelOption(adapter: AgentAdapter, model: string | null): Promise { const options = await this.adapterModels(adapter); - if (model !== null) return options.find((o) => o.id === model); + if (model !== null) return options.find((o) => o.id === model) ?? this.splitCombinedModel(options, model)?.option; return options.find((o) => o.id === 'default') ?? options.find((o) => o.isDefault); } diff --git a/apps/workbench/packages/daemon/test/adapters.test.ts b/apps/workbench/packages/daemon/test/adapters.test.ts index 1efc9f41e1..51e049d8f2 100644 --- a/apps/workbench/packages/daemon/test/adapters.test.ts +++ b/apps/workbench/packages/daemon/test/adapters.test.ts @@ -681,133 +681,67 @@ test('pi fork points are matched to turns by what was asked, not by position', ( assert.deepEqual(withPiForkRefs([turn('one')], []).map((t) => t.forkRef), [undefined]); }); -import { AgyAdapter, agyArgs, agyTurnResult, mapAgyStep, parseAgyModels } from '../src/adapters/agy.js'; +import { AgyAdapter, parseAgyModels } from '../src/adapters/agy.js'; const fakeAgy = join(here, 'fixtures', 'fake-agy.mjs'); const textFrom = (events: EmittedEvent[]) => events.filter((e) => e.type === 'message.delta').map((e) => e.data.text).join(''); -test('mapAgyStep maps reply text and tool steps, and ignores bookkeeping steps', () => { - const started = new Set(); - assert.deepEqual(mapAgyStep({ step_index: 0, state: 'DONE', step_type: 'user_input' }, started), []); - assert.deepEqual(mapAgyStep({ step_index: 3, state: 'DONE', step_type: 'system_message' }, started), []); - // A reply step with no text is the model deciding to call a tool. - assert.deepEqual(mapAgyStep({ step_index: 1, state: 'DONE', step_type: 'agent_response', usage: {} }, started), []); - assert.deepEqual(mapAgyStep({ step_index: 1, state: 'ACTIVE', step_type: 'agent_response', text_delta: 'Hel' }, started), [ - { type: 'message.delta', data: { text: 'Hel' } }, - ]); - - const info = { name: 'run_command', parameters: { CommandLine: 'npm test\necho done' } }; - assert.deepEqual(mapAgyStep({ step_index: 2, state: 'ACTIVE', step_type: 'tool', tool_name: 'run_command', tool_info: info }, started), [ - { type: 'tool.start', data: { id: 'agy-step-2', title: 'npm test', kind: 'execute', status: 'in_progress', tool: 'run_command', input: info.parameters } }, - ]); - assert.deepEqual( - mapAgyStep({ step_index: 2, state: 'DONE', step_type: 'tool', tool_name: 'run_command', tool_info: { ...info, output: '12 passed' } }, started), - [{ type: 'tool.end', data: { id: 'agy-step-2', status: 'completed', output: '12 passed' } }], +test('parseAgyModels groups multi-effort families, keeps single-variant models fixed, and skips invalid lines', () => { + const models = parseAgyModels( + 'Fetching available models...\nfast-high\tFast (High)\nfast-low\tFast (Low)\n\nbroken line\nsolo-medium\tSolo (Medium)\nbig\tBig (Thinking)\n\tno id\n', ); - - // A refused command arrives as an error with the reason. - const refused = mapAgyStep( - { step_index: 5, state: 'ERROR', step_type: 'tool', tool_name: 'run_command', tool_info: { ...info, error: { type: 'TOOL_ERROR', message: 'user denied permission' } } }, - started, - ); - assert.deepEqual(refused.map((e) => [e.type, e.data.status]), [['tool.start', 'in_progress'], ['tool.end', 'failed']], 'a step never seen active still gets its start'); - assert.equal(refused[1].data.output, 'user denied permission'); -}); - -test('mapAgyStep names file tools by what they do, and shows a subagent by its role and task', () => { - const start = (tool_name: string, parameters: Record, index: number) => - mapAgyStep({ step_index: index, state: 'ACTIVE', step_type: 'tool', tool_name, tool_info: { name: tool_name, parameters } }, new Set())[0].data; - assert.deepEqual([start('write_to_file', { TargetFile: '/w/a.txt' }, 1).title, start('write_to_file', { TargetFile: '/w/a.txt' }, 1).kind], ['Write /w/a.txt', 'edit']); - assert.equal(start('replace_file_content', { TargetFile: '/w/a.txt' }, 2).title, 'Edit /w/a.txt'); - assert.deepEqual([start('view_file', { AbsolutePath: '/w/a.txt' }, 3).title, start('view_file', { AbsolutePath: '/w/a.txt' }, 3).kind], ['Read /w/a.txt', 'read']); - assert.deepEqual([start('grep_search', { Query: 'TODO' }, 4).title, start('grep_search', { Query: 'TODO' }, 4).kind], ['grep_search TODO', 'search']); - assert.deepEqual([start('manage_task', {}, 5).title, start('manage_task', {}, 5).kind], ['manage_task', 'other']); - - const [sub] = mapAgyStep( - { - step_index: 6, - state: 'ACTIVE', - step_type: 'subagent', - tool_name: 'invoke_subagent', - subagent_info: { subagents: [{ type_name: 'image-generator', role: 'Image Generator', initial_prompt: 'An orange circle.\nKeep it flat.' }] }, - }, - new Set(), - ); - assert.equal(sub.data.title, 'Image Generator: An orange circle.'); -}); - -test('agyTurnResult: success, interruption, errors, and actions refused for lack of a prompt', () => { - assert.deepEqual(agyTurnResult({ status: 'SUCCESS', response: 'ok' }, false), { stopReason: 'end_turn' }); - assert.deepEqual(agyTurnResult({ status: 'ERROR', error: 'interrupted' }, true), { stopReason: 'cancelled' }); - assert.deepEqual(agyTurnResult({ status: 'ERROR', error: 'quota exceeded' }, false), { stopReason: 'error', error: 'quota exceeded' }); - const denied = agyTurnResult( - { status: 'SUCCESS', response: '', denied_actions: [{ action: 'command', display_name: 'RunCommand' }, { action: 'command', display_name: 'RunCommand' }] }, - false, - ); - assert.equal(denied.stopReason, 'error'); - assert.equal(denied.errorCode, 'permission_refused'); - assert.deepEqual(denied.refused, ['RunCommand'], 'each kind of action is named once'); - assert.match(denied.error!, /refused RunCommand:/); - assert.match(denied.error!, /full access/); -}); - -test('parseAgyModels reads id and label pairs and skips everything else', () => { - const models = parseAgyModels('Fetching available models...\nfast-low\tFast (Low)\n\nbroken line\nbig\tBig (Thinking)\n\tno id\n'); - assert.deepEqual(models.map((m) => [m.id, m.label]), [['fast-low', 'Fast (Low)'], ['big', 'Big (Thinking)']]); - assert.ok(models.every((m) => m.efforts?.length === 0 && m.images === undefined), 'no effort setting; images go in as paths'); + assert.deepEqual(models, [ + { id: 'fast', label: 'Fast', efforts: ['low', 'high'], isDefault: true }, + { id: 'solo-medium', label: 'Solo (Medium)', efforts: [] }, + { id: 'big', label: 'Big (Thinking)', efforts: [] }, + ]); assert.deepEqual(parseAgyModels(''), []); }); -test('agyArgs turns the permission level, model and conversation into flags', () => { - const base = ['--input-format', 'stream-json', '--output-format', 'stream-json']; - assert.deepEqual(agyArgs({}), [...base, '--mode', 'accept-edits', '-p=']); - assert.deepEqual(agyArgs({ permissionMode: 'auto_edit', model: 'fast-low' }), [...base, '--mode', 'accept-edits', '--model', 'fast-low', '-p=']); - assert.deepEqual(agyArgs({ permissionMode: 'full_access', conversationId: 'c1' }), [...base, '--dangerously-skip-permissions', '--conversation', 'c1', '-p=']); - assert.equal(agyArgs({ permissionMode: 'full_access' }).includes('--mode'), false); -}); - test('AgyAdapter: models, a turn with a tool, and several turns in one process', async () => { const adapter = new AgyAdapter([process.execPath, fakeAgy]); assert.equal(await adapter.available(), true); assert.equal(await new AgyAdapter(['definitely-not-installed-agy']).available(), false); - assert.deepEqual((await adapter.models()).map((m) => m.id), ['fast-low', 'fast-high', 'big-thinking']); + assert.deepEqual(await adapter.models(), [ + { id: 'fast', label: 'Fast', efforts: ['low', 'high'], isDefault: true }, + { id: 'big-thinking', label: 'Big (Thinking)', efforts: [] }, + ]); assert.ok((await adapter.commands()).some((c) => c.name === 'usage')); assert.match(adapter.resumeCommand('abc'), /fake-agy\.mjs' --conversation 'abc'$/); assert.equal(new AgyAdapter().resumeCommand('abc'), "'agy' --conversation 'abc'"); - const session = await adapter.start({ cwd: here, model: 'fast-low' }); + const session = await adapter.start({ cwd: here, model: 'fast', effort: 'low' }); try { assert.equal(session.agentSessionId, 'agy-conv-1', 'the conversation id is known before the first message'); const first = collectingHooks(); assert.deepEqual(await session.prompt(turn('use a tool'), first.hooks), { stopReason: 'end_turn' }); - assert.deepEqual(first.events.map((e) => e.type), ['tool.start', 'tool.end', 'message.delta', 'message.delta']); - assert.equal(first.events[1].data.output, 'hi\r\n'); - assert.equal(textFrom(first.events).trim(), 'echo:use a tool;model:fast-low;mode:accept-edits;conv:agy-conv-1'); + assert.deepEqual(first.events.map((e) => e.type), ['turn.phase', 'tool.start', 'tool.end', 'message.delta', 'message.delta', 'usage.updated']); + assert.equal(first.events.find(e => e.type === 'tool.end')!.data.output, 'hi\r\n'); + assert.equal(textFrom(first.events).trim(), 'echo:use a tool;model:fast;effort:low;mode:auto;conv:agy-conv-1'); const second = collectingHooks(); await session.prompt(turn('again'), second.hooks); assert.match(textFrom(second.events), /^echo:again;/); - assert.deepEqual(second.events.map((e) => e.type), ['message.delta', 'message.delta'], 'steps of the first turn are not repeated'); + assert.deepEqual(second.events.map((e) => e.type), ['turn.phase', 'message.delta', 'message.delta', 'usage.updated'], 'steps of the first turn are not repeated'); } finally { await session.close(); } }); -test('AgyAdapter: a permission change restarts the process on the same conversation', async () => { +test('AgyAdapter: permission changes use the same ACP conversation and native approval', async () => { const adapter = new AgyAdapter([process.execPath, fakeAgy]); const session = await adapter.start({ cwd: here, resumeId: 'conv-kept', permissionMode: 'auto_edit' }); try { assert.equal(session.agentSessionId, 'conv-kept'); const refused = collectingHooks(); const result = await session.prompt(turn('run a command'), refused.hooks); - assert.equal(result.stopReason, 'error'); - assert.match(result.error!, /refused RunCommand/); - assert.deepEqual(refused.events.map((e) => [e.type, e.data.status]), [['tool.start', 'in_progress'], ['tool.end', 'failed']]); + assert.equal(result.stopReason, 'end_turn'); + assert.equal(refused.approvals.length, 1); await session.setPermissionMode!('full_access'); const allowed = collectingHooks(); assert.deepEqual(await session.prompt(turn('run a command'), allowed.hooks), { stopReason: 'end_turn' }); - assert.match(textFrom(allowed.events), /mode:always-proceed;conv:conv-kept/); + assert.match(textFrom(allowed.events), /mode:auto;conv:conv-kept/); assert.equal(session.agentSessionId, 'conv-kept'); } finally { await session.close(); @@ -834,21 +768,21 @@ test('AgyAdapter: cancelling stops the turn, and the next message carries on in } }); -test('AgyAdapter: a process that dies mid-turn is reported with what it said, and the session recovers', async () => { +test('AgyAdapter: a process that dies is reported and a new session resumes its conversation', async () => { const adapter = new AgyAdapter([process.execPath, fakeAgy]); const session = await adapter.start({ cwd: here }); try { const result = await session.prompt(turn('crash'), collectingHooks().hooks); assert.equal(result.stopReason, 'error'); - assert.match(result.error!, /code=7.*something broke/); - const after = collectingHooks(); - assert.deepEqual(await session.prompt(turn('still there?'), after.hooks), { stopReason: 'end_turn' }); + assert.match(result.error!, /code=7/); + const resumed = await adapter.start({ cwd: here, resumeId: session.agentSessionId }); + try { assert.equal((await resumed.prompt(turn('still there?'), collectingHooks().hooks)).stopReason, 'end_turn'); } finally { await resumed.close(); } } finally { await session.close(); } - await assert.rejects(new AgyAdapter(['definitely-not-installed-agy']).start({ cwd: here }), /could not be started/); + await assert.rejects(new AgyAdapter(['definitely-not-installed-agy']).start({ cwd: here }), /ENOENT/); // Something that is not agy exits without announcing a conversation; its complaint is passed on. - await assert.rejects(new AgyAdapter([process.execPath, '--no-such-flag']).start({ cwd: here }), /agy exited \(code=\d+.*bad option/); + await assert.rejects(new AgyAdapter([process.execPath, '--no-such-flag']).start({ cwd: here }), /agy-acp exited \(code=\d+/); }); import { formatAgyOutput, parseAgyHelp, parseAgySkills } from '../src/adapters/agy.js'; @@ -882,7 +816,7 @@ test('AgyAdapter: lists what agy answers itself plus its skills, and answers tho const commands = await adapter.commands(here); assert.deepEqual( commands.map((c) => [c.name, c.kind]), - [['config', 'command'], ['skills', 'command'], ['usage', 'command'], ['broken', 'command'], ['make-video', 'skill'], ['review', 'skill']], + [['skills', 'command'], ['usage', 'command'], ['make-video', 'skill'], ['review', 'skill']], 'model and effort are left out: they are set by the hub, per session', ); @@ -895,8 +829,10 @@ test('AgyAdapter: lists what agy answers itself plus its skills, and answers tho await session.prompt(turn('/quota'), alias.hooks); assert.match(textFrom(alias.events), /Weekly Limit Remaining/, 'aliases work too'); - const broken = await session.prompt(turn('/broken'), collectingHooks().hooks); - assert.deepEqual(broken, { stopReason: 'error', error: 'agy /broken failed: /broken failed: not available here' }); + assert.ok((await adapter.commands(here)).some(c => c.name === 'compact')); + const compact = collectingHooks(); + assert.equal((await session.prompt(turn('/compact'), compact.hooks)).stopReason, 'end_turn'); + assert.deepEqual(compact.events.filter(e => e.type === 'tool.start' || e.type === 'tool.end').map(e => e.data.status), ['in_progress', 'completed']); // Skills and unknown commands go to the model as text, through the session's process. const skill = collectingHooks(); @@ -1051,14 +987,14 @@ test('imagePathNote lists the stored files of a message, and nothing for images assert.match(imagePathNote([{ data: PNG, mimeType: 'image/png', path: '/d/a.png' }, { data: PNG, mimeType: 'image/jpeg', path: '/d/b.jpg' }]), /attached 2 images\. Look at them[\s\S]*- \/d\/a\.png\n- \/d\/b\.jpg$/); }); -test('agy gets the pictures of a message as file paths', async () => { +test('agy gets images as native ACP blocks', async () => { const adapter = new AgyAdapter([process.execPath, fakeAgy]); assert.equal(adapter.capabilities.images, true); const session = await adapter.start({ cwd: here }); try { const { hooks, events } = collectingHooks(); await session.prompt(turn('what is this', [{ data: PNG, mimeType: 'image/png', path: '/data/attachments/t/1.png' }]), hooks); - assert.match(textFrom(events), /^echo:what is this\n\nThe user attached an image\. Look at it before answering:\n- \/data\/attachments\/t\/1\.png;/); + assert.match(textFrom(events), /^echo:what is this;image:embedded;/); } finally { await session.close(); } diff --git a/apps/workbench/packages/daemon/test/agent-accounts.test.ts b/apps/workbench/packages/daemon/test/agent-accounts.test.ts index 029fdcf61a..3e1360551c 100644 --- a/apps/workbench/packages/daemon/test/agent-accounts.test.ts +++ b/apps/workbench/packages/daemon/test/agent-accounts.test.ts @@ -308,7 +308,7 @@ test('signed-out model catalog offers typed login recovery and publishes models await waitFor(() => events, list => list.some(event => event.data.agent === id && event.data.models.length > 0)); const response = await api(`/api/agents/${id}/models`); assert.equal(response.status, 200); - assert.ok((await response.json() as any[]).some(model => model.id === 'fast-low')); + assert.ok((await response.json() as any[]).some(model => model.id === 'fast')); assert.equal(registry.get(id).account, 'agy-new@example.com'); } finally { off(); } }); diff --git a/apps/workbench/packages/daemon/test/agy-acp.test.ts b/apps/workbench/packages/daemon/test/agy-acp.test.ts new file mode 100644 index 0000000000..4b06878c9e --- /dev/null +++ b/apps/workbench/packages/daemon/test/agy-acp.test.ts @@ -0,0 +1,63 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { AgyAdapter } from '../src/adapters/agy.js'; +import type { EmittedEvent } from '../src/events.js'; +import type { TurnHooks } from '../src/adapters/types.js'; +const fixture = fileURLToPath(new URL('./fixtures/fake-agy.mjs', import.meta.url)); + +test('agy ACP: settings and compact stay in one process, queries do not enter the conversation, old IDs resume', async () => { + const cwd = mkdtempSync(join(tmpdir(), 'agy-acp-')); + const log = join(cwd, 'rpc.jsonl'); + const adapter = new AgyAdapter([process.execPath, fixture], { FAKE_AGY_RPC_LOG: log }); + const events: EmittedEvent[] = []; + let approvals = 0; + const hooks: TurnHooks = { emit: e => events.push(e), requestApproval: async () => { approvals++; return { optionId: 'allow' }; } }; + const s = await adapter.start({ cwd, resumeId: 'old-conversation', model: 'fast', effort: 'low' }); + const prompt = (text: string) => s.prompt({ text, images: [] }, hooks); + try { + assert.equal(adapter.capabilities.compact, true); + await prompt('hello'); + await s.setModel!('big-thinking'); + await s.setEffort!('high'); + await s.setPermissionMode!('ask'); + await prompt('run a command'); + assert.equal(approvals, 1); + await s.setPermissionMode!('full_access'); + await prompt('run a command'); + assert.equal(approvals, 1, 'full access grants the offered allow option without asking again'); + await s.setWorkMode!('plan'); + await prompt('plan-draft'); + assert.ok(events.some(e => e.type === 'plan.completed')); + await s.setWorkMode!('execute'); + await prompt('/usage'); + events.length = 0; + await prompt('/compact'); + const compact = events.filter(e => e.type !== 'turn.phase'); + assert.deepEqual(compact.map(e => e.type), ['tool.start', 'usage.updated', 'tool.end']); + assert.equal(compact[2].data.status, 'completed'); + assert.equal(compact[1].data.used, 250); + events.length = 0; + await prompt('usage-drop'); + assert.ok(!events.some(e => e.type === 'context.compaction'), 'a decline is not an automatic compaction signal'); + events.length = 0; + assert.equal((await prompt('/compact fail')).stopReason, 'error'); + assert.equal(events.at(-1)?.data.status, 'failed'); + events.length = 0; + const pending = prompt('/compact slow'); + await s.waitForSubmission!(); + await s.cancel(); + assert.equal((await pending).stopReason, 'cancelled'); + assert.equal(events.at(-1)?.data.status, 'failed'); + const calls = readFileSync(log, 'utf8').trim().split('\n').map(l => JSON.parse(l)); + assert.equal(new Set(calls.map(c => c.pid)).size, 1); + assert.ok(calls.some(c => c.method === 'session/resume' && c.params.sessionId === 'old-conversation')); + assert.ok(!calls.some(c => c.method === 'session/new')); + assert.ok(!calls.some(c => c.method === 'session/prompt' && c.params.prompt.some((p: any) => p.text === '/usage'))); + assert.deepEqual(calls.filter(c => c.method === 'session/set_config_option').map(c => [c.params.configId, c.params.value]), + [['model', 'fast'], ['thought_level', 'low'], ['model', 'big-thinking'], ['thought_level', 'high']]); + } finally { await s.close(); rmSync(cwd, { recursive: true, force: true }); } +}); diff --git a/apps/workbench/packages/daemon/test/agy-model-migration.test.ts b/apps/workbench/packages/daemon/test/agy-model-migration.test.ts new file mode 100644 index 0000000000..88ec8d44c0 --- /dev/null +++ b/apps/workbench/packages/daemon/test/agy-model-migration.test.ts @@ -0,0 +1,62 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { AgyAdapter } from '../src/adapters/agy.js'; +import { AttachmentStore } from '../src/attachments.js'; +import { Store } from '../src/store.js'; +import { ThreadManager } from '../src/threads.js'; + +test('grouped catalogs preserve legacy thread, archive and per-account preference choices', async () => { + const root = mkdtempSync(join(tmpdir(), 'agy-family-migration-')); + const catalog = join(root, 'models.json'); + const native = [{ id: 'fast-high', label: 'Fast (High)' }, { id: 'fast-low', label: 'Fast (Low)' }, { id: 'solo-medium', label: 'Solo (Medium)' }]; + writeFileSync(catalog, JSON.stringify({ models: native })); + const adapter = new AgyAdapter([process.execPath, fileURLToPath(new URL('./fixtures/fake-agy.mjs', import.meta.url))], { FAKE_AGY_MODELS_FILE: catalog }); + const other = new AgyAdapter([process.execPath, fileURLToPath(new URL('./fixtures/fake-agy.mjs', import.meta.url))]); + const store = new Store(join(root, 'data')); + const manager = new ThreadManager(store, new Map([['secondary', adapter], ['other', other]]), [root], new AttachmentStore(root)); + const updated: string[] = []; + const off = manager.subscribe(event => { if (event.type === 'thread.updated') updated.push(event.threadId); }); + try { + const active = await manager.createThread({ agent: 'secondary', cwd: root }); + const archived = await manager.createThread({ agent: 'secondary', cwd: root }); + const fixed = await manager.createThread({ agent: 'secondary', cwd: root }); + const elsewhere = await manager.createThread({ agent: 'other', cwd: root }); + store.updateThread(active.id, { model: 'fast-high', effort: null }); + store.updateThread(archived.id, { model: 'fast-low', effort: 'high', archivedAt: new Date().toISOString() }); + store.updateThread(fixed.id, { model: 'solo-medium', effort: null }); + store.updateThread(elsewhere.id, { model: 'fast-low', effort: null }); + store.saveHubSetting('draft.model.preferences', { + secondary: { model: 'fast-high', effort: null, speed: null, perModel: { 'solo-medium': { effort: null, speed: null } } }, + other: { model: 'fast-low', effort: null, speed: null }, + }); + updated.length = 0; + await manager.listModels('secondary'); + assert.equal(store.getThread(active.id)?.model, 'fast'); + assert.equal(store.getThread(active.id)?.effort, 'high'); + assert.equal(store.getThread(archived.id)?.model, 'fast'); + assert.equal(store.getThread(archived.id)?.effort, 'high', 'an explicit effort wins over the old suffix'); + assert.ok(store.getThread(archived.id)?.archivedAt); + assert.equal(store.getThread(fixed.id)?.model, 'solo-medium', 'a fixed-effort model keeps its native id'); + assert.equal(store.getThread(elsewhere.id)?.model, 'fast-low'); + const preferences = await manager.draftModelPreferences(); + assert.equal(preferences.secondary.model, 'fast'); + assert.equal(preferences.secondary.effort, 'high'); + assert.ok(preferences.secondary.perModel?.['solo-medium']); + assert.equal(preferences.other.model, 'fast-low'); + assert.deepEqual(updated.sort(), [active.id, archived.id].sort()); + updated.length = 0; + await manager.listModels('secondary', true); + assert.deepEqual(updated, [], 'catalog refresh does not repeatedly rewrite migrated threads'); + + // Unknown or unavailable catalogs do not erase choices or invent a family mapping. + store.updateThread(active.id, { model: 'future-high', effort: null }); + writeFileSync(catalog, JSON.stringify({ error: true })); + await assert.rejects(manager.listModels('secondary', true)); + assert.equal(store.getThread(active.id)?.model, 'future-high'); + assert.deepEqual(await manager.draftModelPreferences(), preferences); + } finally { off(); await manager.shutdown(); store.close(); rmSync(root, { recursive: true, force: true }); } +}); diff --git a/apps/workbench/packages/daemon/test/api.test.ts b/apps/workbench/packages/daemon/test/api.test.ts index a9ce480e24..615dfe028b 100644 --- a/apps/workbench/packages/daemon/test/api.test.ts +++ b/apps/workbench/packages/daemon/test/api.test.ts @@ -1740,25 +1740,29 @@ test('matchTurns pairs the two histories from the start and gives up when they d assert.deepEqual(matchTurns([], ['a'], 3), { hubToAgent: [-1], agentNext: 0 }); }); -test('agy: two permission levels, no approvals, no images; settings are flags of its process', async () => { +test('agy: ACP approvals, images, compact and per-session settings', async () => { const agents = (await (await api('/api/agents')).json()) as Array<{ id: string; label: string; available: boolean; capabilities: any }>; const agy = agents.find((a) => a.id === 'agy')!; assert.equal(agy.label, 'Antigravity'); assert.equal(agy.available, true); - assert.deepEqual(agy.capabilities.permissionModes, ['auto_edit', 'full_access']); - assert.deepEqual([agy.capabilities.approvals, agy.capabilities.images, agy.capabilities.effortLevels.length], [false, true, 0]); - const models = (await (await api('/api/agents/agy/models')).json()) as Array<{ id: string; efforts: string[] }>; - assert.deepEqual(models.map((m) => m.id), ['fast-low', 'fast-high', 'big-thinking']); + assert.deepEqual(agy.capabilities.permissionModes, ['ask', 'auto_edit', 'full_access']); + assert.equal(agy.capabilities.compact, true); + assert.deepEqual([agy.capabilities.approvals, agy.capabilities.images, agy.capabilities.effortLevels], [true, true, ['low', 'medium', 'high', 'xhigh', 'max']]); + const models = (await (await api('/api/agents/agy/models')).json()) as Array<{ id: string; label: string; efforts: string[]; isDefault?: boolean }>; + assert.deepEqual(models, [ + { id: 'fast', label: 'Fast', efforts: ['low', 'high'], isDefault: true }, + { id: 'big-thinking', label: 'Big (Thinking)', efforts: [] }, + ]); - // It cannot ask, so "ask" is not offered, and a new thread starts with full access: at the lower - // level every command is refused. The lower level can still be chosen; other agents keep theirs. + // ACP adds ask while preserving the existing full-access default. assert.equal(agy.capabilities.defaultPermissionMode, 'full_access'); const ask = await api('/api/threads', { method: 'POST', body: JSON.stringify({ agent: 'agy', cwd: workdir, permissionMode: 'ask' }) }); - assert.equal(ask.status, 400); - assert.equal((await api('/api/threads', { method: 'POST', body: JSON.stringify({ agent: 'agy', cwd: workdir, effort: 'high' }) })).status, 400); + assert.equal(ask.status, 201); + assert.equal((await api('/api/threads', { method: 'POST', body: JSON.stringify({ agent: 'agy', cwd: workdir, effort: 'max' }) })).status, 400); + assert.equal((await api('/api/threads', { method: 'POST', body: JSON.stringify({ agent: 'agy', cwd: workdir, model: 'big-thinking', effort: 'low' }) })).status, 400); assert.equal(((await newThread({ agent: 'agy' })) as { permissionMode?: string }).permissionMode, 'full_access'); assert.equal(((await newThread({ agent: 'claude' })) as { permissionMode?: string }).permissionMode, 'auto_edit'); - const thread = (await newThread({ agent: 'agy', model: 'fast-low', permissionMode: 'auto_edit' })) as { id: string; permissionMode?: string }; + const thread = (await newThread({ agent: 'agy', model: 'fast', effort: 'low', permissionMode: 'auto_edit' })) as { id: string; permissionMode?: string }; assert.equal(thread.permissionMode, 'auto_edit'); const replyOf = (list: Array<{ type: string; turnId: string | null; data: any }>, turnId: string | null) => @@ -1776,25 +1780,41 @@ test('agy: two permission levels, no approvals, no images; settings are flags of const first = await sendAndWait('use a tool'); assert.equal(first.end.type, 'turn.done'); - assert.equal(replyOf(first.list, first.turnId), 'echo:use a tool;model:fast-low;mode:accept-edits;conv:agy-conv-1'); + assert.equal(replyOf(first.list, first.turnId), 'echo:use a tool;model:fast;effort:low;mode:accept-edits;conv:agy-conv-1'); assert.ok(first.list.some((e) => e.type === 'tool.end' && e.data.output === 'hi\r\n')); const view = (await (await api(`/api/threads/${thread.id}`)).json()) as { agentSessionId: string; resumeCommand: string }; assert.equal(view.agentSessionId, 'agy-conv-1'); - assert.equal(view.resumeCommand, `cd ${workdir} && agy --conversation agy-conv-1`); + assert.match(view.resumeCommand, /fake-agy\.mjs' --conversation 'agy-conv-1'$/); - // A command needs a permission it cannot ask for: the turn ends with an explanation. - const refused = await sendAndWait('run a command'); - assert.equal(refused.end.type, 'turn.error'); - assert.match(refused.end.data.message, /full access/); - assert.deepEqual([refused.end.data.code, refused.end.data.refused], ['permission_refused', ['RunCommand']]); + // Native approval requests reach the ordinary approval API. + await post(`/api/threads/${thread.id}/turns`, { text: 'run a command' }); + const approval = await waitFor(async () => { + const log = await events(thread.id); + return log.find(e => e.type === 'approval.request') ?? null; + }); + await post(`/api/approvals/${approval.data.approvalId}`, { optionId: 'allow' }); + await untilIdle(thread.id); + + // Raising the level, changing the effort, and switching to a fixed-effort model all carry on in the same conversation. + assert.equal((await api(`/api/threads/${thread.id}`, { method: 'PATCH', body: JSON.stringify({ effort: 'high' }) })).status, 200); + const higher = await sendAndWait('think harder'); + assert.equal(higher.end.type, 'turn.done'); + assert.equal(replyOf(higher.list, higher.turnId), 'echo:think harder;model:fast;effort:high;mode:accept-edits;conv:agy-conv-1'); - // Raising the level and changing the model both carry on in the same conversation. assert.equal((await api(`/api/threads/${thread.id}`, { method: 'PATCH', body: JSON.stringify({ permissionMode: 'full_access', model: 'big-thinking' }) })).status, 200); const allowed = await sendAndWait('run a command'); assert.equal(allowed.end.type, 'turn.done'); - assert.equal(replyOf(allowed.list, allowed.turnId), 'echo:run a command;model:big-thinking;mode:always-proceed;conv:agy-conv-1'); + assert.equal(replyOf(allowed.list, allowed.turnId), 'echo:run a command;model:big-thinking;mode:auto;conv:agy-conv-1'); + + // The picker sends null effort alongside a model even when effort is already unset. + // It must not discard the ACP session that just accepted the model. + const closes = (await events(thread.id)).filter(e => e.type === 'session.lifecycle' && e.data.action === 'close').length; + await post(`/api/threads/${thread.id}/turns`, { text: 'before model picker' }); + await untilIdle(thread.id); + assert.equal((await api(`/api/threads/${thread.id}`, { method: 'PATCH', body: JSON.stringify({ model: 'fast', effort: null }) })).status, 200); + assert.equal((await events(thread.id)).filter(e => e.type === 'session.lifecycle' && e.data.action === 'close').length, closes); - // Pictures go in as paths to the stored files; agy opens them itself. + // Pictures are native ACP image blocks. const image = await sendAndWait('look at this'); assert.equal(image.end.type, 'turn.done'); const pictured = await api(`/api/threads/${thread.id}/turns`, { method: 'POST', body: JSON.stringify({ text: 'look', images: [{ data: PNG, mimeType: 'image/png' }] }) }); @@ -1804,9 +1824,8 @@ test('agy: two permission levels, no approvals, no images; settings are flags of const all = await events(thread.id); return all.some((e) => e.turnId === picturedTurn && e.type === 'turn.done') ? all : null; }); - const stored = withPicture.find((e) => e.turnId === picturedTurn && e.type === 'turn.started')!.data.images[0]; const said = withPicture.filter((e) => e.turnId === picturedTurn && e.type === 'message.delta').map((e) => e.data.text).join(''); - assert.ok(said.includes(join(dataDir, 'attachments', thread.id, `${stored.id}.png`)), said); + assert.ok(said.includes(';image:embedded;'), said); // What it cannot do is refused up front. assert.equal((await api(`/api/threads/${thread.id}/fork`, { method: 'POST' })).status, 400); @@ -2543,7 +2562,7 @@ test('download serves any readable file whole or by range, with the name it has' test('commands: agy lists and answers its own commands; the answer is a normal turn in the thread', async () => { const list = (await (await api(`/api/agents/agy/commands?cwd=${encodeURIComponent(workdir)}`)).json()) as Array<{ name: string; kind: string }>; assert.ok(list.some((c) => c.name === 'usage' && c.kind === 'command')); - assert.ok(list.some((c) => c.name === 'make-video' && c.kind === 'skill')); + assert.ok(list.some((c) => c.name === 'make-video')); assert.ok(!list.some((c) => c.name === 'model')); const thread = await newThread({ agent: 'agy' }); diff --git a/apps/workbench/packages/daemon/test/auto-handover.test.ts b/apps/workbench/packages/daemon/test/auto-handover.test.ts index 9df0bc674e..e5480c7696 100644 --- a/apps/workbench/packages/daemon/test/auto-handover.test.ts +++ b/apps/workbench/packages/daemon/test/auto-handover.test.ts @@ -426,12 +426,12 @@ test('quota checks do not interrupt a running turn awaiting approval', async () } finally { await h.close(); } }); -test('automatic selection does not broaden an approval-required conversation', async () => { +test('automatic selection keeps ask when the ACP successor supports approvals', async () => { const h = await setup(); try { h.config(); h.store.updateThread(h.thread.id, { permissionMode: 'ask' }); - assert.deepEqual(await h.manager.autoHandover.targets(h.thread.id), []); + assert.deepEqual(await h.manager.autoHandover.targets(h.thread.id), [{ agent: 'agy2', model: 'gemini-pro' }]); } finally { await h.close(); } }); diff --git a/apps/workbench/packages/daemon/test/fixtures/fake-agy.mjs b/apps/workbench/packages/daemon/test/fixtures/fake-agy.mjs index 83c6dd998b..c2f02b86ba 100644 --- a/apps/workbench/packages/daemon/test/fixtures/fake-agy.mjs +++ b/apps/workbench/packages/daemon/test/fixtures/fake-agy.mjs @@ -1,10 +1,8 @@ #!/usr/bin/env node -import { createInterface } from 'node:readline'; if (process.argv.includes('--version')) { process.stdout.write('fixture 1.2.3\n'); process.exit(0); } -// A stand-in for the Antigravity CLI in headless stream-json mode, for tests. -// Prompt text drives behaviour: "tool" runs a command, "command" needs a permission that headless -// mode cannot ask for, "slow" waits until interrupted, "crash" exits. -import { existsSync, mkdirSync, readFileSync, writeFileSync, symlinkSync } from 'node:fs'; +// Antigravity ACP fixture plus the account-query and login CLI entry points. +import { existsSync, mkdirSync, readFileSync, writeFileSync, appendFileSync, symlinkSync } from 'node:fs'; +import { createInterface } from 'node:readline'; import { agyUsage } from './live-usage.mjs'; import { coordinationFixture } from './coordination.mjs'; import { join } from 'node:path'; @@ -42,6 +40,14 @@ if (args[0] === 'models') { process.stderr.write('Fetching available models...\nError: Please sign in to view available models. Launch the CLI without arguments to sign in.\n'); process.exit(1); } + if (process.env.FAKE_AGY_MODELS_FILE) { + const catalog = JSON.parse(readFileSync(process.env.FAKE_AGY_MODELS_FILE, 'utf8')); + if (catalog.startedFile) writeFileSync(catalog.startedFile, 'started'); + if (catalog.delayMs) await new Promise(resolve => setTimeout(resolve, catalog.delayMs)); + if (catalog.error) { process.stderr.write('fixture model catalog unavailable\n'); process.exit(1); } + for (const model of catalog.models) process.stdout.write(`${model.id}\t${model.label}\n`); + process.exit(0); + } if (process.env.FAKE_HANDOVER_QUOTA) { process.stdout.write('gemini-pro\tGemini Pro\nclaude-sonnet\tClaude Sonnet\n'); process.exit(0); } process.stderr.write('Fetching available models...\n'); process.stdout.write('fast-low\tFast (Low)\nfast-high\tFast (High)\nnot a model line\nbig-thinking\tBig (Thinking)\n'); @@ -79,30 +85,46 @@ if (promptIndex >= 0 && args[promptIndex + 1] !== undefined) { process.exit(0); } -const flag = (name) => (args.includes(name) ? args[args.indexOf(name) + 1] : undefined); -if (!args.includes('-p=') || flag('--input-format') !== 'stream-json' || flag('--output-format') !== 'stream-json') { - process.stderr.write('fake-agy: expected stream-json in both directions and -p=\n'); - process.exit(2); -} - -const conversation = flag('--conversation') ?? (process.env.FAKE_HANDOVER_EXHAUST_ONCE ? `agy-conv-${process.pid}` : 'agy-conv-1'); -const model = flag('--model') ?? 'default'; -const fullAccess = args.includes('--dangerously-skip-permissions'); -const mode = fullAccess ? 'always-proceed' : (flag('--mode') ?? 'request-review'); - -const out = (obj) => process.stdout.write(JSON.stringify(obj) + '\n'); +if (args[0] !== 'acp') throw new Error('expected agy acp'); +let conversation = 'agy-conv-1', model = 'default', effort, mode = 'default'; +let fullAccess = false, pending, waiting = false; let stepIndex = 0; -const step = (fields) => out({ event: 'step_update', step_update: { conversation_id: conversation, ...fields } }); -const result = (fields) => out({ event: 'result', result: { conversation_id: conversation, ...fields } }); - -setTimeout(() => out({ event: 'init', conversation_id: conversation, init: { cwd: process.cwd(), tools: [], permission_mode: mode } }), 10); - -let waiting = false; -process.on('SIGINT', () => { - if (waiting) result({ status: 'ERROR', response: 'partial', error: 'interrupted' }); - process.exit(1); -}); +const out = obj => process.stdout.write(JSON.stringify(obj) + '\n'); +const update = u => out({ jsonrpc: '2.0', method: 'session/update', params: { sessionId: conversation, update: u } }); +const reply = (id, result) => out({ jsonrpc: '2.0', id, result }); +const started = new Set(); +const step = s => { + if (s.step_type === 'agent_response' && s.text_delta) update({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: s.text_delta } }); + if (!['tool', 'subagent'].includes(s.step_type)) return; + const id = `agy-step-${s.step_index}`; + const sub = s.subagent_info?.subagents?.[0]; + const name = s.tool_name ?? s.tool_info?.name ?? (sub ? 'invoke_subagent' : 'tool'); + if (!started.has(id)) { + started.add(id); + update({ sessionUpdate: 'tool_call', toolCallId: id, name, title: s.tool_info?.parameters?.CommandLine ?? name, + kind: name === 'run_command' ? 'execute' : 'other', status: 'in_progress', + rawInput: sub ? { TypeName: sub.type_name } : s.tool_info?.parameters }); + } + if (['DONE', 'ERROR'].includes(s.state)) update({ sessionUpdate: 'tool_call_update', toolCallId: id, + status: s.state === 'ERROR' ? 'failed' : 'completed', rawOutput: s.tool_info?.error?.message ?? s.tool_info?.output ?? '' }); +}; +const result = fields => { + waiting = false; + if (fields.status !== 'SUCCESS') { + if (fields.error === 'interrupted') reply(pending, { stopReason: 'cancelled' }); + else out({ jsonrpc: '2.0', id: pending, error: { code: -32000, message: fields.error } }); + } else { + update({ sessionUpdate: 'usage_update', used: 1234, size: 1048576 }); + reply(pending, { stopReason: 'end_turn', ...(fields.usage ? { usage: fields.usage } : {}) }); + } +}; +const config = () => [{ id: 'model', category: 'model', currentValue: model, options: [{ value: 'fast' }, { value: 'big-thinking' }] }, + { id: 'thought_level', category: 'thought_level', currentValue: effort ?? 'high', options: [{ value: 'low' }, { value: 'high' }] }]; +const info = () => ({ sessionId: conversation, configOptions: config(), modes: { currentModeId: mode, + availableModes: ['default', 'accept-edits', 'auto', 'plan'].map(id => ({ id, name: id })) } }); +let advanceIndex = 0; +let advanceScript = ''; function runTurn(text) { step({ step_index: stepIndex++, state: 'DONE', step_type: 'user_input' }); if (process.env.FAKE_AGY_WEB && text.startsWith('Search the web using')) { @@ -143,6 +165,38 @@ function runTurn(text) { return; } const body = text.replace(/[\s\S]*?<\/loochat-context>/g, '').split(//)[0].trim(); + // FAKE_AGY_ADVANCE names a script file consumed one line per turn, in order: "wait:[:]" + // ends the reply with a `[进度] 等外部` line, "doing:" with `[进度] 进行中`, "review" / "blocked" + // with their stages, "error:" fails the turn, "plain:" answers with no progress + // line, and "slow" stalls until interrupted. Rewriting the file starts it over, so a test can + // script the replies that are still to come. + if (process.env.FAKE_AGY_ADVANCE) { + const text = readFileSync(process.env.FAKE_AGY_ADVANCE, 'utf8'); + const entries = text.split('\n').map(l => l.trim()).filter(Boolean); + if (text !== advanceScript) { advanceScript = text; advanceIndex = 0; } + if (advanceIndex >= entries.length) advanceIndex = 0; + const entry = entries[advanceIndex++]; + if (entry !== undefined) { + const colon = entry.indexOf(':'); + const kind = colon >= 0 ? entry.slice(0, colon) : entry; + const rest = colon >= 0 ? entry.slice(colon + 1) : ''; + if (kind === 'slow') { waiting = true; return; } + if (kind === 'error') { result({ status: 'ERROR', error: rest || 'boom' }); return; } + // A trailing ":" on a wait is the minutes the note should promise. + const waitNote = (() => { + const m = /^(.*?)(?::(\d+))?$/.exec(rest); + return m && m[2] ? `${m[1]},约 ${m[2]} 分钟` : rest; + })(); + const reply = kind === 'wait' ? `还没好。\n[进度] 等外部:${waitNote}` + : kind === 'doing' ? `在忙。\n[进度] 进行中:${rest || '还在做'}` + : kind === 'review' ? `做完了。\n[进度] 待验收:${rest || '请检查'}` + : kind === 'blocked' ? `卡住了。\n[进度] 需要你:${rest || '缺信息'}` + : rest; + step({ step_index: stepIndex++, state: 'DONE', step_type: 'agent_response', text_delta: reply }); + result({ status: 'SUCCESS', response: reply, num_turns: 1 }); + return; + } + } if (body.startsWith('provider-error:')) { result({ status: 'ERROR', error: body.slice('provider-error:'.length).trim() }); return; @@ -167,6 +221,27 @@ function runTurn(text) { return; } if (exhaustTrigger) { exhaustNow(); return; } + // A quota error that promises its own reset in the wording the subscriptions use, for the + // resume watch's message-parsed hint; FAKE_HANDOVER_RESET_IN controls how far out it points. + if (body === 'quota-exhausted-reset') { + const in_ = process.env.FAKE_HANDOVER_RESET_IN ?? '61s'; + result({ status: 'ERROR', error: `Individual quota reached. Please upgrade your subscription to increase your limits. Resets in ${in_}.` }); + return; + } + // A transient provider failure, worded like the real gateways (no capacity on the server). With + // FAKE_TRANSIENT_ONCE naming a marker file it happens once per conversation, so a test can watch + // the daemon retry the same ask; without it every matching ask fails, until the retries give up. + if (body === 'no-capacity') { + const transientFail = () => result({ status: 'ERROR', error: 'API error (attempt 2): UNAVAILABLE (code 503): No capacity available for model gemini-3.8-flash-high on the server' }); + const marker = process.env.FAKE_TRANSIENT_ONCE; + if (!marker) { transientFail(); return; } + const seen = existsSync(marker) ? readFileSync(marker, 'utf8') : ''; + if (!seen.includes(conversation)) { + writeFileSync(marker, seen + conversation + '\n'); + transientFail(); + return; + } + } if ((body === 'quota-near' || body.startsWith('[协作消息') && body.endsWith('quota-near')) && process.env.FAKE_HANDOVER_QUOTA) writeFileSync(process.env.FAKE_HANDOVER_QUOTA, JSON.stringify({ 'Gemini Models': 95, 'Claude Models': 20 })); if (text.startsWith('请写一份交接摘要') && process.env.FAKE_HANDOVER_SUMMARY_FAIL) return result({ status: 'ERROR', error: 'summary failed' }); const coordinated = coordinationFixture(text); @@ -178,7 +253,7 @@ function runTurn(text) { if (process.env.FAKE_LIVE_USAGE && text.includes('live usage')) { agyUsage(conversation, stepIndex++); if (text.includes('slow')) { waiting = true; return; } - setTimeout(() => result({ status: 'SUCCESS', response: 'live usage', num_turns: 1 }), 2400); + setTimeout(() => result({ status: 'SUCCESS', response: 'live usage', num_turns: 1, usage: { inputTokens: 100, cachedReadTokens: 50, cachedWriteTokens: 0, outputTokens: 20, totalTokens: 170 } }), 2400); return; } if (text.includes('crash')) { @@ -196,36 +271,63 @@ function runTurn(text) { step({ step_index: index, state: 'ACTIVE', step_type: 'tool', tool_name: 'run_command', tool_info: info }); step({ step_index: index, state: 'DONE', step_type: 'tool', tool_name: 'run_command', tool_info: { ...info, output: 'hi\r\n' } }); } - if (text.includes('command') && !fullAccess) { - const index = stepIndex++; - const info = { name: 'run_command', parameters: { CommandLine: 'make test' } }; - step({ step_index: index, state: 'ACTIVE', step_type: 'tool', tool_name: 'run_command', tool_info: info }); - step({ step_index: index, state: 'ERROR', step_type: 'tool', tool_name: 'run_command', tool_info: { ...info, error: { type: 'TOOL_ERROR', message: 'user denied permission to run command' } } }); - process.stderr.write('jetski: no output produced\n'); - return result({ status: 'SUCCESS', response: '', denied_actions: [{ action: 'command', display_name: 'RunCommand' }] }); - } const index = stepIndex++; - const reply = `echo:${text};model:${model};mode:${mode};conv:${conversation}`; + const reply = `echo:${text};model:${model};${effort ? `effort:${effort};` : ''}mode:${mode};conv:${conversation}`; step({ step_index: index, state: 'ACTIVE', step_type: 'agent_response', text_delta: reply }); step({ step_index: index, state: 'DONE', step_type: 'agent_response', text_delta: '\n' }); result({ status: 'SUCCESS', response: reply + '\n', num_turns: 1 }); } -let buffer = ''; -process.stdin.setEncoding('utf8'); -process.stdin.on('data', (chunk) => { - buffer += chunk; - let idx; - while ((idx = buffer.indexOf('\n')) >= 0) { - const line = buffer.slice(0, idx).trim(); - buffer = buffer.slice(idx + 1); - if (!line) continue; - const msg = JSON.parse(line); - if (msg.event !== 'user') { - process.stderr.write(`warning: ignoring unsupported stream input message event "${msg.event}"\n`); - continue; +const approvals = new Map(); +let approvalId = 1000; +createInterface({ input: process.stdin }).on('line', async line => { + const msg = JSON.parse(line), p = msg.params ?? {}; + if (process.env.FAKE_AGY_RPC_LOG) appendFileSync(process.env.FAKE_AGY_RPC_LOG, JSON.stringify({ pid: process.pid, ...msg }) + '\n'); + if (!msg.method) { approvals.get(msg.id)?.(msg.result); approvals.delete(msg.id); return; } + switch (msg.method) { + case 'initialize': reply(msg.id, { protocolVersion: 1, agentCapabilities: { loadSession: true, sessionCapabilities: { resume: {} } } }); break; + case 'session/new': + case 'session/resume': + case 'session/load': + conversation = p.sessionId ?? (process.env.FAKE_HANDOVER_EXHAUST_ONCE || process.env.FAKE_TRANSIENT_ONCE ? `agy-conv-${process.pid}` : 'agy-conv-1'); + reply(msg.id, info()); + update({ sessionUpdate: 'available_commands_update', availableCommands: [ + { name: 'compact', description: 'Compact the conversation' }, { name: 'goal', description: 'Set a native goal' }, + { name: 'make-video', description: 'Turn a brief into a video' }] }); + update({ sessionUpdate: 'usage_update', used: 0, size: 1048576 }); + break; + case 'session/set_mode': mode = p.modeId; fullAccess = mode === 'auto'; + update({ sessionUpdate: 'current_mode_update', currentModeId: mode }); reply(msg.id, {}); break; + case 'session/set_config_option': + if (p.configId === 'model') model = p.value; + else if (p.configId === 'thought_level') effort = p.value; + else { out({ jsonrpc: '2.0', id: msg.id, error: { code: -32602, message: 'unknown config' } }); break; } + reply(msg.id, { configOptions: config() }); break; + case 'session/prompt': { + pending = msg.id; + let text = p.prompt.filter(c => c.type === 'text').map(c => c.text).join(''); + if (p.prompt.some(c => c.type === 'image')) text += ';image:embedded'; + if (/^\/compact(?:\s|$)/.test(text)) { + if (text === '/compact fail') { result({ status: 'ERROR', error: 'compact failed' }); break; } + if (text === '/compact slow') { waiting = true; break; } + // agy 1.5.12 reports occupancy and a normal prompt result, no compaction entity. + update({ sessionUpdate: 'usage_update', used: 250, size: 1048576 }); + reply(msg.id, { stopReason: 'end_turn' }); break; + } + if (text === 'usage-drop') { update({ sessionUpdate: 'usage_update', used: 10, size: 1048576 }); reply(msg.id, { stopReason: 'end_turn' }); break; } + if (text.includes('run a command')) { + const id = ++approvalId; + const answer = new Promise(resolve => approvals.set(id, resolve)); + out({ jsonrpc: '2.0', id, method: 'session/request_permission', params: { sessionId: conversation, + toolCall: { toolCallId: 'approval-command', title: 'Run command' }, + options: [{ optionId: 'allow', kind: 'allow_once', name: 'Allow' }, { optionId: 'reject', kind: 'reject_once', name: 'Reject' }] } }); + const res = await answer; + if (res.outcome?.optionId !== 'allow') { reply(msg.id, { stopReason: 'cancelled' }); break; } + } + runTurn(text); break; } - runTurn(String(msg.message?.content ?? '')); + case 'session/cancel': if (waiting) result({ status: 'ERROR', error: 'interrupted' }); break; + default: out({ jsonrpc: '2.0', id: msg.id, error: { code: -32601, message: 'Unknown method' } }); } }); process.stdin.on('end', () => process.exit(0)); diff --git a/apps/workbench/packages/daemon/test/native-goals.test.ts b/apps/workbench/packages/daemon/test/native-goals.test.ts index 7d3912d1fe..3f6c862141 100644 --- a/apps/workbench/packages/daemon/test/native-goals.test.ts +++ b/apps/workbench/packages/daemon/test/native-goals.test.ts @@ -91,11 +91,11 @@ test('Claude exposes native goal, forwards the session command and clears during test('agy native goals, when advertised, stay in the resumed conversation', { timeout: 5000 }, async () => { const a = new AgyAdapter([process.execPath, join(here, 'fixtures/fake-agy.mjs')], { FAKE_AGY_GOAL: '1' }); - assert.ok((await a.commands(here)).some(c => c.name === 'goal')); const s = await a.start({ cwd: here, resumeId: 'existing-conversation' }); const events: EmittedEvent[] = []; try { await s.prompt(input('/goal test'), hooks(events)); + assert.ok((await a.commands(here)).some(c => c.name === 'goal')); const text = events.filter(e => e.type === 'message.delta').map(e => e.data.text).join(''); assert.match(text, /echo:\/goal test/); assert.match(text, /conv:existing-conversation/); diff --git a/apps/workbench/packages/daemon/test/plan-mode.test.ts b/apps/workbench/packages/daemon/test/plan-mode.test.ts index 4dd739f7bc..f2f2725479 100644 --- a/apps/workbench/packages/daemon/test/plan-mode.test.ts +++ b/apps/workbench/packages/daemon/test/plan-mode.test.ts @@ -43,7 +43,7 @@ for (const adapter of adapters()) { assert.equal(s.agentSessionId, id); if (['codex', 'traex'].includes(adapter.id)) { assert.match(text, /approval:never/); assert.match(text, /model:gpt-big/); } if (adapter.id === 'claude') assert.match(text, /mode:bypassPermissions/); - if (adapter.id === 'agy') assert.match(text, /mode:always-proceed/); + if (adapter.id === 'agy') assert.match(text, /mode:auto/); } finally { await s.close(); } }); if (adapter.id === 'agy') continue; diff --git a/apps/workbench/packages/e2e/test/agent-login-recovery.spec.mjs b/apps/workbench/packages/e2e/test/agent-login-recovery.spec.mjs index 6383f2e7a0..418f32366d 100644 --- a/apps/workbench/packages/e2e/test/agent-login-recovery.spec.mjs +++ b/apps/workbench/packages/e2e/test/agent-login-recovery.spec.mjs @@ -51,9 +51,9 @@ for (const adapter of ['agy', 'claude']) for (const mobile of [false, true]) for await recovery.waitFor({ state: 'detached' }); // No picker click or page refresh is allowed to trigger this recovery. await page.waitForFunction(({ id, model }) => Object.values(JSON.parse(localStorage.getItem('calli.host.v1') ?? '{}')) - .some(state => state.models?.[id]?.some(item => item.id === model)), { id, model: adapter === 'agy' ? 'fast-low' : 'big' }); + .some(state => state.models?.[id]?.some(item => item.id === model)), { id, model: adapter === 'agy' ? 'fast' : 'big' }); await page.locator('.model-control-trigger').first().click(); - await page.getByText(adapter === 'agy' ? 'Fast (Low)' : 'Big 1.0', { exact: true }).first().waitFor(); + await page.getByText(adapter === 'agy' ? 'Fast' : 'Big 1.0', { exact: true }).first().waitFor(); await shot('models-restored'); assert.ok(existsSync(credentials)); const agents = await (await api(daemon, '/api/agents')).json(); diff --git a/apps/workbench/packages/e2e/test/agy-acp.spec.mjs b/apps/workbench/packages/e2e/test/agy-acp.spec.mjs new file mode 100644 index 0000000000..bc08c0d6bd --- /dev/null +++ b/apps/workbench/packages/e2e/test/agy-acp.spec.mjs @@ -0,0 +1,72 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { startDaemon, openUi, api, launchBrowser } from '../harness.mjs'; + +test('Antigravity effort picker, reload and compact preserve the native ACP conversation on four layouts', { timeout: 120000 }, async () => { + const root = mkdtempSync(join(tmpdir(), 'agy-acp-browser-')); + const log = join(root, 'rpc.jsonl'); + const daemon = await startDaemon({}, { agents: [{ id: 'agy-secondary', adapter: 'agy', label: 'Antigravity', command: ['fake-agy'], env: { FAKE_AGY_RPC_LOG: log } }] }); + const browser = await launchBrowser(); + const get = async path => (await api(daemon, path)).json(); + const waitFor = async check => { + for (let i = 0; i < 150; i++) { if (await check()) return; await new Promise(resolve => setTimeout(resolve, 50)); } + assert.fail('native state did not settle'); + }; + try { + for (const mobile of [false, true]) for (const colorScheme of ['light', 'dark']) { + writeFileSync(log, ''); + const response = await api(daemon, '/api/threads', { method: 'POST', body: JSON.stringify({ agent: 'agy-secondary', cwd: daemon.workdir, title: 'Antigravity reasoning', model: 'fast', effort: 'low' }) }); + assert.equal(response.status, 201); + const thread = await response.json(); + const context = await browser.newContext({ viewport: mobile ? { width: 390, height: 844 } : { width: 1440, height: 1000 }, isMobile: mobile, hasTouch: mobile, colorScheme }); + try { + const page = await context.newPage(), errors = []; + page.on('pageerror', error => errors.push(error.message)); + await openUi(page, daemon); + await page.evaluate(id => { location.hash = `#/thread/${id}`; }, thread.id); + if (mobile) await page.locator('.composer textarea').last().tap(); + const picker = page.locator('.composer .model-control-trigger'); + await waitFor(async () => (await picker.getAttribute('aria-label'))?.includes('Fast · 低')); + const send = async text => { + await page.locator('.composer textarea').last().fill(text); + await page.keyboard.press('Escape'); + const receipt = page.waitForResponse(r => r.request().method() === 'POST' && new URL(r.url()).pathname === `/api/threads/${thread.id}/turns`); + await page.locator('.composer .send-btn:not(.stop)').click(); + assert.equal((await receipt).status(), 202); + await waitFor(async () => (await get(`/api/threads/${thread.id}`)).status === 'idle'); + }; + await send('First question'); + const nativeId = (await get(`/api/threads/${thread.id}`)).agentSessionId; + if (mobile) await page.locator('.composer textarea').last().tap(); + await picker.click(); + await page.getByRole('slider', { name: '思考强度' }).press('End'); + await waitFor(async () => (await get(`/api/threads/${thread.id}`)).effort === 'high'); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true); + if (process.env.LOOCHAT_E2E_SHOTS_DIR) { + mkdirSync(process.env.LOOCHAT_E2E_SHOTS_DIR, { recursive: true }); + await page.screenshot({ path: join(process.env.LOOCHAT_E2E_SHOTS_DIR, `agy-effort-${mobile ? 'phone' : 'desktop'}-${colorScheme}.png`), animations: 'disabled' }); + } + await page.keyboard.press('Escape'); + await send('Think more deeply'); + await page.locator('.markdown').filter({ hasText: 'model:fast;effort:high;' }).last().waitFor(); + await page.reload(); + await page.locator('.sidebar-inner').waitFor({ state: 'attached' }); + await page.evaluate(id => { location.hash = `#/thread/${id}`; }, thread.id); + if (mobile) await page.locator('.composer textarea').last().tap(); + await waitFor(async () => (await picker.getAttribute('aria-label'))?.includes('Fast · 高')); + await send('/compact'); + const events = await get(`/api/threads/${thread.id}/events`); + assert.ok(events.some(e => e.type === 'tool.end' && e.data.id === 'context-compaction' && e.data.status === 'completed')); + assert.ok(events.some(e => e.type === 'usage.updated' && e.data.used === 250)); + assert.equal((await get(`/api/threads/${thread.id}`)).agentSessionId, nativeId); + const calls = readFileSync(log, 'utf8').trim().split('\n').map(line => JSON.parse(line)); + assert.equal(new Set(calls.map(c => c.pid)).size, 1, 'effort changes and compaction keep one native process'); + assert.ok(calls.some(c => c.method === 'session/set_config_option' && c.params.configId === 'thought_level' && c.params.value === 'high')); + assert.deepEqual(errors, []); + } finally { await context.close(); } + } + } finally { await browser.close(); await daemon.stop(); rmSync(root, { recursive: true, force: true }); } +}); diff --git a/apps/workbench/packages/e2e/test/agy-models.spec.mjs b/apps/workbench/packages/e2e/test/agy-models.spec.mjs new file mode 100644 index 0000000000..e42bdacc91 --- /dev/null +++ b/apps/workbench/packages/e2e/test/agy-models.spec.mjs @@ -0,0 +1,66 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { startDaemon, openUi, api, launchBrowser } from '../harness.mjs'; + +// The native catalog observed before and after the account's model entitlement propagated. +const model = (id, label) => ({ id, label }); +const flash = ['high', 'medium', 'low'].map(effort => model(`gemini-3.8-flash-${effort}`, `Gemini 3.8 Flash (${effort})`)); +const oss = model('gpt-oss-120b-medium', 'GPT-OSS 120B (Medium)'); +const initial = [...flash, model('claude-sonnet-4-6', 'Claude Sonnet 4.6 (Thinking)'), model('claude-opus-4-6-thinking', 'Claude Opus 4.6 (Thinking)'), oss]; +const complete = [ + ...['medium', 'high', 'low'].map(e => model(`gemini-4-argon-${e}`, `Gemini 4 Argon (${e})`)), + ...['high', 'xhigh', 'medium', 'low'].map(e => model(`gemini-4-hydrogen-${e}`, `Gemini 4 Hydrogen (${e})`)), + model('gemini-pro-orchestrator-g1-pro', 'Orchestrator (Argon)'), ...flash, + ...['opus', 'sonnet'].flatMap(f => ['low', 'medium', 'high'].map(e => model(`claude-${f}-5-5-${e}`, `Claude ${f} 5.5 (${e})`))), oss, +]; + +test('agy models group effort variants into an effort slider and refresh in an open picker without changing the chosen model', { timeout: 120_000 }, async () => { + const root = mkdtempSync(join(tmpdir(), 'loochat-agy-models-e2e-')); + const file = join(root, 'catalog.json'); + const catalog = models => writeFileSync(file, JSON.stringify({ models })); + catalog(initial); + const daemon = await startDaemon({}, { agents: [{ id: 'agy', adapter: 'agy', label: 'Antigravity', command: ['fake-agy'], env: { FAKE_AGY_MODELS_FILE: file } }] }); + let browser; + try { + browser = await launchBrowser(); + for (const mobile of [false, true]) for (const colorScheme of ['light', 'dark']) { + catalog(initial); + assert.equal((await (await api(daemon, '/api/agents/agy/models?refresh=1')).json()).length, 4); + const context = await browser.newContext({ viewport: mobile ? { width: 390, height: 844 } : { width: 1440, height: 1000 }, isMobile: mobile, hasTouch: mobile, colorScheme }); + try { + await context.addInitScript(() => localStorage.setItem('calli_onboard_dismissed', '1')); + const page = await context.newPage(); + const errors = []; + page.on('pageerror', error => errors.push(String(error))); + await openUi(page, daemon); + await page.locator('.model-control-trigger').click(); + await page.locator('.effort-card').waitFor(); + await page.locator('.effort-model').click(); + await page.getByRole('menuitemradio', { name: 'Claude Sonnet 4.6 (Thinking)', exact: true }).waitFor(); + const preferences = await (await api(daemon, '/api/draft-model-preferences')).json(); + catalog(complete); + const refresh = page.getByRole('button', { name: '刷新模型列表', exact: true }); + await refresh.click(); + await page.getByRole('menuitemradio', { name: 'Gemini 4 Argon', exact: true }).waitFor(); + await page.getByRole('menuitemradio', { name: 'Gemini 4 Hydrogen', exact: true }).waitFor(); + assert.equal(await page.locator('.model-control-panel [role="menuitemradio"]').count(), 8); + const last = page.getByRole('menuitemradio', { name: 'Claude sonnet 5.5', exact: true }); + await last.scrollIntoViewIfNeeded(); + assert.ok(await last.isVisible()); + if (process.env.LOOCHAT_E2E_SHOTS_DIR) { + mkdirSync(process.env.LOOCHAT_E2E_SHOTS_DIR, { recursive: true }); + await page.screenshot({ path: join(process.env.LOOCHAT_E2E_SHOTS_DIR, `agy-models-${mobile ? 'phone' : 'desktop'}-${colorScheme}.png`), animations: 'disabled' }); + } + // A refresh from another client updates this already-open picker through the shared stream. + catalog([...complete, model('gemini-later', 'Newly available model')]); + await api(daemon, '/api/agents/agy/models?refresh=1'); + await page.getByRole('menuitemradio', { name: 'Newly available model', exact: true }).waitFor(); + assert.deepEqual(await (await api(daemon, '/api/draft-model-preferences')).json(), preferences); + assert.deepEqual(errors, []); + } finally { await context.close(); } + } + } finally { await browser?.close(); await daemon.stop(); rmSync(root, { recursive: true, force: true }); } +}); diff --git a/apps/workbench/packages/web/src/App.tsx b/apps/workbench/packages/web/src/App.tsx index e085641f94..707b53d404 100644 --- a/apps/workbench/packages/web/src/App.tsx +++ b/apps/workbench/packages/web/src/App.tsx @@ -124,7 +124,7 @@ import { cachedAgentMarks, cachedThreads, rememberAgentMarks, rememberThreads } import { cachedAgents, cachedDraft, cachedModels, rememberAgents, rememberDraft, rememberModels } from './host-cache'; import { clampSidebarWidth, defaultSidebarWidth, projectDir, savedSidebarWidth, SIDEBAR_MAX_WIDTH, SIDEBAR_MIN_WIDTH, type HostSource } from './sidebar'; import { enabledViews, extensionHash, looksLikeExtensionRoute, resolveExtensionRoute } from './extensions/routes'; -import { AgentPicker, type DiscoveredAccount, type DiscoveredAgent, effortsForModel, imagesBlocked, imagesNote, modelName, speedsForModel, ModelPicker, PermissionPicker, UsageMeter, WorkspacePicker } from './components/Pickers'; +import { AgentPicker, type DiscoveredAccount, type DiscoveredAgent, effortsForModel, imagesBlocked, imagesNote, modelName, resolveModel, speedsForModel, ModelPicker, PermissionPicker, UsageMeter, WorkspacePicker } from './components/Pickers'; import { Sidebar, SIDEBAR_SHORTCUT } from './components/Sidebar'; import { MergedHistory } from './components/MergedHistory'; import { currentPlan, PlanButton } from './components/PlanPanel'; @@ -409,9 +409,12 @@ function savedMemberDefaults(key: string): Record { } function fitDraftModelPreference(value: DraftModelPreference, models: ModelOption[], effortLevels: string[], canSpeed: boolean): DraftModelPreference { - const model = value.model && models.length > 0 && !models.some((option) => option.id === value.model) ? null : value.model; + const resolved = value.model && models.length > 0 ? resolveModel(models, value.model) : undefined; + const impliedEffort = value.model && resolved && resolved.id !== value.model ? value.model.slice(resolved.id.length + 1) : null; + const model = value.model && models.length > 0 ? (resolved?.id ?? null) : value.model; const levels = effortsForModel(models, model, effortLevels); - const effort = value.effort && (levels.includes(value.effort) || (models.length === 0 && effortLevels.length === 0)) ? value.effort : null; + const rawEffort = value.effort ?? impliedEffort; + const effort = rawEffort && (levels.includes(rawEffort) || (models.length === 0 && effortLevels.length === 0)) ? rawEffort : null; const speeds = speedsForModel(models, model); const speed = canSpeed && value.speed && (models.length === 0 || speeds.some((option) => option.id === value.speed)) ? value.speed : null; return { model, effort, speed }; diff --git a/apps/workbench/packages/web/src/components/Pickers.tsx b/apps/workbench/packages/web/src/components/Pickers.tsx index 4d85c98516..0a5f63ae2f 100644 --- a/apps/workbench/packages/web/src/components/Pickers.tsx +++ b/apps/workbench/packages/web/src/components/Pickers.tsx @@ -87,10 +87,11 @@ export function PermissionPicker({ modes, value, onChange, canAsk, openSignal, q } interface ModelProps { - catalogStatus?: 'loading' | 'ready' | 'error'; - onRetryCatalog?: () => void; preferenceStatus?: 'loading' | 'ready' | 'error'; onRetryPreference?: () => void; + /** Loading state for the model catalog itself, before any saved preference is considered. */ + catalogStatus?: 'loading' | 'ready' | 'error'; + onRetryCatalog?: () => void; onDiagnose?: () => void; /** False when the CLI does not expose a model catalog at all, rather than one that failed to load. */ catalog?: boolean; @@ -121,7 +122,10 @@ const AGENT_DEFAULT = 'default'; * entry with the id "default" if there is one (Claude), else the entry flagged as default (pi). */ export function resolveModel(models: ModelOption[], id: string | null): ModelOption | undefined { - if (id !== null) return models.find((m) => m.id === id); + if (id !== null) { + return models.find((m) => m.id === id) + ?? models.find((m) => m.efforts?.some((e) => `${m.id}-${e}` === id)); + } return models.find((m) => m.id === AGENT_DEFAULT) ?? models.find((m) => m.isDefault); } @@ -135,7 +139,7 @@ function defaultTarget(models: ModelOption[]): string | undefined { /** The name shown for a model id. With no override, the model the agent's default points at. */ export function modelName(models: ModelOption[], id: string | null): string { if (id === null) return defaultTarget(models) ?? t('pickers.defaultModel'); - return models.find((m) => m.id === id)?.label ?? id; + return resolveModel(models, id)?.label ?? id; } /** Current load for the selected model, including an agent-owned default alias. */ @@ -218,8 +222,11 @@ export function ModelPicker(props: ModelProps) { const { models, model, efforts, effort, openSignal, quietFor } = props; const narrow = useIsNarrow(); if (props.catalog === false) return null; + const resolved = resolveModel(models, model); + const impliedEffort = !effort && model && resolved && resolved.id !== model && model.startsWith(resolved.id + '-') ? model.slice(resolved.id.length + 1) : null; + const effectiveEffort = effort ?? impliedEffort; const levels = effortsForModel(models, model, efforts); - const shownEffort = effort && levels.includes(effort) ? effort : null; + const shownEffort = effectiveEffort && levels.includes(effectiveEffort) ? effectiveEffort : null; if (props.catalogStatus && props.catalogStatus !== 'ready') { const failed = props.catalogStatus === 'error'; const label = failed ? t('pickers.modelsLoadFailed') : t('common.loading'); @@ -233,7 +240,6 @@ export function ModelPicker(props: ModelProps) { {() => <>
{label}
{failed && }} ; } - if (props.preferenceStatus && props.preferenceStatus !== 'ready') { const failed = props.preferenceStatus === 'error'; const label = failed ? t('pickers.preferenceFailed') : t('common.loading'); @@ -303,7 +309,7 @@ export function ModelPicker(props: ModelProps) { ); } -function ModelControl({ models, model, efforts, effort, onModel, onEffort, speed, onSpeed }: ModelProps) { +function ModelControl({ models, model, efforts, effort, onModel, onEffort, speed, onSpeed, onOpen }: ModelProps) { const levels = effortsForModel(models, model, efforts); const selectedModel = resolveModel(models, model); const loadPercent = selectedModel?.loadPercent; @@ -325,20 +331,24 @@ function ModelControl({ models, model, efforts, effort, onModel, onEffort, speed const accelerated = speeds.some(s => s.id === speed && isFastSpeed(s)); const [showModels, setShowModels] = useState(levels.length === 0 && !canAccelerate); const [preview, setPreview] = useState(undefined); - const selected = effort && levels.includes(effort) ? effort : null; + const impliedEffort = !effort && model && selectedModel && selectedModel.id !== model && model.startsWith(selectedModel.id + '-') ? model.slice(selectedModel.id.length + 1) : null; + const effectiveEffort = effort ?? impliedEffort; + const selected = effectiveEffort && levels.includes(effectiveEffort) ? effectiveEffort : null; const shown = preview === undefined ? selected : preview; + const checkedModel = model === AGENT_DEFAULT ? null : (selectedModel && model !== null ? selectedModel.id : model); return showModels ? ( <>
{(levels.length > 0 || canAccelerate) && } {t('pickers.chooseModel')} + {onOpen && }
{modelRows(models, now).map((row) => ( - ))}
diff --git a/apps/workbench/packages/web/src/i18n/locales/en.ts b/apps/workbench/packages/web/src/i18n/locales/en.ts index 171a075e8b..3ba9eb56d7 100644 --- a/apps/workbench/packages/web/src/i18n/locales/en.ts +++ b/apps/workbench/packages/web/src/i18n/locales/en.ts @@ -2052,6 +2052,7 @@ export const en: Messages = { 'pickers.noModels': 'No models available', 'pickers.noModelsHint': 'No models have been read from this instance yet. Check its model configuration and login, then reload the page.', 'pickers.diagnose': 'Check instance', + 'pickers.refreshModels': 'Refresh model list', 'pickers.modelsLoadFailed': 'Could not load models', 'pickers.preferenceFailed': 'Could not load model preferences', 'pickers.modelAndEffort': 'Model and thinking effort', diff --git a/apps/workbench/packages/web/src/i18n/locales/ja.ts b/apps/workbench/packages/web/src/i18n/locales/ja.ts index e5b0cc0e9f..8fa16129a9 100644 --- a/apps/workbench/packages/web/src/i18n/locales/ja.ts +++ b/apps/workbench/packages/web/src/i18n/locales/ja.ts @@ -2050,6 +2050,7 @@ export const ja: Messages = { 'pickers.noModels': '選択できるモデルがありません', 'pickers.noModelsHint': 'このインスタンスからモデルをまだ取得できていません。インスタンスのモデル設定とログイン状態を確認し、設定後にページを再読み込みしてください。', 'pickers.diagnose': 'インスタンスを確認', + 'pickers.refreshModels': 'モデル一覧を更新', 'pickers.modelsLoadFailed': 'モデル一覧を読み込めませんでした', 'pickers.preferenceFailed': 'モデル設定を読み込めませんでした', 'pickers.modelAndEffort': 'モデルと思考の強さ', diff --git a/apps/workbench/packages/web/src/i18n/locales/zh.ts b/apps/workbench/packages/web/src/i18n/locales/zh.ts index cd45a2f97e..c5ecd0ca2f 100644 --- a/apps/workbench/packages/web/src/i18n/locales/zh.ts +++ b/apps/workbench/packages/web/src/i18n/locales/zh.ts @@ -2052,6 +2052,7 @@ export const zh = { 'pickers.noModels': '暂无可选模型', 'pickers.noModelsHint': '还没有从这个实例读到可选模型。请检查实例的模型配置与登录状态,配置完成后刷新页面。', 'pickers.diagnose': '检查实例', + 'pickers.refreshModels': '刷新模型列表', 'pickers.modelsLoadFailed': '模型列表读取失败', 'pickers.preferenceFailed': '模型偏好读取失败', 'pickers.modelAndEffort': '模型与思考强度', diff --git a/apps/workbench/packages/web/src/styles.css b/apps/workbench/packages/web/src/styles.css index 9b65547ca5..fe847623fe 100644 --- a/apps/workbench/packages/web/src/styles.css +++ b/apps/workbench/packages/web/src/styles.css @@ -10374,6 +10374,7 @@ div.file-card:hover { background: var(--surface); } font-size: 13px; } .model-back svg { transform: rotate(180deg); } +.model-refresh { margin-left: auto; } .context-compact { border-top: 1px solid var(--border); diff --git a/apps/workbench/packages/web/test/pickers.test.ts b/apps/workbench/packages/web/test/pickers.test.ts index e8bc634934..166728ff01 100644 --- a/apps/workbench/packages/web/test/pickers.test.ts +++ b/apps/workbench/packages/web/test/pickers.test.ts @@ -286,3 +286,12 @@ test('a CLI without a native catalog exposes no model or effort picker, includin assert.equal(renderToStaticMarkup(createElement(ModelPicker, props)), ''); assert.equal(renderToStaticMarkup(createElement(ModelPicker, { ...props, quietFor: 'CLI instance' })), ''); }); + +test('a legacy combined model-effort id resolves to its model family and effort', () => { + const models = [ + { id: 'gemini-4-argon', label: 'Gemini 4 Argon', efforts: ['low', 'medium', 'high'], isDefault: true }, + { id: 'gpt-oss-120b-medium', label: 'GPT-OSS 120B (Medium)', efforts: [] }, + ]; + assert.equal(modelName(models, 'gemini-4-argon-high'), 'Gemini 4 Argon'); + assert.deepEqual(effortsForModel(models, 'gemini-4-argon-high', []), ['low', 'medium', 'high']); +}); diff --git a/benchmark/edgebench/run.py b/benchmark/edgebench/run.py index e679d04b05..50efb3b7d3 100644 --- a/benchmark/edgebench/run.py +++ b/benchmark/edgebench/run.py @@ -131,6 +131,14 @@ def main(argv=None): help="Explicit complete v1 Turn contract with shared exact-Turn settlement; heartbeat workers only") parser.add_argument("--context-delivery", choices=("off", "on"), help="Native Codex context delivery: on by default for heartbeat workers; pass off to disable") + parser.add_argument("--compact-direct-read", action="store_true", + help="Opt-in Phase-2 lock-free compact hook direct-read (--compact-direct-read in hooks.json)") + parser.add_argument("--quiet-turn", action="store_true", + help="Opt-in Quiet-Turn skip metadata evaluation for supported heartbeat/turn workers") + parser.add_argument("--epoch-prefetch-json", type=json.loads, default=None, + help="Opt-in Stage-then-Swap EpochReset JSON configuration for supported heartbeat/turn workers") + parser.add_argument("--execution-yardstick-enabled", action=argparse.BooleanOptionalAction, default=None, + help="Opt-in Yardstick measurement review toggle for configure-goal (including WarmStart)") parser.add_argument("--execution-observation", choices=("local_probe",), help="Optional local execution probe for heartbeat workers") parser.add_argument("--native-result-comparison", action="store_true", @@ -216,6 +224,9 @@ def main(argv=None): context_delivery=args.context_delivery, turn_envelope=args.turn_envelope, complete_turn=args.complete_turn, validation_command=args.validation_command_json, native_child_limit=args.native_child_limit, + compact_direct_read=args.compact_direct_read, + quiet_turn=args.quiet_turn, + epoch_prefetch_json=args.epoch_prefetch_json, ) except ValueError as error: parser.error(str(error)) @@ -275,6 +286,8 @@ def main(argv=None): parser.error("--stride-strategy requires a heartbeat worker or turn-resume") if args.planning_horizon_goal is not None and not execution.uses_loopx: parser.error("--planning-horizon-goal requires a heartbeat worker or turn-resume") + if args.execution_yardstick_enabled is not None and not execution.uses_loopx: + parser.error("--execution-yardstick-enabled requires a heartbeat worker or turn-resume") checkpoint_request = None if args.checkpoint_request is not None: if not args.worker.startswith("heartbeat-"): @@ -464,6 +477,12 @@ def main(argv=None): validation_command=execution.validation_command, turn_envelope=args.turn_envelope, **({"complete_turn": True} if args.complete_turn else {}), + **({"compact_direct_read": True} if args.compact_direct_read else {}), + **({"quiet_turn": True} if args.quiet_turn else {}), + **({"epoch_prefetch_json": execution.epoch_prefetch_json} + if execution.epoch_prefetch_json is not None else {}), + **({"execution_yardstick_enabled": args.execution_yardstick_enabled} + if args.execution_yardstick_enabled is not None else {}), context_delivery=args.context_delivery, **({"execution_observation": args.execution_observation} if args.execution_observation is not None else {}), diff --git a/benchmark/runtime/RUNTIME.md b/benchmark/runtime/RUNTIME.md index e5385db2dd..2d2b0e3c68 100644 --- a/benchmark/runtime/RUNTIME.md +++ b/benchmark/runtime/RUNTIME.md @@ -81,6 +81,30 @@ agents: replan_after_turns: 6 ``` +### Official-style Codex Stop hook + +Set `execution_mode: plain` and `official_stop_hook: true` in +`BenchmarkCodex` kwargs for a native Codex baseline. One +`codex exec` owns the conversation. On attempted completion, the native Stop +hook asks Codex to continue working, using the same instruction as EdgeBench's +SForge official profile. The worker uses the remaining phase clock through +native execution. The task controller may stop it earlier when the task's +original final submission is accepted. + +The runner stages only its own hook in the trial's Codex home and trusts the +exact handler identity discovered by that Codex binary. Both discovery requests +share the worker deadline when one is declared. With no worker or phase deadline, +discovery retains its bounded RPC timeouts while model work has no independent +cutoff; the task controller still owns submission and cancellation. If the phase expires during discovery, the wake +records budget exhaustion and no model launch. Earlier discovery failures +still fail the trial before inference. Install and trajectory receipts record +the opt-in. The wake receipt records successful hook discovery. +Use the same pinned task, model, reasoning effort, time and evaluator in +comparison arms. The benchmark adapter still owns feedback, final submission, +and scoring. EdgeBench's SForge auto-resume remains a provider-specific part of +its official profile. Use a fresh trial with the option omitted for a +single-pass Codex baseline. + Historical Short trials request `turn_envelope: true` in heartbeat `kwargs`. Before planning or execution starts a model, the worker previews the selected product's quota response through the same CLI. Its wake receipt records the diff --git a/benchmark/runtime/codex.py b/benchmark/runtime/codex.py index 8766af77fb..a92227f2c1 100644 --- a/benchmark/runtime/codex.py +++ b/benchmark/runtime/codex.py @@ -6,8 +6,10 @@ import json import math import os +from collections.abc import Mapping from dataclasses import dataclass from pathlib import Path +from typing import Any # New benchmark runs and the product both default to six settled work Turns. @@ -20,6 +22,34 @@ SANDBOXES = ("read-only", "workspace-write", "danger-full-access") +def normalize_epoch_prefetch_json(value: Any) -> str | None: + """Normalize optional Stage-then-Swap EpochReset config to canonical compact JSON.""" + if value is None or value == "": + return None + if isinstance(value, Mapping): + parsed = dict(value) + elif isinstance(value, str): + try: + decoded = json.loads(value) + except json.JSONDecodeError as exc: + raise ValueError("epoch_prefetch_json must be valid JSON") from exc + if not isinstance(decoded, dict): + raise ValueError("epoch_prefetch_json must decode to a JSON object") + parsed = decoded + else: + raise ValueError("epoch_prefetch_json must be a JSON string or mapping") + return json.dumps(parsed, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + + +def epoch_prefetch_enabled(value: Any) -> bool: + """Return True iff normalized epoch_prefetch JSON explicitly enables the treatment.""" + normalized = normalize_epoch_prefetch_json(value) + if normalized is None: + return False + decoded = json.loads(normalized) + return isinstance(decoded, dict) and decoded.get("enabled") is True + + @dataclass(frozen=True) class Execution: mode: str = "heartbeat" @@ -32,6 +62,10 @@ class Execution: context_delivery: str | None = None native_child_limit: int | None = None complete_turn: bool = False + compact_direct_read: bool = False + quiet_turn: bool = False + epoch_prefetch_json: str | None = None + official_stop_hook: bool = False def __post_init__(self) -> None: if self.native_child_limit is not None and ( @@ -48,6 +82,24 @@ def __post_init__(self) -> None: raise ValueError("turn_envelope requires heartbeat execution and a boolean opt-in") if type(self.complete_turn) is not bool or (self.complete_turn and (self.mode != "heartbeat" or self.turn_envelope)): raise ValueError("complete_turn requires heartbeat execution without legacy turn_envelope") + if type(self.compact_direct_read) is not bool or ( + self.compact_direct_read and (self.mode != "heartbeat" or self.context_delivery != "on") + ): + raise ValueError("compact_direct_read requires heartbeat execution with context_delivery=on") + if type(self.quiet_turn) is not bool or ( + self.quiet_turn and self.mode not in {"heartbeat", "turn"} + ): + raise ValueError("quiet_turn requires heartbeat or turn execution and a boolean opt-in") + if self.quiet_turn and self.mode == "heartbeat" and self.context_delivery != "on": + raise ValueError("quiet_turn in heartbeat mode requires context_delivery=on") + normalized_prefetch = normalize_epoch_prefetch_json(self.epoch_prefetch_json) + object.__setattr__(self, "epoch_prefetch_json", normalized_prefetch) + if normalized_prefetch is not None and self.mode not in {"heartbeat", "turn"}: + raise ValueError("epoch_prefetch_json requires heartbeat or turn execution") + if normalized_prefetch is not None and self.mode == "heartbeat" and self.context_delivery != "on": + raise ValueError("epoch_prefetch_json in heartbeat mode requires context_delivery=on") + if type(self.official_stop_hook) is not bool or (self.official_stop_hook and self.mode != "plain"): + raise ValueError("official_stop_hook requires plain execution and a boolean opt-in") if self.mode not in MODES or self.context not in CONTEXTS: raise ValueError("unsupported execution mode or iteration context") if self.task_entry is None: @@ -89,22 +141,40 @@ def native_goal(self) -> bool: return self.mode in {"native-goal", "loopx-goal"} -def turn_envelope_receipt(*, explicit: bool, complete: bool = False) -> dict: +def turn_envelope_receipt(*, explicit: bool, complete: bool = False) -> dict[str, Any]: """Record only the explicit display opt-in; checkpoint capture is independent.""" return {**({"turn_envelope": True, "turn_envelope_source": "explicit"} if explicit else {}), **({"complete_turn": True, "complete_turn_source": "explicit"} if complete else {})} -def explicit_turn_display(env: dict[str, str]) -> Execution: +def explicit_turn_display(env: Mapping[str, str]) -> Execution: """Decode the shared explicit display request through its Execution owner.""" - selected = {} + selected: dict[str, bool] = {} for variable, field in (("LOOPX_TURN_ENVELOPE", "turn_envelope"), ("LOOPX_COMPLETE_TURN", "complete_turn")): value = env.get(variable, "0") if value not in {"0", "1"}: raise ValueError(f"{variable} must be 0 or 1") selected[field] = value == "1" - return Execution(**selected) + return Execution( + turn_envelope=selected["turn_envelope"], + complete_turn=selected["complete_turn"], + ) + + +def explicit_context_opt_ins(env: Mapping[str, str]) -> dict[str, Any]: + """Decode strictly default-off hook/Turn optimization opt-ins from worker env.""" + parsed: dict[str, Any] = {} + for variable, field in (("LOOPX_COMPACT_DIRECT_READ", "compact_direct_read"), + ("LOOPX_QUIET_TURN", "quiet_turn")): + value = env.get(variable, "0") + if value not in {"0", "1"}: + raise ValueError(f"{variable} must be 0 or 1") + parsed[field] = value == "1" + parsed["epoch_prefetch_json"] = normalize_epoch_prefetch_json( + env.get("LOOPX_EPOCH_PREFETCH_JSON") + ) + return parsed def native_child_instructions(limit: int | None) -> str: @@ -126,7 +196,7 @@ def native_child_instructions(limit: int | None) -> str: "and close child work before the parent finishes.\n" ) -def validate_model_catalog(model_catalog: Path, model: str) -> dict: +def validate_model_catalog(model_catalog: Path, model: str) -> dict[str, Any]: """Admit only catalog entries that keep Codex's function-tool surface. Real catalog entries are not capability-only. ``tool_mode`` selects how @@ -208,6 +278,7 @@ def codex_settings( "[features]", f"goals = {str(execution.native_goal).lower()}", "unified_exec = true", + *(["hooks = true"] if execution.official_stop_hook else []), *(["[agents]", f"max_concurrent_threads_per_session = {execution.native_child_limit}"] if execution.native_child_limit is not None else []), "[memories]", diff --git a/benchmark/runtime/context_delivery.py b/benchmark/runtime/context_delivery.py index f05a6e1051..e6ed0106b7 100644 --- a/benchmark/runtime/context_delivery.py +++ b/benchmark/runtime/context_delivery.py @@ -5,11 +5,20 @@ """ from __future__ import annotations +import inspect import json import os import stat import shlex from pathlib import Path +from typing import Any + +from .codex import explicit_context_opt_ins +from .native_hooks import prepare_native_hooks + + +class ContextOptInConfigurationError(ValueError): + """Explicit opt-in hook parameter failed validation or product compatibility.""" def preflight_context_instruction(env: dict[str, str], path: Path, digest: str, turn_id: str, *, @@ -44,7 +53,6 @@ def preflight_context_instruction(env: dict[str, str], path: Path, digest: str, def prepare_context_delivery(env: dict[str, str], home: Path) -> None: from loopx.control_plane.turn_driver.codex_context import codex_context_configuration - from loopx.control_plane.turn_driver.codex_stdio import StdioNativeGoalTransport root = home / "loopx-context" root.mkdir(mode=0o700, exist_ok=True) @@ -52,61 +60,37 @@ def prepare_context_delivery(env: dict[str, str], home: Path) -> None: if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077: raise ValueError("context delivery requires a private, physical trial directory") env["LOOPX_CODEX_CONTEXT_DIR"] = str(root) + try: + opt_ins = explicit_context_opt_ins(env) + except ValueError as exc: + raise ContextOptInConfigurationError(str(exc)) from exc + params = inspect.signature(codex_context_configuration).parameters + extra_config: dict[str, Any] = {} + if opt_ins["compact_direct_read"]: + if "compact_direct_read" not in params: + raise ContextOptInConfigurationError( + "compact_direct_read requires a LoopX product release supporting --compact-direct-read" + ) + extra_config["compact_direct_read"] = True + if opt_ins["quiet_turn"]: + if "quiet_turn" not in params: + raise ContextOptInConfigurationError( + "quiet_turn requires a LoopX product release supporting --quiet-turn on context-config/hook" + ) + extra_config["quiet_turn"] = True + if opt_ins["epoch_prefetch_json"] is not None: + if "epoch_prefetch" not in params: + raise ContextOptInConfigurationError( + "epoch_prefetch_json requires a LoopX product release supporting --epoch-prefetch-json on context-config/hook" + ) + extra_config["epoch_prefetch"] = json.loads(opt_ins["epoch_prefetch_json"]) configuration = codex_context_configuration(str(root), goal_id=env["LOOPX_GOAL_ID"], - agent_id=env["LOOPX_AGENT_ID"], scenario="codex_benchmark_heartbeat", cli_argv=[env["LOOPX_CLI"], "--cli-bin", env["LOOPX_CLI"]]) - content = json.dumps({"hooks": configuration["hooks"]}) - path = home / "hooks.json" - if path.is_symlink() or (path.exists() and path.read_text() != content): - raise ValueError("native context hooks changed within a trial; use a new trial") - if not path.exists(): - path.write_text(content) - path.chmod(0o600) - # The native host is the hash/key owner. Do not duplicate its hashing or - # bypass trust for unrelated workspace hooks. Discovery launches no model. - with (home / "context-hooks-stderr.log").open("a") as stderr: - with StdioNativeGoalTransport.spawn( - # This process only reads native hook identities. Catalog/plugin - # startup can clone repositories into an otherwise private home; - # it is unrelated to discovery and must not affect solver config. - [env["CODEX_BIN"], "-c", "features.plugins=false", - "-c", "features.remote_plugin=false", "-c", "features.plugin_sharing=false", - "app-server", "--listen", "stdio://"], - cwd=env["LOOPX_PROJECT"], env=env, stderr=stderr, response_timeout_sec=10, - ) as native: - native.request("initialize", {"clientInfo": {"name": "loopx_context_transport", "version": "0.1.0"}, - "capabilities": {"experimentalApi": True}}) - native.notify("initialized", {}) - listed = native.request("hooks/list", {"cwds": [env["LOOPX_PROJECT"]]}) - hooks = [hook for entry in listed["data"] for hook in entry["hooks"] - if hook.get("sourcePath") == str(path.resolve())] - # Match the generated handler multiset, not just its size. Native discovery - # can reorder it; duplicates, disabled handlers and substitutions cannot - # stand in for an expected event/command/settings combination. - expected = [{"eventName": event[0].lower() + event[1:], - "handlerType": handler["type"], "command": handler["command"], - "matcher": group.get("matcher"), "timeoutSec": handler.get("timeout"), - "async": handler.get("async", False)} - for event, groups in configuration["hooks"].items() - for group in groups for handler in group["hooks"]] - if not expected or len(hooks) != len(expected) or path.read_text() != content: - raise ValueError("native host did not discover the exact trial context hooks") - entries, keys = [], set() - for hook in hooks: - actual = {field: hook.get(field) for field in expected[0]} - if hook.get("enabled") is not True or type(hook.get("async")) is not bool or actual not in expected: - raise ValueError("native host did not discover the exact trial context hooks") - expected.remove(actual) - key, digest = hook.get("key"), hook.get("currentHash") - if not isinstance(key, str) or not key or key in keys or not isinstance(digest, str) or not digest: - raise ValueError("native host returned no unique context-hook trust identity") - keys.add(key) - entries.append(f"{json.dumps(key)} = {{ trusted_hash = {json.dumps(digest)} }}") - # CLI override keys are dot-separated; native keys contain paths/dots. - # Carry the entire table as TOML so native keys remain literal strings. + agent_id=env["LOOPX_AGENT_ID"], scenario="codex_benchmark_heartbeat", cli_argv=[env["LOOPX_CLI"], "--cli-bin", env["LOOPX_CLI"]], + **extra_config) + native_args = prepare_native_hooks(env, home, configuration["hooks"], purpose="context") # This isolated trial's native developer instructions survive compaction; # a failed SessionStart handler cannot erase the read-only recovery route. - native_args = ["-c", "hooks.state={" + ",".join(entries) + "}", - "-c", "developer_instructions=" + json.dumps(configuration["developer_instructions"])] + native_args += ["-c", "developer_instructions=" + json.dumps(configuration["developer_instructions"])] native_args += [argument for key, value in configuration["config_overrides"].items() for argument in ("-c", key + "=" + json.dumps(value))] env["LOOPX_CODEX_CONTEXT_TRUST_ARGS"] = json.dumps(native_args) diff --git a/benchmark/runtime/harbor.py b/benchmark/runtime/harbor.py index b90d81b660..48bc93bc90 100644 --- a/benchmark/runtime/harbor.py +++ b/benchmark/runtime/harbor.py @@ -21,7 +21,13 @@ from loopx.control_plane.goals.goal_vision_policy import DEFAULT_PLANNING_HORIZON_GOAL from .codex_offline import MODEL_CATALOG_REMOTE, CodexOffline, stage_portable_python -from .codex import DEFAULT_REPLAN_AFTER_TURNS, Execution, turn_envelope_receipt +from .codex import ( + DEFAULT_REPLAN_AFTER_TURNS, + Execution, + epoch_prefetch_enabled, + normalize_epoch_prefetch_json, + turn_envelope_receipt, +) from .layout import _ROOT, _SRC, _CONTROL, _CODEX_HOME, _REGISTRY, _LOOPX_RUNTIME from .scheduler import phase_work_reserve @@ -84,6 +90,11 @@ def __init__( agent_id=_AGENT_ID, defer_codex_home=False, complete_turn=False, + compact_direct_read=False, + quiet_turn=False, + epoch_prefetch_json=None, + execution_yardstick_enabled=None, + official_stop_hook=False, **kwargs, ): if "research_loop" in kwargs: @@ -105,6 +116,10 @@ def __init__( context_delivery, native_child_limit, complete_turn=complete_turn, + compact_direct_read=compact_direct_read, + quiet_turn=quiet_turn, + epoch_prefetch_json=normalize_epoch_prefetch_json(epoch_prefetch_json), + official_stop_hook=official_stop_hook, ) if type(provider_request_admission) is not bool: raise ValueError("provider_request_admission must be a boolean opt-in") @@ -149,6 +164,12 @@ def __init__( DEFAULT_PLANNING_HORIZON_GOAL if planning_horizon_goal is None and self.execution.uses_loopx else planning_horizon_goal ) + if execution_yardstick_enabled is not None: + if type(execution_yardstick_enabled) is not bool: + raise ValueError("execution_yardstick_enabled must be a boolean") + if not self.execution.uses_loopx: + raise ValueError("execution_yardstick_enabled requires a LoopX execution mode") + self.execution_yardstick_enabled = execution_yardstick_enabled from .research_probe import resolve_execution_observation self.execution_observation = resolve_execution_observation(execution_observation) @@ -197,7 +218,13 @@ def _turn_envelope_receipt(self) -> dict: return {**turn_envelope_receipt(explicit=self.execution.turn_envelope, complete=self.execution.complete_turn), **({"native_child_limit": self.execution.native_child_limit} if self.execution.native_child_limit is not None else {}), - **({"context_delivery": "on"} if self.execution.context_delivery != "off" else {})} + **({"context_delivery": "on"} if self.execution.context_delivery != "off" else {}), + **({"compact_direct_read": True} if self.execution.compact_direct_read else {}), + **({"quiet_turn": True} if self.execution.quiet_turn else {}), + **({"epoch_prefetch": True, "epoch_prefetch_configured": True} + if epoch_prefetch_enabled(self.execution.epoch_prefetch_json) + else ({"epoch_prefetch_configured": False} + if self.execution.epoch_prefetch_json is not None else {})),} def _planning_receipt(self) -> dict: return {"native_goal_continue": True} if self.native_goal_continue else {} @@ -210,12 +237,33 @@ def _replan_configuration(self) -> tuple[str, str, int]: return ("replan_after_completed_todos", "--execution-replan-after-todos", self.replan_after_todos) - def _replan_receipt(self) -> dict[str, int | str]: + def _replan_receipt(self) -> dict[str, int | str | bool]: key, _, value = self._replan_configuration() return {key: value, **({"stride_strategy": self.stride_strategy} if self.stride_strategy is not None else {}), **({"planning_horizon_goal": self.planning_horizon_goal} - if self.planning_horizon_goal is not None else {})} + if self.planning_horizon_goal is not None else {}), + **({"yardstick_enabled": self.execution_yardstick_enabled} + if self.execution_yardstick_enabled is not None else {})} + + def _yardstick_args(self) -> list[str]: + if self.execution_yardstick_enabled is None: + return [] + return [ + "--execution-yardstick-enabled" + if self.execution_yardstick_enabled + else "--no-execution-yardstick-enabled" + ] + + async def _apply_warm_start_yardstick(self, environment: BaseEnvironment, *, cwd: str) -> None: + args = self._yardstick_args() + if not args: + return + await self._loopx( + environment, + ["configure-goal", "--goal-id", self.goal_id, *args, "--execute"], + cwd=cwd, + ) @staticmethod def name() -> str: @@ -414,6 +462,7 @@ async def install(self, environment: BaseEnvironment) -> None: if self.execution_observation is not None else {}), **self._turn_envelope_receipt(), **self._planning_receipt(), + **({"official_stop_hook": True} if self.execution.official_stop_hook else {}), **({"provider_request_admission": "on"} if self.provider_request_admission else {}), "home_scope": "trial", "loopx_usage_ping_enabled": False, @@ -496,7 +545,8 @@ async def _registry_exists(self, environment: BaseEnvironment) -> bool: return result.return_code == 0 async def _prepare_phase( - self, environment: BaseEnvironment, instruction: str, *, cwd: str + self, environment: BaseEnvironment, instruction: str, *, cwd: str, verify: bool = True, + verify_explore: bool = True, ) -> None: key, option, expected = self._replan_configuration() stride_args = (["--execution-stride-strategy", self.stride_strategy] @@ -504,6 +554,7 @@ async def _prepare_phase( if self.planning_horizon_goal is not None: stride_args.append("--execution-planning-horizon-goal" if self.planning_horizon_goal else "--no-execution-planning-horizon-goal") + stride_args.extend(self._yardstick_args()) pending = await environment.exec( command=f"test -e {_LOOPX_RUNTIME}/benchmark-pending-turn.json" ) @@ -588,9 +639,12 @@ async def _prepare_phase( if self.execution.task_entry == "seeded-todo": await self._seed_phase(environment, cwd=cwd) - await self._verify_phase_configuration(environment, cwd=cwd) + if verify: + await self._verify_phase_configuration(environment, cwd=cwd, verify_explore=verify_explore) - async def _verify_phase_configuration(self, environment: BaseEnvironment, *, cwd: str) -> None: + async def _verify_phase_configuration( + self, environment: BaseEnvironment, *, cwd: str, verify_explore: bool = True, + ) -> None: """Read the treatment without reconfiguring a restored Goal or its queue.""" key, _, expected = self._replan_configuration() cadence = await self._loopx( @@ -611,6 +665,26 @@ async def _verify_phase_configuration(self, environment: BaseEnvironment, *, cwd raise RuntimeError( f"stride strategy readback mismatch: expected {self.stride_strategy or 'off'}, got {strategy!r}" ) + if self.execution_yardstick_enabled is not None: + actual_yardstick = configured_state.get("execution_profile", {}).get("yardstick_enabled") + if type(actual_yardstick) is not bool or actual_yardstick != self.execution_yardstick_enabled: + raise RuntimeError("execution_yardstick_enabled readback mismatch") + if verify_explore and self.execution_yardstick_enabled is True: + turn_context = await self._loopx( + environment, + ["explore", "turn-context", "--goal-id", self.goal_id, "--agent-id", self.agent_id], + cwd=cwd, + ) + graph_obj = turn_context.get("graph") if isinstance(turn_context.get("graph"), dict) else None + if ( + turn_context.get("graph_enabled") is not True + or graph_obj is None + or not isinstance(graph_obj.get("work_yardstick_capture"), dict) + ): + raise RuntimeError( + "execution_yardstick_enabled requires an active Explore evidence graph " + "with work_yardstick_capture available" + ) def _verify_native_child_configuration(self, configured_state: dict) -> None: if self.execution.native_child_limit is None: @@ -695,6 +769,10 @@ def _worker_env(self, *, cwd: str) -> dict[str, str]: **({"LOOPX_TURN_ENVELOPE": "1"} if self.execution.turn_envelope else {}), "LOOPX_COMPLETE_TURN": "1" if self.execution.complete_turn else "0", "LOOPX_CONTEXT_DELIVERY": self.execution.context_delivery, + "LOOPX_COMPACT_DIRECT_READ": "1" if self.execution.compact_direct_read else "0", + "LOOPX_QUIET_TURN": "1" if self.execution.quiet_turn else "0", + "LOOPX_EPOCH_PREFETCH_JSON": self.execution.epoch_prefetch_json or "", + "LOOPX_OFFICIAL_STOP_HOOK": "1" if self.execution.official_stop_hook else "0", # A trial's explicit None must not inherit a container opt-in. "LOOPX_NATIVE_CHILD_LIMIT": ( str(self.execution.native_child_limit) @@ -831,6 +909,7 @@ def token_delta(key: str) -> int | None: "task_entry": self.execution.task_entry, **self._turn_envelope_receipt(), **self._planning_receipt(), + **({"official_stop_hook": True} if self.execution.official_stop_hook else {}), **({"provider_request_admission": "on"} if self.provider_request_admission else {}), "home_scope": "trial", **self._replan_receipt(), @@ -897,7 +976,7 @@ async def run( if entry["status"] == "blocked": return remaining = int(deadline - time.monotonic()) - reserve = phase_work_reserve(self.execution.mode) + reserve = phase_work_reserve(self.execution.mode, official_stop_hook=self.execution.official_stop_hook) if remaining <= reserve: raise TimeoutError("Task budget exhausted before execution handoff") # Planning, admission and work share one absolute phase clock. @@ -913,11 +992,12 @@ async def run( resume_budget_stop=self._phase_number > 1, ) phase_log = f"/logs/agent/worker-phase-{self._phase_number:03d}.log" + supervisor_timeout = remaining + (30 if self.execution.official_stop_hook else 0) shell = ( "set +e; " # Use the task environment's clock, including remote backends. f"export LOOPX_PHASE_DEADLINE_EPOCH=$(( $(date +%s) + {remaining} )); " - f"timeout --signal=TERM --kill-after=30 {remaining}s " + f"timeout --signal=TERM --kill-after=30 {supervisor_timeout}s " f"{shlex.join(command)} >> {shlex.quote(phase_log)} 2>&1; " "rc=$?; " # Budget exhaustion retains partial artifacts for native scoring. @@ -928,7 +1008,7 @@ async def run( command=shell, env=env, cwd=cwd, - timeout_sec=remaining + 60, + timeout_sec=supervisor_timeout + 60, ) finally: # Remote Harbor backends download logs after run(). Read them now diff --git a/benchmark/runtime/native_hooks.py b/benchmark/runtime/native_hooks.py new file mode 100644 index 0000000000..d9c40c1459 --- /dev/null +++ b/benchmark/runtime/native_hooks.py @@ -0,0 +1,106 @@ +"""Stage and trust only the benchmark's generated native Codex hooks.""" + +from __future__ import annotations + +import inspect +import json +import shlex +import subprocess +import time +from collections.abc import Mapping +from functools import partial +from pathlib import Path +from typing import Any + + +OFFICIAL_STOP_HOOK_REASON = "Do not stop. Continue working on the implementation." + + +def prepare_official_stop_hook(env: dict[str, str], home: Path, *, deadline: float | None = None) -> list[str]: + # Put the entire handler in the declaration so native trust covers the + # command body as well as the path to the hook declaration. + response = shlex.quote(json.dumps({"decision": "block", "reason": OFFICIAL_STOP_HOOK_REASON})) + command = rf"cat >/dev/null && printf '%s\n' {response}" + return prepare_native_hooks(env, home, { + "Stop": [{"hooks": [{"type": "command", "command": command, "timeout": 30}]}], + }, purpose="official-stop", deadline=deadline) + + +def prepare_native_hooks(env: dict[str, str], home: Path, configuration: dict, *, + purpose: str, deadline: float | None = None) -> list[str]: + from loopx.control_plane.turn_driver.codex_stdio import NativeGoalProtocolError, StdioNativeGoalTransport + + content = json.dumps({"hooks": configuration}) + path = home / "hooks.json" + if path.is_symlink() or (path.exists() and path.read_text() != content): + raise ValueError(f"native {purpose} hooks changed within a trial; use a new trial") + if not path.exists(): + path.write_text(content) + path.chmod(0o600) + command = [ + env["CODEX_BIN"], "-c", "features.plugins=false", + "-c", "features.remote_plugin=false", "-c", "features.plugin_sharing=false", + "app-server", "--listen", "stdio://", + ] + if deadline is not None and deadline <= time.monotonic(): + raise subprocess.TimeoutExpired(command, 0) + # The native host owns keys and hashes. Discovery launches no model, and + # discovery-only plugin overrides leave the solver configuration intact. + with (home / f"{purpose}-hooks-stderr.log").open("a") as stderr: + with StdioNativeGoalTransport.spawn( + command, cwd=env["LOOPX_PROJECT"], env=env, stderr=stderr, response_timeout_sec=10, + ) as native: + supports_deadline = "deadline" in inspect.signature(native.request).parameters + if deadline is None: + request = native.request + elif supports_deadline: + request = partial(native.request, deadline=deadline) + else: + def request(method: str, params: Mapping[str, Any]) -> Mapping[str, Any]: + started = time.monotonic() + remaining = deadline - started + if remaining <= 0: + raise subprocess.TimeoutExpired(command, 0) + rpc_timeout = 10.0 + caller_limited = remaining <= rpc_timeout + # Split-pinned product releases expose the 2-arg transport; + # cap per-RPC waiting and translate caller-budget timeouts uniformly. + native.response_timeout_sec = remaining if caller_limited else rpc_timeout + try: + return native.request(method, params) + except NativeGoalProtocolError as exc: + if caller_limited and str(exc) == f"app_server_response_timeout:{method}": + raise subprocess.TimeoutExpired(command, remaining) from exc + raise + + request("initialize", {"clientInfo": {"name": "loopx_context_transport", "version": "0.1.0"}, + "capabilities": {"experimentalApi": True}}) + native.notify("initialized", {}) + listed = request("hooks/list", {"cwds": [env["LOOPX_PROJECT"]]}) + hooks = [hook for entry in listed["data"] for hook in entry["hooks"] + if hook.get("sourcePath") == str(path.resolve())] + # Discovery can reorder handlers. Counts alone cannot rule out + # duplicates, disabled handlers or substitutions. + expected = [{"eventName": event[0].lower() + event[1:], + "handlerType": handler["type"], "command": handler["command"], + "matcher": group.get("matcher"), "timeoutSec": handler.get("timeout"), + "async": handler.get("async", False)} + for event, groups in configuration.items() + for group in groups for handler in group["hooks"]] + mismatch = f"native host did not discover the exact trial {purpose} hooks" + if not expected or len(hooks) != len(expected) or path.read_text() != content: + raise ValueError(mismatch) + entries, keys = [], set() + for hook in hooks: + actual = {field: hook.get(field) for field in expected[0]} + if hook.get("enabled") is not True or type(hook.get("async")) is not bool or actual not in expected: + raise ValueError(mismatch) + expected.remove(actual) + key, digest = hook.get("key"), hook.get("currentHash") + if not isinstance(key, str) or not key or key in keys or not isinstance(digest, str) or not digest: + raise ValueError(f"native host returned no unique {purpose}-hook trust identity") + keys.add(key) + entries.append(f"{json.dumps(key)} = {{ trusted_hash = {json.dumps(digest)} }}") + # Native keys contain dots and paths. Pass the whole table with literal + # keys instead of nesting keys via CLI dot notation. + return ["-c", "hooks.state={" + ",".join(entries) + "}"] diff --git a/benchmark/runtime/scheduler.py b/benchmark/runtime/scheduler.py index 3d6944319f..ec79281d40 100644 --- a/benchmark/runtime/scheduler.py +++ b/benchmark/runtime/scheduler.py @@ -18,9 +18,9 @@ PHASE_WORK_RESERVE_SECONDS = 160 -def phase_work_reserve(mode: str) -> int: - """Heartbeat cleanup must not consume the remaining solver allowance.""" - return 0 if mode == "heartbeat" else PHASE_WORK_RESERVE_SECONDS +def phase_work_reserve(mode: str, *, official_stop_hook: bool = False) -> int: + """Give deadline-driven workers the full phase; bound cleanup separately.""" + return 0 if mode == "heartbeat" or official_stop_hook else PHASE_WORK_RESERVE_SECONDS def read_phase_deadline(raw: bytes) -> int | float: diff --git a/benchmark/runtime/sforge.py b/benchmark/runtime/sforge.py index 6887532256..0112fb0d4a 100644 --- a/benchmark/runtime/sforge.py +++ b/benchmark/runtime/sforge.py @@ -20,7 +20,14 @@ from benchmark.edgebench.feedback import FEEDBACK_MODES from benchmark.edgebench.feedback_hook import FEEDBACK_PAYLOAD -from .codex import DEFAULT_REPLAN_AFTER_TURNS, Execution, codex_settings, native_child_instructions, prepare_codex_home +from .codex import ( + DEFAULT_REPLAN_AFTER_TURNS, + Execution, + codex_settings, + native_child_instructions, + normalize_epoch_prefetch_json, + prepare_codex_home, +) from .codex_offline import CodexOffline, MODEL_CATALOG_REMOTE, stage_portable_python from .codex_readiness import native_readiness_budget from .harbor import ( @@ -46,13 +53,17 @@ def profile_execution(profile, *, task_entry=None, context_delivery=None, turn_envelope=False, complete_turn=False, - validation_command=None, native_child_limit=None): + validation_command=None, native_child_limit=None, + compact_direct_read=False, quiet_turn=False, + epoch_prefetch_json=None): """Resolve the native experiment arm through the shared runtime contract.""" if profile not in PROFILE_MODES: raise ValueError("Unknown benchmark worker profile") return Execution( mode=PROFILE_MODES[profile], task_entry=task_entry, context_delivery=context_delivery, turn_envelope=turn_envelope, complete_turn=complete_turn, native_child_limit=native_child_limit, + compact_direct_read=compact_direct_read, quiet_turn=quiet_turn, + epoch_prefetch_json=normalize_epoch_prefetch_json(epoch_prefetch_json), validation_command=() if validation_command is None else validation_command, ) @@ -130,13 +141,19 @@ def __init__(self, config, *, profile: str, cwd: str, checkpoint_request_path: str | None = None, checkpoint_request: bytes | None = None, warm_start=None, research_sidecar: bool = False, - native_result_scope: dict | None = None, complete_turn: bool = False): + native_result_scope: dict | None = None, complete_turn: bool = False, + compact_direct_read: bool = False, quiet_turn: bool = False, + epoch_prefetch_json: str | dict | None = None, + execution_yardstick_enabled: bool | None = None): super().__init__(config) self.execution = profile_execution( profile, task_entry=task_entry, context_delivery=context_delivery, turn_envelope=turn_envelope, complete_turn=complete_turn, validation_command=validation_command, native_child_limit=native_child_limit, + compact_direct_read=compact_direct_read, + quiet_turn=quiet_turn, + epoch_prefetch_json=epoch_prefetch_json, ) self.turn_envelope = self.execution.turn_envelope self.context_delivery = self.execution.context_delivery @@ -207,6 +224,12 @@ def __init__(self, config, *, profile: str, cwd: str, DEFAULT_PLANNING_HORIZON_GOAL if planning_horizon_goal is None and self.execution.uses_loopx else planning_horizon_goal ) + if execution_yardstick_enabled is not None: + if type(execution_yardstick_enabled) is not bool: + raise ValueError("execution_yardstick_enabled must be a boolean") + if not self.execution.uses_loopx: + raise ValueError("execution_yardstick_enabled requires a heartbeat profile or turn-resume") + self.execution_yardstick_enabled = execution_yardstick_enabled self.stride_strategy = stride_strategy self.checkpoint_request_path = None self.checkpoint_request = checkpoint_request @@ -423,6 +446,12 @@ def _install_worker(self, backend, handle, log_dir, logger): task_entry=self.task_entry, turn_envelope=self.turn_envelope, **({"complete_turn": True} if self.execution.complete_turn else {}), + **({"compact_direct_read": True} if self.execution.compact_direct_read else {}), + **({"quiet_turn": True} if self.execution.quiet_turn else {}), + **({"epoch_prefetch_json": self.execution.epoch_prefetch_json} + if self.execution.epoch_prefetch_json is not None else {}), + **({"execution_yardstick_enabled": self.execution_yardstick_enabled} + if self.execution_yardstick_enabled is not None else {}), context_delivery=self.context_delivery, **({"execution_observation": self.execution_observation} if self.execution_observation is not None else {}), @@ -590,20 +619,38 @@ def format_run_cmd(self, prompt_path, *, model=None, cwd="", internet=True, resu # The sealed Goal, task graph, review counters and strategy # are the continuing state. Do not bootstrap, seed another # task, or reset an existing configuration during restore. - if self.native_child_limit is not None: - asyncio.run(self.runtime._verify_phase_configuration(self.environment, cwd=self.cwd)) - asyncio.run(self.runtime._write_task_document(self.environment, result.stdout)) - if self.native_child_limit is None: + if self.execution_yardstick_enabled is not None: + if self.native_child_limit is not None: + retained = asyncio.run(self.runtime._loopx( + self.environment, ["configure-goal", "--goal-id", self.runtime.goal_id], cwd=self.cwd, + )) + self.runtime._verify_native_child_configuration( + retained.get("after") or retained.get("before") or {} + ) + asyncio.run(self.runtime._apply_warm_start_yardstick(self.environment, cwd=self.cwd)) + asyncio.run(self.runtime._write_task_document(self.environment, result.stdout)) asyncio.run(self.runtime._verify_phase_configuration(self.environment, cwd=self.cwd)) + else: + if self.native_child_limit is not None: + asyncio.run(self.runtime._verify_phase_configuration(self.environment, cwd=self.cwd)) + asyncio.run(self.runtime._write_task_document(self.environment, result.stdout)) + if self.native_child_limit is None: + asyncio.run(self.runtime._verify_phase_configuration(self.environment, cwd=self.cwd)) else: - asyncio.run(self.runtime._prepare_phase(self.environment, result.stdout, cwd=self.cwd)) - if self.profile == "heartbeat-explore" and self.warm_start is None: - observed = asyncio.run(self.runtime._loopx(self.environment, [ - "configure-goal", "--goal-id", self.runtime.goal_id, - "--explore-graph-enabled", "--explore-harness-enabled", - "--explore-harness-profile", "adaptive-resilient", "--execute", - ], cwd=self.cwd)) - (self.log_dir / "explore-activation.json").write_text(json.dumps(observed)) + is_explore_cold = self.profile == "heartbeat-explore" + asyncio.run(self.runtime._prepare_phase( + self.environment, result.stdout, cwd=self.cwd, verify=True, verify_explore=not is_explore_cold, + )) + if is_explore_cold: + observed = asyncio.run(self.runtime._loopx(self.environment, [ + "configure-goal", "--goal-id", self.runtime.goal_id, + "--explore-graph-enabled", "--explore-harness-enabled", + "--explore-harness-profile", "adaptive-resilient", "--execute", + ], cwd=self.cwd)) + (self.log_dir / "explore-activation.json").write_text(json.dumps(observed)) + asyncio.run(self.runtime._verify_phase_configuration( + self.environment, cwd=self.cwd, verify_explore=True, + )) else: asyncio.run(self.runtime._write_task_document(self.environment, result.stdout)) if self.warm_start is not None: diff --git a/benchmark/runtime/worker.py b/benchmark/runtime/worker.py index 8b234e193b..19fa05e93e 100644 --- a/benchmark/runtime/worker.py +++ b/benchmark/runtime/worker.py @@ -4,6 +4,7 @@ from __future__ import annotations import json +import math import os import shutil import signal @@ -16,6 +17,8 @@ from benchmark.runtime.codex import ( Execution, + epoch_prefetch_enabled, + explicit_context_opt_ins, explicit_turn_display, prepare_codex_home, process_environment, @@ -352,6 +355,9 @@ def turn_command( if execution.timeout_seconds is not None else []), "--validation-command-json", json.dumps(execution.validation_command), + *(["--epoch-prefetch-json", execution.epoch_prefetch_json] + if execution.epoch_prefetch_json is not None else []), + *(["--quiet-turn"] if execution.quiet_turn else []), "--available-capability", "shell", "--available-capability", @@ -476,7 +482,7 @@ def run_round(suffix, timeout_sec): receipt["native_goal"] = compact_native_goal_receipt(observed[-1]) -def native_command(env, execution, stage, wake, session_wake): +def native_command(env, execution, stage, wake, session_wake, *, native_hook_args=()): if session_wake is None: # Preserve the baseline/Goal-planning entrypoint and its transport inputs. return [ @@ -484,6 +490,7 @@ def native_command(env, execution, stage, wake, session_wake): "--sandbox", execution.sandbox, "--cd", env["LOOPX_PROJECT"], *(["-c", "features.goals=false", "--output-schema", str(wake / "planning-schema.json"), "--output-last-message", str(wake / "planning-result.json")] if stage == "plan" else []), + *native_hook_args, "-", ] from loopx.control_plane.turn_driver.codex_cli import _codex_command @@ -584,7 +591,11 @@ def _qualify_short_envelope(env: dict[str, str], receipt: dict) -> bool: def run_once(env: dict[str, str]) -> dict: if env.get("LOOPX_CONTEXT_DELIVERY", "off") not in {"off", "on"}: raise ValueError("LOOPX_CONTEXT_DELIVERY supports only off or on") + stop_hook = env.get("LOOPX_OFFICIAL_STOP_HOOK", "0") + if stop_hook not in {"0", "1"}: + raise ValueError("LOOPX_OFFICIAL_STOP_HOOK must be 0 or 1") display = explicit_turn_display(env) + context_opt_ins = explicit_context_opt_ins(env) execution = Execution( mode=env.get("LOOPX_EXECUTION_MODE", "heartbeat"), context=env.get("LOOPX_ITERATION_CONTEXT"), @@ -598,6 +609,8 @@ def run_once(env: dict[str, str]) -> dict: native_child_limit=(int(env["LOOPX_NATIVE_CHILD_LIMIT"]) if env.get("LOOPX_NATIVE_CHILD_LIMIT") else None), complete_turn=display.complete_turn, + **context_opt_ins, + official_stop_hook=stop_hook == "1", ) request_admission = False if env.get("LOOPX_PROVIDER_REQUEST_ADMISSION", "off") != "off": @@ -645,6 +658,13 @@ def run_once(env: dict[str, str]) -> dict: if observation_producer is not None else {}), **turn_envelope_receipt(explicit=False, complete=execution.complete_turn), **({"context_delivery": "on"} if execution.context_delivery != "off" else {}), + **({"compact_direct_read": True} if execution.compact_direct_read else {}), + **({"quiet_turn": True} if execution.quiet_turn else {}), + **({"epoch_prefetch": True, "epoch_prefetch_configured": True} + if epoch_prefetch_enabled(execution.epoch_prefetch_json) + else ({"epoch_prefetch_configured": False} + if execution.epoch_prefetch_json is not None else {})), + **({"official_stop_hook": True} if execution.official_stop_hook else {}), **({"native_child_limit": execution.native_child_limit} if execution.native_child_limit is not None else {}), **({"provider_request_admission": "on"} if request_admission else {}), @@ -660,6 +680,11 @@ def run_once(env: dict[str, str]) -> dict: phase_deadline_epoch=env.get("LOOPX_PHASE_DEADLINE_EPOCH")) session_wake = None phase_work_deadline = None + official_worker_deadline = ( + time.time() + execution.timeout_seconds + if execution.official_stop_hook and execution.timeout_seconds is not None + else None + ) wake_context = ExitStack() pending_path = ( Path(env.get("LOOPX_RUNTIME_ROOT", str(home))) / "benchmark-pending-turn.json" @@ -670,16 +695,16 @@ def run_once(env: dict[str, str]) -> dict: if handoff is not None: receipt["recovery_handoff_sha256"] = handoff["sha256"] if stage == "execute" and env.get("LOOPX_PHASE_DEADLINE_EPOCH"): - remaining = float(env["LOOPX_PHASE_DEADLINE_EPOCH"]) - time.time() - # Heartbeat work uses the whole remaining phase. Cleanup is bounded - # by its existing host transport, not subtracted from each wake. - # Native Goal and managed-turn transports retain their own reserve. - reserve = phase_work_reserve(execution.mode) + phase_deadline = float(env["LOOPX_PHASE_DEADLINE_EPOCH"]) + if execution.official_stop_hook and not math.isfinite(phase_deadline): + raise ValueError("official_stop_hook requires a finite phase deadline") + remaining = phase_deadline - time.time() + reserve = phase_work_reserve(execution.mode, official_stop_hook=execution.official_stop_hook) if remaining <= reserve: receipt.update(ok=True, budget_exhausted=True, host_invoked=False) return receipt - if execution.mode == "heartbeat": - phase_work_deadline = float(env["LOOPX_PHASE_DEADLINE_EPOCH"]) + if execution.mode == "heartbeat" or execution.official_stop_hook: + phase_work_deadline = phase_deadline - reserve execution = replace( execution, timeout_seconds=(remaining - reserve if execution.timeout_seconds is None else min(execution.timeout_seconds, remaining - reserve)) @@ -701,6 +726,24 @@ def run_once(env: dict[str, str]) -> dict: Path(env["LOOPX_MODEL_CATALOG"]) if env.get("LOOPX_MODEL_CATALOG") else None ), ) + native_hook_args = () + if execution.official_stop_hook: + from benchmark.runtime.native_hooks import prepare_official_stop_hook + + worker_remaining = ( + None if official_worker_deadline is None else official_worker_deadline - time.time() + ) + remaining, phase_limited = _phase_timeout(worker_remaining, phase_work_deadline) + try: + native_hook_args = prepare_official_stop_hook( + env, home, deadline=None if remaining is None else time.monotonic() + remaining + ) + except subprocess.TimeoutExpired: + receipt["host_invoked"] = False + if phase_limited: + receipt["budget_exhausted"] = True + raise + receipt["official_stop_hook_verified"] = True if execution.mode == "heartbeat": # Checkpoint capture needs the LoopX control plane, which only # heartbeat workers stage; other modes must not import it. @@ -710,14 +753,23 @@ def run_once(env: dict[str, str]) -> dict: else: checkpoint_wake = _InertCheckpointWake() if execution.context_delivery != "off": - from benchmark.runtime.context_delivery import prepare_context_delivery + from benchmark.runtime.context_delivery import ContextOptInConfigurationError, prepare_context_delivery + explicit_h1_opt_in = ( + execution.compact_direct_read + or execution.quiet_turn + or execution.epoch_prefetch_json is not None + ) try: context_env = dict(env) prepare_context_delivery(context_env, home) env.update(context_env) receipt["context_transport"] = {"available": True} + except ContextOptInConfigurationError: + raise except Exception as exc: + if explicit_h1_opt_in: + raise # Optional presentation cannot block an otherwise admitted # trial. Unavailable native hooks keep ordinary full IO. env.pop("LOOPX_CODEX_CONTEXT_DIR", None) @@ -767,6 +819,8 @@ def run_once(env: dict[str, str]) -> dict: if phase_work_deadline is not None and time.time() >= phase_work_deadline: receipt.update(ok=True, budget_exhausted=True, host_invoked=False) return receipt + if official_worker_deadline is not None and time.time() >= official_worker_deadline: + raise subprocess.TimeoutExpired(env["CODEX_BIN"], execution.timeout_seconds) with stderr_path.open("w") as stderr: if execution.native_goal and stage == "execute": run_native_goal(env, execution, body, receipt, stderr, @@ -790,16 +844,24 @@ def run_once(env: dict[str, str]) -> dict: recover_instance=pending["turn_instance_id"] != turn_id, ) if execution.mode == "turn" and stage == "execute" - else native_command(env, execution, stage, wake, session_wake) + else native_command( + env, execution, stage, wake, session_wake, native_hook_args=native_hook_args + ) ) with stdout_path.open("w") as stdout: allowance = 150 if execution.mode == "turn" and stage == "execute" else 0 if stage == "plan": # Planning and execution consume the same phase budget. - timeout = max(0, float(env["LOOPX_PHASE_DEADLINE_EPOCH"]) - time.time()) + phase_end = env.get("LOOPX_PHASE_DEADLINE_EPOCH") + timeout = (max(0, float(phase_end) - time.time()) + if phase_end else execution.timeout_seconds) else: - timeout = (None if execution.timeout_seconds is None - else execution.timeout_seconds + allowance) + timeout = execution.timeout_seconds + if execution.official_stop_hook: + timeout = (None if official_worker_deadline is None + else max(0, official_worker_deadline - time.time())) + elif timeout is not None: + timeout += allowance if checkpoint_wake.listener is not None: timeout, phase_limited = _phase_timeout(timeout, phase_work_deadline) receipt["return_code"] = checkpoint_wake.run( diff --git a/benchmark/tests/test_shared_codex_runtime.py b/benchmark/tests/test_shared_codex_runtime.py index cdca15e337..b270a36399 100644 --- a/benchmark/tests/test_shared_codex_runtime.py +++ b/benchmark/tests/test_shared_codex_runtime.py @@ -49,6 +49,8 @@ def settings(tmp_path, **changes): {"mode": "turn", "validation_command": "true"}, {"mode": "turn", "validation_command": {"command": "true"}}, {"sandbox": "unrecognised"}, + {"mode": "plain", "official_stop_hook": "true"}, + {"mode": "native-goal", "official_stop_hook": True}, ], ) def test_invalid_execution_rejected_before_host(kwargs): @@ -713,6 +715,273 @@ def test_baseline_and_treatment_use_same_harbor_entry(tmp_path): assert agent.replan_after_turns == (6 if agent.execution.uses_loopx else None) +def test_harbor_owns_official_stop_hook_opt_in(tmp_path, monkeypatch): + pytest.importorskip("harbor") + from benchmark.runtime.harbor import BenchmarkCodex + from benchmark.runtime.scheduler import phase_work_reserve + + monkeypatch.setenv("LOOPX_OFFICIAL_STOP_HOOK", "1") + for enabled in (False, True): + agent = BenchmarkCodex(logs_dir=tmp_path, model_name="openai/fixture", + execution_mode="plain", **({"official_stop_hook": True} if enabled else {})) + assert agent._worker_env(cwd="/workspace")["LOOPX_OFFICIAL_STOP_HOOK"] == str(int(enabled)) + reserve = phase_work_reserve(agent.execution.mode, official_stop_hook=agent.execution.official_stop_hook) + assert (reserve == 0) is enabled + + +@pytest.mark.parametrize("blocked_method", ["initialize", "hooks/list"]) +def test_official_stop_discovery_spends_the_same_phase_clock(tmp_path, blocked_method): + env = worker_env(tmp_path) + binary = Path(env["CODEX_BIN"]) + binary.write_text(f"#!{sys.executable}\n" + """ +import json +import os +from pathlib import Path +import sys +import time + +assert "app-server" in sys.argv +Path("discovery.pid").write_text(str(os.getpid())) +for line in sys.stdin: + request = json.loads(line) + if "id" not in request: + continue + method = request["method"] + Path("last-method").write_text(method) + if method == os.environ["BLOCKED_METHOD"]: + time.sleep(60) + time.sleep(.4) + print(json.dumps({"id": request["id"], "result": {}}), flush=True) +""") + env.update(LOOPX_OFFICIAL_STOP_HOOK="1", BLOCKED_METHOD=blocked_method) + started = time.time() + env["LOOPX_PHASE_DEADLINE_EPOCH"] = str(started + 2) + result = run_once(env) + assert time.time() - started < 5 + assert (tmp_path / "last-method").read_text() == blocked_method + assert result["budget_exhausted"] and result["timed_out"] + assert result["host_invoked"] is False and "official_stop_hook_verified" not in result + assert not (tmp_path / "home" / "sessions").exists() + with pytest.raises(ProcessLookupError): + os.kill(int((tmp_path / "discovery.pid").read_text()), 0) + + +def test_official_stop_discovery_preserves_a_protocol_rejection(tmp_path): + from loopx.control_plane.turn_driver.codex_stdio import NativeGoalProtocolError + + env = worker_env(tmp_path) + binary = Path(env["CODEX_BIN"]) + binary.write_text(f"#!{sys.executable}\n" + """ +import json +import sys + +assert "app-server" in sys.argv +request = json.loads(sys.stdin.readline()) +assert request["method"] == "initialize" +print(json.dumps({"id": request["id"], "error": {"code": -32603, "message": "rejected"}}), flush=True) +""") + env.update(LOOPX_OFFICIAL_STOP_HOOK="1", LOOPX_PHASE_DEADLINE_EPOCH=str(time.time() + 4)) + with pytest.raises(NativeGoalProtocolError, match="app_server_request_failed:initialize"): + run_once(env) + receipt, = (tmp_path / "logs" / "wakes").glob("*/receipt.json") + result = json.loads(receipt.read_text()) + assert not result["timed_out"] and "budget_exhausted" not in result + assert not (tmp_path / "home" / "sessions").exists() + + +@pytest.mark.parametrize("case", ["ok", "timeout_initialize", "timeout_hooks_list", "protocol_error", "expired"]) +def test_official_stop_hook_supports_split_pinned_two_arg_transport(tmp_path, monkeypatch, case): + from collections.abc import Mapping + from loopx.control_plane.turn_driver import codex_stdio + from loopx.control_plane.turn_driver.codex_stdio import NativeGoalProtocolError, StdioNativeGoalTransport + + class LegacyTwoArgTransport(StdioNativeGoalTransport): + def request(self, method: str, params: Mapping[str, object]) -> Mapping[str, object]: + request_id = self._next_request_id + self._next_request_id += 1 + self._send({"id": request_id, "method": method, "params": dict(params)}) + deadline = time.monotonic() + self.response_timeout_sec + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise NativeGoalProtocolError(f"app_server_response_timeout:{method}") + message = self._next_message(timeout_sec=remaining) + if message is None: + if self.process.poll() is not None: + raise NativeGoalProtocolError("app_server_exited_before_response") + continue + if message.get("id") == request_id: + if message.get("error") is not None: + raise NativeGoalProtocolError(f"app_server_request_failed:{method}") + result = message.get("result") + return result if isinstance(result, Mapping) else {} + if message.get("method"): + self._pending_events.append(message) + + monkeypatch.setattr(codex_stdio, "StdioNativeGoalTransport", LegacyTwoArgTransport) + env = worker_env(tmp_path) + binary = Path(env["CODEX_BIN"]) + binary.write_text(f"#!{sys.executable}\n" + """ +import json, os, pathlib, sys, time + +home = pathlib.Path(os.environ["CODEX_HOME"]) +if "app-server" in sys.argv: + pathlib.Path("spawned-discovery").write_text("1") + for line in sys.stdin: + req = json.loads(line) + if "id" not in req: + continue + method = req["method"] + pathlib.Path("last-method").write_text(method) + case = os.environ["SPLIT_CASE"] + if case == "protocol_error" and method == "initialize": + print(json.dumps({"id": req["id"], "error": {"code": -32603, "message": "rejected"}}), flush=True) + continue + if case == f"timeout_{method.replace('/', '_')}": + time.sleep(60) + if method == "hooks/list": + hook_path = str((home / "hooks.json").resolve()) + stop = json.loads((home / "hooks.json").read_text())["hooks"]["Stop"][0]["hooks"][0] + print(json.dumps({"id": req["id"], "result": {"data": [{"hooks": [{ + "sourcePath": hook_path, "eventName": "stop", "handlerType": stop["type"], + "command": stop["command"], "matcher": None, "timeoutSec": stop["timeout"], + "async": False, "enabled": True, "key": "stop-0", "currentHash": "hash-0", + }]}]}}), flush=True) + else: + print(json.dumps({"id": req["id"], "result": {}}), flush=True) +else: + sessions = home / "sessions" + sessions.mkdir(exist_ok=True) + (sessions / "session-0.jsonl").write_text("{}\\n") + print(json.dumps({"argv": sys.argv[1:]})) +""") + env.update(LOOPX_OFFICIAL_STOP_HOOK="1", SPLIT_CASE=case) + started = time.time() + env["LOOPX_PHASE_DEADLINE_EPOCH"] = str(started + 2) + if case == "protocol_error": + with pytest.raises(NativeGoalProtocolError, match="app_server_request_failed:initialize"): + run_once(env) + return + if case == "expired": + from benchmark.runtime.native_hooks import prepare_official_stop_hook + home = Path(env["LOOPX_CODEX_HOME"]) + home.mkdir(parents=True, exist_ok=True) + with pytest.raises(subprocess.TimeoutExpired): + prepare_official_stop_hook(env, home, deadline=time.monotonic() - 1) + assert not (tmp_path / "spawned-discovery").exists() + return + result = run_once(env) + if case == "ok": + assert result["ok"] and result["official_stop_hook_verified"] is True + assert result["return_code"] == 0 and "hooks.state=" in ( + tmp_path / "logs" / "wakes" / result["turn_id"] / "stdout.jsonl" + ).read_text() + return + assert time.time() - started < 5 + assert result["budget_exhausted"] and result["timed_out"] and result["host_invoked"] is False + assert (tmp_path / "last-method").read_text() == ( + "initialize" if case == "timeout_initialize" else "hooks/list" + ) + + +@pytest.mark.skipif(not os.environ.get("LOOPX_NATIVE_CHECKPOINT_BIN"), + reason="Explicit native Codex binary required; inference uses loopback only") +@pytest.mark.parametrize("enabled", [False, True]) +def test_official_stop_hook_continues_one_real_native_session_until_timeout(tmp_path, enabled): + from benchmark.runtime.native_hooks import OFFICIAL_STOP_HOOK_REASON + from tests.control_plane.codex_checkpoint_fixture import local_inference_provider + + task = tmp_path / "task.md" + task.write_text("Synthetic task. Propose an implementation.\n") + temporary = tmp_path / "temporary" + temporary.mkdir() + env = {key: value for key, value in os.environ.items() + if key in {"PATH", "USER", "LOGNAME", "SHELL", "LANG", "LC_ALL", "SYSTEMROOT"}} + env.update(HOME=str(tmp_path), TMPDIR=str(temporary), + LOOPX_PROJECT=str(tmp_path), LOOPX_TASK_DOC=str(task), + LOOPX_CODEX_HOME=str(tmp_path / "codex-home"), + LOOPX_WAKE_LOG_DIR=str(tmp_path / "logs" / "wakes"), + LOOPX_EXECUTION_MODE="plain", LOOPX_OFFICIAL_STOP_HOOK=str(int(enabled)), + LOOPX_CODEX_TURN_TIMEOUT_SEC="10", + CODEX_BIN=os.environ["LOOPX_NATIVE_CHECKPOINT_BIN"], + MODEL_NAME="fixture", REASONING_EFFORT="high", OPENAI_API_KEY="synthetic-local") + + def respond(request, number, message): + if number >= 2: + # Leave one continued provider request in flight at the runner deadline. + time.sleep(11) + return message + + with local_inference_provider(response_builder=respond) as (url, calls, requests): + receipt = run_once(env | {"OPENAI_BASE_URL": url}) + assert len(list((tmp_path / "logs" / "sessions").rglob("*.jsonl"))) == 1 + assert receipt["timed_out"] is enabled + assert receipt["ok"] is not enabled + assert (tmp_path / "codex-home" / "hooks.json").exists() is enabled + if enabled: + assert receipt["official_stop_hook_verified"] is True + assert len(calls) == 2 + assert OFFICIAL_STOP_HOOK_REASON in json.dumps(requests[1]["input"]) + else: + assert len(calls) == 1 + assert "official_stop_hook" not in receipt + + +@pytest.mark.skipif(not os.environ.get("LOOPX_NATIVE_CHECKPOINT_BIN"), + reason="Explicit native Codex binary required; inference uses loopback only") +@pytest.mark.skipif(os.name != "posix", reason="Exercises POSIX task-controller cancellation") +def test_official_stop_hook_without_clock_retains_task_controller_cancellation(tmp_path): + from threading import Event + + from benchmark.runtime.native_hooks import OFFICIAL_STOP_HOOK_REASON + from tests.control_plane.codex_checkpoint_fixture import local_inference_provider + + task = tmp_path / "task.md" + task.write_text("Synthetic task. Propose an implementation.\n") + temporary = tmp_path / "temporary" + temporary.mkdir() + env = {key: value for key, value in os.environ.items() + if key in {"PATH", "USER", "LOGNAME", "SHELL", "LANG", "LC_ALL", "SYSTEMROOT"}} + env.update(HOME=str(tmp_path), TMPDIR=str(temporary), + PYTHONPATH=str(Path(__file__).resolve().parents[2]), + LOOPX_PROJECT=str(tmp_path), LOOPX_TASK_DOC=str(task), + LOOPX_CODEX_HOME=str(tmp_path / "codex-home"), + LOOPX_WAKE_LOG_DIR=str(tmp_path / "logs" / "wakes"), + LOOPX_EXECUTION_MODE="plain", LOOPX_OFFICIAL_STOP_HOOK="1", + CODEX_BIN=os.environ["LOOPX_NATIVE_CHECKPOINT_BIN"], + MODEL_NAME="fixture", REASONING_EFFORT="high", OPENAI_API_KEY="synthetic-local") + continued, release = Event(), Event() + + def respond(request, number, message): + if number == 2: + continued.set() + release.wait(20) + return message + + with local_inference_provider(response_builder=respond) as (url, calls, requests): + process = subprocess.Popen([sys.executable, "-m", "benchmark.runtime.worker"], + cwd=tmp_path, env=env | {"OPENAI_BASE_URL": url}, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + try: + assert continued.wait(20), "Native Stop hook did not continue the same conversation" + # The task's final-submission controller may terminate its worker; + # no independent worker/phase deadline is needed for that boundary. + process.terminate() + process.communicate(timeout=10) + finally: + release.set() + if process.poll() is None: + process.kill() + process.communicate(timeout=10) + receipt, = (tmp_path / "logs" / "wakes").glob("*/receipt.json") + result = json.loads(receipt.read_text()) + assert result["official_stop_hook_verified"] is True + assert result["timed_out"] is False and result["ok"] is False + assert len(calls) == 2 + assert OFFICIAL_STOP_HOOK_REASON in json.dumps(requests[1]["input"]) + assert len(list((tmp_path / "logs" / "sessions").rglob("*.jsonl"))) == 1 + + @pytest.mark.parametrize("option,mode,provider_env", [ ("on", "heartbeat", {}), (1, "heartbeat", {}), @@ -1572,3 +1841,537 @@ def request(method, params): def test_context_benchmark_setting_rejects_broad_or_other_host_activation(value): with pytest.raises(ValueError, match="context_delivery"): Execution(context_delivery=value) + + +def test_h1_opt_in_execution_guardrails_and_codex_settings_parity(tmp_path): + from benchmark.runtime.codex import codex_settings + + default_exec = Execution() + assert default_exec.compact_direct_read is False + assert default_exec.quiet_turn is False + assert default_exec.epoch_prefetch_json is None + + opt_in_exec = Execution( + mode="heartbeat", + context_delivery="on", + compact_direct_read=True, + quiet_turn=True, + epoch_prefetch_json='{"b": 2, "a": 1}', + ) + assert opt_in_exec.epoch_prefetch_json == '{"a":1,"b":2}' + base_cfg = codex_settings(execution=default_exec, workspace=tmp_path, model="fixture", effort="low", + base_url="", wire_api="responses") + opt_cfg = codex_settings(execution=opt_in_exec, workspace=tmp_path, model="fixture", effort="low", + base_url="", wire_api="responses") + # WarmStart seals restore-config.toml digest; opt-ins never mutate config.toml. + assert base_cfg == opt_cfg + + for kwargs in ( + {"mode": "plain", "compact_direct_read": True}, + {"mode": "heartbeat", "context_delivery": "off", "compact_direct_read": True}, + {"mode": "heartbeat", "context_delivery": "off", "quiet_turn": True}, + {"mode": "heartbeat", "context_delivery": "off", "epoch_prefetch_json": '{"enabled":true}'}, + {"mode": "native-goal", "quiet_turn": True}, + {"mode": "loopx-goal", "epoch_prefetch_json": '{"enabled":true}'}, + {"mode": "turn", "validation_command": ("true",), "epoch_prefetch_json": "[1,2]"}, + {"mode": "heartbeat", "compact_direct_read": "1"}, + {"mode": "heartbeat", "quiet_turn": 1}, + ): + with pytest.raises(ValueError): + Execution(**kwargs) + + +def test_prepare_context_delivery_opt_ins_default_off_split_pin_and_hooks_json(tmp_path, monkeypatch): + from benchmark.runtime.context_delivery import ContextOptInConfigurationError, prepare_context_delivery + from loopx.control_plane.turn_driver import codex_context + from loopx.control_plane.turn_driver.codex_stdio import StdioNativeGoalTransport + + captured_calls = [] + real_config = codex_context.codex_context_configuration + + @contextmanager + def fake_discovery(argv, **kwargs): + def request(method, params): + if method == "initialize": + return {} + assert method == "hooks/list" + path = Path(kwargs["env"]["LOOPX_CODEX_HOME"]) / "hooks.json" if "LOOPX_CODEX_HOME" in kwargs.get("env", {}) else home_ref["path"] + configured = json.loads(path.read_text())["hooks"] + return {"data": [{"hooks": [ + {"sourcePath": str(path.resolve()), "eventName": event[0].lower() + event[1:], + "handlerType": h["type"], "command": h["command"], "timeoutSec": h["timeout"], + "matcher": g.get("matcher"), "async": False, "enabled": True, + "key": f"{event}-{i}", "currentHash": f"h-{event}-{i}"} + for event, groups in configured.items() for g in groups for i, h in enumerate(g["hooks"]) + ]}]} + yield SimpleNamespace(request=request, notify=lambda *args: None) + + monkeypatch.setattr(StdioNativeGoalTransport, "spawn", fake_discovery) + + # Simulate split-pinned origin/main codex_context_configuration lacking new kwargs: + # default-off must succeed without passing any new kwargs. + def legacy_config(directory, *, goal_id, agent_id, cli_argv, scenario, session_root=False, + inherit_machine=False, progressive_enabled=True): + captured_calls.append("legacy") + return real_config(directory, goal_id=goal_id, agent_id=agent_id, cli_argv=cli_argv, + scenario=scenario, session_root=session_root, + inherit_machine=inherit_machine, progressive_enabled=progressive_enabled) + + monkeypatch.setattr(codex_context, "codex_context_configuration", legacy_config) + home_off = tmp_path / "home-off" + home_off.mkdir() + home_ref = {"path": home_off / "hooks.json"} + env_off = {"LOOPX_CLI": "loopx", "LOOPX_GOAL_ID": "g", "LOOPX_AGENT_ID": "a", + "CODEX_BIN": "codex", "LOOPX_PROJECT": str(tmp_path)} + prepare_context_delivery(env_off, home_off) + assert captured_calls == ["legacy"] + off_hooks = (home_off / "hooks.json").read_text() + assert "--compact-direct-read" not in off_hooks + assert "--quiet-turn" not in off_hooks + assert "--epoch-prefetch-json" not in off_hooks + + # Explicit H1 opt-in fails closed against legacy signature lacking support. + home_fail = tmp_path / "home-fail" + home_fail.mkdir() + with pytest.raises(ContextOptInConfigurationError, match="compact_direct_read"): + prepare_context_delivery({**env_off, "LOOPX_COMPACT_DIRECT_READ": "1"}, home_fail) + + # Restore real codex_context_configuration -> verifies all 3 opt-in flags reach hooks.json. + monkeypatch.setattr(codex_context, "codex_context_configuration", real_config) + home_on = tmp_path / "home-on" + home_on.mkdir() + home_ref["path"] = home_on / "hooks.json" + env_on = { + **env_off, + "LOOPX_COMPACT_DIRECT_READ": "1", + "LOOPX_QUIET_TURN": "1", + "LOOPX_EPOCH_PREFETCH_JSON": '{"prefetch_command": ["git", "status", "--short"], "enabled": true}', + } + prepare_context_delivery(env_on, home_on) + hooks_json = json.loads((home_on / "hooks.json").read_text())["hooks"] + start_cmd = hooks_json["SessionStart"][0]["hooks"][0]["command"] + assert "--compact-direct-read" in start_cmd + assert "--quiet-turn" in start_cmd + assert "--epoch-prefetch-json" in start_cmd + assert '{"enabled":true,"prefetch_command":["git","status","--short"]}' in start_cmd + + +def test_worker_turn_command_and_run_once_forward_h1_opt_ins_default_off(tmp_path, monkeypatch): + from benchmark.tests.test_resume_sessions import resume_env + from loopx.control_plane.turn_driver.codex_stdio import StdioNativeGoalTransport + + env_turn = {"LOOPX_CLI": "loopx", "LOOPX_REGISTRY": "/r", "LOOPX_RUNTIME_ROOT": "/rt", + "LOOPX_PROJECT": "/p", "LOOPX_GOAL_ID": "g", "LOOPX_AGENT_ID": "a", + "REASONING_EFFORT": "low", "CODEX_BIN": "codex", "MODEL_NAME": "m"} + cmd_off = turn_command(env_turn, Execution(mode="turn", validation_command=("true",)), "w1") + assert "--quiet-turn" not in cmd_off + assert "--epoch-prefetch-json" not in cmd_off + + cmd_on = turn_command( + env_turn, + Execution(mode="turn", validation_command=("true",), quiet_turn=True, + epoch_prefetch_json={"enabled": True, "timeout_ms": 500}), + "w2", + ) + assert "--quiet-turn" in cmd_on + assert cmd_on[cmd_on.index("--epoch-prefetch-json") + 1] == '{"enabled":true,"timeout_ms":500}' + + # Real run_once(heartbeat) end-to-end verification (default-off vs opt-in hooks.json + receipt). + @contextmanager + def fake_spawn(argv, **kwargs): + home_p = Path(kwargs["env"]["LOOPX_CODEX_HOME"]) + def req(method, params): + if method == "initialize": + return {} + path = home_p / "hooks.json" + configured = json.loads(path.read_text())["hooks"] + return {"data": [{"hooks": [ + {"sourcePath": str(path.resolve()), "eventName": e[0].lower() + e[1:], + "handlerType": h["type"], "command": h["command"], "timeoutSec": h["timeout"], + "matcher": g.get("matcher"), "async": False, "enabled": True, + "key": f"{e}-{i}", "currentHash": f"h-{e}-{i}"} + for e, groups in configured.items() for g in groups for i, h in enumerate(g["hooks"]) + ]}]} + yield SimpleNamespace(request=req, notify=lambda *args: None) + + monkeypatch.setattr(StdioNativeGoalTransport, "spawn", fake_spawn) + monkeypatch.setattr("benchmark.runtime.worker.heartbeat_body", lambda *a, **kw: "Task body.") + + off_tmp = tmp_path / "off" + off_tmp.mkdir() + e_off = resume_env(off_tmp, monkeypatch) + e_off["LOOPX_CONTEXT_DELIVERY"] = "on" + res_off = run_once(e_off) + assert res_off["ok"] + assert "compact_direct_read" not in res_off + assert "quiet_turn" not in res_off + assert "epoch_prefetch" not in res_off + assert "--compact-direct-read" not in (Path(e_off["LOOPX_CODEX_HOME"]) / "hooks.json").read_text() + + on_tmp = tmp_path / "on" + on_tmp.mkdir() + e_on = resume_env(on_tmp, monkeypatch) + e_on.update({ + "LOOPX_CONTEXT_DELIVERY": "on", + "LOOPX_COMPACT_DIRECT_READ": "1", + "LOOPX_QUIET_TURN": "1", + "LOOPX_EPOCH_PREFETCH_JSON": '{"enabled": true}', + }) + res_on = run_once(e_on) + assert res_on["ok"] + assert res_on["compact_direct_read"] is True + assert res_on["quiet_turn"] is True + assert res_on["epoch_prefetch"] is True + assert res_on["epoch_prefetch_configured"] is True + hooks_text = (Path(e_on["LOOPX_CODEX_HOME"]) / "hooks.json").read_text() + assert "--compact-direct-read" in hooks_text + assert "--quiet-turn" in hooks_text + assert "--epoch-prefetch-json" in hooks_text + + # Explicitly disabled epoch_prefetch_json must NOT set epoch_prefetch=True in receipt. + dis_tmp = tmp_path / "dis" + dis_tmp.mkdir() + e_dis = resume_env(dis_tmp, monkeypatch) + e_dis.update({"LOOPX_CONTEXT_DELIVERY": "on", "LOOPX_EPOCH_PREFETCH_JSON": '{"enabled": false}'}) + res_dis = run_once(e_dis) + assert res_dis["ok"] + assert "epoch_prefetch" not in res_dis + assert res_dis["epoch_prefetch_configured"] is False + + +def test_harbor_h1_h2_opt_in_worker_env_and_warm_start_yardstick(tmp_path, monkeypatch): + pytest.importorskip("harbor") + from benchmark.runtime.harbor import BenchmarkCodex + from loopx.cli import main + + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("LOOPX_COMPACT_DIRECT_READ", "1") + monkeypatch.setenv("LOOPX_QUIET_TURN", "1") + monkeypatch.setenv("LOOPX_EPOCH_PREFETCH_JSON", '{"enabled":true}') + implicit = BenchmarkCodex(logs_dir=tmp_path / "imp", model_name="openai/fixture") + explicit = BenchmarkCodex(logs_dir=tmp_path / "exp", model_name="openai/fixture", + compact_direct_read=False, quiet_turn=False, + epoch_prefetch_json=None, execution_yardstick_enabled=None) + assert implicit._worker_env(cwd="/task") == explicit._worker_env(cwd="/task") + assert implicit._worker_env(cwd="/task")["LOOPX_COMPACT_DIRECT_READ"] == "0" + assert implicit._worker_env(cwd="/task")["LOOPX_QUIET_TURN"] == "0" + assert implicit._worker_env(cwd="/task")["LOOPX_EPOCH_PREFETCH_JSON"] == "" + assert "yardstick_enabled" not in implicit._replan_receipt() + + # Invalid execution_yardstick_enabled rejections. + for bad in ({"execution_yardstick_enabled": "yes"}, + {"execution_mode": "plain", "execution_yardstick_enabled": True}): + with pytest.raises(ValueError, match="execution_yardstick_enabled"): + BenchmarkCodex(logs_dir=tmp_path / "bad", model_name="openai/fixture", **bad) + + # Cold Harbor H2 without active Explore Graph must fail closed instead of accepting inert yardstick=True. + reg = tmp_path / "reg.json" + rt = tmp_path / "rt" + agent = BenchmarkCodex( + logs_dir=tmp_path / "h2", model_name="openai/fixture", + task_entry="seeded-todo", compact_direct_read=True, quiet_turn=True, + epoch_prefetch_json={"enabled": True}, execution_yardstick_enabled=True, + ) + assert agent._replan_receipt()["yardstick_enabled"] is True + assert agent._turn_envelope_receipt()["compact_direct_read"] is True + assert agent._turn_envelope_receipt()["quiet_turn"] is True + assert agent._turn_envelope_receipt()["epoch_prefetch"] is True + + calls = [] + async def cli(environment, args, **kwargs): + import contextlib + import io + calls.append(args) + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + code = main(["--format", "json", "--registry", str(reg), "--runtime-root", str(rt), *args]) + assert code == 0, buf.getvalue() + return json.loads(buf.getvalue()) + + async def no_pending(**kwargs): + return SimpleNamespace(return_code=1) + + async def noop(*a, **kw): + return None + + async def reg_exists(*a, **kw): + return reg.is_file() and reg.stat().st_size > 0 + + monkeypatch.setattr(agent, "_loopx", cli) + monkeypatch.setattr(agent, "_write_task_document", noop) + monkeypatch.setattr(agent, "_registry_exists", reg_exists) + with pytest.raises(RuntimeError, match="active Explore evidence graph"): + asyncio.run(agent._prepare_phase(SimpleNamespace(exec=no_pending), "Task 1", cwd=str(tmp_path))) + + # Enabling Explore Graph on the Goal allows cold/existing-registry and WarmStart H2 readback to pass, + # verifying real `explore turn-context` exposes `graph_enabled` and `work_yardstick_capture`. + asyncio.run(cli(None, ["configure-goal", "--goal-id", agent.goal_id, "--explore-graph-enabled", "--execute"])) + asyncio.run(agent._prepare_phase(SimpleNamespace(exec=no_pending), "Task 1", cwd=str(tmp_path))) + turn_ctx = asyncio.run(cli(None, ["explore", "turn-context", "--goal-id", agent.goal_id, "--agent-id", agent.agent_id])) + assert turn_ctx["graph_enabled"] is True + assert isinstance(turn_ctx["graph"]["work_yardstick_capture"], dict) + + # Reset yardstick externally, then simulate WarmStart / existing registry Phase 2 -> must re-apply! + asyncio.run(cli(None, ["configure-goal", "--goal-id", agent.goal_id, "--no-execution-yardstick-enabled", "--execute"])) + asyncio.run(agent._prepare_phase(SimpleNamespace(exec=no_pending), "Task 2", cwd=str(tmp_path))) + readback = asyncio.run(cli(None, ["configure-goal", "--goal-id", agent.goal_id])) + assert readback["after"]["execution_profile"]["yardstick_enabled"] is True + assert any("--execution-yardstick-enabled" in c for c in calls) + + # Explicit execution_yardstick_enabled=False persists cleanly without requiring Explore. + agent_off = BenchmarkCodex( + logs_dir=tmp_path / "h2-off", model_name="openai/fixture", + task_entry="seeded-todo", execution_yardstick_enabled=False, + ) + monkeypatch.setattr(agent_off, "_loopx", cli) + monkeypatch.setattr(agent_off, "_write_task_document", noop) + monkeypatch.setattr(agent_off, "_registry_exists", reg_exists) + asyncio.run(agent_off._prepare_phase(SimpleNamespace(exec=no_pending), "Task off", cwd=str(tmp_path))) + off_readback = asyncio.run(cli(None, ["configure-goal", "--goal-id", agent_off.goal_id])) + assert off_readback["after"]["execution_profile"]["yardstick_enabled"] is False + + # Readback mismatch must fail closed. + async def stale_cli(environment, args, **kwargs): + return {"after": {"execution_profile": { + "replan_after_effective_turns": 6, "planning_horizon_goal": True, + "stride_strategy": "off", "yardstick_enabled": False, + }}} + monkeypatch.setattr(agent, "_loopx", stale_cli) + with pytest.raises(RuntimeError, match="execution_yardstick_enabled readback mismatch"): + asyncio.run(agent._verify_phase_configuration(SimpleNamespace(), cwd=str(tmp_path))) + + +def test_sforge_worker_h2_warm_start_and_cold_explore_yardstick(tmp_path, monkeypatch): + pytest.importorskip("sforge") + pytest.importorskip("harbor") + from sforge.harness.config import SForgeConfig + from benchmark.runtime.sforge import SForgeWorker + + monkeypatch.chdir(tmp_path) + auth_file = tmp_path / "auth.json" + auth_file.write_text("{}", encoding="utf-8") + monkeypatch.setenv("CODEX_AUTH_JSON_PATH", str(auth_file)) + monkeypatch.setattr("benchmark.runtime.harbor.BenchmarkCodex.install", lambda self, env: asyncio.sleep(0)) + monkeypatch.setattr(SForgeWorker, "_warm_command", lambda *a, **kw: None) + + worker = SForgeWorker( + SForgeConfig(agent_model="fixture", agent_effort="xhigh"), + profile="heartbeat-explore", + cwd=str(tmp_path), + execution_yardstick_enabled=True, + ) + reg = tmp_path / "sforge-reg.json" + rt = tmp_path / "sforge-rt" + calls = [] + + async def cli(environment, args, **kwargs): + import contextlib + import io + from loopx.cli import main + calls.append(args) + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + code = main(["--format", "json", "--registry", str(reg), "--runtime-root", str(rt), *args]) + assert code == 0, buf.getvalue() + return json.loads(buf.getvalue()) + + async def noop(*a, **kw): + return None + + async def reg_exists(*a, **kw): + return reg.is_file() and reg.stat().st_size > 0 + + class DummyEnv: + async def exec(self, command, **_kw): + if command.startswith("cat "): + return SimpleNamespace(return_code=0, stdout="Solve the task.\n") + return SimpleNamespace(return_code=1, stdout="") + + async def upload_file(self, *a, **kw): + return None + + worker.backend = SimpleNamespace( + exec_run=lambda *a, **kw: SimpleNamespace(exit_code=0, output=""), + exec_run_with_exit_code=lambda *a, **kw: SimpleNamespace(timed_out=False, exit_code=0, output=""), + copy_to_container=lambda *a: None, + ) + logs = tmp_path / "logs" + logs.mkdir() + worker.install_stop_hook(worker.backend, None, logs, None) + worker.runtime.environment = DummyEnv() + worker.environment = DummyEnv() + monkeypatch.setattr(worker.runtime, "_loopx", cli) + monkeypatch.setattr(worker.runtime, "_write_task_document", noop) + monkeypatch.setattr(worker.runtime, "_registry_exists", reg_exists) + worker.format_run_cmd(str(tmp_path / "prompt.md"), model="fixture", cwd=str(tmp_path)) + assert (logs / "explore-activation.json").is_file() + readback = asyncio.run(cli(None, ["configure-goal", "--goal-id", worker.runtime.goal_id])) + assert readback["after"]["execution_profile"]["yardstick_enabled"] is True + + # Simulate warm_start forwarding --execution-yardstick-enabled on restore. + asyncio.run(cli(None, ["configure-goal", "--goal-id", worker.runtime.goal_id, "--no-execution-yardstick-enabled", "--execute"])) + warm = SimpleNamespace( + goal_id=worker.runtime.goal_id, + agent_id=worker.runtime.agent_id, + stage=lambda *a, **kw: asyncio.sleep(0, result=()), + research_sidecar=False, + native_child_limit=None, + deadline_epoch=time.time() + 600, + verify=lambda _cwd: None, + source_context_dir=lambda: tmp_path / "src-ctx", + ) + (tmp_path / "src-ctx").mkdir() + worker_warm = SForgeWorker( + SForgeConfig(agent_model="fixture", agent_effort="xhigh"), + profile="heartbeat-explore", + cwd=str(tmp_path), + task_entry="loopx-planned", + warm_start=warm, + execution_yardstick_enabled=True, + ) + worker_warm.backend = worker.backend + logs_warm = tmp_path / "logs-warm" + logs_warm.mkdir() + worker_warm.install_stop_hook(worker_warm.backend, None, logs_warm, None) + worker_warm.environment = DummyEnv() + worker_warm.runtime.environment = DummyEnv() + monkeypatch.setattr(worker_warm.runtime, "_loopx", cli) + monkeypatch.setattr(worker_warm.runtime, "_write_task_document", noop) + monkeypatch.setattr(worker_warm.runtime, "_registry_exists", reg_exists) + worker_warm.format_run_cmd(str(tmp_path / "prompt.md"), model="fixture", cwd=str(tmp_path)) + readback2 = asyncio.run(cli(None, ["configure-goal", "--goal-id", worker_warm.runtime.goal_id])) + assert readback2["after"]["execution_profile"]["yardstick_enabled"] is True + + +def test_sforge_worker_default_off_opt_ins_and_base_verification_before_explore(tmp_path, monkeypatch): + pytest.importorskip("sforge") + pytest.importorskip("harbor") + from sforge.harness.config import SForgeConfig + from benchmark.runtime.sforge import SForgeWorker + from loopx.cli import main + + monkeypatch.chdir(tmp_path) + auth_file = tmp_path / "auth.json" + auth_file.write_text("{}", encoding="utf-8") + monkeypatch.setenv("CODEX_AUTH_JSON_PATH", str(auth_file)) + monkeypatch.setenv("LOOPX_COMPACT_DIRECT_READ", "1") + monkeypatch.setenv("LOOPX_QUIET_TURN", "1") + monkeypatch.setenv("LOOPX_EPOCH_PREFETCH_JSON", '{"enabled":true}') + monkeypatch.setattr("benchmark.runtime.harbor.BenchmarkCodex.install", lambda self, env: asyncio.sleep(0)) + monkeypatch.setattr(SForgeWorker, "_warm_command", lambda *a, **kw: None) + + class DummyEnv: + async def exec(self, command, **_kw): + if command.startswith("cat "): + return SimpleNamespace(return_code=0, stdout="Solve the task.\n") + return SimpleNamespace(return_code=1, stdout="") + + async def upload_file(self, *a, **kw): + return None + + async def noop(*a, **kw): + return None + + dummy_backend = SimpleNamespace( + exec_run=lambda *a, **kw: SimpleNamespace(exit_code=0, output=""), + exec_run_with_exit_code=lambda *a, **kw: SimpleNamespace(timed_out=False, exit_code=0, output=""), + copy_to_container=lambda *a: None, + ) + + # 1. Default-off SForgeWorker ignores ambient H1 host env vars and never enables H1/H2/Explore by default. + off_dir = tmp_path / "off" + off_dir.mkdir() + reg_off = tmp_path / "off-reg.json" + rt_off = tmp_path / "off-rt" + logs_off = tmp_path / "off-logs" + logs_off.mkdir() + w_off = SForgeWorker(SForgeConfig(agent_model="fixture", agent_effort="xhigh"), profile="heartbeat-resume", cwd=str(off_dir)) + assert w_off.execution.compact_direct_read is False + assert w_off.execution.quiet_turn is False + assert w_off.execution.epoch_prefetch_json is None + assert w_off.execution_yardstick_enabled is None + w_off.backend = dummy_backend + w_off.install_stop_hook(w_off.backend, None, logs_off, None) + assert w_off.runtime._worker_env(cwd=str(off_dir))["LOOPX_COMPACT_DIRECT_READ"] == "0" + assert w_off.runtime._worker_env(cwd=str(off_dir))["LOOPX_QUIET_TURN"] == "0" + assert w_off.runtime._worker_env(cwd=str(off_dir))["LOOPX_EPOCH_PREFETCH_JSON"] == "" + assert "yardstick_enabled" not in w_off.runtime._replan_receipt() + turn_receipt = w_off.runtime._turn_envelope_receipt() + assert "compact_direct_read" not in turn_receipt + assert "quiet_turn" not in turn_receipt + assert "epoch_prefetch" not in turn_receipt + + calls_off = [] + + async def cli_off(environment, args, **kwargs): + import contextlib + import io + calls_off.append(list(args)) + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + code = main(["--format", "json", "--registry", str(reg_off), "--runtime-root", str(rt_off), *args]) + assert code == 0, buf.getvalue() + return json.loads(buf.getvalue()) + + monkeypatch.chdir(off_dir) + w_off.environment = DummyEnv() + w_off.runtime.environment = DummyEnv() + monkeypatch.setattr(w_off.runtime, "_loopx", cli_off) + monkeypatch.setattr(w_off.runtime, "_write_task_document", noop) + monkeypatch.setattr(w_off.runtime, "_registry_exists", lambda *a, **kw: asyncio.sleep(0, result=reg_off.is_file())) + w_off.format_run_cmd(str(tmp_path / "prompt.md"), model="fixture", cwd=str(off_dir)) + assert not (logs_off / "explore-activation.json").exists() + off_state = asyncio.run(cli_off(None, ["configure-goal", "--goal-id", w_off.runtime.goal_id])) + assert off_state["after"]["execution_profile"].get("yardstick_enabled") in (None, False) + assert not any("--execution-yardstick-enabled" in call or "--explore-graph-enabled" in call for call in calls_off) + + # 2. Stale base replan configuration on cold heartbeat-explore MUST fail BEFORE activating Explore or writing explore-activation.json. + stale_dir = tmp_path / "stale" + stale_dir.mkdir() + monkeypatch.chdir(stale_dir) + reg_stale = tmp_path / "stale-reg.json" + rt_stale = tmp_path / "stale-rt" + logs_stale = tmp_path / "stale-logs" + logs_stale.mkdir() + w_stale = SForgeWorker( + SForgeConfig(agent_model="fixture", agent_effort="xhigh"), + profile="heartbeat-explore", + cwd=str(stale_dir), + execution_yardstick_enabled=True, + ) + w_stale.backend = dummy_backend + w_stale.install_stop_hook(w_stale.backend, None, logs_stale, None) + w_stale.environment = DummyEnv() + w_stale.runtime.environment = DummyEnv() + + seen_args = [] + + async def stale_base_cli(environment, args, **kwargs): + import contextlib + import io + seen_args.append(list(args)) + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + code = main(["--format", "json", "--registry", str(reg_stale), "--runtime-root", str(rt_stale), *args]) + assert code == 0, buf.getvalue() + payload = json.loads(buf.getvalue()) + if args[:2] == ["configure-goal", "--goal-id"] and "--execute" not in args: + payload = { + **payload, + "after": { + **payload.get("after", {}), + "execution_profile": { + **payload.get("after", {}).get("execution_profile", {}), + "replan_after_effective_turns": 99, + }, + }, + } + return payload + + monkeypatch.setattr(w_stale.runtime, "_loopx", stale_base_cli) + monkeypatch.setattr(w_stale.runtime, "_write_task_document", noop) + monkeypatch.setattr(w_stale.runtime, "_registry_exists", lambda *a, **kw: asyncio.sleep(0, result=reg_stale.is_file())) + with pytest.raises(RuntimeError, match="replan cadence readback mismatch"): + w_stale.format_run_cmd(str(tmp_path / "prompt.md"), model="fixture", cwd=str(stale_dir)) + assert not any("--explore-graph-enabled" in call for call in seen_args) + assert not (logs_stale / "explore-activation.json").exists() diff --git a/benchmark/tests/test_task_entry.py b/benchmark/tests/test_task_entry.py index 715161791b..ccb9f2135b 100644 --- a/benchmark/tests/test_task_entry.py +++ b/benchmark/tests/test_task_entry.py @@ -367,9 +367,12 @@ def planning_env(tmp_path): @pytest.mark.parametrize("context", ["fresh", "resume"]) +@pytest.mark.parametrize("phase_clock", [True, False], ids=["bounded", "natural"]) def test_planning_writes_real_todo_then_reuses_it_without_executing_task( - planning_env, context + planning_env, context, phase_clock ): + if not phase_clock: + planning_env.pop("LOOPX_PHASE_DEADLINE_EPOCH") planning_env["LOOPX_ITERATION_CONTEXT"] = context if context == "fresh": planning_env.pop("LOOPX_TASK_ENTRY") # Omitted worker setting uses the same planner. diff --git a/docs/architecture/rfcs/hierarchical-agent-stride-control-v0.md b/docs/architecture/rfcs/hierarchical-agent-stride-control-v0.md index 8a19632ad9..3ab1d5625f 100644 --- a/docs/architecture/rfcs/hierarchical-agent-stride-control-v0.md +++ b/docs/architecture/rfcs/hierarchical-agent-stride-control-v0.md @@ -638,6 +638,195 @@ decision through the same `previous_review` requirement. Feature-off context and legacy decision references remain unchanged. This repairs feedback delivery; execution quality and goal benefit still require separate evidence. + + +#### Meta-goals and single-Todo acceptance (proposal) + +A **meta-goal** is a planning objective for pursuing one or more existing goals. +It specifies what should be true of a plan, a choice among candidate plans, or +the relationship between plans, and how to tell when that condition is met. +A decision question identifies an uncertainty that could change the choice. +The same meta-goal can span Turns as questions and actions change. +[Wilensky, §2.2](https://www2.eecs.berkeley.edu/Pubs/TechRpts/1980/Archive/ERL-m-80-33.pdf) + +| Meta-goal | Example and success condition | Possible Stride action | +|---|---|---| +| Resolve a conflict between goals | Two Goals may need the same limited test window. Find an order or alternative route that meets both sets of acceptance criteria and deadlines. If the commitments cannot both be met, the authorized Goal owners decide the trade-off. | `verify` whether the windows overlap, or `switch` to test a mechanism that can run independently. | +| Combine overlapping plans | Two plans require equivalent validation against the same input revision. Run it once with coverage for both sets of criteria, and let each acceptance decision reference the shared result. | `verify` coverage if it is uncertain. Confirmed coverage can support `grow` on the shared route within its validated scope. | +| Choose the highest-value feasible continuation | Compare expected goal value within the same acceptance, deadline, authority and resource constraints. When expected outcomes, risks and later options are equivalent, prefer the lower full cost. | Compare `grow` on a supported route with a `switch` experiment. Use `verify` when the evidence could improve that choice enough to justify the probe. | + +Stride chooses the next action in pursuit of the meta-goal. `verify` gathers +evidence that can change the choice at a justified cost. `grow` expands work on +a supported route. `switch` tests a materially different mechanism. The same +meta-goal can call for different actions as evidence arrives. Plan changes +such as reordering work or sharing a dependency use the existing Todo paths. +Goal commitments, acceptance, budget and authority remain with their owners. + +**Value of a continuation.** Compare the incremental utility delivered by the +current slice and the expected additional utility from later choices. One +Bellman-style expression for this comparison is + +$$ +Q(s,b,a)=\mathbb E\!\left[\Delta U_{\mathrm{now}}+ +D(\Delta t)V_{\mathrm{future}}(S',b-K)\mid s,b,a\right]. +$$ + +Here `s` and `b` are the current state and remaining resources. An action +uses resources `K` and leads to state `S'` with updated results and evidence. +`D(Δt)` discounts utility over the time until the next decision. Use one when +time is governed solely by the deadline. Define utility from the Goal's +acceptance criteria. The future term counts the additional utility available +from feasible choices after the current slice. + +Information has value through better later choices. Estimate that value by +comparing the later decision with and without the new observation at the same +time and resource point. Count it once in the evidence-conditioned future +term. An action can deliver utility and informative evidence together. +When comparing a probe with acting directly, include the probe's resource +use and delay. Terminal-outcome objectives and stopping follow the existing +[budgeted planning model](target-yardstick-stride-decisions-v0.md#budgeted-planning). + +**First acceptance trial.** Use one Todo to deliver a faster scheduler under +its existing correctness and budget constraints. The meta-goal is to select +the optimization route that warrants further investment. The decision +question is whether the candidate's gains carry over to peak load. Compare +tuning immediately with spending part of the same budget on a peak-load +probe that could change which route to scale. State the objective and choice +in the existing Stride plan and reasons. For the probe path, choose `verify` +and use `next_probe` to compare the candidate and incumbent under matched peak +conditions, with a prediction, minimum evidence, adoption criterion and cost bound. + +**Worked scheduler example.** Give the Todo 10 budget units and a hard +deadline, with $D=1$. In this example, a 10% accepted peak-throughput gain +over the incumbent is worth 10 utility points. The prior probability that +the current mechanism's gain transfers to peak load is $P(T)=0.60$. +At remaining budget $r$, `grow` earns $r$ points if $T$ holds and retains the +incumbent at 0 points otherwise. `switch` earns $r/2$ points in either state. +Both payoffs assume $r$ covers implementation, any switch, and final +validation under the same acceptance criteria. + +The probe costs 1 unit, leaves 9 for either route, and delivers 0 immediate +throughput points. Assume the matched peak comparison passes its correctness +checks and returns one of two valid results. A $+$ means the candidate reaches +at least the declared 5% gain, and a $-$ means it falls below it. Assume +symmetric sensitivity and specificity $P(+\mid T)=P(-\mid \neg T)=q=0.90$. +Let $p$ be the transfer probability given the evidence so far. At any +positive remaining budget $r$, `grow` beats `switch` when $p>0.50$, since +their expected values are $rp$ and $r/2$. + +| Valid probe result | Probability | Transfer probability after the result | Next choice | +|---|---:|---:|---| +| $+$ | 0.58 | $0.54/0.58 \approx 93.1\%$ | `grow` | +| $-$ | 0.42 | $0.06/0.42 \approx 14.3\%$ | `switch` | + +| Continuation | Total budget | Expected accepted gain (points) | +|---|---:|---:| +| Direct `grow` | 10 | $0.60\times10=6.00$ | +| Direct `switch` | 10 | $10/2=5.00$ | +| `verify`, then choose | $1+9=10$ | $0.54\times9+0.42\times4.5=6.75$ | + +In the last row, 0.54 is the joint probability of transfer and a positive +signal. The alternative earns 4.5 points in either state after a negative +signal. Using prior evidence with the same 9 units gives +$\max(0.60\times9,4.5)=5.40$. The information is worth $6.75-5.40=1.35$ +points, the budget it consumes costs $6.00-5.40=0.60$ in foregone utility, +and the net gain over direct `grow` is 0.75 points. + +For symmetric accuracy $0.50\le q\le0.60$, `grow` remains optimal after +either result, giving the information zero decision value. When $q>0.60$, +the results fall on opposite sides of the 50% decision threshold. +For probe cost $k$, the probabilities $P(T,+)=0.60q$ and $P(-)=0.60-0.20q$ +give expected value $(10-k)[0.60q+(0.60-0.20q)/2]=(10-k)(0.30+0.50q)$. +With feasible follow-up work, probe when this exceeds 6.00. At $q=0.90$, +this requires $k<2$ units. At $k=1$, it requires $q>11/15$ (about 73.3%). +Equality gives the same expected value as direct `grow`. If a probe can +return an inconclusive result, include that outcome's probability and its +continuation value at the remaining budget in the comparison. + +**Estimate the inputs before choosing.** Fix the incumbent, peak workload +and scale, evaluation horizon, and acceptance criteria for the comparison. +In the actual Todo, $T$ means the current mechanism meets the declared useful +peak gain at that scale under the existing correctness constraints. + +- **Transfer prior.** Use the closest comparable independent evaluations + available before the probe, matched by mechanism, workload, scale and + acceptance. Report verified transfers over resolved cases, alongside + missing labels and uncertainty. Repeated timings can refine a case's + noise estimate and share one transfer label. +- **Probe accuracy.** Use cases with a quick result and an independent + reference verdict for the same candidate revision and workload scope. + Within each reference state ($T$ or $\neg T$), divide positive, negative + and inconclusive counts by the paired-case count to estimate the + likelihoods of each result. The two error rates can differ. A state + without pairs remains unknown. Report which probe results obtained + reference labels and scope the estimates to that coverage. Where useful + within budget, check some probe-negative cases for missed transfers. +- **Route utility.** For `grow` and `switch`, use comparable runs to estimate + the possible accepted gains over the same incumbent at the same remaining + budget and horizon. Weight the outcomes by their likelihood, including + fallback after failure. Include implementation, switching, recovery and + final verification in the resource estimates. Use ranges supported by + comparable runs or the mechanism's limits, and retain unknowns for + quantities those sources cannot bound. + +Before results arrive, use the existing Stride plan and probe to record or +reference the estimates, scope, evidence and what observation could change +the choice. + +**Choose with sparse evidence.** Compare feasible choices across plausible +ranges for the prior, probe likelihoods, gains and costs. Use the preferred +route if the ordering is stable. If it can flip, identify the assumption +that changes the choice. Favor a bounded probe when the expected improvement +justifies its cost and delay and leaves time and resources for final +confirmation. Otherwise favor a supported, reversible next slice, or retain +the incumbent and record the question as unresolved through the existing +stop or wait conditions. + +In a later authorized Turn, use `decision_followthrough` and `previous_review` +to tie the next choice to the exact candidate, workload and observed result. +Read back all three outcomes across the trial cases. + +- The evidence favors expanding the current route and shows useful headroom. + Choose `grow` and execute a larger coherent slice within the remaining budget. +- The evidence favors testing a different mechanism. Choose `switch` and run a + bounded test of that mechanism. +- The cost bound is reached with insufficient evidence. Record the choice as + unresolved and handle settlement or waiting through the existing owner. + +Use the existing Todo, Turn admission and settlement paths. Independently +verify the action taken. For executed follow-up work, check whether it +followed the decision and how its result compares with the original acceptance +criteria. Record complete costs, including inconclusive probes, in all three cases. + +**Calibrate from verified outcomes.** Link the original forecast to the +observed probe result, the route actually executed, the independent verdict +and full observed cost. Update transfer counts with resolved reference +labels, probe likelihoods with paired results and labels, and route payoff +estimates with the executed route's verified outcomes and cost. For example, +a negative probe followed by an accepted `switch` outcome updates the +`switch` estimate. The original mechanism's transfer and the probe's +classification error remain unknown until independently checked. + +Keep the original forecast and the evidence for the update. Report unresolved +labels and unchosen outcomes as unknown. As comparable cases accumulate, +compare prior and posterior forecasts against verified frequencies separately, +and check gain and cost ranges against realized results. Keep comparisons +scoped to the mechanism, workload, horizon, and probe and reference versions. +Check revised estimates on later comparable cases. + +**Follow-up work.** For cross-Todo planning, start with two Todos within one +Goal. Check that shared validation covers each Todo's acceptance criteria and +read back both consumers' use. Cross-Goal changes follow the authority of the +affected Goals. + +For cross-task strategy evolution, use verified decision episodes to propose a +bounded, versioned Stride strategy change through its owner. An independent +evaluator compares it with the current version on held-out tasks under the same +model, starting conditions and budget. Read back actual adoption and outcomes +in later authorized work. Use those observations and the evaluation verdict to +decide whether to revise, retain or withdraw the candidate and what to try next. +[Capability evolution research](frontier-science-research-program-v0.md#t07-diversity-preserving-capability-evolution) + #### An iterative strategy and engineering boundary The first strategy is **model-guided, evidence-conditioned work planning**. diff --git a/docs/architecture/rfcs/hierarchical-agent-stride-control-v0.zh-CN.md b/docs/architecture/rfcs/hierarchical-agent-stride-control-v0.zh-CN.md index cba0c7322b..592da2d76e 100644 --- a/docs/architecture/rfcs/hierarchical-agent-stride-control-v0.zh-CN.md +++ b/docs/architecture/rfcs/hierarchical-agent-stride-control-v0.zh-CN.md @@ -546,6 +546,141 @@ Turn、义务、settlement identity 与已接受的回执必须一致;派生 context 和历史决策引用保持兼容。这里修复的是反馈送达,执行质量和目标收益 仍需独立证据。 + + +#### 元目标与单 Todo 首版验收(提案) + +**元目标**是关于如何实现一个或多个既定目标的规划目标。它规定一个计划、候选计划的 +选择或计划之间的关系应达到什么状态,以及如何判断该状态已经达到。决策问题指出 +哪项不确定性可能改变选择。同一个元目标可以跨 Turn 延续,具体问题和动作随证据变化。 +[Wilensky §2.2](https://www2.eecs.berkeley.edu/Pubs/TechRpts/1980/Archive/ERL-m-80-33.pdf) + +| 元目标 | 例子与达成条件 | 可选的 Stride 动作 | +|---|---|---| +| 解决目标之间的冲突 | 两个 Goal 可能需要使用同一个有限的测试窗口。找到能同时满足双方验收和期限的顺序或替代路线。若双方承诺确实无法同时兑现,由获授权的 Goal 归属方决定取舍。 | 用 `verify` 核对窗口是否重叠,或用 `switch` 测试能独立运行的另一种机制。 | +| 合并重叠计划 | 两个计划需要对相同输入版本做等价验证。执行一次覆盖双方验收条件的验证,各自的验收决定均可引用该结果。 | 覆盖范围不确定时用 `verify`。已确认的覆盖可以支持在验证范围内用 `grow` 扩大共享路线。 | +| 选择预期价值最高的可行接续 | 在相同验收、时限、权限和资源约束下比较预期目标价值。预期成果、风险和后续选择等价时,选完整成本更低的方案。 | 比较用 `grow` 扩大已有依据的路线与用 `switch` 测试另一种机制。若证据能改善这一选择且值得探针成本,使用 `verify`。 | + +Stride 选择推进元目标的下一步。`verify` 用合理成本获取可能改变选择的证据。`grow` +扩大已有证据支持的路线。`switch` 测试实质不同的机制。同一个元目标可随新证据改用 +不同动作。重排工作、共享依赖等计划变更沿用既有 Todo 路径。Goal 承诺、验收、预算 +和权限仍由原归属方管理。 + +**接续方案的价值。** 比较当前切片带来的增量效用,以及后续选择能带来的预期增量效用。 +可以用 Bellman 形式表达这一比较。 + +$$ +Q(s,b,a)=\mathbb E\!\left[\Delta U_{\mathrm{now}}+ +D(\Delta t)V_{\mathrm{future}}(S',b-K)\mid s,b,a\right]. +$$ + +`s` 和 `b` 分别是当前状态和剩余资源。动作消耗资源 `K`,得到包含新结果和新证据的 +状态 `S'`。`D(Δt)` 按到下一次决策的时间折现效用。若时间只受截止期限约束,取 1。 +效用由 Goal 的验收标准定义。未来项计入当前切片结束后仍可通过可行选择实现的增量效用。 + +信息通过改善后续决策产生价值。在相同的时间和资源条件下,比较看到新观测与沿用 +已有证据时的后续选择,估计由此增加的预期效用。这部分价值在基于新证据的未来项中 +计一次。一个动作可以同时产出有用结果和决策证据。比较探针与直接推进时,计入探针 +的资源消耗和延迟。终局成果目标及停止条件沿用 +[预算规划模型](target-yardstick-stride-decisions-v0.zh-CN.md#budgeted-planning)。 + +**首版验收。** 用一个 Todo 在既有正确性与预算约束下交付更快的调度器。元目标是 +选出值得进一步投入的优化路线。决策问题是候选方案的收益能否迁移到峰值负载。 +比较立即调优与在同一预算内先做峰值探针,后者可能改变要扩大的路线。在既有 Stride +计划与理由中写清目标和选择。采用探针时选择 `verify`,用 `next_probe` 在相同峰值 +条件下比较候选与基线,并声明预测、最低证据、采用条件和成本边界。 + +**调度器算例。** 假设该 Todo 有 10 个预算单位,时间只受硬截止期限约束,取 $D=1$。 +效用以通过原验收的峰值吞吐增幅计分。相对基线增长 10% 计 10 分。当前机制的收益能 +迁移到峰值负载的先验概率为 $P(T)=0.60$。剩余预算为 $r$ 时,若 $T$ 成立,`grow` +获 $r$ 分,否则保留基线,计 0 分。`switch` 在两种状态下均获 $r/2$ 分。两条路线 +都用 $r$ 覆盖实施、必要的切换和最终验证,沿用相同验收标准。 + +探针花 1 个单位,留 9 个单位给后续路线,当期吞吐增益计 0 分。假设同一峰值负载下的 +对照通过正确性检查,并返回两种有效结果之一。候选达到预先声明的 5% 增幅记为 $+$, +低于该增幅记为 $-$。假设灵敏度和特异度相同,$P(+\mid T)=P(-\mid \neg T)=q=0.90$。 +令 $p$ 为依据已有证据估计的迁移概率。只要剩余预算 $r$ 大于 0,$p>0.50$ 时 +`grow` 的期望值 $rp$ 就超过 `switch` 的 $r/2$。 + +| 有效探针结果 | 概率 | 观测后的迁移概率 | 下一步 | +|---|---:|---:|---| +| $+$ | 0.58 | $0.54/0.58 \approx 93.1\%$ | `grow` | +| $-$ | 0.42 | $0.06/0.42 \approx 14.3\%$ | `switch` | + +| 接续方案 | 总预算 | 期望验收收益(分) | +|---|---:|---:| +| 直接 `grow` | 10 | $0.60\times10=6.00$ | +| 直接 `switch` | 10 | $10/2=5.00$ | +| 先 `verify` 再选 | $1+9=10$ | $0.54\times9+0.42\times4.5=6.75$ | + +最后一行的 0.54 是收益可迁移且探针为正的联合概率。探针为负时,切换机制在两种 +状态下都获 4.5 分。同样只剩 9 单位时,沿用先验信息的最优期望为 +$\max(0.60\times9,4.5)=5.40$。信息价值为 $6.75-5.40=1.35$ 分,消耗 1 单位 +预算放弃的效用为 $6.00-5.40=0.60$ 分,相对直接 `grow` 的净收益为 0.75 分。 + +当对称准确率 $0.50\le q\le0.60$ 时,两种结果下 `grow` 均仍是最优选择,信息的 +决策价值为零。$q>0.60$ 时,两个结果分落在 50% 选择阈值两侧。联合概率 +$P(T,+)=0.60q$,负结果概率 $P(-)=0.60-0.20q$。成本为 $k$ 的探针期望值为 +$(10-k)[0.60q+(0.60-0.20q)/2]=(10-k)(0.30+0.50q)$。后续工作可行且期望值 +超过 6.00 时,探针值得做。$q=0.90$ 时要求 $k<2$ 个单位。$k=1$ 时要求 +$q>11/15$,约为 73.3%。等号表示与直接 `grow` 的期望值持平。若探针可能无结论, +比较时还要计入这种结果的概率和其剩余预算下的后续价值。 + +**选择前估计输入。** 固定对照基线、峰值工作负载及规模、评估时限和验收条件。 +实际 Todo 中,$T$ 表示当前机制在目标规模下符合既有正确性约束,并达到已声明的 +有意义峰值增益。 + +- **迁移先验。** 使用探针开始前已有的、机制、负载、规模和验收可比的独立评估。 + 用已核验迁移的次数除以已有明确结论的次数,同时记录缺失标签和不确定性。 + 同一案例的重复测量可帮助估计噪声,共用一个迁移标签。 +- **探针准确率。** 使用同时有快速探针结果和独立参考结论的案例,匹配候选版本与 + 负载范围。按参考结论 $T$ 或 $\neg T$ 分组,用正、负、无结论各自的计数除以该 + 组的配对总数,估计各结果在该状态下的概率。两种误判率可以不同。没有配对的状态 + 保留未知。记录哪些探针结果得到参考标签,并限定估计的适用范围。若有决策价值且 + 预算允许,可抽查部分探针负例,发现漏判的迁移。 +- **路线收益。** 对 `grow` 和 `switch`,用可比运行估计在相同剩余预算与时限下 + 相对同一基线可能获得的验收增益。按各结果的概率加权,计入失败后保留的成果。 + 资源估计包括实施、切换、恢复与最终验证。用可比运行或机制的约束给出有依据的 + 范围。无法据此约束的量保留未知。 + +在结果出现前,用现有 Stride 计划与探针记录或引用估计、适用范围、证据及可能改变 +选择的观测。 + +**样本不足时的选择。** 用有依据的先验、探针条件概率、收益和成本范围比较可行路线。 +排序稳定时选择优先路线。排序可能翻转时,找出影响选择的假设。若有界探针的预期 +收益能覆盖其成本和延迟,且仍留有最终确认所需的时间与资源,就优先测该假设。 +否则优先走有依据、可回退的小切片,或保留基线,沿用既有停止或等待条件记录未决。 + +在后续获准的 Turn 中,通过 `decision_followthrough` 和 `previous_review` 将下一次 +选择与确切的候选、负载和观测结果关联。在不同验收案例中读回三种结果。 + +- 证据更支持扩大当前路线,且仍有实际收益空间。选择 `grow`,在剩余预算内执行更大的连贯工作切片。 +- 证据支持测试另一种机制。选择 `switch`,执行该机制的有界测试。 +- 到达成本边界时证据仍不足。记录选择未决,通过原归属方处理结算或等待。 + +沿用既有 Todo、Turn 准入和结算路径。独立核验实际采取的动作。对于已执行的后续工作, +检查它是否遵循该决定,以及结果与原验收标准是否相符。三种情况均记录完整成本,包括 +未能得出结论的探针。 + +**用核验结果校准。** 把原预测与探针结果、实际执行路线、独立验收结论及实耗资源 +关联起来。用已核验的参考标签更新迁移计数,用成对的探针结果与标签更新探针条件 +概率,用实际执行路线的已核验成果和成本更新该路线的收益估计。例如,探针为负后 +切换成功,可更新 `switch` 的估计。原机制是否迁移、探针是否误判,在独立核验 +之前仍为未知。 + +保留原预测和修订所依据的证据。未决标签和未执行路线的结果仍标为未知。随着可比 +案例积累,把先验和后验预测分别与已核验频率比较,并用实测结果检查收益和成本的 +预测范围。比较限于相应机制、负载、时限以及探针与参考评估版本。用后续可比案例 +检验修订后的估计。 + +**后续工作。** 跨 Todo 规划先从同一 Goal 内的两个 Todo 开始。检查共享验证能否 +覆盖各自的验收条件,并读回双方的实际使用。跨 Goal 变更遵循相关 Goal 的权限边界。 + +跨任务演进使用已核验的决策案例,由 Stride 策略归属方提出有界的版本改动。独立评测方 +固定模型、起始条件和预算,在留出任务上比较候选与当前版本。通过后续获准工作读回实际 +采用和结果。结合评测结论与这些观测,决定修订、保留或撤回候选,以及下一轮试什么。 +[能力进化研究](frontier-science-research-program-v0.zh-CN.md#t07-保留多样性的能力进化) + #### 可迭代策略与工程边界 第一版策略是**模型依据证据规划完整工作**:显式选择 grow(扩大有支持的路线)、 diff --git a/docs/architecture/rfcs/monorepo-distribution-split-v0.md b/docs/architecture/rfcs/monorepo-distribution-split-v0.md index 7533646745..d50944a530 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.md @@ -4796,3 +4796,21 @@ view shows its independently checked result in the same conversation. - **Boundary:** this is a source wiring repair. Installed Core and composition qualification, interrupted original-Task recovery, complete context/closure, actual models, costs, full R1/M3 and C1 cutover remain separate acceptance. + +### 2026-11-22 — Checkpoint replay returns the selected runtime's artifacts + +- **Gap:** replaying a committed checkpoint from a copied runtime validated the + relocated artifacts through the existing typed owner, but the public + `refresh-state` response still returned paths from the original runtime. +- **Delta:** the Python transport retains that validated replay result and uses + its JSON and Markdown paths in the idempotent response. Path selection, + artifact validation and refusal remain on the existing TypeScript checkpoint + owner; no new path authority or historical-record migration is introduced. +- **Source evidence:** ten real CLI cases cover File and SQLite, dry-run and + repeated replay, and missing or symlinked JSON/Markdown artifacts. They verify + the relocated bytes, unchanged original/copied history and checkpoint proofs, + preserved settlement identity, no appended replay and zero spend. The fixed + main baseline reproduced the stale public path before this repair. +- **Boundary:** this is a bounded V2/V4/R1 recovery repair. Full original-Goal + regression, installed composition, complete default closure and costs, real + model adoption, R1/M3 acceptance and C1 cutover remain separate gates. diff --git a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md index 860206b561..71f657f544 100644 --- a/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md +++ b/docs/architecture/rfcs/monorepo-distribution-split-v0.zh-CN.md @@ -3703,3 +3703,17 @@ workspace 批准和脚本模型工作。桌面视图在采用检查后显示原 - **边界:**本次是源码接线修复。Installed Core 与组合资格、被中断原 Task 的 恢复、完整 context/closure、真实模型、成本、完整 R1/M3 及 C1 cutover 仍是 独立验收。 + +### 2026-11-22 — Checkpoint 回放返回所选 runtime 的产物路径 + +- **缺口:**从复制的 runtime 回放已提交 checkpoint 时,既有 typed owner + 已验证迁移后的产物,但公开 `refresh-state` 响应仍返回原 runtime 的路径。 +- **改动:**Python 传输保留该已验证的回放结果,并在幂等响应中使用其 JSON + 和 Markdown 路径。路径选择、产物验证和拒绝仍由既有 TypeScript checkpoint + owner 负责;不新增路径权限,不迁移历史记录。 +- **源码证据:**十项真实 CLI 用例覆盖 File、SQLite、dry-run、重复回放, + 以及 JSON/Markdown 产物缺失或被符号链接替换。它们核对迁移后的字节、 + 原始与复制历史及 checkpoint 证明不变、结算 identity 保留、回放不追加记录 + 和零消费。修复前,固定 main 基线已复现公开响应路径陈旧。 +- **边界:**这是有界的 V2/V4/R1 恢复修复。原 Goal 完整回归、安装组合、 + 完整默认闭包与成本、真实模型采纳、R1/M3 验收和 C1 切换仍是独立门槛。 diff --git a/docs/product/release-readiness.md b/docs/product/release-readiness.md index e87b63c43d..199efbc95d 100644 --- a/docs/product/release-readiness.md +++ b/docs/product/release-readiness.md @@ -431,6 +431,97 @@ job 结果仍待确认,`publicationAuthorized` 始终为 false。API/下载/ 实际 Windows 路径及发布恢复须独立评审和维护者授权;本机 smoke 不等于 hosted 采用, 复用 runner 也不构成组织级容量预留。 +## Multi-Surface Release Execution Pipeline + +A complete LoopX release coordinates four deliverables: **Core CLI/PyPI + +`stable` ref**, **Desktop App / Tauri Updater**, **`dsh-loopx-plugin` (GitHub +Release + npm + `awesome-dsh-plugin`)**, and **Bilingual Release Notes + Personal +Feishu Guide**. Execute these stages concurrently where safe instead of waiting +serially: + +### Stage 0: Fast Upfront Preflight (`< 5s`) + +Run one static & online inventory command before starting long qualification +runs so version skew, missing signing secrets, or npm bootstrap prerequisites +surface immediately: + +```bash +uv run --extra test python scripts/release_multi_surface_preflight.py --online +``` + +### Stage 1: Four Concurrent Local Qualification Lanes + +On one clean, frozen release commit (preserving `origin/stable` ancestry), fan +out four independent qualification lanes in parallel: + +1. **Lane A (Static, Boundary, Canary & Companion Packaging):** + `loopx check --scan-root .`, `examples/release/*-smoke.py`, manpage + dev-book + smokes, `dsh-loopx-plugin` unit tests & registry smoke. +2. **Lane B (Low-Frequency Live Model Behavior):** + `uv run --extra test python scripts/qualify-doubao-model-behavior-live.py --qualification-id --repo-root .` + against the exact commit (and optional DeepSeek/Ark smoke). +3. **Lane C (Wheel Install, Upgrade, Runtime Probe & Packaged UI):** + Build `wheel`/`sdist`, install in a clean environment, verify + `runtime_activation_qualification`, upgrade from `origin/stable`, and run + `npm --prefix apps/presentation/dashboard run smoke:personal-workspace-packaged`. +4. **Lane D (Single-Wave Sharded Pytest & Release Receipt):** + `uv run --extra test python scripts/qualify_release_commit.py --repo-root . --output-dir .local/release-qualification --preflight-since --resume` + (using single-wave shard concurrency via `default_pytest_parallelism`), then + settle with `uv run --extra test loopx canary release-qualification --manifest-json --repo-root .`. + +### Stage 2: Concurrent Tag Fan-Out & Reactive Waiting + +1. Fast-forward/push annotated tags (`vX.Y.Z` for Core + Desktop, and + `dsh-loopx-plugin-vA.B.C` when the DSH plugin changed) to trigger + `release-artifacts.yml` and `desktop-release-artifacts.yml`; once the + non-draft `vX.Y.Z` and `dsh-loopx-plugin-vA.B.C` GitHub Releases are + published, `desktop-updater.yml` runs on release publication (or + `workflow_dispatch`) and `dsh-plugin-publish.yml` is dispatched via + `workflow_dispatch`. +2. Never busy-poll workflow runs with `sleep` loops. While GitHub Actions builds + and notarizes binaries, immediately author the companion + [Personal Feishu Release Guide](#personal-feishu-release-guide) (using real + post-upgrade screenshots) and open/update the `awesome-dsh-plugin` catalog PR. + +### Stage 3: npm Trusted Publisher Bootstrap (First-Time Package Setup) + +npm OIDC Trusted Publishing (`dsh-plugin-publish.yml`) cannot create a package +before it exists on `registry.npmjs.org` (`HTTP 404` catch-22): + +1. Enable `auth-and-writes` 2FA on the owning npm account. +2. Perform a one-time web-auth publish using the **exact immutable GitHub Release + tarball** (`npm publish dsh-loopx-plugin-VERSION.tgz --access public --tag + latest --ignore-scripts`), then immediately run `npm logout` so no long-lived + CLI token remains on disk. +3. On `https://www.npmjs.com/package//access` under **Trusted Publisher**, + select **GitHub Actions** with Organization/User `loopx-project`, Repository + `loopx`, Workflow filename `dsh-plugin-publish.yml`, **blank** `Environment + name`, and **`Allow npm publish` checked** (the default `npm stage publish` + only setting rejects direct `npm publish --provenance`). Re-dispatch + `dsh-plugin-publish.yml` to verify OIDC provenance and readback. + +### Stage 4: Complete Cross-Surface Readback & `stable` Promotion + +1. Run end-to-end online readback: + ```bash + uv run --extra test python scripts/release_multi_surface_preflight.py --online --require-published + node packages/dsh-loopx-plugin/scripts/verify-distribution.mjs --tarball + ``` +2. Verify `SHA256SUMS` / `DESKTOP-SHA256SUMS`, GitHub artifact attestations, + signed `desktop-stable/desktop-updater.json`, remote GitHub Release body hash + (`release-readiness-doc-smoke.py`), and fast-forward `origin/stable` once + all surfaces pass. + +### 多端协同发布执行流水线(中文精要) + +完整发布协同 **Core CLI / PyPI 与 `stable` 分支**、**Desktop 应用与签名热更新**、**`dsh-loopx-plugin`(GitHub Release + npm + `awesome-dsh-plugin`)** 及 **双语 Release Notes 与个人飞书使用指南**,按 5 个阶段并行推进: + +1. **阶段 0(5 秒前置巡检):** 先跑 `uv run --extra test python scripts/release_multi_surface_preflight.py --online`,在耗时资格化前暴露版本漂移、桌面配置缺失或 npm 首包前置门禁。 +2. **阶段 1(本地四路并行资格化):** 在同一冻结提交上并发执行静态/边界/文档/DSH smoke、低频模型行为门禁(`scripts/qualify-doubao-model-behavior-live.py --qualification-id `)、Wheel+Upgrade+Packaged UI(`npm --prefix apps/presentation/dashboard run smoke:personal-workspace-packaged`)全链路,以及单波多片 `qualify_release_commit.py --resume`,汇总至 `loopx canary release-qualification`。 +3. **阶段 2(远端并发触发与响应式等待):** 并发推注核心 tag(`vX.Y.Z`)与插件 tag(`dsh-loopx-plugin-vA.B.C`)触发 `release-artifacts.yml` 与 `desktop-release-artifacts.yml`;非草稿 Release 发布后,`desktop-updater.yml` 按发布事件(或 `workflow_dispatch`)运行、`dsh-plugin-publish.yml` 经 `workflow_dispatch` 执行。等待构建/公证期间并行编写[个人飞书指南](#personal-feishu-release-guide)与 `awesome-dsh-plugin` 目录 PR(禁止用轮询 `sleep` 干等)。 +4. **阶段 3(npm 首包建档与 Trusted Publisher 一次性引导):** 若 `registry.npmjs.org` 尚无包档(`404`),先开启 `auth-and-writes` 2FA,取 GitHub Release 同字节 `.tgz` 经网页 2FA 执行一次 `npm publish --access public --tag latest --ignore-scripts` 后立即 `npm logout`;再到包 Access 页添加 `GitHub Actions`(`loopx-project` / `loopx` / `dsh-plugin-publish.yml`、`Environment name` 留空、必须勾选 **`Allow npm publish`**),随后重跑 `dsh-plugin-publish.yml` 验签。 +5. **阶段 4(全端回读与 `stable` 推广):** 运行 `release_multi_surface_preflight.py --online --require-published` 与 `verify-distribution.mjs`,核对全部校验和/证明/更新清单/飞书链接/Release 正文哈希无误后推广 `origin/stable`。 + ## Public Release Timeline The public GitHub release timeline starts at `v0.1.3`. Earlier work should be @@ -1068,8 +1159,12 @@ path, and canary route rather than as a user-facing release baseline. `LoopX_2.4.0_x64_en-US.msi`. The companion [DSH plugin 0.1.1-beta.7](https://github.com/loopx-project/loopx/releases/tag/dsh-loopx-plugin-v0.1.1-beta.7) - GitHub prerelease tarball targets LoopX 2.4.0+ and DSH `0.2.2-rc.1..rc.3` - (npm trusted publishing remains gated on npmjs owner setup). + is published on both GitHub Releases (targeting LoopX 2.4.0+ and DSH + `0.2.2-rc.1..rc.3`), + [npm (`dsh-loopx-plugin`)](https://www.npmjs.com/package/dsh-loopx-plugin), and + the `awesome-dsh-plugin` marketplace catalog + (`awesome-dsh-plugin#17660`); token-free CI OIDC awaits final Trusted + Publisher confirmation on npmjs. [Published release](https://github.com/loopx-project/loopx/releases/tag/v2.4.0), [PyPI packages](https://pypi.org/project/loopx/2.4.0/#files), [Personal illustrated guide](https://my.feishu.cn/docx/JXvbdWcFDoZJgvxktvScYfJwnRf). diff --git a/docs/quota-allocation.md b/docs/quota-allocation.md index ca193f0edd..ebb039bb39 100644 --- a/docs/quota-allocation.md +++ b/docs/quota-allocation.md @@ -276,6 +276,26 @@ Controller 停止或恢复均沿用该记录。对已启用的 Goal 再次恢复 重新判定。未绑定的等待 Turn 在恢复后取得资格时,在同一把锁内追加首次准入回执, 后续重放复用该回执。 +If the canonical File or SQLite lease has replaced the original prepared +generation and neither writeback nor debit has started, recovery reports +`execution_loss_closeout` for the original Turn. Read the current Todo lease +and use the projected `refresh-state --execution-loss-closeout --dry-run` with +the original Goal, Agent, Todo and Turn plus the current control-writer proof. +The preview checks the same fences as commit. Execute the same command without +`--dry-run` after the preview qualifies, then read back +`typed_blocked_writeback_no_spend`. The original work admission stays intact +and the Todo remains open for a separately admitted Turn. An absent or +foreign control-writer proof holds settlement. A replacement lease cannot +authorize business delivery for the old Turn. + +原准入租约已被 File 或 SQLite 权威确认换代,且原 Turn 的写回与扣额都尚未开始时, +恢复决策会指向该 Turn 的 `execution_loss_closeout`。先读当前 Todo 租约,用原 +Goal、Agent、Todo 与 Turn 身份及当前控制写入凭据运行投影的 +`refresh-state --execution-loss-closeout --dry-run`。预览通过后再去掉 +`--dry-run` 提交,读回 `typed_blocked_writeback_no_spend`。原准入回执保留, +Todo 仍可由新 Turn 依法接续。当前控制写入凭据缺失或归属其他 Agent 时保持等待, +新租约不授予旧 Turn 的业务交付权。 + An admitted advancement Todo can also become persistently `blocked` through its ordinary owner-authorized lifecycle. Its original Turn then offers the same blocked writeback command. The settlement owner freezes the current diff --git a/docs/reference/goal-acceptance-observations.md b/docs/reference/goal-acceptance-observations.md index 345ee46471..cc0ff5ef8e 100644 --- a/docs/reference/goal-acceptance-observations.md +++ b/docs/reference/goal-acceptance-observations.md @@ -163,7 +163,9 @@ Goal 完成;要求/工作变化使依据过期,产物修改后须重新核 Native `goal-acceptance` and outcome-update `refresh-state` rejections retain their stable error code. A known outcome validation rule also supplies optional -`error_detail`, such as `source ref must be an opaque identifier`, in JSON and +`error_detail`, such as +`source ref must be an opaque identifier (ASCII letters/digits and . _ : @ -, no '/' paths or spaces)`, +in JSON and Markdown. This detail contains fixed rule text and validator-measured byte counts, never the rejected value or provider/IO context. Validation rejection writes nothing: after confirming that result, correct the document and retry @@ -183,7 +185,7 @@ other available Goals. 中文:原生 `goal-acceptance` 和成果更新 `refresh-state` 拒绝保留稳定错误码。 已知成果校验规则还会在 JSON 与 Markdown 中提供可选 `error_detail`,例如 -`source ref must be an opaque identifier`。详情只包含固定规则及校验器实测字节数,不回显被拒值或 +`source ref must be an opaque identifier (ASCII letters/digits and . _ : @ -, no '/' paths or spaces)`。详情只包含固定规则及校验器实测字节数,不回显被拒值或 provider/IO 上下文。校验拒绝不写入状态;确认这一结果后,修正文档并沿用原操作和 仍有效的 provider revision 重试。写入结果不确定时继续遵循原有回执与恢复规则。 成功操作和未标记错误保持既有行为。 diff --git a/docs/reference/protocols/loopx-turn-v0.md b/docs/reference/protocols/loopx-turn-v0.md index 0027a3b7c2..d78e4444d9 100644 --- a/docs/reference/protocols/loopx-turn-v0.md +++ b/docs/reference/protocols/loopx-turn-v0.md @@ -1139,6 +1139,24 @@ sessions retain their existing Todo-bound approval/handoff contract; this CLI option applies to exec conversations. Other hosts retain their adapter's Todo-based session contract. +For a managed `turn run-once --host codex-cli --codex-operation-tools` +invocation, set `LOOPX_CODEX_OPERATION_WORKER_USER` and +`LOOPX_CODEX_OPERATION_WORKER_HOME` to opt into Linux process isolation. The +Core launcher needs root authority to start the app server as the named +unprivileged Worker. Provision the absolute Worker home and its `.codex` +directory with mode `0700` and Worker ownership. Configure model access in +that account. The Core environment is excluded, and the app server starts +without supplementary groups or the ability to gain privileges on exec. + +Use a read-only sandbox and omit a Core-provided MCP server. The Core runtime +root and owning project registry directory must be private, Core-owned +physical directories with protected ancestors. The Worker profile is bound +to the native session. +Core rechecks current Goal authority at durable writeback, and the existing +Turn journal keeps its original effect identity and recovery rules. This +profile protects local LoopX writeback. Additional business write endpoints +need their own credentials and authorization checks. + Use a new `turn_instance_id` for each new iteration. Reuse the same id only for an explicit replay or failed-Turn recovery. The context policy controls Host memory, while the TurnEnvelope and durable LoopX frontier remain the sole diff --git a/loopx/canary/module_metric_baseline.json b/loopx/canary/module_metric_baseline.json index a8d626f2eb..54735f7368 100644 --- a/loopx/canary/module_metric_baseline.json +++ b/loopx/canary/module_metric_baseline.json @@ -101,6 +101,11 @@ "dict_any_count": 0, "lines": 1109 }, + "loopx/control_plane/todos/contract.py": { + "any_count": 0, + "dict_any_count": 0, + "lines": 1274 + }, "loopx/control_plane/todos/quota_summary.py": { "any_count": 0, "dict_any_count": 0, @@ -121,8 +126,9 @@ "lines": 627 }, "loopx/extensions/lark/goal_topic_runtime.py": { - "any_count": 56, - "dict_any_count": 0 + "any_count": 0, + "dict_any_count": 0, + "lines": 1617 }, "loopx/extensions/lark/manager_returns.py": { "any_count": 0, @@ -143,8 +149,9 @@ "lines": 1199 }, "loopx/history.py": { - "any_count": 51, - "dict_any_count": 0 + "any_count": 0, + "dict_any_count": 0, + "lines": 1035 }, "loopx/pr_review.py": { "any_count": 49, @@ -174,9 +181,9 @@ "dict_any_count": 0 }, "loopx/status.py": { - "any_count": 180, + "any_count": 0, "dict_any_count": 0, - "lines": 1999 + "lines": 1339 }, "loopx/todos.py": { "any_count": 0, diff --git a/loopx/capabilities/agent_turn_recall/runtime.py b/loopx/capabilities/agent_turn_recall/runtime.py index 5eaca95d6f..f384764e3d 100644 --- a/loopx/capabilities/agent_turn_recall/runtime.py +++ b/loopx/capabilities/agent_turn_recall/runtime.py @@ -3,7 +3,6 @@ import hashlib import json import os -import re import tempfile from collections.abc import Mapping from datetime import datetime, timezone @@ -12,6 +11,7 @@ from ...history import load_registry from ...materials import find_registry_goal, goal_repo +from ...paths import PATH_SEGMENT_UNSAFE_RE from ..context_providers.base import ContextProvider from ..reward_memory.experiment import ( resolve_reward_memory_experiment, @@ -27,11 +27,10 @@ AGENT_TURN_RECALL_RECEIPT_SCHEMA_VERSION = "agent_turn_recall_receipt_v1" -_SAFE_PATH_TOKEN = re.compile(r"[^A-Za-z0-9._-]+") def _safe_token(value: str, *, fallback: str) -> str: - readable = _SAFE_PATH_TOKEN.sub("-", value).strip("-") or fallback + readable = PATH_SEGMENT_UNSAFE_RE.sub("-", value).strip("-") or fallback digest = hashlib.sha256(value.encode("utf-8")).hexdigest()[:12] return f"{readable[:60]}-{digest}" diff --git a/loopx/capabilities/native_chat/codex_context.py b/loopx/capabilities/native_chat/codex_context.py index 572bc70f7f..5368edef97 100644 --- a/loopx/capabilities/native_chat/codex_context.py +++ b/loopx/capabilities/native_chat/codex_context.py @@ -10,7 +10,10 @@ import os import sys from pathlib import Path -from typing import Any, Mapping +from typing import TYPE_CHECKING, Any, Mapping + +if TYPE_CHECKING: + from ...control_plane.turn_driver.codex_worker_identity import CodexWorkerIdentity def codex_home(base_home: Path, policy: Mapping[str, Any] | None) -> Path: @@ -115,6 +118,16 @@ def process_environment(home: Path, *, isolated: bool) -> dict[str, str]: return env +def process_profile(configured_home: Path | None, policy: Mapping[str, Any] | None, + isolated: bool, worker: CodexWorkerIdentity | None) -> tuple[Path, Path, dict[str, str]]: + """Resolve the host store and environment without preparing Worker-owned paths as Core.""" + if worker is not None: + return worker.codex_home, worker.codex_home, worker.environment + base = (configured_home or Path(os.environ.get("CODEX_HOME") or "~/.codex")).expanduser().resolve() + home = codex_home(base, policy) + return base, home, process_environment(home, isolated=isolated) + + def shared_chatgpt_transport(host_config: Mapping[str, Any], native_config: Mapping[str, Any], *, provider: str = "loopx_host_chatgpt_http") -> dict[str, Any]: """Use native HTTP for the trusted-host ChatGPT auth bridge. diff --git a/loopx/capabilities/native_chat/github_pr_evidence.py b/loopx/capabilities/native_chat/github_pr_evidence.py index 94834bfdc2..a9f5c5b436 100644 --- a/loopx/capabilities/native_chat/github_pr_evidence.py +++ b/loopx/capabilities/native_chat/github_pr_evidence.py @@ -3,6 +3,7 @@ from __future__ import annotations import configparser +from datetime import datetime, timezone import json from pathlib import Path import re @@ -41,6 +42,44 @@ {"FAILURE", "TIMED_OUT", "CANCELLED", "ACTION_REQUIRED", "STARTUP_FAILURE"} ) _CHECK_PASS_CONCLUSIONS = frozenset({"SUCCESS", "NEUTRAL", "SKIPPED"}) +_KNOWN_BOT_LOGINS = frozenset( + {"mergify", "codecov", "codecov-commenter", "github-actions", "dependabot"} +) +_MAINTAINER_ASSOCIATIONS = frozenset({"OWNER", "MEMBER", "COLLABORATOR"}) +_NON_MAINTAINER_ASSOCIATIONS = frozenset( + {"NONE", "CONTRIBUTOR", "FIRST_TIMER", "FIRST_TIME_CONTRIBUTOR", "MANNEQUIN"} +) + + +def _parse_iso_timestamp(value: Any) -> tuple[datetime, str] | None: + raw = str(value or "").strip() + if not raw: + return None + normalized = f"{raw[:-1]}+00:00" if raw.endswith("Z") else raw + try: + dt = datetime.fromisoformat(normalized) + except ValueError: + return None + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) + else: + dt = dt.astimezone(timezone.utc) + return dt, raw + + +def _is_bot_login(login: str) -> bool: + cleaned = str(login or "").strip().casefold() + return not cleaned or cleaned.endswith("[bot]") or cleaned in _KNOWN_BOT_LOGINS + + +def _is_bot_actor(raw_user: Any, login: str) -> bool: + if _is_bot_login(login): + return True + if isinstance(raw_user, Mapping): + actor_type = str(raw_user.get("__typename") or raw_user.get("type") or "").strip().casefold() + if actor_type == "bot": + return True + return False def normalize_github_repo_slug(value: Any) -> str | None: @@ -275,6 +314,102 @@ def _actor_actionable_verdict(record: Mapping[str, Any]) -> str | None: return None +def _post_reply_role( + entry: Mapping[str, Any], + *, + pr_author: str, + rc_reviewer_logins: set[str], +) -> tuple[int, str] | None: + raw_user = entry.get("author") or entry.get("user") or {} + login = str(raw_user.get("login") if isinstance(raw_user, Mapping) else "").strip() + if _is_bot_actor(raw_user, login): + return None + if pr_author and login.casefold() == pr_author.casefold(): + return 1, "author" + assoc = str(entry.get("authorAssociation") or entry.get("author_association") or "").strip().upper() + if assoc in _MAINTAINER_ASSOCIATIONS or ( + bool(login) and login.casefold() in rc_reviewer_logins and assoc not in _NON_MAINTAINER_ASSOCIATIONS + ): + return 0, "maintainer" + return None + + +def _summarize_request_changes_stall( + row: Mapping[str, Any], + *, + raw_reviews: Sequence[Mapping[str, Any]], + latest_record_by_actor: Mapping[tuple[str, str], tuple[str, dict[str, Any]]], + head_oid: str, + pr_author: str, +) -> tuple[str | None, str | None, bool, bool]: + rc_candidates: list[tuple[datetime, str, dict[str, Any], str]] = [] + for verdict_val, rec in latest_record_by_actor.values(): + if verdict_val != "REQUEST_CHANGES": + continue + parsed = _parse_iso_timestamp(rec.get("submitted_at")) + if parsed is not None: + rc_candidates.append((parsed[0], str(rec.get("id") or ""), rec, parsed[1])) + if not rc_candidates: + return None, None, False, False + latest_rc_dt, _latest_id, latest_rec, rc_iso = max( + rc_candidates, key=lambda item: (item[0], item[1]) + ) + latest_rc_review_id = latest_rec.get("id") + rc_reviewer_logins = { + str(rec.get("author_login") or "").strip().casefold() + for _dt, _rid, rec, _iso in rc_candidates + if rec.get("author_login") and not rec.get("author_is_pr_author") + } + anchors: list[tuple[datetime, str]] = [(latest_rc_dt, rc_iso)] + for commit_key in ("headCommitPushedAt", "headCommitCommittedAt"): + parsed_commit = _parse_iso_timestamp(row.get(commit_key)) + if parsed_commit is not None: + anchors.append(parsed_commit) + stalled_anchor_dt, stalled_since = max(anchors, key=lambda pair: pair[0]) + + earliest_comment_dt: datetime | None = None + has_post_anchor_comment_reply = False + post_replies: list[tuple[datetime, int, str]] = [] + for comment in row.get("comments") or []: + if not isinstance(comment, Mapping): + continue + parsed_ts = _parse_iso_timestamp(comment.get("createdAt") or comment.get("created_at")) + if parsed_ts is None: + continue + if earliest_comment_dt is None or parsed_ts[0] < earliest_comment_dt: + earliest_comment_dt = parsed_ts[0] + if parsed_ts[0] <= stalled_anchor_dt: + continue + role_info = _post_reply_role(comment, pr_author=pr_author, rc_reviewer_logins=rc_reviewer_logins) + if role_info is not None: + has_post_anchor_comment_reply = True + post_replies.append((parsed_ts[0], role_info[0], role_info[1])) + + for review in raw_reviews: + if str(review.get("state") or "").strip().upper() != "COMMENTED": + continue + parsed_ts = _parse_iso_timestamp(review.get("submittedAt") or review.get("submitted_at")) + if parsed_ts is None or parsed_ts[0] <= stalled_anchor_dt: + continue + if _extract_review_record(review, head_oid=head_oid, pr_author=pr_author)["valid_verdict_review"]: + continue + role_info = _post_reply_role(review, pr_author=pr_author, rc_reviewer_logins=rc_reviewer_logins) + if role_info is not None: + post_replies.append((parsed_ts[0], role_info[0], role_info[1])) + + post_replies.sort(key=lambda item: (item[0], item[1])) + author_replied = bool(pr_author and post_replies and post_replies[-1][2] == "author") + # GraphQL comments(last: N) returns a newest-last suffix, so coverage is complete when + # there is no earlier page, the fetched suffix reaches the anchor, or a newer reply + # from the PR author or a maintainer in the visible suffix supersedes older comments. + comments_coverage_complete = ( + row.get("commentsHasPreviousPage") is not True + or (earliest_comment_dt is not None and earliest_comment_dt <= stalled_anchor_dt) + or has_post_anchor_comment_reply + ) + return latest_rc_review_id, stalled_since, author_replied, not comments_coverage_complete + + def summarize_github_pr_signal(row: Mapping[str, Any]) -> dict[str, Any]: """Project compact, deterministic exact-head review, check, and gate facts.""" head_oid = str(row.get("headRefOid") or "").strip() @@ -297,6 +432,7 @@ def summarize_github_pr_signal(row: Mapping[str, Any]) -> dict[str, Any]: exact_reviews.sort(key=lambda item: (item["submitted_at"] or "", item["id"] or "")) latest_by_actor: dict[tuple[str, str], str | None] = {} + latest_record_by_actor: dict[tuple[str, str], tuple[str, dict[str, Any]]] = {} inconsistent_verdict = False for record in exact_reviews: actionable = _actor_actionable_verdict(record) @@ -308,11 +444,24 @@ def summarize_github_pr_signal(row: Mapping[str, Any]) -> dict[str, Any]: ) if actionable == "DISMISSED": latest_by_actor.pop(actor_key, None) + latest_record_by_actor.pop(actor_key, None) elif actionable == "CONFLICT": inconsistent_verdict = True latest_by_actor[actor_key] = "REQUEST_CHANGES" + latest_record_by_actor[actor_key] = ("REQUEST_CHANGES", record) else: latest_by_actor[actor_key] = actionable + latest_record_by_actor[actor_key] = (actionable, record) + + latest_rc_review_id, stalled_since, author_replied_after_rc, comments_coverage_incomplete = ( + _summarize_request_changes_stall( + row, + raw_reviews=raw_reviews, + latest_record_by_actor=latest_record_by_actor, + head_oid=head_oid, + pr_author=pr_author, + ) + ) verdicts = {val for val in latest_by_actor.values() if val} review_decision = str(row.get("reviewDecision") or "").strip().upper() @@ -363,11 +512,18 @@ def summarize_github_pr_signal(row: Mapping[str, Any]) -> dict[str, Any]: "mergeStateStatus": row.get("mergeStateStatus"), "mergeable": row.get("mergeable"), "updatedAt": row.get("updatedAt"), + "stalled_since": stalled_since, + "author_replied_after_request_changes": author_replied_after_rc, + "comments_coverage_incomplete": comments_coverage_incomplete, "checks_summary": checks_summary, "review_summary": { "effective_verdict": effective_verdict, "has_review_conflict": has_conflict, "stale_review_count": stale_count, + "latest_request_changes_review_id": latest_rc_review_id, + "stalled_since": stalled_since, + "author_replied_after_request_changes": author_replied_after_rc, + "comments_coverage_incomplete": comments_coverage_incomplete, "exact_head_reviews": exact_reviews, }, "bypassed_gates": bypassed_gates, @@ -382,6 +538,27 @@ def summarize_github_pr_signal(row: Mapping[str, Any]) -> dict[str, Any]: _GITHUB_PR_LIST_PAGE_SIZE = 20 _GITHUB_PR_LIST_MAX_PAGES = 5 +_GITHUB_PR_COMMENT_MAX_BACKFILL_PAGES = 3 +_GITHUB_PR_COMMENTS_PAGE_QUERY = """query($owner: String!, $name: String!, $number: Int!, $before: String!) { + repository(owner: $owner, name: $name) { + pullRequest(number: $number) { + comments(last: 50, before: $before) { + pageInfo { + hasPreviousPage + startCursor + } + nodes { + createdAt + authorAssociation + author { + __typename + login + } + } + } + } + } +}""" _GITHUB_OPEN_PRS_GRAPHQL_QUERY = """query($owner: String!, $name: String!, $cursor: String) { repository(owner: $owner, name: $name) { pullRequests( @@ -409,13 +586,29 @@ def summarize_github_pr_signal(row: Mapping[str, Any]) -> dict[str, Any]: author { login } + comments(last: 20) { + pageInfo { + hasPreviousPage + startCursor + } + nodes { + createdAt + authorAssociation + author { + __typename + login + } + } + } reviews(last: 20) { nodes { id state submittedAt body + authorAssociation author { + __typename login } commit { @@ -426,6 +619,9 @@ def summarize_github_pr_signal(row: Mapping[str, Any]) -> dict[str, Any]: commits(last: 1) { nodes { commit { + oid + committedDate + pushedDate statusCheckRollup { contexts(first: 30) { nodes { @@ -460,15 +656,41 @@ def _normalize_graphql_pr_node(node: Mapping[str, Any]) -> dict[str, Any]: else: reviews = [] + raw_comments = node.get("comments") + comments_page_info: Mapping[str, Any] = {} + if isinstance(raw_comments, Mapping): + raw_nodes = raw_comments.get("nodes") + comments = [item for item in raw_nodes if isinstance(item, Mapping)] if isinstance(raw_nodes, list) else [] + raw_page_info = raw_comments.get("pageInfo") + if isinstance(raw_page_info, Mapping): + comments_page_info = raw_page_info + elif isinstance(raw_comments, list): + comments = [item for item in raw_comments if isinstance(item, Mapping)] + else: + comments = [] + comments_has_previous_page = bool(comments_page_info.get("hasPreviousPage") is True) + comments_start_cursor = str(comments_page_info.get("startCursor") or "").strip() or None + + raw_commits = node.get("commits") + commit_nodes = raw_commits.get("nodes") if isinstance(raw_commits, Mapping) else None + first_commit = ( + commit_nodes[0].get("commit") + if isinstance(commit_nodes, list) and commit_nodes and isinstance(commit_nodes[0], Mapping) + else None + ) + head_oid = str(node.get("headRefOid") or "").strip() + head_committed_at = node.get("headCommitCommittedAt") + head_pushed_at = node.get("headCommitPushedAt") + if isinstance(first_commit, Mapping): + commit_oid = str(first_commit.get("oid") or "").strip() + if not commit_oid or not head_oid or commit_oid.casefold() == head_oid.casefold(): + if head_committed_at is None: + head_committed_at = first_commit.get("committedDate") + if head_pushed_at is None: + head_pushed_at = first_commit.get("pushedDate") + rollup = node.get("statusCheckRollup") if rollup is None: - raw_commits = node.get("commits") - commit_nodes = raw_commits.get("nodes") if isinstance(raw_commits, Mapping) else None - first_commit = ( - commit_nodes[0].get("commit") - if isinstance(commit_nodes, list) and commit_nodes and isinstance(commit_nodes[0], Mapping) - else None - ) raw_rollup = first_commit.get("statusCheckRollup") if isinstance(first_commit, Mapping) else None raw_contexts = raw_rollup.get("contexts") if isinstance(raw_rollup, Mapping) else None context_nodes = raw_contexts.get("nodes") if isinstance(raw_contexts, Mapping) else None @@ -487,20 +709,100 @@ def _normalize_graphql_pr_node(node: Mapping[str, Any]) -> dict[str, Any]: "mergeStateStatus": node.get("mergeStateStatus"), "mergeable": node.get("mergeable"), "updatedAt": node.get("updatedAt"), + "headCommitCommittedAt": head_committed_at, + "headCommitPushedAt": head_pushed_at, + "comments": comments, + "commentsHasPreviousPage": comments_has_previous_page, + "commentsStartCursor": comments_start_cursor, "reviews": reviews, "statusCheckRollup": rollup, } +def _backfill_pr_comments_if_needed( + norm_node: dict[str, Any], + summary: dict[str, Any], + *, + owner: str, + name: str, + number: int, + runner: Callable[..., Any], +) -> dict[str, Any]: + """Boundedly backfill older PR comment pages when active RC reply coverage is truncated.""" + attempts = 0 + while ( + summary.get("comments_coverage_incomplete") is True + and attempts < _GITHUB_PR_COMMENT_MAX_BACKFILL_PAGES + ): + comment_cursor = str(norm_node.get("commentsStartCursor") or "").strip() + if not comment_cursor: + break + attempts += 1 + try: + completed = runner( + [ + "gh", + "api", + "graphql", + "-f", + f"query={_GITHUB_PR_COMMENTS_PAGE_QUERY}", + "-f", + f"owner={owner}", + "-f", + f"name={name}", + "-F", + f"number={number}", + "-f", + f"before={comment_cursor}", + ], + capture_output=True, + text=True, + check=False, + timeout=20, + ) + except (OSError, ValueError, TypeError, subprocess.TimeoutExpired): + break + if completed.returncode != 0: + break + try: + payload = json.loads(completed.stdout or "{}") + except (ValueError, TypeError): + break + if not isinstance(payload, Mapping) or payload.get("errors"): + break + data = payload.get("data") + repo = data.get("repository") if isinstance(data, Mapping) else None + pr_data = repo.get("pullRequest") if isinstance(repo, Mapping) else None + comments_conn = pr_data.get("comments") if isinstance(pr_data, Mapping) else None + older_nodes = comments_conn.get("nodes") if isinstance(comments_conn, Mapping) else None + page_info = comments_conn.get("pageInfo") if isinstance(comments_conn, Mapping) else None + if not isinstance(older_nodes, list) or not isinstance(page_info, Mapping): + break + older_comments = [item for item in older_nodes if isinstance(item, Mapping)] + next_has_prev = page_info.get("hasPreviousPage") is True + next_cursor = str(page_info.get("startCursor") or "").strip() or None + stalled_cursor = next_has_prev and (not next_cursor or next_cursor == comment_cursor) + norm_node["comments"] = [*older_comments, *norm_node["comments"]] + norm_node["commentsHasPreviousPage"] = next_has_prev + norm_node["commentsStartCursor"] = None if stalled_cursor else next_cursor + summary = summarize_github_pr_signal(norm_node) + if stalled_cursor: + break + return summary + + def observe_github_repository_prs( - repo_slug: str, *, runner: Callable[..., Any] = subprocess.run + repo_slug: str, + *, + runner: Callable[..., Any] = subprocess.run, + backfill_comments: bool = False, ) -> dict[str, Any]: """Read bounded public/authorized open PR signal metadata without side effects.""" normalized = normalize_github_repo_slug(repo_slug) if not normalized or "/" not in normalized: return {"status": "unavailable", "repository": repo_slug} owner, name = normalized.split("/", 1) - by_number: dict[int, dict[str, Any]] = {} + raw_nodes_by_number: dict[int, Mapping[str, Any]] = {} cursor: str | None = None try: for page_index in range(_GITHUB_PR_LIST_MAX_PAGES): @@ -540,7 +842,7 @@ def observe_github_repository_prs( continue number = int(node.get("number") or 0) if number > 0: - by_number[number] = summarize_github_pr_signal(_normalize_graphql_pr_node(node)) + raw_nodes_by_number[number] = node page_info = pull_requests.get("pageInfo") if not isinstance(page_info, Mapping) or page_info.get("hasNextPage") is not True: break @@ -550,7 +852,20 @@ def observe_github_repository_prs( return {"status": "unavailable", "repository": repo_slug} break cursor = next_cursor - items = [by_number[num] for num in sorted(by_number)] + items: list[dict[str, Any]] = [] + for number in sorted(raw_nodes_by_number): + norm_node = _normalize_graphql_pr_node(raw_nodes_by_number[number]) + summary = summarize_github_pr_signal(norm_node) + if backfill_comments: + summary = _backfill_pr_comments_if_needed( + norm_node, + summary, + owner=owner, + name=name, + number=number, + runner=runner, + ) + items.append(summary) return {"status": "ok", "repository": repo_slug, "items": items} except (OSError, ValueError, TypeError, subprocess.TimeoutExpired): return {"status": "unavailable", "repository": repo_slug} diff --git a/loopx/capabilities/native_chat/steward_monitor.py b/loopx/capabilities/native_chat/steward_monitor.py index ddfe008552..1df0861845 100644 --- a/loopx/capabilities/native_chat/steward_monitor.py +++ b/loopx/capabilities/native_chat/steward_monitor.py @@ -9,13 +9,15 @@ from datetime import datetime, timedelta, timezone import hashlib +import inspect import json import logging +import math from pathlib import Path import re import subprocess import time -from typing import Any, Mapping +from typing import Any, Callable, Mapping from ...agent_registry import load_goal_from_registry from ...chat_store import _atomic_write_json @@ -202,9 +204,35 @@ def _github_repo_slug(task_repository: Any) -> str | None: return slug if _REPO_PATTERN.fullmatch(slug) else None -def _observe_github_repository_prs(repo_slug: str) -> dict[str, Any]: +def _observe_github_repository_prs( + repo_slug: str, *, backfill_comments: bool = False +) -> dict[str, Any]: """Read bounded public/authorized open PR signal metadata without side effects.""" - return observe_github_repository_prs(repo_slug, runner=subprocess.run) + return observe_github_repository_prs( + repo_slug, runner=subprocess.run, backfill_comments=backfill_comments + ) + + +def _signal_scope_uses_stalled_age(signal_scope: Mapping[str, Any] | None) -> bool: + if not isinstance(signal_scope, Mapping): + return False + pr_filter = signal_scope.get("pr_filter") + if not isinstance(pr_filter, Mapping): + return False + min_stalled_hours = pr_filter.get("min_stalled_hours") + return ( + isinstance(min_stalled_hours, (int, float)) + and not isinstance(min_stalled_hours, bool) + and math.isfinite(float(min_stalled_hours)) + and float(min_stalled_hours) > 0 + ) + + +def _accepts_backfill_comments(fn: Callable[..., Any]) -> bool: + params = inspect.signature(fn).parameters + return "backfill_comments" in params or any( + param.kind is inspect.Parameter.VAR_KEYWORD for param in params.values() + ) _MONITOR_TARGET_KEY_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,119}$") @@ -501,7 +529,13 @@ def _collect_signal_monitor(self, actor: dict[str, Any], context: dict[str, Any] else: inbox_items = [] repo_slug = _github_repo_slug(todo.get("task_repository")) - repo_snapshot = _observe_github_repository_prs(repo_slug) if repo_slug else None + backfill_comments = _signal_scope_uses_stalled_age(signal_scope) + if not repo_slug: + repo_snapshot = None + elif backfill_comments and _accepts_backfill_comments(_observe_github_repository_prs): + repo_snapshot = _observe_github_repository_prs(repo_slug, backfill_comments=True) + else: + repo_snapshot = _observe_github_repository_prs(repo_slug) observed_at = now_utc().isoformat() signal_request: dict[str, Any] = { "portfolio_observation": portfolio, diff --git a/loopx/capabilities/native_chat/steward_turn.py b/loopx/capabilities/native_chat/steward_turn.py index a312a97ee1..c40b543af0 100644 --- a/loopx/capabilities/native_chat/steward_turn.py +++ b/loopx/capabilities/native_chat/steward_turn.py @@ -1667,7 +1667,7 @@ def run(native_request: Mapping[str, Any], launch_scope: Any) -> dict[str, Any]: followup_ctx = self._steward_followup_context(actor, session_id, request, authority) prompt += ( "\nSteward advancement instructions: Evaluate the monitor prompt and signal snapshot against authorized recipients (`context_delegation.targets`), prior receipts (`prior_handoff_receipts`, avoid duplicate delivery for unchanged PR@headRefOid), and open user todos (`open_user_todos`). " - "When `signal_snapshot.repository_snapshot.items` is present, each PR carries `mergeable`, `checks_summary`, `bypassed_gates`, and `review_summary` (`effective_verdict`, `has_review_conflict`, `stale_review_count`, `exact_head_reviews` with `reviewer_declaration`, `valid_verdict_review`, `author_owned_fallback`). Keep triage read-only; never execute merges here. " + "When `signal_snapshot.repository_snapshot.items` is present, each PR carries `mergeable`, `checks_summary`, `bypassed_gates`, `stalled_since`, `author_replied_after_request_changes`, optional `stalled_bucket` (`awaiting_maintainer_reply` | `under_24h` | `24h_to_72h` | `72h_plus` | `7d_plus`), and `review_summary` (`effective_verdict`, `has_review_conflict`, `stale_review_count`, `latest_request_changes_review_id`, `stalled_since`, `author_replied_after_request_changes`, `exact_head_reviews` with `reviewer_declaration`, `valid_verdict_review`, `author_owned_fallback`). Keep triage read-only; never execute merges here. " "You may include optional top-level JSON fields alongside the normal kernel fields: " "`context_handoff` (single object or array <=32 of {goal_id, agent_id, brief} with `schema_version='collaboration_brief_v0'` and `inputs=[]` when referencing URLs/PRs, restricted to `context_delegation.targets`), " "`steward_owner_report` (optional non-empty Markdown string <=24000 chars or `{markdown}` delivered once directly to the bound Steward App and Feishu conversation; omit or set `null` when silent/no report should be sent), " diff --git a/loopx/capabilities/reward_memory/outcome_lifecycle.py b/loopx/capabilities/reward_memory/outcome_lifecycle.py index 7d37b96d76..9039f5b19d 100644 --- a/loopx/capabilities/reward_memory/outcome_lifecycle.py +++ b/loopx/capabilities/reward_memory/outcome_lifecycle.py @@ -3,7 +3,6 @@ import hashlib import json import os -import re import tempfile from collections.abc import Mapping from datetime import datetime, timezone @@ -13,6 +12,7 @@ from ...control_plane.runtime.public_safety import public_safe_compact_text from ...history import load_registry from ...materials import find_registry_goal, goal_repo +from ...paths import PATH_SEGMENT_UNSAFE_RE from ..context_providers.base import ContextProvider from .experiment import ( resolve_reward_memory_experiment, @@ -37,7 +37,6 @@ LEGACY_PENDING_MIGRATION_SCHEMA_VERSION = ( "turn_reward_memory_legacy_pending_migration_v0" ) -_SAFE_PATH_TOKEN = re.compile(r"[^A-Za-z0-9._-]+") _PENDING_PROVIDER_STATUSES = { "committed_pending", "provider_unavailable", @@ -92,7 +91,7 @@ def _base( def _identity_token(value: str, *, fallback: str) -> str: - readable = _SAFE_PATH_TOKEN.sub("-", str(value or "")).strip("-") or fallback + readable = PATH_SEGMENT_UNSAFE_RE.sub("-", str(value or "")).strip("-") or fallback digest = hashlib.sha256(str(value or "").encode("utf-8")).hexdigest()[:12] return f"{readable[:60]}-{digest}" diff --git a/loopx/capabilities/steward_memory/runtime.py b/loopx/capabilities/steward_memory/runtime.py index 3d9f1ce556..0abd96f7cf 100644 --- a/loopx/capabilities/steward_memory/runtime.py +++ b/loopx/capabilities/steward_memory/runtime.py @@ -3,7 +3,6 @@ import json import os -import re import shutil import subprocess import tempfile @@ -17,6 +16,7 @@ from ...control_plane.effect_runtime import EffectRuntimeRejected, effect_runtime_result from ...control_plane.runtime.public_safety import public_safe_compact_text +from ...paths import PATH_SEGMENT_UNSAFE_RE from ..context_providers.openviking_scope import classify_openviking_scope from .machine_defaults import ( DEFAULT_RECALL_TIMEOUT_SECONDS, @@ -35,7 +35,6 @@ SPEAKER_PREFERENCE_CHAR_LIMIT = 1500 EVENT_SNIPPET_CHAR_LIMIT = 600 COMMIT_TIMEOUT_SECONDS = 3.0 -_SAFE_TURN_SEGMENT_RE = re.compile(r"[^A-Za-z0-9._-]+") CommandRunner = Callable[..., subprocess.CompletedProcess[str]] @@ -572,7 +571,7 @@ def recall_steward_memory_for_turn( def _safe_event_filename(turn_id: str) -> str: - cleaned = _SAFE_TURN_SEGMENT_RE.sub("-", str(turn_id or "").strip()).strip("-.")[:64] + cleaned = PATH_SEGMENT_UNSAFE_RE.sub("-", str(turn_id or "").strip()).strip("-.")[:64] if not cleaned: cleaned = f"turn-{int(time.time())}" return f"{cleaned}.md" diff --git a/loopx/chat_agent.py b/loopx/chat_agent.py index e92c1afaf2..35095e5316 100644 --- a/loopx/chat_agent.py +++ b/loopx/chat_agent.py @@ -15,6 +15,7 @@ from pathlib import Path from typing import Any, Callable, Iterator, Mapping +from .control_plane.turn_driver.codex_worker_identity import CodexWorkerIdentity from .presentation.codex_activity import CodexActivitySteps from .chat import ( CHAT_REVIEW_CLOSE_TAG, @@ -539,6 +540,7 @@ def start( launch_guard: Callable[[], AbstractContextManager[None]] | None = None, account_runtime_root: Path | None = None, account_consumer: str = "worker", + worker_identity: CodexWorkerIdentity | None = None, _compatibility_catalog_path: Path | None = None, ) -> "CodexChatAgentSession": resolved = shutil.which(codex_bin) @@ -599,13 +601,8 @@ def start( owner_git_write_roots.append(str(root / ".codex" / "skills")) # Pin the host store explicitly, including compatibility retries. Never # redirect an existing thread by inheriting a different launch context. - base_home = ( - (codex_home or Path(os.environ.get("CODEX_HOME") or "~/.codex")) - .expanduser() - .resolve() - ) - runtime_home = codex_context.codex_home(base_home, policy if project_context is not None else None) - runtime_env = codex_context.process_environment(runtime_home, isolated=bool(permissions_profile)) + base_home, runtime_home, runtime_env = codex_context.process_profile( + codex_home, policy if project_context is not None else None, bool(permissions_profile), worker_identity) # Select an operator-defined native provider for ordinary Chat only. # Codex owns its configuration/authentication; never copy credentials # or replace a resumed thread to change its upstream transport. @@ -620,7 +617,7 @@ def start( provider=provider_override, eligible=not execution_mode, consumer=account_consumer, model=model, environment=runtime_env) command = [resolved, "app-server"] - if permissions_profile: + if permissions_profile or worker_identity is not None: # Keep this native store independent even when the account's # default credential backend is a shared OS keychain. command.extend(["-c", 'cli_auth_credentials_store="file"']) @@ -634,6 +631,8 @@ def start( ] ) command.extend(["--listen", "stdio://"]) + if worker_identity is not None: + command = [worker_identity.setpriv, "--no-new-privs", "--", *command] process = None try: # The admitting caller owns this short launch fence. Native startup @@ -651,6 +650,7 @@ def start( encoding="utf-8", bufsize=1, start_new_session=isolate_process_tree and os.name == "posix", + **(worker_identity.process_options if worker_identity is not None else {}), ) except OSError as exc: raise CodexChatAgentError( @@ -908,7 +908,7 @@ def start( return session except _LegacyModelCatalogSchemaError as exc: session.close() - if _compatibility_catalog_path is not None or fork_thread_id: + if _compatibility_catalog_path is not None or fork_thread_id or worker_identity is not None: raise _model_catalog_compatibility_error() from exc with _current_builtin_model_catalog(resolved, environment=runtime_env) as catalog_path: return cls.start( diff --git a/loopx/cli_commands/project_lifecycle_refresh_state.py b/loopx/cli_commands/project_lifecycle_refresh_state.py index 187d4f9465..b7592838c3 100644 --- a/loopx/cli_commands/project_lifecycle_refresh_state.py +++ b/loopx/cli_commands/project_lifecycle_refresh_state.py @@ -202,6 +202,8 @@ def register_refresh_state_command( refresh_state_parser.add_argument("--goal-instance-id", help=argparse.SUPPRESS) refresh_state_parser.add_argument("--task-lease-idempotency-key", help=argparse.SUPPRESS) refresh_state_parser.add_argument("--task-lease-expected-version", type=int, help=argparse.SUPPRESS) + refresh_state_parser.add_argument("--execution-loss-closeout", action="store_true", + help="Close an original prepared Turn after its execution generation is lost, without debit.") refresh_state_parser.add_argument("--completion-todo-id", help=argparse.SUPPRESS) refresh_state_parser.add_argument("--completion-turn-key", help=argparse.SUPPRESS) refresh_state_parser.add_argument( @@ -449,6 +451,31 @@ def handle_refresh_state_command( if args.command != "refresh-state": return None fmt = output_format(args) + if args.execution_loss_closeout: + from ..control_plane.goals.first_party_host_admission import capture_first_party_host_goal_ref + from ..control_plane.goals.goal_ref_validation import exact_goal_ref + from ..control_plane.quota.execution_preparation import commit_execution_loss_closeout + from .project_lifecycle_inputs import inline_progress_observation + + try: + ref = (exact_goal_ref(args.goal_id, args.goal_instance_id) if args.goal_instance_id + else capture_first_party_host_goal_ref(registry_path=registry_path, goal_id=args.goal_id)) + payload = commit_execution_loss_closeout( + registry_path=registry_path, runtime_root_override=args.runtime_root, + goal_id=args.goal_id, agent_id=args.agent_id or "", todo_id=args.todo_id or "", + turn_instance_id=args.turn_instance_id or "", goal_ref=ref, + requested_proof={"idempotency_key": args.task_lease_idempotency_key, + "expected_version": args.task_lease_expected_version}, + progress_observation=inline_progress_observation(args), + delivery_outcome=args.delivery_outcome, delivery_boundary=args.delivery_boundary, + requested_effects=vars(args), dry_run=args.dry_run, + ) + except (OSError, RuntimeError, TypeError, ValueError) as exc: + code = getattr(exc, "code", None) + payload = {"ok": False, "goal_id": args.goal_id, "appended": False, "error": str(exc), + **({"error_code": code} if isinstance(code, str) else {})} + print_payload(payload, fmt, render_state_refresh_markdown) + return 0 if payload["ok"] is True else 1 agent_vision_packet: dict[str, object] | None = None progress_observation: dict[str, object] | None = None merge_agent_vision_patch = False diff --git a/loopx/cli_commands/quota_native_context.py b/loopx/cli_commands/quota_native_context.py index 94a2a4f568..5445a4a293 100644 --- a/loopx/cli_commands/quota_native_context.py +++ b/loopx/cli_commands/quota_native_context.py @@ -7,7 +7,7 @@ import stat import subprocess import tempfile -from collections.abc import Callable +from collections.abc import Callable, Mapping from contextlib import AbstractContextManager, nullcontext from functools import partial from pathlib import Path @@ -373,7 +373,9 @@ def _handle_context_config( config = codex_context_configuration(directory, goal_id=args.goal_id, agent_id=args.agent_id, cli_argv=cli_argv, scenario=activation["scenario"], session_root=bool(getattr(args, "codex_context_root", None)), inherit_machine=bool(machine_runtime), progressive_enabled=activation["progressive_enabled"], - compact_direct_read=bool(getattr(args, "compact_direct_read", False))) + compact_direct_read=bool(getattr(args, "compact_direct_read", False)), + quiet_turn=bool(getattr(args, "quiet_turn", False)), + epoch_prefetch=getattr(args, "epoch_prefetch_json", None)) explicit_options = "--context-delivery on" if activation["progressive_enabled"] else "--context-delivery off --delta-delivery auto" payload = {"ok": True, "context_delivery": activation, "native_config": config, "activation": "Apply config_overrides, merge hooks and append developer_instructions to the existing native configuration; " @@ -429,8 +431,7 @@ def _handle_context_hook(args: argparse.Namespace, *, activation: dict[str, Any] raise ValueError("context directory unavailable") scenario = activation["scenario"] progressive_enabled = activation["progressive_enabled"] - if getattr(args, "compact_direct_read", False) and "compact_direct_read" not in event: - event = {**event, "compact_direct_read": True} + event = _inject_context_hook_opt_ins(args, event) payload = codex_context_hook(directory, event) request = None preparation_context = "" @@ -528,6 +529,43 @@ def _handle_context_hook(args: argparse.Namespace, *, activation: dict[str, Any] return 0 +def _inject_context_hook_opt_ins(args: argparse.Namespace, event: dict[str, Any]) -> dict[str, Any]: + """Attach explicit default-off CLI hook flags absent from stdin event JSON.""" + updated = dict(event) + if getattr(args, "compact_direct_read", False) and "compact_direct_read" not in updated: + updated["compact_direct_read"] = True + if getattr(args, "quiet_turn", False) and "quiet_turn" not in updated: + updated["quiet_turn"] = True + epoch_prefetch = getattr(args, "epoch_prefetch_json", None) + if isinstance(epoch_prefetch, Mapping) and "epoch_prefetch" not in updated: + updated["epoch_prefetch"] = dict(epoch_prefetch) + return updated + + +def _validate_context_hook_opt_ins(args: argparse.Namespace, print_payload: Callable[..., None]) -> int | None: + """Enforce closed subcommand & shape validation for explicit context hook opt-ins.""" + hook_cmd = args.quota_command in ("context-config", "context-hook") + for flag, attr in ( + ("--compact-direct-read", "compact_direct_read"), + ("--quiet-turn", "quiet_turn"), + ): + if getattr(args, attr, False) and not hook_cmd: + print_payload({"ok": False, "reason": f"{flag} is only supported by context-config or context-hook"}, + args.format, str) + return 1 + epoch_prefetch = getattr(args, "epoch_prefetch_json", None) + if epoch_prefetch is not None: + if not hook_cmd: + print_payload({"ok": False, "reason": "--epoch-prefetch-json is only supported by context-config or context-hook"}, + args.format, str) + return 1 + if not isinstance(epoch_prefetch, dict): + print_payload({"ok": False, "reason": "--epoch-prefetch-json must decode to a JSON object"}, + args.format, str) + return 1 + return None + + def handle_native_context_command(args: argparse.Namespace, *, print_payload: Callable[..., None], registry_path: Path | None = None, runtime_root_arg: str | None = None) -> int | None: """Dispatch captured reads and native lifecycle IO before quota authority access.""" @@ -537,10 +575,9 @@ def handle_native_context_command(args: argparse.Namespace, *, print_payload: Ca print_payload({"ok": False, "reason": "--prepared-claim-operation-id requires quota context-project"}, args.format, str) return 1 - if getattr(args, "compact_direct_read", False) and args.quota_command not in ("context-config", "context-hook"): - print_payload({"ok": False, "reason": "--compact-direct-read is only supported by context-config or context-hook"}, - args.format, str) - return 1 + opt_in_rc = _validate_context_hook_opt_ins(args, print_payload) + if opt_in_rc is not None: + return opt_in_rc if getattr(args, "complete_turn", False) and (args.quota_command != "should-run" or args.format != "json"): print_payload({"ok": False, "reason": "--complete-turn requires JSON quota should-run"}, args.format, str) return 1 diff --git a/loopx/cli_commands/quota_presentation.py b/loopx/cli_commands/quota_presentation.py index ffb29ffe75..daf39dadbf 100644 --- a/loopx/cli_commands/quota_presentation.py +++ b/loopx/cli_commands/quota_presentation.py @@ -73,7 +73,8 @@ def select(source: object, *keys: str) -> dict[str, object]: view = select( payload, "ok", "goal_id", "goal_ref", "runtime_root", "state", - "error", "error_code", "reason", "status", "recommended_action", "effective_action", "should_run", + "decision", "error", "error_code", "reason", "reason_code", "status", + "recommended_action", "effective_action", "should_run", ) if payload.get("ok") is not True: return view @@ -94,6 +95,24 @@ def select(source: object, *keys: str) -> dict[str, object]: ("agent_identity", ("agent_id",)), ("autonomous_replan_obligation", ("required", "obligation_id", "agent_id", "resolution_mode")), ("heartbeat_receipt", ("settlement_identity",)), + ( + "unsettled_host_turn_recovery", + ( + "schema_version", + "state", + "reason_code", + "scope", + "prior_turn_instance_id", + "prior_event_id", + "binding_kind", + "binding_id", + "settlement_effect_id", + "repair", + "missing_receipts", + "admissions_without_progress", + "admission_limit", + ), + ), ): if key in payload: view[key] = select(payload[key], *fields) diff --git a/loopx/cli_commands/quota_registration.py b/loopx/cli_commands/quota_registration.py index b821cd1c60..232465bc83 100644 --- a/loopx/cli_commands/quota_registration.py +++ b/loopx/cli_commands/quota_registration.py @@ -1,6 +1,7 @@ from __future__ import annotations import argparse +import json from ..control_plane.quota.spend_sources import ( DEFAULT_SLOT_SPEND_SOURCE, @@ -275,6 +276,10 @@ def register_quota_command( "context-config renders native configuration for the exact Goal/Agent; no host configuration, trust, guard or spend are changed.") quota_parser.add_argument("--compact-direct-read", action="store_true", help="Opt-in Phase-2 lock-free in-process JSON pointer read, wake deduplication, and automatic failure/obligation extraction for native compact hooks.") + quota_parser.add_argument("--quiet-turn", action="store_true", + help="Opt-in Quiet-Turn zero-tax skip metadata evaluation for native context-config/context-hook (default-off).") + quota_parser.add_argument("--epoch-prefetch-json", type=json.loads, default=None, + help="Opt-in Stage-then-Swap EpochReset prefetch configuration JSON for native context-config/context-hook (default-off).") quota_parser.add_argument("--capture-sha256", help="For context-read, context-project or replan-view: exact SHA-256 supplied with the capture reference.") quota_parser.add_argument("--initial-read", action="store_true", diff --git a/loopx/cli_commands/todo.py b/loopx/cli_commands/todo.py index dd46614ffb..fb8a9e5aa9 100644 --- a/loopx/cli_commands/todo.py +++ b/loopx/cli_commands/todo.py @@ -521,6 +521,7 @@ def handle_todo_command( claim_operation_id=args.claim_operation_id, task_lease_idempotency_key=args.task_lease_idempotency_key, task_lease_expected_version=args.task_lease_expected_version, + ttl_seconds=args.ttl_seconds, **_todo_path_args(args), dry_run=bool(args.dry_run), ) @@ -560,10 +561,22 @@ def handle_todo_command( ] payload["instruction"] = ( "Continue the task. Use this original claim reference for progress " - "or completion; retain normal Turn settlement when applicable." + "or completion; pass --ttl-seconds on claim (1..86400) for long " + "(>45m) execution wakes or renew via `loopx task-lease renew` " + "before lease_expires_at, and retain normal Turn settlement " + "(omitting --next-action on completed-Todo semantic_closeout " + "refresh-state)." ) - # Normal callers need the accepted task reference, not lease - # counters or a second inline copy of the native receipt. + # Extract compact lease deadline/TTL scalars before removing + # internal lease CAS counters or a second copy of the receipt. + lease = payload.get("lease") + if isinstance(lease, dict): + expires_at = lease.get("expires_at") + if isinstance(expires_at, str) and expires_at: + payload["lease_expires_at"] = expires_at + acquire_ttl = lease.get("acquire_ttl_seconds") + if isinstance(acquire_ttl, int) and not isinstance(acquire_ttl, bool): + payload["lease_ttl_seconds"] = acquire_ttl for internal in ( "lease", "lease_changed", diff --git a/loopx/cli_commands/todo_argument_validation.py b/loopx/cli_commands/todo_argument_validation.py index 469b20f582..b612651ef1 100644 --- a/loopx/cli_commands/todo_argument_validation.py +++ b/loopx/cli_commands/todo_argument_validation.py @@ -46,6 +46,7 @@ ("--claimed-by", "claimed_by"), ("--task-lease-idempotency-key", "task_lease_idempotency_key"), ("--task-lease-expected-version", "task_lease_expected_version"), + ("--ttl-seconds", "ttl_seconds"), ("--bound-agent", "bound_agent"), ("--goal-bound", "goal_bound"), ("--blocks-agent", "blocks_agent"), @@ -153,8 +154,8 @@ "plan": frozenset({"text", "agent_id", "project"}), "project-markdown": frozenset({"state_file", "execute", "provider_revision", "project"}), "claim": frozenset({"role", "todo_id", "claimed_by", "agent_id", "state_file", - "claim_operation_id", "task_lease_idempotency_key", "task_lease_expected_version", - "project", "dry_run", "todo_thin"}), + "claim_operation_id", "ttl_seconds", "task_lease_idempotency_key", + "task_lease_expected_version", "project", "dry_run", "todo_thin"}), "update": frozenset(_TODO_UPDATE_MUTABLE_FIELDS) | frozenset({ "role", "todo_id", "agent_id", "state_file", "project", "dry_run", "authority_reason", "claim_operation_id", "update_operation_id", "update_expected_provider_revision", @@ -437,7 +438,7 @@ def validate_todo_claim_options(args: argparse.Namespace) -> None: if unsupported: raise TodoClaimArgumentError( "todo claim only accepts --todo-id, --claimed-by, --agent-id, optional --role, " - "--claim-operation-id, --task-lease-idempotency-key, " + "--claim-operation-id, --ttl-seconds, --task-lease-idempotency-key, " "--task-lease-expected-version, --project, --state-file, --dry-run, and --thin; unsupported: " + ", ".join(unsupported) ) @@ -445,6 +446,16 @@ def validate_todo_claim_options(args: argparse.Namespace) -> None: raise TodoClaimArgumentError( "--task-lease-expected-version requires --task-lease-idempotency-key" ) + if args.ttl_seconds is not None: + if args.ttl_seconds <= 0 or args.ttl_seconds > 86400: + raise ValueError("ttl seconds must be between 1 and 86400") + if args.task_lease_idempotency_key is None and ( + args.agent_id is None or args.agent_id != args.claimed_by + ): + raise ValueError( + "--ttl-seconds requires managed execution (--agent-id matching --claimed-by) " + "or --task-lease-idempotency-key" + ) def validate_todo_update_options(args: argparse.Namespace) -> None: @@ -718,6 +729,8 @@ def validate_shared_todo_options(args: argparse.Namespace) -> None: "--task-lease-idempotency-key and --task-lease-expected-version " "are supported only by todo claim, todo update, todo complete, and todo supersede" ) + if args.todo_command != "claim" and getattr(args, "ttl_seconds", None) is not None: + raise ValueError("--ttl-seconds is supported only by todo claim") if args.capability_binding_ref and args.todo_command != "add": raise ValueError( "--capability-binding-ref is immutable and supported only by todo add" diff --git a/loopx/cli_commands/todo_registration.py b/loopx/cli_commands/todo_registration.py index 0bec8edaf1..1b92fc0d48 100644 --- a/loopx/cli_commands/todo_registration.py +++ b/loopx/cli_commands/todo_registration.py @@ -307,6 +307,15 @@ def register_todo_command( # use claim_operation_id; do not advertise the host transport as task work. todo_parser.add_argument("--task-lease-idempotency-key", help=argparse.SUPPRESS) todo_parser.add_argument("--task-lease-expected-version", type=int, help=argparse.SUPPRESS) + todo_parser.add_argument( + "--ttl-seconds", + type=int, + help=( + "For todo claim, optional lease TTL in seconds (1..86400; default " + "2700 = 45m). Pass a higher TTL on claim for long (>45m) execution " + "wakes, or renew via `task-lease renew` before expiry." + ), + ) todo_parser.add_argument( "--bound-agent", help=( diff --git a/loopx/cli_commands/turn.py b/loopx/cli_commands/turn.py index 7522139661..e4a58ec422 100644 --- a/loopx/cli_commands/turn.py +++ b/loopx/cli_commands/turn.py @@ -111,6 +111,7 @@ def project_preparation_effects(value: dict[str, Any]) -> None: ): from ..control_plane.turn_driver.codex_execution_preparation import ( builtin_execution_preparation_claim, + unconsumed_preparation_refusal, ) from .turn_host_request import prepare_turn_host_arguments @@ -146,7 +147,7 @@ def record_claim(receipt: Mapping[str, Any]) -> None: preparation_error = "execution preparation did not make the same Todo ready" def execution_preparer(decision: Mapping[str, Any]) -> str | None: - return builtin_execution_preparation_claim( + prepared_todo = builtin_execution_preparation_claim( decision, agent_id=args.agent_id, registry_path=registry_path.expanduser().resolve(), @@ -157,6 +158,13 @@ def execution_preparer(decision: Mapping[str, Any]) -> str | None: admit_start=admit_preparation, on_claim=record_claim, ) + if prepared_todo is None and preparation_admission is None: + refusal = unconsumed_preparation_refusal( + decision, goal_id=args.goal_id, agent_id=args.agent_id, + ) + if refusal is not None: + raise refusal + return prepared_todo resume_instance = getattr(args, "resume_turn_instance_id", None) if resume_instance is not None: diff --git a/loopx/cli_commands/turn_rendering.py b/loopx/cli_commands/turn_rendering.py index cda0d23560..5060bb51ab 100644 --- a/loopx/cli_commands/turn_rendering.py +++ b/loopx/cli_commands/turn_rendering.py @@ -262,6 +262,14 @@ def render_loopx_turn_execution_markdown(payload: dict[str, object]) -> str: f"- quota_spent: {effects.get('quota_spent')}", *_turn_start_observation_lines(payload), *([f"- error: {payload['error']}"] if payload.get("error") else []), + *( + [ + f"- reason: {payload['error_code']}", + *([f"- claim_command: {payload['claim_command']}", + f"- next_step: {payload['next_step']}"] if payload.get("claim_command") else []), + ] + if payload.get("status") == "execution_preparation_required" else [] + ), *([f"- journal_readback: {journal_observation.get('status')}", f"- recorded_effects: {journal_observation.get('recorded_effects')}", f"- recovery_from: {(journal_observation.get('recovery_decision') or {}).get('resume_from')}", diff --git a/loopx/cli_commands/turn_run_once.py b/loopx/cli_commands/turn_run_once.py index 7be454f34c..ffc504c981 100644 --- a/loopx/cli_commands/turn_run_once.py +++ b/loopx/cli_commands/turn_run_once.py @@ -511,6 +511,16 @@ def todo_completion( ) return completion_payload + def require_isolated_codex_writeback() -> None: + if args.host != "codex-cli" or not getattr(args, "codex_operation_tools", False): + return + from ..control_plane.turn_driver.codex_worker_identity import worker_isolation_requested + + if worker_isolation_requested(): + if goal_admission is None: + raise ValueError("isolated managed Codex writeback requires current Goal authority") + goal_admission.require_running(operation="isolated_codex_durable_writeback") + def completion_writeback( result: dict[str, object], *, @@ -518,6 +528,7 @@ def completion_writeback( ) -> dict[str, object]: nonlocal rebound_lease_active require_effect_ref(effect_ref, SettlementStepKind.DURABLE_WRITEBACK) + require_isolated_codex_writeback() prior = completion_readback() if prior is None: if args.execute: @@ -617,6 +628,7 @@ def codex_writeback( # a predeclared terminal Todo. Other hosts keep their existing order. if result.get("result_kind") == "validated_completion": return completion_writeback(result, effect_ref=effect_ref) + require_isolated_codex_writeback() return writeback(result, effect_ref=effect_ref) def current_status() -> dict[str, object]: diff --git a/loopx/cli_runtime.py b/loopx/cli_runtime.py index 007b525707..fb2c36c372 100644 --- a/loopx/cli_runtime.py +++ b/loopx/cli_runtime.py @@ -661,6 +661,11 @@ def _dispatch_common_command( if args.command in PROJECT_LIFECYCLE_COMMANDS: from .cli_commands.project_lifecycle import handle_project_lifecycle_command from .cli_rollout import append_cli_rollout_event + if args.command == "refresh-state" and getattr(args, "execution_loss_closeout", False): + return handle_project_lifecycle_command( + args, registry_path=registry_path, print_payload=print_payload, + output_format=output_format, append_cli_rollout_event=append_cli_rollout_event, + ) from .capabilities.periodic_report.post_writeback_hook import ( build_periodic_report_post_writeback_projection, periodic_report_post_writeback_hooks_for_goal, diff --git a/loopx/codex_app_thread_activity.py b/loopx/codex_app_thread_activity.py index c81cfa11c4..fba46e8b4e 100644 --- a/loopx/codex_app_thread_activity.py +++ b/loopx/codex_app_thread_activity.py @@ -207,6 +207,38 @@ def observe_codex_thread_execution_identity( return {"status": "unavailable", "reason": fallback} +def _rollout_stamp(stat: os.stat_result) -> tuple[int, int, int, int]: + return stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns + + +def _confirm_windows_rollout( + path: Path, cursor: RolloutCursor, source: os.stat_result, + result: HostThreadActivity, reader: Reader, +) -> bool: + if not reader.remaining or result.state is HostThreadState.UNKNOWN: + return False + # A fresh descriptor and cursor verify the header and independently choose + # the marker and latest event, including when the first read used a + # retained forward cursor. The repeat uses only the unused read budget. + expected = _rollout_stamp(source) + with open_rollout(path) as handle: + before = os.fstat(handle.fileno()) + if _rollout_stamp(before) != expected: + return False + fresh = RolloutCursor(cursor.binding, cursor.thread_id) + confirmation = fresh.observe( + Reader(handle, reader.remaining, chunk_bytes=reader.chunk_bytes), before, + ) + after = os.fstat(handle.fileno()) + return ( + confirmation == result + and _rollout_stamp(after) == expected + and after.st_ctime_ns == before.st_ctime_ns + and Path(os.path.realpath(path)) == path + and _rollout_stamp(path.stat()) == expected + ) + + def _rollout_activity( rollout_path: Any, home: Path, *, thread_id: str, cache_root: Path | None = None, ) -> HostThreadActivity: @@ -246,8 +278,18 @@ def _rollout_activity( if Path(os.path.realpath(path)) != path or (end.st_dev, end.st_ino) != (named.st_dev, named.st_ino) or end.st_size < stat.st_size: _rollout_cache.pop(binding, None) return HostThreadActivity.unknown(HostThreadUnknownReason.STORE_UNAVAILABLE) - if end.st_size == stat.st_size and (end.st_mtime_ns != stat.st_mtime_ns or end.st_ctime_ns != stat.st_ctime_ns): + if end.st_size == stat.st_size and end.st_mtime_ns != stat.st_mtime_ns: + _rollout_cache.pop(binding, None) + return HostThreadActivity.unknown(HostThreadUnknownReason.RECORD_UNRECOGNIZED) + if end.st_size == stat.st_size and end.st_ctime_ns != stat.st_ctime_ns: + # Don't persist the first cursor across ambiguous metadata. _rollout_cache.pop(binding, None) + if ( + os.name == "nt" and stat.st_dev and stat.st_ino + and _rollout_stamp(stat) == _rollout_stamp(end) + and _confirm_windows_rollout(path, cursor, end, result, reader) + ): + return result return HostThreadActivity.unknown(HostThreadUnknownReason.RECORD_UNRECOGNIZED) cursor.save(cache_root) # An append may contain a newer end/cancel. Do not publish an old diff --git a/loopx/control_plane/collaboration/delegation_preview_transport.py b/loopx/control_plane/collaboration/delegation_preview_transport.py index bd082759ae..b7f9163a20 100644 --- a/loopx/control_plane/collaboration/delegation_preview_transport.py +++ b/loopx/control_plane/collaboration/delegation_preview_transport.py @@ -19,6 +19,7 @@ from typing import Any from ..effect_runtime import _node_executable +from ..runtime.node_probe import node_typescript_flags BRIDGE_CLOSE_TIMEOUT_SECONDS = 5.0 @@ -164,7 +165,13 @@ def preview(self, *, command: list[str], workspace: Path, release: Path, ) bridge = Path(__file__).with_name("delegation_preview_bridge.ts") self._process = subprocess.Popen( - [_node_executable(), "--no-warnings", "--experimental-strip-types", str(bridge)], + [ + _node_executable(), + "--no-warnings", + "--experimental-strip-types", + *node_typescript_flags(), + str(bridge), + ], env=environment, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, encoding="utf-8", start_new_session=True, diff --git a/loopx/control_plane/collaboration/steward_managed_mode.ts b/loopx/control_plane/collaboration/steward_managed_mode.ts index b9ee59d153..18c5b509f3 100644 --- a/loopx/control_plane/collaboration/steward_managed_mode.ts +++ b/loopx/control_plane/collaboration/steward_managed_mode.ts @@ -1053,11 +1053,19 @@ function hasMatchingApprovedReviewerDeclaration(item: JsonObject, requiredTokens ); } +function classifyStalledBucket(stalledAgeMs: number, authorReplyBypass: boolean): string { + if (authorReplyBypass) return "awaiting_maintainer_reply"; + if (stalledAgeMs >= 168 * 3_600_000) return "7d_plus"; + if (stalledAgeMs >= 72 * 3_600_000) return "72h_plus"; + if (stalledAgeMs >= 24 * 3_600_000) return "24h_to_72h"; + return "under_24h"; +} + function filterScopedRepositoryItems( rawItems: unknown[], filter: JsonObject | null, observedAtValue: unknown, -): JsonObject[] { +): { items: JsonObject[]; observationIncomplete: boolean } { const minStalledHours = typeof filter?.min_stalled_hours === "number" ? filter.min_stalled_hours : null; let observedAtMs = NaN; if (minStalledHours !== null) { @@ -1100,16 +1108,90 @@ function filterScopedRepositoryItems( if (authorMode === "exclude" && login && authors.has(login)) continue; } if (minStalledHours !== null) { - const updatedMs = typeof item.updatedAt === "string" ? Date.parse(item.updatedAt) : NaN; - if (!Number.isFinite(updatedMs) || observedAtMs - updatedMs < minStalledHours * 3_600_000) { + const authorReplied = item.author_replied_after_request_changes === true + || reviewSummary?.author_replied_after_request_changes === true; + const hasExplicitStalledSince = Object.prototype.hasOwnProperty.call(item, "stalled_since") + || (reviewSummary !== null && Object.prototype.hasOwnProperty.call(reviewSummary, "stalled_since")); + const rawStalledSince = typeof item.stalled_since === "string" + ? item.stalled_since + : (typeof reviewSummary?.stalled_since === "string" ? reviewSummary.stalled_since : null); + if ( + hasExplicitStalledSince + && rawStalledSince === null + && effectiveVerdicts !== null + && effectiveVerdicts.size === 1 + && effectiveVerdicts.has("REQUEST_CHANGES") + ) { continue; } - matched.push({ ...item, stalled_threshold_met: true }); + // Fail closed when comment pagination did not reach the stalled anchor or a newer + // author/maintainer reply, so evicted replies cannot drop awaiting_maintainer_reply. + const commentsCoverageIncomplete = item.comments_coverage_incomplete === true + || reviewSummary?.comments_coverage_incomplete === true; + if (commentsCoverageIncomplete) { + return { items: [], observationIncomplete: true }; + } + const basisIso = rawStalledSince ?? (typeof item.updatedAt === "string" ? item.updatedAt : null); + const basisMs = basisIso !== null ? Date.parse(basisIso) : NaN; + const authorReplyBypass = authorReplied && authorMode === "exclude"; + const thresholdMet = Number.isFinite(basisMs) && observedAtMs - basisMs >= minStalledHours * 3_600_000; + if (!authorReplyBypass && !thresholdMet) { + continue; + } + const stalledAgeMs = Number.isFinite(basisMs) ? Math.max(0, observedAtMs - basisMs) : 0; + matched.push({ + ...item, + stalled_threshold_met: thresholdMet, + stalled_bucket: classifyStalledBucket(stalledAgeMs, authorReplyBypass), + }); } else { matched.push(item); } } - return matched; + return { items: matched, observationIncomplete: false }; +} + +const AGE_FILTER_ITEM_FIELDS = [ + "stalled_since", + "author_replied_after_request_changes", + "comments_coverage_incomplete", + "stalled_threshold_met", + "stalled_bucket", +] as const; + +const AGE_FILTER_REVIEW_SUMMARY_FIELDS = [ + "latest_request_changes_review_id", + "stalled_since", + "author_replied_after_request_changes", + "comments_coverage_incomplete", +] as const; + +function omitKeys(obj: JsonObject, keysToOmit: readonly string[]): JsonObject { + const omit = new Set(keysToOmit); + return Object.fromEntries(Object.entries(obj).filter(([key]) => !omit.has(key))); +} + +function projectRepositoryItemForMaterialHash(rawItem: unknown, usesStalledAgeFilter: boolean): unknown { + const item = jsonObject(rawItem); + if (!item) return rawItem; + const reviewSummary = jsonObject(item.review_summary); + if (usesStalledAgeFilter) { + const hasStalledSinceClock = typeof item.stalled_since === "string" + || typeof reviewSummary?.stalled_since === "string"; + const omittedItemFields = hasStalledSinceClock + ? ["comments_coverage_incomplete", "updatedAt"] + : ["comments_coverage_incomplete"]; + const projectedItem = omitKeys(item, omittedItemFields); + if (reviewSummary !== null) { + projectedItem.review_summary = omitKeys(reviewSummary, ["comments_coverage_incomplete"]); + } + return projectedItem; + } + const projectedItem = omitKeys(item, AGE_FILTER_ITEM_FIELDS); + if (reviewSummary !== null) { + projectedItem.review_summary = omitKeys(reviewSummary, AGE_FILTER_REVIEW_SUMMARY_FIELDS); + } + return projectedItem; } /** Combine authorized local portfolio, inbox and optional repository signal @@ -1119,40 +1201,54 @@ function filterScopedRepositoryItems( export function observeStewardSignalMonitor(params: JsonObject): JsonObject { const previousHash = typeof params.previous_hash === "string" && params.previous_hash ? params.previous_hash : null; + const incompleteObservation: JsonObject = { + result_hash: previousHash, + material_change: false, + observation_incomplete: true, + own_monitor_bookkeeping_excluded: true, + }; const signalScope = normalizeStewardSignalMonitorScope(params.signal_scope); const repo = params.repository_snapshot == null ? null : requireJsonObject(params.repository_snapshot, "repository signal"); if (repo !== null && repo.status === "unavailable") { - return { - result_hash: previousHash, - material_change: false, - observation_incomplete: true, - own_monitor_bookkeeping_excluded: true, - }; + return incompleteObservation; } const portfolio = params.portfolio_observation == null ? null : requireJsonObject(params.portfolio_observation, "portfolio observation"); const inboxItems = Array.isArray(params.inbox_items) ? params.inbox_items : []; const rawRepoItems = repo === null ? null : (Array.isArray(repo.items) ? repo.items : []); - const scopedRepoItems = signalScope !== null && rawRepoItems !== null + const prFilter = signalScope === null ? null : jsonObject(signalScope.pr_filter); + const rawMinStalledHours = prFilter?.min_stalled_hours; + const usesStalledAgeFilter = typeof rawMinStalledHours === "number" + && Number.isFinite(rawMinStalledHours) + && rawMinStalledHours > 0; + const scopedResult = signalScope !== null && rawRepoItems !== null ? filterScopedRepositoryItems( rawRepoItems, - signalScope.pr_filter === undefined ? null : jsonObject(signalScope.pr_filter), + prFilter, params.observed_at ?? repo?.observed_at, ) : null; + if (scopedResult?.observationIncomplete) { + return incompleteObservation; + } + const scopedRepoItems = scopedResult === null ? null : scopedResult.items; + const baseRepoItems = scopedRepoItems ?? rawRepoItems; + const hashedRepoItems = baseRepoItems === null + ? null + : baseRepoItems.map((item) => projectRepositoryItemForMaterialHash(item, usesStalledAgeFilter)); const includePortfolio = signalScope === null ? true : signalScope.include_portfolio === true; const includeInbox = signalScope === null ? true : signalScope.include_inbox === true; const facts = signalScope === null ? { portfolio_hash: portfolio?.result_hash ?? null, inbox_items: inboxItems, - repository_items: rawRepoItems, + repository_items: hashedRepoItems, } : { signal_scope: signalScope, portfolio_hash: includePortfolio ? (portfolio?.result_hash ?? null) : null, inbox_items: includeInbox ? inboxItems : [], - repository_items: scopedRepoItems, + repository_items: hashedRepoItems, }; const clocks = new Set(["snapshot_id", "portfolio_snapshot_id", "collected_at", "collection_completed_at", "generated_at", "evaluated_at", "age_seconds", "observed_at"]); diff --git a/loopx/control_plane/coordination/claim_execution.ts b/loopx/control_plane/coordination/claim_execution.ts index 04c2e2875e..da9dd22acf 100644 --- a/loopx/control_plane/coordination/claim_execution.ts +++ b/loopx/control_plane/coordination/claim_execution.ts @@ -99,7 +99,7 @@ export function maintainClaimExecution(head: JsonObject, input: ExecutionInput, * transfer grant). Expired execution is reclaimable without the old process; * acquisition still validates scope, eligibility and generation under one CAS. */ export async function prepareClaimExecution(head: JsonObject, - input: ExecutionInput & {operation_id: string; claimed_by: string}, + input: ExecutionInput & {operation_id: string; claimed_by: string; ttl_seconds?: number}, observeWorkspace?: ClaimWorkspaceObserver): Promise<{lease: LeaseRecord; changed: boolean; overlapAdvisories?: JsonObject[]}> { const index = indexCoordinationProjection(head, input.goal_id); const facts = canonicalTaskLeaseAcquireFacts(index, input.goal_id, input.todo_id, input.registered_agents, input.now); @@ -119,7 +119,7 @@ export async function prepareClaimExecution(head: JsonObject, const command = {owner: input.claimed_by, idempotency_key: `claim-${canonicalAuthoritySha256({goal_id: input.goal_id, todo_id: input.todo_id, owner: input.claimed_by, operation_id: input.operation_id})}`, - expected_version: current ? leaseVersion(current) : 0, ttl_seconds: normalizeTtl(null), + expected_version: current ? leaseVersion(current) : 0, ttl_seconds: normalizeTtl(input.ttl_seconds), write_scopes: writeScopes, ...(workspace ? {write_workspace: workspace} : {})}; const decision = evaluateTaskLeaseAcquireDecision({handoff_mode: String(head.handoff_mode), registered_agents: [...input.registered_agents], ...facts, diff --git a/loopx/control_plane/coordination/local_authority.py b/loopx/control_plane/coordination/local_authority.py index 5717d8331b..922d23dcfb 100644 --- a/loopx/control_plane/coordination/local_authority.py +++ b/loopx/control_plane/coordination/local_authority.py @@ -191,6 +191,7 @@ def claim_canonical_todo_if_promoted( operation_id: str | None = None, task_lease_idempotency_key: str | None = None, task_lease_expected_version: int | None = None, + ttl_seconds: int | None = None, manage_execution: bool = False, expected_provider_revision: str | None = None, expected_registry_sha256: str | None = None, @@ -202,6 +203,15 @@ def claim_canonical_todo_if_promoted( reviewed = expected_provider_revision is not None or expected_registry_sha256 is not None if reviewed and not (manage_execution and expected_provider_revision and expected_registry_sha256): raise ValueError("A reviewed managed claim requires both canonical revision and registry digest") + if ttl_seconds is not None and ( + isinstance(ttl_seconds, bool) + or not isinstance(ttl_seconds, int) + or ttl_seconds <= 0 + or ttl_seconds > 86400 + ): + raise ValueError("ttl seconds must be between 1 and 86400") + if ttl_seconds is not None and task_lease_idempotency_key is None and not manage_execution: + raise ValueError("ttl_seconds requires managed execution or task_lease_idempotency_key") with authority_registry_source(registry_path, routing_registry_witness=routing_registry_witness) as registry_source: registered = registered_agent_ids_from_registry(registry_path, goal_id) # This is only a candidate location. The lease owner observes physical @@ -229,6 +239,11 @@ def claim_canonical_todo_if_promoted( else f"todo-claim:{goal_id}:{todo_id}:{uuid4().hex}" ), **({"manage_execution": True} if manage_execution else {}), + **( + {"ttl_seconds": ttl_seconds} + if task_lease_idempotency_key is None and ttl_seconds is not None + else {} + ), **( {"expected_provider_revision": expected_provider_revision, "expected_registry_sha256": expected_registry_sha256} @@ -239,7 +254,7 @@ def claim_canonical_todo_if_promoted( { "idempotency_key": task_lease_idempotency_key, "expected_version": task_lease_expected_version, - "ttl_seconds": None, + "ttl_seconds": ttl_seconds, } if task_lease_idempotency_key is not None else None diff --git a/loopx/control_plane/coordination/local_authority_runtime.ts b/loopx/control_plane/coordination/local_authority_runtime.ts index 9889a97e27..b891036f9e 100644 --- a/loopx/control_plane/coordination/local_authority_runtime.ts +++ b/loopx/control_plane/coordination/local_authority_runtime.ts @@ -1057,6 +1057,12 @@ export async function claimLocalCoordinationTodo( } if (Object.hasOwn(input, "manage_execution") && !managed) throw new TypeError("Managed execution requires claim request v2"); + const hasTopLevelTtl = Object.hasOwn(input, "ttl_seconds") + && input.ttl_seconds !== undefined && input.ttl_seconds !== null; + if (hasTopLevelTtl && !managed) { + throw new TypeError("Managed execution TTL requires claim request v2"); + } + const topLevelTtl = hasTopLevelTtl ? normalizeTtl(input.ttl_seconds) : undefined; if (reviewed ? input.manage_execution !== true || typeof input.expected_registry_sha256 !== "string" : Object.hasOwn(input, "expected_registry_sha256")) throw new TypeError("A Todo claim review basis requires a reviewed managed claim"); @@ -1116,6 +1122,7 @@ export async function claimLocalCoordinationTodo( operation_id: requireAuthorityStoreId(input.operation_id, "operation id"), lease_request: leaseRequest, ...(input.manage_execution === undefined ? {} : {manage_execution: input.manage_execution as boolean}), + ...(topLevelTtl === undefined ? {} : {ttl_seconds: topLevelTtl}), ...(expectedRevision === undefined ? {} : {expected_provider_revision: expectedRevision}), dry_run: input.dry_run === true, now: claimObservedAt(input.observed_at), diff --git a/loopx/control_plane/coordination/remote_authority_gateway.py b/loopx/control_plane/coordination/remote_authority_gateway.py index a2c16ce0c0..de4fb29862 100644 --- a/loopx/control_plane/coordination/remote_authority_gateway.py +++ b/loopx/control_plane/coordination/remote_authority_gateway.py @@ -52,13 +52,14 @@ def check_remote_authority_gateway_status( if not credential: return {**projection, "status": "unavailable", "reason_code": "remote_authority_credential_required"} from ..effect_runtime import EffectRuntimeStartupError, _node_executable + from ..runtime.node_probe import node_typescript_flags try: # The user-owned registry supplies the origin and optional private CA. # Pass the credential and binding through the private pipe, not argv. bridge = Path(__file__).with_name("remote_authority_probe.ts") completed = subprocess.run( - [_node_executable(), "--no-warnings", "--experimental-strip-types", str(bridge)], + [_node_executable(), "--no-warnings", "--experimental-strip-types", *node_typescript_flags(), str(bridge)], input=json.dumps({ **{key: cfg[key] for key in _REQUIRED_BINDING}, "goal_id": goal_id, "credential": credential, "ca_file": cfg.get("ca_file"), diff --git a/loopx/control_plane/coordination/todo_claim.ts b/loopx/control_plane/coordination/todo_claim.ts index 12e5a8b0ef..df0c18fea2 100644 --- a/loopx/control_plane/coordination/todo_claim.ts +++ b/loopx/control_plane/coordination/todo_claim.ts @@ -65,6 +65,7 @@ export interface CoordinationTodoClaimInput { readonly replan_obligation_id?: string; readonly lease_request?: CoordinationTodoClaimLeaseRequest | null; readonly manage_execution?: boolean; + readonly ttl_seconds?: number; /** Admission constraint on every attempt and replay, not a new business intent. */ readonly required_handoff_mode?: ExecutionHandoffMode; readonly dry_run: boolean; @@ -376,6 +377,8 @@ async function executeClaimAttempt( ? null : normalizeTodoAgent(rawInput.actor_agent_id, "actor_agent_id"), registered_agents: normalizeRegisteredTodoAgents(rawInput.registered_agents), lease_request: normalizeLeaseRequest(rawInput.lease_request), + ttl_seconds: rawInput.ttl_seconds === undefined || rawInput.ttl_seconds === null + ? undefined : normalizeTtl(rawInput.ttl_seconds), }; if (input.manage_execution !== undefined) requireAuthorityBoolean(input.manage_execution, "manage_execution"); if (input.required_handoff_mode !== undefined && !EXECUTION_HANDOFF_MODES.includes(input.required_handoff_mode)) { @@ -384,6 +387,9 @@ async function executeClaimAttempt( if (input.manage_execution && (input.lease_request != null || input.actor_agent_id !== input.claimed_by)) { throw new AuthorityStoreProtocolError("Managed execution requires the claiming actor and no explicit lease request"); } + if (input.ttl_seconds !== undefined && !input.manage_execution) { + throw new AuthorityStoreProtocolError("Managed execution TTL requires manage_execution and no explicit lease request"); + } requireAuthorityBoolean(input.dry_run, "dry_run"); requireAuthorityDate(input.now, "now"); } catch (error) { @@ -413,6 +419,7 @@ async function executeClaimAttempt( dry_run: input.dry_run, ...(leaseRequest === null ? {} : {lease_request: leaseRequest}), ...(input.manage_execution ? {manage_execution: true} : {}), + ...(input.ttl_seconds === undefined ? {} : {ttl_seconds: input.ttl_seconds}), ...(input.replan_obligation_id === undefined ? {} : {replan_obligation_id: input.replan_obligation_id}), }; const requestSha = canonicalAuthoritySha256(requestIdentity); diff --git a/loopx/control_plane/effect_runtime.py b/loopx/control_plane/effect_runtime.py index 49c82f08cd..ad71b09cf6 100644 --- a/loopx/control_plane/effect_runtime.py +++ b/loopx/control_plane/effect_runtime.py @@ -32,6 +32,7 @@ MINIMUM_NODE_VERSION_TEXT as MINIMUM_NODE_VERSION_TEXT, STARTUP_READY_TIMEOUT_SECONDS as STARTUP_READY_TIMEOUT_SECONDS, node_probe_remediation, + node_typescript_flags as _node_typescript_flags, probe_node as _probe_node, ) from .content_digest import BARE_SHA256_PATTERN @@ -1332,6 +1333,7 @@ def _start_runtime(*, fingerprint: str, info_path: Path) -> dict[str, Any]: _node_executable(), "--no-warnings", "--experimental-strip-types", + *_node_typescript_flags(), "--import", # ESM specifiers require file URLs on Windows; encode # reserved path characters on every platform as well. @@ -1448,6 +1450,7 @@ def _start_stdio_runtime(fingerprint: str) -> _StdioRuntime: _node_executable(), "--no-warnings", "--experimental-strip-types", + *_node_typescript_flags(), str(_control_plane_root() / "effect_runtime_stdio.ts"), fingerprint, ], diff --git a/loopx/control_plane/effect_runtime_handlers.ts b/loopx/control_plane/effect_runtime_handlers.ts index 88df41aed7..69ca2031c3 100644 --- a/loopx/control_plane/effect_runtime_handlers.ts +++ b/loopx/control_plane/effect_runtime_handlers.ts @@ -389,6 +389,7 @@ export function createEffectRuntimeHandlers( ["quota.spend.commit", lazyHandler(() => import("./quota/spend_commit.ts"), ({evaluateQuotaSpendCommit}) => evaluateQuotaSpendCommit)], ["quota.void.commit", lazyHandler(() => import("./quota/void_commit.ts"), ({evaluateQuotaVoidCommit}) => evaluateQuotaVoidCommit)], ["quota.settlement.read", lazyHandler(() => import("./quota/settlement_readback.ts"), ({readQuotaSettlement}) => readQuotaSettlement)], + ["quota.execution_loss_closeout.commit", lazyHandler(() => import("./quota/execution_loss_closeout.ts"), ({commitExecutionLossCloseout}) => commitExecutionLossCloseout)], ["quota.heartbeat_receipt.select", lazyHandler(() => import("./quota/heartbeat_receipt_identity.ts"), ({projectHeartbeatReceiptSelection}) => projectHeartbeatReceiptSelection)], [ "quota.prior_host_turn_closeout.preflight", diff --git a/loopx/control_plane/goals/checkpoint_context_io.py b/loopx/control_plane/goals/checkpoint_context_io.py index 0ffc13bbaa..d63b51467e 100644 --- a/loopx/control_plane/goals/checkpoint_context_io.py +++ b/loopx/control_plane/goals/checkpoint_context_io.py @@ -236,11 +236,20 @@ def commit_checkpoint_run( return result -def inspect_checkpoint_replay(runtime_root: Path, goal_id: str, prior: dict[str, Any]) -> None: - if isinstance(prior.get("vision_checkpoint"), dict) and prior["vision_checkpoint"].get("read_context"): - _checkpoint_effect("goal.checkpoint_read_context.inspect_replay", { - "runtime_root": str(runtime_root.resolve()), "goal_id": goal_id, "prior": prior, - }) +def inspect_checkpoint_replay( + runtime_root: Path, goal_id: str, prior: dict[str, Any], +) -> dict[str, Any] | None: + checkpoint = prior.get("vision_checkpoint") + if not isinstance(checkpoint, dict) or not checkpoint.get("read_context"): + return None + result = _checkpoint_effect("goal.checkpoint_read_context.inspect_replay", { + "runtime_root": str(runtime_root.resolve()), "goal_id": goal_id, "prior": prior, + }) + if not isinstance(result, dict) or not isinstance(result.get("ok"), bool): + raise RuntimeError("invalid typed checkpoint replay result") + if not result["ok"]: + raise CheckpointReadContextRejected(result) + return result def render_checkpoint_context(payload: dict[str, Any]) -> str: diff --git a/loopx/control_plane/goals/first_party_host_runtime.ts b/loopx/control_plane/goals/first_party_host_runtime.ts index e2b655ccad..8a5baa2baf 100644 --- a/loopx/control_plane/goals/first_party_host_runtime.ts +++ b/loopx/control_plane/goals/first_party_host_runtime.ts @@ -140,6 +140,12 @@ function registryWitness(value: unknown): {path: string; sha256: string} | null ? {path: witness.path, sha256: witness.sha256} : null; } +/** Legacy registration follows the existing active-* Goal frontier vocabulary. */ +export function legacyGoalRegistrationIsActive(value: unknown): boolean { + const registration = typeof value === "string" ? value.trim().toLowerCase() : ""; + return registration === "active" || registration.startsWith("active-"); +} + /** Launch rechecks the registry. An already dispatched Turn checks its running authority. */ function legacyRuntime(facts: JsonObject): FirstPartyHostRuntimeDecision { const current = jsonObject(facts.authority); @@ -148,9 +154,7 @@ function legacyRuntime(facts: JsonObject): FirstPartyHostRuntimeDecision { || current.goal_id !== facts.goal_id) return {kind: "reject", code: "goal_authority_unavailable"}; // Legacy registration accepts the active-* variants used by the existing // Goal frontier. Source-session registration remains exact-only below. - const registration = typeof current.registration_status === "string" - ? current.registration_status.trim().toLowerCase() : ""; - if (registration !== "active" && !registration.startsWith("active-")) { + if (!legacyGoalRegistrationIsActive(current.registration_status)) { return {kind: "reject", code: "goal_not_registered"}; } if (current.activation_state === "stopped") return {kind: "reject", code: "goal_stopped"}; diff --git a/loopx/control_plane/goals/outcome_requirements.ts b/loopx/control_plane/goals/outcome_requirements.ts index bfcb59154e..6790d72fbb 100644 --- a/loopx/control_plane/goals/outcome_requirements.ts +++ b/loopx/control_plane/goals/outcome_requirements.ts @@ -41,7 +41,10 @@ function text(value: unknown, label: string, max = 512): string { } function id(value: unknown, label: string): string { const result = text(value, label, 128); - requireValue(/^[A-Za-z0-9][A-Za-z0-9_.:@-]*$/.test(result), `${label} must be an opaque identifier`); + requireValue( + /^[A-Za-z0-9][A-Za-z0-9_.:@-]*$/.test(result), + `${label} must be an opaque identifier (ASCII letters/digits and . _ : @ -, no '/' paths or spaces)`, + ); return result; } function keys(row: JsonObject, required: string[], optional: string[] = []): void { diff --git a/loopx/control_plane/projects/registry_codec.py b/loopx/control_plane/projects/registry_codec.py index 15442a1d10..3070c3261c 100644 --- a/loopx/control_plane/projects/registry_codec.py +++ b/loopx/control_plane/projects/registry_codec.py @@ -425,6 +425,8 @@ def backup_preimage(self) -> Path: """Verify a private original-byte backup before a caller's migration.""" if not self._existed or self._finished: raise RuntimeError("registry backup requires an open existing transaction") + from ..runtime.document_io import fsync_state_directory + raw = self._document.raw_bytes if self._path.read_bytes() != raw: raise ProjectRegistryMutationError("Registry changed before preimage backup") diff --git a/loopx/control_plane/quota/execution_loss_closeout.ts b/loopx/control_plane/quota/execution_loss_closeout.ts new file mode 100644 index 0000000000..5e3e8ece48 --- /dev/null +++ b/loopx/control_plane/quota/execution_loss_closeout.ts @@ -0,0 +1,462 @@ +/** Explicit administrative closeout. The immutable Run is its durable intent; + * original admission and the current provider head stay fenced through append. */ +import {createHash, randomUUID} from "node:crypto"; +import {closeSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync} from "node:fs"; +import {dirname, join, resolve} from "node:path"; +import {isDeepStrictEqual} from "node:util"; +import {settlementIdentity, settlementIdentityPayload, type JsonObject} from "../effect_program.ts"; +import {EffectRuntimeRequestError} from "../effect_runtime_errors.ts"; +import {appendJsonLineSync, claimFileMutationLock, mutationLockOwner, releaseFileMutationLockClaim, + type FileMutationLockClaim} from "../effect_runtime_io.ts"; +import {jsonObject, requireJsonObject, requireNonEmptyString} from "../runtime_decode.ts"; +import {canonicalAuthoritySha256} from "../coordination/authority_store_codec.ts"; +import {indexCoordinationProjection} from "../coordination/coordination_projection.ts"; +import {FileAuthorityStore} from "../coordination/file_authority_store.ts"; +import {SqliteAuthorityStore} from "../coordination/sqlite_authority_store.ts"; +import {openRuntimeAuthorityStore, requireLocalAuthorityRuntimeRoot} from "../coordination/local_authority_provider.ts"; +import {requireShadowPrimaryWriteAllowed, shadowMaintenanceLockPath} from "../coordination/shadow_management.ts"; +import {decodeTaskLeaseAuthority} from "../work_items/task_lease_acquire.ts"; +import {legacyGoalRegistrationIsActive} from "../goals/first_party_host_runtime.ts"; +import {EXECUTION_LOSS_CLOSEOUT_SCHEMA, isExecutionLossCloseout} from "./execution_loss_closeout_record.ts"; +import {parseExactGoalRef} from "../goals/goal_instance_identity.ts"; +import {canonicalTaskLease, canonicalLeaseTodoFact} from "../coordination/task_lease_state.ts"; +import {leaseIsActive} from "../work_items/task_lease_record.ts"; +import {decodeTaskLeaseProof} from "../coordination/task_lease_proof.ts"; +import {heartbeatReceiptBinding, heartbeatReceiptDetails, heartbeatReceiptFactFromEvent} + from "./heartbeat_receipt_identity.ts"; +import {heartbeatPreparedWorkAdmission, type HeartbeatPreparedLease} from "./heartbeat_receipt_identity.ts"; +import {nativeChildReportAdmission} from "../capabilities/native_child_admission.ts"; +import {parseTodoTimestampMicros} from "../runtime_timestamp.ts"; +import {projectProgressDelta} from "../work_items/progress_delta.ts"; +import {leaseRepositoryRejection} from "../work_items/task_lease_repository.ts"; +import {leaseOwnerRejection} from "../work_items/task_lease_eligibility.ts"; +import {goalRolloutEventLogPath} from "../rollout_receipt_log.ts"; +import {parseQuotaAccountingOwner, quotaGoalRef, requireCurrentQuotaAccountingOwner, + requireQuotaOwnerProjection, withBorrowedQuotaAccountingOwner, type QuotaAccountingOwner} from "./source_admission.ts"; +import {QUOTA_SETTLEMENT_READBACK_REQUEST_SCHEMA, readQuotaSettlementForAdmittedOwnerFromSnapshot, + readQuotaSettlementSnapshot} from "./settlement_readback.ts"; + +export const EXECUTION_LOSS_QUALIFICATION_SCHEMA = "execution_loss_closeout_qualification_v0"; + +function rejectExecutionLoss(message: string): never { + throw new EffectRuntimeRequestError(`execution-loss closeout ${message}`, "refresh_task_lease_unavailable"); +} + +function executionLossClock(value: unknown): bigint { + if (typeof value !== "string") rejectExecutionLoss("requires an exact aware timestamp"); + const time = parseTodoTimestampMicros(value, true); + if (time === null) rejectExecutionLoss("has an invalid or ambiguous timestamp"); + return time; +} + +/** Pure qualification consumed only by the fenced administrative commit owner. + * A current lease proves control-writer ownership, never original execution. */ +export function qualifyReceiptBoundExecutionLossCloseout(value: unknown): JsonObject { + const request = requireJsonObject(value, "execution-loss qualification"); + if (request.schema_version !== EXECUTION_LOSS_QUALIFICATION_SCHEMA) + rejectExecutionLoss("qualification schema is unsupported"); + const binding = requireJsonObject(request.identity, "execution-loss identity"); + const identity = settlementIdentity({goal_id: requireNonEmptyString(binding.goal_id, "goal_id"), + agent_id: requireNonEmptyString(binding.agent_id, "agent_id"), todo_id: requireNonEmptyString(binding.todo_id, "todo_id"), + turn_instance_id: requireNonEmptyString(binding.turn_instance_id, "turn_instance_id")}); + if (identity.binding_kind !== "todo" || !identity.todo_id + || !isDeepStrictEqual(settlementIdentityPayload(identity), binding)) + rejectExecutionLoss("requires the exact original Todo Turn identity"); + const receipt = requireJsonObject(request.receipt, "original heartbeat receipt"); + if (request.goal_ref === undefined) { + if (Object.hasOwn(receipt, "goal_ref")) rejectExecutionLoss("cannot mix legacy and exact Goal ownership"); + } else { + const current = parseExactGoalRef(request.goal_ref), original = parseExactGoalRef(receipt.goal_ref); + if (current.kind !== "parsed" || original.kind !== "parsed" + || current.value.goalId.value !== identity.goal_id + || !isDeepStrictEqual(request.goal_ref, receipt.goal_ref)) + rejectExecutionLoss("requires the original exact Goal lifetime"); + } + const details = heartbeatReceiptDetails(receipt), fact = heartbeatReceiptFactFromEvent(receipt); + const originalBinding = heartbeatReceiptBinding(identity.goal_id, identity.agent_id, fact); + const prepared = heartbeatPreparedWorkAdmission(receipt, identity); + if (receipt.schema_version !== "loopx_rollout_event_v0" || receipt.event_kind !== "quota_should_run" + || receipt.goal_id !== identity.goal_id || receipt.agent_id !== identity.agent_id + || receipt.run_id !== identity.turn_instance_id || fact.todo_id !== identity.todo_id + || originalBinding?.binding_kind !== "todo" || originalBinding.binding_id !== identity.todo_id + || (fact.settlement_effect_id !== null && fact.settlement_effect_id !== identity.effect_id) || fact.closeout_required !== true + || !prepared || prepared.prepared_lease_epoch === undefined + || (Object.hasOwn(details, "prepared_lease_required") && details.prepared_lease_required !== true) + || (details.semantic_replan_obligation_id != null && details.semantic_replan_obligation_id !== "") + || nativeChildReportAdmission(details, receipt.status, identity.effect_id, "open", false) + .report_permission !== "new_operation") + rejectExecutionLoss("requires complete original prepared work admission"); + const todo = requireJsonObject(request.current_todo, "current Todo"); + const registered = request.registered_agents; + if (!Array.isArray(registered) || registered.some(agent => typeof agent !== "string") + || !registered.includes(identity.agent_id) || todo.todo_id !== identity.todo_id + || todo.role !== "agent" || todo.task_class !== "advancement_task" + || todo.archive_state !== "active" || todo.status !== "open" + || todo.claimed_by !== identity.agent_id || todo.done === true) + rejectExecutionLoss("requires the current registered control writer and unfinished Todo"); + if (leaseOwnerRejection(canonicalLeaseTodoFact(todo), identity.agent_id, registered as string[]) !== null) + rejectExecutionLoss("current control writer is not eligible for this Todo"); + const lease = canonicalTaskLease(requireJsonObject(request.current_lease, "current task lease"), + identity.goal_id, identity.todo_id); + const proof = decodeTaskLeaseProof(request.control_writer_proof); + if (!proof || leaseRepositoryRejection(todo, lease) !== null + || lease.owner !== identity.agent_id || lease.status !== "active" + || typeof lease.version !== "number" || !Number.isSafeInteger(lease.version) + || typeof lease.lease_epoch !== "number" || !Number.isSafeInteger(lease.lease_epoch) + || proof.idempotency_key !== lease.idempotency_key || proof.expected_version !== lease.version) + rejectExecutionLoss("requires the exact current control-writer proof"); + const now = executionLossClock(request.observed_at), admittedAt = executionLossClock(receipt.recorded_at); + const acquired = executionLossClock(lease.acquired_at), updated = executionLossClock(lease.updated_at); + const expires = executionLossClock(lease.expires_at); + if (admittedAt > acquired || acquired > updated || updated > now || expires <= now || expires <= updated) + rejectExecutionLoss("current control-writer clock is stale or ambiguous"); + const currentHash = createHash("sha256").update(proof.idempotency_key).digest("hex"); + if (!fencesPreparedGeneration(prepared, lease)) + rejectExecutionLoss("cannot replace an available or ambiguous original generation"); + const progress = requireJsonObject(request.progress_observation, "blocked observation"); + if (progress.result_class !== "blocked" || progress.work_item_id !== identity.todo_id + || typeof progress.blocker_id !== "string" || !Array.isArray(progress.evidence_ids) + || progress.evidence_ids.length === 0 + || Object.keys(progress).some(field => !["schema_version", "result_class", "work_item_id", + "blocker_id", "evidence_ids", "fingerprint"].includes(field))) + rejectExecutionLoss("requires only verified blocked observation and evidence"); + projectProgressDelta({current: progress, baseline: null, window: []}); + return {schema_version: EXECUTION_LOSS_CLOSEOUT_SCHEMA, effect_id: identity.effect_id, + todo_id: identity.todo_id, source: "turn_settlement", observed_at: request.observed_at, + original_receipt_event_id: requireNonEmptyString(receipt.event_id, "original receipt event id"), + original_prepared: {...prepared}, current_control_writer: { + lease_key_sha256: currentHash, version: lease.version, lease_epoch: lease.lease_epoch, + owner: lease.owner, store_identity: requireNonEmptyString(request.provider_identity, "provider identity"), + provider_revision: requireNonEmptyString(request.provider_revision, "provider revision")}, + observation_fingerprint: progress.fingerprint}; +} + +function fencesPreparedGeneration(prepared: HeartbeatPreparedLease, lease: JsonObject): boolean { + return prepared.prepared_lease_epoch !== undefined + && typeof lease.lease_epoch === "number" && Number.isSafeInteger(lease.lease_epoch) + && lease.lease_epoch > prepared.prepared_lease_epoch + && typeof lease.version === "number" && Number.isSafeInteger(lease.version) + && lease.version > prepared.prepared_lease_version + && typeof lease.idempotency_key === "string" && !!lease.idempotency_key + && createHash("sha256").update(lease.idempotency_key).digest("hex") !== prepared.prepared_lease_key_sha256; +} + +/** Read-only recovery advice; commit independently verifies this proof under its writer fence. */ +export async function observeFencedExecution(root: string, identity: ReturnType, + receipt: JsonObject): Promise { + const prepared = heartbeatPreparedWorkAdmission(receipt, identity); + if (!prepared || prepared.prepared_lease_epoch === undefined || !identity.todo_id + || optionalAssignedReplan(receipt)) return null; + const store = await openRuntimeAuthorityStore(root, identity.goal_id, {}).catch(() => null); + if (!(store instanceof FileAuthorityStore) && !(store instanceof SqliteAuthorityStore)) return null; + const head = await store.loadAuthority(); + if (head.status !== "loaded" || head.head.handoff_mode !== "hard_lease") return null; + const projection = indexCoordinationProjection(head.head, identity.goal_id); + const todo = projection.todos.get(identity.todo_id); + const rawLease = projection.leases.get(identity.todo_id); + if (!todo || todo.status !== "open" || todo.role !== "agent" || todo.task_class !== "advancement_task" + || todo.archive_state !== "active" || !rawLease) return null; + const lease = canonicalTaskLease(rawLease, identity.goal_id, identity.todo_id); + if (!fencesPreparedGeneration(prepared, lease)) return null; + return {original_prepared_epoch: prepared.prepared_lease_epoch, current_lease_epoch: lease.lease_epoch, + current_lease_version: lease.version, current_owner: lease.owner, + current_control_writer_active: todo.claimed_by === identity.agent_id && lease.owner === identity.agent_id + && leaseRepositoryRejection(todo, lease) === null && leaseIsActive(lease, new Date())}; +} + +function optionalAssignedReplan(receipt: JsonObject): boolean { + const id = heartbeatReceiptDetails(receipt).semantic_replan_obligation_id; + return id != null && id !== ""; +} + +export const EXECUTION_LOSS_COMMIT_SCHEMA = "quota_execution_loss_closeout_commit_v0"; +export const EXECUTION_LOSS_COMMIT_RESULT_SCHEMA = "quota_execution_loss_closeout_result_v0"; + +function reject(message: string, code = "refresh_task_lease_unavailable"): never { + throw new EffectRuntimeRequestError(`execution-loss closeout ${message}`, code); +} +const digest = (bytes: Uint8Array): string => createHash("sha256").update(bytes).digest("hex"); +function optionalBytes(path: string): Buffer | null { + try {return readFileSync(path);} + catch (error) {if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; throw error;} +} +const bytes = (path: string): Buffer => optionalBytes(path) ?? Buffer.alloc(0); +function rows(path: string): JsonObject[] { + const content = bytes(path); + if (content.length && content[content.length - 1] !== 10) + reject("has an incomplete history tail; retain the immutable Run for inspection", "execution_loss_commit_unknown"); + return content.toString("utf8").split(/\r?\n/u).filter(line => line.trim()).map(line => { + try {return requireJsonObject(JSON.parse(line), "closeout history row");} + catch {reject("has malformed history", "execution_loss_commit_unknown");} + }); +} +function immutableText(path: string, content: string): void { + const existing = optionalBytes(path); + if (existing !== null) { + if (existing.toString("utf8") !== content) reject("immutable artifact differs", "execution_loss_commit_unknown"); + return; + } + mkdirSync(dirname(path), {recursive: true, mode: 0o700}); + const temporary = `${path}.tmp-${randomUUID()}`; + try { + const fd = openSync(temporary, "wx", 0o600); + try {writeFileSync(fd, content, "utf8"); fsyncSync(fd);} finally {closeSync(fd);} + renameSync(temporary, path); + if (process.platform !== "win32") { + const directory = openSync(dirname(path), "r"); + try {fsyncSync(directory);} finally {closeSync(directory);} + } + } finally {try {unlinkSync(temporary);} catch (error) {if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;}} +} + +/** No alternate writer hooks or semantic defaults enter this closed intent. */ +export function decodeExecutionLossCloseoutIntent(value: unknown): JsonObject { + const intent = requireJsonObject(value, "administrative closeout intent"); + if (Object.keys(intent).sort().join("|") !== + ["delivery_outcome", "delivery_boundary", "progress_observation"].sort().join("|") + || intent.delivery_outcome !== "outcome_gap" || intent.delivery_boundary !== "semantic_closeout") + reject("permits only explicit blocked no-spend intent"); + return {...intent, progress_observation: requireJsonObject(intent.progress_observation, "blocked observation")}; +} + +function rejectRequestedEffects(value: unknown): void { + const effects = requireJsonObject(value, "requested administrative effects"); + const route = ["command", "format", "subcommand_format", "registry", "runtime_root", "goal_id", "goal_instance_id", + "project", "state_file", "classification", "execution_loss_closeout", "agent_id", "todo_id", "turn_instance_id", + "delivery_outcome", "delivery_boundary", "delivery_batch_scale", "progress_result_class", "progress_work_item_id", + "progress_blocker_id", "progress_evidence_ids", "task_lease_idempotency_key", "task_lease_expected_version", + "no_global_sync", "suppress_external_sinks", "quiet", "thin", "verbose", "dry_run"]; + for (const [field, value] of Object.entries(effects)) { + if (field === "delivery_batch_scale" && value !== null && value !== undefined && value !== "single_surface") + reject("permits only single-surface administrative closeout"); + if (!route.includes(field) && value !== null && value !== undefined && value !== false + && !(Array.isArray(value) && value.length === 0)) reject(`does not permit ${field}`); + } +} + +export async function commitExecutionLossCloseout(value: unknown): Promise { + const request = requireJsonObject(value, "administrative closeout request"); + if (request.schema_version !== EXECUTION_LOSS_COMMIT_SCHEMA || request.execution_loss_closeout !== true) + reject("requires its explicit typed operation"); + const permitted = ["schema_version", "execution_loss_closeout", "runtime_root", "identity", "goal_ref", + "source_admission", "registry_source", "locks", "intent", "control_writer_proof", "observed_at", "requested_effects", "dry_run"]; + if (typeof request.dry_run !== "boolean") reject("requires an explicit preview or execution mode"); + if (Object.keys(request).some(field => !permitted.includes(field))) reject("has unsupported requested effects"); + rejectRequestedEffects(request.requested_effects ?? {}); + const root = requireLocalAuthorityRuntimeRoot(request.runtime_root); + const binding = requireJsonObject(request.identity, "original identity"); + const identity = settlementIdentity({goal_id: requireNonEmptyString(binding.goal_id, "goal_id"), + agent_id: requireNonEmptyString(binding.agent_id, "agent_id"), todo_id: requireNonEmptyString(binding.todo_id, "todo_id"), + turn_instance_id: requireNonEmptyString(binding.turn_instance_id, "turn_instance_id")}); + if (!isDeepStrictEqual(binding, settlementIdentityPayload(identity))) reject("identity is not canonical"); + const intent = decodeExecutionLossCloseoutIntent(request.intent); + const owner = parseQuotaAccountingOwner({goalRefValue: request.goal_ref, + sourceAdmissionValue: request.source_admission, runtimeRoot: root, goalId: identity.goal_id}); + if (owner.kind === "alias" && (Object.hasOwn(request, "goal_ref") || Object.hasOwn(request, "source_admission"))) + reject("legacy ownership requires absent exact-source fields"); + const registrySource = requireJsonObject(request.registry_source, "registry source"); + const registryPath = resolve(requireNonEmptyString(registrySource.path, "registry path")); + const lifetimeSources = registrySource.lifetime_sources ?? []; + if (!Array.isArray(lifetimeSources) || lifetimeSources.length > 1 + || (owner.kind === "exact_source" && lifetimeSources.length)) reject("legacy source lifetime is unsupported"); + const upstream = lifetimeSources.map(source => requireJsonObject(source, "legacy source lifetime")); + if (owner.kind === "exact_source" && registryPath !== owner.admission.registryPath) + reject("registry differs from the original source admission"); + const indexPath = join(root, "goals", identity.goal_id, "runs", "index.jsonl"); + const eventPath = goalRolloutEventLogPath(root, identity.goal_id); + const artifact = join(dirname(indexPath), `execution-loss-${createHash("sha256").update(identity.effect_id).digest("hex")}`); + const jsonPath = `${artifact}.json`, markdownPath = `${artifact}.md`; + const targets = [shadowMaintenanceLockPath(root, identity.goal_id), eventPath, + ...(owner.kind === "alias" ? [indexPath, registryPath, + ...upstream.map(source => requireNonEmptyString(source.path, "legacy source path"))] : [])] + .map(path => resolve(path)); + const requestDigest = canonicalAuthoritySha256({identity: binding, goal_ref: quotaGoalRef(owner), intent}); + const claims: FileMutationLockClaim[] = []; + try { + if (!Array.isArray(request.locks) || request.locks.length !== targets.length) + reject("requires the existing writer/lifetime lock handoff"); + for (const [index, value] of request.locks.entries()) { + const witness = requireJsonObject(value, "writer lock witness"); + if (resolve(String(witness.target)) !== targets[index]) reject("writer lock target differs"); + const token = requireNonEmptyString(witness.token, "lock token"); + const claim = await claimFileMutationLock(targets[index], token); + if (!claim) reject("writer lock handoff expired"); + claims.push(claim); + const current = await mutationLockOwner(targets[index]); + if (current?.token !== token || current.pid !== witness.pid) reject("writer lock owner changed"); + } + return await withBorrowedQuotaAccountingOwner(owner, async () => { + const registryBytes = readFileSync(registryPath); + if (digest(registryBytes) !== registrySource.sha256) reject("current registry changed"); + // The existing registry codec validated this transport observation. Bind + // it to complete bytes; exact-source absence cannot become a legacy alias. + const document = JSON.parse(registryBytes.toString("utf8")); + const registry = requireJsonObject(registrySource.payload, "decoded registry source"); + const rawPayload = Array.isArray(document) && document.length === 2 ? document[1] : document; + if (!isDeepStrictEqual(registry, rawPayload) + || (registry.profile_id === "source_session_v1") !== (owner.kind === "exact_source")) + reject("registry profile and receipt ownership differ"); + const goals = registry.goals; + if (!Array.isArray(goals)) reject("registry Goal authority is unavailable"); + const matches = goals.filter(goal => jsonObject(goal)?.id === identity.goal_id).map(goal => requireJsonObject(goal, "Goal")); + const goal = matches[0]; + if (matches.length !== 1 || !goal || (owner.kind === "alias" + ? !legacyGoalRegistrationIsActive(goal.status ?? "active") : goal.status !== "active") + || Object.hasOwn(goal, "activation_state") + || (goal.activation != null && (jsonObject(goal.activation)?.schema_version != null + && jsonObject(goal.activation)?.schema_version !== "loopx_goal_activation_v1" + || jsonObject(goal.activation)?.state !== "active")) + || (owner.kind === "exact_source" && goal.goal_instance_id !== owner.goalRef.goalInstanceId.value)) + reject("current Goal is stopped, unavailable or recreated"); + const sourceRoute = goal.source_registry; + const expectedUpstream = owner.kind === "alias" && typeof sourceRoute === "string" && sourceRoute.trim() + ? resolve(dirname(registryPath), sourceRoute.trim()) : null; + if ((sourceRoute != null && sourceRoute !== "" && typeof sourceRoute !== "string") + || (expectedUpstream === null ? upstream.length !== 0 + : upstream.length !== 1 || resolve(String(upstream[0].path)) !== expectedUpstream)) + reject("current legacy source route differs from its lifetime admission"); + for (const source of upstream) { + const sourceBytes = readFileSync(String(source.path)); + const sourcePayload = requireJsonObject(source.payload, "legacy source registry"); + const raw = JSON.parse(sourceBytes.toString("utf8")); + if (digest(sourceBytes) !== source.sha256 || !isDeepStrictEqual(sourcePayload, Array.isArray(raw) ? raw[1] : raw) + || sourcePayload.profile_id === "source_session_v1") reject("legacy source ownership changed"); + const sourceGoals = Array.isArray(sourcePayload.goals) ? sourcePayload.goals.map(jsonObject) : []; + const sourceGoal = sourceGoals.filter(row => row?.id === identity.goal_id); + if (sourceGoal.length !== 1 || !legacyGoalRegistrationIsActive(sourceGoal[0]?.status ?? "active") + || Object.hasOwn(sourceGoal[0]!, "activation_state") + || (sourceGoal[0]?.activation != null && jsonObject(sourceGoal[0].activation)?.state !== "active")) + reject("legacy source Goal is unavailable or stopped"); + } + const authority = decodeTaskLeaseAuthority({handoff_mode: "hard_lease", todos: [], + registered_agent_candidates: [jsonObject(goal.coordination)?.registered_agents, goal.registered_agents, + jsonObject(goal.spawn_policy)?.registered_agents], + source_receipts: [{source_id: "registry", path: registryPath, state: "file", sha256: digest(registryBytes)}]}); + rows(indexPath); rows(eventPath); + const indexDigest = digest(bytes(indexPath)), eventDigest = digest(bytes(eventPath)); + const snapshot = await readQuotaSettlementSnapshot(root, identity.goal_id); + const readback = readQuotaSettlementForAdmittedOwnerFromSnapshot({ + schema_version: QUOTA_SETTLEMENT_READBACK_REQUEST_SCHEMA, runtime_root: root, + goal_id: identity.goal_id, agent_id: identity.agent_id, todo_id: identity.todo_id, + turn_instance_id: identity.turn_instance_id, infer_turn_instance_id: false, allow_unbound_binding: false, + }, owner, snapshot, {includeOriginalPreparedReceipt: true}); + const receipt = jsonObject(readback.original_prepared_receipt); + if (receipt === null) reject("the original Turn's positive prepared admission is unavailable"); + requireQuotaOwnerProjection(owner, receipt.goal_ref, "original heartbeat receipt"); + if (jsonObject(readback.identity)?.failure != null) reject("original settlement identity could not be verified"); + const existingBytes = optionalBytes(jsonPath); + let existing: JsonObject | null = null; + if (existingBytes !== null) { + try {existing = requireJsonObject(JSON.parse(existingBytes.toString("utf8")), "immutable closeout Run");} + catch {reject("immutable Run is empty or malformed", "execution_loss_commit_unknown");} + } + if (existing && jsonObject(existing.execution_loss_commit)?.request_sha256 !== requestDigest) + reject("intent differs from the original immutable Run", "committed_writeback_payload_conflict"); + const prior = jsonObject(readback.writeback_run); + if (prior && (!existing || !isDeepStrictEqual(prior, existing))) + reject("cannot replace the original writeback", "committed_writeback_payload_conflict"); + if (readback.spend_run != null || readback.spend_event != null || readback.completion_event != null + || readback.supersede_event != null || (!existing && readback.writeback_event != null)) + reject("cannot erase business completion or a committed debit"); + if (!existing && (readback.replay_phase !== "open" || jsonObject(readback.progress)?.state !== "writeback_required")) + reject("requires the original unclosed first writeback"); + if (existing && prior && readback.replay_phase === "settled") { + return closeoutReply(readback, root, binding, prior, owner, request.dry_run === true, true); + } + await requireShadowPrimaryWriteAllowed(root, identity.goal_id); + const store = await openRuntimeAuthorityStore(root, identity.goal_id, {}); + if (!(store instanceof FileAuthorityStore) && !(store instanceof SqliteAuthorityStore)) + reject("supports only the existing File and SQLite provider fences"); + const result = await store.withCheckpointHead((head, providerIdentity) => { + // No await from current canonical head through all durable writes. + if (digest(readFileSync(registryPath)) !== registrySource.sha256 + || digest(bytes(indexPath)) !== indexDigest || digest(bytes(eventPath)) !== eventDigest) + reject("sources changed before administrative commit"); + if (upstream.some(source => digest(readFileSync(String(source.path))) !== source.sha256)) + reject("legacy source changed before administrative commit"); + requireCurrentQuotaAccountingOwner(owner); + const projection = indexCoordinationProjection(head.head, identity.goal_id); + if (head.head.handoff_mode !== "hard_lease") reject("requires original hard-lease authority"); + const qualification = qualifyReceiptBoundExecutionLossCloseout({ + schema_version: EXECUTION_LOSS_QUALIFICATION_SCHEMA, identity: binding, + ...(owner.kind === "exact_source" ? {goal_ref: quotaGoalRef(owner)} : {}), receipt, + current_todo: projection.todos.get(identity.todo_id!), current_lease: projection.leases.get(identity.todo_id!), + registered_agents: authority.registered_agents, control_writer_proof: request.control_writer_proof, + progress_observation: intent.progress_observation, observed_at: request.observed_at, + provider_identity: providerIdentity, provider_revision: head.provider_revision, + }); + const buildRun = (qualified: JsonObject, observedAt: unknown): JsonObject => { + const event = {schema_version: "loopx_rollout_event_v0", + event_id: createHash("sha256").update(`${identity.effect_id}#execution-loss-closeout`).digest("hex"), + event_kind: "refresh_state", goal_id: identity.goal_id, agent_id: identity.agent_id, + todo_id: identity.todo_id, run_id: identity.turn_instance_id, status: "appended", + recorded_at: observedAt, ...(owner.kind === "exact_source" ? {goal_ref: quotaGoalRef(owner)} : {}), + details: {settlement_effect_id: identity.effect_id, execution_loss_closeout: qualified}}; + return {generated_at: observedAt, goal_id: identity.goal_id, agent_id: identity.agent_id, + todo_id: identity.todo_id, turn_instance_id: identity.turn_instance_id, settlement_identity: binding, + ...(owner.kind === "exact_source" ? {goal_ref: quotaGoalRef(owner)} : {}), + classification: "execution_loss_closeout", delivery_outcome: "outcome_gap", delivery_batch_scale: "single_surface", + delivery_boundary: "semantic_closeout", progress_observation: intent.progress_observation, + blocked_retry: qualified, execution_loss_closeout: qualified, + json_path: jsonPath, markdown_path: markdownPath, + execution_loss_commit: {schema_version: EXECUTION_LOSS_COMMIT_SCHEMA, request_sha256: requestDigest, + original_receipt_sha256: canonicalAuthoritySha256(receipt), event}}; + }; + if (request.dry_run === true) return {record: buildRun(qualification, request.observed_at), preview: true}; + let record = existing; + if (!record) { + record = buildRun(qualification, request.observed_at); + immutableText(jsonPath, JSON.stringify(record, null, 2) + "\n"); + } else { + const frozen = jsonObject(record.execution_loss_closeout); + if (!frozen || !isExecutionLossCloseout(frozen, identity.todo_id) + || frozen.effect_id !== identity.effect_id || frozen.observed_at !== record.generated_at + || frozen.original_receipt_event_id !== receipt.event_id + || !isDeepStrictEqual(frozen.original_prepared, qualification.original_prepared) + || jsonObject(frozen.current_control_writer)?.owner !== identity.agent_id + || jsonObject(frozen.current_control_writer)?.store_identity !== providerIdentity + || frozen.observation_fingerprint !== jsonObject(intent.progress_observation)?.fingerprint + || !isDeepStrictEqual(record, buildRun(frozen, record.generated_at))) + reject("immutable Run does not match original administrative intent", "execution_loss_commit_unknown"); + } + const event = requireJsonObject(requireJsonObject(record.execution_loss_commit, "closeout intent").event, "closeout receipt"); + if (event.event_kind !== "refresh_state" || event.run_id !== identity.turn_instance_id + || jsonObject(event.details)?.settlement_effect_id !== identity.effect_id + || !isDeepStrictEqual(jsonObject(event.details)?.execution_loss_closeout, record.execution_loss_closeout)) + reject("immutable refresh receipt is invalid", "execution_loss_commit_unknown"); + immutableText(markdownPath, `# Administrative execution-loss closeout\n\nTurn: ${identity.turn_instance_id}\nNo delivery, completion or quota spend.\n`); + const indexed = rows(indexPath).filter(row => jsonObject(row.settlement_identity)?.effect_id === identity.effect_id); + if (indexed.length > 1 || (indexed.length === 1 && !isDeepStrictEqual(indexed[0], record))) + reject("indexed writeback differs", "execution_loss_commit_unknown"); + const recorded = rows(eventPath).filter(row => row.event_id === event.event_id); + if (recorded.length > 1 || (recorded.length === 1 && !isDeepStrictEqual(recorded[0], event))) + reject("refresh receipt differs", "execution_loss_commit_unknown"); + if (!indexed.length) appendJsonLineSync(indexPath, record); + if (!recorded.length) appendJsonLineSync(eventPath, event); + return {record, replayed: indexed.length === 1 && recorded.length === 1}; + }); + if (result.preview === true) { + return closeoutReply(readback, root, binding, requireJsonObject(result.record, "preview Run"), owner, true, false); + } + const finalSnapshot = await readQuotaSettlementSnapshot(root, identity.goal_id); + const final = readQuotaSettlementForAdmittedOwnerFromSnapshot({schema_version: QUOTA_SETTLEMENT_READBACK_REQUEST_SCHEMA, + runtime_root: root, goal_id: identity.goal_id, agent_id: identity.agent_id, todo_id: identity.todo_id, + turn_instance_id: identity.turn_instance_id, infer_turn_instance_id: false, allow_unbound_binding: false}, owner, finalSnapshot); + if (final.replay_phase !== "settled") reject("durable no-spend readback is incomplete", "execution_loss_commit_unknown"); + return closeoutReply(final, root, binding, requireJsonObject(result.record, "closeout Run"), owner, false, + result.replayed === true); + }); + } finally {for (const claim of claims.reverse()) await releaseFileMutationLockClaim(claim);} +} + +function closeoutReply(readback: JsonObject, root: string, binding: JsonObject, + record: JsonObject, owner: QuotaAccountingOwner, preview: boolean, replayed: boolean): JsonObject { + return {schema_version: EXECUTION_LOSS_COMMIT_RESULT_SCHEMA, ok: true, mode: "execution_loss_closeout", + classification: "execution_loss_closeout", appended: !preview && !replayed, idempotent_replay: replayed, + dry_run: preview, runtime_root: root, goal_id: binding.goal_id, settlement_identity: binding, + ...(owner.kind === "exact_source" ? {goal_ref: quotaGoalRef(owner)} : {}), + execution_loss_closeout: record.execution_loss_closeout, + ...(preview ? {would_close_without_spend: !replayed} : {json_path: record.json_path, markdown_path: record.markdown_path}), + settlement_progress: readback.progress, replay_phase: readback.replay_phase, + settlement_result: jsonObject(readback.settlement)?.payload}; +} diff --git a/loopx/control_plane/quota/execution_loss_closeout_record.ts b/loopx/control_plane/quota/execution_loss_closeout_record.ts new file mode 100644 index 0000000000..baed472470 --- /dev/null +++ b/loopx/control_plane/quota/execution_loss_closeout_record.ts @@ -0,0 +1,42 @@ +/** Frozen administrative closeout record. Reading history never loads current lease authority. */ +import {isDeepStrictEqual} from "node:util"; +import type {JsonObject} from "../effect_program.ts"; +import {BARE_SHA256_PATTERN} from "../content_digest.ts"; +import {requireJsonObject} from "../runtime_decode.ts"; +import {parseTodoTimestampMicros} from "../runtime_timestamp.ts"; +import {heartbeatPreparedLease} from "./heartbeat_receipt_identity.ts"; + +export const EXECUTION_LOSS_CLOSEOUT_SCHEMA = "quota_execution_loss_closeout_v0"; + +/** Historical readback validates the frozen qualification, not today's lease. */ +export function isExecutionLossCloseout(value: unknown, todoId: string | null): boolean { + const closeout = typeof value === "object" && value !== null && !Array.isArray(value) ? value as JsonObject : null; + if (!closeout || closeout.schema_version !== EXECUTION_LOSS_CLOSEOUT_SCHEMA || !todoId + || closeout.todo_id !== todoId || closeout.source !== "turn_settlement" + || Object.keys(closeout).sort().join("|") !== ["schema_version", "effect_id", "todo_id", "source", + "observed_at", "original_receipt_event_id", "original_prepared", "current_control_writer", + "observation_fingerprint"].sort().join("|")) return false; + try { + const original = requireJsonObject(closeout.original_prepared, "original preparation"); + const prepared = heartbeatPreparedLease(original); + const writer = requireJsonObject(closeout.current_control_writer, "control-writer witness"); + if (typeof closeout.observed_at !== "string" + || parseTodoTimestampMicros(closeout.observed_at, true) === null) return false; + return !!prepared && prepared.prepared_lease_epoch !== undefined + && isDeepStrictEqual(original, prepared) + && Object.keys(writer).sort().join("|") === ["lease_key_sha256", "version", "lease_epoch", "owner", + "store_identity", "provider_revision"].sort().join("|") + && typeof closeout.effect_id === "string" && !!closeout.effect_id + && BARE_SHA256_PATTERN.test(String(writer.lease_key_sha256)) + && writer.lease_key_sha256 !== prepared.prepared_lease_key_sha256 + && typeof writer.version === "number" && Number.isSafeInteger(writer.version) + && writer.version > prepared.prepared_lease_version + && typeof writer.lease_epoch === "number" && Number.isSafeInteger(writer.lease_epoch) + && writer.lease_epoch > prepared.prepared_lease_epoch + && typeof closeout.original_receipt_event_id === "string" && !!closeout.original_receipt_event_id + && typeof writer.owner === "string" && !!writer.owner + && typeof writer.store_identity === "string" && !!writer.store_identity + && typeof writer.provider_revision === "string" && !!writer.provider_revision + && /^[a-f0-9]{16}$/u.test(String(closeout.observation_fingerprint)); + } catch {return false;} +} diff --git a/loopx/control_plane/quota/execution_preparation.py b/loopx/control_plane/quota/execution_preparation.py index 64cc7162c1..d2f153925a 100644 --- a/loopx/control_plane/quota/execution_preparation.py +++ b/loopx/control_plane/quota/execution_preparation.py @@ -3,7 +3,7 @@ import hashlib import shlex from collections.abc import Iterator, Mapping -from contextlib import ExitStack, contextmanager +from contextlib import ExitStack, nullcontext, contextmanager from pathlib import Path from typing import TYPE_CHECKING, Any @@ -145,6 +145,80 @@ class RefreshTaskLeaseUnavailable(ValueError): code = "refresh_task_lease_unavailable" +def commit_execution_loss_closeout( + *, registry_path: Path, runtime_root_override: str | None, goal_id: str, agent_id: str, + todo_id: str, turn_instance_id: str, goal_ref: Mapping[str, Any] | None, + requested_proof: Mapping[str, Any] | None, progress_observation: Mapping[str, Any] | None, + delivery_outcome: str | None, delivery_boundary: str | None, + requested_effects: Mapping[str, Any], dry_run: bool, +) -> dict[str, Any]: + """Transport one explicit administrative intent; TS owns every verdict/write.""" + from ...file_lock import cross_runtime_lock_witness + from ...paths import resolve_runtime_root + from ..effect_runtime import EffectRuntimeRejected + from ..goals.first_party_host_admission import FirstPartyHostGoalAdmission + from ..projects.registry_codec import load_project_registry + from ..runtime.time import now_local_iso + from ..work_items.progress_observation import normalize_progress_observation + from .accounting_admission import quota_accounting_admission + from .settlement import SettlementIdentity + + registry_path = registry_path.expanduser().resolve() + registry = load_project_registry(registry_path) + root = resolve_runtime_root(registry, runtime_root_override, registry_path=registry_path) + identity = SettlementIdentity(goal_id=goal_id, agent_id=agent_id, todo_id=todo_id, + turn_instance_id=turn_instance_id).as_dict() + progress = (normalize_progress_observation(progress_observation, work_item_id=todo_id) + if progress_observation is not None else None) + admission = FirstPartyHostGoalAdmission.for_plan(registry_path=registry_path, + goal_id=goal_id, planned_goal_ref=goal_ref, agent_id=agent_id) + with quota_accounting_admission(runtime_root=root, registry_path=registry_path, + goal_id=goal_id, goal_ref=goal_ref, operation="execution-loss-closeout", + handoff_legacy_index=True) as source_admission: + lifetime = (nullcontext() if source_admission is not None + else admission._legacy_lifetime(operation="execution-loss-closeout", launch=False)) + with lifetime, ExitStack() as locks: + targets = [shadow_maintenance_lock_target(root, goal_id), + root / "goals" / goal_id / "rollout-event-log.jsonl"] + for target in targets: + # Existing quota requalification can own the rollout lock + # before asking for index/source; do not wait in reverse order. + locks.enter_context(exclusive_cross_runtime_file_lock(target, + timeout_seconds=0, operation="execution-loss-closeout")) + raw = registry_path.read_bytes() + witnesses = [cross_runtime_lock_witness(target) for target in targets] + lifetime_sources = [] + if source_admission is None: + witnesses.append(cross_runtime_lock_witness(root / "goals" / goal_id / "runs" / "index.jsonl")) + witnesses.append(cross_runtime_lock_witness(registry_path)) + upstream = admission.legacy_source_admission + while upstream is not None: + source_path = upstream.registry_path + source_bytes = source_path.read_bytes() + lifetime_sources.append({"path": str(source_path), "sha256": hashlib.sha256(source_bytes).hexdigest(), + "payload": load_project_registry(source_path)}) + witnesses.append(cross_runtime_lock_witness(source_path)) + upstream = upstream.legacy_source_admission + request = {"schema_version": "quota_execution_loss_closeout_commit_v0", + "execution_loss_closeout": True, "dry_run": dry_run, "runtime_root": str(root), "identity": identity, + **({"goal_ref": dict(goal_ref)} if goal_ref is not None else {}), + **({"source_admission": source_admission} if source_admission is not None else {}), + "registry_source": {"path": str(registry_path), "sha256": hashlib.sha256(raw).hexdigest(), + "payload": load_project_registry(registry_path), "lifetime_sources": lifetime_sources}, "locks": witnesses, + "intent": {"delivery_outcome": delivery_outcome, "delivery_boundary": delivery_boundary, + "progress_observation": progress}, "control_writer_proof": dict(requested_proof) if requested_proof else None, + "requested_effects": dict(requested_effects), "observed_at": now_local_iso()} + try: + result = effect_runtime_result("quota.execution_loss_closeout.commit", request) + except EffectRuntimeRejected as exc: + error = RefreshTaskLeaseUnavailable(str(exc)) + error.code = exc.diagnostic_code + raise error from exc + if not isinstance(result, dict) or result.get("schema_version") != "quota_execution_loss_closeout_result_v0": + raise RuntimeError("typed execution-loss closeout returned an invalid result") + return result + + def read_active_task_lease_epoch( *, runtime_root: Path, diff --git a/loopx/control_plane/quota/heartbeat_receipt_identity.ts b/loopx/control_plane/quota/heartbeat_receipt_identity.ts index 6935ac3614..d08e40b0de 100644 --- a/loopx/control_plane/quota/heartbeat_receipt_identity.ts +++ b/loopx/control_plane/quota/heartbeat_receipt_identity.ts @@ -10,7 +10,7 @@ * this rule, so it lives here rather than in either caller. */ import type { JsonObject } from "../effect_program.ts"; -import {executionRequestSubject, settlementIdentity, type SettlementIdentity, type ExecutionRequestSubject} from "../effect_program.ts"; +import {effectIdsMatch, executionRequestSubject, settlementIdentity, type SettlementIdentity, type ExecutionRequestSubject} from "../effect_program.ts"; import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts"; import { BARE_SHA256_PATTERN } from "../content_digest.ts"; import { jsonObject, requireJsonObject } from "../runtime_decode.ts"; @@ -258,7 +258,7 @@ export function selectAdmissionHeartbeatReceipt( return identities.size === 1 ? [...identities.values()][0]! : null; } -interface HeartbeatPreparedLease extends JsonObject { +export interface HeartbeatPreparedLease extends JsonObject { prepared_lease_key_sha256: string; prepared_lease_version: number; prepared_lease_epoch?: number; @@ -278,6 +278,26 @@ export function heartbeatPreparedLease(details: JsonObject): HeartbeatPreparedLe ...(epoch === undefined ? {} : {prepared_lease_epoch: epoch})}; } +export function heartbeatPreparedWorkAdmission( + event: JsonObject, + identity: SettlementIdentity, +): HeartbeatPreparedLease | null { + const fact = heartbeatReceiptFactFromEvent(event); + const binding = heartbeatReceiptBinding(identity.goal_id, identity.agent_id, fact); + const receiptDetails = heartbeatReceiptDetails(event); + if (event.schema_version !== "loopx_rollout_event_v0" || event.event_kind !== "quota_should_run" + || event.goal_id !== identity.goal_id || event.agent_id !== identity.agent_id + || fact.run_id !== identity.turn_instance_id || fact.todo_id !== identity.todo_id + || binding?.binding_kind !== "todo" || binding.binding_id !== identity.todo_id + || (fact.settlement_effect_id !== null && !effectIdsMatch(fact.settlement_effect_id, identity.effect_id)) + || fact.closeout_required !== true + || (Object.hasOwn(receiptDetails, "prepared_lease_required") && receiptDetails.prepared_lease_required !== true) + || nativeChildReportAdmission(receiptDetails, event.status, identity.effect_id, "open", false, + normalizeHeartbeatReplanObligationId(receiptDetails.semantic_replan_obligation_id)) + .report_permission !== "new_operation") return null; + return heartbeatPreparedLease(receiptDetails); +} + export function isHeartbeatLeaseReadiness(event: JsonObject): boolean { return heartbeatReceiptDetails(event).settlement_receipt_revision === "lease_readiness"; } diff --git a/loopx/control_plane/quota/scheduler_ack.py b/loopx/control_plane/quota/scheduler_ack.py index b0dcba0df2..f78de83ff3 100644 --- a/loopx/control_plane/quota/scheduler_ack.py +++ b/loopx/control_plane/quota/scheduler_ack.py @@ -8,6 +8,7 @@ from pathlib import Path from ..effect_runtime import _node_executable +from ..runtime.node_probe import node_typescript_flags from ..runtime.time import now_local_iso from ..scheduler.state import ( CODEX_APP_STATEFUL_BACKOFF_STATE_KEY, @@ -217,6 +218,7 @@ def _run_native_followup( _node_executable(), "--no-warnings", "--experimental-strip-types", + *node_typescript_flags(), str( Path(__file__).resolve().parents[1] / "scheduler" diff --git a/loopx/control_plane/quota/settlement_cli.py b/loopx/control_plane/quota/settlement_cli.py index af15708a63..c22d45aa3e 100644 --- a/loopx/control_plane/quota/settlement_cli.py +++ b/loopx/control_plane/quota/settlement_cli.py @@ -513,7 +513,11 @@ def quota_rollout_details( details["admission_resume_when"] = selected_todo.get("resume_when") details["admission_resume_ready"] = selected_todo.get("resume_ready") recovery = payload.get("unsettled_host_turn_recovery") - if isinstance(recovery, Mapping) and recovery.get("state") == "recovery_required": + if ( + not getattr(args, "scheduler_observation", False) + and isinstance(recovery, Mapping) + and recovery.get("state") == "recovery_required" + ): checkpoint = recovery.get("admission_checkpoint") if isinstance(checkpoint, Mapping): details.update(checkpoint) diff --git a/loopx/control_plane/quota/settlement_phase.ts b/loopx/control_plane/quota/settlement_phase.ts index 4836ddf165..92d231e2d7 100644 --- a/loopx/control_plane/quota/settlement_phase.ts +++ b/loopx/control_plane/quota/settlement_phase.ts @@ -3,6 +3,7 @@ import { jsonObject } from "../runtime_decode.ts"; import { parseTodoTimestampMicros } from "../runtime_timestamp.ts"; import { isCanonicalTodoId } from "../todos/identity.ts"; import { blockedResumeInstant, isBlockedLifecycleWait, isCausalBlockedWait, isMonitorUnavailableWait } from "./blocked_wait.ts"; +import {isExecutionLossCloseout} from "./execution_loss_closeout_record.ts"; import { isTurnScopedSettlementOutcome } from "../work_items/delivery_outcome.ts"; function retryDelayIsBounded(seconds: number): boolean { @@ -13,6 +14,7 @@ function retryDelayIsBounded(seconds: number): boolean { * retry/causal wait, blocked lifecycle or a Monitor unavailable attempt. * A lifecycle/Monitor closeout creates no retry clock or execution grant. */ export function isBoundedBlockedRetry(value: unknown, todoId: string | null): boolean { + if (isExecutionLossCloseout(value, todoId)) return true; if (isCausalBlockedWait(value, todoId)) return true; if (isBlockedLifecycleWait(value, todoId)) return true; if (isMonitorUnavailableWait(value, todoId)) return true; diff --git a/loopx/control_plane/quota/settlement_readback.ts b/loopx/control_plane/quota/settlement_readback.ts index ee4da148d5..67b4b1be40 100644 --- a/loopx/control_plane/quota/settlement_readback.ts +++ b/loopx/control_plane/quota/settlement_readback.ts @@ -1,5 +1,8 @@ import { createHash } from "node:crypto"; import { isAbsolute, join } from "node:path"; +import {isDeepStrictEqual} from "node:util"; +import {canonicalAuthoritySha256} from "../coordination/authority_store_codec.ts"; +import {EXECUTION_LOSS_CLOSEOUT_SCHEMA, isExecutionLossCloseout} from "./execution_loss_closeout_record.ts"; import { readReceiptLogSnapshot } from "../runtime/receipt_log_snapshot.ts"; import { @@ -66,6 +69,7 @@ import { selectEffectiveHeartbeatReceipt, heartbeatWorkRequalification, heartbeatPreparedLease, + heartbeatPreparedWorkAdmission, isHeartbeatLeaseReadiness, type HeartbeatReceiptFact, } from "./heartbeat_receipt_identity.ts"; @@ -86,6 +90,7 @@ import { } from "../work_items/replan_semantics.ts"; import { parseQuotaAccountingOwner, + quotaGoalRef, quotaOwnerOwnsProjection, withBorrowedQuotaAccountingOwner, withQuotaAccountingOwner, @@ -1384,6 +1389,7 @@ function readQuotaSettlementFromRequest( snapshot: QuotaSettlementReadbackSnapshot, nameOwedPriorTurn = true, matchedSpend?: MatchedSpendRecords, + includeOriginalPreparedReceipt = false, ): JsonObject { if ( snapshot.runtimeRoot !== request.runtime_root || @@ -1482,6 +1488,45 @@ function readQuotaSettlementFromRequest( } const completionEvent = findStepEvent(events, identity, "todo_complete"); const supersedeEvent = findStepEvent(events, identity, "todo_supersede"); + const executionLoss = writebackRun !== null && ( + writebackRun.classification === "execution_loss_closeout" || + writebackRun.execution_loss_closeout !== undefined || writebackRun.execution_loss_commit !== undefined || + jsonObject(writebackRun.blocked_retry)?.schema_version === EXECUTION_LOSS_CLOSEOUT_SCHEMA); + const originalPreparedReceipt = executionLoss || includeOriginalPreparedReceipt + ? heartbeatValidationEvent(events, heartbeatReceipt, identity) : null; + if (executionLoss && writebackRun !== null) { + const closeout = jsonObject(writebackRun.execution_loss_closeout); + const commit = jsonObject(writebackRun.execution_loss_commit); + const permittedRunFields = ["generated_at", "goal_id", "agent_id", "todo_id", "turn_instance_id", + "settlement_identity", "classification", "delivery_outcome", "delivery_batch_scale", "delivery_boundary", + "progress_observation", "blocked_retry", "execution_loss_closeout", "json_path", "markdown_path", + "execution_loss_commit", ...(request.owner.kind === "exact_source" ? ["goal_ref"] : [])]; + if (!closeout || !isExecutionLossCloseout(closeout, identity.todo_id) + || Object.keys(writebackRun).sort().join("|") !== permittedRunFields.sort().join("|") + || writebackRun.classification !== "execution_loss_closeout" + || writebackRun.delivery_outcome !== "outcome_gap" || writebackRun.delivery_boundary !== "semantic_closeout" + || writebackRun.delivery_batch_scale !== "single_surface" || writebackRun.generated_at !== closeout.observed_at + || closeout.effect_id !== identity.effect_id + || originalPreparedReceipt === null + || closeout.original_receipt_event_id !== originalPreparedReceipt.event_id + || !isDeepStrictEqual(closeout.original_prepared, heartbeatPreparedWorkAdmission(originalPreparedReceipt, identity)) + || jsonObject(closeout.current_control_writer)?.owner !== identity.agent_id + || closeout.observation_fingerprint !== jsonObject(writebackRun.progress_observation)?.fingerprint + || !isDeepStrictEqual(writebackRun.blocked_retry, closeout) + || !commit || Object.keys(commit).sort().join("|") !== ["schema_version", "request_sha256", + "original_receipt_sha256", "event"].sort().join("|") + || commit.schema_version !== "quota_execution_loss_closeout_commit_v0" + || commit.original_receipt_sha256 !== canonicalAuthoritySha256(originalPreparedReceipt) + || commit.request_sha256 !== canonicalAuthoritySha256({identity: settlementIdentityPayload(identity), + goal_ref: quotaGoalRef(request.owner), intent: {delivery_outcome: "outcome_gap", delivery_boundary: "semantic_closeout", + progress_observation: writebackRun.progress_observation}}) + || !isDeepStrictEqual(jsonObject(commit.event)?.details, + {settlement_effect_id: identity.effect_id, execution_loss_closeout: closeout}) + || (writebackEvent !== null && !isDeepStrictEqual(writebackEvent, commit.event))) { + throw new EffectRuntimeRequestError("administrative execution-loss receipt differs from original admission", + "malformed_settlement_state"); + } + } const closeoutStarted = [writebackRun, writebackEvent, spendRun, spendEvent, completionEvent, supersedeEvent] .some((receipt) => receipt !== null); @@ -1603,7 +1648,7 @@ function readQuotaSettlementFromRequest( settlement: bundle(settled, includeRecords), terminal_closeout: bundle(terminalCloseout), terminal_settlement: bundle(terminalSettlement), - progress, + progress: executionLoss && noSpendKind ? {...progress, no_spend: true} : progress, workspace_causality: workspaceCausality, semantic_replan_guard: semanticReplanGuard, writeback_run: includeRecords ? writebackRun : null, @@ -1614,6 +1659,9 @@ function readQuotaSettlementFromRequest( ), spend_run: includeRecords ? spendRun : null, heartbeat_receipt: includeRecords ? heartbeatReceipt : null, + ...(includeOriginalPreparedReceipt && originalPreparedReceipt && + heartbeatPreparedWorkAdmission(originalPreparedReceipt, identity) + ? {original_prepared_receipt: originalPreparedReceipt} : {}), ...(preparedLease === null ? {} : {prepared_lease: preparedLease}), ...(receiptDetails.prepared_lease_required === true ? {prepared_lease_required: true} : {}), admission_recorded_at: typeof admissionReceipt?.recorded_at === "string" @@ -1660,8 +1708,10 @@ export function readQuotaSettlementFromSnapshot( export function readAdmittedQuotaSettlementFromSnapshot( value: unknown, snapshot: QuotaSettlementReadbackSnapshot, + options: {includeOriginalPreparedReceipt?: boolean} = {}, ): JsonObject { - return readQuotaSettlementFromRequest(decodeRequest(value), snapshot); + return readQuotaSettlementFromRequest(decodeRequest(value), snapshot, true, undefined, + options.includeOriginalPreparedReceipt); } /** Read under the parsed owner already admitted by the enclosing transaction. */ @@ -1669,8 +1719,10 @@ export function readQuotaSettlementForAdmittedOwnerFromSnapshot( value: unknown, owner: QuotaAccountingOwner, snapshot: QuotaSettlementReadbackSnapshot, + options: {includeOriginalPreparedReceipt?: boolean} = {}, ): JsonObject { - return readQuotaSettlementFromRequest(decodeRequest(value, owner), snapshot); + return readQuotaSettlementFromRequest(decodeRequest(value, owner), snapshot, true, undefined, + options.includeOriginalPreparedReceipt); } export async function readQuotaSettlement(value: unknown): Promise { diff --git a/loopx/control_plane/quota/unsettled_host_turn.py b/loopx/control_plane/quota/unsettled_host_turn.py index 1196069dcd..eca586d362 100644 --- a/loopx/control_plane/quota/unsettled_host_turn.py +++ b/loopx/control_plane/quota/unsettled_host_turn.py @@ -337,7 +337,7 @@ def _unsettled_host_turn_recovery( goal_ref: Mapping[str, Any] | None = None, owner_action_id: str | None = None, ) -> dict[str, Any] | None: - if not agent_id or not current_turn_instance_id: + if not agent_id: return None preflight = _prior_closeout_preflight( runtime_root=runtime_root, @@ -438,8 +438,9 @@ def apply_unsettled_host_turn_recovery_if_required( current_turn_instance_id=current_turn_instance_id, available_capabilities=available_capabilities, scheduler_execution_context=scheduler_execution_context, ) - if verdict["recovery"].get("state") == "attention_required": - payload["scheduler_hint"] = project_scheduler_hint(payload, arbitration=arbitration) + # Refresh scheduler_hint for both recovery_required and attention_required so + # an earlier wait or terminal stop hint never overrides recovery arbitration. + payload["scheduler_hint"] = project_scheduler_hint(payload, arbitration=arbitration) return True diff --git a/loopx/control_plane/quota/unsettled_host_turn_recovery.ts b/loopx/control_plane/quota/unsettled_host_turn_recovery.ts index 3c4b224797..eed2bcc088 100644 --- a/loopx/control_plane/quota/unsettled_host_turn_recovery.ts +++ b/loopx/control_plane/quota/unsettled_host_turn_recovery.ts @@ -14,7 +14,7 @@ * whose settlement already validates is answered by the preflight, so the * caller reads no bound facts for it. */ -import type { JsonObject } from "../effect_program.ts"; +import {settlementIdentity, type JsonObject} from "../effect_program.ts"; import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts"; import { jsonObject, @@ -255,6 +255,7 @@ async function preflightPriorHostTurnCloseoutForOwner( const readback = readAdmittedQuotaSettlementFromSnapshot( settlementReadbackRequest(request, selected), settlementSnapshot, + {includeOriginalPreparedReceipt: true}, ); const missingReceipts = missingCloseoutReceipts(readback, requireWritebackForRecovery); if (missingReceipts === undefined) continue; @@ -271,6 +272,18 @@ async function preflightPriorHostTurnCloseoutForOwner( } continue; } + let executionLoss: JsonObject | null = null; + const original = jsonObject(readback.original_prepared_receipt); + if (original && selected.binding_kind === "todo" && missingReceipts.length === 2 + && readback.replay_phase === "open" && readback.writeback_run == null && readback.writeback_event == null + && readback.spend_run == null && readback.spend_event == null + && readback.completion_event == null && readback.supersede_event == null) { + const {observeFencedExecution} = await import("./execution_loss_closeout.ts"); + executionLoss = await observeFencedExecution(request.runtime_root, settlementIdentity({ + goal_id: request.goal_id, agent_id: request.agent_id, todo_id: selected.binding_id, + turn_instance_id: selected.prior_turn_instance_id, + }), original); + } const monitorPoll = selected.binding_kind === "todo" ? committedMonitorPollFromSnapshot(settlementSnapshot, { goal_id: request.goal_id, agent_id: request.agent_id, @@ -286,7 +299,8 @@ async function preflightPriorHostTurnCloseoutForOwner( turns_validated: turnsValidated, candidate: selected, missing_receipts: missingReceipts, - recovery_admissions: recoveryAdmissions(receipts ?? [], selected, missingReceipts, request), + recovery_admissions: { ...recoveryAdmissions(receipts ?? [], selected, missingReceipts, request), + ...(executionLoss === null ? {} : {execution_loss: executionLoss}) }, }; } return { @@ -458,7 +472,7 @@ function acceptedLifecycleCloseout(todo: CandidateTodoFacts | null): AcceptedClo return settled ? "typed_blocker_or_lifecycle_transition" : null; } -type RecoveryRepair = "monitor_poll" | "resume_prior_turn" | "lifecycle"; +type RecoveryRepair = "monitor_poll" | "resume_prior_turn" | "lifecycle" | "execution_loss_closeout"; function recoveryRepair( bindingKind: HeartbeatReceiptBinding["binding_kind"], @@ -595,11 +609,16 @@ export function reduceUnsettledHostTurnRecovery(value: unknown): JsonObject { recovery.binding_target_key = todo.target_key; recovery.binding_cadence = todo.cadence; } - const repair = replanSpendOwed ? "resume_prior_turn" : recoveryRepair(selected.binding_kind, todo); + const admissions = jsonObject(request.recovery_admissions); + const executionLoss = jsonObject(admissions?.execution_loss); + const canReportExecutionLoss = executionLoss !== null && selected.binding_kind === "todo" + && todo?.task_class === "advancement_task" && todo.status === "open" && missingReceipts.length === 2; + const repair = canReportExecutionLoss ? "execution_loss_closeout" + : replanSpendOwed ? "resume_prior_turn" : recoveryRepair(selected.binding_kind, todo); + if (canReportExecutionLoss) recovery.execution_loss = executionLoss; // The typed repair lane lets the CLI renderer project its command list // without re-deriving which closeout family the Turn belongs to. recovery.repair = repair; - const admissions = jsonObject(request.recovery_admissions); const count = admissions?.count ?? 0; if (typeof count !== "number" || !Number.isSafeInteger(count) || count < 0) { throw new EffectRuntimeRequestError("recovery admission count must be a nonnegative integer"); @@ -609,21 +628,33 @@ export function reduceUnsettledHostTurnRecovery(value: unknown): JsonObject { recovery.admission_checkpoint = checkpoint; recovery.admissions_without_progress = count; recovery.admission_limit = RECOVERY_ADMISSION_LIMIT; - const attention = count >= RECOVERY_ADMISSION_LIMIT; + const writerRequired = canReportExecutionLoss && executionLoss.current_control_writer_active !== true; + const attention = count >= RECOVERY_ADMISSION_LIMIT || writerRequired; + const attentionReason = writerRequired ? "execution_loss_control_writer_required" + : "unsettled_recovery_admission_limit"; const obligation = recoveryObligation(repair, selected.binding_id); if (attention) { recovery.state = "attention_required"; - recovery.reason_code = "unsettled_recovery_admission_limit"; + recovery.reason_code = attentionReason; Object.assign(obligation, { must_attempt_work: false, notify: "NOTIFY", - reason_code: "unsettled_recovery_admission_limit", + reason_code: attentionReason, reason: "prior host Turn recovery exhausted its unchanged admission allowance", recommendation_reason: "recovery needs receipt progress or explicit owner resume", unsettled_reason: "unchanged prior host Turn recovery requires attention", recommended_action: "Repair the named original Turn's missing receipts, or explicitly stop and resume the Goal as owner to renew the recovery allowance; do not create a new debt or invent a closeout", }); } + if (canReportExecutionLoss) { + obligation.reason = "the original execution lease generation is fenced"; + obligation.recommendation_reason = "execution-loss closeout requires current control-writer proof"; + obligation.unsettled_reason = "the fenced original Turn needs an administrative closeout"; + if (writerRequired) obligation.reason = "the original execution lease is fenced and the current control-writer proof is unavailable"; + obligation.recommended_action = executionLoss.current_control_writer_active === true + ? "Use the original Turn and current control-writer proof for execution-loss closeout without debit. Verify the closeout before fresh work." + : "The original execution lease generation was replaced. Obtain authorized control-writer proof for the same Todo before execution-loss closeout. The replacement cannot resume the original business execution."; + } return { schema_version: UNSETTLED_HOST_TURN_RECOVERY_RESULT_SCHEMA, status: attention ? "attention_required" : "recovery_required", diff --git a/loopx/control_plane/runtime/node_probe.py b/loopx/control_plane/runtime/node_probe.py index ae57291b9c..983c0e0416 100644 --- a/loopx/control_plane/runtime/node_probe.py +++ b/loopx/control_plane/runtime/node_probe.py @@ -6,15 +6,23 @@ """ from __future__ import annotations +import platform import re import shutil import subprocess +import sys from dataclasses import dataclass from enum import StrEnum MINIMUM_NODE_VERSION = (22, 22, 3) MINIMUM_NODE_VERSION_TEXT = ".".join(str(part) for part in MINIMUM_NODE_VERSION) STARTUP_READY_TIMEOUT_SECONDS = 15.0 +_LINUX_X86_MACHINES = frozenset({"x86_64", "amd64"}) +_LINUX_X86_TYPESCRIPT_V8_FLAGS = ( + "--liftoff-only", + "--no-wasm-tier-up", + "--no-wasm-dynamic-tiering", +) HOST_PERMISSION_RECOMMENDATION = ( "retry the same registry, Goal, Agent and Turn through host-approved " "local runtime access; do not enable optional capabilities, replace " @@ -135,3 +143,20 @@ def probe_node(*, timeout: float = STARTUP_READY_TIMEOUT_SECONDS) -> NodeProbe: if prerelease is not None: version_text += f"-{prerelease}" return NodeProbe(outcome, executable, version_text) + + +def node_typescript_flags( + *, + system: str | None = None, + machine: str | None = None, +) -> tuple[str, ...]: + """Return V8 Wasm baseline flags for Node TypeScript stripping on Linux x86_64. + + Under QEMU/TCG or Linux PKU environments Node's Amaro Wasm TypeScript + stripper can trap in V8 ThreadIsolation during TurboFan Wasm tier-up. + """ + resolved_system = (sys.platform if system is None else system).lower() + resolved_machine = (platform.machine() if machine is None else machine).lower() + if resolved_system.startswith("linux") and resolved_machine in _LINUX_X86_MACHINES: + return _LINUX_X86_TYPESCRIPT_V8_FLAGS + return () diff --git a/loopx/control_plane/runtime/node_version.ts b/loopx/control_plane/runtime/node_version.ts index 7bd7bd679e..9d7b109c7b 100644 --- a/loopx/control_plane/runtime/node_version.ts +++ b/loopx/control_plane/runtime/node_version.ts @@ -1,5 +1,10 @@ const MINIMUM_NODE_VERSION = [22, 22, 3] as const; const NODE_VERSION_PATTERN = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/; +const LINUX_X86_TYPESCRIPT_V8_FLAGS = [ + "--liftoff-only", + "--no-wasm-tier-up", + "--no-wasm-dynamic-tiering", +] as const; export function isSupportedNodeVersion(version: string): boolean { const match = NODE_VERSION_PATTERN.exec(version); @@ -12,3 +17,13 @@ export function isSupportedNodeVersion(version: string): boolean { } return match[4] === undefined; } + +export function nodeTypescriptFlags( + platform: string = process.platform, + arch: string = process.arch, +): string[] { + if (platform === "linux" && (arch === "x64" || arch === "amd64")) { + return [...LINUX_X86_TYPESCRIPT_V8_FLAGS]; + } + return []; +} diff --git a/loopx/control_plane/runtime/runtime_projection_route.py b/loopx/control_plane/runtime/runtime_projection_route.py index 85876c2897..6c8dd69ec3 100644 --- a/loopx/control_plane/runtime/runtime_projection_route.py +++ b/loopx/control_plane/runtime/runtime_projection_route.py @@ -484,15 +484,17 @@ def _route_projection_is_current( rows, _ = load_index( target_runtime_root / "goals" / goal_id / "runs" / "index.jsonl" ) - return any( - isinstance(row.get(marker_field), dict) - and row[marker_field].get("runtime_projection_route_id") - == route_id - and row[marker_field].get("source_generated_at") == source_generated_at - and row.get("json_exists") is True - and row.get("markdown_exists") is True - for row in rows - ) + for row in rows: + marker = row.get(marker_field) + if ( + isinstance(marker, dict) + and marker.get("runtime_projection_route_id") == route_id + and marker.get("source_generated_at") == source_generated_at + and row.get("json_exists") is True + and row.get("markdown_exists") is True + ): + return True + return False def _source_routes_for_registry( diff --git a/loopx/control_plane/state_recovery_io.py b/loopx/control_plane/state_recovery_io.py index ebe24345fc..731565ba9e 100644 --- a/loopx/control_plane/state_recovery_io.py +++ b/loopx/control_plane/state_recovery_io.py @@ -24,6 +24,7 @@ from typing import Any, BinaryIO, Iterator, NoReturn from .effect_runtime import _node_executable, effect_runtime_result, effect_runtime_request_scope +from .runtime.node_probe import node_typescript_flags MAX_ARCHIVE_BYTES = 128 * 1024 * 1024 MAX_EXPANDED_BYTES = 512 * 1024 * 1024 @@ -87,6 +88,7 @@ def _runtime(method: str, request: dict[str, Any]) -> dict[str, Any]: def _audit_owners(request: dict[str, Any]) -> dict[str, Any]: command = [_node_executable(), "--no-warnings", "--max-old-space-size=512", "--experimental-sqlite", "--experimental-strip-types", + *node_typescript_flags(), str(Path(__file__).with_name("state_recovery_worker.ts"))] try: completed = subprocess.run(command, input=json.dumps(request), text=True, encoding="utf-8", diff --git a/loopx/control_plane/status/run_projection.py b/loopx/control_plane/status/run_projection.py index db19f49c9f..bbb4dc433f 100644 --- a/loopx/control_plane/status/run_projection.py +++ b/loopx/control_plane/status/run_projection.py @@ -12,7 +12,7 @@ latest_agent_lane_run as _latest_agent_lane_run, latest_run_recommended_action_for_projection as _latest_run_recommended_action_for_projection, ) -from ..progress_scope import AGENT_LANE_PROGRESS_SCOPE +from ..progress_scope import AGENT_LANE_PROGRESS_SCOPE as AGENT_LANE_PROGRESS_SCOPE from ..runtime.public_safety import public_safe_compact_text from ..runtime.run_history import latest_run as _latest_run from ..runtime.time import parse_timestamp diff --git a/loopx/control_plane/testing/authority_e2e_fixtures.py b/loopx/control_plane/testing/authority_e2e_fixtures.py index ca2aa94001..2e7c0d1ace 100644 --- a/loopx/control_plane/testing/authority_e2e_fixtures.py +++ b/loopx/control_plane/testing/authority_e2e_fixtures.py @@ -24,6 +24,7 @@ from ..coordination.coordination_state_contract_generated import ( LOCAL_AUTHORITY_SHADOW_CONFIG_SCHEMA, ) +from ..runtime.node_probe import node_typescript_flags REPO_ROOT = Path(__file__).resolve().parents[3] TS_READBACK_PROBE = Path("tests") / "control_plane_ts" / "authority_store_readback_probe.ts" @@ -541,6 +542,7 @@ def ts_readback( node, "--no-warnings", "--experimental-strip-types", + *node_typescript_flags(), str(REPO_ROOT / TS_READBACK_PROBE), "--directory", str(directory or workspace.shadow_directory), diff --git a/loopx/control_plane/testing/authority_e2e_ladder.py b/loopx/control_plane/testing/authority_e2e_ladder.py index 7f078be5c9..7c5b863153 100644 --- a/loopx/control_plane/testing/authority_e2e_ladder.py +++ b/loopx/control_plane/testing/authority_e2e_ladder.py @@ -31,6 +31,7 @@ QUALIFIED_NOKV_API_VERSION as QUALIFIED_NOKV_API_VERSION, QUALIFIED_NOKV_SDK_VERSION as QUALIFIED_NOKV_SDK_VERSION, ) +from ..runtime.node_probe import node_typescript_flags from .authority_e2e_row_support import ( AGENT_A, RowAssertionError, @@ -208,7 +209,7 @@ def _row_local_conformance(context: RowContext, provider: str) -> RowOutcome: return unverified("local_conformance_suite_missing") summary = tap_summary( [node, "--no-warnings", "--experimental-sqlite", "--experimental-strip-types", - "--test", "--test-reporter=tap", str(suite)], + *node_typescript_flags(), "--test", "--test-reporter=tap", str(suite)], env=context.environ, timeout=900, ) @@ -347,6 +348,7 @@ def _row_nokv_live_qualification(context: RowContext) -> RowOutcome: node, "--no-warnings", "--experimental-strip-types", + *node_typescript_flags(), str(REPO_ROOT / NOKV_QUALIFICATION_SCRIPT), "--execute-live", "--config-json", @@ -457,6 +459,7 @@ def _row_postgresql_conformance_live(context: RowContext) -> RowOutcome: node, "--no-warnings", "--experimental-strip-types", + *node_typescript_flags(), "--test", "--test-reporter=tap", str(PG_INTEGRATION_TEST), diff --git a/loopx/control_plane/testing/canary_harness.py b/loopx/control_plane/testing/canary_harness.py index 770959b540..9a7dc9a25f 100644 --- a/loopx/control_plane/testing/canary_harness.py +++ b/loopx/control_plane/testing/canary_harness.py @@ -8,6 +8,8 @@ from pathlib import Path from typing import Any, Iterable +from ..runtime.node_probe import node_typescript_flags + REPO_ROOT = Path(__file__).resolve().parents[3] @@ -302,7 +304,15 @@ def advance_fixture_authority( "process.stdout.write(JSON.stringify(result));" ) process = subprocess.run( - ["node", "--no-warnings", "--experimental-strip-types", "--input-type=module", "-e", script], + [ + "node", + "--no-warnings", + "--experimental-strip-types", + *node_typescript_flags(), + "--input-type=module", + "-e", + script, + ], input=json.dumps({"root": str(runtime_root), "goal": goal_id, "projection": projection, "operation_id": operation_id}), capture_output=True, text=True, encoding="utf-8", check=False, timeout=45, diff --git a/loopx/control_plane/todos/contract.py b/loopx/control_plane/todos/contract.py index 7321a8bc03..4b816fd779 100644 --- a/loopx/control_plane/todos/contract.py +++ b/loopx/control_plane/todos/contract.py @@ -2,11 +2,12 @@ import hashlib import json +from collections.abc import Callable, Iterable, Mapping from pathlib import Path import re from dataclasses import dataclass from enum import Enum -from typing import Any, Callable +from typing import TypedDict from urllib.parse import quote, unquote from ...repository_identity import normalize_repository_identity @@ -67,7 +68,7 @@ ) -def normalize_todo_watch_only(value: Any) -> bool | None: +def normalize_todo_watch_only(value: object) -> bool | None: if value is True or str(value or "").strip().lower() == "true": return True if value is False or str(value or "").strip().lower() == "false": @@ -196,47 +197,74 @@ class TodoContinuationPolicy(str, Enum): ) -def compact_todo_text(value: Any) -> str: +def compact_todo_text(value: object) -> str: return " ".join(str(value or "").strip().split()) -def normalize_todo_action_kind(value: Any) -> str | None: - candidate = str(value or "").strip().lower() +def _match_token( + value: object, + pattern: re.Pattern[str], + *, + lower: bool = True, + full: bool = False, +) -> str | None: + candidate = str(value or "").strip() + if lower: + candidate = candidate.lower() if not candidate: return None - if TODO_ACTION_KIND_PATTERN.match(candidate): - return candidate - return None + matched = pattern.fullmatch(candidate) if full else pattern.match(candidate) + return candidate if matched else None -def normalize_todo_task_domain(value: Any) -> str | None: +def _choice_token(value: object, choices: set[str] | frozenset[str]) -> str | None: candidate = str(value or "").strip().lower() - if not candidate: - return None - if TODO_TASK_DOMAIN_PATTERN.fullmatch(candidate): - return candidate - return None + return candidate if candidate in choices else None -def normalize_todo_replan_obligation_id(value: Any) -> str | None: - candidate = str(value or "").strip() - if not candidate: - return None - if TODO_REPLAN_OBLIGATION_ID_PATTERN.fullmatch(candidate): - return candidate - return None +def _split_delimited_items(value: object, *, split_regex: bool = True) -> list[object]: + if value is None: + return [] + if isinstance(value, (list, tuple, set)): + return list(value) + if split_regex: + return list(re.split(r"[,;|]", str(value or ""))) + if isinstance(value, str): + return list(value.split(",")) + return [value] -def normalize_todo_capability_binding_ref(value: Any) -> str | None: - candidate = str(value or "").strip().lower() - if not candidate: - return None - if TODO_CAPABILITY_BINDING_REF_PATTERN.fullmatch(candidate): - return candidate - return None +def _dedupe_normalized( + raw_items: Iterable[object], + normalize: Callable[[object], str | None], +) -> list[str]: + seen: set[str] = set() + items: list[str] = [] + for raw in raw_items: + item = normalize(raw) + if item and item not in seen: + seen.add(item) + items.append(item) + return items + +def normalize_todo_action_kind(value: object) -> str | None: + return _match_token(value, TODO_ACTION_KIND_PATTERN) -def normalize_todo_task_repository(value: Any) -> str | None: + +def normalize_todo_task_domain(value: object) -> str | None: + return _match_token(value, TODO_TASK_DOMAIN_PATTERN, full=True) + + +def normalize_todo_replan_obligation_id(value: object) -> str | None: + return _match_token(value, TODO_REPLAN_OBLIGATION_ID_PATTERN, lower=False, full=True) + + +def normalize_todo_capability_binding_ref(value: object) -> str | None: + return _match_token(value, TODO_CAPABILITY_BINDING_REF_PATTERN, full=True) + + +def normalize_todo_task_repository(value: object) -> str | None: candidate = str(value or "").strip() if not candidate: return None @@ -246,83 +274,63 @@ def normalize_todo_task_repository(value: Any) -> str | None: return None -def normalize_todo_continuation_policy(value: Any) -> str | None: - candidate = str(value or "").strip().lower() - if candidate in TODO_CONTINUATION_POLICY_VALUES: - return candidate - return None +def normalize_todo_continuation_policy(value: object) -> str | None: + return _choice_token(value, TODO_CONTINUATION_POLICY_VALUES) -def normalize_removed_todo_continuation_policy(value: Any) -> str | None: - candidate = str(value or "").strip().lower() - if candidate in TODO_REMOVED_REVIEW_CONTINUATION_POLICY_VALUES: - return candidate - return None +def normalize_removed_todo_continuation_policy(value: object) -> str | None: + return _choice_token(value, TODO_REMOVED_REVIEW_CONTINUATION_POLICY_VALUES) -def normalize_todo_claimed_by(value: Any) -> str | None: +def normalize_todo_claimed_by(value: object) -> str | None: candidate = compact_todo_text(value).lower().replace(" ", "-") - if candidate and TODO_AGENT_CLAIM_PATTERN.match(candidate): - return candidate - return None + return candidate if candidate and TODO_AGENT_CLAIM_PATTERN.match(candidate) else None -def normalize_todo_blocks_agent(value: Any) -> str | None: +def normalize_todo_blocks_agent(value: object) -> str | None: return normalize_todo_claimed_by(value) -def normalize_todo_bound_agent(value: Any) -> str | None: +def normalize_todo_bound_agent(value: object) -> str | None: return normalize_todo_claimed_by(value) -def normalize_todo_goal_bound(value: Any) -> bool | None: +def normalize_todo_goal_bound(value: object) -> bool | None: return normalize_todo_global_gate(value) -def normalize_todo_excluded_agents(value: Any) -> list[str]: - if value is None: - return [] - if isinstance(value, str): - candidates = value.split(",") - elif isinstance(value, (list, tuple, set)): - candidates = list(value) - else: - candidates = [value] - return sorted( - { - agent_id - for candidate in candidates - for agent_id in [normalize_todo_claimed_by(candidate)] - if agent_id - } - ) - - -def require_todo_excluded_agents( - value: Any, +def _normalize_todo_excluded_agents( + value: object, *, + strict: bool, field: str = "excluded_agents", ) -> list[str]: - if value is None: - return [] - if isinstance(value, str): - candidates = value.split(",") - elif isinstance(value, (list, tuple, set)): - candidates = list(value) - else: - candidates = [value] normalized: set[str] = set() - for candidate in candidates: + for candidate in _split_delimited_items(value, split_regex=False): agent_id = normalize_todo_claimed_by(candidate) if not agent_id: - raise ValueError( - f"{field} must contain public-safe agent tokens such as codex-side-bypass" - ) + if strict: + raise ValueError( + f"{field} must contain public-safe agent tokens such as codex-side-bypass" + ) + continue normalized.add(agent_id) return sorted(normalized) -def normalize_todo_global_gate(value: Any) -> bool | None: +def normalize_todo_excluded_agents(value: object) -> list[str]: + return _normalize_todo_excluded_agents(value, strict=False) + + +def require_todo_excluded_agents( + value: object, + *, + field: str = "excluded_agents", +) -> list[str]: + return _normalize_todo_excluded_agents(value, strict=True, field=field) + + +def normalize_todo_global_gate(value: object) -> bool | None: if isinstance(value, bool): return value candidate = compact_todo_text(value).lower() @@ -333,14 +341,11 @@ def normalize_todo_global_gate(value: Any) -> bool | None: return None -def normalize_todo_id(value: Any) -> str | None: - candidate = str(value or "").strip().lower() - if candidate and TODO_ID_PATTERN.match(candidate): - return candidate - return None +def normalize_todo_id(value: object) -> str | None: + return _match_token(value, TODO_ID_PATTERN) -def normalize_todo_id_list(value: Any) -> list[str]: +def normalize_todo_id_list(value: object) -> list[str]: if value is None: return [] raw_values = value if isinstance(value, (list, tuple, set)) else [value] @@ -356,7 +361,7 @@ def normalize_todo_id_list(value: Any) -> list[str]: return todo_ids -def merge_todo_id_lists(*values: Any) -> list[str]: +def merge_todo_id_lists(*values: object) -> list[str]: todo_ids: list[str] = [] for value in values: for todo_id in normalize_todo_id_list(value): @@ -365,85 +370,59 @@ def merge_todo_id_lists(*values: Any) -> list[str]: return todo_ids -def normalize_required_write_scopes(value: Any) -> list[str]: - if value is None: - return [] - if isinstance(value, (list, tuple, set)): - raw_values = [str(item or "") for item in value] - else: - raw_values = re.split(r"[,;|]", str(value or "")) - scopes: list[str] = [] - seen: set[str] = set() - for raw in raw_values: - scope = compact_todo_text(raw) - if not scope: - continue - if len(scope) > TODO_WRITE_SCOPE_MAX_CHARS: - continue - if scope.startswith(("/", "~")) or ".." in scope.split("/"): - continue - if re.search(r"[\s<>]", scope): - continue - if scope in seen: - continue - seen.add(scope) - scopes.append(scope) - return scopes +def _normalize_single_write_scope(raw: object) -> str | None: + scope = compact_todo_text(raw) + if ( + not scope + or len(scope) > TODO_WRITE_SCOPE_MAX_CHARS + or scope.startswith(("/", "~")) + or ".." in scope.split("/") + or re.search(r"[\s<>]", scope) + ): + return None + return scope -def normalize_required_capabilities(value: Any) -> list[str]: - if value is None: - return [] - if isinstance(value, (list, tuple, set)): - raw_values = [str(item or "") for item in value] - else: - raw_values = re.split(r"[,;|]", str(value or "")) - capabilities: list[str] = [] - seen: set[str] = set() - for raw in raw_values: - capability = compact_todo_text(raw).lower().replace("-", "_").replace(" ", "_") - if not capability: - continue - if not TODO_CAPABILITY_PATTERN.match(capability): - continue - if capability in seen: - continue - seen.add(capability) - capabilities.append(capability) - return capabilities +def _normalize_single_capability(raw: object) -> str | None: + capability = compact_todo_text(raw).lower().replace("-", "_").replace(" ", "_") + return capability if capability and TODO_CAPABILITY_PATTERN.match(capability) else None + +def _normalize_single_explore_ref(raw: object) -> str | None: + ref = compact_todo_text(raw) + return ref if ref and TODO_EXPLORE_RESULT_NODE_REF_PATTERN.match(ref) else None -def normalize_target_capabilities(value: Any) -> list[str]: + +def normalize_required_write_scopes(value: object) -> list[str]: + return _dedupe_normalized(_split_delimited_items(value), _normalize_single_write_scope) + + +def normalize_required_capabilities(value: object) -> list[str]: + return _dedupe_normalized(_split_delimited_items(value), _normalize_single_capability) + + +def normalize_target_capabilities(value: object) -> list[str]: return normalize_required_capabilities(value) -def normalize_explore_result_node_refs(value: Any) -> list[str]: +def normalize_explore_result_node_refs(value: object) -> list[str]: """Normalize explicit public-safe Explore node ids attached to a todo.""" - if value is None: - return [] - if isinstance(value, (list, tuple, set)): - raw_values = [str(item or "") for item in value] - else: - raw_values = re.split(r"[,;|]", str(value or "")) - refs: list[str] = [] - seen: set[str] = set() - for raw in raw_values: - ref = compact_todo_text(raw) - if not ref or not TODO_EXPLORE_RESULT_NODE_REF_PATTERN.match(ref): - continue - if ref not in seen: - seen.add(ref) - refs.append(ref) - return refs + return _dedupe_normalized(_split_delimited_items(value), _normalize_single_explore_ref) + + +class ReplanSuccessorSemanticBinding(TypedDict, total=False): + action_kind: str + target_key: str + explore_result_node_refs: list[str] def replan_successor_semantic_binding( *, - action_kind: Any, - target_key: Any, - explore_result_node_refs: Any, -) -> dict[str, Any] | None: + action_kind: object, + target_key: object, + explore_result_node_refs: object, +) -> ReplanSuccessorSemanticBinding | None: """Return the typed executable identity of a replan successor. An obligation id establishes causality, but it does not turn a planning @@ -458,7 +437,7 @@ def replan_successor_semantic_binding( ) if not safe_action_kind or not (safe_target_key or safe_explore_refs): return None - binding: dict[str, Any] = {"action_kind": safe_action_kind} + binding: ReplanSuccessorSemanticBinding = {"action_kind": safe_action_kind} if safe_target_key: binding["target_key"] = safe_target_key if safe_explore_refs: @@ -466,7 +445,11 @@ def replan_successor_semantic_binding( return binding -def normalize_todo_decision_scope(value: Any) -> dict[str, str] | None: +def _format_scope_identity(scope: Mapping[str, object]) -> str: + return f"{scope['kind']}:{scope['granularity']}:{scope['scope_key']}" + + +def normalize_todo_decision_scope(value: object) -> dict[str, str] | None: """Normalize the compact decision-scope metadata token. Markdown todo metadata stores the v0 shape as @@ -474,10 +457,10 @@ def normalize_todo_decision_scope(value: Any) -> dict[str, str] | None: active-state comments. Status and quota expose the normalized object. """ - raw_kind: Any = None - raw_granularity: Any = None - raw_scope_key: Any = None - raw_decision_id: Any = None + raw_kind: object = None + raw_granularity: object = None + raw_scope_key: object = None + raw_decision_id: object = None if isinstance(value, dict): raw_kind = value.get("kind") raw_granularity = value.get("granularity") @@ -512,12 +495,11 @@ def normalize_todo_decision_scope(value: Any) -> dict[str, str] | None: return payload -def normalize_todo_decision_outcome(value: Any) -> str | None: - candidate = compact_todo_text(value).lower() - return candidate if candidate in TODO_DECISION_OUTCOME_VALUES else None +def normalize_todo_decision_outcome(value: object) -> str | None: + return _choice_token(value, TODO_DECISION_OUTCOME_VALUES) -def require_todo_decision_outcome(value: Any) -> str: +def require_todo_decision_outcome(value: object) -> str: outcome = normalize_todo_decision_outcome(value) if not outcome: raise ValueError( @@ -527,7 +509,7 @@ def require_todo_decision_outcome(value: Any) -> str: return outcome -def require_todo_decision_scope(value: Any) -> dict[str, str]: +def require_todo_decision_scope(value: object) -> dict[str, str]: scope = normalize_todo_decision_scope(value) if not scope: raise ValueError( @@ -538,19 +520,13 @@ def require_todo_decision_scope(value: Any) -> dict[str, str]: def _normalize_todo_required_decision_scopes( - value: Any, + value: object, *, strict: bool, ) -> list[dict[str, str]]: - if value is None: - return [] - if isinstance(value, (list, tuple, set)): - raw_values = list(value) - else: - raw_values = re.split(r"[,;|]", str(value or "")) scopes: list[dict[str, str]] = [] seen: set[tuple[str, str, str]] = set() - for raw in raw_values: + for raw in _split_delimited_items(value): scope = normalize_todo_decision_scope(raw) if not scope: if strict: @@ -567,45 +543,33 @@ def _normalize_todo_required_decision_scopes( return scopes -def normalize_todo_required_decision_scopes(value: Any) -> list[dict[str, str]]: +def normalize_todo_required_decision_scopes(value: object) -> list[dict[str, str]]: return _normalize_todo_required_decision_scopes(value, strict=False) -def require_todo_required_decision_scopes(value: Any) -> list[dict[str, str]]: +def require_todo_required_decision_scopes(value: object) -> list[dict[str, str]]: return _normalize_todo_required_decision_scopes(value, strict=True) -def decision_scope_metadata_value(value: Any) -> str | None: - if value is None: - return None - scope = require_todo_decision_scope(value) - return f"{scope['kind']}:{scope['granularity']}:{scope['scope_key']}" +def decision_scope_metadata_value(value: object) -> str | None: + return None if value is None else _format_scope_identity(require_todo_decision_scope(value)) -def required_decision_scopes_metadata_value(value: Any) -> str | None: +def required_decision_scopes_metadata_value(value: object) -> str | None: if value is None: return None scopes = require_todo_required_decision_scopes(value) - if not scopes: - return None - return ",".join( - f"{scope['kind']}:{scope['granularity']}:{scope['scope_key']}" - for scope in scopes - ) + return ",".join(_format_scope_identity(scope) for scope in scopes) or None -def normalize_todo_decision_scope_outcomes(value: Any) -> list[dict[str, Any]]: - if value is None: - return [] - raw_values = list(value) if isinstance(value, (list, tuple, set)) else [value] - if isinstance(value, str): - raw_values = [item for item in value.split(",") if item] - outcomes: list[dict[str, Any]] = [] +def normalize_todo_decision_scope_outcomes(value: object) -> list[dict[str, object]]: + raw_values = _split_delimited_items(value, split_regex=False) + outcomes: list[dict[str, object]] = [] positions: dict[tuple[str, str, str], int] = {} for raw in raw_values: - raw_outcome: Any = None - raw_scope: Any = None - raw_source_todo_id: Any = None + raw_outcome: object = None + raw_scope: object = None + raw_source_todo_id: object = None if isinstance(raw, dict): raw_outcome = raw.get("outcome") raw_scope = raw.get("decision_scope") or raw.get("scope") @@ -619,7 +583,7 @@ def normalize_todo_decision_scope_outcomes(value: Any) -> list[dict[str, Any]]: source_todo_id = normalize_todo_id(raw_source_todo_id) if not outcome or not scope or not source_todo_id: continue - payload = { + payload: dict[str, object] = { "schema_version": TODO_DECISION_SCOPE_OUTCOME_SCHEMA_VERSION, "outcome": outcome, "decision_scope": scope, @@ -634,63 +598,47 @@ def normalize_todo_decision_scope_outcomes(value: Any) -> list[dict[str, Any]]: return outcomes -def decision_scope_outcomes_metadata_value(value: Any) -> str | None: +def _format_decision_scope_outcome_token(item: Mapping[str, object]) -> str: + raw_scope = item.get("decision_scope") + scope = raw_scope if isinstance(raw_scope, Mapping) else {} + return f"{item.get('outcome', '')}|{_format_scope_identity(scope)}|{item.get('source_todo_id', '')}" + + +def decision_scope_outcomes_metadata_value(value: object) -> str | None: outcomes = normalize_todo_decision_scope_outcomes(value) if not outcomes: return None - return ",".join( - "|".join( - ( - item["outcome"], - ":".join( - ( - item["decision_scope"]["kind"], - item["decision_scope"]["granularity"], - item["decision_scope"]["scope_key"], - ) - ), - item["source_todo_id"], - ) - ) - for item in outcomes - ) + return ",".join(_format_decision_scope_outcome_token(item) for item in outcomes) def build_todo_id( *, - role: Any, - source_section: Any, - index: Any, - text: Any, + role: object, + source_section: object, + index: object, + text: object, ) -> str: identity = "|".join(str(part or "") for part in (role, source_section, index, compact_todo_text(text))) return f"todo_{hashlib.sha1(identity.encode('utf-8')).hexdigest()[:12]}" -def normalize_explicit_todo_task_class(value: Any) -> str | None: - candidate = str(value or "").strip().lower() - if candidate in TODO_TASK_CLASS_VALUES: - return candidate - return None +def normalize_explicit_todo_task_class(value: object) -> str | None: + return _choice_token(value, TODO_TASK_CLASS_VALUES) -def normalize_todo_status(value: Any) -> str | None: - candidate = str(value or "").strip().lower() - if candidate in TODO_STATUS_VALUES: - return candidate - return None +def normalize_todo_status(value: object) -> str | None: + return _choice_token(value, TODO_STATUS_VALUES) -def normalize_todo_role(value: Any) -> str | None: - candidate = str(value or "").strip().lower() - return candidate if candidate in {"user", "agent"} else None +def normalize_todo_role(value: object) -> str | None: + return _choice_token(value, {"user", "agent"}) -def todo_done_for_status(status: Any) -> bool: +def todo_done_for_status(status: object) -> bool: return normalize_todo_status(status) in TODO_TERMINAL_STATUS_VALUES -def todo_terminal_for_status(status: Any) -> bool: +def todo_terminal_for_status(status: object) -> bool: candidate = str(status or "").strip().lower() return ( normalize_todo_status(candidate) in TODO_TERMINAL_STATUS_VALUES @@ -698,7 +646,7 @@ def todo_terminal_for_status(status: Any) -> bool: ) -def todo_status_from_marker(marker: Any) -> str: +def todo_status_from_marker(marker: object) -> str: candidate = str(marker or "").strip().lower() if candidate == "x": return TODO_STATUS_DONE @@ -707,7 +655,7 @@ def todo_status_from_marker(marker: Any) -> str: return TODO_STATUS_OPEN -def todo_marker_for_status(status: Any) -> str: +def todo_marker_for_status(status: object) -> str: normalized = normalize_todo_status(status) or TODO_STATUS_OPEN if normalized == TODO_STATUS_DEFERRED: return "-" @@ -716,52 +664,56 @@ def todo_marker_for_status(status: Any) -> str: return " " -def encode_metadata_value(value: Any, *, preserve_whitespace: bool = False) -> str: +def encode_metadata_value(value: object, *, preserve_whitespace: bool = False) -> str: text = str(value or "") if preserve_whitespace else compact_todo_text(value) return quote(text, safe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_.:-") -def decode_metadata_value(value: Any, *, preserve_whitespace: bool = False) -> str: +def decode_metadata_value(value: object, *, preserve_whitespace: bool = False) -> str: text = unquote(str(value or "")) return text if preserve_whitespace else compact_todo_text(text) -MetadataValueNormalizer = Callable[[Any], Any] -MetadataValueEncoder = Callable[[Any], str | None] -MetadataInvalidPredicate = Callable[[Any], bool] +MetadataValueNormalizer = Callable[[object], object] +MetadataValueEncoder = Callable[[object], str | None] +MetadataInvalidPredicate = Callable[[object], bool] -def _truthy_value(value: Any) -> Any: +def _truthy_value(value: object) -> object: return value if value else None -def _nonempty_metadata_text(value: Any) -> str | None: - text = compact_todo_text(value) - return text or None +def _nonempty_metadata_text(value: object) -> str | None: + return compact_todo_text(value) or None -def _nonblank_verbatim_metadata_text(value: str) -> str | None: +def _nonblank_verbatim_metadata_text(value: object) -> str | None: + if not isinstance(value, str): + text = str(value or "") + return text if text.strip() else None return value if value.strip() else None -def _optional_output_bool(value: Any) -> bool | None: +def _optional_output_bool(value: object) -> bool | None: return None if value is None else bool(value) -def _metadata_bool_text(value: Any) -> str: +def _metadata_bool_text(value: object) -> str: return "true" if value else "false" -def _metadata_csv(value: Any) -> str: - return ",".join(str(item) for item in value) +def _metadata_csv(value: object) -> str: + if isinstance(value, Iterable) and not isinstance(value, (str, bytes)): + return ",".join(str(item) for item in value) + return str(value or "") -def _normalize_optional_decision_scope_for_write(value: Any) -> dict[str, str] | None: +def _normalize_optional_decision_scope_for_write(value: object) -> dict[str, str] | None: return None if value is None else require_todo_decision_scope(value) def _normalize_optional_required_decision_scopes_for_write( - value: Any, + value: object, ) -> list[dict[str, str]]: return [] if value is None else require_todo_required_decision_scopes(value) @@ -779,7 +731,7 @@ class _TodoMetadataField: block_field: bool = True preserve_whitespace: bool = False - def normalize_for_write(self, value: Any) -> Any: + def normalize_for_write(self, value: object) -> object: normalizer = self.write_normalizer or self.read_normalizer normalized = normalizer(value) if ( @@ -791,309 +743,185 @@ def normalize_for_write(self, value: Any) -> Any: return normalized -def _metadata_value_is_present(value: Any) -> bool: +def _metadata_value_is_present(value: object) -> bool: return value is not None and value != "" and value != [] +def _bool_field(key: str, read_normalizer: MetadataValueNormalizer) -> _TodoMetadataField: + return _TodoMetadataField( + key, + read_normalizer, + write_normalizer=_optional_output_bool, + encoder=_metadata_bool_text, + invalid_when=lambda value: value is not None, + ) + + +def _todo_id_message(key: str) -> str: + return f"{key} must use the public token shape todo_" + + +def _csv_field( + key: str, + read_normalizer: MetadataValueNormalizer, + *, + write_normalizer: MetadataValueNormalizer | None = None, + invalid_message: str | None = None, +) -> _TodoMetadataField: + return _TodoMetadataField( + key, + read_normalizer, + write_normalizer=write_normalizer, + encoder=_metadata_csv, + invalid_message=invalid_message, + ) + + _TODO_METADATA_FIELD_SCHEMA = ( + _TodoMetadataField("todo_id", normalize_todo_id, invalid_message=_todo_id_message("todo_id")), _TodoMetadataField( - "todo_id", - normalize_todo_id, - invalid_message=( - "todo_id must use the public token shape " - "todo_" - ), - ), - _TodoMetadataField( - "status", - normalize_todo_status, - invalid_message=( - "todo status must be one of: " + ", ".join(sorted(TODO_STATUS_VALUES)) - ), - ), - _TodoMetadataField( - "role", - normalize_todo_role, - invalid_message="todo role must be one of: agent, user", + "status", normalize_todo_status, + invalid_message="todo status must be one of: " + ", ".join(sorted(TODO_STATUS_VALUES)), ), + _TodoMetadataField("role", normalize_todo_role, invalid_message="todo role must be one of: agent, user"), _TodoMetadataField( - "task_class", - normalize_explicit_todo_task_class, - invalid_message=( - "todo task_class must be one of: " - + ", ".join(sorted(TODO_TASK_CLASS_VALUES)) - ), + "task_class", normalize_explicit_todo_task_class, + invalid_message="todo task_class must be one of: " + ", ".join(sorted(TODO_TASK_CLASS_VALUES)), ), _TodoMetadataField( - "action_kind", - normalize_todo_action_kind, - invalid_message=( - "todo action_kind must be a public-safe token: lowercase letters, " - "digits, '_' or '-'" - ), + "action_kind", normalize_todo_action_kind, + invalid_message="todo action_kind must be a public-safe token: lowercase letters, digits, '_' or '-'", ), _TodoMetadataField( - "task_domain", - normalize_todo_task_domain, - invalid_message=( - "todo task_domain must be a public-safe token: lowercase letters, " - "digits, '_', '-' or '.'" - ), + "task_domain", normalize_todo_task_domain, + invalid_message="todo task_domain must be a public-safe token: lowercase letters, digits, '_', '-' or '.'", ), _TodoMetadataField( - "capability_binding_ref", - normalize_todo_capability_binding_ref, - invalid_message=( - "capability_binding_ref must be a public-safe namespaced token" - ), + "capability_binding_ref", normalize_todo_capability_binding_ref, + invalid_message="capability_binding_ref must be a public-safe namespaced token", ), _TodoMetadataField( - "task_repository", - normalize_todo_task_repository, - invalid_message=( - "todo task_repository must be a credential-free Git remote or canonical " - "git:/ identity" - ), + "task_repository", normalize_todo_task_repository, + invalid_message="todo task_repository must be a credential-free Git remote or canonical git:/ identity", ), _TodoMetadataField( - "continuation_policy", - normalize_todo_continuation_policy, - invalid_message=( - "todo continuation_policy must be one of: " - + ", ".join(sorted(TODO_CONTINUATION_POLICY_VALUES)) - ), + "continuation_policy", normalize_todo_continuation_policy, + invalid_message="todo continuation_policy must be one of: " + ", ".join(sorted(TODO_CONTINUATION_POLICY_VALUES)), read_fallback_key="removed_continuation_policy", read_fallback_normalizer=normalize_removed_todo_continuation_policy, ), _TodoMetadataField( - "removed_continuation_policy", - normalize_removed_todo_continuation_policy, + "removed_continuation_policy", normalize_removed_todo_continuation_policy, invalid_message=( "removed_continuation_policy must be one of: " + ", ".join(sorted(TODO_REMOVED_REVIEW_CONTINUATION_POLICY_VALUES)) ), block_field=False, ), - _TodoMetadataField( - "required_write_scopes", - normalize_required_write_scopes, - encoder=_metadata_csv, - invalid_message=( - "required_write_scopes must contain public-safe relative scope tokens" - ), + _csv_field( + "required_write_scopes", normalize_required_write_scopes, + invalid_message="required_write_scopes must contain public-safe relative scope tokens", ), - _TodoMetadataField( - "required_capabilities", - normalize_required_capabilities, - encoder=_metadata_csv, - invalid_message=( - "required_capabilities must contain public-safe capability tokens" - ), + _csv_field( + "required_capabilities", normalize_required_capabilities, + invalid_message="required_capabilities must contain public-safe capability tokens", ), - _TodoMetadataField( - "target_capabilities", - normalize_target_capabilities, - encoder=_metadata_csv, - invalid_message=( - "target_capabilities must contain public-safe capability tokens" - ), + _csv_field( + "target_capabilities", normalize_target_capabilities, + invalid_message="target_capabilities must contain public-safe capability tokens", ), - _TodoMetadataField( - "explore_result_node_refs", - normalize_explore_result_node_refs, - encoder=_metadata_csv, - invalid_message=( - "explore_result_node_refs must contain public-safe Explore node ids" - ), + _csv_field( + "explore_result_node_refs", normalize_explore_result_node_refs, + invalid_message="explore_result_node_refs must contain public-safe Explore node ids", ), _TodoMetadataField( - "decision_scope", - normalize_todo_decision_scope, + "decision_scope", normalize_todo_decision_scope, write_normalizer=_normalize_optional_decision_scope_for_write, encoder=decision_scope_metadata_value, invalid_when=lambda value: value is not None, ), _TodoMetadataField( - "required_decision_scopes", - normalize_todo_required_decision_scopes, + "required_decision_scopes", normalize_todo_required_decision_scopes, write_normalizer=_normalize_optional_required_decision_scopes_for_write, encoder=required_decision_scopes_metadata_value, ), _TodoMetadataField( - "decision_outcome", - normalize_todo_decision_outcome, - invalid_message=( - "decision_outcome must be one of: " - + ", ".join(sorted(TODO_DECISION_OUTCOME_VALUES)) - ), + "decision_outcome", normalize_todo_decision_outcome, + invalid_message="decision_outcome must be one of: " + ", ".join(sorted(TODO_DECISION_OUTCOME_VALUES)), ), _TodoMetadataField( - "decision_scope_outcomes", - normalize_todo_decision_scope_outcomes, + "decision_scope_outcomes", normalize_todo_decision_scope_outcomes, encoder=decision_scope_outcomes_metadata_value, - invalid_message=( - "decision_scope_outcomes must contain outcome, decision_scope, and " - "source_todo_id" - ), + invalid_message="decision_scope_outcomes must contain outcome, decision_scope, and source_todo_id", ), _TodoMetadataField( - "claimed_by", - normalize_todo_claimed_by, - invalid_message=( - "claimed_by must be a public-safe agent token such as codex-main-control" - ), + "claimed_by", normalize_todo_claimed_by, + invalid_message="claimed_by must be a public-safe agent token such as codex-main-control", ), _TodoMetadataField( - "last_actor_agent_id", - normalize_todo_claimed_by, + "last_actor_agent_id", normalize_todo_claimed_by, invalid_message="last_actor_agent_id must be a public-safe agent token", ), _TodoMetadataField( - "bound_agent", - normalize_todo_bound_agent, - invalid_message=( - "bound_agent must be a public-safe agent token such as codex-main-control" - ), - ), - _TodoMetadataField( - "goal_bound", - normalize_todo_goal_bound, - write_normalizer=_optional_output_bool, - encoder=_metadata_bool_text, - invalid_when=lambda value: value is not None, - ), - _TodoMetadataField( - "blocks_agent", - normalize_todo_blocks_agent, - invalid_message=( - "blocks_agent must be a public-safe agent token such as codex-side-bypass" - ), - ), - _TodoMetadataField( - "excluded_agents", - normalize_todo_excluded_agents, - write_normalizer=require_todo_excluded_agents, - encoder=_metadata_csv, - ), - _TodoMetadataField( - "global_gate", - normalize_todo_global_gate, - write_normalizer=_optional_output_bool, - encoder=_metadata_bool_text, - invalid_when=lambda value: value is not None, + "bound_agent", normalize_todo_bound_agent, + invalid_message="bound_agent must be a public-safe agent token such as codex-main-control", ), + _bool_field("goal_bound", normalize_todo_goal_bound), _TodoMetadataField( - "unblocks_todo_id", - normalize_todo_id, - invalid_message=( - "unblocks_todo_id must use the public token shape " - "todo_" - ), - ), - _TodoMetadataField( - "successor_todo_ids", - normalize_todo_id_list, - encoder=_metadata_csv, - invalid_message=( - "successor_todo_ids must contain public " - "todo_ tokens" - ), + "blocks_agent", normalize_todo_blocks_agent, + invalid_message="blocks_agent must be a public-safe agent token such as codex-side-bypass", ), - _TodoMetadataField( - "completion_continuation", - normalize_todo_completion_continuation, - invalid_message=( - "completion_continuation must be one of: active_goal, successor, " - "no_followup" - ), + _csv_field("excluded_agents", normalize_todo_excluded_agents, write_normalizer=require_todo_excluded_agents), + _bool_field("global_gate", normalize_todo_global_gate), + _TodoMetadataField("unblocks_todo_id", normalize_todo_id, invalid_message=_todo_id_message("unblocks_todo_id")), + _csv_field( + "successor_todo_ids", normalize_todo_id_list, + invalid_message="successor_todo_ids must contain public todo_ tokens", ), _TodoMetadataField( - "completion_recovery", - normalize_todo_completion_recovery, - invalid_message=( - "completion_recovery must be same_turn_terminal_closeout or " - "lifecycle_reentry_terminal_closeout" - ), + "completion_continuation", normalize_todo_completion_continuation, + invalid_message="completion_continuation must be one of: active_goal, successor, no_followup", ), _TodoMetadataField( - "replan_obligation_id", - normalize_todo_replan_obligation_id, - invalid_message=( - "replan_obligation_id must use the current replan-<16 lowercase hex> " - "identity" - ), + "completion_recovery", normalize_todo_completion_recovery, + invalid_message="completion_recovery must be same_turn_terminal_closeout or lifecycle_reentry_terminal_closeout", ), _TodoMetadataField( - "resume_when", - normalize_todo_resume_when, - invalid_message=( - "resume_when must be public-safe, e.g. " - "todo_done:todo_ab12cd34ef56, " - "monitor_changed:todo_monitor123, pr_merged:#532, or " - "capacity_available:short_pool" - ), + "replan_obligation_id", normalize_todo_replan_obligation_id, + invalid_message="replan_obligation_id must use the current replan-<16 lowercase hex> identity", ), _TodoMetadataField( - "resume_monitor_generation", - normalize_todo_generation, + "resume_when", normalize_todo_resume_when, invalid_message=( - "resume_monitor_generation must be a non-negative integer" + "resume_when must be public-safe, e.g. todo_done:todo_ab12cd34ef56, " + "monitor_changed:todo_monitor123, pr_merged:#532, or capacity_available:short_pool" ), ), _TodoMetadataField( - "no_followup", - normalize_todo_no_followup, - write_normalizer=_optional_output_bool, - encoder=_metadata_bool_text, - invalid_when=lambda value: value is not None, + "resume_monitor_generation", normalize_todo_generation, + invalid_message="resume_monitor_generation must be a non-negative integer", ), + _bool_field("no_followup", normalize_todo_no_followup), *( _TodoMetadataField( - key, - _nonempty_metadata_text, - write_normalizer=normalize_todo_generation - if key == "material_change_generation" - else _truthy_value, + key, _nonempty_metadata_text, + write_normalizer=normalize_todo_generation if key == "material_change_generation" else _truthy_value, ) for key in TODO_MONITOR_METADATA_FIELDS ), *( - _TodoMetadataField( - key, - _nonempty_metadata_text, - write_normalizer=_truthy_value, - ) - for key in ( - "note", - "evidence", - "reason", - "completed_at", - "updated_at", - "completion_turn_key", - "completion_receipt_id", - ) + _TodoMetadataField(key, _nonempty_metadata_text, write_normalizer=_truthy_value) + for key in ("note", "evidence", "reason", "completed_at", "updated_at", "completion_turn_key", "completion_receipt_id") ), # The declaration digest includes exact command arguments and label text. # Percent encoding keeps these values within one Markdown comment line. *( - _TodoMetadataField(key, _nonblank_verbatim_metadata_text, - write_normalizer=_truthy_value, preserve_whitespace=True) + _TodoMetadataField(key, _nonblank_verbatim_metadata_text, write_normalizer=_truthy_value, preserve_whitespace=True) for key in ("validation_command", "validation_command_argv") ), _TodoMetadataField("validation_label", _truthy_value, preserve_whitespace=True), - _TodoMetadataField( - "validation_timeout_seconds", - _nonempty_metadata_text, - write_normalizer=_truthy_value, - ), - _TodoMetadataField( - "superseded_by", - normalize_todo_id, - invalid_message=( - "superseded_by must use the public token shape " - "todo_" - ), - ), + _TodoMetadataField("validation_timeout_seconds", _nonempty_metadata_text, write_normalizer=_truthy_value), + _TodoMetadataField("superseded_by", normalize_todo_id, invalid_message=_todo_id_message("superseded_by")), ) _TODO_METADATA_FIELD_BY_TOKEN = { @@ -1133,11 +961,11 @@ def _todo_metadata_block_fields() -> tuple[str, ...]: TODO_METADATA_FIELDS = _todo_metadata_block_fields() -def parse_todo_metadata_line(line: str) -> dict[str, Any] | None: +def parse_todo_metadata_line(line: str) -> dict[str, object] | None: tokens = parse_todo_metadata_tokens(line) if tokens is None: return None - metadata: dict[str, Any] = {} + metadata: dict[str, object] = {} for key, value in tokens: field = _TODO_METADATA_FIELD_BY_TOKEN.get(key) if field is None: @@ -1156,8 +984,8 @@ def parse_todo_metadata_line(line: str) -> dict[str, Any] | None: return metadata or None -def _normalize_todo_metadata_for_write(values: dict[str, Any]) -> dict[str, Any]: - normalized: dict[str, Any] = {} +def _normalize_todo_metadata_for_write(values: Mapping[str, object]) -> dict[str, object]: + normalized: dict[str, object] = {} for field in _TODO_METADATA_FIELD_SCHEMA: value = field.normalize_for_write(values.get(field.key)) if _metadata_value_is_present(value): @@ -1169,25 +997,28 @@ def _normalize_todo_metadata_for_write(values: dict[str, Any]) -> dict[str, Any] raise ValueError( "continuation_policy and removed_continuation_policy are mutually exclusive" ) - if ( - field.key == "excluded_agents" - and normalized.get("claimed_by") - and normalized["claimed_by"] in normalized.get("excluded_agents", []) - ): - raise ValueError( - f"claimed_by={normalized['claimed_by']!r} cannot also appear in " - "excluded_agents" - ) + if field.key == "excluded_agents": + claimed_by = normalized.get("claimed_by") + excluded = normalized.get("excluded_agents") + if ( + isinstance(claimed_by, str) + and claimed_by + and isinstance(excluded, list) + and claimed_by in excluded + ): + raise ValueError( + f"claimed_by={claimed_by!r} cannot also appear in excluded_agents" + ) return normalized -def normalize_todo_metadata_for_write(values: dict[str, Any]) -> dict[str, Any]: +def normalize_todo_metadata_for_write(values: Mapping[str, object]) -> dict[str, object]: """Return canonical typed Todo metadata without Markdown encoding.""" return _normalize_todo_metadata_for_write(values) -def _format_todo_metadata_values(values: dict[str, Any]) -> str | None: +def _format_todo_metadata_values(values: Mapping[str, object]) -> str | None: normalized = _normalize_todo_metadata_for_write(values) fields = [] for field in _TODO_METADATA_FIELD_SCHEMA: @@ -1214,23 +1045,23 @@ def format_todo_metadata_line( task_repository: str | None = None, continuation_policy: str | None = None, removed_continuation_policy: str | None = None, - required_write_scopes: Any = None, - required_capabilities: Any = None, - target_capabilities: Any = None, - explore_result_node_refs: Any = None, - decision_scope: Any = None, - required_decision_scopes: Any = None, + required_write_scopes: object = None, + required_capabilities: object = None, + target_capabilities: object = None, + explore_result_node_refs: object = None, + decision_scope: object = None, + required_decision_scopes: object = None, decision_outcome: str | None = None, - decision_scope_outcomes: Any = None, + decision_scope_outcomes: object = None, claimed_by: str | None = None, last_actor_agent_id: str | None = None, bound_agent: str | None = None, goal_bound: bool | None = None, blocks_agent: str | None = None, - excluded_agents: Any = None, + excluded_agents: object = None, global_gate: bool | None = None, unblocks_todo_id: str | None = None, - successor_todo_ids: Any = None, + successor_todo_ids: object = None, completion_continuation: str | None = None, completion_recovery: str | None = None, completion_receipt_id: str | None = None, @@ -1268,187 +1099,146 @@ def format_todo_metadata_line( return _format_todo_metadata_values(values) -def todo_block_metadata(block: dict[str, Any]) -> dict[str, Any]: - metadata: dict[str, Any] = {} +_BLOCK_READ_NORMALIZERS: dict[str, MetadataValueNormalizer] = { + "required_write_scopes": normalize_required_write_scopes, + "task_domain": normalize_todo_task_domain, + "task_repository": normalize_todo_task_repository, + "required_capabilities": normalize_required_capabilities, + "target_capabilities": normalize_target_capabilities, + "excluded_agents": normalize_todo_excluded_agents, + "explore_result_node_refs": normalize_explore_result_node_refs, + "continuation_policy": normalize_todo_continuation_policy, + "decision_scope": normalize_todo_decision_scope, + "required_decision_scopes": normalize_todo_required_decision_scopes, + "decision_outcome": normalize_todo_decision_outcome, + "decision_scope_outcomes": normalize_todo_decision_scope_outcomes, + "no_followup": normalize_todo_no_followup, + "completion_continuation": normalize_todo_completion_continuation, + "completion_recovery": normalize_todo_completion_recovery, + "global_gate": normalize_todo_global_gate, + "goal_bound": normalize_todo_global_gate, +} + +_BLOCK_TRUTHY_OR_POP_NORMALIZERS: dict[str, MetadataValueNormalizer] = { + "required_write_scopes": normalize_required_write_scopes, + "task_repository": normalize_todo_task_repository, + "required_capabilities": normalize_required_capabilities, + "target_capabilities": normalize_target_capabilities, + "excluded_agents": normalize_todo_excluded_agents, + "explore_result_node_refs": normalize_explore_result_node_refs, + "required_decision_scopes": require_todo_required_decision_scopes, + "decision_scope_outcomes": normalize_todo_decision_scope_outcomes, + "successor_todo_ids": normalize_todo_id_list, +} + +_BLOCK_OPTIONAL_BOOL_NORMALIZERS: dict[str, Callable[[object], bool | None]] = { + "no_followup": normalize_todo_no_followup, + "global_gate": normalize_todo_global_gate, + "goal_bound": normalize_todo_global_gate, +} + +_BLOCK_STRICT_SETTERS: dict[str, MetadataValueNormalizer] = { + "task_domain": _TODO_METADATA_FIELD_BY_TOKEN["task_domain"].normalize_for_write, + "decision_scope": require_todo_decision_scope, + "decision_outcome": require_todo_decision_outcome, +} + + +def todo_block_metadata(block: Mapping[str, object]) -> dict[str, object]: + metadata: dict[str, object] = {} for key in TODO_METADATA_FIELDS: value = block.get(key) if value is None: continue - normalized: Any - if key == "required_write_scopes": - normalized = normalize_required_write_scopes(value) - elif key == "task_domain": - normalized = normalize_todo_task_domain(value) - elif key == "task_repository": - normalized = normalize_todo_task_repository(value) - elif key == "required_capabilities": - normalized = normalize_required_capabilities(value) - elif key == "target_capabilities": - normalized = normalize_target_capabilities(value) - elif key == "excluded_agents": - normalized = normalize_todo_excluded_agents(value) - elif key == "explore_result_node_refs": - normalized = normalize_explore_result_node_refs(value) - elif key == "continuation_policy": - normalized = normalize_todo_continuation_policy(value) - elif key == "decision_scope": - normalized = normalize_todo_decision_scope(value) - elif key == "required_decision_scopes": - normalized = normalize_todo_required_decision_scopes(value) - elif key == "decision_outcome": - normalized = normalize_todo_decision_outcome(value) - elif key == "decision_scope_outcomes": - normalized = normalize_todo_decision_scope_outcomes(value) - elif key == "no_followup": - normalized = normalize_todo_no_followup(value) - elif key == "completion_continuation": - normalized = normalize_todo_completion_continuation(value) - elif key == "completion_recovery": - normalized = normalize_todo_completion_recovery(value) - elif key in {"global_gate", "goal_bound"}: - normalized = normalize_todo_global_gate(value) + normalizer = _BLOCK_READ_NORMALIZERS.get(key) + if normalizer is not None: + normalized = normalizer(value) elif _TODO_METADATA_FIELD_BY_TOKEN[key].preserve_whitespace: normalized = value else: normalized = str(value).strip() - if normalized is not None and normalized != [] and normalized != "": + if _metadata_value_is_present(normalized): metadata[key] = normalized return metadata +def _apply_todo_block_update( + metadata: dict[str, object], + key: str, + value: object, +) -> None: + if value is None: + metadata.pop(key, None) + elif (truthy_norm := _BLOCK_TRUTHY_OR_POP_NORMALIZERS.get(key)) is not None: + normalized = truthy_norm(value) + if normalized: + metadata[key] = normalized + else: + metadata.pop(key, None) + elif (strict_setter := _BLOCK_STRICT_SETTERS.get(key)) is not None: + metadata[key] = strict_setter(value) + elif key == "continuation_policy": + normalized_policy = normalize_todo_continuation_policy(value) + if normalized_policy: + metadata[key] = normalized_policy + elif value: + raise ValueError( + "todo continuation_policy must be one of: " + + ", ".join(sorted(TODO_CONTINUATION_POLICY_VALUES)) + ) + else: + metadata.pop(key, None) + elif (bool_norm := _BLOCK_OPTIONAL_BOOL_NORMALIZERS.get(key)) is not None: + normalized_bool = bool_norm(value) + if normalized_bool is not None: + metadata[key] = normalized_bool + else: + metadata.pop(key, None) + elif key in {"completion_continuation", "completion_recovery"}: + normalized_completion = require_todo_completion_metadata(key, value) + if normalized_completion: + metadata[key] = normalized_completion + else: + metadata.pop(key, None) + elif _TODO_METADATA_FIELD_BY_TOKEN[key].preserve_whitespace: + metadata[key] = value + elif str(value).strip(): + metadata[key] = str(value).strip() + + def metadata_line_for_todo_block( - block: dict[str, Any], - updates: dict[str, Any], + block: Mapping[str, object], + updates: Mapping[str, object], ) -> str | None: metadata = todo_block_metadata(block) for key, value in updates.items(): - if key not in TODO_METADATA_FIELDS: - continue - if value is None: - metadata.pop(key, None) - elif key == "required_write_scopes": - normalized = normalize_required_write_scopes(value) - if normalized: - metadata[key] = normalized - else: - metadata.pop(key, None) - elif key == "task_domain": - metadata[key] = _TODO_METADATA_FIELD_BY_TOKEN[ - key - ].normalize_for_write(value) - elif key == "task_repository": - normalized_repository = normalize_todo_task_repository(value) - if normalized_repository: - metadata[key] = normalized_repository - else: - metadata.pop(key, None) - elif key == "required_capabilities": - normalized = normalize_required_capabilities(value) - if normalized: - metadata[key] = normalized - else: - metadata.pop(key, None) - elif key == "target_capabilities": - normalized = normalize_target_capabilities(value) - if normalized: - metadata[key] = normalized - else: - metadata.pop(key, None) - elif key == "excluded_agents": - normalized = normalize_todo_excluded_agents(value) - if normalized: - metadata[key] = normalized - else: - metadata.pop(key, None) - elif key == "explore_result_node_refs": - normalized = normalize_explore_result_node_refs(value) - if normalized: - metadata[key] = normalized - else: - metadata.pop(key, None) - elif key == "continuation_policy": - normalized_continuation_policy = normalize_todo_continuation_policy(value) - if normalized_continuation_policy: - metadata[key] = normalized_continuation_policy - elif value: - raise ValueError( - "todo continuation_policy must be one of: " - + ", ".join(sorted(TODO_CONTINUATION_POLICY_VALUES)) - ) - else: - metadata.pop(key, None) - elif key == "decision_scope": - metadata[key] = require_todo_decision_scope(value) - elif key == "required_decision_scopes": - normalized_decision_scopes = require_todo_required_decision_scopes(value) - if normalized_decision_scopes: - metadata[key] = normalized_decision_scopes - else: - metadata.pop(key, None) - elif key == "decision_outcome": - metadata[key] = require_todo_decision_outcome(value) - elif key == "decision_scope_outcomes": - normalized_scope_outcomes = normalize_todo_decision_scope_outcomes(value) - if normalized_scope_outcomes: - metadata[key] = normalized_scope_outcomes - else: - metadata.pop(key, None) - elif key == "no_followup": - normalized_no_followup = normalize_todo_no_followup(value) - if normalized_no_followup is not None: - metadata[key] = normalized_no_followup - else: - metadata.pop(key, None) - elif key == "successor_todo_ids": - normalized = normalize_todo_id_list(value) - if normalized: - metadata[key] = normalized - else: - metadata.pop(key, None) - elif key in {"completion_continuation", "completion_recovery"}: - normalized_completion = require_todo_completion_metadata(key, value) - if normalized_completion: - metadata[key] = normalized_completion - else: - metadata.pop(key, None) - elif key in {"global_gate", "goal_bound"}: - normalized_global_gate = normalize_todo_global_gate(value) - if normalized_global_gate is not None: - metadata[key] = normalized_global_gate - else: - metadata.pop(key, None) - elif _TODO_METADATA_FIELD_BY_TOKEN[key].preserve_whitespace: - metadata[key] = value - elif str(value).strip(): - metadata[key] = str(value).strip() + if key in TODO_METADATA_FIELDS: + _apply_todo_block_update(metadata, key, value) if "todo_id" not in metadata and block.get("todo_id"): metadata["todo_id"] = str(block["todo_id"]) if "status" not in metadata: metadata["status"] = TODO_STATUS_DONE if block.get("done") else TODO_STATUS_OPEN - return format_todo_metadata_line(**metadata) + return _format_todo_metadata_values(metadata) + + +_TODO_TEXT_CLASS_RULES: tuple[tuple[tuple[re.Pattern[str], ...], str], ...] = ( + (TODO_HARD_MONITOR_PATTERNS, TODO_TASK_CLASS_MONITOR), + (TODO_ADVANCEMENT_OVERRIDE_PATTERNS, TODO_TASK_CLASS_ADVANCEMENT), + (TODO_BLOCKED_MONITOR_PATTERNS, TODO_TASK_CLASS_MONITOR), + (TODO_MONITOR_PATTERNS, TODO_TASK_CLASS_MONITOR), + (TODO_ADVANCEMENT_PATTERNS, TODO_TASK_CLASS_ADVANCEMENT), +) def todo_task_class_for_text(text: str) -> str: compact = compact_todo_text(text) - for pattern in TODO_HARD_MONITOR_PATTERNS: - if pattern.search(compact): - return TODO_TASK_CLASS_MONITOR - for pattern in TODO_ADVANCEMENT_OVERRIDE_PATTERNS: - if pattern.search(compact): - return TODO_TASK_CLASS_ADVANCEMENT - for pattern in TODO_BLOCKED_MONITOR_PATTERNS: - if pattern.search(compact): - return TODO_TASK_CLASS_MONITOR - for pattern in TODO_MONITOR_PATTERNS: - if pattern.search(compact): - return TODO_TASK_CLASS_MONITOR - for pattern in TODO_ADVANCEMENT_PATTERNS: - if pattern.search(compact): - return TODO_TASK_CLASS_ADVANCEMENT + for patterns, task_class in _TODO_TEXT_CLASS_RULES: + if any(pattern.search(compact) for pattern in patterns): + return task_class return TODO_TASK_CLASS_ADVANCEMENT -def normalize_todo_task_class(value: Any, *, text: str, action_kind: Any = None) -> str: +def normalize_todo_task_class(value: object, *, text: str, action_kind: object = None) -> str: candidate = normalize_explicit_todo_task_class(value) if candidate: return candidate diff --git a/loopx/control_plane/todos/markdown.py b/loopx/control_plane/todos/markdown.py index a5037a75bc..e5f0b53bb1 100644 --- a/loopx/control_plane/todos/markdown.py +++ b/loopx/control_plane/todos/markdown.py @@ -194,6 +194,16 @@ def cell(value: Any) -> str: return "\n".join(lines) +def _render_execution_managed_claim_lines(payload: dict[str, Any]) -> list[str]: + """Render compact managed-claim lease metadata alongside claim identity.""" + lines = ["", f"- claim_operation_id: `{payload['claim_operation_id']}`"] + if payload.get("lease_expires_at"): + lines.append(f"- lease_expires_at: `{payload['lease_expires_at']}`") + if payload.get("lease_ttl_seconds") is not None: + lines.append(f"- lease_ttl_seconds: `{payload['lease_ttl_seconds']}`") + return lines + + def render_todo_markdown(payload: dict[str, Any]) -> str: if payload.get("todo_detail_projection"): return _render_todo_detail(payload) @@ -370,7 +380,7 @@ def render_todo_markdown(payload: dict[str, Any]) -> str: lines.extend(["", str(payload["instruction"])]) lines.extend(_render_settlement_plan(payload["settlement_plan"])) if not payload.get("error") and payload.get("execution_managed"): - lines.extend(["", f"- claim_operation_id: `{payload['claim_operation_id']}`"]) + lines.extend(_render_execution_managed_claim_lines(payload)) if not payload.get("error"): lines.extend(render_settlement_progress_markdown(payload)) if not payload.get("error") and (payload.get("execution_managed") or payload.get("settlement_progress")): diff --git a/loopx/control_plane/todos/mutation_api.py b/loopx/control_plane/todos/mutation_api.py index e5f4da8db0..53048d1a81 100644 --- a/loopx/control_plane/todos/mutation_api.py +++ b/loopx/control_plane/todos/mutation_api.py @@ -313,6 +313,7 @@ def update_goal_todo( routing_registry_witness: dict[str, str] | None = None, task_lease_idempotency_key: str | None = None, task_lease_expected_version: int | None = None, + ttl_seconds: int | None = None, project: Path | None = None, state_file: Path | None = None, dry_run: bool = False, @@ -349,7 +350,16 @@ def update_goal_todo( raise ValueError( "--task-lease-expected-version requires --task-lease-idempotency-key" ) + if not claim_only and ttl_seconds is not None: + raise ValueError("ttl_seconds is supported only by todo claim") if claim_only: + if ttl_seconds is not None and ( + isinstance(ttl_seconds, bool) + or not isinstance(ttl_seconds, int) + or ttl_seconds <= 0 + or ttl_seconds > 86400 + ): + raise ValueError("ttl seconds must be between 1 and 86400") unsupported_claim_values = ( text, priority, clear_priority or None, status, note, validation_command, validation_command_json, validation_label, @@ -390,6 +400,7 @@ def update_goal_todo( routing_registry_witness=routing_registry_witness, task_lease_idempotency_key=task_lease_idempotency_key, task_lease_expected_version=task_lease_expected_version, + ttl_seconds=ttl_seconds, project=project, state_file=state_file, ) diff --git a/loopx/control_plane/turn_driver/codex_context.py b/loopx/control_plane/turn_driver/codex_context.py index 70e63b2b95..e258464a41 100644 --- a/loopx/control_plane/turn_driver/codex_context.py +++ b/loopx/control_plane/turn_driver/codex_context.py @@ -327,7 +327,9 @@ def codex_context_recovery_instructions(directory: str, *, goal_id: str, agent_i def codex_context_configuration(directory: str, *, goal_id: str, agent_id: str, cli_argv: list[str], scenario: str, session_root: bool = False, inherit_machine: bool = False, progressive_enabled: bool = True, - compact_direct_read: bool = False) -> dict[str, Any]: + compact_direct_read: bool = False, + quiet_turn: bool = False, + epoch_prefetch: Mapping[str, Any] | None = None) -> dict[str, Any]: """Native configuration data shared by the worker and CLI setup journey. This renders no trust hashes and writes no host configuration. The native @@ -340,6 +342,15 @@ def codex_context_configuration(directory: str, *, goal_id: str, agent_id: str, raise ValueError("unsupported native context configuration scenario") if not goal_id or not agent_id: raise ValueError("context configuration requires exact goal-id and agent-id") + if type(compact_direct_read) is not bool or type(quiet_turn) is not bool: + raise ValueError("compact_direct_read and quiet_turn require explicit booleans") + canonical_epoch_prefetch: str | None = None + if epoch_prefetch is not None: + if not isinstance(epoch_prefetch, Mapping): + raise ValueError("epoch_prefetch must be a JSON object") + canonical_epoch_prefetch = json.dumps( + dict(epoch_prefetch), ensure_ascii=False, sort_keys=True, separators=(",", ":"), + ) directory = str(_private_root(directory)) option = "--codex-context-root" if session_root else "--codex-context-dir" activation_args = ["--context-delivery", "on"] if progressive_enabled else [ @@ -348,6 +359,9 @@ def codex_context_configuration(directory: str, *, goal_id: str, agent_id: str, *cli_argv, "--format", "json", "quota", "context-hook", *([] if inherit_machine else activation_args), *(["--compact-direct-read"] if compact_direct_read else []), + *(["--quiet-turn"] if quiet_turn else []), + *(["--epoch-prefetch-json", canonical_epoch_prefetch] + if canonical_epoch_prefetch is not None else []), *(["--codex-app"] if scenario == "codex_app_heartbeat" else ["--runtime-profile", "codex_app_ssh_goal" if scenario == "codex_app_ssh_goal" else "generic_cli"]), option, directory]), "timeout": 10} @@ -434,6 +448,258 @@ def _reduce_hook_lifecycle( raise +def _epoch_prefetch_is_configured(state: Mapping[str, Any], event: Mapping[str, Any]) -> bool: + """Return True only when Stage-then-Swap EpochReset prefetch is explicitly enabled.""" + cfg = ( + event.get("epoch_prefetch") + if isinstance(event.get("epoch_prefetch"), Mapping) + else state.get("epoch_prefetch_policy") + if isinstance(state.get("epoch_prefetch_policy"), Mapping) + else None + ) + return isinstance(cfg, Mapping) and cfg.get("enabled") is True + + +def _utf8_prefix_text(text: str, max_bytes: int) -> str: + if max_bytes <= 0: + return "" + raw = text.encode("utf-8") + if len(raw) <= max_bytes: + return text + clipped = raw[:max_bytes] + while clipped and (clipped[-1] & 0xC0) == 0x80: + clipped = clipped[:-1] + return clipped.decode("utf-8", errors="replace") + + +def _extract_epoch_prefetch_part( + prefetch_text: str, + ep_meta: Mapping[str, Any], + *, + direct_operator: str | None, + continuation_text: str, +) -> str: + part = prefetch_text + if ep_meta.get("operator") == "EpochReset": + if "\n[Stage-then-Swap EpochReset Receipt" in part: + part = part[part.index("[Stage-then-Swap EpochReset Receipt"):] + suffix = f"\nOriginal saved capture remains available at: {continuation_text}" + if continuation_text and suffix in part: + part = part.replace(suffix, "", 1).rstrip() + elif continuation_text and continuation_text in part: + part = part.replace(continuation_text, "", 1).rstrip() + return part + if ep_meta.get("operator") == "KeepRaw" and direct_operator == "EpochReset": + for marker in ("\nPreserved failure facts:", "\nPrefetch fallback notice (KeepRaw):"): + idx = part.find(marker) + if idx != -1: + return part[idx + 1:].strip() + return part + + +def _composition_budgets( + *, + has_direct: bool, + has_prefetch: bool, + direct_read_cfg: Mapping[str, Any] | None, + epoch_prefetch_cfg: Mapping[str, Any] | None, + baseline_bytes: int | None, +) -> tuple[int | None, int | None, int | None]: + direct_cap: int | None = None + if has_direct and isinstance(direct_read_cfg, Mapping): + val = direct_read_cfg.get("max_output_bytes") + if isinstance(val, int) and not isinstance(val, bool) and val > 0: + direct_cap = val + epoch_caps: list[int] = [direct_cap] if direct_cap is not None else [] + if has_prefetch and isinstance(epoch_prefetch_cfg, Mapping): + val = epoch_prefetch_cfg.get("max_output_bytes") + epoch_caps.append(val if isinstance(val, int) and not isinstance(val, bool) and val > 0 else 16_384) + epoch_output_cap = min(epoch_caps) if epoch_caps else None + baseline_ceiling: int | None = None + if baseline_bytes is not None: + raw_min = epoch_prefetch_cfg.get("min_net_savings_bytes") if isinstance(epoch_prefetch_cfg, Mapping) else None + min_net = int(raw_min) if isinstance(raw_min, int) and not isinstance(raw_min, bool) else 1 + baseline_ceiling = max(0, int(baseline_bytes) - min_net) + return direct_cap, epoch_output_cap, baseline_ceiling + + +def _fail_closed_epoch_prefetch_meta( + ep_meta: dict[str, Any], + *, + superseded: bool, + delivered_bytes: int, + budget_bytes: int | None, +) -> dict[str, Any]: + return { + **ep_meta, + "configured": True, + "superseded": superseded, + "superseded_by": "compact_direct_read" if superseded else None, + "composed_with_compact_direct_read": superseded, + "operator": "KeepRaw", + "status": "fallback_keep_raw", + "fallback_reason": "composed_budget_exceeded", + "preserves_raw_state": True, + "reclaimed_turns": 0, + "dropped_failures": 0, + "round_trips_saved": 0, + "bytes_saved": 0, + "delivered_bytes": delivered_bytes, + "composed_budget_bytes": budget_bytes, + } + + +def _compose_direct_read_and_epoch_prefetch( + direct_reply: dict[str, Any] | None, + prefetch_hook: dict[str, Any] | None, + *, + hook_name: Any, + epoch_prefetch_configured: bool, + recovery_needed: bool, + has_recovery_command: bool, + direct_read_cfg: Mapping[str, Any] | None = None, + epoch_prefetch_cfg: Mapping[str, Any] | None = None, + baseline_bytes: int | None = None, + continuation_text: str = "", +) -> dict[str, Any] | None: + """Keep compact direct-read and EpochReset prefetch composition within delivered UTF-8 byte budgets.""" + direct_cap, epoch_output_cap, baseline_ceiling = _composition_budgets( + has_direct=direct_reply is not None, + has_prefetch=prefetch_hook is not None, + direct_read_cfg=direct_read_cfg, + epoch_prefetch_cfg=epoch_prefetch_cfg, + baseline_bytes=baseline_bytes, + ) + if direct_reply is None: + if prefetch_hook is None: + return None + prefetch_out = dict(prefetch_hook.get("hookSpecificOutput") or {}) + ep_meta = dict(prefetch_out.get("epochPrefetch") or {}) + add_text = prefetch_out.get("additionalContext") + if isinstance(add_text, str) and ep_meta.get("operator") == "EpochReset": + delivered_bytes = len(add_text.encode("utf-8")) + epoch_bounds = [b for b in (epoch_output_cap, baseline_ceiling) if b is not None] + effective_budget = min(epoch_bounds) if epoch_bounds else None + if effective_budget is not None and delivered_bytes > effective_budget: + ep_meta = _fail_closed_epoch_prefetch_meta( + ep_meta, superseded=False, delivered_bytes=delivered_bytes, budget_bytes=effective_budget, + ) + notice = ( + f"[Stage-then-Swap EpochReset Fallback | operator=KeepRaw | reason=composed_budget_exceeded " + f"| delivered_bytes={delivered_bytes} | budget_bytes={effective_budget}]" + ) + prefetch_out["additionalContext"] = notice + prefetch_out["epochPrefetch"] = ep_meta + return {"hookSpecificOutput": prefetch_out} + if baseline_bytes is not None: + if isinstance(ep_meta.get("bytes_saved"), int) and not isinstance(ep_meta.get("bytes_saved"), bool): + ep_meta["bytes_saved"] = min(int(ep_meta["bytes_saved"]), max(0, int(baseline_bytes) - delivered_bytes)) + ep_meta["delivered_bytes"] = delivered_bytes + prefetch_out["epochPrefetch"] = ep_meta + return {"hookSpecificOutput": prefetch_out} + + direct_out = dict(direct_reply.get("hookSpecificOutput") or {}) + if prefetch_hook is None: + if epoch_prefetch_configured: + reason = ( + "post_compact_defers_to_session_start" + if hook_name != "SessionStart" + else "recovery_not_needed" + if not recovery_needed + else "missing_recovery_command" + if not has_recovery_command + else "no_prefetch_receipt" + ) + direct_out["epochPrefetch"] = { + "schema_version": "loopx_epoch_prefetch_receipt_v0", + "configured": True, + "executed": False, + "replayed": False, + "superseded": hook_name == "SessionStart", + "superseded_by": "compact_direct_read" if hook_name == "SessionStart" else None, + "operator": "KeepRaw", + "status": "superseded_by_compact_direct_read" + if hook_name == "SessionStart" + else "deferred_until_session_start", + "reason": reason, + } + return {"hookSpecificOutput": direct_out} + + prefetch_out = dict(prefetch_hook.get("hookSpecificOutput") or {}) + direct_meta = dict(direct_out.get("compactDirectRead") or {}) + ep_meta = dict(prefetch_out.get("epochPrefetch") or {}) + raw_direct_text = direct_out.get("additionalContext") + direct_part = raw_direct_text if isinstance(raw_direct_text, str) and raw_direct_text.strip() else None + raw_prefetch_text = prefetch_out.get("additionalContext") + prefetch_part: str | None = None + if isinstance(raw_prefetch_text, str) and raw_prefetch_text.strip(): + prefetch_part = ( + _extract_epoch_prefetch_part( + raw_prefetch_text, + ep_meta, + direct_operator=str(direct_meta.get("operator") or ""), + continuation_text=continuation_text, + ) + if direct_part is not None + else raw_prefetch_text + ) + + parts = [part for part in (direct_part, prefetch_part) if part] + composed_text = "\n\n".join(parts) + delivered_bytes = len(composed_text.encode("utf-8")) + epoch_bounds = [b for b in (epoch_output_cap, baseline_ceiling) if b is not None] + epoch_budget = min(epoch_bounds) if epoch_bounds else None + + if ep_meta.get("operator") == "EpochReset" and epoch_budget is not None and delivered_bytes > epoch_budget: + ep_meta = _fail_closed_epoch_prefetch_meta( + ep_meta, superseded=True, delivered_bytes=delivered_bytes, budget_bytes=epoch_budget, + ) + composed_text = direct_part or "" + delivered_bytes = len(composed_text.encode("utf-8")) + elif direct_cap is not None and delivered_bytes > direct_cap and prefetch_part: + ep_meta = { + **ep_meta, + "configured": True, + "superseded": True, + "superseded_by": "compact_direct_read", + "composed_with_compact_direct_read": True, + "fallback_reason": ep_meta.get("fallback_reason") or "composed_budget_exceeded", + "round_trips_saved": 0, + "bytes_saved": 0, + "delivered_bytes": delivered_bytes, + "composed_budget_bytes": direct_cap, + } + composed_text = direct_part or "" + delivered_bytes = len(composed_text.encode("utf-8")) + else: + ep_meta = { + **ep_meta, + "configured": True, + "superseded": False, + "composed_with_compact_direct_read": True, + "delivered_bytes": delivered_bytes, + } + if ep_meta.get("operator") == "EpochReset" and baseline_bytes is not None: + if isinstance(ep_meta.get("bytes_saved"), int) and not isinstance(ep_meta.get("bytes_saved"), bool): + ep_meta["bytes_saved"] = min(int(ep_meta["bytes_saved"]), max(0, int(baseline_bytes) - delivered_bytes)) + + if direct_cap is not None and delivered_bytes > direct_cap and direct_meta.get("operator") == "EpochReset": + direct_meta["operator"] = "KeepRaw" + direct_meta["fallback_reason"] = "composed_budget_exceeded" + composed_text = _utf8_prefix_text(composed_text, direct_cap) + + composed: dict[str, Any] = { + "hookEventName": hook_name, + **({"additionalContext": composed_text} if composed_text else {}), + "compactDirectRead": { + **direct_meta, + "composed_with_epoch_prefetch": True, + }, + "epochPrefetch": ep_meta, + } + return {"hookSpecificOutput": composed} + + def _maybe_resolve_compact_direct_read( root: Path, updated: dict[str, Any], @@ -475,6 +741,8 @@ def _maybe_resolve_compact_direct_read( ) if reply is not None and direct_state != updated: _save(root, direct_state) + updated.clear() + updated.update(direct_state) return reply @@ -505,7 +773,9 @@ def codex_context_hook(directory: str | None, event: dict[str, Any]) -> dict[str if name == "PostToolUse" and not pages: return {} # ordinary tool use neither invalidates nor rewrites the journal state: dict[str, Any] = {} + effective_state: dict[str, Any] = state recovery = None + direct_read_cfg: Mapping[str, Any] | None = None direct_reply: dict[str, Any] | None = None try: with _locked(directory) as root: @@ -561,6 +831,7 @@ def codex_context_hook(directory: str | None, event: dict[str, Any]) -> dict[str } if updated != state: _save(root, updated) + effective_state = updated saved = updated.get("recovery") current_file_epoch = (isinstance(saved, dict) and saved.get("continuity_basis") == "captured_file" @@ -585,8 +856,32 @@ def codex_context_hook(directory: str | None, event: dict[str, Any]) -> dict[str raise except (OSError, ValueError, TypeError, RecursionError, EffectRuntimeRemoteError, EffectRuntimeStartupError): recovery_needed = True - if direct_reply is not None: - return direct_reply + ep_cfg = ( + event.get("epoch_prefetch") + if isinstance(event.get("epoch_prefetch"), Mapping) + else effective_state.get("epoch_prefetch_policy") + if isinstance(effective_state.get("epoch_prefetch_policy"), Mapping) + else None + ) + epoch_prefetch_configured = _epoch_prefetch_is_configured(effective_state, event) + continuation_text = ( + _context_continuation_instructions(recovery["command"]) + if isinstance(recovery, dict) and recovery.get("command") + else "" + ) + baseline_bytes: int | None = None + if ( + isinstance(ep_cfg, Mapping) + and isinstance(ep_cfg.get("baseline_bytes"), int) + and not isinstance(ep_cfg.get("baseline_bytes"), bool) + ): + baseline_bytes = int(ep_cfg["baseline_bytes"]) + elif isinstance(recovery, Mapping) and isinstance(recovery.get("path"), str): + try: + baseline_bytes = Path(recovery["path"]).stat().st_size + except OSError: + baseline_bytes = None + prefetch_hook: dict[str, Any] | None = None if (name == "SessionStart" and recovery_needed and isinstance(recovery, dict) and recovery.get("command")): from .epoch_prefetch import resolve_codex_context_epoch_prefetch_hook @@ -594,13 +889,13 @@ def codex_context_hook(directory: str | None, event: dict[str, Any]) -> dict[str prefetch_hook = resolve_codex_context_epoch_prefetch_hook( directory=directory, hook_name=name, - state=state, + state=effective_state, event=event, recovery=recovery, lock_ctx=_locked, read_state_fn=_state, save_state_fn=_save, - continuation_text=_context_continuation_instructions(recovery["command"]), + continuation_text=continuation_text, raw_guidance_text=( CONTEXT_CAPTURE_SELECTION_GUIDANCE + _NATIVE_CONTEXT_OUTPUT_GUIDANCE @@ -608,11 +903,24 @@ def codex_context_hook(directory: str | None, event: dict[str, Any]) -> dict[str + CONTEXT_CAPTURE_PAGE_GUIDANCE ), ) - if prefetch_hook is not None: - return prefetch_hook + if direct_reply is not None or prefetch_hook is not None: + return _compose_direct_read_and_epoch_prefetch( + direct_reply, + prefetch_hook, + hook_name=name, + epoch_prefetch_configured=epoch_prefetch_configured, + recovery_needed=recovery_needed, + has_recovery_command=bool(isinstance(recovery, dict) and recovery.get("command")), + direct_read_cfg=direct_read_cfg, + epoch_prefetch_cfg=ep_cfg, + baseline_bytes=baseline_bytes, + continuation_text=continuation_text, + ) or {} + if (name == "SessionStart" and recovery_needed + and isinstance(recovery, dict) and recovery.get("command")): return {"hookSpecificOutput": {"hookEventName": name, "additionalContext": "LoopX model-context baseline invalidated. Saved files remain available. " - + _context_continuation_instructions(recovery["command"]) + + continuation_text + CONTEXT_CAPTURE_SELECTION_GUIDANCE + _NATIVE_CONTEXT_OUTPUT_GUIDANCE + "If you choose to read an entire file: " + CONTEXT_CAPTURE_PAGE_GUIDANCE}} @@ -620,7 +928,7 @@ def codex_context_hook(directory: str | None, event: dict[str, Any]) -> dict[str quiet_hook = resolve_codex_context_quiet_turn_hook( hook_name=name, - state=state, + state=effective_state, event=event, recovery=recovery, root_dir=_private_root(directory), diff --git a/loopx/control_plane/turn_driver/codex_execution_preparation.py b/loopx/control_plane/turn_driver/codex_execution_preparation.py index ba292b259e..5873a9a8c9 100644 --- a/loopx/control_plane/turn_driver/codex_execution_preparation.py +++ b/loopx/control_plane/turn_driver/codex_execution_preparation.py @@ -194,6 +194,16 @@ class ExecutionPreparationClaimFailed(ValueError): } +class UnconsumedExecutionPreparationClaim(ValueError): + """The builtin adapter could not prepare a required managed claim.""" + + code = "turn_execution_preparation_claim_not_consumed" + + def __init__(self, recovery: Mapping[str, str]) -> None: + super().__init__("The builtin CLI did not claim the Todo required to run this Turn.") + self.payload = {"status": "execution_preparation_required", "executed": False, **recovery} + + def _exact_identity(value: object) -> str | None: """Keep a decision identity exact; display normalization cannot stand in for it.""" if isinstance(value, str) and value and value == value.strip(): @@ -201,29 +211,9 @@ def _exact_identity(value: object) -> str | None: return None -def builtin_execution_preparation_claim( - decision: Mapping[str, Any], - *, - agent_id: str, - registry_path: Path, - runtime_root: Path, - cwd: Path, - turn_instance_id: str | None = None, - goal_ref: Mapping[str, object] | None = None, - runner: CommandRunner | None = None, - timeout: float = 30, - admit_start: Callable[[SettlementIdentity], bool] | None = None, - on_claim: Callable[[Mapping[str, Any]], None] | None = None, -) -> str | None: - """Execute the exact ordinary claim a decision advertised for a Host. - - The decision stays the owner of readiness: this adapter runs only the - claim the decision already published as Host-executable, then the caller - re-reads the same decision and must observe the same Todo ready. A - preparation this adapter does not recognise is left untouched so its - original typed wait keeps its meaning. - """ - +def _builtin_claim_identity( + decision: Mapping[str, Any], agent_id: str, +) -> tuple[str, str, str, list[str]] | None: preparation = decision.get("execution_preparation") selected = decision.get("selected_todo") if not isinstance(preparation, Mapping) or not isinstance(selected, Mapping): @@ -249,10 +239,6 @@ def builtin_execution_preparation_claim( decision_agent_id = ( _exact_identity(declared_agent) if declared_agent is not None else identity_agent_id ) - expected_claim = [ - "todo", "claim", "--goal-id", goal_id, "--todo-id", todo_id, - "--agent-id", caller_agent_id, "--claimed-by", caller_agent_id, - ] if ( preparation.get("schema_version") != "execution_preparation_v0" or preparation.get("delivery_allowed") is not False @@ -268,12 +254,41 @@ def builtin_execution_preparation_claim( or preparation_agent_id != caller_agent_id or (selected_agent is not None and selected_agent_id != caller_agent_id) or (identity_agent is not None and identity_agent_id != caller_agent_id) - or claim.get("cli_args") != expected_claim - or not registry_path.is_absolute() - or not runtime_root.is_absolute() - or not cwd.is_absolute() ): return None + expected_claim = [ + "todo", "claim", "--goal-id", goal_id, "--todo-id", todo_id, + "--agent-id", caller_agent_id, "--claimed-by", caller_agent_id, + ] + if claim.get("cli_args") != expected_claim: + return None + return goal_id, caller_agent_id, todo_id, expected_claim + + +def builtin_execution_preparation_claim( + decision: Mapping[str, Any], + *, + agent_id: str, + registry_path: Path, + runtime_root: Path, + cwd: Path, + turn_instance_id: str | None = None, + goal_ref: Mapping[str, object] | None = None, + runner: CommandRunner | None = None, + timeout: float = 30, + admit_start: Callable[[SettlementIdentity], bool] | None = None, + on_claim: Callable[[Mapping[str, Any]], None] | None = None, +) -> str | None: + """Execute the exact ordinary claim a decision advertised for a Host. + + The decision stays the owner of readiness: this adapter runs only the + claim the decision already published as Host-executable, then the caller + re-reads the same decision and must observe the same Todo ready. + """ + claim_identity = _builtin_claim_identity(decision, agent_id) + if claim_identity is None or not all(path.is_absolute() for path in (registry_path, runtime_root, cwd)): + return None + goal_id, caller_agent_id, todo_id, expected_claim = claim_identity heartbeat = decision.get("heartbeat_receipt") # Resolve one Turn identity before reading a receipt or running the claim. # The transaction plan applies the same normalization, so a padded or @@ -374,6 +389,31 @@ def before_bind() -> None: return todo_id +def unconsumed_preparation_refusal( + decision: Mapping[str, Any], *, goal_id: str, agent_id: str, +) -> UnconsumedExecutionPreparationClaim | None: + """Surface only a claim the exact builtin adapter could accept.""" + preparation = decision.get("execution_preparation") + if not isinstance(preparation, Mapping) or preparation.get("state") != "claim_required": + return None + recovery: dict[str, str] = {} + identity = _builtin_claim_identity(decision, agent_id) + if identity is not None and identity[0] == goal_id: + _, _, todo_id, argv = identity + command = shlex.join(["loopx", *argv, "--thin"]) + if preparation["claim"].get("command_line") == command: + recovery = { + "todo_id": todo_id, + "claim_command": command, + "next_step": ( + "Use the same registry and runtime options for the claim. " + "Rerun quota should-run for the same Goal, agent, Todo, and Turn, " + "and continue only when execution_preparation.state is ready." + ), + } + return UnconsumedExecutionPreparationClaim(recovery) + + def _native_claim_operation_id(request: Mapping[str, Any]) -> str: """Reuse the captured managed claim identity on an authorized retry.""" digest = request.get("claim_source_sha256") diff --git a/loopx/control_plane/turn_driver/codex_operation_host.py b/loopx/control_plane/turn_driver/codex_operation_host.py index ff1203b5d6..d1063c7432 100644 --- a/loopx/control_plane/turn_driver/codex_operation_host.py +++ b/loopx/control_plane/turn_driver/codex_operation_host.py @@ -74,6 +74,11 @@ def run_codex_operation_host( if not all(lineage.values()): raise ValueError("managed operation tools require a Todo-bound Turn") mcp_server = normalize_codex_stdio_mcp_server(mcp_server) + from .codex_worker_identity import load_worker_identity + + worker = load_worker_identity(runtime_root, registry_path) + if worker is not None and (sandbox != "read-only" or mcp_server is not None): + raise ValueError("isolated managed Codex requires read-only operation tools without a Core-provided MCP server") request_source = operation_request_source(operation_request_file, operation_request_sha256) resolved_bin = shutil.which(codex_bin) if not resolved_bin: @@ -86,18 +91,22 @@ def run_codex_operation_host( "reasoning_effort": reasoning_effort, "sandbox": sandbox, "workspace": str(project.resolve()), - "codex_home": str( + "codex_home": str(worker.codex_home) if worker is not None else str( Path(os.environ.get("CODEX_HOME") or "~/.codex").expanduser().resolve() ), "codex_binary_digest": binary_digest, "mcp_server": mcp_server, } + if worker is not None: + profile["worker_identity"] = {"uid": worker.uid, "gid": worker.gid} if request_source is not None: profile["operation_request"] = request_source.profile(source_route) admission = goal_admission or FirstPartyHostGoalAdmission.for_plan( registry_path=registry_path, goal_id=lineage["goal_id"], planned_goal_ref=request.get("goal_ref"), agent_id=lineage["agent_id"], ) + if worker is not None and (admission.legacy_source_admission is not None or admission.registry_path != registry_path): + raise ValueError("isolated managed Codex requires the owning project registry") profile_digest = hashlib.sha256( json.dumps(profile, sort_keys=True, separators=(",", ":")).encode() ).hexdigest() @@ -150,6 +159,7 @@ def run_codex_operation_host( resume_thread_id=binding["session_id"] if binding else None, dynamic_tools=[operations.OPERATION_TOOL], host_config=host_config, + **({"worker_identity": worker} if worker is not None else {}), launch_guard=lambda: admission.launch_lifetime(operation="codex_operation_process_launch"), response_timeout_sec=30 if timeout_seconds is None else min(timeout_seconds, 30), hard_timeout_sec=timeout_seconds, diff --git a/loopx/control_plane/turn_driver/codex_stdio.py b/loopx/control_plane/turn_driver/codex_stdio.py index d35543499e..700a0ccf5a 100644 --- a/loopx/control_plane/turn_driver/codex_stdio.py +++ b/loopx/control_plane/turn_driver/codex_stdio.py @@ -109,14 +109,25 @@ def _next_message(self, *, timeout_sec: float) -> Mapping[str, Any] | None: raise NativeGoalProtocolError(str(message)) from message return message - def request(self, method: str, params: Mapping[str, Any]) -> Mapping[str, Any]: + def request( + self, method: str, params: Mapping[str, Any], *, deadline: float | None = None, + ) -> Mapping[str, Any]: + """Use a monotonic caller deadline when it is earlier than the RPC limit.""" + started = time.monotonic() + if deadline is not None and deadline <= started: + raise subprocess.TimeoutExpired(self.process.args, 0) request_id = self._next_request_id self._next_request_id += 1 self._send({"id": request_id, "method": method, "params": dict(params)}) - deadline = time.monotonic() + self.response_timeout_sec + response_deadline = time.monotonic() + self.response_timeout_sec + caller_limited = deadline is not None and deadline <= response_deadline + if caller_limited: + response_deadline = deadline while True: - remaining = deadline - time.monotonic() + remaining = response_deadline - time.monotonic() if remaining <= 0: + if caller_limited: + raise subprocess.TimeoutExpired(self.process.args, response_deadline - started) raise NativeGoalProtocolError(f"app_server_response_timeout:{method}") message = self._next_message(timeout_sec=remaining) if message is None: diff --git a/loopx/control_plane/turn_driver/codex_worker_identity.py b/loopx/control_plane/turn_driver/codex_worker_identity.py new file mode 100644 index 0000000000..1bf6ebd4f3 --- /dev/null +++ b/loopx/control_plane/turn_driver/codex_worker_identity.py @@ -0,0 +1,81 @@ +"""Linux process identity for the managed Codex operation host.""" +from __future__ import annotations + +import os +import shutil +import stat +import sys +from dataclasses import dataclass +from pathlib import Path + + +@dataclass(frozen=True) +class CodexWorkerIdentity: + uid: int + gid: int + home: Path + setpriv: str + + @property + def codex_home(self) -> Path: + return self.home / ".codex" + + @property + def process_options(self) -> dict: + return {"user": self.uid, "group": self.gid, "extra_groups": [], "umask": 0o077} + + @property + def environment(self) -> dict[str, str]: + return {"HOME": str(self.home), "USERPROFILE": str(self.home), + "CODEX_HOME": str(self.codex_home), "PATH": os.defpath} + + +def worker_isolation_requested() -> bool: + return bool(os.environ.get("LOOPX_CODEX_OPERATION_WORKER_USER") or + os.environ.get("LOOPX_CODEX_OPERATION_WORKER_HOME")) + + +def _require_private_directory(path: Path, uid: int) -> None: + if not path.is_absolute() or path.resolve(strict=True) != path: + raise ValueError("isolated Codex paths must be absolute physical directories") + info = path.stat() + if not stat.S_ISDIR(info.st_mode) or info.st_uid != uid or info.st_mode & 0o077: + raise ValueError("isolated Codex directory must be private and owned by its account") + + +def load_worker_identity(runtime_root: Path, registry_path: Path) -> CodexWorkerIdentity | None: + if not worker_isolation_requested(): + return None + if sys.platform != "linux" or os.geteuid() != 0: + raise ValueError("isolated managed Codex launch requires a Linux Core launcher with setuid authority") + import pwd + + name = os.environ.get("LOOPX_CODEX_OPERATION_WORKER_USER", "") + home_value = os.environ.get("LOOPX_CODEX_OPERATION_WORKER_HOME", "") + if not name or not home_value: + raise ValueError("isolated managed Codex requires both a Worker user and a private Worker home") + try: + worker = pwd.getpwnam(name) + except KeyError as exc: + raise ValueError("isolated managed Codex Worker user does not exist") from exc + if worker.pw_uid == 0 or worker.pw_gid == 0: + raise ValueError("isolated managed Codex requires an unprivileged Worker account") + home = Path(home_value) + _require_private_directory(home, worker.pw_uid) + _require_private_directory(home / ".codex", worker.pw_uid) + registry = registry_path.lstat() + if not stat.S_ISREG(registry.st_mode) or registry.st_uid != 0 or registry.st_mode & 0o022: + raise ValueError("isolated managed Codex requires a Core-owned physical registry file") + for core in (runtime_root, registry_path.parent): + _require_private_directory(core, os.geteuid()) + if home.is_relative_to(core) or core.is_relative_to(home): + raise ValueError("Worker home must be separate from LoopX authority directories") + for parent in core.parents: + entry = parent.stat() + sticky_system_directory = entry.st_uid == 0 and entry.st_mode & stat.S_ISVTX + if entry.st_uid == worker.pw_uid or (entry.st_mode & 0o022 and not sticky_system_directory): + raise ValueError("LoopX authority has a writable ancestor outside the Core account") + setpriv = shutil.which("setpriv", path=os.defpath) + if not setpriv: + raise ValueError("isolated managed Codex requires the system setpriv command") + return CodexWorkerIdentity(worker.pw_uid, worker.pw_gid, home, setpriv) diff --git a/loopx/control_plane/turn_driver/epoch_prefetch.py b/loopx/control_plane/turn_driver/epoch_prefetch.py index 29eeee3959..9caf784a38 100644 --- a/loopx/control_plane/turn_driver/epoch_prefetch.py +++ b/loopx/control_plane/turn_driver/epoch_prefetch.py @@ -14,6 +14,7 @@ import os from pathlib import Path import selectors +import shlex import signal import sqlite3 import subprocess @@ -1524,6 +1525,67 @@ def attach_epoch_metadata_to_journal( journal["quiet_turn"] = dict(quiet_meta) +_WORKSPACE_ONLY_PROBE_EXES = frozenset({"git", "ls", "pwd", "wc", "stat", "find"}) +_LOOPX_STATE_PROBE_SUBCOMMANDS = frozenset({"status", "doctor", "version"}) + + +def _parse_prefetch_argv(command: Any) -> list[str]: + if isinstance(command, str): + stripped = command.strip() + if not stripped: + return [] + try: + return shlex.split(stripped) + except ValueError: + return stripped.split() + if isinstance(command, (list, tuple)): + return [str(part) for part in command] + return [] + + +def _loopx_subcommand_tokens(argv: list[str], *, python_mode: bool) -> list[str]: + args = argv[1:] + if python_mode: + if len(args) < 2 or args[0] != "-m": + return [] + args = args[2:] + cursor = 0 + while cursor < len(args) and args[cursor].startswith("-"): + flag = args[cursor] + if flag in {"--registry", "--runtime-root", "--format"}: + cursor += 2 + continue + cursor += 1 + return args[cursor:] + + +def _command_binds_capture_source(command: Any, capture_path: str) -> bool: + """Return True when prefetch_command targets the compact capture or reads files directly.""" + argv = _parse_prefetch_argv(command) + if not argv: + return True + capture_name = Path(capture_path).name if capture_path else "" + if capture_path and any(capture_path in tok or (capture_name and capture_name in tok) for tok in argv): + return True + for idx in range(len(argv) - 1): + if argv[idx] == "quota" and argv[idx + 1] == "context-read": + return True + exe = Path(argv[0]).name + if exe in _WORKSPACE_ONLY_PROBE_EXES: + return False + if exe == "loopx" or exe.startswith("python"): + sub = _loopx_subcommand_tokens(argv, python_mode=exe.startswith("python")) + if not sub: + return True + if sub[:2] == ["quota", "context-read"]: + return True + if sub[0] in _LOOPX_STATE_PROBE_SUBCOMMANDS: + return False + if len(sub) >= 2 and (sub[0], sub[1]) in {("turn", "inspect"), ("todo", "list"), ("task-lease", "inspect")}: + return False + return True + + def resolve_codex_context_epoch_prefetch_hook( *, directory: str, @@ -1547,32 +1609,55 @@ def resolve_codex_context_epoch_prefetch_hook( ) if not (isinstance(cfg, Mapping) and cfg.get("enabled") is True): return None - source_ref = ( + recovery_ref = ( {"path": str(recovery["path"]), "sha256": str(recovery["sha256"])} if isinstance(recovery.get("path"), str) and isinstance(recovery.get("sha256"), str) else None ) baseline_bytes = cfg.get("baseline_bytes") - if baseline_bytes is None and source_ref is not None: + if baseline_bytes is None and recovery_ref is not None: try: - baseline_bytes = Path(source_ref["path"]).stat().st_size + baseline_bytes = Path(recovery_ref["path"]).stat().st_size except OSError: baseline_bytes = None - goal_label = str(state.get("goal_id") or event.get("goal_id") or "default") - agent_label = str(state.get("agent_id") or event.get("agent_id") or "default") - context_epoch = str(state.get("context_epoch") or "epoch-0") with lock_ctx(directory) as root: current_state = read_state_fn(root) + locked_cfg = ( + event.get("epoch_prefetch") + if isinstance(event.get("epoch_prefetch"), Mapping) + else current_state.get("epoch_prefetch_policy") + if isinstance(current_state.get("epoch_prefetch_policy"), Mapping) + else cfg + ) + if not (isinstance(locked_cfg, Mapping) and locked_cfg.get("enabled") is True): + return None + if baseline_bytes is None and isinstance(locked_cfg.get("baseline_bytes"), int): + baseline_bytes = locked_cfg.get("baseline_bytes") + explicit_source_ref = locked_cfg.get("source_ref") + if isinstance(explicit_source_ref, Mapping): + source_ref: dict[str, str] | None = { + "path": str(explicit_source_ref.get("path") or ""), + "sha256": str(explicit_source_ref.get("sha256") or ""), + } + elif recovery_ref is not None and _command_binds_capture_source( + locked_cfg.get("prefetch_command"), recovery_ref["path"], + ): + source_ref = recovery_ref + else: + source_ref = None + goal_label = str(current_state.get("goal_id") or state.get("goal_id") or event.get("goal_id") or "default") + agent_label = str(current_state.get("agent_id") or state.get("agent_id") or event.get("agent_id") or "default") + context_epoch = str(current_state.get("context_epoch") or state.get("context_epoch") or "epoch-0") receipt = resolve_or_execute_epoch_prefetch( - epoch_prefetch=cfg, + epoch_prefetch=locked_cfg, scope_key=f"codex_context:{goal_label}:{agent_label}", context_epoch=context_epoch, file_store_dir=root / "epoch_prefetch", sqlite_path=root / "epoch_prefetch.sqlite", - reclaimed_turns=int(event.get("reclaimed_turns") or cfg.get("reclaimed_turns") or 0), - dropped_failures=int(event.get("dropped_failures") or cfg.get("dropped_failures") or 0), - failure_facts=list(event.get("failure_facts") or cfg.get("failure_facts") or ()), - open_obligations=list(event.get("open_obligations") or cfg.get("open_obligations") or ()), + reclaimed_turns=int(event.get("reclaimed_turns") or locked_cfg.get("reclaimed_turns") or 0), + dropped_failures=int(event.get("dropped_failures") or locked_cfg.get("dropped_failures") or 0), + failure_facts=list(event.get("failure_facts") or locked_cfg.get("failure_facts") or ()), + open_obligations=list(event.get("open_obligations") or locked_cfg.get("open_obligations") or ()), source_ref=source_ref, baseline_bytes=baseline_bytes, cwd=event.get("cwd"), @@ -1585,6 +1670,8 @@ def resolve_codex_context_epoch_prefetch_hook( return None epoch_meta = { "schema_version": receipt["schema_version"], + "configured": True, + "superseded": False, "operator": receipt["operator"], "status": receipt["status"], "fallback_reason": receipt.get("fallback_reason"), diff --git a/loopx/control_plane/turn_driver/host_process_transport.py b/loopx/control_plane/turn_driver/host_process_transport.py index 0b1e79869d..9a2309a580 100644 --- a/loopx/control_plane/turn_driver/host_process_transport.py +++ b/loopx/control_plane/turn_driver/host_process_transport.py @@ -15,6 +15,7 @@ from ...file_lock import lock_holder_host_label from ..effect_runtime import _node_executable +from ..runtime.node_probe import node_typescript_flags from .host_bridge_transport import GuardedHostBridge # Keep Python's Windows executable/batch launcher compatibility. No timeout, @@ -347,6 +348,7 @@ def run_host_process( _node_executable(), "--no-warnings", "--experimental-strip-types", + *node_typescript_flags(), str(bridge), *launch_arguments, ], diff --git a/loopx/control_plane/work_items/attention_queue.py b/loopx/control_plane/work_items/attention_queue.py index 5f6ae9f88e..11b9fcc9e2 100644 --- a/loopx/control_plane/work_items/attention_queue.py +++ b/loopx/control_plane/work_items/attention_queue.py @@ -28,11 +28,11 @@ class AttentionQueueContext: latest_autonomous_replan_ack_for_projection: Callable[[list[dict[str, Any]] | None], dict[str, Any] | None] compact_control_plane_policy: Callable[[Any], dict[str, Any]] subagent_activity_for_goal: Callable[[dict[str, Any]], dict[str, Any] | None] - interface_budget_cadence_for_runs: Callable[[list[dict[str, Any]]], dict[str, Any]] + interface_budget_cadence_for_runs: Callable[[list[dict[str, Any]]], dict[str, Any] | None] active_state_projection_warning: Callable[[dict[str, Any], dict[str, Any] | None], dict[str, Any] | None] enrich_project_asset: Callable[..., None] project_asset_latest_validation: Callable[[dict[str, Any] | None], dict[str, Any] | None] - attach_active_state_project_asset_fields: Callable[..., None] + attach_active_state_project_asset_fields: Callable[..., object] sync_connected_attention_action_from_todos: Callable[[dict[str, Any]], None] quota_status: Callable[..., dict[str, Any]] quota_with_handoff_outcome_floor: Callable[..., dict[str, Any]] diff --git a/loopx/control_plane/work_items/interaction_contract.py b/loopx/control_plane/work_items/interaction_contract.py index 868773ab99..320a4b3cad 100644 --- a/loopx/control_plane/work_items/interaction_contract.py +++ b/loopx/control_plane/work_items/interaction_contract.py @@ -1043,7 +1043,8 @@ def _admitted_interaction_next_cli_actions( lifecycle_actor_args=lifecycle_actor_args, typed_quota_guard=typed_quota_guard, ) - if mode == "unsettled_host_turn_recovery": + recovery = _as_mapping(payload.get("unsettled_host_turn_recovery")) + if mode == "unsettled_host_turn_recovery" or recovery.get("repair") == "execution_loss_closeout": return recovery_cli_actions( payload, command_prefix=command_prefix, diff --git a/loopx/control_plane/work_items/unsettled_host_turn_contract.py b/loopx/control_plane/work_items/unsettled_host_turn_contract.py index a57a024381..f3a3dc25db 100644 --- a/loopx/control_plane/work_items/unsettled_host_turn_contract.py +++ b/loopx/control_plane/work_items/unsettled_host_turn_contract.py @@ -65,6 +65,30 @@ def recovery_cli_actions( " --progress-evidence-id ''"), "Read back the settled blocked closeout. Do not spend a slot or rebind this Turn; the next real host Turn selects independent work.", ] + if recovery.get("repair") == "execution_loss_closeout": + prior_turn = shlex.quote(str(recovery["prior_turn_instance_id"])) + scope = f"--goal-id {shlex.quote(goal_id)} --todo-id {shlex.quote(prior_todo_id)}" + goal_ref = payload.get("goal_ref") + instance = goal_ref.get("goal_instance_id") if isinstance(goal_ref, Mapping) else None + instance_arg = f" --goal-instance-id {shlex.quote(instance)}" if isinstance(instance, str) else "" + proof = recovery.get("execution_loss") + if not isinstance(proof, Mapping): + raise RuntimeError("execution-loss recovery is missing its fenced generation observation") + evidence = shlex.quote(f"lease-generation:{proof['original_prepared_epoch']}:{proof['current_lease_epoch']}") + closeout = ( + f"{command_prefix} refresh-state --execution-loss-closeout {scope}{instance_arg}{lifecycle_actor_args}" + f" --turn-instance-id {prior_turn} --classification execution_loss_closeout" + " --delivery-batch-scale single_surface --delivery-outcome outcome_gap --delivery-boundary semantic_closeout" + " --progress-result-class blocked --progress-blocker-id original-execution-fenced" + f" --progress-evidence-id {evidence} --task-lease-idempotency-key ''" + " --task-lease-expected-version '' --no-global-sync --suppress-external-sinks" + ) + return [ + f"{command_prefix} task-lease inspect {scope}", + "Use the current control-writer proof for the original Agent. When unavailable, recover ownership through the authorized Todo lifecycle before closing.", + f"{closeout} --dry-run", + "After the preview establishes a no-spend closeout, execute the same command without --dry-run and verify the original settlement. Resume fresh work only through its own guard.", + ] if recovery.get("repair") == "resume_prior_turn": prior_turn_id = str(recovery["prior_turn_instance_id"]) return [ diff --git a/loopx/entrypoint.py b/loopx/entrypoint.py index 9017b22404..3c2bf912b2 100644 --- a/loopx/entrypoint.py +++ b/loopx/entrypoint.py @@ -6,6 +6,7 @@ from pathlib import Path from . import __version__ +from .control_plane.runtime.node_probe import node_typescript_flags def pin_utf8_stdio() -> None: @@ -123,6 +124,7 @@ def _native_scheduler_followup_argv(raw_argv: list[str]) -> list[str] | None: node, "--no-warnings", "--experimental-strip-types", + *node_typescript_flags(), str(entry), *raw_argv, ] diff --git a/loopx/extensions/lark/goal_topic_runtime.py b/loopx/extensions/lark/goal_topic_runtime.py index 1adfa2b3aa..1396d6b816 100644 --- a/loopx/extensions/lark/goal_topic_runtime.py +++ b/loopx/extensions/lark/goal_topic_runtime.py @@ -9,10 +9,11 @@ import re import subprocess import threading -from collections.abc import Callable, Mapping +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence +from contextlib import AbstractContextManager, nullcontext from datetime import datetime, timezone from pathlib import Path -from typing import TYPE_CHECKING, Any, Literal, overload +from typing import TYPE_CHECKING, Literal, Protocol, overload from ...chat_manager import MANAGER_AGENT_OBJECTIVE from ...control_plane.collaboration import conversation_reply_context @@ -35,11 +36,11 @@ from .event_collector_runtime import EVENT_DIAGNOSTIC_PREFIX, EVENT_READY_PREFIX from .event_inbox import ( LarkTopicInput, - MESSAGE_ID_PATTERN, acknowledge_lark_event_inbox, ingest_lark_event_inbox, inspect_lark_event_inbox, ) +from .identity_shapes import LARK_MESSAGE_ID_PATTERN as MESSAGE_ID_PATTERN from .goal_channel_contracts import ( LarkTopicEventDecisionReason, bindings_for_goal, @@ -99,15 +100,23 @@ from ...chat_runtime import ChatRuntimeController -Answer = Callable[[Mapping[str, Any], str], str | Mapping[str, Any]] -SnapshotProvider = Callable[[], Mapping[str, Any]] -SimpleRunner = Callable[[list[str]], Mapping[str, Any]] -ProcessFactory = Callable[[list[str]], Any] -HealthSink = Callable[[Mapping[str, Any]], None] -ProposalDeliverer = Callable[ - [Mapping[str, Any], list[str]], Mapping[str, Any] -] -ReviewCallbackHandler = Callable[[Mapping[str, Any]], Mapping[str, Any]] +class _StreamProcess(Protocol): + @property + def stdout(self) -> Iterable[str] | None: ... + def poll(self) -> int | None: ... + def terminate(self) -> None: ... + def kill(self) -> None: ... + def wait(self, timeout: float | None = None) -> int: ... + + +Answer = Callable[[Mapping[str, object], str], str | Mapping[str, object]] +SnapshotProvider = Callable[[], Mapping[str, object]] +SimpleRunner = Callable[[Sequence[str]], Mapping[str, object]] +ProcessFactory = Callable[[list[str]], _StreamProcess] +HealthSink = Callable[[Mapping[str, object]], None] +ProposalDeliverer = Callable[[Mapping[str, object], list[str]], Mapping[str, object]] +ReviewCallbackHandler = Callable[[Mapping[str, object]], Mapping[str, object]] +ProviderRunner = Callable[..., object] EventLane = tuple[str, ...] CapturedEventLane = tuple[EventLane, dict[str, object] | None, TopicIntakeRoute | None] @@ -115,7 +124,7 @@ class LarkGoalTopicTurnFailed(RuntimeError): """A terminal runtime receipt, without copying arbitrary upstream details.""" - def __init__(self, error_code: str, effect_receipt: Mapping[str, Any]) -> None: + def __init__(self, error_code: str, effect_receipt: Mapping[str, object]) -> None: super().__init__("Lark Goal Topic turn did not complete") self.error_code = error_code self.effect_receipt = effect_receipt @@ -142,34 +151,98 @@ def __init__(self, error_code: str, effect_receipt: Mapping[str, Any]) -> None: _EVENT_EXIT_REASON = re.compile(r"\(reason: (limit|timeout|signal)\)$") -def _active_group_profile_configs(snapshot: Mapping[str, object]) -> dict[str, dict[str, str]]: - target_payload = snapshot.get("target_payload") - target_payload = target_payload if isinstance(target_payload, Mapping) else {} - binding_payloads = snapshot.get("binding_payloads") - binding_payloads = binding_payloads if isinstance(binding_payloads, Mapping) else {} - profiles: dict[str, dict[str, str]] = {} +def _as_mapping(value: object) -> Mapping[str, object]: + return value if isinstance(value, Mapping) else {} + + +def _as_dict(value: object) -> dict[str, object]: + return {str(k): v for k, v in value.items()} if isinstance(value, Mapping) else {} + + +def _str_field(mapping: Mapping[str, object], key: str, default: str = "") -> str: + return str(mapping.get(key) or default) + + +def _int_field(mapping: Mapping[str, object], key: str, default: int = 0) -> int: + value = mapping.get(key) + if isinstance(value, bool): + return int(value) if value else default + return int(value) if isinstance(value, (int, float, str)) and value != "" else default + + +def _str_list(value: object, *, skip_empty: bool = False) -> list[str]: + if not isinstance(value, Sequence) or isinstance(value, (str, bytes, bytearray)): + return [] + items = [str(item) for item in value] + return [item for item in items if item] if skip_empty else items + + +def _dict_list(value: object) -> list[dict[str, object]]: + if not isinstance(value, Sequence) or isinstance(value, (str, bytes, bytearray)): + return [] + return [_as_dict(item) for item in value if isinstance(item, Mapping)] + + +def _iter_enabled_bindings( + binding_payloads: Mapping[str, object], +) -> Iterator[tuple[str, Mapping[str, object], Mapping[str, object]]]: for goal_id, payload in binding_payloads.items(): if not isinstance(payload, Mapping): continue for binding in bindings_for_goal(payload, str(goal_id)): - if binding.get("enabled") is not True: - continue - target = goal_channel_target_for_name( - target_payload, - str(binding.get("target_ref") or ""), - ) - if target is None or target.get("enabled") is not True: - continue - identity = target.get("identity") - identity = identity if isinstance(identity, Mapping) else {} - profile = str(identity.get("sender_profile") or "").strip() - if not profile: - continue + if binding.get("enabled") is True: + yield str(goal_id), payload, binding + + +def _event_consume_args( + cli_bin: str, profile: str, *, timeout: str, max_events: str, quiet: bool = False, +) -> list[str]: + args = [ + cli_bin, "--profile", profile, "event", "consume", "im.message.receive_v1", + "--as", "bot", "--timeout", timeout, "--max-events", max_events, "--jq", _EVENT_PROJECTION, + ] + return [*args, "--quiet"] if quiet else args + + +def _empty_poll_result(status: str, *, ok: bool = True) -> dict[str, object]: + return {"ok": ok, "status": status, "event_count": 0, "replied_count": 0} + + +def _topic_error( + status: str, goal_id: object, *, inbox_config_ref: str | None = None, + source_acknowledged: bool | None = None, **extra: object, +) -> dict[str, object]: + payload: dict[str, object] = {"ok": False, "status": status, "goal_id": goal_id, **extra} + if inbox_config_ref is not None: + payload["inbox_config_ref"] = inbox_config_ref + if source_acknowledged is not None: + payload["source_acknowledged"] = source_acknowledged + return payload + + +def _persist_delivery(path: Path, state: dict[str, object], **updates: object) -> None: + if updates: + state.update(updates) + state["updated_at"] = datetime.now(timezone.utc).isoformat() + _write_manager_delivery(path, state) + + +def _active_group_profile_configs(snapshot: Mapping[str, object]) -> dict[str, dict[str, str]]: + target_payload = _as_mapping(snapshot.get("target_payload")) + binding_payloads = _as_mapping(snapshot.get("binding_payloads")) + profiles: dict[str, dict[str, str]] = {} + for _goal_id, _payload, binding in _iter_enabled_bindings(binding_payloads): + target = goal_channel_target_for_name(target_payload, _str_field(binding, "target_ref")) + if target is None or target.get("enabled") is not True: + continue + identity = _as_mapping(target.get("identity")) + profile = _str_field(identity, "sender_profile").strip() + if profile: profiles.setdefault( profile, { - "cli_bin": str(identity.get("cli_bin") or "lark-cli"), - "bot_app_id": str(identity.get("bot_app_id") or ""), + "cli_bin": _str_field(identity, "cli_bin", "lark-cli"), + "bot_app_id": _str_field(identity, "bot_app_id"), }, ) return profiles @@ -179,69 +252,58 @@ def _active_profile_configs(snapshot: Mapping[str, object]) -> dict[str, dict[st from .conversation_identity import identity_ref profiles = _active_group_profile_configs(snapshot) - private = snapshot.get("private_profiles") - for profile, config in (private.items() if isinstance(private, Mapping) else []): + for profile, raw_config in _as_mapping(snapshot.get("private_profiles")).items(): + config = dict(raw_config) if isinstance(raw_config, Mapping) else {} if profile in profiles: stored_app_id = profiles[profile].get("bot_app_id") app_id = stored_app_id or config.get("bot_app_id") if (config.get("audience", "owner") != "owner" or not app_id - or identity_ref(app_id) != config.get("provider_ref")): + or identity_ref(str(app_id)) != config.get("provider_ref")): raise ValueError("shared listener requires the same verified App and separate audiences") - profiles[profile] = {**profiles[profile], **dict(config)} + profiles[str(profile)] = {**profiles[profile], **config} if not stored_app_id: # Keep the pre-upgrade group lease until its original owner # exits. Verified private discovery supplies identity, not a # reason to start a second consumer under a new App key. - profiles[profile]["consumer_ref"] = hashlib.sha256(profile.encode("utf-8")).hexdigest()[:32] + profiles[str(profile)]["consumer_ref"] = hashlib.sha256(str(profile).encode("utf-8")).hexdigest()[:32] else: - profiles[profile] = dict(config) + profiles[str(profile)] = config return profiles -def _native_profile_event(snapshot: Mapping[str, Any], profile: str, event: Mapping[str, object]) -> bool: +def _native_profile_event(snapshot: Mapping[str, object], profile: str, event: Mapping[str, object]) -> bool: """Select a transport lane only; its original owner still admits the input. An owner-private binding may share one consumer with legacy group routes. A private rejection never falls through to a group authority or vice versa. """ - config = dict(snapshot.get("private_profiles") or {}).get(profile) + config = _as_mapping(snapshot.get("private_profiles")).get(profile) return isinstance(config, Mapping) and not ( config.get("audience", "owner") == "owner" and event.get("chat_type") == "group" and profile in _active_group_profile_configs(snapshot) ) -def _default_simple_runner(args: list[str]) -> Mapping[str, Any]: +def _default_simple_runner(args: Sequence[str]) -> Mapping[str, object]: try: completed = subprocess.run( - args, - capture_output=True, - text=True, encoding="utf-8", errors="replace", - check=False, - timeout=15, + args, capture_output=True, text=True, encoding="utf-8", errors="replace", + check=False, timeout=15, ) except (OSError, subprocess.SubprocessError): return {"returncode": 1, "stdout": "", "stderr": ""} - return { - "returncode": completed.returncode, - "stdout": completed.stdout, - "stderr": completed.stderr, - } + return {"returncode": completed.returncode, "stdout": completed.stdout, "stderr": completed.stderr} def _default_process_factory(args: list[str]) -> subprocess.Popen[str]: return subprocess.Popen( - args, - stdin=subprocess.DEVNULL, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - text=True, encoding="utf-8", errors="replace", - bufsize=1, + args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + text=True, encoding="utf-8", errors="replace", bufsize=1, ) def _target_for_profile_chat( - target_payload: Mapping[str, Any], + target_payload: Mapping[str, object], *, profile: str, chat_id: str, @@ -249,74 +311,53 @@ def _target_for_profile_chat( active_target_refs: set[str] | None = None, root_id: str = "", binding_payloads: Mapping[str, object] | None = None, -) -> tuple[str, Mapping[str, Any]] | None: - targets = target_payload.get("targets") - targets = targets if isinstance(targets, Mapping) else {} - candidates: list[tuple[str, Mapping[str, Any]]] = [] +) -> tuple[str, Mapping[str, object]] | None: + targets = _as_mapping(target_payload.get("targets")) + candidates: list[tuple[str, Mapping[str, object]]] = [] for target_ref, target in targets.items(): if active_target_refs is not None and str(target_ref) not in active_target_refs: continue if not isinstance(target, Mapping) or target.get("enabled") is not True: continue - channel = target.get("channel") - channel = channel if isinstance(channel, Mapping) else {} - identity = target.get("identity") - identity = identity if isinstance(identity, Mapping) else {} - same_app = ( - bool(bot_app_id) and str(identity.get("bot_app_id") or "") == bot_app_id - ) - if str(channel.get("chat_id") or "") == chat_id and ( - same_app or str(identity.get("sender_profile") or "") == profile + channel = _as_mapping(target.get("channel")) + identity = _as_mapping(target.get("identity")) + same_app = bool(bot_app_id) and _str_field(identity, "bot_app_id") == bot_app_id + if _str_field(channel, "chat_id") == chat_id and ( + same_app or _str_field(identity, "sender_profile") == profile ): candidates.append((str(target_ref), target)) if len(candidates) == 1: return candidates[0] - bindings = binding_payloads if isinstance(binding_payloads, Mapping) else {} + bindings = _as_mapping(binding_payloads) if root_id: - rooted = [ - candidate - for candidate in candidates - if root_id in _topic_roots_for_target(bindings, target_ref=candidate[0]) - ] + rooted = [c for c in candidates if root_id in _topic_roots_for_target(bindings, target_ref=c[0])] if len(rooted) == 1: return rooted[0] if rooted: return None - managers = [ - candidate - for candidate in candidates - if has_manager_binding(bindings, candidate[0]) - ] + managers = [c for c in candidates if has_manager_binding(bindings, c[0])] return managers[0] if len(managers) == 1 else None -def _topic_roots_for_target( - binding_payloads: Mapping[str, Any], *, target_ref: str -) -> list[str]: +def _topic_roots_for_target(binding_payloads: Mapping[str, object], *, target_ref: str) -> list[str]: roots: list[str] = [] for goal_id, payload in binding_payloads.items(): - if not isinstance(payload, Mapping): - continue - bindings = bindings_for_goal(payload, str(goal_id)) - roots.extend(_topic_roots_for_bindings(bindings, target_ref=target_ref)) + if isinstance(payload, Mapping): + roots.extend(_topic_roots_for_bindings(bindings_for_goal(payload, str(goal_id)), target_ref=target_ref)) return roots def _topic_roots_for_bindings( - bindings: list[Mapping[str, Any]], *, target_ref: str + bindings: Sequence[Mapping[str, object]], *, target_ref: str ) -> list[str]: roots: list[str] = [] for binding in bindings: - if binding.get("enabled") is not True: + if binding.get("enabled") is not True or _str_field(binding, "target_ref") != target_ref: continue - if str(binding.get("target_ref") or "") != target_ref: - continue - topic = binding.get("topic") - topic = topic if isinstance(topic, Mapping) else {} - channel = binding.get("channel") - channel = channel if isinstance(channel, Mapping) else {} root_id = str( - topic.get("root_message_id") or channel.get("pinned_message_id") or "" + _as_mapping(binding.get("topic")).get("root_message_id") + or _as_mapping(binding.get("channel")).get("pinned_message_id") + or "" ) if MESSAGE_ID_PATTERN.fullmatch(root_id): roots.append(root_id) @@ -324,23 +365,17 @@ def _topic_roots_for_bindings( def _binding_payloads_for_target( - binding_payloads: Mapping[str, Any], *, target_ref: str -) -> dict[str, Mapping[str, Any]]: - selected: dict[str, Mapping[str, Any]] = {} - for goal_id, payload in binding_payloads.items(): - if not isinstance(payload, Mapping): - continue - if any( - binding.get("enabled") is True - and str(binding.get("target_ref") or "") == target_ref - for binding in bindings_for_goal(payload, str(goal_id)) - ): - selected[str(goal_id)] = payload - return selected + binding_payloads: Mapping[str, object], *, target_ref: str +) -> dict[str, Mapping[str, object]]: + return { + goal_id: payload + for goal_id, payload, binding in _iter_enabled_bindings(binding_payloads) + if _str_field(binding, "target_ref") == target_ref + } -def _event_payloads(stdout: Any) -> list[Mapping[str, Any]]: - events: list[Mapping[str, Any]] = [] +def _event_payloads(stdout: object) -> list[Mapping[str, object]]: + events: list[Mapping[str, object]] = [] for line in str(stdout or "").splitlines(): try: payload = json.loads(line) @@ -356,59 +391,40 @@ def _event_payloads(stdout: Any) -> list[Mapping[str, Any]]: def _profile_event_route( *, profile: str, - snapshot: Mapping[str, Any], - event: Mapping[str, Any], + snapshot: Mapping[str, object], + event: Mapping[str, object], ) -> tuple[ - tuple[Mapping[str, Any], dict[str, Mapping[str, Any]], dict[str, Any]] | None, str + tuple[Mapping[str, object], dict[str, Mapping[str, object]], dict[str, object]] | None, str ]: """Select the existing profile/target/Topic scope; never grant turn authority.""" profile_config = _active_profile_configs(snapshot).get(profile) if profile_config is None: return None, "inactive" - target_payload = snapshot.get("target_payload") - target_payload = target_payload if isinstance(target_payload, Mapping) else {} - binding_payloads = snapshot.get("binding_payloads") - binding_payloads = binding_payloads if isinstance(binding_payloads, Mapping) else {} + target_payload = _as_mapping(snapshot.get("target_payload")) + binding_payloads = _as_mapping(snapshot.get("binding_payloads")) active_target_refs = { - str(binding.get("target_ref") or "") - for goal_id, payload in binding_payloads.items() - if isinstance(payload, Mapping) - for binding in bindings_for_goal(payload, str(goal_id)) - if binding.get("enabled") is True + _str_field(binding, "target_ref") for _, _, binding in _iter_enabled_bindings(binding_payloads) } - chat_id = str(event.get("chat_id") or "") target_match = _target_for_profile_chat( - target_payload, - profile=profile, - chat_id=chat_id, + target_payload, profile=profile, chat_id=_str_field(event, "chat_id"), bot_app_id=str(profile_config.get("bot_app_id") or ""), - active_target_refs=active_target_refs, - root_id=str(event.get("root_id") or ""), + active_target_refs=active_target_refs, root_id=_str_field(event, "root_id"), binding_payloads=binding_payloads, ) if target_match is None: return None, "target_unmatched" target_ref, _target = target_match routed_event = dict(event) - root_id = str(routed_event.get("root_id") or "") - if not MESSAGE_ID_PATTERN.fullmatch(root_id) and not has_manager_binding( - binding_payloads, target_ref - ): - candidate_roots = _topic_roots_for_target( - binding_payloads, - target_ref=target_ref, - ) + root_id = _str_field(routed_event, "root_id") + if not MESSAGE_ID_PATTERN.fullmatch(root_id) and not has_manager_binding(binding_payloads, target_ref): + candidate_roots = _topic_roots_for_target(binding_payloads, target_ref=target_ref) if len(candidate_roots) > 1: return None, "topic_context_ambiguous" if not candidate_roots: return None, "topic_context_missing" routed_event["root_id"] = candidate_roots[0] - return ( - target_payload, - _binding_payloads_for_target(binding_payloads, target_ref=target_ref), - routed_event, - ), "matched" + return (target_payload, _binding_payloads_for_target(binding_payloads, target_ref=target_ref), routed_event), "matched" @overload @@ -430,7 +446,7 @@ def _profile_event_lane( def _profile_event_lane( *, profile: str, - snapshot: Mapping[str, Any], + snapshot: Mapping[str, object], event: Mapping[str, object], runtime_root: str | Path, capture_mention: MentionCapture | None = None, @@ -445,14 +461,15 @@ def result( ) -> EventLane | CapturedEventLane: return (lane, capture, intake) if include_capture else lane - private_config = dict(snapshot.get("private_profiles") or {}).get(profile) + private_config = _as_mapping(snapshot.get("private_profiles")).get(profile) if isinstance(private_config, Mapping) and _native_profile_event(snapshot, profile, event): from .conversation_identity import lark_private_source try: - private_source = lark_private_source( - provider_ref=private_config["provider_ref"], event=event - ) + raw_provider_ref = private_config["provider_ref"] + if not isinstance(raw_provider_ref, str): + raise TypeError("provider_ref must be a string") + private_source = lark_private_source(provider_ref=raw_provider_ref, event=event) except (KeyError, TypeError, ValueError): pass # Malformed hints retain the conservative unmatched lane. else: @@ -460,20 +477,16 @@ def result( # Use the same App/chat/topic (or private sender) source shape for # scheduling, never a grant or a persisted Session selection. Core # still verifies the provider and acquires its fresh source fence. - return result(("private." + private_source["source_ref"],)) + return result(("private." + str(private_source["source_ref"]),)) - scoped, _status = _profile_event_route( - profile=profile, snapshot=snapshot, event=event - ) + scoped, _status = _profile_event_route(profile=profile, snapshot=snapshot, event=event) if scoped is not None: targets, bindings, routed_event = scoped decision = decide_lark_topic_event( - target_payload=targets, - binding_payloads=bindings, - event=routed_event, - runtime_root=runtime_root, + target_payload=targets, binding_payloads=bindings, + event=routed_event, runtime_root=runtime_root, ) - route = decision.get("route") or {} + route = _as_mapping(decision.get("route")) if route: if route.get("conversation_kind") == "manager": source = "manager." + _opaque_digest(route.get("app_ref"), event.get("chat_id")) @@ -501,66 +514,48 @@ def result( def poll_lark_goal_topic_profile_once( *, profile: str, - snapshot: Mapping[str, Any], + snapshot: Mapping[str, object], runtime_root: str | Path, answer: Answer, consume_runner: SimpleRunner = _default_simple_runner, - provider_runner: Any = subprocess.run, + provider_runner: ProviderRunner = subprocess.run, reply_runner: CommandRunner = _default_simple_runner, proposal_deliverer: ProposalDeliverer | None = None, private_admitter: Callable[[str, dict[str, object]], Mapping[str, object]] | None = None, mention_capture: Mapping[str, object] | None = None, live_turn_capture: Mapping[str, object] | None = None, -) -> dict[str, Any]: +) -> dict[str, object]: """Consume one bounded event batch for an App and reuse Inbox reply/ACK.""" - profile_configs = _active_profile_configs(snapshot) - profile_config = profile_configs.get(profile) + profile_config = _active_profile_configs(snapshot).get(profile) if profile_config is None: - return {"ok": True, "status": "inactive", "event_count": 0, "replied_count": 0} - cli_bin = str(profile_config["cli_bin"]) + return _empty_poll_result("inactive") result = consume_runner( - [ - cli_bin, - "--profile", - profile, - "event", - "consume", - "im.message.receive_v1", - "--as", - "bot", - "--timeout", - "5s", - "--max-events", - "50", - "--jq", - _EVENT_PROJECTION, - "--quiet", - ] + _event_consume_args(str(profile_config["cli_bin"]), profile, timeout="5s", max_events="50", quiet=True) ) - if int(result.get("returncode") or 0) != 0: - return { - "ok": False, - "status": "consume_failed", - "event_count": 0, - "replied_count": 0, - } + if _int_field(result, "returncode") != 0: + return _empty_poll_result("consume_failed", ok=False) events = _event_payloads(result.get("stdout")) + raw_contexts = snapshot.get("goal_contexts") + goal_contexts = ( + {str(k): v for k, v in raw_contexts.items() if isinstance(v, Mapping)} + if isinstance(raw_contexts, Mapping) else {} + ) replied_count = 0 event_statuses: list[str] = [] event_reasons: list[str | None] = [] for event in events: if _native_profile_event(snapshot, profile, event): - private_result = private_admitter(profile, dict(event)) if private_admitter else {"status": "private_admission_unavailable"} - event_statuses.append(str(private_result.get("status") or "unknown")) + private_result = ( + private_admitter(profile, dict(event)) + if private_admitter + else {"status": "private_admission_unavailable"} + ) + event_statuses.append(_str_field(private_result, "status", "unknown")) event_reasons.append(None) continue - scoped, rejection = _profile_event_route( - profile=profile, - snapshot=snapshot, - event=event, - ) + scoped, rejection = _profile_event_route(profile=profile, snapshot=snapshot, event=event) if scoped is None: event_statuses.append(rejection) event_reasons.append(None) @@ -568,36 +563,22 @@ def poll_lark_goal_topic_profile_once( target_payload, binding_payloads, routed_event = scoped try: event_result = process_lark_goal_topic_event( - target_payload=target_payload, - binding_payloads=binding_payloads, - event=routed_event, - runtime_root=runtime_root, - goal_contexts=( - snapshot.get("goal_contexts") - if isinstance(snapshot.get("goal_contexts"), Mapping) - else {} - ), - answer=answer, - reply_runner=reply_runner, - provider_runner=provider_runner, - proposal_deliverer=proposal_deliverer, - mention_capture=mention_capture, + target_payload=target_payload, binding_payloads=binding_payloads, event=routed_event, + runtime_root=runtime_root, goal_contexts=goal_contexts, answer=answer, + reply_runner=reply_runner, provider_runner=provider_runner, + proposal_deliverer=proposal_deliverer, mention_capture=mention_capture, live_turn_capture=live_turn_capture, ) except Exception: event_statuses.append("processing_failed") event_reasons.append(None) continue - event_statuses.append(str(event_result.get("status") or "unknown")) - event_reasons.append(str(event_result.get("reason") or "") or None) + event_statuses.append(_str_field(event_result, "status", "unknown")) + event_reasons.append(_str_field(event_result, "reason") or None) replied_count += int(event_result.get("status") == "replied_and_acknowledged") return { - "ok": True, - "status": "polled", - "event_count": len(events), - "replied_count": replied_count, - "event_statuses": event_statuses, - "event_reasons": event_reasons, + "ok": True, "status": "polled", "event_count": len(events), "replied_count": replied_count, + "event_statuses": event_statuses, "event_reasons": event_reasons, } @@ -609,7 +590,7 @@ def stream_lark_goal_topic_profile( runtime_root: str | Path, answer: Answer, process_factory: ProcessFactory = _default_process_factory, - provider_runner: Any = subprocess.run, + provider_runner: ProviderRunner = subprocess.run, reply_runner: CommandRunner = _default_simple_runner, health_sink: HealthSink | None = None, proposal_deliverer: ProposalDeliverer | None = None, @@ -617,50 +598,22 @@ def stream_lark_goal_topic_profile( capture_mention: MentionCapture | None = None, review_callback_handler: ReviewCallbackHandler | None = None, callback_availability_sink: Callable[[TeamPlanReviewCallbackStream], None] | None = None, -) -> dict[str, Any]: +) -> dict[str, object]: """Keep one bounded long-lived CLI consumer attached between messages.""" snapshot = snapshot_provider() profile_config = _active_profile_configs(snapshot).get(profile) if profile_config is None: - return { - "ok": True, - "status": "inactive", - "event_count": 0, - "replied_count": 0, - } + return _empty_poll_result("inactive") cli_bin = str(profile_config["cli_bin"]) - process = process_factory( - [ - cli_bin, - "--profile", - profile, - "event", - "consume", - "im.message.receive_v1", - "--as", - "bot", - "--timeout", - "30m", - "--max-events", - "0", - "--jq", - _EVENT_PROJECTION, - ] - ) + process = process_factory(_event_consume_args(cli_bin, profile, timeout="30m", max_events="0")) callback_disconnected = threading.Event() callback_stream = ( start_team_plan_review_callback_stream( - snapshot=snapshot, - profile=profile, - cli_bin=cli_bin, - process_factory=process_factory, - parent_stop=stop, - handler=review_callback_handler, - availability_sink=callback_availability_sink, + snapshot=snapshot, profile=profile, cli_bin=cli_bin, process_factory=process_factory, + parent_stop=stop, handler=review_callback_handler, availability_sink=callback_availability_sink, ) - if review_callback_handler is not None - else None + if review_callback_handler is not None else None ) if health_sink is not None: # Keep the connection non-ready until the @@ -669,13 +622,16 @@ def stream_lark_goal_topic_profile( watcher_done = threading.Event() configuration_removed = threading.Event() + def terminate_streams(*, include_callback: bool = True) -> None: + if process.poll() is None: + process.terminate() + if include_callback and callback_stream is not None: + callback_stream.terminate() + def stop_consumer() -> None: while not watcher_done.wait(1.0): if stop.is_set(): - if process.poll() is None: - process.terminate() - if callback_stream is not None: - callback_stream.terminate() + terminate_streams() return if dispatch.failed: # A worker can fail while stdout waits indefinitely for the @@ -685,19 +641,13 @@ def stop_consumer() -> None: try: with result_lock: if health_sink is not None: - health_sink( - {"status": "failed", "error_code": "lark_event_listener_failed"} - ) + health_sink({"status": "failed", "error_code": "lark_event_listener_failed"}) finally: - if process.poll() is None: - process.terminate() - if callback_stream is not None: - callback_stream.terminate() + terminate_streams() return if callback_stream is not None and callback_stream.disconnected(): callback_disconnected.set() - if process.poll() is None: - process.terminate() + terminate_streams(include_callback=False) return try: configured = profile in _active_profile_configs(snapshot_provider()) @@ -707,17 +657,10 @@ def stop_consumer() -> None: if not configured: configuration_removed.set() stop.set() - if process.poll() is None: - process.terminate() - if callback_stream is not None: - callback_stream.terminate() + terminate_streams() return - watcher = threading.Thread( - target=stop_consumer, - name=f"loopx-lark-stop-{profile}", - daemon=True, - ) + watcher = threading.Thread(target=stop_consumer, name=f"loopx-lark-stop-{profile}", daemon=True) event_count = 0 replied_count = 0 provider_ready = False @@ -726,7 +669,6 @@ def stop_consumer() -> None: def note_provider_ready() -> None: nonlocal provider_ready - with result_lock: if provider_ready: return @@ -734,15 +676,19 @@ def note_provider_ready() -> None: if health_sink is not None and not dispatch.failed: health_sink({"status": "listening", "error_code": None}) - def report_result(result: Mapping[str, Any]) -> None: + def report_result(result: Mapping[str, object]) -> None: nonlocal event_count, replied_count - - events = int(result.get("event_count") or 0) + events = _int_field(result, "event_count") if not events: return - replies = int(result.get("replied_count") or 0) - statuses = list(result.get("event_statuses") or []) - reasons = list(result.get("event_reasons") or []) + replies = _int_field(result, "replied_count") + statuses = _str_list(result.get("event_statuses")) + raw_reasons = result.get("event_reasons") + reasons = ( + list(raw_reasons) + if isinstance(raw_reasons, Sequence) and not isinstance(raw_reasons, (str, bytes)) + else [] + ) with result_lock: event_count += events replied_count += replies @@ -751,9 +697,8 @@ def report_result(result: Mapping[str, Any]) -> None: health_sink({ "status": "failed" if failed else "listening" if provider_ready else "starting", "error_code": "lark_event_listener_failed" if failed else None, - "event_count": events, - "replied_count": replies, - "last_event_status": str(statuses[-1]) if statuses else None, + "event_count": events, "replied_count": replies, + "last_event_status": statuses[-1] if statuses else None, "last_event_reason": str(reasons[-1]) if reasons and reasons[-1] else None, }) print(json.dumps({ @@ -764,28 +709,17 @@ def report_result(result: Mapping[str, Any]) -> None: def dispatch_event( event: Mapping[str, object], mention: Mapping[str, object] | None, - current_snapshot: Mapping[str, object], - *, live_turn_capture: Mapping[str, object] | None = None, + current_snapshot: Mapping[str, object], *, live_turn_capture: Mapping[str, object] | None = None, ) -> None: - message_id = str(event.get("message_id") or "") + message_id = _str_field(event, "message_id") record_event_timing(profile, message_id, "dispatch_started") record_event_timing(profile, message_id, "dispatch_snapshot_ready") result = poll_lark_goal_topic_profile_once( - profile=profile, - snapshot=current_snapshot, - runtime_root=runtime_root, - answer=answer, - consume_runner=lambda _args: { - "returncode": 0, - "stdout": json.dumps(event, ensure_ascii=False), - "stderr": "", - }, - provider_runner=provider_runner, - reply_runner=reply_runner, - proposal_deliverer=proposal_deliverer, - private_admitter=private_admitter, - mention_capture=mention, - live_turn_capture=live_turn_capture, + profile=profile, snapshot=current_snapshot, runtime_root=runtime_root, answer=answer, + consume_runner=lambda _args: {"returncode": 0, "stdout": json.dumps(event, ensure_ascii=False), "stderr": ""}, + provider_runner=provider_runner, reply_runner=reply_runner, + proposal_deliverer=proposal_deliverer, private_admitter=private_admitter, + mention_capture=mention, live_turn_capture=live_turn_capture, ) record_event_timing(profile, message_id, "dispatch_returned") report_result(result) @@ -800,18 +734,14 @@ def can_steer(state: Mapping[str, object]) -> bool: reserve_priority = can_steer(snapshot) root = Path(runtime_root).expanduser().resolve() - provider_ref = _opaque_digest(profile_config.get("bot_app_id") or profile) - intake = ProfileTopicIntake(root, provider_ref) + intake = ProfileTopicIntake(root, _opaque_digest(profile_config.get("bot_app_id") or profile)) def report_retained_input() -> None: - report_result({ - "event_count": 1, "replied_count": 0, - "event_statuses": ["already_captured"], "event_reasons": [None], - }) + report_result({"event_count": 1, "replied_count": 0, "event_statuses": ["already_captured"], "event_reasons": [None]}) - def matches_input(inbox_key: str, packet: LarkTopicInput, snapshot: Mapping[str, object]) -> bool: + def matches_input(inbox_key: str, packet: LarkTopicInput, current: Mapping[str, object]) -> bool: lane, _, route = _profile_event_lane( - profile=profile, snapshot=snapshot, event=packet["event"], + profile=profile, snapshot=current, event=packet["event"], runtime_root=root, include_capture=True, prepare_intake=True, ) if route is None: @@ -820,7 +750,7 @@ def matches_input(inbox_key: str, packet: LarkTopicInput, snapshot: Mapping[str, # Previously captured compatibility input still belongs to its Topic # even if another connection no longer reserves a steering worker. return ( - (can_steer(snapshot) or ingress_mode == IngressMode.DIRECT_SESSION.value) + (can_steer(current) or ingress_mode == IngressMode.DIRECT_SESSION.value) and route.inbox_key == inbox_key and route.digest == packet["route_ref"] and lane == packet["lane"] and ( @@ -850,22 +780,13 @@ def handle_event(line: str) -> None: dispatch_event(envelope["event"], envelope["mention_capture"], snapshot_provider()) dispatch = ProfileEventDispatch(handle_event, stop, reserve_priority=reserve_priority) - watcher.start() stream_failed = True try: - intake.restore( - dispatch, - lambda key, packet: matches_input(key, packet, snapshot), - ) + intake.restore(dispatch, lambda key, packet: matches_input(key, packet, snapshot)) stdout = process.stdout if stdout is None: - return { - "ok": False, - "status": "stream_failed", - "event_count": 0, - "replied_count": 0, - } + return _empty_poll_result("stream_failed", ok=False) for line in stdout: if stop.is_set(): break @@ -884,7 +805,7 @@ def handle_event(line: str) -> None: for event in _event_payloads(line): # Recovered local input alone does not attest provider readiness. note_provider_ready() - message_id = str(event.get("message_id") or "") + message_id = _str_field(event, "message_id") record_event_timing(profile, message_id, "received") if intake.retains(message_id): # A provider retry is the same source input even if the @@ -898,16 +819,12 @@ def handle_event(line: str) -> None: reserve_priority = can_steer(current_snapshot) dispatch.set_priority_reservation(reserve_priority) lane, mention_capture, intake_route = _profile_event_lane( - profile=profile, - snapshot=current_snapshot, - event=event, - runtime_root=runtime_root, + profile=profile, snapshot=current_snapshot, event=event, runtime_root=runtime_root, capture_mention=capture_mention if reserve_priority else None, - include_capture=True, - prepare_intake=reserve_priority, + include_capture=True, prepare_intake=reserve_priority, ) record_event_timing(profile, message_id, "lane_ready") - priority = bool((mention_capture or {}).get("target_turn_id")) + priority = bool(_as_mapping(mention_capture).get("target_turn_id")) if reserve_priority and intake_route is not None and not priority: live_turn_capture = None if (intake_route.route.get("ingress_mode") == "live_steering" @@ -917,8 +834,7 @@ def handle_event(line: str) -> None: if intake.capture( dispatch, intake_route, lane, event, mention_capture, lambda: _inbox_config( - runtime_root=root, route=intake_route.route, - target_payload=intake_route.targets, + runtime_root=root, route=intake_route.route, target_payload=intake_route.targets, )[0], live_turn_capture=live_turn_capture, ): @@ -950,38 +866,20 @@ def handle_event(line: str) -> None: # successfully with reason=signal (e.g. a Feishu/Lark domain mismatch). # Only our own stop or the requested bound is a planned stream ending. unexpected_exit = ( - provider_ready - and not stopped - and ( - callback_disconnected.is_set() - or returncode != 0 - or exit_reason not in {"limit", "timeout"} - ) + provider_ready and not stopped + and (callback_disconnected.is_set() or returncode != 0 or exit_reason not in {"limit", "timeout"}) ) return { - "ok": configuration_removed.is_set() - or stopped - or (returncode == 0 and provider_ready and not unexpected_exit), + "ok": configuration_removed.is_set() or stopped or (returncode == 0 and provider_ready and not unexpected_exit), **( - { - "error_code": ( - "lark_review_callback_source_disconnected" - if callback_disconnected.is_set() - else "lark_event_source_disconnected" - ) - } - if unexpected_exit - else {} + {"error_code": "lark_review_callback_source_disconnected" if callback_disconnected.is_set() else "lark_event_source_disconnected"} + if unexpected_exit else {} ), "status": ( - "configuration_removed" - if configuration_removed.is_set() - else "stopped" - if stopped - else "source_disconnected" - if unexpected_exit - else "stream_ended" - if provider_ready + "configuration_removed" if configuration_removed.is_set() + else "stopped" if stopped + else "source_disconnected" if unexpected_exit + else "stream_ended" if provider_ready else "stream_not_ready" ), "event_count": event_count, @@ -1064,53 +962,42 @@ def _steering_reply(route: Mapping[str, object], decision: Mapping[str, object]) def answer_lark_goal_topic( *, - route: Mapping[str, Any], + route: Mapping[str, object], text: str, work_dir: str | Path, objective: str, - runtime_controller: Any, -) -> str | Mapping[str, Any]: + runtime_controller: ChatRuntimeController, +) -> str | Mapping[str, object]: """Deliver one Topic message using its exact Agent ingress contract.""" - goal_id = str(route.get("goal_id") or "") - ingress_mode = str(route.get("ingress_mode") or "direct_session") - session_id = str(route.get("session_id") or "") + goal_id = _str_field(route, "goal_id") + ingress_mode = _str_field(route, "ingress_mode", "direct_session") + session_id = _str_field(route, "session_id") manager = route.get("conversation_kind") == "manager" - agent_id = manager_turn_executor(runtime_controller) if manager else str( - route.get("agent_id") or "codex" - ) - expected_channel = ( - str(route.get("manager_channel_id") or "") if manager else f"goal.{goal_id}" - ) + agent_id = manager_turn_executor(runtime_controller) if manager else _str_field(route, "agent_id", "codex") + expected_channel = _str_field(route, "manager_channel_id") if manager else f"goal.{goal_id}" if manager: objective = MANAGER_AGENT_OBJECTIVE resolved_work_dir = Path(work_dir).expanduser().resolve() reply_context = ( str(conversation_reply_context(dict(route))["context_text"]) - if route.get("parent_id") or route.get("thread_context") - else "" + if route.get("parent_id") or route.get("thread_context") else "" ) if manager: - message = manager_message( - text, route.get("context_materials"), reply_context=reply_context - ) + message = manager_message(text, route.get("context_materials"), reply_context=reply_context) else: message = ( "这是来自已绑定 Lark Goal Topic 的用户消息。请直接回答当前问题;" "任何 Goal、Todo 或其他持久状态修改只生成预览,等待用户在 LoopX 明确确认后应用。" + ("\n\n" + reply_context if reply_context else "") - + "\n\n用户消息:" - + str(text or "").strip() + + "\n\n用户消息:" + str(text or "").strip() ) - client_turn_id = "lark." + _opaque_digest( - route.get("message_id"), - route.get("topic_root_message_id"), - ) + client_turn_id = "lark." + _opaque_digest(route.get("message_id"), route.get("topic_root_message_id")) native_mention = route.get("native_mention") is True if native_mention: from ...capabilities.native_chat.queued_admission import deliver_native_mention - capture = route.get("mention_capture") - capture = capture if isinstance(capture, Mapping) else capture_topic_mention(route, runtime_controller) + raw_capture = route.get("mention_capture") + capture = raw_capture if isinstance(raw_capture, Mapping) else capture_topic_mention(route, runtime_controller) current = _bound_topic_session(route, runtime_controller) binding_matches = ( current is not None and capture.get("binding_matches") is True @@ -1122,7 +1009,7 @@ def answer_lark_goal_topic( from ...chat_manager_context import manager_authorization_scope_is_current binding_matches = manager_authorization_scope_is_current( - runtime_controller.registry_path, runtime_controller.manager_scope_resolver, current, + runtime_controller.registry_path, runtime_controller.manager_scope_resolver, dict(current), current.get("manager_authorization_scope_id"), runtime_root=runtime_controller.coordination_runtime_root, ) @@ -1151,22 +1038,18 @@ def answer_lark_goal_topic( if _bound_topic_session(route, runtime_controller) is None: if manager and manager_session_requires_executor_rebind( runtime_controller.store.load_session(session_id), - expected_channel=expected_channel, - agent_id=agent_id, + expected_channel=expected_channel, agent_id=agent_id, ): - raise LarkGoalTopicTurnFailed( - "manager_channel_executor_rebind_required", - _session_turn_effect(route), - ) + raise LarkGoalTopicTurnFailed("manager_channel_executor_rebind_required", _session_turn_effect(route)) raise RuntimeError("bound Agent session is unavailable or no longer matches") if ingress_mode == "live_steering": - capture = route.get("live_turn_capture") - if isinstance(capture, Mapping): - if (capture.get("binding_matches") is not True - or capture.get("session_id") != session_id - or capture.get("connection_id") != route.get("connection_id")): + live_capture = route.get("live_turn_capture") + if isinstance(live_capture, Mapping): + if (live_capture.get("binding_matches") is not True + or live_capture.get("session_id") != session_id + or live_capture.get("connection_id") != route.get("connection_id")): return _steering_reply(route, {"action": "reject", "error_code": "live_steering_session_not_attached"}) - target_turn_id = capture.get("target_turn_id") + target_turn_id = live_capture.get("target_turn_id") if not isinstance(target_turn_id, str) or not target_turn_id: return _steering_reply(route, {"action": "reject", "error_code": "live_steering_requires_active_turn"}) try: @@ -1192,114 +1075,66 @@ def answer_lark_goal_topic( session_id=session_id, client_ingress_id=client_turn_id, message=message, ) else: - if ( - manager - and route.get("source_sender_id") - and hasattr(runtime_controller.store, "root") - ): + if manager and route.get("source_sender_id") and hasattr(runtime_controller.store, "root"): from ...capabilities.manager_context import register_ingress register_ingress( - runtime_controller.store.root.parent, - session_id=session_id, - client_turn_id=client_turn_id, - channel=expected_channel, - sender_id=str(route["source_sender_id"]), - message=message, + runtime_controller.store.root.parent, session_id=session_id, + client_turn_id=client_turn_id, channel=expected_channel, + sender_id=str(route["source_sender_id"]), message=message, source_id="lark:" + str(route["message_id"]), source_message=( - (reply_context + "\n\nUser message:\n" if reply_context else "") - + str(text or "").strip() + (reply_context + "\n\nUser message:\n" if reply_context else "") + str(text or "").strip() ), ) turn, _created = runtime_controller.enqueue_turn( - session_id=session_id, - client_turn_id=client_turn_id, - message=message, - work_dir=resolved_work_dir, - objective=str(objective or goal_id), - origin="lark", + session_id=session_id, client_turn_id=client_turn_id, message=message, + work_dir=resolved_work_dir, objective=str(objective or goal_id), origin="lark", ) if native_mention: - runtime_controller.store.update_ingress_receipt( - session_id, client_turn_id, status="delivered", - ) + runtime_controller.store.update_ingress_receipt(session_id, client_turn_id, status="delivered") else: # Compatibility path for bindings created before the three ingress modes. channel_id = "lark." + _opaque_digest( - route.get("app_ref"), - route.get("target_ref"), - route.get("topic_root_message_id"), + route.get("app_ref"), route.get("target_ref"), route.get("topic_root_message_id"), ) session, _resumed = runtime_controller.open_session( - goal_id=goal_id, - agent_id=agent_id, - work_dir=resolved_work_dir, - objective=str(objective or goal_id), - mode="resume_latest", - channel_id=channel_id, - agent_goal_id=goal_id, + goal_id=goal_id, agent_id=agent_id, work_dir=resolved_work_dir, + objective=str(objective or goal_id), mode="resume_latest", + channel_id=channel_id, agent_goal_id=goal_id, ) session_id = str(session["session_id"]) turn, _created = runtime_controller.submit_turn( - session_id=session_id, - client_turn_id=client_turn_id, - message=message, - work_dir=resolved_work_dir, - objective=str(objective or goal_id), + session_id=session_id, client_turn_id=client_turn_id, message=message, + work_dir=resolved_work_dir, objective=str(objective or goal_id), ) - completed = runtime_controller.wait_for_turn( - session_id=session_id, - turn_id=str(turn["turn_id"]), - ) + completed = runtime_controller.wait_for_turn(session_id=session_id, turn_id=str(turn["turn_id"])) if completed.get("status") != "completed": if completed.get("status") not in {"failed", "timed_out", "interrupted"}: raise RuntimeError("Lark Goal Topic turn has no terminal receipt") - raise LarkGoalTopicTurnFailed( - str(completed.get("error_code") or ""), - _session_turn_effect(route), - ) + raise LarkGoalTopicTurnFailed(str(completed.get("error_code") or ""), _session_turn_effect(route)) response = completed.get("response") - reply_text = ( - str(response.get("message") or "") if isinstance(response, Mapping) else "" - ) + reply_text = _str_field(response, "message") if isinstance(response, Mapping) else "" if not reply_text.strip(): raise RuntimeError("Lark Goal Topic turn returned no message") if not manager: return reply_text - proposal_ids = proposal_ids_after_turn( - runtime_controller, - session_id=session_id, - turn_id=str(turn["turn_id"]), - ) - if proposal_ids: - return { - "response_text": reply_text, - "proposal_ids": proposal_ids, - } - return reply_text + proposal_ids = proposal_ids_after_turn(runtime_controller, session_id=session_id, turn_id=str(turn["turn_id"])) + return {"response_text": reply_text, "proposal_ids": proposal_ids} if proposal_ids else reply_text def _inbox_config( - *, - runtime_root: Path, - route: Mapping[str, Any], - target_payload: Mapping[str, Any], + *, runtime_root: Path, route: Mapping[str, object], target_payload: Mapping[str, object], ) -> tuple[Path, str]: - target_ref = str(route.get("target_ref") or "") - target = goal_channel_target_for_name(target_payload, target_ref) + target = goal_channel_target_for_name(target_payload, _str_field(route, "target_ref")) if target is None: raise ValueError("the routed Lark target is unavailable") - channel = ( - target.get("channel") if isinstance(target.get("channel"), Mapping) else {} - ) - identity = ( - target.get("identity") if isinstance(target.get("identity"), Mapping) else {} - ) - chat_id = str(channel.get("chat_id") or "") - profile = str(route.get("app_ref") or "") - bot_display_name = str(identity.get("bot_display_name") or profile) - digest = topic_inbox_key(profile, chat_id, str(route.get("topic_root_message_id") or "")) + channel = _as_mapping(target.get("channel")) + identity = _as_mapping(target.get("identity")) + chat_id = _str_field(channel, "chat_id") + profile = _str_field(route, "app_ref") + topic_root = _str_field(route, "topic_root_message_id") + digest = topic_inbox_key(profile, chat_id, topic_root) config_ref = f".loopx/config/lark-goal-topics/{digest}.json" config_path = runtime_root / config_ref payload = { @@ -1307,7 +1142,7 @@ def _inbox_config( "enabled": True, "inbox_dir": f".loopx/inbox/lark-goal-topics/{digest}", "capture_scope": "configured_chat_all", - "topic_root_message_id": str(route.get("topic_root_message_id") or ""), + "topic_root_message_id": topic_root, "material_review": { "enabled": route.get("conversation_kind") == "manager", "drain_limit": MANAGER_CONTEXT_ITEM_LIMIT, @@ -1316,15 +1151,13 @@ def _inbox_config( "enabled": True, "sender_profile": profile, "sender_identity": "bot", - "bot_display_name": bot_display_name, - "bot_app_id": str(identity.get("bot_app_id") or ""), - "bot_open_id": str(identity.get("bot_open_id") or ""), + "bot_display_name": _str_field(identity, "bot_display_name", profile), + "bot_app_id": _str_field(identity, "bot_app_id"), + "bot_open_id": _str_field(identity, "bot_open_id"), "chat_id": chat_id, "placement_policy": "source_context", "editorial_style": "bullet_points_preferred", - "received_reaction_policy": ( - "retain" if route.get("conversation_kind") == "manager" else "transient" - ), + "received_reaction_policy": "retain" if route.get("conversation_kind") == "manager" else "transient", }, } config_path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) @@ -1334,18 +1167,18 @@ def _inbox_config( def process_lark_goal_topic_event( *, - target_payload: Mapping[str, Any], - binding_payloads: Mapping[str, Mapping[str, Any]], - event: Mapping[str, Any], + target_payload: Mapping[str, object], + binding_payloads: Mapping[str, Mapping[str, object]], + event: Mapping[str, object], runtime_root: str | Path, - goal_contexts: Mapping[str, Mapping[str, Any]] | None = None, + goal_contexts: Mapping[str, Mapping[str, object]] | None = None, answer: Answer, reply_runner: CommandRunner, - provider_runner: Any | None = None, + provider_runner: ProviderRunner | None = None, proposal_deliverer: ProposalDeliverer | None = None, mention_capture: Mapping[str, object] | None = None, live_turn_capture: Mapping[str, object] | None = None, -) -> dict[str, Any]: +) -> dict[str, object]: """Single-flight a manager or live mention through ingress, reply and ACK. The inbox and delivery receipt make sequential retries safe, but two @@ -1355,21 +1188,20 @@ def process_lark_goal_topic_event( """ decision = decide_lark_topic_event( - target_payload=target_payload, - binding_payloads=binding_payloads, - event=event, - runtime_root=runtime_root, + target_payload=target_payload, binding_payloads=binding_payloads, + event=event, runtime_root=runtime_root, ) - route = decision.get("route") - native_mention = isinstance(route, Mapping) and _route_native_mention(event, route, target_payload) + raw_route = decision.get("route") + route = dict(raw_route) if isinstance(raw_route, Mapping) else None + native_mention = route is not None and _route_native_mention(event, route, target_payload) if mention_capture is not None and not native_mention: return {"ok": True, "status": "ignored", "reason": "mention_binding_changed"} if live_turn_capture is not None: - if not isinstance(route, Mapping) or route.get("ingress_mode") != "live_steering" or native_mention: + if route is None or route.get("ingress_mode") != "live_steering" or native_mention: return {"ok": True, "status": "ignored", "reason": LarkTopicEventDecisionReason.BINDING_UNAVAILABLE.value} route = {**route, "live_turn_capture": live_turn_capture} decision = {**decision, "route": route} - if native_mention: + if route is not None and native_mention: route = { **route, "native_mention": True, @@ -1377,186 +1209,121 @@ def process_lark_goal_topic_event( "mention_capture": mention_capture, } decision = {**decision, "route": route} - if isinstance(route, Mapping) and ( - native_mention or (route.get("conversation_kind") == "manager" - and route.get("authority_mode") == ManagerAuthorityMode.TURN_AUTHORIZED.value) + lock: AbstractContextManager[object] = nullcontext() + if route is not None and ( + native_mention or ( + route.get("conversation_kind") == "manager" + and route.get("authority_mode") == ManagerAuthorityMode.TURN_AUTHORIZED.value + ) ): - message_id = str(route.get("message_id") or "") + message_id = _str_field(route, "message_id") if not MESSAGE_ID_PATTERN.fullmatch(message_id): raise ValueError("manager route has an invalid message id") lock_dir = Path(runtime_root).expanduser().resolve() / ".loopx/locks/lark-manager" lock_dir.mkdir(parents=True, exist_ok=True, mode=0o700) os.chmod(lock_dir, 0o700) - with exclusive_file_lock( - lock_dir / message_id, - timeout_seconds=960, - operation="lark_manager_message", - ): - return _process_lark_goal_topic_event( - target_payload=target_payload, - event=event, - runtime_root=runtime_root, - goal_contexts=goal_contexts, - answer=answer, - reply_runner=reply_runner, - provider_runner=provider_runner, - proposal_deliverer=proposal_deliverer, - decision=decision, - ) - return _process_lark_goal_topic_event( - target_payload=target_payload, - event=event, - runtime_root=runtime_root, - goal_contexts=goal_contexts, - answer=answer, - reply_runner=reply_runner, - provider_runner=provider_runner, - proposal_deliverer=proposal_deliverer, - decision=decision, - ) + lock = exclusive_file_lock(lock_dir / message_id, timeout_seconds=960, operation="lark_manager_message") + with lock: + return _process_lark_goal_topic_event( + target_payload=target_payload, event=event, runtime_root=runtime_root, + goal_contexts=goal_contexts, answer=answer, reply_runner=reply_runner, + provider_runner=provider_runner, proposal_deliverer=proposal_deliverer, decision=decision, + ) def _process_lark_goal_topic_event( *, - target_payload: Mapping[str, Any], - event: Mapping[str, Any], + target_payload: Mapping[str, object], + event: Mapping[str, object], runtime_root: str | Path, - goal_contexts: Mapping[str, Mapping[str, Any]] | None, + goal_contexts: Mapping[str, Mapping[str, object]] | None, answer: Answer, reply_runner: CommandRunner, provider_runner: object | None, proposal_deliverer: ProposalDeliverer | None, - decision: Mapping[str, Any], + decision: Mapping[str, object], ) -> dict[str, object]: """Persist, answer, reply, and ACK the already-routed Topic event.""" - route = decision.get("route") - if route is None: + raw_route = decision.get("route") + if not isinstance(raw_route, Mapping): return { "ok": True, "status": "ignored", - "reason": str( - decision.get("reason") - or LarkTopicEventDecisionReason.BINDING_UNAVAILABLE.value - ), + "reason": _str_field(decision, "reason", LarkTopicEventDecisionReason.BINDING_UNAVAILABLE.value), } - ingress_mode = str(route.get("ingress_mode") or "direct_session") + route: dict[str, object] = dict(raw_route) + goal_id = route["goal_id"] + ingress_mode = _str_field(route, "ingress_mode", "direct_session") if ingress_mode == "async_inbox": - contexts = goal_contexts if isinstance(goal_contexts, Mapping) else {} - context = contexts.get(str(route.get("goal_id") or "")) - context = context if isinstance(context, Mapping) else {} - work_dir = str(context.get("work_dir") or "").strip() - config_ref = str(route.get("inbox_config_ref") or "").strip() + context = _as_mapping(_as_mapping(goal_contexts).get(str(goal_id or ""))) + work_dir = _str_field(context, "work_dir").strip() + config_ref = _str_field(route, "inbox_config_ref").strip() if not work_dir or not config_ref: - return { - "ok": False, - "status": "agent_inbox_unavailable", - "goal_id": route["goal_id"], - } + return _topic_error("agent_inbox_unavailable", goal_id) root = Path(work_dir).expanduser().resolve() config_path = Path(config_ref) else: root = Path(runtime_root).expanduser().resolve() - config_path, config_ref = _inbox_config( - runtime_root=root, - route=route, - target_payload=target_payload, - ) - canonical: dict[str, Any] = { + config_path, config_ref = _inbox_config(runtime_root=root, route=route, target_payload=target_payload) + canonical: dict[str, object] = { "schema_version": "lark_event_inbox_event_v0", "event_id": str(event.get("event_id") or event.get("message_id") or ""), - "message_id": str(event.get("message_id") or ""), - "create_time": str(event.get("create_time") or ""), - "content": str(event.get("content") or ""), - "sender_type": str(event.get("sender_type") or ""), - "sender_id": str(event.get("sender_id") or ""), - "root_id": str(event.get("root_id") or ""), - "thread_id": str(event.get("thread_id") or ""), + "message_id": _str_field(event, "message_id"), + "create_time": _str_field(event, "create_time"), + "content": _str_field(event, "content"), + "sender_type": _str_field(event, "sender_type"), + "sender_id": _str_field(event, "sender_id"), + "root_id": _str_field(event, "root_id"), + "thread_id": _str_field(event, "thread_id"), "thread_context": event.get("thread_context"), - "parent_id": str(event.get("parent_id") or ""), - "mentions": event.get("mentions") - if isinstance(event.get("mentions"), list) - else [], + "parent_id": _str_field(event, "parent_id"), + "mentions": event.get("mentions") if isinstance(event.get("mentions"), list) else [], "reply_context_verified": event.get("reply_context_verified") is True, "reply_to_bot": event.get("reply_to_bot") is True, "reply_context": event.get("reply_context"), } - ingest = ingest_lark_event_inbox( - project=root, - config_path=config_path, - events=[canonical], - execute=True, - ) + ingest = ingest_lark_event_inbox(project=root, config_path=config_path, events=[canonical], execute=True) manager = route.get("conversation_kind") == "manager" - authority_mode = ( - parse_manager_authority_mode(route.get("authority_mode")) if manager else None - ) + authority_mode = parse_manager_authority_mode(route.get("authority_mode")) if manager else None if manager and authority_mode is None: return invalid_manager_authority_result(route, inbox_config_ref=config_ref) retention = {"discarded_count": 0, "expired_count": 0, "overflow_count": 0} if manager: _, retention = manager_context_projection( - project=root, - config_path=config_path, - current_message_id=str(canonical.get("message_id") or ""), + project=root, config_path=config_path, current_message_id=_str_field(canonical, "message_id"), ) if authority_mode is ManagerAuthorityMode.CONTEXT_ONLY: return { "ok": True, - "status": ( - "context_only_captured" - if int(ingest.get("accepted_count") or 0) - else "context_only_already_captured" - ), - "reason": ( - normalize_lark_topic_event_rejection_reason(route.get("trigger_reason")) - or LarkTopicEventDecisionReason.NOT_ADDRESSED.value - ), - "goal_id": route["goal_id"], + "status": "context_only_captured" if _int_field(ingest, "accepted_count") else "context_only_already_captured", + "reason": normalize_lark_topic_event_rejection_reason(route.get("trigger_reason")) or LarkTopicEventDecisionReason.NOT_ADDRESSED.value, + "goal_id": goal_id, "inbox_config_ref": config_ref, "turn_authorized": False, "model_invoked": False, "external_write_performed": False, "context_retention_discarded_count": retention["discarded_count"], } - context_sync: Mapping[str, Any] | None = None - if route.get("conversation_kind") == "manager" and provider_runner is not None: + context_sync: Mapping[str, object] | None = None + if manager and provider_runner is not None: context_sync = sync_manager_context( - project=root, - config_path=config_path, - target_payload=target_payload, - target_ref=str(route.get("target_ref") or ""), - provider_runner=provider_runner, + project=root, config_path=config_path, target_payload=target_payload, + target_ref=_str_field(route, "target_ref"), provider_runner=provider_runner, ) message_id = str(route["message_id"]) - projection = inspect_lark_event_inbox( - project=root, config_path=config_path, limit=0 - ) + projection = inspect_lark_event_inbox(project=root, config_path=config_path, limit=0) if manager: projection, retention = manager_context_projection( - project=root, - config_path=config_path, - current_message_id=message_id, + project=root, config_path=config_path, current_message_id=message_id, ) - pending_ids = { - str(item.get("message_id") or "") - for item in projection.get("items", []) - if isinstance(item, Mapping) - } - if message_id not in pending_ids: - return { - "ok": True, - "status": "already_acknowledged", - "goal_id": route["goal_id"], - "inbox_config_ref": config_ref, - } + projection_items = _dict_list(projection.get("items")) + if message_id not in {_str_field(item, "message_id") for item in projection_items}: + return {"ok": True, "status": "already_acknowledged", "goal_id": goal_id, "inbox_config_ref": config_ref} if ingress_mode == "async_inbox": return { - "ok": True, - "status": "queued_for_agent", - "goal_id": route["goal_id"], - "agent_id": route.get("agent_id"), - "inbox_config_ref": config_ref, + "ok": True, "status": "queued_for_agent", "goal_id": goal_id, + "agent_id": route.get("agent_id"), "inbox_config_ref": config_ref, **({"reason": "async_inbox_requires_bound_session"} if route.get("native_mention") else {}), } # Receipt ACK is visible while the synchronous manager is reasoning. The @@ -1565,100 +1332,62 @@ def _process_lark_goal_topic_event( # A cosmetic reaction failure must not suppress the actual answer. received_reaction = None if manager: - profile = str(route.get("app_ref") or "") + profile = _str_field(route, "app_ref") try: received_reaction = ensure_lark_event_inbox_received_reaction( - project=root, - config_path=config_path, - event=canonical, - create_reaction=lambda mid, emoji: _create_reaction( - runner=reply_runner, - profile=profile, - message_id=mid, - emoji_type=emoji, - ), - delete_reaction=lambda mid, rid: _delete_reaction( - runner=reply_runner, - profile=profile, - message_id=mid, - reaction_id=rid, - ), + project=root, config_path=config_path, event=canonical, + create_reaction=lambda mid, emoji: _create_reaction(runner=reply_runner, profile=profile, message_id=mid, emoji_type=emoji), + delete_reaction=lambda mid, rid: _delete_reaction(runner=reply_runner, profile=profile, message_id=mid, reaction_id=rid), ) except (OSError, ValueError): received_reaction = {"ok": False, "status": "reaction_state_unavailable"} if not received_reaction.get("ok"): - logging.getLogger(__name__).warning( - "Lark manager received reaction was not verified" - ) + logging.getLogger(__name__).warning("Lark manager received reaction was not verified") # Sender provenance comes from the provider event, never the model response. # Context-only messages stay visibly non-authoritative inside the next # addressed manager Turn and never call the model on their own. - context_materials = ( - manager_context_materials(projection, current_message_id=message_id) - if manager - else [] - ) - captured_event = next( - item for item in projection["items"] if item.get("message_id") == message_id - ) + context_materials = manager_context_materials(projection, current_message_id=message_id) if manager else [] + captured_event = next(item for item in projection_items if item.get("message_id") == message_id) if route.get("native_mention") and ( not captured_event.get("target_mention_count") or captured_event.get("historical_context_only") or captured_event.get("sender_id") != canonical["sender_id"] ): - return {"ok": False, "status": "native_mention_proof_changed", "goal_id": route["goal_id"]} + return _topic_error("native_mention_proof_changed", goal_id) route = { **route, - "source_sender_id": str(canonical.get("sender_id") or ""), - "source_conversation_id": str(event.get("chat_id") or ""), + "source_sender_id": _str_field(canonical, "sender_id"), + "source_conversation_id": _str_field(event, "chat_id"), # The immutable captured event owns reply ancestry on delivery retries. "parent_id": captured_event.get("parent_id", ""), "reply_context": captured_event.get("reply_context"), "root_id": captured_event.get("root_id", ""), "thread_id": captured_event.get("thread_id", ""), "thread_context": captured_event.get("thread_context"), - **({"native_mention_fresh": int(ingest.get("accepted_count") or 0) > 0} if route.get("native_mention") else {}), + **({"native_mention_fresh": _int_field(ingest, "accepted_count") > 0} if route.get("native_mention") else {}), **({"context_materials": context_materials} if context_materials else {}), } delivery_path: Path | None = None - delivery_state: dict[str, Any] | None = None + delivery_state: dict[str, object] | None = None saved_response_reused = False if manager: try: - delivery_path, delivery_state = _load_manager_delivery( - project=root, config_path=config_path, event=canonical - ) + delivery_path, delivery_state = _load_manager_delivery(project=root, config_path=config_path, event=canonical) except (OSError, ValueError): - return { - "ok": False, - "status": "reply_delivery_state_invalid", - "goal_id": route["goal_id"], - "inbox_config_ref": config_ref, - "source_acknowledged": False, - } - if delivery_state is not None and delivery_state["status"] == "acknowledged": - return { - "ok": False, - "status": "reply_delivery_state_invalid", - "goal_id": route["goal_id"], - "inbox_config_ref": config_ref, - "source_acknowledged": False, - } + return _topic_error("reply_delivery_state_invalid", goal_id, inbox_config_ref=config_ref, source_acknowledged=False) + if delivery_state is not None and delivery_state.get("status") == "acknowledged": + return _topic_error("reply_delivery_state_invalid", goal_id, inbox_config_ref=config_ref, source_acknowledged=False) try: - route = restore_manager_context_route( - route, - projection, - current_message_id=message_id, - delivery_state=delivery_state, - ) + route = restore_manager_context_route(route, projection, current_message_id=message_id, delivery_state=delivery_state) except ValueError: - return unavailable_manager_context_result( - route, inbox_config_ref=config_ref - ) - if "context_materials" in route: - context_materials = route["context_materials"] + return unavailable_manager_context_result(route, inbox_config_ref=config_ref) + raw_materials = route.get("context_materials") + if isinstance(raw_materials, list): + context_materials = [ + {str(k): str(v) for k, v in item.items()} for item in raw_materials if isinstance(item, Mapping) + ] failure_code: str | None = None - effect_receipt: Mapping[str, Any] | None = None + effect_receipt: Mapping[str, object] | None = None proposal_ids: list[str] = [] answer_completed = False if delivery_state is not None: @@ -1670,7 +1399,7 @@ def _process_lark_goal_topic_event( effect_receipt = saved_effect if isinstance(saved_effect, Mapping) else None saved_failure = delivery_state.get("failure_code") failure_code = str(saved_failure) if saved_failure else None - proposal_ids = [str(value) for value in delivery_state.get("proposal_ids") or []] + proposal_ids = _str_list(delivery_state.get("proposal_ids")) else: try: answer_result = answer(route, str(canonical["content"])) @@ -1679,10 +1408,7 @@ def _process_lark_goal_topic_event( if not manager: raise failure_code, failure_text = _manager_failure_reply(exc) - answer_result = { - "response_text": failure_text, - "effect_receipt": exc.effect_receipt, - } + answer_result = {"response_text": failure_text, "effect_receipt": exc.effect_receipt} except Exception as exc: # A synchronous manager route must leave a user-visible, bounded # receipt even when the worker raises an untyped exception. The @@ -1690,70 +1416,49 @@ def _process_lark_goal_topic_event( # type is logged and the public reply uses the generic failure label. if not manager: raise - logging.getLogger(__name__).warning( - "Lark manager answer failed with %s", type(exc).__name__ - ) + logging.getLogger(__name__).warning("Lark manager answer failed with %s", type(exc).__name__) failure_code, failure_text = _manager_failure_reply(exc) - answer_result = { - "response_text": failure_text, - "effect_receipt": _session_turn_effect(route), - } + answer_result = {"response_text": failure_text, "effect_receipt": _session_turn_effect(route)} if isinstance(answer_result, Mapping): - reply_text = str(answer_result.get("response_text") or "").strip() + reply_text = _str_field(answer_result, "response_text").strip() candidate_receipt = answer_result.get("effect_receipt") - effect_receipt = ( - candidate_receipt if isinstance(candidate_receipt, Mapping) else None - ) - proposal_ids = [ - str(value) - for value in answer_result.get("proposal_ids") or [] - if str(value) - ] + effect_receipt = candidate_receipt if isinstance(candidate_receipt, Mapping) else None + proposal_ids = _str_list(answer_result.get("proposal_ids"), skip_empty=True) else: reply_text = str(answer_result or "").strip() content_format = "markdown" if manager else "text" - connector = route.get("connector") - connector = connector if isinstance(connector, Mapping) else None + raw_connector = route.get("connector") + connector = raw_connector if isinstance(raw_connector, Mapping) else None if not reply_text: answer_completed = False - if manager: - # Empty model output is a terminal, non-replayable failure for a - # manager request. Reply through the same inbox path so the - # source is ACKed only after provider verification. - failure_code = "answer_empty" - reply_text = ( - "已收到你的消息,但本次没有生成可发送的完整答复。" - "请求不会自动重放;请在 LoopX 管家会话查看状态或重新发起。" - ) - effect_receipt = effect_receipt or _session_turn_effect(route) - else: - return { - "ok": False, - "status": "answer_empty", - "goal_id": route["goal_id"], - "inbox_config_ref": config_ref, - } - rich_text_repairs: list[dict[str, Any]] = [] + if not manager: + return _topic_error("answer_empty", goal_id, inbox_config_ref=config_ref) + # Empty model output is a terminal, non-replayable failure for a + # manager request. Reply through the same inbox path so the + # source is ACKed only after provider verification. + failure_code = "answer_empty" + reply_text = ( + "已收到你的消息,但本次没有生成可发送的完整答复。" + "请求不会自动重放;请在 LoopX 管家会话查看状态或重新发起。" + ) + effect_receipt = effect_receipt or _session_turn_effect(route) + rich_text_repairs: list[dict[str, object]] = [] if manager: # The reader must not receive a one-line answer whose bullet list is # still escaped, nor raw braces left by an unresolved template. Repair # those defects before the first send: the strict validator keeps # owning unsafe markup, and a repaired markdown answer stays markdown # instead of degrading to plain text. - reply_text, rich_text_repairs = repair_manager_reply_text(reply_text) + reply_text, repairs = repair_manager_reply_text(reply_text) + rich_text_repairs = [dict(item) for item in repairs] reply_text = present_lark_conversation_text(reply_text) if manager and delivery_state is None: assert delivery_path is not None delivery_state = _pending_manager_delivery( - event=canonical, - text=reply_text, - content_format=content_format, - effect_receipt=effect_receipt, - failure_code=failure_code, - context_material_ids=[ - item["message_id"] for item in context_materials - ], + event=canonical, text=reply_text, content_format=content_format, + effect_receipt=effect_receipt, failure_code=failure_code, + context_material_ids=[item["message_id"] for item in context_materials], proposal_ids=proposal_ids, ) if rich_text_repairs: @@ -1761,55 +1466,32 @@ def _process_lark_goal_topic_event( try: _write_manager_delivery(delivery_path, delivery_state) except OSError: - return { - "ok": False, - "status": "reply_delivery_state_unavailable", - "goal_id": route["goal_id"], - "inbox_config_ref": config_ref, - "source_acknowledged": False, - } + return _topic_error("reply_delivery_state_unavailable", goal_id, inbox_config_ref=config_ref, source_acknowledged=False) if connector is not None: effect_decision = decide_external_event_ack( - event_id=canonical["event_id"], - effect_receipt=effect_receipt, + event_id=str(canonical["event_id"]), effect_receipt=effect_receipt, response_policy=ExternalResponsePolicy.NO_RESPONSE.value, ) if not effect_decision["effect_ready"]: - return { - "ok": False, - "status": "durable_effect_required", - "goal_id": route["goal_id"], - "inbox_config_ref": config_ref, - "ack_decision": effect_decision, - } + return _topic_error("durable_effect_required", goal_id, inbox_config_ref=config_ref, ack_decision=effect_decision) - if delivery_state is not None and delivery_state["status"] == "sent_verified": - reply = { + if delivery_state is not None and delivery_state.get("status") == "sent_verified": + reply: dict[str, object] = { "ok": True, "status": "sent_verified", "idempotency_key": delivery_state.get("reply_idempotency_key"), - "external_write_performed": delivery_state.get("external_write_performed") - is True, + "external_write_performed": delivery_state.get("external_write_performed") is True, "verification_performed": True, "reply_verified": True, } else: if delivery_state is not None: - delivery_state["attempt_count"] = ( - int(delivery_state.get("attempt_count") or 0) + 1 - ) - delivery_state["updated_at"] = datetime.now(timezone.utc).isoformat() assert delivery_path is not None - _write_manager_delivery(delivery_path, delivery_state) + _persist_delivery(delivery_path, delivery_state, attempt_count=_int_field(delivery_state, "attempt_count") + 1) try: reply = reply_lark_event_inbox( - project=root, - config_path=config_path, - message_id=message_id, - text=reply_text, - content_format=content_format, - execute=True, - runner=reply_runner, + project=root, config_path=config_path, message_id=message_id, text=reply_text, + content_format=content_format, execute=True, runner=reply_runner, # Ordinary answers use the provider capacity. The shared Inbox # sender splits oversized rich replies without a text downgrade. short_message_limit=None, @@ -1820,174 +1502,109 @@ def _process_lark_goal_topic_event( # Length is handled by the shared rich-post splitter. Invalid # presentation remains an explicit failure, never a text downgrade. assert delivery_state is not None and delivery_path is not None - delivery_state.update(last_delivery_status="format_unrepresentable", - updated_at=datetime.now(timezone.utc).isoformat()) - _write_manager_delivery(delivery_path, delivery_state) - return {"ok": False, "status": "reply_delivery_pending", - "reason": "reply_format_invalid", "format_degraded": False, - "goal_id": route["goal_id"], "inbox_config_ref": config_ref, - "source_acknowledged": False} + _persist_delivery(delivery_path, delivery_state, last_delivery_status="format_unrepresentable") + return _topic_error( + "reply_delivery_pending", goal_id, inbox_config_ref=config_ref, + source_acknowledged=False, reason="reply_format_invalid", format_degraded=False, + ) if manager and reply.get("content_format") in {"markdown", "text"}: content_format = str(reply["content_format"]) if manager and delivery_state is not None: delivery_state.update(manager_part_delivery_readback(reply)) if not reply.get("ok"): + reply_status = _str_field(reply, "status", "reply_failed") if manager: assert delivery_state is not None and delivery_path is not None - delivery_state.update( - last_delivery_status=str(reply.get("status") or "reply_failed"), - last_blocker=str(reply.get("blocker") or "reply_delivery_unverified"), - updated_at=datetime.now(timezone.utc).isoformat(), + _persist_delivery( + delivery_path, delivery_state, last_delivery_status=reply_status, + last_blocker=_str_field(reply, "blocker", "reply_delivery_unverified"), ) - _write_manager_delivery(delivery_path, delivery_state) - return { - "ok": False, - "status": ( - "reply_delivery_pending" - if manager - else str(reply.get("status") or "reply_failed") - ), + return _topic_error( + "reply_delivery_pending" if manager else reply_status, + goal_id, + inbox_config_ref=config_ref, + source_acknowledged=False if manager else None, + blocker=reply.get("blocker"), **( { - "delivery_status": str(reply.get("status") or "reply_failed"), - "format_degraded": bool( - delivery_state and delivery_state.get("format_degraded") - ), - "rich_text_repairs": list( - (delivery_state or {}).get("rich_text_repairs") or [] - ), + "delivery_status": reply_status, + "format_degraded": bool(delivery_state and delivery_state.get("format_degraded")), + "rich_text_repairs": _dict_list((delivery_state or {}).get("rich_text_repairs")), **manager_part_delivery_readback(reply), "delivery_notice_sent": reply.get("delivery_notice_sent") is True, } - if manager - else {} + if manager else {} ), - "goal_id": route["goal_id"], - "blocker": reply.get("blocker"), - "inbox_config_ref": config_ref, - **({"source_acknowledged": False} if manager else {}), - } + ) if manager: assert delivery_state is not None and delivery_path is not None - delivery_state.update( - status="sent_verified", - delivery_text=reply_text, - delivery_digest=_manager_delivery_text_digest(reply_text), - content_format=content_format, - reply_idempotency_key=reply.get("idempotency_key"), - external_write_performed=(reply.get("external_write_performed") is True), - verification_performed=(reply.get("verification_performed") is True), - reply_verified=(reply.get("reply_verified") is True), - last_delivery_status=str(reply.get("status") or "sent_verified"), - updated_at=datetime.now(timezone.utc).isoformat(), - ) try: - _write_manager_delivery(delivery_path, delivery_state) + _persist_delivery( + delivery_path, delivery_state, + status="sent_verified", delivery_text=reply_text, + delivery_digest=_manager_delivery_text_digest(reply_text), + content_format=content_format, + reply_idempotency_key=reply.get("idempotency_key"), + external_write_performed=(reply.get("external_write_performed") is True), + verification_performed=(reply.get("verification_performed") is True), + reply_verified=(reply.get("reply_verified") is True), + last_delivery_status=_str_field(reply, "status", "sent_verified"), + ) except OSError: - return { - "ok": False, - "status": "reply_delivery_receipt_unavailable", - "goal_id": route["goal_id"], - "inbox_config_ref": config_ref, - "source_acknowledged": False, - } + return _topic_error("reply_delivery_receipt_unavailable", goal_id, inbox_config_ref=config_ref, source_acknowledged=False) proposal_delivery_status = settle_team_plan_proposal_delivery( - delivery_state=delivery_state, - delivery_path=delivery_path, - route=route, - proposal_ids=proposal_ids, - proposal_deliverer=proposal_deliverer, + delivery_state=delivery_state, delivery_path=delivery_path, route=route, + proposal_ids=proposal_ids, proposal_deliverer=proposal_deliverer, ) if proposal_delivery_status is not None: - return { - "ok": False, - "status": proposal_delivery_status, - "goal_id": route["goal_id"], - "inbox_config_ref": config_ref, - "source_acknowledged": False, - } + return _topic_error(proposal_delivery_status, goal_id, inbox_config_ref=config_ref, source_acknowledged=False) if connector is not None: ack_decision = decide_external_event_ack( - event_id=canonical["event_id"], + event_id=str(canonical["event_id"]), effect_receipt=effect_receipt, - response_policy=str(connector.get("response_policy") or ""), + response_policy=_str_field(connector, "response_policy"), response_receipt=build_external_event_response_receipt( - event_id=canonical["event_id"], - external_write_performed=( - reply.get("external_write_performed") is True - ), + event_id=str(canonical["event_id"]), + external_write_performed=(reply.get("external_write_performed") is True), verification_performed=(reply.get("verification_performed") is True), response_verified=reply.get("reply_verified") is True, ), ) if not ack_decision["ack_allowed"]: - return { - "ok": False, - "status": str(ack_decision["reason"]), - "goal_id": route["goal_id"], - "inbox_config_ref": config_ref, - "ack_decision": ack_decision, - } + return _topic_error(str(ack_decision["reason"]), goal_id, inbox_config_ref=config_ref, ack_decision=ack_decision) context_settled_count = settle_manager_context( - project=root, - config_path=config_path, + project=root, config_path=config_path, materials=context_materials if answer_completed else [], ) - acknowledge_lark_event_inbox( - project=root, - config_path=config_path, - message_ids=[message_id], - execute=True, - ) + acknowledge_lark_event_inbox(project=root, config_path=config_path, message_ids=[message_id], execute=True) if manager: assert delivery_state is not None and delivery_path is not None - delivery_state.update( - status="acknowledged", - updated_at=datetime.now(timezone.utc).isoformat(), - ) delivery_state.pop("delivery_text", None) delivery_state.pop("effect_receipt", None) try: - _write_manager_delivery(delivery_path, delivery_state) + _persist_delivery(delivery_path, delivery_state, status="acknowledged") except OSError: - logging.getLogger(__name__).warning( - "Lark manager delivery receipt cleanup could not be persisted" - ) + logging.getLogger(__name__).warning("Lark manager delivery receipt cleanup could not be persisted") return { "ok": failure_code is None, "status": "processing_failed" if failure_code else "replied_and_acknowledged", - **( - { - "reason": failure_code, - "failure_reply_verified": True, - "source_acknowledged": True, - } - if failure_code - else {} - ), + **({"reason": failure_code, "failure_reply_verified": True, "source_acknowledged": True} if failure_code else {}), "received_reaction_status": (received_reaction or {}).get("status"), **( { "saved_response_reused": saved_response_reused, "format_degraded": bool(delivery_state.get("format_degraded")), - "rich_text_repairs": list( - delivery_state.get("rich_text_repairs") or [] - ), + "rich_text_repairs": _dict_list(delivery_state.get("rich_text_repairs")), **manager_part_delivery_readback(delivery_state), } - if manager and delivery_state is not None - else {} + if manager and delivery_state is not None else {} ), "context_material_count": len(context_materials), "context_settled_count": context_settled_count, "context_retention_discarded_count": retention["discarded_count"], - "context_sync_status": ( - str(context_sync.get("status") or "unknown") - if context_sync is not None - else "not_attempted" - ), - "goal_id": route["goal_id"], + "context_sync_status": _str_field(context_sync, "status", "unknown") if context_sync is not None else "not_attempted", + "goal_id": goal_id, "inbox_config_ref": config_ref, } diff --git a/loopx/extensions/openviking_semantic_preference/history_export.py b/loopx/extensions/openviking_semantic_preference/history_export.py index 2d3721dc36..40146c1f10 100644 --- a/loopx/extensions/openviking_semantic_preference/history_export.py +++ b/loopx/extensions/openviking_semantic_preference/history_export.py @@ -33,6 +33,7 @@ from ...control_plane.runtime.public_safety import public_safe_compact_text from ...entrypoint import pin_utf8_stdio from ...history import collect_history, validate_goal_id_path_segment +from ...paths import PATH_SEGMENT_UNSAFE_RE from ...public_safe_text import IDENTITY_TOKEN_PATTERN as _PUBLIC_GOAL_ID_RE HISTORY_EXPORT_SCHEMA_VERSION = "loopx_history_conclusion_export_v0" @@ -42,7 +43,6 @@ _CORPUS_DIR = "history-conclusions" _MANIFEST_FILE = ".loopx-history-conclusion-export.json" _MANIFEST_SCHEMA_VERSION = "loopx_history_conclusion_export_manifest_v0" -_SLUG_RE = re.compile(r"[^A-Za-z0-9._-]+") # Bounded ISO-8601-ish timestamp: digits, T/space, colon, dot, +/- and Z only. _TIMESTAMP_RE = re.compile(r"^[0-9]{4}-[0-9]{2}-[0-9]{2}[T ][0-9:.+\-]{1,20}Z?$") _SECRET_SHAPED_GOAL_ID_RE = re.compile( @@ -88,7 +88,7 @@ def _safe_generated_at(value: Any) -> str: def _slug(value: str) -> str: - slug = _SLUG_RE.sub("-", value).strip("-") + slug = PATH_SEGMENT_UNSAFE_RE.sub("-", value).strip("-") return slug[:80] or "run" diff --git a/loopx/extensions/turn_host.py b/loopx/extensions/turn_host.py index a9657128ec..ff0726c203 100644 --- a/loopx/extensions/turn_host.py +++ b/loopx/extensions/turn_host.py @@ -10,6 +10,7 @@ from pathlib import Path from ..control_plane.effect_runtime import _node_executable +from ..control_plane.runtime.node_probe import node_typescript_flags from ..control_plane.goals.goal_ref_validation import exact_goal_ref from ..control_plane.turn_driver.executor import validate_loopx_turn_host_result from ..control_plane.turn_driver.host_candidate import ( @@ -37,4 +38,11 @@ def supervised_stdio_command(command: Sequence[str]) -> list[str]: if not command or any(not isinstance(arg, str) or "\0" in arg for arg in command) or not command[0]: raise ValueError("a stdio command argv is required") bridge = Path(__file__).resolve().parents[1] / "control_plane" / "turn_driver" / "host_stdio_bridge.ts" - return [_node_executable(), "--no-warnings", "--experimental-strip-types", str(bridge), *command] + return [ + _node_executable(), + "--no-warnings", + "--experimental-strip-types", + *node_typescript_flags(), + str(bridge), + *command, + ] diff --git a/loopx/feedback.py b/loopx/feedback.py index 1b44e1339b..fbebb0742c 100644 --- a/loopx/feedback.py +++ b/loopx/feedback.py @@ -12,7 +12,6 @@ from pathlib import Path from .control_plane.runtime.time import chronology_key -from .history import append_run_index_record, load_index, load_registry from .paths import resolve_runtime_root from .public_safe_text import ( PRIVATE_TEXT_PATTERNS as SHARED_PRIVATE_TEXT_PATTERNS, @@ -27,10 +26,16 @@ "require_prose_state_write_allowed": "loopx.control_plane.coordination.legacy_writer_fence", "atomic_write_state_text": "loopx.control_plane.runtime.document_io", } +_LAZY_IMPORTS = { + **_MUTATION_ADAPTERS, + "append_run_index_record": "loopx.history", + "load_index": "loopx.history", + "load_registry": "loopx.history", +} def __getattr__(name: str) -> Any: - owner = _MUTATION_ADAPTERS.get(name) + owner = _LAZY_IMPORTS.get(name) if owner is None: raise AttributeError(f"module {__name__!r} has no attribute {name!r}") value = getattr(_import_module(owner), name) @@ -39,7 +44,7 @@ def __getattr__(name: str) -> Any: def __dir__() -> list[str]: - return sorted(set(globals()) | set(_MUTATION_ADAPTERS)) + return sorted(set(globals()) | set(_LAZY_IMPORTS)) def _mutation_adapter(name: str) -> Any: @@ -442,10 +447,10 @@ def append_human_reward( _mutation_adapter("atomic_write_state_text") actor = normalize_owner_controller_actor(actor_kind, required=not dry_run) validate_goal_id(goal_id) - registry = load_registry(registry_path) + registry = _mutation_adapter("load_registry")(registry_path) runtime_root = resolve_runtime_root(registry, runtime_root_override, registry_path=registry_path) index_path = runtime_root / "goals" / goal_id / "runs" / "index.jsonl" - runs, raw_count = load_index(index_path) + runs, raw_count = _mutation_adapter("load_index")(index_path) selected = select_run(runs, run_generated_at) missing_paths = [ @@ -519,7 +524,7 @@ def append_human_reward( ) state_text_to_write = planned if changed else None index_path.parent.mkdir(parents=True, exist_ok=True) - append_run_index_record(index_path, index_record) + _mutation_adapter("append_run_index_record")(index_path, index_record) if state_file_to_write and state_text_to_write is not None: try: _mutation_adapter("atomic_write_state_text")(state_file_to_write, state_text_to_write) @@ -652,4 +657,4 @@ def render_reward_markdown(payload: dict[str, Any]) -> str: # Keep the historical star-import surface, including the deferred adapters. -__all__ = [name for name in globals() if not name.startswith("_")] + list(_MUTATION_ADAPTERS) +__all__ = [name for name in globals() if not name.startswith("_")] + list(_LAZY_IMPORTS) diff --git a/loopx/history.py b/loopx/history.py index e863b93230..11bbc3fd85 100644 --- a/loopx/history.py +++ b/loopx/history.py @@ -1,11 +1,9 @@ from __future__ import annotations -from typing import Any, cast - import hashlib import json from contextlib import nullcontext -from collections.abc import Callable, Iterable, Mapping +from collections.abc import Callable, Iterable, Mapping, Sequence from dataclasses import dataclass from heapq import merge from itertools import chain, islice @@ -87,9 +85,86 @@ ) -def goal_registry_digest(goal: Mapping[str, Any]) -> str: +def _as_dict(value: object) -> dict[str, object]: + return {str(k): v for k, v in value.items()} if isinstance(value, Mapping) else {} + + +def _as_mapping(value: object) -> Mapping[str, object]: + return value if isinstance(value, Mapping) else {} + + +def _mapping_list(value: object) -> list[Mapping[str, object]]: + if not isinstance(value, Sequence) or isinstance(value, (str, bytes, bytearray)): + return [] + return [item for item in value if isinstance(item, Mapping)] + + +def _int_field(mapping: Mapping[str, object], key: str, default: int = 0) -> int: + value = mapping.get(key) + if isinstance(value, bool): + return int(value) if value else default + return int(value) if isinstance(value, (int, float, str)) and value != "" else default + + +def _normalized_activation(state: GoalActivationState | str | None) -> str | None: + return normalize_goal_activation_state(state).value if state is not None else None + + +def _goal_index_paths( + registry_path: Path, runtime_root_override: str | None, goal_id: str | None, +) -> tuple[dict[str, object], Path, list[tuple[str, Path]]]: + registry = load_registry(registry_path) + runtime_root = resolve_runtime_root(registry, runtime_root_override, registry_path=registry_path) + goal_ids = discover_goal_ids(runtime_root, registry, goal_id) + return registry, runtime_root, [ + (gid, runtime_root / "goals" / gid / "runs" / "index.jsonl") for gid in goal_ids + ] + + +def _index_command_payload( + registry_path: Path, runtime_root: Path, goal_id: str | None, + checked_goal_count: int, **extra: object, +) -> dict[str, object]: + return { + "ok": True, "registry": str(registry_path), "runtime_root": str(runtime_root), + "goal_filter": goal_id, "checked_goal_count": checked_goal_count, **extra, + } + + +def _group_index_lines( + lines: Iterable[str], +) -> tuple[int, dict[tuple[str, str, str], list[tuple[int, dict[str, object]]]]]: + raw_count = 0 + grouped: dict[tuple[str, str, str], list[tuple[int, dict[str, object]]]] = {} + for line_number, line in enumerate(lines, start=1): + if not line.strip(): + continue + raw_count += 1 + try: + item = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(item, dict): + grouped.setdefault(index_identity(item), []).append((line_number, item)) + return raw_count, grouped + + +def _markdown_report_lines( + title: str, payload: Mapping[str, object], header_fields: Sequence[tuple[str, object]], + *, columns: Sequence[str] = (), rows: Iterable[Sequence[object]] = (), +) -> list[str] | str: + if not payload.get("ok"): + return f"# {title}\n\n- ok: `False`\n- error: {payload.get('error')}" + lines = [f"# {title}", "", *(f"- {label}: `{value}`" for label, value in header_fields)] + if columns: + lines.extend(["", markdown_table_row(list(columns)), markdown_table_separator(len(columns))]) + lines.extend(markdown_table_row(list(row)) for row in rows) + return lines + + +def goal_registry_digest(goal: Mapping[str, object]) -> str: encoded = json.dumps( - goal, + goal if isinstance(goal, dict) else dict(goal), ensure_ascii=True, sort_keys=True, separators=(",", ":"), @@ -97,7 +172,7 @@ def goal_registry_digest(goal: Mapping[str, Any]) -> str: return f"sha256:{hashlib.sha256(encoded).hexdigest()}" -def host_worker_goal_observation_digest(goal: dict[str, Any], *, registry_path: Path) -> str | None: +def host_worker_goal_observation_digest(goal: Mapping[str, object], *, registry_path: Path) -> str | None: """Bind a driver observation to its actual source Goal, not sync metadata. A global row must still match the existing sanitizer/merge projection of @@ -110,7 +185,8 @@ def host_worker_goal_observation_digest(goal: dict[str, Any], *, registry_path: try: selected_registry = registry_path.expanduser().resolve() source_route = goal.get("source_registry") - source_registry, source_goal = selected_registry, goal + source_registry = selected_registry + source_goal: Mapping[str, object] = goal if source_route: if not isinstance(source_route, str) or not Path(source_route).is_absolute(): return None @@ -120,15 +196,16 @@ def host_worker_goal_observation_digest(goal: dict[str, Any], *, registry_path: if row.get("id") == goal.get("id")] if len(candidates) != 1: return None - source_goal = candidates[0] + candidate = candidates[0] # A global row has one owning source. Do not accept an # unverified chain of projections as that source. - if source_goal.get("source_registry"): + if candidate.get("source_registry"): return None expected = preserve_attention_override({}, sanitize_goal_for_global( - source_goal, source_registry=source_registry, synced_at="")) + candidate, source_registry=source_registry, synced_at="")) if preserve_attention_override({}, {**goal, "synced_at": ""}) != expected: return None + source_goal = candidate return goal_registry_digest({"source_registry": str(source_registry), "goal": source_goal}) except (OSError, RuntimeError, TypeError, ValueError): return None @@ -155,37 +232,27 @@ class RunHistoryAudit: goals: tuple[RunIndexAudit, ...] def matches( - self, - *, - registry_path: Path, - runtime_root: Path, - goal_id: str | None, - activation_state_filter: GoalActivationState | str | None, - include_runtime_goals: bool, + self, *, registry_path: Path, runtime_root: Path, goal_id: str | None, + activation_state_filter: GoalActivationState | str | None, include_runtime_goals: bool, ) -> bool: - normalized_activation = ( - normalize_goal_activation_state(activation_state_filter).value - if activation_state_filter is not None - else None - ) return ( self.registry_path == registry_path.expanduser().resolve() and self.runtime_root == runtime_root.expanduser().resolve() and self.goal_id == (str(goal_id or "").strip() or None) - and self.activation_state_filter == normalized_activation + and self.activation_state_filter == _normalized_activation(activation_state_filter) and self.include_runtime_goals is include_runtime_goals ) @dataclass(frozen=True, slots=True) class StatusHistoryCollection: - status_history: dict[str, Any] + status_history: dict[str, object] contract_audit: RunHistoryAudit @dataclass(frozen=True, slots=True) class RunIndexSnapshot: - records: list[dict[str, Any]] + records: list[dict[str, object]] raw_count: int digest: str | None invalid_count: int = 0 @@ -211,14 +278,18 @@ def reserve_unique_run_paths(runs_dir: Path, generated_at: str) -> tuple[Path, P def append_run_index_record( index_path: Path, - record: dict[str, Any], + record: Mapping[str, object], *, allow_nan: bool = True, ) -> None: """Append one readable JSONL record after any unterminated final row.""" encoded = ( - json.dumps(record, ensure_ascii=False, allow_nan=allow_nan).encode("utf-8") + json.dumps( + record if isinstance(record, dict) else dict(record), + ensure_ascii=False, + allow_nan=allow_nan, + ).encode("utf-8") + b"\n" ) with index_path.open("a+b") as handle: @@ -234,10 +305,10 @@ def write_reserved_run_artifacts( *, runs_dir: Path, generated_at: str, - record: dict[str, Any], - index_record: dict[str, Any], - payload: dict[str, Any], - render_markdown: Callable[[dict[str, Any]], str], + record: dict[str, object], + index_record: dict[str, object], + payload: dict[str, object], + render_markdown: Callable[[dict[str, object]], str], ) -> None: from .control_plane.quota.usage_collector import ingest_usage_into_run_record from .control_plane.work_items.delivery_history import ( @@ -260,8 +331,9 @@ def write_reserved_run_artifacts( payload["json_path"] = str(json_path) payload["markdown_path"] = str(markdown_path) payload["index_path"] = str(index_path) - if isinstance(record.get("usage"), dict): - payload["usage"] = dict(record["usage"]) + usage = record.get("usage") + if isinstance(usage, dict): + payload["usage"] = dict(usage) json_path.write_text( json.dumps(record, ensure_ascii=False, indent=2, allow_nan=False) + "\n", encoding="utf-8", @@ -272,7 +344,7 @@ def write_reserved_run_artifacts( def discover_goal_ids( runtime_root: Path, - registry: dict[str, Any], + registry: Mapping[str, object], requested_goal: str | None, *, include_runtime_goals: bool = True, @@ -280,14 +352,15 @@ def discover_goal_ids( if requested_goal: return [requested_goal] - ids = {str(goal.get("id")) for goal in registry_goals(registry)} + raw_registry = registry if isinstance(registry, dict) else dict(registry) + ids = {str(goal.get("id")) for goal in registry_goals(raw_registry)} goals_dir = runtime_root / "goals" if include_runtime_goals and goals_dir.exists(): ids.update(path.name for path in goals_dir.iterdir() if path.is_dir()) return sorted(ids) -def _indexed_artifact_exists(value: Any, *, artifact_root: Path | None) -> bool: +def _indexed_artifact_exists(value: object, *, artifact_root: Path | None) -> bool: text = str(value or "").strip() if not text: return False @@ -304,7 +377,7 @@ def _indexed_artifact_exists(value: Any, *, artifact_root: Path | None) -> bool: def _observe_run_artifacts( - records: Iterable[dict[str, Any]], *, artifact_root: Path | None, + records: Iterable[dict[str, object]], *, artifact_root: Path | None, ) -> None: """Fresh request-local observations, shared by full and selected reads.""" observed: dict[str, bool] = {} @@ -342,7 +415,7 @@ def load_index_snapshot( except FileNotFoundError: return RunIndexSnapshot(records=[], raw_count=0, digest=None) - records: list[dict[str, Any]] = [] + records: list[dict[str, object]] = [] positions: dict[tuple[str, str, str], int] = {} raw_count = 0 invalid_count = 0 @@ -376,11 +449,7 @@ def load_index_snapshot( invalid_count += 1 continue - key = ( - str(item.get("generated_at") or ""), - str(item.get("json_path") or ""), - str(item.get("markdown_path") or ""), - ) + key = index_identity(item) item = dict(item) # These are observations, never persisted index authority. item.pop("json_exists", None) @@ -405,12 +474,12 @@ def load_index( path: Path, *, artifact_root: Path | None = None, -) -> tuple[list[dict[str, Any]], int]: +) -> tuple[list[dict[str, object]], int]: snapshot = load_index_snapshot(path, artifact_root=artifact_root) return snapshot.records, snapshot.raw_count -def latest_status_run(runs: list[dict[str, Any]]) -> dict[str, Any] | None: +def latest_status_run(runs: Sequence[dict[str, object]]) -> dict[str, object] | None: for run in runs: if str(run.get("classification") or "") in STATUS_NEUTRAL_CLASSIFICATIONS: continue @@ -430,74 +499,53 @@ def collect_history( activation_state_filter: GoalActivationState | str | None = None, agent_lane_id: str | None = None, scoped_agent_id: str | None = None, - registry: dict[str, Any] | None = None, + registry: Mapping[str, object] | None = None, tolerate_undecodable: bool = False, -) -> dict[str, Any]: +) -> dict[str, object]: from .capabilities.machine_configuration.builtins import ( read_builtin_goal_machine_configuration, project_goal_with_builtin_machine_configuration, ) from .quota import goal_quota_with_spend_ledger, quota_with_unreadable_index_rows - if registry is None: - registry = load_registry(registry_path) + resolved_registry = ( + load_registry(registry_path) if registry is None + else (registry if isinstance(registry, dict) else dict(registry)) + ) machine_configuration = read_builtin_goal_machine_configuration(runtime_root) - registry_goal_rows = registry_goals(registry) - registry_goal_digests = { - str(goal.get("id")): goal_registry_digest(goal) - for goal in registry_goal_rows - } - registry_goal_meta = { - str(goal.get("id")): goal - for goal in registry_goal_rows - } + registry_goal_meta = {str(goal.get("id")): goal for goal in registry_goals(resolved_registry)} + registry_goal_digests = {gid: goal_registry_digest(goal) for gid, goal in registry_goal_meta.items()} goal_meta = { - str(goal.get("id")): project_goal_with_builtin_machine_configuration( - goal, machine_configuration - ) - for goal in registry_goal_rows + gid: project_goal_with_builtin_machine_configuration(goal, machine_configuration) + for gid, goal in registry_goal_meta.items() } activation_filter = ( normalize_goal_activation_state(activation_state_filter) - if activation_state_filter is not None - else None + if activation_state_filter is not None else None ) - goals: list[dict[str, Any]] = [] - recent_runs: list[dict[str, Any]] = [] + goals: list[dict[str, object]] = [] + recent_runs: list[dict[str, object]] = [] run_count = 0 recent_limit = max(0, limit) for current_goal_id in discover_goal_ids( - runtime_root, - registry, - goal_id, + runtime_root, resolved_registry, goal_id, include_runtime_goals=include_runtime_goals and activation_filter is None, ): registry_member = current_goal_id in goal_meta meta = goal_meta.get(current_goal_id) or {} - activation_state = ( - goal_activation_state(meta) - if registry_member - else GoalActivationState.ACTIVE - ) + activation_state = goal_activation_state(meta) if registry_member else GoalActivationState.ACTIVE if activation_filter is not None and activation_state is not activation_filter: continue index_path = runtime_root / "goals" / current_goal_id / "runs" / "index.jsonl" index_snapshot = load_index_snapshot( - index_path, - include_artifact_status=False, - tolerate_undecodable=tolerate_undecodable, + index_path, include_artifact_status=False, tolerate_undecodable=tolerate_undecodable, ) - runs = index_snapshot.records raw_count = index_snapshot.raw_count runs = [ - run - for _, run in sorted( - enumerate(runs), - key=lambda item: ( - *_chronology_key(item[1].get("generated_at")), - item[0], - ), + run for _, run in sorted( + enumerate(index_snapshot.records), + key=lambda item: (*_chronology_key(item[1].get("generated_at")), item[0]), reverse=True, ) ] @@ -510,25 +558,29 @@ def collect_history( if scoped_agent_id: runs = [run for run in goal_runs if run.get("agent_id") == scoped_agent_id] run_count += len(runs) - recent_runs = list( - islice( - merge( - recent_runs, - runs, - key=lambda item: _chronology_key(item.get("generated_at")), - reverse=True, - ), - recent_limit, - ) - ) + recent_runs = list(islice( + merge(recent_runs, runs, key=lambda item: _chronology_key(item.get("generated_at")), reverse=True), + recent_limit, + )) - adapter = cast(dict[str, Any], meta.get("adapter")) if isinstance(meta.get("adapter"), dict) else {} + adapter = _as_mapping(meta.get("adapter")) + raw_spawn_policy = meta.get("spawn_policy") + spawn_policy = _as_dict(raw_spawn_policy) if isinstance(raw_spawn_policy, dict) else None + explore_harness = (spawn_policy or {}).get("explore_harness") + raw_guards = meta.get("guards") quota = goal_quota_with_spend_ledger(meta, goal_runs) if registry_member else None if quota is not None and index_snapshot.undecodable_count: # The undecodable rows may be the spend or void events the projection # just summed without them; report that instead of an exact count. quota = quota_with_unreadable_index_rows(quota, index_snapshot.undecodable_count) - goal_record: dict[str, Any] = { + status_run = latest_status_run(runs) + latest_runs = latest_runs_with_agent_context( + runs, + limit=limit, + agent_lane_id=None if scoped_agent_id else agent_lane_id, + ) + semantic_history = goal_semantic_history_from_runs(runs) + goal_record: dict[str, object] = { "id": current_goal_id, **goal_parent_fields(meta), "activation_state": activation_state.value, @@ -548,12 +600,16 @@ def collect_history( "legacy_runtime_goal": not registry_member, "adapter_kind": adapter.get("kind"), "adapter_status": adapter.get("status"), - "coordination": cast(dict[str, Any], meta.get("coordination")) if isinstance(meta.get("coordination"), dict) else None, - "explore_graph": compact_explore_graph_policy(meta.get("explore_graph"), (meta.get("spawn_policy") or {}).get("explore_harness")) if meta.get("explore_graph") is not None or (meta.get("spawn_policy") or {}).get("explore_harness") else None, - "spawn_policy": cast(dict[str, Any], meta.get("spawn_policy")) if isinstance(meta.get("spawn_policy"), dict) else None, + "coordination": _as_dict(meta.get("coordination")) if isinstance(meta.get("coordination"), dict) else None, + "explore_graph": ( + compact_explore_graph_policy(meta.get("explore_graph"), explore_harness) + if meta.get("explore_graph") is not None or explore_harness + else None + ), + "spawn_policy": spawn_policy, "execution_profile": compact_execution_profile(meta.get("execution_profile")) if registry_member else None, "control_plane": compact_control_plane_policy(meta.get("control_plane")) if registry_member else None, - "guards": cast(list[Any], meta.get("guards")) if isinstance(meta.get("guards"), list) else [], + "guards": list(raw_guards) if isinstance(raw_guards, list) else [], "next_probe": meta.get("next_probe") if registry_member else None, "authority_registry": goal_authority_registry_summary(meta) if registry_member else None, "quota": quota, @@ -569,23 +625,18 @@ def collect_history( else {} ), "unique_runs": len(runs), - "latest_status_run": latest_status_run(runs), - "latest_runs": latest_runs_with_agent_context( - runs, - limit=limit, - agent_lane_id=None if scoped_agent_id else agent_lane_id, - ), - "semantic_history": goal_semantic_history_from_runs(runs), + "latest_status_run": status_run, + "latest_runs": latest_runs, + "semantic_history": semantic_history, } # Reduce the full index first. Old semantic evidence and lane windows # may survive outside --limit; every returned Run still needs fresh # flags. These references also cover the global recent_runs window. - status_run = goal_record["latest_status_run"] _observe_run_artifacts( chain( - goal_record["latest_runs"], + latest_runs, [status_run] if status_run is not None else [], - iter_goal_semantic_history_runs(goal_record["semantic_history"]), + iter_goal_semantic_history_runs(semantic_history), ), artifact_root=registry_project_root(registry_path), ) @@ -608,115 +659,65 @@ def collect_history( def build_run_history_audit( - history: dict[str, Any], - *, - registry_path: Path, - runtime_root: Path, - goal_id: str | None, - activation_state_filter: GoalActivationState | str | None, + history: Mapping[str, object], *, registry_path: Path, runtime_root: Path, + goal_id: str | None, activation_state_filter: GoalActivationState | str | None, include_runtime_goals: bool, ) -> RunHistoryAudit: - normalized_activation = ( - normalize_goal_activation_state(activation_state_filter).value - if activation_state_filter is not None - else None - ) return RunHistoryAudit( registry_path=registry_path.expanduser().resolve(), runtime_root=runtime_root.expanduser().resolve(), goal_id=str(goal_id or "").strip() or None, - activation_state_filter=normalized_activation, + activation_state_filter=_normalized_activation(activation_state_filter), include_runtime_goals=include_runtime_goals, - goal_count=int(history.get("goal_count") or 0), - run_count=int(history.get("run_count") or 0), + goal_count=_int_field(history, "goal_count"), + run_count=_int_field(history, "run_count"), goals=tuple( RunIndexAudit( goal_id=str(item.get("id") or ""), index_path=Path(str(item.get("index_path") or "")), - raw_index_records=int(item.get("raw_index_records") or 0), - unique_runs=int(item.get("unique_runs") or 0), + raw_index_records=_int_field(item, "raw_index_records"), + unique_runs=_int_field(item, "unique_runs"), legacy_runtime_goal=bool(item.get("legacy_runtime_goal")), ) - for item in history.get("goals") or [] - if isinstance(item, dict) + for item in _mapping_list(history.get("goals")) ), ) -def history_for_registry_members( - history: dict[str, Any], - *, - limit: int, -) -> dict[str, Any]: - goals = [ - goal - for goal in history.get("goals") or [] - if isinstance(goal, dict) and goal.get("registry_member") is True - ] +def history_for_registry_members(history: Mapping[str, object], *, limit: int) -> dict[str, object]: + goals = [goal for goal in _mapping_list(history.get("goals")) if goal.get("registry_member") is True] recent_limit = max(0, limit) - recent_runs = list( - islice( - merge( - *( - goal.get("latest_runs", [])[:recent_limit] - for goal in goals - if isinstance(goal.get("latest_runs"), list) - ), - key=lambda item: _chronology_key(item.get("generated_at")), - reverse=True, - ), - recent_limit, - ) - ) + recent_runs = list(islice( + merge(*(_mapping_list(goal.get("latest_runs"))[:recent_limit] for goal in goals), + key=lambda item: _chronology_key(item.get("generated_at")), reverse=True), + recent_limit, + )) return { - **history, - "goal_count": len(goals), - "run_count": sum(int(goal.get("unique_runs") or 0) for goal in goals), - "goals": goals, - "runs": recent_runs, + **history, "goal_count": len(goals), + "run_count": sum(_int_field(goal, "unique_runs") for goal in goals), + "goals": goals, "runs": recent_runs, } def collect_status_history( - *, - registry_path: Path, - runtime_root: Path, - goal_id: str | None, - limit: int, + *, registry_path: Path, runtime_root: Path, goal_id: str | None, limit: int, status_include_runtime_goals: bool, activation_state_filter: GoalActivationState | str | None = None, - agent_lane_id: str | None = None, - registry: dict[str, Any] | None = None, + agent_lane_id: str | None = None, registry: Mapping[str, object] | None = None, ) -> StatusHistoryCollection: history = collect_history( - registry_path=registry_path, - runtime_root=runtime_root, - goal_id=goal_id, - limit=limit, - include_runtime_goals=True, - activation_state_filter=activation_state_filter, - agent_lane_id=agent_lane_id, - registry=registry, + registry_path=registry_path, runtime_root=runtime_root, goal_id=goal_id, limit=limit, + include_runtime_goals=True, activation_state_filter=activation_state_filter, + agent_lane_id=agent_lane_id, registry=registry, ) audit = build_run_history_audit( - history, - registry_path=registry_path, - runtime_root=runtime_root, - goal_id=goal_id, - activation_state_filter=activation_state_filter, - include_runtime_goals=True, + history, registry_path=registry_path, runtime_root=runtime_root, goal_id=goal_id, + activation_state_filter=activation_state_filter, include_runtime_goals=True, ) status_history = history - if ( - not status_include_runtime_goals - and not str(goal_id or "").strip() - and activation_state_filter is None - ): + if not status_include_runtime_goals and not str(goal_id or "").strip() and activation_state_filter is None: status_history = history_for_registry_members(history, limit=limit) - return StatusHistoryCollection( - status_history=status_history, - contract_audit=audit, - ) + return StatusHistoryCollection(status_history=status_history, contract_audit=audit) def inspect_index_duplicates( @@ -725,101 +726,61 @@ def inspect_index_duplicates( runtime_root_override: str | None, goal_id: str | None, limit: int, -) -> dict[str, Any]: - registry = load_registry(registry_path) - runtime_root = resolve_runtime_root( - registry, - runtime_root_override, - registry_path=registry_path, +) -> dict[str, object]: + _registry, runtime_root, goal_indexes = _goal_index_paths( + registry_path, runtime_root_override, goal_id ) - groups: list[dict[str, Any]] = [] - checked_goal_count = 0 + artifact_root = registry_project_root(registry_path) + groups: list[dict[str, object]] = [] raw_index_records = 0 duplicate_row_count = 0 - for current_goal_id in discover_goal_ids(runtime_root, registry, goal_id): - checked_goal_count += 1 - index_path = runtime_root / "goals" / current_goal_id / "runs" / "index.jsonl" + for current_goal_id, index_path in goal_indexes: if not index_path.exists(): continue - - grouped: dict[tuple[str, str, str], list[tuple[int, dict[str, Any]]]] = {} with index_path.open(encoding="utf-8") as f: - for line_number, line in enumerate(f, start=1): - if not line.strip(): - continue - raw_index_records += 1 - try: - item = json.loads(line) - except json.JSONDecodeError: - continue - if not isinstance(item, dict): - continue - key = ( - str(item.get("generated_at") or ""), - str(item.get("json_path") or ""), - str(item.get("markdown_path") or ""), - ) - grouped.setdefault(key, []).append((line_number, item)) + file_raw_count, grouped = _group_index_lines(f) + raw_index_records += file_raw_count for key, records in grouped.items(): if len(records) <= 1: continue duplicate_row_count += len(records) - 1 generated_at, json_path, markdown_path = key - reward_records = sum(1 for _, record in records if isinstance(record.get("human_reward"), dict)) - classifications = sorted({str(record.get("classification") or "") for _, record in records}) - health_checks = sorted({str(record.get("health_check") or "") for _, record in records if record.get("health_check")}) - duplicate_classification = classify_index_duplicate_records([record for _, record in records]) - groups.append( - { - "goal_id": current_goal_id, - "index_path": str(index_path), - "generated_at": generated_at, - "json_path": json_path, - "markdown_path": markdown_path, - "json_exists": _indexed_artifact_exists( - json_path, - artifact_root=registry_project_root(registry_path), - ), - "markdown_exists": _indexed_artifact_exists( - markdown_path, - artifact_root=registry_project_root(registry_path), - ), - "line_numbers": [line_number for line_number, _ in records], - "raw_rows": len(records), - "duplicate_rows": len(records) - 1, - "duplicate_kind": duplicate_classification.get("duplicate_kind"), - "severity": duplicate_classification.get("severity"), - "classifications": classifications, - "health_checks": health_checks, - "reward_overlay_rows": reward_records, - "repair_hint": duplicate_classification.get("repair_hint"), - } - ) + raw_records = [record for _, record in records] + duplicate_classification = classify_index_duplicate_records(raw_records) + groups.append({ + "goal_id": current_goal_id, + "index_path": str(index_path), + "generated_at": generated_at, + "json_path": json_path, + "markdown_path": markdown_path, + "json_exists": _indexed_artifact_exists(json_path, artifact_root=artifact_root), + "markdown_exists": _indexed_artifact_exists(markdown_path, artifact_root=artifact_root), + "line_numbers": [line_number for line_number, _ in records], + "raw_rows": len(records), + "duplicate_rows": len(records) - 1, + "duplicate_kind": duplicate_classification.get("duplicate_kind"), + "severity": duplicate_classification.get("severity"), + "classifications": sorted({str(record.get("classification") or "") for record in raw_records}), + "health_checks": sorted({str(record.get("health_check") or "") for record in raw_records if record.get("health_check")}), + "reward_overlay_rows": sum(1 for record in raw_records if isinstance(record.get("human_reward"), dict)), + "repair_hint": duplicate_classification.get("repair_hint"), + }) severity_priority = {"warning": 0, "info": 1} - groups.sort( - key=lambda item: ( - severity_priority.get(str(item.get("severity")), 99), - str(item.get("goal_id")), - str(item.get("generated_at")), - ) - ) + groups.sort(key=lambda item: ( + severity_priority.get(str(item.get("severity")), 99), + str(item.get("goal_id")), + str(item.get("generated_at")), + )) limited_groups = groups[: max(0, limit)] - return { - "ok": True, - "registry": str(registry_path), - "runtime_root": str(runtime_root), - "goal_filter": goal_id, - "checked_goal_count": checked_goal_count, - "raw_index_records": raw_index_records, - "duplicate_group_count": len(groups), - "duplicate_row_count": duplicate_row_count, - "groups": limited_groups, - "truncated": len(groups) > len(limited_groups), - "limit": limit, - } + return _index_command_payload( + registry_path, runtime_root, goal_id, len(goal_indexes), + raw_index_records=raw_index_records, duplicate_group_count=len(groups), + duplicate_row_count=duplicate_row_count, groups=limited_groups, + truncated=len(groups) > len(limited_groups), limit=limit, + ) def repair_index_duplicates( @@ -829,106 +790,74 @@ def repair_index_duplicates( goal_id: str | None, limit: int, execute: bool, -) -> dict[str, Any]: - registry = load_registry(registry_path) - runtime_root = resolve_runtime_root( - registry, - runtime_root_override, - registry_path=registry_path, +) -> dict[str, object]: + _registry, runtime_root, goal_indexes = _goal_index_paths( + registry_path, runtime_root_override, goal_id ) - checked_goal_count = 0 raw_index_records = 0 removed_row_count = 0 preserved_reward_overlay_rows = 0 unrepaired_group_count = 0 - groups: list[dict[str, Any]] = [] + groups: list[dict[str, object]] = [] - for current_goal_id in discover_goal_ids(runtime_root, registry, goal_id): - checked_goal_count += 1 - index_path = runtime_root / "goals" / current_goal_id / "runs" / "index.jsonl" + for current_goal_id, index_path in goal_indexes: if not index_path.exists(): continue - # GH-C07: read and rewrite the index under the same lock the append # path takes. A dry run only reports, so it must not block writers. lock = ( exclusive_run_index_lock(index_path, operation="history_index_repair") - if execute - else nullcontext() + if execute else nullcontext() ) with lock: raw_lines = split_index_lines(index_path.read_text(encoding="utf-8")) - grouped: dict[tuple[str, str, str], list[tuple[int, dict[str, Any]]]] = {} - for line_number, line in enumerate(raw_lines, start=1): - if not line.strip(): - continue - raw_index_records += 1 - try: - item = json.loads(line) - except json.JSONDecodeError: - continue - if not isinstance(item, dict): - continue - grouped.setdefault(index_identity(item), []).append((line_number, item)) + file_raw_count, grouped = _group_index_lines(raw_lines) + raw_index_records += file_raw_count remove_lines: set[int] = set() for records in grouped.values(): if len(records) <= 1: continue decision = duplicate_repair_decision(records) - removed_lines = list(decision.get("removed_line_numbers") or []) + removed_lines = [int(ln) for ln in (decision.get("removed_line_numbers") or [])] if decision.get("action") == "preserve_reward_overlay": preserved_reward_overlay_rows += len(records) - 1 elif decision.get("repairable"): - remove_lines.update(int(line_number) for line_number in removed_lines) + remove_lines.update(removed_lines) removed_row_count += len(removed_lines) else: unrepaired_group_count += 1 first_record = records[0][1] - groups.append( - { - "goal_id": current_goal_id, - "index_path": str(index_path), - "generated_at": first_record.get("generated_at"), - "json_path": first_record.get("json_path"), - "markdown_path": first_record.get("markdown_path"), - "action": decision.get("action"), - "repairable": decision.get("repairable"), - "line_numbers": decision.get("line_numbers"), - "kept_line_numbers": decision.get("kept_line_numbers"), - "removed_line_numbers": removed_lines, - "reason": decision.get("reason"), - } - ) + groups.append({ + "goal_id": current_goal_id, + "index_path": str(index_path), + "generated_at": first_record.get("generated_at"), + "json_path": first_record.get("json_path"), + "markdown_path": first_record.get("markdown_path"), + "action": decision.get("action"), + "repairable": decision.get("repairable"), + "line_numbers": decision.get("line_numbers"), + "kept_line_numbers": decision.get("kept_line_numbers"), + "removed_line_numbers": removed_lines, + "reason": decision.get("reason"), + }) if execute and remove_lines: - rewritten = [ - line - for line_number, line in enumerate(raw_lines, start=1) - if line_number not in remove_lines - ] + rewritten = [line for ln, line in enumerate(raw_lines, start=1) if ln not in remove_lines] tmp_path = index_path.with_suffix(index_path.suffix + ".tmp") tmp_path.write_text("".join(line + "\n" for line in rewritten), encoding="utf-8") tmp_path.replace(index_path) limited_groups = groups[: max(0, limit)] - return { - "ok": True, - "dry_run": not execute, - "repaired": bool(execute and removed_row_count), - "registry": str(registry_path), - "runtime_root": str(runtime_root), - "goal_filter": goal_id, - "checked_goal_count": checked_goal_count, - "raw_index_records": raw_index_records, - "removed_row_count": removed_row_count, - "preserved_reward_overlay_rows": preserved_reward_overlay_rows, - "unrepaired_group_count": unrepaired_group_count, - "groups": limited_groups, - "truncated": len(groups) > len(limited_groups), - "limit": limit, - } + return _index_command_payload( + registry_path, runtime_root, goal_id, len(goal_indexes), + dry_run=not execute, repaired=bool(execute and removed_row_count), + raw_index_records=raw_index_records, removed_row_count=removed_row_count, + preserved_reward_overlay_rows=preserved_reward_overlay_rows, + unrepaired_group_count=unrepaired_group_count, groups=limited_groups, + truncated=len(groups) > len(limited_groups), limit=limit, + ) def rebuild_index_artifact_collisions( @@ -937,216 +866,170 @@ def rebuild_index_artifact_collisions( runtime_root_override: str | None, goal_id: str | None, limit: int, - reviewed_plan: dict[str, Any] | None, + reviewed_plan: Mapping[str, object] | None, execute: bool, -) -> dict[str, Any]: - registry = load_registry(registry_path) - runtime_root = resolve_runtime_root( - registry, - runtime_root_override, - registry_path=registry_path, +) -> dict[str, object]: + _registry, runtime_root, goal_indexes = _goal_index_paths( + registry_path, runtime_root_override, goal_id ) - all_groups: list[dict[str, Any]] = [] - checked_goal_count = 0 - for current_goal_id in discover_goal_ids(runtime_root, registry, goal_id): - checked_goal_count += 1 - index_path = runtime_root / "goals" / current_goal_id / "runs" / "index.jsonl" + all_groups: list[dict[str, object]] = [] + for current_goal_id, index_path in goal_indexes: if index_path.exists(): all_groups.extend(collision_review_groups(index_path, current_goal_id)) groups = all_groups[: max(0, limit)] truncated = len(groups) < len(all_groups) current_plan = build_collision_rebuild_plan( - groups, - goal_filter=goal_id, - total_collision_group_count=len(all_groups), - truncated=truncated, + groups, goal_filter=goal_id, total_collision_group_count=len(all_groups), truncated=truncated, ) if execute: if reviewed_plan is None: raise ValueError( "rebuild-index-collisions --execute requires --review-plan-json from a reviewed dry-run" ) - plan_sha256 = validate_reviewed_collision_plan(reviewed_plan, current_plan) - rebuilt_indexes = apply_reviewed_collision_rebuild( + plan_sha256 = validate_reviewed_collision_plan( + reviewed_plan if isinstance(reviewed_plan, dict) else dict(reviewed_plan), current_plan, - plan_sha256=plan_sha256, ) + rebuilt_indexes = apply_reviewed_collision_rebuild(current_plan, plan_sha256=plan_sha256) else: rebuilt_indexes = [] - return { - "ok": True, - "dry_run": not execute, - "rebuilt": bool(execute and rebuilt_indexes), - "registry": str(registry_path), - "runtime_root": str(runtime_root), - "goal_filter": goal_id, - "checked_goal_count": checked_goal_count, - "collision_group_count": len(groups), - "total_collision_group_count": len(all_groups), - "truncated": truncated, - "review_required": not execute and bool(groups), - "review_plan": current_plan, - "rebuilt_indexes": rebuilt_indexes, - "destructive_row_deletion": False, - } + return _index_command_payload( + registry_path, runtime_root, goal_id, len(goal_indexes), + dry_run=not execute, rebuilt=bool(execute and rebuilt_indexes), + collision_group_count=len(groups), total_collision_group_count=len(all_groups), + truncated=truncated, review_required=not execute and bool(groups), + review_plan=current_plan, rebuilt_indexes=rebuilt_indexes, + destructive_row_deletion=False, + ) -def render_index_collision_rebuild_markdown(payload: dict[str, Any]) -> str: - if not payload.get("ok"): - return "# LoopX Artifact Collision Rebuild\n\n- ok: `False`\n- error: " + str(payload.get("error")) - plan = payload.get("review_plan") or {} - return "\n".join( +def render_index_collision_rebuild_markdown(payload: Mapping[str, object]) -> str: + plan = _as_mapping(payload.get("review_plan")) + lines = _markdown_report_lines( + "LoopX Artifact Collision Rebuild", + payload, [ - "# LoopX Artifact Collision Rebuild", - "", - f"- dry_run: `{payload.get('dry_run')}`", - f"- rebuilt: `{payload.get('rebuilt')}`", - f"- collision_groups: `{payload.get('collision_group_count')}`", - f"- total_collision_groups: `{payload.get('total_collision_group_count')}`", - f"- truncated: `{payload.get('truncated')}`", - f"- review_required: `{payload.get('review_required')}`", - f"- plan_sha256: `{plan.get('plan_sha256')}`", - "- destructive_row_deletion: `False`", - "- contract: `review the exact plan, then execute with --review-plan-json`", - ] + ("dry_run", payload.get("dry_run")), + ("rebuilt", payload.get("rebuilt")), + ("collision_groups", payload.get("collision_group_count")), + ("total_collision_groups", payload.get("total_collision_group_count")), + ("truncated", payload.get("truncated")), + ("review_required", payload.get("review_required")), + ("plan_sha256", plan.get("plan_sha256")), + ("destructive_row_deletion", False), + ("contract", "review the exact plan, then execute with --review-plan-json"), + ], ) + return lines if isinstance(lines, str) else "\n".join(lines) -def render_index_duplicate_repair_markdown(payload: dict[str, Any]) -> str: - if not payload.get("ok"): - return "# LoopX Index Duplicate Repair\n\n- ok: `False`\n- error: " + str(payload.get("error")) - - lines = [ - "# LoopX Index Duplicate Repair", - "", - f"- dry_run: `{payload.get('dry_run')}`", - f"- repaired: `{payload.get('repaired')}`", - f"- runtime_root: `{payload.get('runtime_root')}`", - f"- registry: `{payload.get('registry')}`", - f"- goal_filter: `{payload.get('goal_filter')}`", - f"- checked_goals: `{payload.get('checked_goal_count')}`", - f"- raw_index_records: `{payload.get('raw_index_records')}`", - f"- removed_rows: `{payload.get('removed_row_count')}`", - f"- preserved_reward_overlay_rows: `{payload.get('preserved_reward_overlay_rows')}`", - f"- unrepaired_groups: `{payload.get('unrepaired_group_count')}`", - f"- truncated: `{payload.get('truncated')}`", - "", - markdown_table_row( - ["goal", "generated_at", "action", "repairable", "kept", "removed", "reason"] - ), - markdown_table_separator(7), - ] - for group in payload.get("groups") or []: - lines.append( - markdown_table_row( - [ - markdown_code(group.get("goal_id")), - markdown_code(group.get("generated_at")), - markdown_code(group.get("action")), - markdown_code(group.get("repairable")), - markdown_code(group.get("kept_line_numbers")), - markdown_code(group.get("removed_line_numbers")), - group.get("reason"), - ] +def render_index_duplicate_repair_markdown(payload: Mapping[str, object]) -> str: + rendered = _markdown_report_lines( + "LoopX Index Duplicate Repair", + payload, + [ + (label, payload.get(key)) + for label, key in ( + ("dry_run", "dry_run"), ("repaired", "repaired"), ("runtime_root", "runtime_root"), + ("registry", "registry"), ("goal_filter", "goal_filter"), ("checked_goals", "checked_goal_count"), + ("raw_index_records", "raw_index_records"), ("removed_rows", "removed_row_count"), + ("preserved_reward_overlay_rows", "preserved_reward_overlay_rows"), + ("unrepaired_groups", "unrepaired_group_count"), ("truncated", "truncated"), ) - ) - return "\n".join(lines) + ], + columns=("goal", "generated_at", "action", "repairable", "kept", "removed", "reason"), + rows=( + ( + markdown_code(group.get("goal_id")), markdown_code(group.get("generated_at")), + markdown_code(group.get("action")), markdown_code(group.get("repairable")), + markdown_code(group.get("kept_line_numbers")), markdown_code(group.get("removed_line_numbers")), + group.get("reason"), + ) + for group in _mapping_list(payload.get("groups")) + ), + ) + return rendered if isinstance(rendered, str) else "\n".join(rendered) -def render_history_markdown(payload: dict[str, Any]) -> str: - if not payload.get("ok"): - return "# LoopX Run History\n\n- ok: `False`\n- error: " + str(payload.get("error")) - - lines = [ - "# LoopX Run History", - "", - f"- runtime_root: `{payload.get('runtime_root')}`", - f"- registry: `{payload.get('registry')}`", - f"- goal_filter: `{payload.get('goal_filter')}`", - f"- goals: `{payload.get('goal_count')}`", - f"- unique_runs: `{payload.get('run_count')}`", - ] - unreadable = sum( - int(goal.get("unreadable_index_rows") or 0) for goal in payload.get("goals") or [] +def render_history_markdown(payload: Mapping[str, object]) -> str: + goals = _mapping_list(payload.get("goals")) + unreadable = sum(_int_field(goal, "unreadable_index_rows") for goal in goals) + lines = _markdown_report_lines( + "LoopX Run History", + payload, + [ + (label, payload.get(key)) + for label, key in ( + ("runtime_root", "runtime_root"), ("registry", "registry"), + ("goal_filter", "goal_filter"), ("goals", "goal_count"), ("unique_runs", "run_count"), + ) + ], + columns=("generated_at", "goal", "classification", "files", "action"), + rows=( + ( + markdown_code(run.get("generated_at")), markdown_code(run.get("goal_id")), + markdown_code(run.get("classification")), + f"{run.get('json_exists')}/{run.get('markdown_exists')}", run.get("recommended_action"), + ) + for run in _mapping_list(payload.get("runs")) + ), ) + if isinstance(lines, str): + return lines if unreadable: - lines.append( + lines.insert( + 7, f"- WARNING unreadable_index_rows: `{unreadable}` " - "(rows that could not be decoded were skipped; the listing below is incomplete)" - ) - lines += [ - "", - markdown_table_row(["generated_at", "goal", "classification", "files", "action"]), - markdown_table_separator(5), - ] - for run in payload.get("runs") or []: - lines.append( - markdown_table_row( - [ - markdown_code(run.get("generated_at")), - markdown_code(run.get("goal_id")), - markdown_code(run.get("classification")), - f"{run.get('json_exists')}/{run.get('markdown_exists')}", - run.get("recommended_action"), - ] - ) + "(rows that could not be decoded were skipped; the listing below is incomplete)", ) - lines.extend(["", "## Goals"]) - for goal in payload.get("goals") or []: + for goal in goals: + unreadable_suffix = ( + f", unreadable_index_rows=`{goal.get('unreadable_index_rows')}`" + if goal.get("unreadable_index_rows") else "" + ) lines.append( - "- " - f"`{goal.get('id')}`: status=`{goal.get('status')}`, " + f"- `{goal.get('id')}`: status=`{goal.get('status')}`, " f"registry_member=`{goal.get('registry_member')}`, " f"adapter=`{goal.get('adapter_kind')}:{goal.get('adapter_status')}`, " f"index_exists=`{goal.get('index_exists')}`, " f"records=`{goal.get('raw_index_records')}`, " - f"unique_runs=`{goal.get('unique_runs')}`" - + ( - f", unreadable_index_rows=`{goal.get('unreadable_index_rows')}`" - if goal.get("unreadable_index_rows") - else "" - ) + f"unique_runs=`{goal.get('unique_runs')}`{unreadable_suffix}" ) return "\n".join(lines) -def render_index_duplicate_inspection_markdown(payload: dict[str, Any]) -> str: - if not payload.get("ok"): - return "# LoopX Index Duplicate Inspection\n\n- ok: `False`\n- error: " + str(payload.get("error")) - - lines = [ - "# LoopX Index Duplicate Inspection", - "", - f"- runtime_root: `{payload.get('runtime_root')}`", - f"- registry: `{payload.get('registry')}`", - f"- goal_filter: `{payload.get('goal_filter')}`", - f"- checked_goals: `{payload.get('checked_goal_count')}`", - f"- raw_index_records: `{payload.get('raw_index_records')}`", - f"- duplicate_groups: `{payload.get('duplicate_group_count')}`", - f"- duplicate_rows: `{payload.get('duplicate_row_count')}`", - f"- truncated: `{payload.get('truncated')}`", - "", - markdown_table_row( - ["goal", "generated_at", "kind", "severity", "rows", "classifications", "repair_hint"] - ), - markdown_table_separator(7), - ] - for group in payload.get("groups") or []: - classifications = ", ".join(str(item) for item in group.get("classifications") or []) - lines.append( - markdown_table_row( - [ - markdown_code(group.get("goal_id")), - markdown_code(group.get("generated_at")), - markdown_code(group.get("duplicate_kind")), - markdown_code(group.get("severity")), - markdown_code(group.get("line_numbers")), - markdown_code(classifications), - group.get("repair_hint"), - ] - ) +def render_index_duplicate_inspection_markdown(payload: Mapping[str, object]) -> str: + def row(group: Mapping[str, object]) -> tuple[object, ...]: + raw_classes = group.get("classifications") + class_items = ( + raw_classes + if isinstance(raw_classes, Sequence) and not isinstance(raw_classes, (str, bytes)) + else [] ) - return "\n".join(lines) + return ( + markdown_code(group.get("goal_id")), markdown_code(group.get("generated_at")), + markdown_code(group.get("duplicate_kind")), markdown_code(group.get("severity")), + markdown_code(group.get("line_numbers")), + markdown_code(", ".join(str(item) for item in class_items)), + group.get("repair_hint"), + ) + + rendered = _markdown_report_lines( + "LoopX Index Duplicate Inspection", + payload, + [ + (label, payload.get(key)) + for label, key in ( + ("runtime_root", "runtime_root"), ("registry", "registry"), ("goal_filter", "goal_filter"), + ("checked_goals", "checked_goal_count"), ("raw_index_records", "raw_index_records"), + ("duplicate_groups", "duplicate_group_count"), ("duplicate_rows", "duplicate_row_count"), + ("truncated", "truncated"), + ) + ], + columns=("goal", "generated_at", "kind", "severity", "rows", "classifications", "repair_hint"), + rows=(row(group) for group in _mapping_list(payload.get("groups"))), + ) + return rendered if isinstance(rendered, str) else "\n".join(rendered) diff --git a/loopx/paths.py b/loopx/paths.py index 420aed1588..d6b1e765f1 100644 --- a/loopx/paths.py +++ b/loopx/paths.py @@ -2,11 +2,16 @@ import ast import os +import re import stat from enum import StrEnum from pathlib import Path +# One alphabet for repository-relative file-name segments. Callers keep their +# own fallback, truncation and digest policy. +PATH_SEGMENT_UNSAFE_RE = re.compile(r"[^A-Za-z0-9._-]+") + DEFAULT_RUNTIME_ROOT = Path.home() / ".loopx" LEGACY_RUNTIME_ROOT = Path.home() / ".codex" / "loopx" DEFAULT_PROJECT_REGISTRY = Path(".loopx") / "registry.json" diff --git a/loopx/quota.py b/loopx/quota.py index 46af12acd9..0263c3ea4b 100644 --- a/loopx/quota.py +++ b/loopx/quota.py @@ -1387,9 +1387,9 @@ def spend_quota_slot( ) spent_result = settlement_readback.settlement if spent_result.failure is None: - no_spend = ( - _as_dict(settlement_readback.progress).get("closeout_kind") - == "capability_duty_retired_no_spend" + progress = _as_dict(settlement_readback.progress) + no_spend = progress.get("no_spend") is True or ( + progress.get("closeout_kind") == "capability_duty_retired_no_spend" ) return _spend_slot_reply( ok=True, execute=execute, goal_id=safe_goal_id, goal_ref=goal_ref, diff --git a/loopx/semantics/production.py b/loopx/semantics/production.py index 63f9caa3e7..b9de9370fb 100644 --- a/loopx/semantics/production.py +++ b/loopx/semantics/production.py @@ -8,6 +8,7 @@ import subprocess from typing import Any, Callable +from ..control_plane.runtime.node_probe import node_typescript_flags from .inventory import SourceFile from .python_production import Production, enum_members, scan_python_production @@ -292,7 +293,7 @@ def probe_settlement_binding_production(vocabulary: dict[str, Any]) -> list[Prod for count in (2, 3) for group in combinations(bindings, count)] probes.extend(conflicts) completed = subprocess.run( - ['node', '--no-warnings', '--experimental-strip-types', + ['node', '--no-warnings', '--experimental-strip-types', *node_typescript_flags(), str(root / 'scripts/settlement_binding_witness.mts')], input=json.dumps({'probes': probes}), capture_output=True, text=True, encoding='utf-8', check=False, @@ -337,7 +338,7 @@ def probe_quota_run_decision_production(vocabulary: dict[str, Any]) -> list[Prod root = Path(__file__).resolve().parents[2] try: completed = subprocess.run( - ['node', '--no-warnings', '--experimental-strip-types', + ['node', '--no-warnings', '--experimental-strip-types', *node_typescript_flags(), str(root / 'scripts/quota_run_decision_witness.mts')], input=json.dumps({'values': vocabulary['values']}), capture_output=True, text=True, encoding='utf-8', check=False, timeout=30, diff --git a/loopx/semantics/project_registry_io_classifications_v1.json b/loopx/semantics/project_registry_io_classifications_v1.json index 3ab5f90fc5..32f7b2331b 100644 --- a/loopx/semantics/project_registry_io_classifications_v1.json +++ b/loopx/semantics/project_registry_io_classifications_v1.json @@ -5,6 +5,8 @@ "loopx/control_plane/goals/deletion_service.py::._restore_locked_registry::direct_json_write:atomic_write_json#1": "global_registry_io", "loopx/control_plane/goals/deletion_service.py::._write_deletion::direct_json_read:read_json#1": "global_registry_io", "loopx/control_plane/goals/deletion_service.py::._write_locked_registry::direct_json_write:atomic_write_json#1": "global_registry_io", + "loopx/control_plane/quota/execution_loss_closeout.ts::::direct_json_read:readFileSync#1": "codec_internal", + "loopx/control_plane/quota/execution_loss_closeout.ts::::direct_json_read:readFileSync#2": "codec_internal", "loopx/control_plane/scheduler/heartbeat_commit.ts::readCurrentGoalInstance::direct_json_read:readFile#1": "codec_internal", "loopx/state_migration.py::.legacy_registry_goal_ids::direct_json_read:read_json_object#1": "legacy_registry_source", "loopx/state_migration.py::.migrate_legacy_state::direct_json_read:read_json_object#1": "legacy_registry_source" diff --git a/loopx/state_refresh.py b/loopx/state_refresh.py index d63eac6af6..890e255286 100644 --- a/loopx/state_refresh.py +++ b/loopx/state_refresh.py @@ -941,13 +941,16 @@ def refresh_state_run( checkpoint_supplement = bool( refresh_recovery["decision"] == "supplement_checkpoint" ) + checkpoint_replay = None if refresh_recovery.get("decision") in {"replay", "repair_receipt"} and prior_writeback_run: - inspect_checkpoint_replay(runtime_root, safe_goal_id, prior_writeback_run) + checkpoint_replay = inspect_checkpoint_replay(runtime_root, safe_goal_id, prior_writeback_run) recovery_payload = refresh_recovery_payload( settlement_readback, registry_path=registry_path, runtime_root=runtime_root, goal_id=safe_goal_id, dry_run=dry_run, goal_ref=goal_ref, ) if recovery_payload is not None: + if checkpoint_replay is not None: + recovery_payload.update({key: checkpoint_replay[key] for key in ("json_path", "markdown_path")}) return recover_refresh_todo_projection( recovery_payload, registry_path=registry_path, runtime_root=runtime_root, goal_id=safe_goal_id, project=project, state_file=state_file, diff --git a/loopx/status.py b/loopx/status.py index 4d6e5357d3..2bf348200d 100644 --- a/loopx/status.py +++ b/loopx/status.py @@ -2,7 +2,7 @@ from collections.abc import Mapping, Sequence from pathlib import Path -from typing import Any +from typing import cast from .control_plane.work_items.replan_history_codec import ( REPLAN_HISTORY_NEUTRAL_CLASSIFICATIONS as _REPLAN_HISTORY_NEUTRAL_CLASSIFICATIONS, @@ -15,11 +15,6 @@ CONNECTED_ADAPTER_STATUSES as CONNECTED_ADAPTER_STATUSES, CONNECTED_DELIVERY_ADAPTER_STATUSES as CONNECTED_DELIVERY_ADAPTER_STATUSES, ) -# Refs #4447: one definition for this vocabulary. Both status projections pass the -# same two sets into the same injected parameters of the attention and lifecycle -# read models, so the owner is the control-plane status package and this facade -# keeps exporting the established names for existing callers as identity aliases -# instead of restating the values. from .control_plane.status.autonomous_replan_projection import ( AUTONOMOUS_REPLAN_PERIODIC_RUN_THRESHOLD as AUTONOMOUS_REPLAN_PERIODIC_RUN_THRESHOLD, DEAD_MONITOR_REPEAT_THRESHOLD as DEAD_MONITOR_REPEAT_THRESHOLD, @@ -335,12 +330,6 @@ ) - - - - - - def active_state_sections(state_text: str, headings: tuple[str, ...]) -> dict[str, list[str]]: from .control_plane.status.active_state_projection import ( active_state_sections as _active_state_sections, @@ -349,7 +338,7 @@ def active_state_sections(state_text: str, headings: tuple[str, ...]) -> dict[st return _active_state_sections(state_text, headings) -def parse_issue_meta_surface(state_text: str) -> dict[str, Any] | None: +def parse_issue_meta_surface(state_text: str) -> dict[str, object] | None: from .control_plane.status.active_state_projection import ( parse_issue_meta_surface as _parse_issue_meta_surface, ) @@ -365,7 +354,7 @@ def active_state_section_entries(lines: list[str]) -> list[str]: return _active_state_section_entries(lines) -def backlog_hygiene_warning(state_text: str, *, agent_todos: dict[str, Any] | None) -> dict[str, Any] | None: +def backlog_hygiene_warning(state_text: str, *, agent_todos: dict[str, object] | None) -> dict[str, object] | None: from .control_plane.status.active_state_projection import ( backlog_hygiene_warning as _backlog_hygiene_warning, ) @@ -374,10 +363,10 @@ def backlog_hygiene_warning(state_text: str, *, agent_todos: dict[str, Any] | No def build_autonomous_replan_obligation( - evidence: list[dict[str, Any]], + evidence: list[dict[str, object]], *, - agent_todos: dict[str, Any] | None, -) -> dict[str, Any] | None: + agent_todos: dict[str, object] | None, +) -> dict[str, object] | None: from .control_plane.status.autonomous_replan_projection import ( build_autonomous_replan_obligation as _build_autonomous_replan_obligation, ) @@ -389,7 +378,7 @@ def build_autonomous_replan_obligation( def run_history_monitor_wait_already_acknowledged( - latest_runs: list[dict[str, Any]] | None, + latest_runs: list[dict[str, object]] | None, *, signal_count: int, ) -> bool: @@ -404,8 +393,8 @@ def run_history_monitor_wait_already_acknowledged( def latest_autonomous_replan_ack_for_projection( - latest_runs: list[dict[str, Any]] | None, -) -> dict[str, Any] | None: + latest_runs: list[dict[str, object]] | None, +) -> dict[str, object] | None: from .control_plane.status.autonomous_replan_projection import ( latest_autonomous_replan_ack_for_projection as _latest_autonomous_replan_ack_for_projection, ) @@ -414,10 +403,10 @@ def latest_autonomous_replan_ack_for_projection( def autonomous_replan_periodic_review_from_runs( - latest_runs: list[dict[str, Any]] | None, + latest_runs: list[dict[str, object]] | None, *, - agent_todos: dict[str, Any] | None, -) -> dict[str, Any] | None: + agent_todos: dict[str, object] | None, +) -> dict[str, object] | None: from .control_plane.status.autonomous_replan_projection import ( autonomous_replan_periodic_review_from_runs as _autonomous_replan_periodic_review_from_runs, ) @@ -429,13 +418,13 @@ def autonomous_replan_periodic_review_from_runs( def autonomous_replan_obligation_from_runs( - latest_runs: list[dict[str, Any]] | None, + latest_runs: list[dict[str, object]] | None, *, - agent_todos: dict[str, Any] | None, + agent_todos: dict[str, object] | None, agent_id: str | None = None, - external_progress_review: dict[str, Any] | None = None, - effective_turn_cadence: dict[str, Any] | None = None, -) -> dict[str, Any] | None: + external_progress_review: dict[str, object] | None = None, + effective_turn_cadence: dict[str, object] | None = None, +) -> dict[str, object] | None: from .control_plane.status.autonomous_replan_projection import ( autonomous_replan_obligation_from_runs as _autonomous_replan_obligation_from_runs, ) @@ -450,9 +439,9 @@ def autonomous_replan_obligation_from_runs( def external_progress_review_context( - goal: dict[str, Any], + goal: dict[str, object], runtime_root: Path | None, -) -> dict[str, Any] | None: +) -> dict[str, object] | None: """Status reads the sentinel context through the capability-owned loader.""" from .capabilities.progress_review.context import ( @@ -463,10 +452,10 @@ def external_progress_review_context( def autonomous_backlog_candidates( - items: list[dict[str, Any]], + items: list[dict[str, object]], *, limit: int = MAX_AUTONOMOUS_BACKLOG_CANDIDATES, -) -> dict[str, Any] | None: +) -> dict[str, object] | None: from .control_plane.status.attention_projection import ( autonomous_backlog_candidates as _autonomous_backlog_candidates, ) @@ -475,10 +464,10 @@ def autonomous_backlog_candidates( def autonomous_monitor_candidates( - items: list[dict[str, Any]], + items: list[dict[str, object]], *, limit: int = MAX_AUTONOMOUS_BACKLOG_CANDIDATES, -) -> dict[str, Any] | None: +) -> dict[str, object] | None: from .control_plane.status.attention_projection import ( autonomous_monitor_candidates as _autonomous_monitor_candidates, ) @@ -488,11 +477,11 @@ def autonomous_monitor_candidates( def build_attention_queue_projection( *, - items: list[dict[str, Any]], + items: list[dict[str, object]], goal_id_filter: str | None, - autonomous_backlog_candidates: dict[str, Any] | None, - autonomous_monitor_candidates: dict[str, Any] | None, -) -> dict[str, Any]: + autonomous_backlog_candidates: dict[str, object] | None, + autonomous_monitor_candidates: dict[str, object] | None, +) -> dict[str, object]: from .control_plane.status.attention_projection import ( build_attention_queue_projection as _build_attention_queue_projection, ) @@ -505,7 +494,7 @@ def build_attention_queue_projection( ) -def active_state_projection_warning(goal: dict[str, Any], current_run: dict[str, Any] | None) -> dict[str, Any] | None: +def active_state_projection_warning(goal: dict[str, object], current_run: dict[str, object] | None) -> dict[str, object] | None: return _stale_latest_run_projection_warning_read_model( goal, current_run, @@ -520,7 +509,7 @@ def active_state_projection_warning(goal: dict[str, Any], current_run: dict[str, ) -def is_handoff_ready_run(run: dict[str, Any]) -> bool: +def is_handoff_ready_run(run: dict[str, object]) -> bool: return _is_handoff_ready_run_read_model( run, handoff_ready_classifications=HANDOFF_READY_CLASSIFICATIONS, @@ -528,7 +517,7 @@ def is_handoff_ready_run(run: dict[str, Any]) -> bool: ) -def run_has_external_evidence_watch_signal(run: dict[str, Any]) -> bool: +def run_has_external_evidence_watch_signal(run: dict[str, object]) -> bool: """Return true only for explicit external-evidence watch state. Feature names may legitimately start with words such as "monitor"; routing @@ -542,7 +531,7 @@ def run_has_external_evidence_watch_signal(run: dict[str, Any]) -> bool: ) -def is_custom_post_handoff_work_run(run: dict[str, Any]) -> bool: +def is_custom_post_handoff_work_run(run: dict[str, object]) -> bool: return _is_custom_post_handoff_work_run_read_model( run, is_status_neutral_run=is_status_neutral_run, @@ -554,21 +543,21 @@ def is_custom_post_handoff_work_run(run: dict[str, Any]) -> bool: ) -def compact_post_handoff_run(run: dict[str, Any], profile: dict[str, Any] | None = None) -> dict[str, Any]: - return project_post_handoff_history([run], profile)["post_handoff_latest_run"] +def compact_post_handoff_run(run: dict[str, object], profile: dict[str, object] | None = None) -> dict[str, object]: + return cast(dict[str, object], project_post_handoff_history([run], profile)["post_handoff_latest_run"]) def project_post_handoff_history( - runs: list[dict[str, Any]], profile: dict[str, Any] | None = None, -) -> dict[str, Any]: + runs: list[dict[str, object]], profile: dict[str, object] | None = None, +) -> dict[str, object]: if not runs: return {} floor = execution_profile_outcome_floor(profile) floor_configured = bool(floor.get("outcome_markers") or floor.get("surface_only_hints")) projection = project_delivery_history(runs, outcome_floor_configured=floor_configured) - compact_runs = [] + compact_runs: list[dict[str, object]] = [] for run, signal in zip(runs, projection["runs"], strict=True): - compact = {field: run[field] for field in ( + compact: dict[str, object] = {field: run[field] for field in ( "generated_at", "classification", "health_check", "json_exists", "markdown_exists", "progress_scope", ) if field in run} @@ -583,7 +572,7 @@ def project_post_handoff_history( compact, run, compact_session_runtime_projection_from_run=compact_session_runtime_projection_from_run, )) - result = { + result: dict[str, object] = { "post_handoff_latest_run": compact_runs[0], "post_handoff_recent_runs": compact_runs, "post_handoff_small_scale_streak": projection["small_scale_streak"], @@ -596,9 +585,9 @@ def project_post_handoff_history( def project_asset_handoff_state( *, ready: bool, - project_asset: dict[str, Any], - latest_runs: list[dict[str, Any]] | None, -) -> dict[str, Any]: + project_asset: dict[str, object], + latest_runs: list[dict[str, object]] | None, +) -> dict[str, object]: return _project_asset_handoff_state_read_model( ready=ready, project_asset=project_asset, @@ -613,10 +602,10 @@ def project_asset_handoff_state( def project_asset_handoff_readiness( - item: dict[str, Any], + item: dict[str, object], *, - latest_runs: list[dict[str, Any]] | None = None, -) -> dict[str, Any] | None: + latest_runs: list[dict[str, object]] | None = None, +) -> dict[str, object] | None: return _project_asset_handoff_readiness_read_model( item, latest_runs=latest_runs, @@ -627,17 +616,17 @@ def project_asset_handoff_readiness( def enrich_project_asset( - item: dict[str, Any], + item: dict[str, object], *, - user_todos: dict[str, Any] | None = None, - agent_todos: dict[str, Any] | None = None, - quota: dict[str, Any] | None = None, - latest_validation: dict[str, Any] | None = None, - latest_runs: list[dict[str, Any]] | None = None, - execution_profile: dict[str, Any] | None = None, - orchestration: dict[str, Any] | None = None, - subagent_activity: dict[str, Any] | None = None, - interface_budget_cadence: dict[str, Any] | None = None, + user_todos: dict[str, object] | None = None, + agent_todos: dict[str, object] | None = None, + quota: dict[str, object] | None = None, + latest_validation: dict[str, object] | None = None, + latest_runs: list[dict[str, object]] | None = None, + execution_profile: dict[str, object] | None = None, + orchestration: dict[str, object] | None = None, + subagent_activity: dict[str, object] | None = None, + interface_budget_cadence: dict[str, object] | None = None, ) -> None: _enrich_project_asset_read_model( item, @@ -663,21 +652,21 @@ def enrich_project_asset( def active_state_todo_fields( - goal: dict[str, Any], + goal: dict[str, object], *, runtime_root: Path | None = None, registry_path: Path | None = None, todo_snapshot: _CanonicalTodoSnapshot | None = None, include_agent_next_actions: bool = False, - rollout_events: Sequence[Mapping[str, Any]] | None = None, -) -> dict[str, Any]: + rollout_events: Sequence[Mapping[str, object]] | None = None, +) -> dict[str, object]: return _active_state_todo_fields_read_model( goal, runtime_root=runtime_root, registry_path=registry_path, + todo_snapshot=todo_snapshot, include_agent_next_actions=include_agent_next_actions, rollout_events=rollout_events, - **({"todo_snapshot": todo_snapshot} if todo_snapshot is not None else {}), resolve_goal_local_path=resolve_goal_local_path, active_state_next_action_entries=active_state_next_action_entries, load_rollout_events=load_rollout_events, @@ -705,11 +694,11 @@ def attention_item( next_handoff_condition: str | None = None, lifecycle_phase: str | None = None, lifecycle_flags: list[str] | None = None, - user_todos: dict[str, Any] | None = None, - agent_todos: dict[str, Any] | None = None, + user_todos: dict[str, object] | None = None, + agent_todos: dict[str, object] | None = None, todo_state_file: str | None = None, - dreaming_proposal: dict[str, Any] | None = None, -) -> dict[str, Any]: + dreaming_proposal: dict[str, object] | None = None, +) -> dict[str, object]: return _attention_item_read_model( goal_id=goal_id, status=status, @@ -733,7 +722,7 @@ def attention_item( ) -def sync_connected_attention_action_from_todos(item: dict[str, Any]) -> None: +def sync_connected_attention_action_from_todos(item: dict[str, object]) -> None: _sync_connected_attention_action_from_todos_read_model( item, first_open_todo_text=first_open_todo_text, @@ -741,10 +730,10 @@ def sync_connected_attention_action_from_todos(item: dict[str, Any]) -> None: def active_state_todo_attention_item( - goal: dict[str, Any], - fields: dict[str, Any], - current_run: dict[str, Any] | None, -) -> dict[str, Any] | None: + goal: dict[str, object], + fields: dict[str, object], + current_run: dict[str, object] | None, +) -> dict[str, object] | None: return _active_state_todo_attention_item_read_model( goal, fields, @@ -757,7 +746,7 @@ def active_state_todo_attention_item( ) -def todo_summary_open_count(summary: dict[str, Any] | None) -> int: +def todo_summary_open_count(summary: dict[str, object] | None) -> int: from .control_plane.status.monitor_display_projection import ( todo_summary_open_count as _todo_summary_open_count, ) @@ -765,7 +754,7 @@ def todo_summary_open_count(summary: dict[str, Any] | None) -> int: return _todo_summary_open_count(summary) -def todo_summary_lane_items(summary: dict[str, Any] | None, lane: str) -> list[dict[str, Any]]: +def todo_summary_lane_items(summary: dict[str, object] | None, lane: str) -> list[dict[str, object]]: from .control_plane.status.monitor_display_projection import ( todo_summary_lane_items as _todo_summary_lane_items, ) @@ -773,7 +762,7 @@ def todo_summary_lane_items(summary: dict[str, Any] | None, lane: str) -> list[d return _todo_summary_lane_items(summary, lane) -def attention_item_is_monitor_quiet_display_candidate(item: dict[str, Any]) -> bool: +def attention_item_is_monitor_quiet_display_candidate(item: dict[str, object]) -> bool: from .control_plane.status.monitor_display_projection import ( attention_item_is_monitor_quiet_display_candidate as _attention_item_is_monitor_quiet_display_candidate, ) @@ -789,7 +778,7 @@ def quiet_monitor_display_action(raw_action: str | None) -> str: return _quiet_monitor_display_action(raw_action) -def normalize_monitor_quiet_attention_display(item: dict[str, Any]) -> None: +def normalize_monitor_quiet_attention_display(item: dict[str, object]) -> None: from .control_plane.status.monitor_display_projection import ( normalize_monitor_quiet_attention_display as _normalize_monitor_quiet_attention_display, ) @@ -799,9 +788,9 @@ def normalize_monitor_quiet_attention_display(item: dict[str, Any]) -> None: def merge_global_registry_attention_findings( *, - health_items: list[dict[str, Any]], - history_items: list[dict[str, Any]], - findings: list[Any], + health_items: list[dict[str, object]], + history_items: list[dict[str, object]], + findings: list[object], goal_id_filter: str | None, ) -> None: from .control_plane.status.registry_health_projection import ( @@ -820,8 +809,8 @@ def collect_global_registry_health( *, registry_path: Path, runtime_root: Path, - current_registry: dict[str, Any], -) -> dict[str, Any]: + current_registry: dict[str, object], +) -> dict[str, object]: from .control_plane.status.registry_health_projection import ( collect_global_registry_health as _collect_global_registry_health, ) @@ -833,7 +822,7 @@ def collect_global_registry_health( ) -def is_status_neutral_run(run: dict[str, Any]) -> bool: +def is_status_neutral_run(run: dict[str, object]) -> bool: from .control_plane.status.run_projection import ( is_status_neutral_run as _is_status_neutral_run, ) @@ -841,7 +830,7 @@ def is_status_neutral_run(run: dict[str, Any]) -> bool: return _is_status_neutral_run(run) -def latest_agent_lane_run(goal: dict[str, Any]) -> dict[str, Any] | None: +def latest_agent_lane_run(goal: dict[str, object]) -> dict[str, object] | None: from .control_plane.status.run_projection import ( latest_agent_lane_run as _latest_agent_lane_run, ) @@ -849,7 +838,7 @@ def latest_agent_lane_run(goal: dict[str, Any]) -> dict[str, Any] | None: return _latest_agent_lane_run(goal) -def compact_agent_lane_recommendation(run: dict[str, Any] | None) -> dict[str, Any] | None: +def compact_agent_lane_recommendation(run: dict[str, object] | None) -> dict[str, object] | None: from .control_plane.status.run_projection import ( compact_agent_lane_recommendation as _compact_agent_lane_recommendation, ) @@ -859,9 +848,9 @@ def compact_agent_lane_recommendation(run: dict[str, Any] | None) -> dict[str, A def latest_run_recommended_action_for_projection( *, - current_status_run: dict[str, Any] | None, - agent_lane_recommendation: dict[str, Any] | None, - active_state_next_action: Any = None, + current_status_run: dict[str, object] | None, + agent_lane_recommendation: dict[str, object] | None, + active_state_next_action: object = None, preferred_agent_id: str | None = None, limit: int = 320, ) -> tuple[str | None, str | None]: @@ -878,7 +867,7 @@ def latest_run_recommended_action_for_projection( ) -def latest_run(goal: dict[str, Any]) -> dict[str, Any] | None: +def latest_run(goal: dict[str, object]) -> dict[str, object] | None: from .control_plane.status.run_projection import ( latest_run as _latest_run, ) @@ -902,7 +891,7 @@ def primary_lifecycle_phase(flags: list[str], fallback: str = "registered") -> s return _primary_lifecycle_phase(flags, fallback=fallback) -def run_lifecycle_flags(run: dict[str, Any] | None) -> list[str]: +def run_lifecycle_flags(run: dict[str, object] | None) -> list[str]: from .control_plane.status.lifecycle_projection import ( run_lifecycle_flags as _run_lifecycle_flags, ) @@ -910,7 +899,7 @@ def run_lifecycle_flags(run: dict[str, Any] | None) -> list[str]: return _run_lifecycle_flags(run) -def run_lifecycle_phase(run: dict[str, Any] | None) -> str: +def run_lifecycle_phase(run: dict[str, object] | None) -> str: from .control_plane.status.lifecycle_projection import ( run_lifecycle_phase as _run_lifecycle_phase, ) @@ -918,7 +907,7 @@ def run_lifecycle_phase(run: dict[str, Any] | None) -> str: return _run_lifecycle_phase(run) -def goal_lifecycle_fields(goal: dict[str, Any], current_run: dict[str, Any] | None) -> dict[str, Any]: +def goal_lifecycle_fields(goal: dict[str, object], current_run: dict[str, object] | None) -> dict[str, object]: from .control_plane.status.lifecycle_projection import ( goal_lifecycle_fields as _goal_lifecycle_fields, ) @@ -926,7 +915,7 @@ def goal_lifecycle_fields(goal: dict[str, Any], current_run: dict[str, Any] | No return _goal_lifecycle_fields(goal, current_run) -def readiness_attention_fields(run: dict[str, Any] | None) -> dict[str, Any]: +def readiness_attention_fields(run: dict[str, object] | None) -> dict[str, object]: from .control_plane.status.lifecycle_projection import ( readiness_attention_fields as _readiness_attention_fields, ) @@ -934,7 +923,7 @@ def readiness_attention_fields(run: dict[str, Any] | None) -> dict[str, Any]: return _readiness_attention_fields(run) -def operator_gate_attention_fields(run: dict[str, Any] | None) -> dict[str, Any]: +def operator_gate_attention_fields(run: dict[str, object] | None) -> dict[str, object]: from .control_plane.status.lifecycle_projection import ( operator_gate_attention_fields as _operator_gate_attention_fields, ) @@ -942,7 +931,7 @@ def operator_gate_attention_fields(run: dict[str, Any] | None) -> dict[str, Any] return _operator_gate_attention_fields(run) -def compact_server_planning_contract(value: Any) -> dict[str, Any]: +def compact_server_planning_contract(value: object) -> dict[str, object]: from .control_plane.status.dreaming_projection import ( compact_server_planning_contract as _compact_server_planning_contract, ) @@ -950,7 +939,7 @@ def compact_server_planning_contract(value: Any) -> dict[str, Any]: return _compact_server_planning_contract(value) -def compact_dreaming_proposal(run: dict[str, Any] | None) -> dict[str, Any] | None: +def compact_dreaming_proposal(run: dict[str, object] | None) -> dict[str, object] | None: from .control_plane.status.dreaming_projection import ( compact_dreaming_proposal as _compact_dreaming_proposal, ) @@ -958,7 +947,7 @@ def compact_dreaming_proposal(run: dict[str, Any] | None) -> dict[str, Any] | No return _compact_dreaming_proposal(run) -def compact_dreaming_lane_badge(proposal: dict[str, Any] | None) -> dict[str, Any] | None: +def compact_dreaming_lane_badge(proposal: dict[str, object] | None) -> dict[str, object] | None: from .control_plane.status.dreaming_projection import ( compact_dreaming_lane_badge as _compact_dreaming_lane_badge, ) @@ -966,7 +955,7 @@ def compact_dreaming_lane_badge(proposal: dict[str, Any] | None) -> dict[str, An return _compact_dreaming_lane_badge(proposal) -def dreaming_attention_fields(run: dict[str, Any] | None) -> dict[str, Any]: +def dreaming_attention_fields(run: dict[str, object] | None) -> dict[str, object]: from .control_plane.status.dreaming_projection import ( dreaming_attention_fields as _dreaming_attention_fields, ) @@ -975,10 +964,10 @@ def dreaming_attention_fields(run: dict[str, Any] | None) -> dict[str, Any]: def legacy_runtime_goal_attention( - goal: dict[str, Any], - current_run: dict[str, Any] | None, - readiness_fields: dict[str, Any], -) -> dict[str, Any] | None: + goal: dict[str, object], + current_run: dict[str, object] | None, + readiness_fields: dict[str, object], +) -> dict[str, object] | None: from .control_plane.status.goal_attention_projection import ( legacy_runtime_goal_attention as _legacy_runtime_goal_attention, ) @@ -990,7 +979,7 @@ def legacy_runtime_goal_attention( ) -def goal_attention(goal: dict[str, Any]) -> dict[str, Any] | None: +def goal_attention(goal: dict[str, object]) -> dict[str, object] | None: from .control_plane.status.goal_attention_projection import ( goal_attention as _goal_attention, ) @@ -999,11 +988,11 @@ def goal_attention(goal: dict[str, Any]) -> dict[str, Any] | None: def build_task_graph_projection( - item: dict[str, Any], + item: dict[str, object], *, - goal: dict[str, Any], - goal_latest_runs: list[dict[str, Any]] | None = None, -) -> dict[str, Any] | None: + goal: dict[str, object], + goal_latest_runs: list[dict[str, object]] | None = None, +) -> dict[str, object] | None: return _build_task_graph_projection_read_model( item, goal=goal, @@ -1013,11 +1002,12 @@ def build_task_graph_projection( latest_run=latest_run, ) + def attach_goal_channel_projection( - item: dict[str, Any], + item: dict[str, object], *, - goal: dict[str, Any], - goal_latest_runs: list[dict[str, Any]], + goal: dict[str, object], + goal_latest_runs: list[dict[str, object]], runtime_root: Path | None = None, ) -> None: _attach_goal_channel_projection_read_model( @@ -1031,26 +1021,26 @@ def attach_goal_channel_projection( def build_attention_queue( *, - contract: dict[str, Any], - history: dict[str, Any], - global_registry: dict[str, Any], + contract: dict[str, object], + history: dict[str, object], + global_registry: dict[str, object], runtime_root: Path | None = None, include_task_graph: bool = False, goal_id_filter: str | None = None, include_stopped_goal_context: bool = False, events_for_goal: EventsForGoal | None = None, todo_snapshot: _CanonicalTodoSnapshot | None = None, - current_registry: dict[str, Any] | None = None, + current_registry: dict[str, object] | None = None, registry_path: Path | None = None, include_goal_channel_projection: bool = True, tolerate_malformed_settlement_history: bool = False, agent_lane_id: str | None = None, -) -> dict[str, Any]: +) -> dict[str, object]: def request_active_state_todo_fields( - goal: dict[str, Any], + goal: dict[str, object], *, runtime_root: Path | None = None, - ) -> dict[str, Any]: + ) -> dict[str, object]: goal_id = str(goal.get("id") or "").strip() supplied_events = ( events_for_goal( @@ -1066,7 +1056,7 @@ def request_active_state_todo_fields( include_agent_next_actions=include_task_graph, registry_path=registry_path, rollout_events=supplied_events, - **({"todo_snapshot": todo_snapshot} if todo_snapshot is not None else {}), + todo_snapshot=todo_snapshot, ) queue = _build_attention_queue_read_model( @@ -1154,9 +1144,10 @@ def request_active_state_todo_fields( continue goal_ref = None if (current_registry or {}).get("profile_id") == "source_session_v1": + raw_goals = (current_registry or {}).get("goals") matches = [ goal - for goal in (current_registry or {}).get("goals") or [] + for goal in (raw_goals if isinstance(raw_goals, list) else ()) if isinstance(goal, dict) and goal.get("id") == goal_id and goal.get("status") == "active" @@ -1188,7 +1179,7 @@ def request_active_state_todo_fields( return queue -def compact_run(run: dict[str, Any]) -> dict[str, Any]: +def compact_run(run: dict[str, object]) -> dict[str, object]: compact = _compact_run_base_read_model( run, run_compact_fields=RUN_COMPACT_FIELDS, @@ -1211,7 +1202,7 @@ def compact_run(run: dict[str, Any]) -> dict[str, Any]: ) -def build_status_contract() -> dict[str, Any]: +def build_status_contract() -> dict[str, object]: from .control_plane.status.contract_projection import ( build_status_contract as _build_status_contract, ) @@ -1219,7 +1210,7 @@ def build_status_contract() -> dict[str, Any]: return _build_status_contract() -def build_contract_health_projection(contract: dict[str, Any]) -> dict[str, Any]: +def build_contract_health_projection(contract: dict[str, object]) -> dict[str, object]: from .control_plane.status.contract_projection import ( build_contract_health_projection as _build_contract_health_projection, ) @@ -1255,8 +1246,8 @@ def build_status_runtime_summary_context() -> StatusRuntimeSummaryContext: def build_status_runtime_summaries( *, - history: dict[str, Any], - queue: dict[str, Any], + history: dict[str, object], + queue: dict[str, object], runtime_root: Path, goal_id_filter: str | None, display_limit: int, @@ -1264,7 +1255,7 @@ def build_status_runtime_summaries( recent_run_limit: int | None = None, include_goal_subagent_configuration: bool = False, events_for_goal: EventsForGoal | None = None, -) -> dict[str, Any]: +) -> dict[str, object]: return _build_status_runtime_summaries_read_model( history=history, queue=queue, @@ -1313,7 +1304,7 @@ def collect_status( limit: int, include_task_graph: bool = False, goal_id: str | None = None, - available_capabilities: Any = None, + available_capabilities: object = None, recent_run_limit: int | None = None, include_goal_subagent_configuration: bool = False, include_zcode_goal_eligibility: bool = False, @@ -1322,7 +1313,7 @@ def collect_status( allow_missing_registry: bool = False, include_presentation_projections: bool = True, tolerate_malformed_settlement_history: bool = False, -) -> dict[str, Any]: +) -> dict[str, object]: with effect_runtime_request_scope(): return _collect_status_read_model( registry_path=registry_path, diff --git a/loopx/usage_ping.py b/loopx/usage_ping.py index 6f05f9aa3f..9b468e8de2 100644 --- a/loopx/usage_ping.py +++ b/loopx/usage_ping.py @@ -15,6 +15,7 @@ from typing import Any from . import __version__ +from .control_plane.runtime.node_probe import node_typescript_flags from .paths import select_default_runtime_root STATE_FILENAME = "usage-ping.json" @@ -120,7 +121,14 @@ def _command() -> list[str]: raise UsageSettingsUnavailable(message="Usage settings require the supported Node.js runtime.") # Keep the Python sender's proxy behavior when moving I/O to Node. This # native flag is available in the repository's supported Node versions. - return [node, "--no-warnings", "--use-env-proxy", "--experimental-strip-types", str(_ENTRY)] + return [ + node, + "--no-warnings", + "--use-env-proxy", + "--experimental-strip-types", + *node_typescript_flags(), + str(_ENTRY), + ] def control(action: str, path: Path | None = None, **fields: Any) -> dict[str, Any]: diff --git a/loopx/zcode_goal_mode/bridge.py b/loopx/zcode_goal_mode/bridge.py index 4cec542a58..8147578f02 100644 --- a/loopx/zcode_goal_mode/bridge.py +++ b/loopx/zcode_goal_mode/bridge.py @@ -17,6 +17,7 @@ from ..control_plane.goals.activation import goal_is_stopped from ..control_plane.goals.goal_ref_validation import exact_goal_ref, require_goal_id from ..control_plane.runtime.goal_project_route import resolve_goal_project_route +from ..control_plane.runtime.node_probe import node_typescript_flags from ..control_plane.projects.registry_codec import load_registry from ..host_loop_activation import normalize_agent_type from ..registry import registry_goals @@ -274,7 +275,11 @@ def zcode_goal_operation( request["task_body"] = _heartbeat_task(binding, loopx_command) if action in {"bind", "start", "resume"}: request["goal_basis"] = _goal_basis(binding) - payload = _run_json([node, "--experimental-strip-types", str(Path(__file__).with_name("cli.ts"))], project=binding["project"], request=request) + payload = _run_json( + [node, "--experimental-strip-types", *node_typescript_flags(), str(Path(__file__).with_name("cli.ts"))], + project=binding["project"], + request=request, + ) for key in ("goal_id", "goal_ref", "goal_creation_operation_id", "agent_id"): if key not in payload or payload[key] != binding[key]: raise ZCodeGoalBridgeError("ZCode readback did not match the exact Goal and Agent requested.", code="zcode_goal_invalid_readback", status=409) diff --git a/loopx/zcode_goal_mode/cli.ts b/loopx/zcode_goal_mode/cli.ts index e61392c360..29b837504f 100644 --- a/loopx/zcode_goal_mode/cli.ts +++ b/loopx/zcode_goal_mode/cli.ts @@ -11,6 +11,7 @@ import {ZCODE_GOAL_ACTIONS, isGoalBasis, sameBinding, ZCodeGoalError, safeFailur import {NativeGoalController, readState, atomicState, type BindingState} from "./runtime.ts"; import {ZCodeAppServer} from "./app-server.ts"; import {acquireFileMutationLock, releaseFileMutationLock, durableWriteJson} from "../control_plane/effect_runtime_io.ts"; +import {nodeTypescriptFlags} from "../control_plane/runtime/node_version.ts"; const MAX_INPUT = 64 * 1024; const MAX_RESPONSE = 1024 * 1024; @@ -153,7 +154,7 @@ async function serve(request: NativeRequest): Promise { const storage = request.state_path + ".host"; await mkdir(storage, {recursive: true, mode: 0o700}); const guardedCommand = [process.execPath, "--no-warnings", "--experimental-strip-types", - fileURLToPath(new URL("./guard.ts", import.meta.url)), "--", ...selected.cli_command]; + ...nodeTypescriptFlags(), fileURLToPath(new URL("./guard.ts", import.meta.url)), "--", ...selected.cli_command]; const host = new ZCodeAppServer(guardedCommand, selected.project, { ...process.env, ZCODE_STORAGE_DIR: storage, ZCODE_DATA_BASE_DIR: storage, ZCODE_SESSION_DB_PATH: join(storage, "sessions.db"), }, {guardian: true, onExit: () => {void shutdown();}}); @@ -272,7 +273,7 @@ async function dispatch(request: NativeRequest): Promise { if (!state && !request.cli_command) throw new ZCodeGoalError("ZCode CLI was not found"); await validate(request, ["pause", "stop"].includes(request.action)); const child = spawn(process.execPath, ["--no-warnings", "--experimental-strip-types", - fileURLToPath(import.meta.url), "--serve"], {cwd: request.project, detached: true, + ...nodeTypescriptFlags(), fileURLToPath(import.meta.url), "--serve"], {cwd: request.project, detached: true, windowsHide: true, stdio: ["pipe", "ignore", "ignore"], env: process.env}); child.on("error", () => {}); child.stdin!.end(JSON.stringify(request)); diff --git a/packages/dsh-loopx-plugin/README.md b/packages/dsh-loopx-plugin/README.md index f6815f202a..64e04fe886 100644 --- a/packages/dsh-loopx-plugin/README.md +++ b/packages/dsh-loopx-plugin/README.md @@ -261,12 +261,20 @@ For every DSH plugin release: or configured trusted publishing belongs to the release operator. For token-free CI publication, configure the package's npm Trusted Publisher - with organization `loopx-project`, repository `loopx`, and workflow filename - `dsh-plugin-publish.yml`, permitting `npm publish`. Then dispatch **Publish + on `https://www.npmjs.com/package/dsh-loopx-plugin/access` with provider + `GitHub Actions`, organization `loopx-project`, repository `loopx`, workflow + filename `dsh-plugin-publish.yml`, blank `Environment name`, and **`Allow npm publish`** + checked (default stage-only mode rejects direct `npm publish`). + Because npm rejects Trusted Publisher creation before a package exists (`HTTP + 404` catch-22), enable `auth-and-writes` 2FA on the npm account first, run a + one-time web-auth `npm publish --access public --tag latest + --ignore-scripts` against the exact GitHub Release tarball, then immediately + `npm logout` before binding Trusted Publishing. Dispatch **Publish DSH Plugin to npm** on the existing published plugin tag or on `main`, using that same tag for the `release_tag` input. Dispatching from `main` still - checks out `refs/tags/` so the artifact commit and npm - provenance stay pinned to the immutable tag. + checks out `refs/tags/` (while refreshing + `scripts/verify-distribution.mjs` from `origin/main` when present) so the + artifact commit and npm provenance stay pinned to the immutable tag. The workflow requires a merged tag, consumes its GitHub asset without rebuilding, and verifies npm bytes and discovery. It neither creates a GitHub release nor replaces npm account ownership or the release guide gate. diff --git a/packages/dsh-loopx-plugin/scripts/verify-distribution.mjs b/packages/dsh-loopx-plugin/scripts/verify-distribution.mjs index 2d672f4bbd..affdf37bcf 100644 --- a/packages/dsh-loopx-plugin/scripts/verify-distribution.mjs +++ b/packages/dsh-loopx-plugin/scripts/verify-distribution.mjs @@ -13,12 +13,22 @@ const manifest = JSON.parse(await readFile(join(packageRoot, 'package.json'), 'u const args = process.argv.slice(2) let tarball let registry = 'https://registry.npmjs.org/' +let searchTimeoutMs = 45_000 +let searchPollMs = 3_000 for (let index = 0; index < args.length; index += 2) { const [flag, value] = args.slice(index, index + 2) - assert(value && (flag === '--tarball' || flag === '--registry'), - 'usage: verify-distribution.mjs --tarball PATH [--registry URL]') + assert( + value && (flag === '--tarball' || flag === '--registry' || flag === '--search-timeout-ms' || flag === '--search-poll-ms'), + 'usage: verify-distribution.mjs --tarball PATH [--registry URL] [--search-timeout-ms MS] [--search-poll-ms MS]', + ) if (flag === '--tarball') tarball = resolve(value) - else registry = `${value.replace(/\/+$/u, '')}/` + else if (flag === '--registry') registry = `${value.replace(/\/+$/u, '')}/` + else { + const parsed = Number(value) + assert(Number.isFinite(parsed) && parsed >= 0, `${flag} must be a non-negative number`) + if (flag === '--search-timeout-ms') searchTimeoutMs = parsed + else searchPollMs = parsed + } } assert(tarball, '--tarball is required: compare the exact package approved for publication') @@ -28,6 +38,10 @@ async function json(path) { return response.json() } +function repoSlug(url) { + return String(url ?? '').replace(/^git\+/u, '').replace(/\.git$/u, '').toLowerCase() +} + const published = await json(encodeURIComponent(manifest.name)) const version = published.versions?.[manifest.version] assert(version, `registry has no ${manifest.name}@${manifest.version}`) @@ -46,16 +60,48 @@ assert.equal(`sha512-${createHash('sha512').update(Buffer.from(await remote.arra integrity, 'downloaded registry artifact differs from the approved tarball') const repo = new URL(manifest.repository.url.replace(/^git\+/u, '').replace(/\.git$/u, '')).pathname.slice(1) -const search = await json(`-/v1/search?text=${encodeURIComponent(`repository:${repo}`)}&size=250`) -// Match the market's repository-and-keyword discovery contract, independently -// of the package name appearing in an unrelated search result. -const candidates = (search.objects ?? []).filter(({ package: pkg }) => - typeof pkg?.name === 'string' - && String(pkg.repository?.url ?? pkg.links?.repository ?? '').toLowerCase() - .includes(`github.com/${repo}`.toLowerCase())) -const selected = candidates.find(({ package: pkg }) => - pkg.keywords?.some(keyword => typeof keyword === 'string' && keyword.toLowerCase() === 'dsh-plugin')) - ?? candidates[0] +const maintainers = [...new Set( + [...(published.maintainers ?? []), ...(version.maintainers ?? [])] + .map(entry => (typeof entry === 'string' ? entry : entry?.name ?? entry?.username)) + .filter(name => typeof name === 'string' && name.length > 0), +)].slice(0, 5) +const searchQueries = [`repository:${repo}`, ...maintainers.map(name => `maintainer:${name}`)] + +async function searchRepositoryCandidates() { + const merged = [] + const seen = new Set() + for (const query of searchQueries) { + const search = await json(`-/v1/search?text=${encodeURIComponent(query)}&size=250`) + for (const item of search.objects ?? []) { + const pkgName = item?.package?.name + if (typeof pkgName !== 'string' || seen.has(pkgName)) continue + seen.add(pkgName) + merged.push(item) + } + } + return merged.filter(({ package: pkg }) => + repoSlug(pkg.repository?.url ?? pkg.links?.repository).includes(`github.com/${repo.toLowerCase()}`)) +} + +function selectPluginCandidate(candidates) { + return candidates.find(({ package: pkg }) => + pkg.keywords?.some(keyword => typeof keyword === 'string' && keyword.toLowerCase() === 'dsh-plugin')) + ?? candidates[0] +} + +// Match the market's repository-and-keyword discovery contract while retrying +// brief npm OpenSearch indexing delays (including while other repository +// packages are indexed first) and falling back to maintainer queries because +// npm's public search API does not restrict repository: qualifiers. +const deadline = Date.now() + searchTimeoutMs +let candidates = await searchRepositoryCandidates() +let selected = selectPluginCandidate(candidates) +while (selected?.package.name !== manifest.name && Date.now() < deadline) { + const delayMs = Math.min(searchPollMs, Math.max(0, deadline - Date.now())) + if (delayMs > 0) await new Promise(resolveDelay => setTimeout(resolveDelay, delayMs)) + candidates = await searchRepositoryCandidates() + selected = selectPluginCandidate(candidates) +} assert.equal(selected?.package.name, manifest.name, 'DSH Hub repository search does not yet select this plugin; publication is not marketplace-ready') process.stdout.write(`verified ${manifest.name}@${manifest.version}: latest, artifact integrity, repository discovery\n`) diff --git a/packages/dsh-loopx-plugin/smoke/dsh-registry-smoke.mjs b/packages/dsh-loopx-plugin/smoke/dsh-registry-smoke.mjs index 2aa14ae4ca..b7cbba2e76 100644 --- a/packages/dsh-loopx-plugin/smoke/dsh-registry-smoke.mjs +++ b/packages/dsh-loopx-plugin/smoke/dsh-registry-smoke.mjs @@ -38,18 +38,31 @@ const metadata = { ...manifest, dist: { integrity: `sha512-${createHash('sha512').update(bytes).digest('base64')}` }, } +let repositorySearchObjects = searchObjects +let maintainerSearchObjects = [] +let delayedRepoSearchAttemptsRemaining = 0 const server = createServer((request, response) => { const url = new URL(request.url, registry) requested.add(url.pathname) if (url.pathname === `/${manifest.name}`) { response.setHeader('Content-Type', 'application/json') - response.end(JSON.stringify({ name: manifest.name, + response.end(JSON.stringify({ name: manifest.name, maintainers: [{ name: 'fixture-maintainer' }], 'dist-tags': distTags, versions: { [manifest.version]: metadata } })) } else if (url.pathname === '/artifact.tgz') { response.end(bytes) } else if (url.pathname === '/-/v1/search') { response.setHeader('Content-Type', 'application/json') - response.end(JSON.stringify({ objects: searchObjects })) + const query = url.searchParams.get('text') ?? '' + let objects + if (query.startsWith('maintainer:')) { + objects = maintainerSearchObjects + } else if (delayedRepoSearchAttemptsRemaining > 0) { + delayedRepoSearchAttemptsRemaining -= 1 + objects = [searchObjects[1]] + } else { + objects = repositorySearchObjects + } + response.end(JSON.stringify({ objects })) } else { // DSH still resolves its own real host dependencies through the registry. // Their metadata is not simulated by this package-distribution test. @@ -106,18 +119,31 @@ try { assert((await readFile(join(dirname(installedManifest), entry.default))) .equals(await readFile(join(packageRoot, entry.default))), `installed ${entry.default} differs from the build`) } + // Live npmjs tokenizes repository: broadly so zero-score prereleases can fall + // past rank 250; verify the maintainer: fallback finds the package too. + repositorySearchObjects = [searchObjects[0]] + maintainerSearchObjects = [searchObjects[2]] + await run(process.execPath, [join(packageRoot, 'scripts', 'verify-distribution.mjs'), + '--tarball', tarball, '--registry', registry, '--search-timeout-ms', '0']) + // Retry until the plugin itself appears even when non-plugin packages under + // the same repository are already indexed on early search polls. + delayedRepoSearchAttemptsRemaining = 1 + maintainerSearchObjects = [] + repositorySearchObjects = searchObjects + await run(process.execPath, [join(packageRoot, 'scripts', 'verify-distribution.mjs'), + '--tarball', tarball, '--registry', registry, '--search-timeout-ms', '2000', '--search-poll-ms', '50']) // Existing publication metadata cannot hide a wrong tag or discovery target. distTags.latest = '0.0.0' await assert.rejects(run(process.execPath, [join(packageRoot, 'scripts', 'verify-distribution.mjs'), - '--tarball', tarball, '--registry', registry]), /latest must name the qualified release/u) + '--tarball', tarball, '--registry', registry, '--search-timeout-ms', '0']), /latest must name the qualified release/u) distTags.latest = manifest.version searchObjects.unshift({ package: { name: 'other-plugin', keywords: ['dsh-plugin'], links: { repository: manifest.repository.url } } }) await assert.rejects(run(process.execPath, [join(packageRoot, 'scripts', 'verify-distribution.mjs'), - '--tarball', tarball, '--registry', registry]), /repository search does not yet select this plugin/u) + '--tarball', tarball, '--registry', registry, '--search-timeout-ms', '0']), /repository search does not yet select this plugin/u) searchObjects.shift() metadata.dist.integrity = 'sha512-unqualified' await assert.rejects(run(process.execPath, [join(packageRoot, 'scripts', 'verify-distribution.mjs'), - '--tarball', tarball, '--registry', registry]), /registry integrity differs/u) + '--tarball', tarball, '--registry', registry, '--search-timeout-ms', '0']), /registry integrity differs/u) await runDsh(['plugin', '--profile', 'web', 'remove', manifest.name]) const removed = await runDsh(['--profile', 'web', '--dump-config']) assert(!removed.includes('name: dsh-loopx-plugin'), 'removal retained a plugin row') diff --git a/scripts/dashboard-dev.sh b/scripts/dashboard-dev.sh index c6a445ccf0..fdf7812394 100755 --- a/scripts/dashboard-dev.sh +++ b/scripts/dashboard-dev.sh @@ -18,7 +18,15 @@ if [[ "${LOOPX_ENABLE_GOAL_SUBAGENT_CONFIGURATION:-0}" = "1" ]]; then fi node_is_supported() { - "$1" --no-warnings --experimental-strip-types --input-type=module -e ' + local node_ts_flags=() + if [[ "$(uname -s 2>/dev/null || true)" == Linux* ]]; then + case "$(uname -m 2>/dev/null || true)" in + x86_64|amd64) + node_ts_flags=(--liftoff-only --no-wasm-tier-up --no-wasm-dynamic-tiering) + ;; + esac + fi + "$1" --no-warnings --experimental-strip-types ${node_ts_flags[@]+"${node_ts_flags[@]}"} --input-type=module -e ' import { pathToFileURL } from "node:url"; const { isSupportedNodeVersion } = await import(pathToFileURL(process.argv[1]).href); process.exit(isSupportedNodeVersion(process.versions.node) ? 0 : 1); diff --git a/scripts/loopx b/scripts/loopx index 57f5abd088..caf7d9b03a 100755 --- a/scripts/loopx +++ b/scripts/loopx @@ -71,7 +71,15 @@ if [[ "$loopx_command" == "quota" \ exit 2 fi export LOOPX_RELEASE_ROOT="$repo_root" - exec node --no-warnings --experimental-strip-types "$native_scheduler_entry" "$@" + node_ts_flags=() + if [[ "$(uname -s 2>/dev/null || true)" == Linux* ]]; then + case "$(uname -m 2>/dev/null || true)" in + x86_64|amd64) + node_ts_flags=(--liftoff-only --no-wasm-tier-up --no-wasm-dynamic-tiering) + ;; + esac + fi + exec node --no-warnings --experimental-strip-types ${node_ts_flags[@]+"${node_ts_flags[@]}"} "$native_scheduler_entry" "$@" fi # Codex host-match ACKs need the entrypoint's fresh App read before TS commit. diff --git a/scripts/qualify_release_commit.py b/scripts/qualify_release_commit.py index b9e57816f8..9209b7ce91 100644 --- a/scripts/qualify_release_commit.py +++ b/scripts/qualify_release_commit.py @@ -99,8 +99,15 @@ def _load_pytest_norecursedirs(repo_root: Path) -> tuple[str, ...]: return tuple(patterns) +def _normalize_rel_path(raw: str) -> str: + normalized = raw.replace("\\", "/") + while normalized.startswith("./"): + normalized = normalized[2:] + return normalized.lstrip("/") + + def _is_excluded_by_norecursedirs(rel_path: str, patterns: Sequence[str]) -> bool: - normalized = rel_path.replace("\\", "/").lstrip("./").strip("/") + normalized = _normalize_rel_path(rel_path).strip("/") if not normalized or not patterns: return False parts = Path(normalized).parent.parts @@ -130,7 +137,7 @@ def select_preflight_tests( seen: set[str] = set() def add(rel_path: str) -> None: - normalized = rel_path.replace("\\", "/").lstrip("./") + normalized = _normalize_rel_path(rel_path) if normalized in seen or _is_excluded_by_norecursedirs(normalized, norecursedirs): return if (repo_root / normalized).is_file(): @@ -138,10 +145,12 @@ def add(rel_path: str) -> None: selected.append(normalized) for raw in changed_paths: - rel = raw.replace("\\", "/").lstrip("./") - if not rel or _is_excluded_by_norecursedirs(rel, norecursedirs): + rel = _normalize_rel_path(raw) + if not rel: continue if _is_direct_test_path(rel): + if _is_excluded_by_norecursedirs(rel, norecursedirs): + continue add(rel) if any(rel.startswith(prefix) for prefix in _PUBLIC_SAFETY_SURFACE_PREFIXES): for test_path in _PUBLIC_SAFETY_TESTS: @@ -162,6 +171,19 @@ def add(rel_path: str) -> None: add("tests/control_plane/test_actual_default_model_behavior_live.py") if rel == "pyproject.toml": add("tests/test_python_ci_workflow.py") + if rel.startswith("packages/dsh-loopx-plugin/") or rel in { + ".github/workflows/dsh-plugin.yml", + ".github/workflows/dsh-plugin-publish.yml", + }: + add("tests/test_dsh_plugin_publish_workflow.py") + if rel.startswith(("scripts/desktop_", ".github/workflows/desktop-")): + add("tests/desktop/test_desktop_signing_workflow.py") + add("tests/desktop/test_update_feed.py") + if rel in { + "scripts/release_multi_surface_preflight.py", + "docs/product/release-readiness.md", + }: + add("tests/control_plane/test_release_multi_surface_preflight.py") if rel.endswith(".py") and rel.startswith(("loopx/", "scripts/")): stem = Path(rel).stem if stem != "__init__" and len(stem) >= 4: diff --git a/scripts/release_multi_surface_preflight.py b/scripts/release_multi_surface_preflight.py new file mode 100644 index 0000000000..d4e9f45d2c --- /dev/null +++ b/scripts/release_multi_surface_preflight.py @@ -0,0 +1,837 @@ +#!/usr/bin/env python3 +"""Preflight and readback checks across LoopX's four release surfaces. + +Covers core CLI/PyPI, Desktop App/Tauri updater, DSH plugin/npm/awesome-dsh, +and bilingual release notes + Feishu guide without importing the candidate +``loopx`` package. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import runpy +import shutil +import subprocess +import time +import tomllib +import urllib.error +import urllib.parse +import urllib.request +from pathlib import Path +from typing import Any, Callable + +SCHEMA_VERSION = "loopx_multi_surface_release_preflight_v1" +ALL_SURFACES: tuple[str, ...] = ("core", "desktop", "dsh", "notes") +DEFAULT_AWESOME_DSH_REPO = "awesome-dsh-plugin/awesome-dsh-plugin" +DEFAULT_GITHUB_REPO = "loopx-project/loopx" +FORBIDDEN_NOTE_PATTERNS: tuple[str, ...] = ( + "/Users/", + "/private/tmp/", + "OPENAI_API_KEY", + "ANTHROPIC_API_KEY", + "raw_thread", + "session_history", + "verifier_output_tail", + "ACTIVE_GOAL_STATE.md:", +) + + +def _run_git(repo_root: Path, *args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + ["git", "-C", str(repo_root), *args], + check=False, + capture_output=True, + text=True, + ) + + +def _http_get_text(url: str, *, timeout: float = 15.0, attempts: int = 2) -> tuple[int | None, str, str | None]: + last_err: str | None = None + for attempt in range(max(1, attempts)): + req = urllib.request.Request(url, headers={"User-Agent": "loopx-release-preflight/1.0"}) + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + return int(resp.status), resp.read().decode("utf-8", errors="replace"), None + except urllib.error.HTTPError as exc: + body = exc.read().decode("utf-8", errors="replace") if exc.fp is not None else "" + return int(exc.code), body, f"HTTP {exc.code}" + except Exception as exc: + last_err = str(exc) + if attempt + 1 < attempts: + time.sleep(0.5) + return None, "", last_err + + +def _gh_release_view(github_repo: str, tag: str) -> dict[str, Any]: + if not shutil.which("gh"): + return {"available": False, "error": "gh CLI not found"} + proc = subprocess.run( + [ + "gh", + "release", + "view", + tag, + "--repo", + github_repo, + "--json", + "tagName,isDraft,isPrerelease,targetCommitish,body,assets", + ], + check=False, + capture_output=True, + text=True, + ) + if proc.returncode != 0: + return { + "available": True, + "exists": False, + "error": (proc.stderr or proc.stdout).strip() or f"exit {proc.returncode}", + } + try: + payload = json.loads(proc.stdout) + except json.JSONDecodeError as exc: + return {"available": True, "exists": False, "error": f"invalid gh json: {exc}"} + assets = [ + { + "name": item.get("name"), + "size": item.get("size"), + "url": item.get("url"), + } + for item in (payload.get("assets") or []) + if isinstance(item, dict) + ] + return { + "available": True, + "exists": True, + "tag_name": payload.get("tagName"), + "is_draft": payload.get("isDraft"), + "is_prerelease": payload.get("isPrerelease"), + "body": str(payload.get("body") or ""), + "asset_names": sorted(a["name"] for a in assets if isinstance(a.get("name"), str)), + "assets": assets, + } + + +def _load_core_metadata(repo_root: Path) -> dict[str, str]: + metadata_script = repo_root / "loopx" / "control_plane" / "testing" / "release_metadata.py" + if not metadata_script.is_file(): + raise ValueError(f"missing static metadata reader: {metadata_script}") + ns = runpy.run_path(str(metadata_script)) + return dict(ns["checkout_release_metadata"](repo_root)) + + +def _check_core( + repo_root: Path, + *, + core_meta: dict[str, str], + github_repo: str, + online: bool, + require_clean: bool, + http_get: Callable[[str], tuple[int | None, str, str | None]], + gh_release: Callable[[str, str], dict[str, Any]], +) -> tuple[dict[str, Any], list[dict[str, str]]]: + remediations: list[dict[str, str]] = [] + version = core_meta["version"] + expected_tag = f"v{version}" + head = _run_git(repo_root, "rev-parse", "HEAD") + head_sha = head.stdout.strip() if head.returncode == 0 else None + + status = _run_git(repo_root, "status", "--porcelain", "--untracked-files=no") + tracked_clean = status.returncode == 0 and not status.stdout.strip() + + stable_ref = _run_git(repo_root, "rev-parse", "--verify", "origin/stable") + stable_sha = stable_ref.stdout.strip() if stable_ref.returncode == 0 else None + stable_is_ancestor: bool | None = None + if stable_sha and head_sha: + anc = _run_git(repo_root, "merge-base", "--is-ancestor", stable_sha, head_sha) + stable_is_ancestor = anc.returncode == 0 + + manpage_exists = (repo_root / "man" / "loopx.1").is_file() + local_ok = bool(version) and manpage_exists and (stable_is_ancestor is not False) and ( + not require_clean or tracked_clean + ) + if not tracked_clean: + remediations.append( + { + "surface": "core", + "code": "dirty_tracked_tree", + "action": "Commit or isolate changes in a clean worktree before qualifying or tagging a release.", + } + ) + if not manpage_exists: + remediations.append( + { + "surface": "core", + "code": "missing_manpage", + "action": "Run scripts/render-manpage.py --output man/loopx.1 and examples/cli-help-manpage-smoke.py.", + } + ) + if stable_is_ancestor is False: + remediations.append( + { + "surface": "core", + "code": "stable_not_ancestor", + "action": "Reconcile divergent origin/stable history through a reviewed merge PR before tagging.", + } + ) + + surface: dict[str, Any] = { + "local_ok": local_ok, + "published_ok": None, + "package_name": core_meta["name"], + "version": version, + "expected_tag": expected_tag, + "head_commit": head_sha, + "tracked_clean": tracked_clean, + "origin_stable_commit": stable_sha, + "stable_is_ancestor_of_head": stable_is_ancestor, + "manpage_present": manpage_exists, + } + if online: + gh_info = gh_release(github_repo, expected_tag) + asset_names = set(gh_info.get("asset_names") or []) + expected_whl = f"loopx-{version}-py3-none-any.whl" + expected_sdist = f"loopx-{version}.tar.gz" + github_release_ok = bool( + gh_info.get("exists") + and gh_info.get("is_draft") is False + and expected_whl in asset_names + and expected_sdist in asset_names + and "SHA256SUMS" in asset_names + ) + + code, body, err = http_get(f"https://pypi.org/pypi/{urllib.parse.quote(core_meta['name'])}/json") + pypi_has_version = False + if code == 200 and body: + try: + pypi_data = json.loads(body) + pypi_has_version = version in (pypi_data.get("releases") or {}) + except json.JSONDecodeError: + err = "invalid PyPI json" + surface["online"] = { + "github_release": { + "exists": bool(gh_info.get("exists")), + "is_draft": gh_info.get("is_draft"), + "expected_assets_present": github_release_ok, + "error": gh_info.get("error"), + }, + "pypi": { + "http_status": code, + "version_present": pypi_has_version, + "error": err, + }, + } + surface["published_ok"] = github_release_ok and pypi_has_version + if not github_release_ok: + remediations.append( + { + "surface": "core", + "code": "github_core_release_incomplete", + "action": f"Publish non-draft tag {expected_tag} via release-artifacts.yml with wheel, sdist, and SHA256SUMS.", + } + ) + if not pypi_has_version: + remediations.append( + { + "surface": "core", + "code": "pypi_version_missing", + "action": f"Verify PYPI_PUBLISH_ENABLED=true and PyPI Trusted Publisher for loopx=={version}.", + } + ) + return surface, remediations + + +def _check_desktop( + repo_root: Path, + *, + core_version: str, + github_repo: str, + online: bool, + http_get: Callable[[str], tuple[int | None, str, str | None]], + gh_release: Callable[[str, str], dict[str, Any]], +) -> tuple[dict[str, Any], list[dict[str, str]]]: + remediations: list[dict[str, str]] = [] + desktop_root = repo_root / "apps" / "desktop" / "loopx-control-plane" + pkg_path = desktop_root / "package.json" + tauri_path = desktop_root / "src-tauri" / "tauri.conf.json" + cargo_path = desktop_root / "src-tauri" / "Cargo.toml" + signing_script = repo_root / "scripts" / "desktop_macos_signing.py" + artifacts_script = repo_root / "scripts" / "desktop_release_artifacts.py" + + missing_files = [ + str(p.relative_to(repo_root)) + for p in (pkg_path, tauri_path, cargo_path, signing_script, artifacts_script) + if not p.is_file() + ] + tauri_ok = False + updater_endpoints: list[str] = [] + updater_pubkey_present = False + tauri_version: str | None = None + cargo_version: str | None = None + expected_assets: list[str] = [] + + if tauri_path.is_file(): + tauri_cfg = json.loads(tauri_path.read_text(encoding="utf-8")) + tauri_version = tauri_cfg.get("version") + updater = ((tauri_cfg.get("plugins") or {}).get("updater") or {}) + pubkey = updater.get("pubkey") + endpoints = updater.get("endpoints") + updater_pubkey_present = isinstance(pubkey, str) and bool(pubkey.strip()) + if isinstance(endpoints, list): + updater_endpoints = [str(e) for e in endpoints if isinstance(e, str)] + tauri_ok = bool(updater_pubkey_present and updater_endpoints) + + if cargo_path.is_file(): + cargo_data = tomllib.loads(cargo_path.read_text(encoding="utf-8")) + cargo_version = (cargo_data.get("package") or {}).get("version") + + if artifacts_script.is_file(): + ns = runpy.run_path(str(artifacts_script)) + expected_assets = list(ns["expected_artifact_names"](core_version)) + + local_ok = not missing_files and tauri_ok and bool(expected_assets) + if not local_ok: + remediations.append( + { + "surface": "desktop", + "code": "desktop_config_incomplete", + "action": "Check tauri.conf.json updater pubkey/endpoints and scripts/desktop_release_artifacts.py.", + } + ) + + surface: dict[str, Any] = { + "local_ok": local_ok, + "published_ok": None, + "tauri_config_version": tauri_version, + "cargo_version": cargo_version, + "release_tag_version": core_version, + "updater_pubkey_present": updater_pubkey_present, + "updater_endpoints": updater_endpoints, + "expected_installer_assets": expected_assets, + "missing_files": missing_files, + } + if online: + expected_tag = f"v{core_version}" + gh_info = gh_release(github_repo, expected_tag) + asset_names = set(gh_info.get("asset_names") or []) + present_assets = [name for name in expected_assets if name in asset_names] + missing_assets = [name for name in expected_assets if name not in asset_names] + checksum_present = "DESKTOP-SHA256SUMS" in asset_names + updater_info = gh_release(github_repo, "desktop-stable") + updater_assets = set(updater_info.get("asset_names") or []) + updater_assets_present = bool( + updater_info.get("exists") + and "desktop-updater.json" in updater_assets + and "desktop-updater.json" in asset_names + and "LoopX.app.tar.gz" in asset_names + and "LoopX.app.tar.gz.sig" in asset_names + ) + feed_url = f"https://github.com/{github_repo}/releases/download/desktop-stable/desktop-updater.json" + feed_code, feed_body, feed_err = http_get(feed_url) + feed_version: str | None = None + feed_platforms_non_empty = False + if feed_code == 200 and feed_body: + try: + feed_payload = json.loads(feed_body) + if isinstance(feed_payload, dict): + raw_ver = feed_payload.get("version") + feed_version = str(raw_ver) if isinstance(raw_ver, str) else None + platforms = feed_payload.get("platforms") + feed_platforms_non_empty = isinstance(platforms, dict) and bool(platforms) + except json.JSONDecodeError as exc: + feed_err = f"invalid updater json: {exc}" + updater_feed_ok = bool( + updater_assets_present and feed_code == 200 and feed_platforms_non_empty and feed_version == core_version + ) + surface["online"] = { + "release_tag": expected_tag, + "present_installer_assets": present_assets, + "missing_installer_assets": missing_assets, + "checksum_manifest_present": checksum_present, + "desktop_stable_feed_ok": updater_feed_ok, + "updater_feed_version": feed_version, + "updater_feed_http_status": feed_code, + "updater_feed_error": feed_err, + } + surface["published_ok"] = ( + bool(gh_info.get("exists")) + and not missing_assets + and checksum_present + and updater_feed_ok + ) + if missing_assets or not checksum_present: + remediations.append( + { + "surface": "desktop", + "code": "desktop_release_assets_incomplete", + "action": f"Dispatch desktop-release-artifacts.yml for tag {expected_tag} (missing: {missing_assets}).", + } + ) + if not updater_assets_present or feed_code != 200 or not feed_platforms_non_empty: + remediations.append( + { + "surface": "desktop", + "code": "desktop_updater_feed_incomplete", + "action": "Verify desktop-updater.yml published desktop-updater.json under desktop-stable and LoopX.app.tar.gz(.sig) + desktop-updater.json under the versioned release tag.", + } + ) + elif feed_version != core_version: + remediations.append( + { + "surface": "desktop", + "code": "desktop_updater_feed_version_mismatch", + "action": f"Refresh desktop-stable/desktop-updater.json so version {feed_version!r} matches {core_version!r}.", + } + ) + return surface, remediations + + +def _check_dsh( + repo_root: Path, + *, + github_repo: str, + awesome_repo: str, + online: bool, + http_get: Callable[[str], tuple[int | None, str, str | None]], + gh_release: Callable[[str, str], dict[str, Any]], +) -> tuple[dict[str, Any], list[dict[str, str]]]: + remediations: list[dict[str, str]] = [] + dsh_root = repo_root / "packages" / "dsh-loopx-plugin" + pkg_path = dsh_root / "package.json" + lock_path = dsh_root / "pnpm-lock.yaml" + if not pkg_path.is_file(): + return { + "local_ok": False, + "published_ok": None, + "error": "missing packages/dsh-loopx-plugin/package.json", + }, [ + { + "surface": "dsh", + "code": "dsh_package_missing", + "action": "Restore packages/dsh-loopx-plugin/package.json.", + } + ] + + pkg = json.loads(pkg_path.read_text(encoding="utf-8")) + name = str(pkg.get("name") or "") + version = str(pkg.get("version") or "") + expected_tag = f"{name}-v{version}" + expected_tarball_name = f"{name}-{version}.tgz" + expected_tarball_url = ( + f"https://github.com/{github_repo}/releases/download/{expected_tag}/{expected_tarball_name}" + ) + keywords = pkg.get("keywords") or [] + patch_rel = str(((pkg.get("dsh") or {}).get("bundle") or {}).get("patch") or "") + patch_ok = bool(patch_rel) and (dsh_root / patch_rel).is_file() + lock_ok = lock_path.is_file() + has_dsh_keyword = isinstance(keywords, list) and "dsh-plugin" in keywords + local_ok = bool(name and version and patch_ok and lock_ok and has_dsh_keyword) + if not local_ok: + remediations.append( + { + "surface": "dsh", + "code": "dsh_manifest_incomplete", + "action": "Verify package name/version, dsh-plugin keyword, cordis.patch.yml, and pnpm-lock.yaml.", + } + ) + + surface: dict[str, Any] = { + "local_ok": local_ok, + "published_ok": None, + "package_name": name, + "version": version, + "expected_tag": expected_tag, + "expected_tarball_name": expected_tarball_name, + "expected_tarball_url": expected_tarball_url, + "has_dsh_plugin_keyword": has_dsh_keyword, + "patch_present": patch_ok, + "pnpm_lock_present": lock_ok, + } + if online: + gh_info = gh_release(github_repo, expected_tag) + asset_names = set(gh_info.get("asset_names") or []) + gh_tarball_ok = bool(gh_info.get("exists") and expected_tarball_name in asset_names) + + npm_code, npm_body, npm_err = http_get(f"https://registry.npmjs.org/{urllib.parse.quote(name)}") + npm_state = "error" + latest_tag: str | None = None + npm_has_version = False + npm_maintainers: list[str] = [] + if npm_code == 404: + npm_state = "bootstrap_required" + elif npm_code == 200 and npm_body: + try: + npm_data = json.loads(npm_body) + versions = list((npm_data.get("versions") or {}).keys()) + latest_tag = (npm_data.get("dist-tags") or {}).get("latest") + npm_has_version = version in versions + npm_maintainers = [ + str(m.get("name") or m.get("username")) + for m in (npm_data.get("maintainers") or []) + if isinstance(m, dict) and (m.get("name") or m.get("username")) + ] + if versions == ["0.0.0-stage"]: + npm_state = "staging_scan_in_progress" + elif npm_has_version and latest_tag == version: + npm_state = "published" + else: + npm_state = "tag_or_version_mismatch" + except json.JSONDecodeError: + npm_err = "invalid npm json" + + cat_url = ( + f"https://raw.githubusercontent.com/{awesome_repo}/main/data/plugins/" + f"loopx-project__loopx--packages-dsh-loopx-plugin.yml" + ) + cat_code, cat_body, cat_err = http_get(cat_url) + cat_match = re.search(r"^tarball:\s*(.+)$", cat_body, flags=re.MULTILINE) if cat_code == 200 else None + catalog_tarball = cat_match.group(1).strip() if cat_match else None + catalog_ok = catalog_tarball == expected_tarball_url + + surface["online"] = { + "github_release": { + "exists": bool(gh_info.get("exists")), + "tarball_present": gh_tarball_ok, + "error": gh_info.get("error"), + }, + "npm": { + "state": npm_state, + "http_status": npm_code, + "latest_dist_tag": latest_tag, + "target_version_present": npm_has_version, + "maintainers": npm_maintainers, + "error": npm_err, + }, + "awesome_catalog": { + "http_status": cat_code, + "tarball": catalog_tarball, + "matches_expected_url": catalog_ok, + "error": cat_err, + }, + } + surface["published_ok"] = gh_tarball_ok and npm_state == "published" and catalog_ok + + if not gh_tarball_ok: + remediations.append( + { + "surface": "dsh", + "code": "dsh_github_release_missing", + "action": f"Publish GitHub Release {expected_tag} with {expected_tarball_name}.", + } + ) + if npm_state == "bootstrap_required": + remediations.append( + { + "surface": "dsh", + "code": "npm_bootstrap_required", + "action": ( + f"First-time npm bootstrap required for {name}: enable npm 2FA (auth-and-writes), " + f"run one-time web-auth 'npm publish {expected_tarball_name} --access public --tag latest --ignore-scripts', " + "run 'npm logout', then bind Trusted Publisher (loopx-project / loopx / dsh-plugin-publish.yml / " + "blank Environment name / check Allow npm publish)." + ), + } + ) + elif npm_state != "published": + remediations.append( + { + "surface": "dsh", + "code": f"npm_{npm_state}", + "action": ( + f"Dispatch dsh-plugin-publish.yml with release_tag={expected_tag} and verify Trusted Publisher " + "(Allow npm publish enabled) plus verify-distribution.mjs readback." + ), + } + ) + if not catalog_ok: + remediations.append( + { + "surface": "dsh", + "code": "awesome_catalog_stale", + "action": f"Update {awesome_repo} tarball URL to {expected_tarball_url}.", + } + ) + return surface, remediations + + +def _check_notes( + repo_root: Path, + *, + version: str, + github_repo: str, + online: bool, + gh_release: Callable[[str, str], dict[str, Any]], +) -> tuple[dict[str, Any], list[dict[str, str]]]: + remediations: list[dict[str, str]] = [] + note_rel = f"docs/product/releases/v{version}.md" + note_path = repo_root / note_rel + exists = note_path.is_file() + has_en_decision = False + has_zh_decision = False + boundary_hits: list[str] = [] + feishu_urls: list[str] = [] + + if exists: + text = note_path.read_text(encoding="utf-8") + has_en_decision = "## Release Decision" in text + has_zh_decision = "### 升级决策" in text + boundary_hits = [needle for needle in FORBIDDEN_NOTE_PATTERNS if needle in text] + feishu_urls = sorted(set(re.findall(r"https://[^\s)>\]]*feishu\.cn/docx/[A-Za-z0-9]+", text))) + readiness_doc = repo_root / "docs" / "product" / "release-readiness.md" + if not feishu_urls and readiness_doc.is_file(): + rtext = readiness_doc.read_text(encoding="utf-8") + marker = f"`v{version}` release" + idx = rtext.find(marker) + if idx >= 0: + snippet = rtext[idx : idx + 2000] + feishu_urls = sorted(set(re.findall(r"https://[^\s)>\]]*feishu\.cn/docx/[A-Za-z0-9]+", snippet))) + + local_ok = exists and has_en_decision and has_zh_decision and not boundary_hits + if not exists: + remediations.append( + { + "surface": "notes", + "code": "release_note_missing", + "action": f"Create {note_rel} from docs/product/release-note-template.md and validate via release-readiness-doc-smoke.py.", + } + ) + elif boundary_hits: + remediations.append( + { + "surface": "notes", + "code": "release_note_public_boundary_hit", + "action": f"Remove forbidden strings {boundary_hits} from {note_rel}.", + } + ) + elif not has_en_decision or not has_zh_decision: + remediations.append( + { + "surface": "notes", + "code": "release_note_bilingual_sections_incomplete", + "action": f"Ensure {note_rel} contains both '## Release Decision' and '### 升级决策'.", + } + ) + + surface: dict[str, Any] = { + "local_ok": local_ok, + "published_ok": None, + "release_note_path": note_rel, + "exists": exists, + "has_english_release_decision": has_en_decision, + "has_chinese_release_decision": has_zh_decision, + "public_boundary_clean": not boundary_hits, + "feishu_guide_urls": feishu_urls, + } + if online: + expected_tag = f"v{version}" + gh_info = gh_release(github_repo, expected_tag) + body = str(gh_info.get("body") or "") + release_exists = bool(gh_info.get("exists") and gh_info.get("is_draft") is False) + release_bilingual = "## Release Decision" in body and "### 升级决策" in body + release_boundary_hits = [needle for needle in FORBIDDEN_NOTE_PATTERNS if needle in body] + feishu_present = bool(feishu_urls) + release_links_feishu = feishu_present and all(url in body for url in feishu_urls) + release_notes_ok = ( + release_exists + and release_bilingual + and not release_boundary_hits + and release_links_feishu + ) + surface["online"] = { + "release_tag": expected_tag, + "release_exists": release_exists, + "release_has_bilingual_decisions": release_bilingual, + "release_public_boundary_clean": not release_boundary_hits, + "release_body_links_feishu": release_links_feishu, + "feishu_doc_verification": "requires_authenticated_lark_cli", + } + surface["published_ok"] = local_ok and release_notes_ok + if not feishu_present: + remediations.append( + { + "surface": "notes", + "code": "feishu_guide_link_missing", + "action": "Publish the companion Personal Feishu Release Guide and link its URL in bilingual sections.", + } + ) + if not (release_exists and release_bilingual and not release_boundary_hits and (not feishu_present or release_links_feishu)): + remediations.append( + { + "surface": "notes", + "code": "github_release_notes_incomplete", + "action": f"Publish non-draft {expected_tag} GitHub Release body containing bilingual decision sections, zero forbidden paths, and the Feishu guide link.", + } + ) + return surface, remediations + + +def run_preflight( + *, + repo_root: Path, + selected_surfaces: tuple[str, ...], + online: bool = False, + require_published: bool = False, + require_clean: bool = False, + github_repo: str = DEFAULT_GITHUB_REPO, + awesome_dsh_repo: str = DEFAULT_AWESOME_DSH_REPO, + http_get: Callable[[str], tuple[int | None, str, str | None]] = _http_get_text, + gh_release: Callable[[str, str], dict[str, Any]] = _gh_release_view, +) -> dict[str, Any]: + core_meta = _load_core_metadata(repo_root) + surfaces: dict[str, Any] = {} + remediations: list[dict[str, str]] = [] + + if "core" in selected_surfaces: + surf, rem = _check_core( + repo_root, + core_meta=core_meta, + github_repo=github_repo, + online=online, + require_clean=require_clean, + http_get=http_get, + gh_release=gh_release, + ) + surfaces["core"] = surf + remediations.extend(rem) + if "desktop" in selected_surfaces: + surf, rem = _check_desktop( + repo_root, + core_version=core_meta["version"], + github_repo=github_repo, + online=online, + http_get=http_get, + gh_release=gh_release, + ) + surfaces["desktop"] = surf + remediations.extend(rem) + if "dsh" in selected_surfaces: + surf, rem = _check_dsh( + repo_root, + github_repo=github_repo, + awesome_repo=awesome_dsh_repo, + online=online, + http_get=http_get, + gh_release=gh_release, + ) + surfaces["dsh"] = surf + remediations.extend(rem) + if "notes" in selected_surfaces: + surf, rem = _check_notes( + repo_root, + version=core_meta["version"], + github_repo=github_repo, + online=online, + gh_release=gh_release, + ) + surfaces["notes"] = surf + remediations.extend(rem) + + ready_for_local = all(bool(item.get("local_ok")) for item in surfaces.values()) + published_complete: bool | None = None + if online: + published_complete = all(bool(item.get("published_ok")) for item in surfaces.values()) + + ok = ready_for_local and (not require_published or bool(published_complete)) + return { + "ok": ok, + "schema_version": SCHEMA_VERSION, + "repo_root": repo_root.name, + "mode": "online" if online else "offline", + "selected_surfaces": list(selected_surfaces), + "ready_for_local_qualification": ready_for_local, + "published_complete": published_complete, + "surfaces": surfaces, + "remediations": remediations, + } + + +def render_markdown(payload: dict[str, Any]) -> str: + lines = [ + f"# Multi-Surface Release Preflight (`{payload['mode']}`)", + "", + f"- **Local qualification ready:** `{payload['ready_for_local_qualification']}`", + f"- **Published complete:** `{payload['published_complete']}`", + "", + "| Surface | Local | Published | Key Detail |", + "| --- | --- | --- | --- |", + ] + for name in payload["selected_surfaces"]: + item = payload["surfaces"][name] + detail = item.get("expected_tag") or item.get("release_note_path") or item.get("release_tag_version") or "" + if name == "dsh" and isinstance(item.get("online"), dict): + detail = f"{detail} (npm={item['online']['npm']['state']})" + lines.append(f"| `{name}` | `{item.get('local_ok')}` | `{item.get('published_ok')}` | `{detail}` |") + if payload["remediations"]: + lines.extend(["", "## Remediations", ""]) + for rem in payload["remediations"]: + lines.append(f"- **[{rem['surface']}] `{rem['code']}`:** {rem['action']}") + return "\n".join(lines) + "\n" + + +def _parse_surfaces(raw: list[str] | None) -> tuple[str, ...]: + if not raw or "all" in raw: + return ALL_SURFACES + seen: list[str] = [] + for item in raw: + if item not in seen: + seen.append(item) + return tuple(seen) + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--repo-root", type=Path, default=Path(__file__).resolve().parents[1]) + parser.add_argument( + "--surface", + action="append", + choices=("all", *ALL_SURFACES), + help="Target release surface to inspect (default: all).", + ) + parser.add_argument("--online", action="store_true", help="Probe GitHub Releases, PyPI, npmjs, and awesome-dsh-plugin.") + parser.add_argument( + "--require-published", + action="store_true", + help="Exit non-zero unless all selected surfaces are also verified published online (implies --online).", + ) + parser.add_argument( + "--require-clean", + action="store_true", + help="Fail local preflight when tracked repository files have uncommitted modifications.", + ) + parser.add_argument("--github-repo", default=DEFAULT_GITHUB_REPO) + parser.add_argument("--awesome-dsh-repo", default=DEFAULT_AWESOME_DSH_REPO) + parser.add_argument( + "--keep-proxy", + action="store_true", + help="Preserve ambient HTTP(S)_PROXY/ALL_PROXY environment variables instead of clearing them.", + ) + parser.add_argument("--format", choices=("json", "markdown"), default="markdown") + return parser + + +def main(argv: list[str] | None = None) -> int: + args = build_parser().parse_args(argv) + online = bool(args.online or args.require_published) + if not args.keep_proxy: + for key in ("HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"): + os.environ.pop(key, None) + payload = run_preflight( + repo_root=args.repo_root.resolve(), + selected_surfaces=_parse_surfaces(args.surface), + online=online, + require_published=bool(args.require_published), + require_clean=bool(args.require_clean), + github_repo=args.github_repo, + awesome_dsh_repo=args.awesome_dsh_repo, + ) + if args.format == "json": + print(json.dumps(payload, ensure_ascii=False, indent=2)) + else: + print(render_markdown(payload), end="") + return 0 if payload["ok"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/architecture/test_path_segment_alphabet_owner.py b/tests/architecture/test_path_segment_alphabet_owner.py new file mode 100644 index 0000000000..4f132fed54 --- /dev/null +++ b/tests/architecture/test_path_segment_alphabet_owner.py @@ -0,0 +1,34 @@ +"""One owner for the safe path-segment alphabet.""" + +from __future__ import annotations + +import inspect + +from loopx import paths +from loopx.capabilities.agent_turn_recall import runtime as agent_turn_recall +from loopx.capabilities.reward_memory import outcome_lifecycle +from loopx.capabilities.steward_memory import runtime as steward_memory +from loopx.extensions.openviking_semantic_preference import history_export + +CONSUMERS = (agent_turn_recall, outcome_lifecycle, steward_memory, history_export) + + +def test_every_consumer_borrows_the_owner_alphabet() -> None: + owner = paths.PATH_SEGMENT_UNSAFE_RE + for module in CONSUMERS: + assert module.PATH_SEGMENT_UNSAFE_RE is owner, module.__name__ + + +def test_consumers_keep_allowed_punctuation_and_replace_the_rest() -> None: + value = "a.b_c-d/e f" + readable = "a.b_c-d-e-f" + assert agent_turn_recall._safe_token(value, fallback="fallback").startswith(f"{readable}-") + assert outcome_lifecycle._identity_token(value, fallback="fallback").startswith(f"{readable}-") + assert steward_memory._safe_event_filename(value) == f"{readable}.md" + assert history_export._slug(value) == readable + + +def test_consumers_do_not_restate_the_alphabet() -> None: + literal = r"[^A-Za-z0-9._-]+" + for module in CONSUMERS: + assert literal not in inspect.getsource(module), module.__name__ diff --git a/tests/canary/test_maintainability_ratchet.py b/tests/canary/test_maintainability_ratchet.py index 6e8f1a6a56..af9c89d6e6 100644 --- a/tests/canary/test_maintainability_ratchet.py +++ b/tests/canary/test_maintainability_ratchet.py @@ -46,7 +46,7 @@ def test_current_repository_debt_is_reviewed_without_line_count_pins() -> None: baseline = module_metric_baseline( REPOSITORY_ROOT / "loopx" / "canary" / "module_metric_baseline.json" ) - assert "lines" not in baseline["loopx/extensions/lark/goal_topic_runtime.py"] + assert "lines" not in baseline["loopx/canary/planner.py"] assert baseline["loopx/heartbeat_prompt.py"]["lines"] == 1199 for relative_path, ceilings in baseline.items(): if ceilings.get("lines", MODULE_LINE_LIMIT) > MODULE_LINE_LIMIT: diff --git a/tests/control_plane/test_checkpoint_relocated_replay.py b/tests/control_plane/test_checkpoint_relocated_replay.py new file mode 100644 index 0000000000..907c3a5ba9 --- /dev/null +++ b/tests/control_plane/test_checkpoint_relocated_replay.py @@ -0,0 +1,118 @@ +"""Public CLI replay returns the verified artifacts from the selected runtime.""" +from __future__ import annotations + +import json +from pathlib import Path +import shutil + +import pytest + +from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime +from tests.managed_effect_runtime_fixture import stop_disposable_effect_runtimes +from tests.control_plane.test_checkpoint_read_context import _missing +from tests.control_plane.test_quota_settlement_cli import GOAL_ID, _run_cli, _spend_run_count + + +@pytest.fixture(autouse=True) +def _retire_owned_runtime(tmp_path: Path): + yield + stop_disposable_effect_runtimes(tmp_path) + + +def _historical_records(runtime: Path) -> dict[str, bytes]: + goal = runtime / "goals" / GOAL_ID + paths = [ + *sorted((goal / "runs").glob("*.json")), + *sorted((goal / "runs").glob("*.md")), + *sorted((goal / "runs").glob("*.jsonl")), + *sorted((goal / "checkpoint-contexts").glob("*.json")), + ] + events = goal / "rollout-event-log.jsonl" + if events.exists(): + paths.append(events) + return {str(path.relative_to(goal)): path.read_bytes() for path in paths} + + +def _relocated_checkpoint(tmp_path: Path, monkeypatch, provider: str): + isolate_sqlite_runtime(tmp_path, monkeypatch) + project, runtime, registry, binding, delivery, original = _missing(tmp_path, provider=provider) + rc, context = _run_cli(registry, runtime, "checkpoint-context", *binding, cwd=project) + assert rc == 0, context + replay_args = ( + *delivery, + "--vision-unchanged-reason", "The accepted scope and evidence remain applicable.", + "--checkpoint-read-context", context["read_context_id"], + ) + rc, committed = _run_cli(registry, runtime, *replay_args, cwd=project) + assert rc == 0 and committed["appended"] is True, committed + assert committed["vision_checkpoint"]["satisfied"] is True + assert committed["vision_checkpoint"]["read_context"]["ok"] is True + assert committed["settlement_identity"] == original["settlement_identity"] + relocated = tmp_path / "copied-runtime" + # Copy a completed disposable runtime without rewriting historical paths, + # provider lineage, receipts, checkpoint proofs or index rows. + shutil.copytree(runtime, relocated, symlinks=True) + return project, runtime, relocated, registry, replay_args, committed + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_public_checkpoint_replay_returns_relocated_artifacts_without_rewriting_history( + tmp_path: Path, monkeypatch, provider: str, +): + project, runtime, relocated, registry, replay_args, committed = _relocated_checkpoint( + tmp_path, monkeypatch, provider, + ) + original_records = _historical_records(runtime) + copied_records = _historical_records(relocated) + assert copied_records == original_records + for dry_run in (True, False, False): + rc, replay = _run_cli( + registry, relocated, *replay_args, *(("--dry-run",) if dry_run else ()), cwd=project, + ) + assert rc == 0 and replay["ok"] is True, replay + assert replay["dry_run"] is dry_run + assert replay["appended"] is False and replay["idempotent_replay"] is True + assert replay["settlement_identity"] == committed["settlement_identity"] + assert replay["vision_checkpoint"] == committed["vision_checkpoint"] + assert replay["generated_at"] == committed["generated_at"] + for field in ("json_path", "markdown_path"): + original_path = Path(committed[field]) + expected = (relocated / "goals" / GOAL_ID / "runs" / original_path.name).resolve() + assert Path(replay[field]) == expected + assert expected != original_path.resolve() + assert expected.read_bytes() == original_path.read_bytes() + # The selected index and artifact still record their historical basis. + assert _historical_records(relocated) == copied_records + assert _historical_records(runtime) == original_records + assert _spend_run_count(relocated) == _spend_run_count(runtime) == 0 + assert json.loads(Path(replay["json_path"]).read_text())["vision_checkpoint"] == committed["vision_checkpoint"] + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("field", ["json_path", "markdown_path"]) +@pytest.mark.parametrize("failure", ["missing", "symlink"]) +def test_public_checkpoint_replay_rejects_missing_or_linked_relocated_artifacts( + tmp_path: Path, monkeypatch, provider: str, field: str, failure: str, +): + project, runtime, relocated, registry, replay_args, committed = _relocated_checkpoint( + tmp_path, monkeypatch, provider, + ) + original_records = _historical_records(runtime) + original_path = Path(committed[field]) + candidate = relocated / "goals" / GOAL_ID / "runs" / original_path.name + candidate.unlink() + if failure == "symlink": + candidate.symlink_to(original_path) + copied_records = _historical_records(relocated) + rc, rejected = _run_cli(registry, relocated, *replay_args, cwd=project) + assert rc == 1 and rejected["ok"] is False, rejected + assert rejected["error_code"] == "checkpoint_commit_unknown", rejected + assert "checkpoint artifact path is invalid" in rejected["error"] + assert rejected["checkpoint_read_context"]["reread_required"] is False + assert _historical_records(relocated) == copied_records + assert _historical_records(runtime) == original_records + assert _spend_run_count(relocated) == _spend_run_count(runtime) == 0 + if failure == "symlink": + assert candidate.is_symlink() and candidate.resolve() == original_path.resolve() + else: + assert not candidate.exists() diff --git a/tests/control_plane/test_codex_hook_direct_read.py b/tests/control_plane/test_codex_hook_direct_read.py index 38498882e5..203f6d61c6 100644 --- a/tests/control_plane/test_codex_hook_direct_read.py +++ b/tests/control_plane/test_codex_hook_direct_read.py @@ -500,6 +500,337 @@ def test_default_off_parity_and_zero_post_tool_friction_and_cli_opt_in( assert not registry.exists() and not runtime.exists() +def test_quota_context_config_and_hook_opt_ins_quiet_turn_and_epoch_prefetch( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + """Verify --quiet-turn & --epoch-prefetch-json stay off by default and activate cleanly.""" + import os + from loopx.cli import main + + journal_dir = tmp_path / "ctx" + journal_dir.mkdir(mode=0o700) + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.setenv("LOOPX_EXECUTION_MODE", "heartbeat") + + def _run_cli(argv: list[str]) -> tuple[int, dict]: + import contextlib + import io + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + code = main(["--format", "json", "--registry", str(tmp_path / "r.json"), "--runtime-root", str(tmp_path / "rt"), *argv]) + return code, json.loads(buf.getvalue()) + + c_default, p_default = _run_cli([ + "quota", "context-config", + "--goal-id", "g1", "--agent-id", "a1", + "--context-delivery", "on", "--codex-app", + "--codex-context-dir", str(journal_dir), + ]) + assert c_default == 0 and p_default["ok"] is True, p_default + default_cmd = p_default["native_config"]["hooks"]["SessionStart"][0]["hooks"][0]["command"] + assert "--compact-direct-read" not in default_cmd + assert "--quiet-turn" not in default_cmd + assert "--epoch-prefetch-json" not in default_cmd + + prefetch_cfg = {"enabled": True, "prefetch_command": ["git", "status", "--short"]} + c_opt, p_opt = _run_cli([ + "quota", "context-config", + "--goal-id", "g1", "--agent-id", "a1", + "--context-delivery", "on", "--codex-app", + "--compact-direct-read", "--quiet-turn", + "--epoch-prefetch-json", json.dumps(prefetch_cfg), + "--codex-context-dir", str(journal_dir), + ]) + assert c_opt == 0 and p_opt["ok"] is True, p_opt + opt_cmd = p_opt["native_config"]["hooks"]["SessionStart"][0]["hooks"][0]["command"] + assert "--compact-direct-read" in opt_cmd + assert "--quiet-turn" in opt_cmd + assert "--epoch-prefetch-json" in opt_cmd + + # Reject context-hook flags on unrelated quota subcommands cleanly. + c_bad, p_bad = _run_cli(["quota", "should-run", "--goal-id", "g1", "--quiet-turn"]) + assert c_bad == 1 and "context-config or context-hook" in p_bad["reason"] + c_bad2, p_bad2 = _run_cli(["quota", "should-run", "--goal-id", "g1", "--epoch-prefetch-json", '{"enabled":true}']) + assert c_bad2 == 1 and "context-config or context-hook" in p_bad2["reason"] + + # Real CLI subprocess quota context-hook with --quiet-turn on unchanged digest. + capture = tmp_path / "capture.json" + capture.write_bytes(b'{"goal_id":"g1","selected_todo":{"todo_id":"todo_1","status":"open"}}') + digest = hashlib.sha256(capture.read_bytes()).hexdigest() + from loopx.control_plane.turn_driver import codex_context as ctx + ctx._save(journal_dir, { + "session_id": "s-qt", + "cwd": str(tmp_path), + "context_epoch": "epoch-1", + "candidate": {"epoch": "epoch-1"}, + "recovery": {"path": str(capture), "sha256": digest, "command": "loopx quota context-read"}, + }) + worktree_root = str(Path(__file__).resolve().parents[2]) + env_clean = {k: v for k, v in os.environ.items() if k != "LOOPX_CODEX_HOOK_DIRECT_READ"} + env_clean["HOME"] = str(tmp_path) + env_clean["PYTHONPATH"] = worktree_root + hook_cmd = [ + sys.executable, "-m", "loopx.entrypoint", + "--registry", str(tmp_path / "absent.json"), + "--runtime-root", str(tmp_path / "absent-rt"), + "--format", "json", "quota", "context-hook", + "--context-delivery", "on", "--codex-app", "--quiet-turn", + "--codex-context-dir", str(journal_dir), + ] + evt_hook = {"session_id": "s-qt", "cwd": str(tmp_path), "hook_event_name": "PostCompact"} + subprocess.run(hook_cmd, input=json.dumps(evt_hook), capture_output=True, text=True, env=env_clean, check=True) + r2 = subprocess.run(hook_cmd, input=json.dumps(evt_hook), capture_output=True, text=True, env=env_clean, check=True) + second_out = json.loads(r2.stdout) + assert second_out.get("hookSpecificOutput", {}).get("quietTurn", {}).get("skipped") is True + + # Real CLI subprocess quota context-hook with --epoch-prefetch-json on compact recovery. + prefetch_repo = tmp_path / "prefetch-repo" + prefetch_repo.mkdir() + subprocess.run(["git", "init"], cwd=prefetch_repo, capture_output=True, check=True) + large_capture = tmp_path / "large-capture.json" + large_capture.write_text(json.dumps({ + "goal_id": "g1", + "selected_todo": {"todo_id": "todo_1", "status": "open"}, + "padding": "x" * 2048, + })) + large_digest = hashlib.sha256(large_capture.read_bytes()).hexdigest() + prefetch_dir = tmp_path / "ctx-prefetch" + prefetch_dir.mkdir(mode=0o700) + ctx._save(prefetch_dir, { + "session_id": "s-ep", + "cwd": str(prefetch_repo), + "context_epoch": "epoch-9", + "recovery": {"path": str(large_capture), "sha256": large_digest, "command": "loopx quota context-read"}, + }) + ep_cfg = { + "enabled": True, + "prefetch_command": ["git", "status", "--short"], + "baseline_bytes": large_capture.stat().st_size, + "min_net_savings_bytes": 1, + } + ep_cmd = [ + sys.executable, "-m", "loopx.entrypoint", + "--registry", str(tmp_path / "absent2.json"), + "--runtime-root", str(tmp_path / "absent2-rt"), + "--format", "json", "quota", "context-hook", + "--context-delivery", "on", "--codex-app", + "--epoch-prefetch-json", json.dumps(ep_cfg), + "--codex-context-dir", str(prefetch_dir), + ] + ep_evt = {"session_id": "s-ep", "cwd": str(prefetch_repo), "hook_event_name": "SessionStart", "source": "compact"} + r_ep = subprocess.run( + ep_cmd, input=json.dumps(ep_evt), capture_output=True, text=True, + env=env_clean, cwd=prefetch_repo, check=True, + ) + ep_out = json.loads(r_ep.stdout)["hookSpecificOutput"] + assert ep_out["epochPrefetch"]["operator"] == "EpochReset" + assert ep_out["epochPrefetch"]["bytes_saved"] > 0 + + +def test_combined_compact_direct_read_and_epoch_prefetch_generated_hook_lifecycle( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + """Generated combined H1 hook executes both direct read and EpochReset prefetch, never silently dropping either.""" + import os + import shlex + from loopx.cli import main + from loopx.control_plane.turn_driver import codex_context as ctx + + repo = tmp_path / "repo" + repo.mkdir() + subprocess.run(["git", "init"], cwd=repo, capture_output=True, check=True) + (repo / "tracked.txt").write_text("base\n", encoding="utf-8") + subprocess.run(["git", "add", "tracked.txt"], cwd=repo, capture_output=True, check=True) + subprocess.run( + ["git", "-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "-m", "init"], + cwd=repo, capture_output=True, check=True, + ) + (repo / "dirty.txt").write_text("dirty\n", encoding="utf-8") + + capture = tmp_path / "combo-capture.json" + capture.write_text(json.dumps({ + "goal_id": "g-combo", + "selected_todo": {"todo_id": "todo_combo", "title": "Preserve direct read and prefetch"}, + "padding": "y" * 4096, + }), encoding="utf-8") + capture.chmod(0o600) + digest = hashlib.sha256(capture.read_bytes()).hexdigest() + + journal_dir = tmp_path / "ctx-combo" + journal_dir.mkdir(mode=0o700) + ctx._save(journal_dir, { + "session_id": "s-combo", + "cwd": str(repo), + "context_epoch": "epoch-combo-1", + "goal_id": "g-combo", + "agent_id": "a1", + "recovery": {"path": str(capture), "sha256": digest, "command": f"loopx quota context-read --capture-file {capture}"}, + }) + + ep_cfg = { + "enabled": True, + "prefetch_command": ["git", "status", "--short"], + "baseline_bytes": capture.stat().st_size, + "min_net_savings_bytes": 1, + } + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.setenv("LOOPX_EXECUTION_MODE", "heartbeat") + + import contextlib + import io + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + rc = main([ + "--format", "json", + "--registry", str(tmp_path / "r.json"), + "--runtime-root", str(tmp_path / "rt"), + "quota", "context-config", + "--goal-id", "g-combo", "--agent-id", "a1", + "--context-delivery", "on", "--codex-app", + "--compact-direct-read", "--quiet-turn", + "--epoch-prefetch-json", json.dumps(ep_cfg), + "--codex-context-dir", str(journal_dir), + ]) + assert rc == 0 + hooks = json.loads(buf.getvalue())["native_config"]["hooks"] + cmd_tokens = shlex.split(hooks["SessionStart"][0]["hooks"][0]["command"]) + worktree_root = str(Path(__file__).resolve().parents[2]) + hook_cmd = [ + sys.executable, "-m", "loopx.entrypoint", + "--registry", str(tmp_path / "absent-combo.json"), + "--runtime-root", str(tmp_path / "absent-combo-rt"), + *cmd_tokens[cmd_tokens.index("--format"):], + ] + env_clean = {k: v for k, v in os.environ.items() if k != "LOOPX_CODEX_HOOK_DIRECT_READ"} + env_clean["HOME"] = str(tmp_path) + env_clean["PYTHONPATH"] = worktree_root + + # 1. PostCompact stays inert ({}) without setting compact_hook_wake or running prefetch. + r_post = subprocess.run( + hook_cmd, + input=json.dumps({"session_id": "s-combo", "cwd": str(repo), "hook_event_name": "PostCompact"}), + capture_output=True, text=True, env=env_clean, cwd=repo, check=True, + ) + assert json.loads(r_post.stdout) == {} + assert "compact_hook_wake" not in ctx._state(journal_dir) + + # 2. First SessionStart(compact) runs BOTH: non-deduped compactDirectRead AND real EpochReset prefetch! + start_evt = {"session_id": "s-combo", "cwd": str(repo), "hook_event_name": "SessionStart", "source": "compact"} + r_start = subprocess.run( + hook_cmd, input=json.dumps(start_evt), capture_output=True, text=True, + env=env_clean, cwd=repo, check=True, + ) + start_out = json.loads(r_start.stdout)["hookSpecificOutput"] + assert start_out["compactDirectRead"]["operator"] == "EpochReset" + assert start_out["compactDirectRead"]["deduplicated"] is False + assert start_out["compactDirectRead"]["composed_with_epoch_prefetch"] is True + assert start_out["epochPrefetch"]["configured"] is True + assert start_out["epochPrefetch"]["superseded"] is False + assert start_out["epochPrefetch"]["composed_with_compact_direct_read"] is True + assert start_out["epochPrefetch"]["operator"] == "EpochReset" + assert start_out["epochPrefetch"]["executed"] is True + assert start_out["epochPrefetch"]["replayed"] is False + assert start_out["epochPrefetch"]["bytes_saved"] > 0 + assert "todo_combo" in start_out["additionalContext"] + assert "dirty.txt" in start_out["additionalContext"] + + # 3. Replay on same epoch deduplicates compactDirectRead and NEVER re-executes prefetch_command. + r_replay = subprocess.run( + hook_cmd, input=json.dumps(start_evt), capture_output=True, text=True, + env=env_clean, cwd=repo, check=True, + ) + replay_out = json.loads(r_replay.stdout)["hookSpecificOutput"] + assert replay_out["compactDirectRead"]["deduplicated"] is True + assert replay_out["epochPrefetch"]["replayed"] is True + assert replay_out["epochPrefetch"]["executed"] is False + assert replay_out["epochPrefetch"]["superseded"] is False + + # 3a. Compaction #2 (C2) in combined mode (including --quiet-turn): PreCompact/PostCompact + # must never emit additionalContext/compactDirectRead and clear compact_hook_wake even with + # candidate absent so C2 SessionStart(compact) re-injects BOTH! + r_c2_pre = subprocess.run( + hook_cmd, + input=json.dumps({"session_id": "s-combo", "cwd": str(repo), "hook_event_name": "PreCompact"}), + capture_output=True, text=True, env=env_clean, cwd=repo, check=True, + ) + c2_pre_out = json.loads(r_c2_pre.stdout).get("hookSpecificOutput") or {} + assert "additionalContext" not in c2_pre_out + assert "compactDirectRead" not in c2_pre_out + r_c2_post = subprocess.run( + hook_cmd, + input=json.dumps({"session_id": "s-combo", "cwd": str(repo), "hook_event_name": "PostCompact"}), + capture_output=True, text=True, env=env_clean, cwd=repo, check=True, + ) + c2_post_out = json.loads(r_c2_post.stdout).get("hookSpecificOutput") or {} + assert "additionalContext" not in c2_post_out + assert "compactDirectRead" not in c2_post_out + assert "compact_hook_wake" not in ctx._state(journal_dir) + r_c2_start = subprocess.run( + hook_cmd, input=json.dumps(start_evt), capture_output=True, text=True, + env=env_clean, cwd=repo, check=True, + ) + c2_out = json.loads(r_c2_start.stdout)["hookSpecificOutput"] + assert c2_out["compactDirectRead"]["operator"] == "EpochReset" + assert c2_out["compactDirectRead"]["deduplicated"] is False + assert c2_out["compactDirectRead"]["composed_with_epoch_prefetch"] is True + assert c2_out["epochPrefetch"]["operator"] == "EpochReset" + assert c2_out["epochPrefetch"]["superseded"] is False + assert c2_out["epochPrefetch"]["composed_with_compact_direct_read"] is True + assert "todo_combo" in c2_out["additionalContext"] + assert "dirty.txt" in c2_out["additionalContext"] + r_c2_dup = subprocess.run( + hook_cmd, input=json.dumps(start_evt), capture_output=True, text=True, + env=env_clean, cwd=repo, check=True, + ) + assert json.loads(r_c2_dup.stdout)["hookSpecificOutput"]["compactDirectRead"]["deduplicated"] is True + + # 3b. Direct SessionStart(compact) without prior PostCompact includes BOTH pointer payload and EpochReset output. + ctx._save(journal_dir, { + "session_id": "s-combo", + "cwd": str(repo), + "context_epoch": "epoch-combo-direct-start", + "goal_id": "g-combo", + "agent_id": "a1", + "recovery": {"path": str(capture), "sha256": digest, "command": f"loopx quota context-read --capture-file {capture}"}, + }) + r_direct_start = subprocess.run( + hook_cmd, input=json.dumps(start_evt), capture_output=True, text=True, + env=env_clean, cwd=repo, check=True, + ) + direct_start_out = json.loads(r_direct_start.stdout)["hookSpecificOutput"] + assert direct_start_out["compactDirectRead"]["operator"] == "EpochReset" + assert direct_start_out["compactDirectRead"]["deduplicated"] is False + assert direct_start_out["epochPrefetch"]["operator"] == "EpochReset" + assert direct_start_out["epochPrefetch"]["executed"] is True + assert direct_start_out["epochPrefetch"]["superseded"] is False + assert "todo_combo" in direct_start_out["additionalContext"] + assert "dirty.txt" in direct_start_out["additionalContext"] + + # 4. Failing epoch prefetch falls back cleanly to KeepRaw while preserving direct-read output. + ctx._save(journal_dir, { + "session_id": "s-combo", + "cwd": str(repo), + "context_epoch": "epoch-combo-fail", + "goal_id": "g-combo", + "agent_id": "a1", + "recovery": {"path": str(capture), "sha256": digest, "command": f"loopx quota context-read --capture-file {capture}"}, + }) + fail_ep = {"enabled": True, "prefetch_command": ["cat", str(repo / "missing-file.txt")], "baseline_bytes": 4096} + fail_cmd = list(hook_cmd) + fail_cmd[fail_cmd.index("--epoch-prefetch-json") + 1] = json.dumps(fail_ep) + r_fail = subprocess.run( + fail_cmd, input=json.dumps(start_evt), capture_output=True, text=True, + env=env_clean, cwd=repo, check=True, + ) + fail_out = json.loads(r_fail.stdout)["hookSpecificOutput"] + assert fail_out["compactDirectRead"]["operator"] == "EpochReset" + assert fail_out["epochPrefetch"]["configured"] is True + assert fail_out["epochPrefetch"]["superseded"] is False + assert fail_out["epochPrefetch"]["operator"] == "KeepRaw" + assert "todo_combo" in fail_out["additionalContext"] + assert "Prefetch fallback notice (KeepRaw)" in fail_out["additionalContext"] + + def test_read_json_pointers_paginated_fails_closed_over_pointer_cap(tmp_path: Path) -> None: capture = tmp_path / "capture-overcap.json" payload = {f"k{idx}": idx for idx in range(direct_read.MAX_POINTERS_PER_HOOK)} @@ -522,6 +853,275 @@ def test_read_json_pointers_paginated_fails_closed_over_pointer_cap(tmp_path: Pa assert result["requested_count"] == direct_read.MAX_POINTERS_PER_HOOK + 1 +def test_epoch_rotation_passes_effective_state_and_commits_prefetch_under_lock( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + """Fix 1: Rotated context_epoch on updated state (not stale pre-lifecycle state) governs prefetch key and replay.""" + from loopx.control_plane.turn_driver import codex_context as ctx + from loopx.control_plane.turn_driver import epoch_prefetch as ep_mod + + repo = tmp_path / "repo-rot" + repo.mkdir() + subprocess.run(["git", "init"], cwd=repo, capture_output=True, check=True) + (repo / "base.txt").write_text("v1\n", encoding="utf-8") + subprocess.run(["git", "add", "base.txt"], cwd=repo, capture_output=True, check=True) + subprocess.run( + ["git", "-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "-m", "init"], + cwd=repo, capture_output=True, check=True, + ) + (repo / "changed.txt").write_text("dirty\n", encoding="utf-8") + + cap = tmp_path / "rot-cap.json" + cap.write_text(json.dumps({"goal_id": "g-rot", "selected_todo": {"todo_id": "t-rot"}, "pad": "x" * 4096}), encoding="utf-8") + cap.chmod(0o600) + dig = hashlib.sha256(cap.read_bytes()).hexdigest() + + journal_dir = tmp_path / "ctx-rot" + journal_dir.mkdir(mode=0o700) + ctx._save(journal_dir, { + "session_id": "s-rot", + "cwd": str(repo), + "context_epoch": "epoch-1", + "goal_id": "g-rot", + "agent_id": "a-rot", + "recovery": {"path": str(cap), "sha256": dig, "command": f"loopx quota context-read --capture-file {cap}"}, + }) + + # Rotate epoch inside _reduce_hook_lifecycle on call 1 (simulating same-turn lifecycle epoch rotation). + real_reduce = ctx._reduce_hook_lifecycle + rotations = {"n": 0} + + def rotating_reduce(*args, **kwargs): + res = real_reduce(*args, **kwargs) + rotations["n"] += 1 + if rotations["n"] == 1: + res = {**res, "context_epoch": "epoch-2", "goal_id": "g-rot-updated"} + return res + + monkeypatch.setattr(ctx, "_reduce_hook_lifecycle", rotating_reduce) + + exec_calls = {"count": 0} + real_subproc = ep_mod.run_bounded_prefetch_subprocess + + def counting_subproc(*args, **kwargs): + exec_calls["count"] += 1 + return real_subproc(*args, **kwargs) + + monkeypatch.setattr(ep_mod, "run_bounded_prefetch_subprocess", counting_subproc) + + evt = { + "session_id": "s-rot", + "cwd": str(repo), + "hook_event_name": "SessionStart", + "source": "compact", + "epoch_prefetch": { + "enabled": True, + "prefetch_command": ["git", "status", "--short"], + "baseline_bytes": cap.stat().st_size, + "min_net_savings_bytes": 1, + }, + } + first = ctx.codex_context_hook(str(journal_dir), evt) + ep1 = first["hookSpecificOutput"]["epochPrefetch"] + assert ep1["operator"] == "EpochReset" + assert ep1["context_epoch"] == "epoch-2" + assert ep1["executed"] is True + assert ep1["replayed"] is False + assert exec_calls["count"] == 1 + + persisted = ctx._state(journal_dir) + assert persisted["context_epoch"] == "epoch-2" + assert persisted["epoch_prefetch"]["context_epoch"] == "epoch-2" + + # Identical retry MUST replay the committed epoch-2 receipt rather than re-executing prefetch_command. + second = ctx.codex_context_hook(str(journal_dir), evt) + ep2 = second["hookSpecificOutput"]["epochPrefetch"] + assert ep2["operator"] == "EpochReset" + assert ep2["context_epoch"] == "epoch-2" + assert ep2["executed"] is False + assert ep2["replayed"] is True + assert exec_calls["count"] == 1 + + # Even if a direct caller passes stale state["context_epoch"], resolve_codex_context_epoch_prefetch_hook + # reads locked disk current_state["context_epoch"] ("epoch-2") under the file lock. + direct_res = ep_mod.resolve_codex_context_epoch_prefetch_hook( + directory=str(journal_dir), + hook_name="SessionStart", + state={"context_epoch": "epoch-1", "goal_id": "stale-g", "agent_id": "a-rot"}, + event=evt, + recovery={"path": str(cap), "sha256": dig, "command": f"loopx quota context-read --capture-file {cap}"}, + lock_ctx=ctx._locked, + read_state_fn=ctx._state, + save_state_fn=ctx._save, + continuation_text="read capture", + raw_guidance_text="guidance", + ) + assert direct_res is not None + direct_ep = direct_res["hookSpecificOutput"]["epochPrefetch"] + assert direct_ep["context_epoch"] == "epoch-2" + assert direct_ep["replayed"] is True + assert direct_ep["executed"] is False + assert exec_calls["count"] == 1 + + +def test_combined_hook_enforces_delivered_utf8_byte_budget_and_four_arm_comparison( + tmp_path: Path, +) -> None: + """Fix 2: Composition enforces combined delivered UTF-8 byte budget + compares all 4 H1 arms.""" + from loopx.control_plane.turn_driver import codex_context as ctx + + repo = tmp_path / "repo-budget" + repo.mkdir() + subprocess.run(["git", "init"], cwd=repo, capture_output=True, check=True) + (repo / "base.txt").write_text("v1\n", encoding="utf-8") + subprocess.run(["git", "add", "base.txt"], cwd=repo, capture_output=True, check=True) + subprocess.run( + ["git", "-c", "user.name=Test", "-c", "user.email=test@example.com", "commit", "-m", "init"], + cwd=repo, capture_output=True, check=True, + ) + (repo / "dirty.txt").write_text("dirty\n", encoding="utf-8") + + # 1. Small capture (cap_bytes ~ 387): combined hook MUST fail closed epochPrefetch instead of inflating + # additionalContext by 9x while falsely claiming EpochReset + positive bytes_saved. + small_cap = tmp_path / "small-cap.json" + small_cap.write_text(json.dumps({ + "goal_id": "g-small", + "selected_todo": {"todo_id": "t-small", "title": "Small capture"}, + "padding": "p" * 290, + }), encoding="utf-8") + small_cap.chmod(0o600) + small_bytes = small_cap.stat().st_size + assert 350 <= small_bytes <= 430, small_bytes + small_dig = hashlib.sha256(small_cap.read_bytes()).hexdigest() + + def _run_small(mode_name: str, extra_evt: dict) -> dict: + d = tmp_path / f"ctx-small-{mode_name}" + d.mkdir(mode=0o700) + ctx._save(d, { + "session_id": f"s-{mode_name}", + "cwd": str(repo), + "context_epoch": "epoch-small-1", + "goal_id": "g-small", + "agent_id": "a1", + "recovery": {"path": str(small_cap), "sha256": small_dig, "command": f"loopx quota context-read --capture-file {small_cap}"}, + }) + return ctx.codex_context_hook(str(d), { + "session_id": f"s-{mode_name}", + "cwd": str(repo), + "hook_event_name": "SessionStart", + "source": "compact", + **extra_evt, + })["hookSpecificOutput"] + + small_direct_only = _run_small("direct", {"compact_direct_read": {"enabled": True}}) + small_combo = _run_small("combo", { + "compact_direct_read": {"enabled": True}, + "epoch_prefetch": { + "enabled": True, + "prefetch_command": ["git", "status", "--short"], + "baseline_bytes": small_bytes, + "min_net_savings_bytes": 1, + }, + }) + assert small_combo["epochPrefetch"]["operator"] == "KeepRaw" + assert small_combo["epochPrefetch"]["fallback_reason"] == "composed_budget_exceeded" + assert small_combo["epochPrefetch"]["superseded"] is True + assert small_combo["epochPrefetch"]["bytes_saved"] == 0 + assert small_combo["epochPrefetch"]["round_trips_saved"] == 0 + assert len(small_combo["additionalContext"].encode("utf-8")) == len( + small_direct_only["additionalContext"].encode("utf-8") + ) + + # 2. Explicit tight max_output_bytes on a large capture bounds total delivered UTF-8 bytes strictly <= budget. + big_cap = tmp_path / "big-cap.json" + big_cap.write_text(json.dumps({ + "goal_id": "g-big", + "selected_todo": {"todo_id": "t-big", "title": "Realistic large capture"}, + "padding": "z" * 8192, + }), encoding="utf-8") + big_cap.chmod(0o600) + big_bytes = big_cap.stat().st_size + big_dig = hashlib.sha256(big_cap.read_bytes()).hexdigest() + + tight_dir = tmp_path / "ctx-tight" + tight_dir.mkdir(mode=0o700) + ctx._save(tight_dir, { + "session_id": "s-tight", + "cwd": str(repo), + "context_epoch": "epoch-tight-1", + "goal_id": "g-big", + "agent_id": "a1", + "recovery": {"path": str(big_cap), "sha256": big_dig, "command": f"loopx quota context-read --capture-file {big_cap}"}, + }) + tight_cap_bytes = 1850 + tight_out = ctx.codex_context_hook(str(tight_dir), { + "session_id": "s-tight", + "cwd": str(repo), + "hook_event_name": "SessionStart", + "source": "compact", + "compact_direct_read": {"enabled": True, "max_output_bytes": tight_cap_bytes}, + "epoch_prefetch": { + "enabled": True, + "prefetch_command": ["git", "status", "--short"], + "baseline_bytes": big_bytes, + "min_net_savings_bytes": 1, + }, + })["hookSpecificOutput"] + assert len(tight_out["additionalContext"].encode("utf-8")) <= tight_cap_bytes + assert tight_out["epochPrefetch"]["operator"] == "KeepRaw" + assert tight_out["epochPrefetch"]["fallback_reason"] == "composed_budget_exceeded" + assert tight_out["epochPrefetch"]["bytes_saved"] == 0 + + # 3. 4-arm comparison (off, direct_read, epoch_prefetch, combined) on an 8KB capture. + def _run_big(arm: str, extra_evt: dict) -> tuple[dict, int]: + d = tmp_path / f"ctx-arm-{arm}" + d.mkdir(mode=0o700) + ctx._save(d, { + "session_id": f"s-arm-{arm}", + "cwd": str(repo), + "context_epoch": f"epoch-arm-{arm}", + "goal_id": "g-big", + "agent_id": "a1", + "recovery": {"path": str(big_cap), "sha256": big_dig, "command": f"loopx quota context-read --capture-file {big_cap}"}, + }) + out = ctx.codex_context_hook(str(d), { + "session_id": f"s-arm-{arm}", + "cwd": str(repo), + "hook_event_name": "SessionStart", + "source": "compact", + **extra_evt, + })["hookSpecificOutput"] + return out, len(out["additionalContext"].encode("utf-8")) + + arm_off, bytes_off = _run_big("off", {}) + arm_direct, bytes_direct = _run_big("direct", {"compact_direct_read": {"enabled": True}}) + ep_cfg_big = { + "enabled": True, + "prefetch_command": ["git", "status", "--short"], + "baseline_bytes": big_bytes, + "min_net_savings_bytes": 1, + } + arm_ep, bytes_ep = _run_big("prefetch", {"epoch_prefetch": ep_cfg_big}) + arm_combo, bytes_combo = _run_big("combined", { + "compact_direct_read": {"enabled": True}, + "epoch_prefetch": ep_cfg_big, + }) + + assert "compactDirectRead" not in arm_off and "epochPrefetch" not in arm_off + assert arm_direct["compactDirectRead"]["operator"] == "EpochReset" + assert "epochPrefetch" not in arm_direct + assert arm_ep["epochPrefetch"]["operator"] == "EpochReset" + assert arm_ep["epochPrefetch"]["bytes_saved"] <= big_bytes - bytes_ep + assert arm_combo["compactDirectRead"]["operator"] == "EpochReset" + assert arm_combo["epochPrefetch"]["operator"] == "EpochReset" + assert arm_combo["epochPrefetch"]["superseded"] is False + assert bytes_direct < big_bytes and bytes_ep < big_bytes and bytes_combo < big_bytes + assert bytes_combo < bytes_direct + bytes_ep + assert arm_combo["epochPrefetch"]["bytes_saved"] <= big_bytes - bytes_combo + assert arm_combo["epochPrefetch"]["bytes_saved"] > 0 + assert bytes_off > 0 + + @pytest.mark.parametrize("path_mode", ["ts_lifecycle", "lock_free_fallback"]) def test_multi_compaction_clears_compact_hook_wake_and_reinjects_c2( tmp_path: Path, diff --git a/tests/control_plane/test_effect_runtime_node_probe.py b/tests/control_plane/test_effect_runtime_node_probe.py index 9f500b2d90..058d979b08 100644 --- a/tests/control_plane/test_effect_runtime_node_probe.py +++ b/tests/control_plane/test_effect_runtime_node_probe.py @@ -296,3 +296,71 @@ def test_deep_readiness_second_probe_timeout_recovers_real_request(tmp_path, mon assert recovered["runtime_identity"]["sqlite_authority_qualified"] is True finally: assert effect_runtime.restart_effect_runtime()["stopped"] is True + + +@pytest.mark.parametrize( + ("system", "machine", "expected"), + [ + ("linux", "x86_64", ("--liftoff-only", "--no-wasm-tier-up", "--no-wasm-dynamic-tiering")), + ("linux", "AMD64", ("--liftoff-only", "--no-wasm-tier-up", "--no-wasm-dynamic-tiering")), + ("linux", "aarch64", ()), + ("darwin", "arm64", ()), + ("win32", "AMD64", ()), + ], +) +def test_node_typescript_flags_scopes_wasm_baseline_workaround_to_linux_x86_64( + system: str, + machine: str, + expected: tuple[str, ...], +) -> None: + assert node_probe.node_typescript_flags(system=system, machine=machine) == expected + + +def test_stdio_and_server_runtime_launch_include_linux_x86_wasm_flags(tmp_path: Path, monkeypatch) -> None: + monkeypatch.setattr(node_probe.sys, "platform", "linux") + monkeypatch.setattr(node_probe.platform, "machine", lambda: "x86_64") + monkeypatch.setattr(effect_runtime, "_node_executable", lambda: "node") + launched: list[list[str]] = [] + + class _FakePipe: + pid = 123 + + def close(self, **_kwargs) -> bool: + return True + + def fake_stdio(argv, _env): + launched.append(list(argv)) + return _FakePipe() + + monkeypatch.setattr(effect_runtime, "EffectRuntimeStdio", fake_stdio) + monkeypatch.setattr( + effect_runtime, + "_request_with_info", + lambda *_args, **_kwargs: { + "result": {"ready": True, "pid": 123, "fingerprint": "f" * 64, "runtime_identity": None}, + }, + ) + runtime = effect_runtime._start_stdio_runtime("f" * 64) + assert runtime.fingerprint == "f" * 64 + assert launched and launched[0][:6] == [ + "node", + "--no-warnings", + "--experimental-strip-types", + "--liftoff-only", + "--no-wasm-tier-up", + "--no-wasm-dynamic-tiering", + ] + assert Path(launched[0][6]).name == "effect_runtime_stdio.ts" + + server_launches: list[list[str]] = [] + observations = iter([None, {"ready": True}]) + monkeypatch.setattr(effect_runtime, "_read_info", lambda *_args, **_kwargs: next(observations)) + monkeypatch.setattr( + effect_runtime.subprocess, + "Popen", + lambda args, **_kwargs: server_launches.append(list(args)) or SimpleNamespace(poll=lambda: None), + ) + info = tmp_path / "runtime" / "runtime.json" + assert effect_runtime._start_runtime(fingerprint="f" * 64, info_path=info) == {"ready": True} + assert server_launches and server_launches[0][:6] == launched[0][:6] + assert "--import" in server_launches[0] diff --git a/tests/control_plane/test_execution_loss_closeout_cli.py b/tests/control_plane/test_execution_loss_closeout_cli.py new file mode 100644 index 0000000000..377030e000 --- /dev/null +++ b/tests/control_plane/test_execution_loss_closeout_cli.py @@ -0,0 +1,481 @@ +"""A lost execution generation can close only its original Turn, without spend.""" +from __future__ import annotations + +from datetime import datetime, timedelta, timezone +from hashlib import sha256 +import json +import sys + +import pytest +from loopx.agent_registry import registered_agent_ids_for_goal + +from canonical_authority_fixture import initialize_canonical_source_fixture, isolate_sqlite_runtime +from codex_checkpoint_fixture import read_cli_policy_payload +from loopx.cli import main as cli_main +from loopx.control_plane.coordination import local_authority +from loopx.control_plane.effect_runtime import effect_runtime_result +from loopx.control_plane.goals.source_session_registration import ( + FreshSourceSessionRegistration, + configure_source_creation_goal, + register_fresh_source_session_project, +) +from loopx.control_plane.quota import settlement +from loopx.control_plane.projects.registry_codec import load_project_registry +from loopx.control_plane.quota.effect_program import SettlementIdentity +from loopx.control_plane.quota.execution_preparation import prepared_lease_receipt_fields +from loopx.control_plane.quota.heartbeat_receipt import ( + ensure_turn_heartbeat_settlement_receipt, + requalify_bound_heartbeat_receipt, + retain_pending_heartbeat_action_selection, + upgrade_identityless_heartbeat_receipt, +) +from loopx.control_plane.runtime import time as runtime_time +from loopx.control_plane.todos.completion_validation_projection import ( + completion_validation_declaration, + project_completion_validation_authority, +) +from loopx.control_plane.todos.completion_validation_store import ( + persist_completion_validation_declaration, + prepare_completion_validation_declaration, +) +from loopx.control_plane.work_items import task_lease +from loopx.rollout_event_log import append_rollout_event, build_rollout_event, rollout_event_log_path +from tests.control_plane.test_quota_settlement_cli import _write_fixture as write_legacy_fixture + + +GOAL = "execution-loss-closeout" +OWNER = "original-worker" +PEER = "replacement-worker" +TURN = "original-prepared-turn" + + +def _registered_agents(context): + goal = next(goal for goal in load_project_registry(context["registry"])["goals"] + if goal["id"] == context["goal_id"]) + return registered_agent_ids_for_goal(goal) + + +def _source_transaction(context, method, schema, *, operation_id, **intent): + registry_digest = sha256(context["registry"].read_bytes()).hexdigest() + result = effect_runtime_result(method, { + "schema_version": schema, "runtime_root": str(context["runtime"].resolve()), + "goal_id": context["goal_id"], "operation_id": operation_id, + "expected_provider_revision": _canonical(context)["provider_revision"], + "expected_registry_sha256": registry_digest, + "registry_source": {"path": str(context["registry"].resolve()), "sha256": registry_digest}, + "registered_agents": _registered_agents(context), "dry_run": False, + "observed_at": runtime_time.now_local_iso(), **intent, + }) + assert result["status"] == "applied", result + assert result["decision_read_from_provider"] is True + assert result["legacy_fallback_used"] is False + return result + + +def _source_create_todo(context, validation_argv): + operation = "execution-loss-task" + todo_id = "todo_" + sha256(operation.encode()).hexdigest()[:24] + fields = {"schema_version": "todo_domain_record_v0", "todo_id": todo_id, + "role": "agent", "text": "Validate the original task before declaring completion.", + "status": "open", "done": False, "archive_state": "active", + "task_class": "advancement_task", "action_kind": "validate", + "continuation_policy": "same_agent_non_delivery", "claimed_by": OWNER, + "validation_command_argv": validation_argv} + declaration = completion_validation_declaration(fields) + assert declaration is not None + prepare_completion_validation_declaration(runtime_root=context["runtime"], + goal_id=context["goal_id"], declaration=declaration) + result = _source_transaction(context, "coordination.local_authority.todo_create", + "loopx_local_coordination_todo_create_request_v3", operation_id=operation, + actor_agent_id=OWNER, todo=project_completion_validation_authority(fields)) + assert result["todo_id"] == todo_id + assert result["todo"]["completion_validation_required"] is True + persist_completion_validation_declaration(runtime_root=context["runtime"], + goal_id=context["goal_id"], todo_id=todo_id, declaration=declaration) + return todo_id + + +def _claim(context, owner, operation): + if context["source_profile"]: + return _source_transaction(context, "coordination.local_authority.todo_claim", + "loopx_local_coordination_todo_claim_request_v3", operation_id=operation, + todo_id=context["todo"], role="agent", actor_agent_id=owner, claimed_by=owner, + manage_execution=True, lease_request=None) + code, claimed = context["cli"]("todo", "claim", "--goal-id", context["goal_id"], + "--todo-id", context["todo"], "--agent-id", owner, "--claimed-by", owner) + assert code == 0, claimed + return claimed + + +def _source_reservation(context): + # SourceSession's generic work producer is intentionally unavailable. Model + # stored reservation history through the existing append/binding owners; + # TS alone derives work_admission and closeout_required below. + fields = {"ok": True, "should_run": False, "must_attempt_work": False, + "delivery_allowed": False, "quiet_noop_allowed": True, + "prepared_lease_required": True, "semantic_replan_obligation_id": "", + "stall_observation": "not_applicable"} + reserved = append_rollout_event(rollout_event_log_path(context["runtime"], context["goal_id"]), + build_rollout_event(goal_id=context["goal_id"], goal_ref=context["goal_ref"], + event_kind="quota_should_run", agent_id=OWNER, run_id=TURN, + status="turn_reservation", details=fields)) + retained, appended = retain_pending_heartbeat_action_selection(context["runtime"], + goal_id=context["goal_id"], goal_ref=context["goal_ref"], agent_id=OWNER, + turn_instance_id=TURN, todo_id=context["todo"], reason="claim_required") + assert appended is True and retained["event_id"] != reserved["event_id"] + identity = SettlementIdentity(goal_id=context["goal_id"], agent_id=OWNER, + todo_id=context["todo"], turn_instance_id=TURN) + bound, appended = upgrade_identityless_heartbeat_receipt(context["runtime"], + goal_id=context["goal_id"], goal_ref=context["goal_ref"], agent_id=OWNER, + turn_instance_id=TURN, todo_id=context["todo"], settlement_effect_id=identity.effect_id, + status="turn_reservation", summary="Retain the original Todo while execution is prepared.", details=fields) + assert appended is True and bound["details"]["settlement_receipt_revision"] == "identity_upgrade" + ensured = ensure_turn_heartbeat_settlement_receipt(context["runtime"], identity, + semantic_replan_guard_scoped=True, semantic_replan_obligation_id=None, + prepared_lease_required=True, goal_ref=context["goal_ref"]) + assert ensured == bound + context["reservation_details"] = {key: value for key, value in bound["details"].items() + if key not in {"settlement_receipt_revision", "closeout_required"}} + + +def _source_requalify(context, lease): + fields = {**context["reservation_details"], "ok": True, "should_run": True, + "must_attempt_work": True, "delivery_allowed": True, "quiet_noop_allowed": False, + "selected_todo_id": context["todo"]} + if lease is not None: + fields.update(prepared_lease_receipt_fields({"idempotency_key": lease["idempotency_key"], + "expected_version": lease["version"]}, lease_epoch=lease["lease_epoch"])) + return requalify_bound_heartbeat_receipt(context["runtime"], + goal_id=context["goal_id"], goal_ref=context["goal_ref"], agent_id=OWNER, + turn_instance_id=TURN, todo_id=context["todo"], replan_obligation_id=None, + status="normal_run", details=fields, registry_path=context["registry"]) + + +def _fixture(tmp_path, monkeypatch, capsys, provider, *, prepared=True, + replace=True, replacement_owner=OWNER, source_profile=True): + isolate_sqlite_runtime(tmp_path, monkeypatch) + project, runtime = tmp_path / "project", tmp_path / "runtime" + registry = project / ".loopx" / "registry.json" + state = project / "GOAL.md" + if source_profile: + project.mkdir() + goal = {"id": GOAL, "project_id": "project", "title": "Recover original Turn", + "status": "active", "repo": str(project), "state_file": state.name} + configure_source_creation_goal(goal, [OWNER, PEER], provider, "register-execution-loss-goal") + created = register_fresh_source_session_project(FreshSourceSessionRegistration( + registry_path=registry, runtime_root=runtime, + operation_id="register-execution-loss-goal", project_id="project", goal_id=GOAL, + objective="Retain the original work while closing its interrupted Turn.", + non_goals=["Do not complete the task or credit delivery."], + acceptance=["Original Turn recovery preserves the current work owner."], + unknowns=[], next_effect="Inspect the interrupted execution.", + stop_condition="Stop when the original execution authority is unavailable.", + project_record={"id": "project", "kind": "work", "path": str(project)}, + goal_record=goal, state_file=state, + )) + assert created["ok"] is True, created + goal_ref, goal_id = created["goal_ref"], GOAL + else: + project, runtime, registry = write_legacy_fixture(tmp_path) + configuration = json.loads(registry.read_text()) + goal = configuration["goals"][0] + goal["coordination"]["registered_agents"] = [OWNER, PEER] + registry.write_text(json.dumps(configuration)) + goal_id, goal_ref = goal["id"], None + state = project / goal["state_file"] + state.write_text(state.read_text().split("## Agent Todo")[0] + "## Agent Todo\n\n") + initialize_canonical_source_fixture( + runtime, goal_id, state_path=state, provider=provider, handoff_mode="hard_lease", + ) + + def cli(*argv): + # This callable always exercises the real public parser and dispatcher. + with monkeypatch.context() as context: + context.chdir(project) + code = cli_main([ + "--registry", str(registry), "--runtime-root", str(runtime), + "--format", "json", *argv, + ]) + return code, read_cli_policy_payload(capsys.readouterr().out, returncode=code) + + context = {"cli": cli, "project": project, "runtime": runtime, "registry": registry, + "state": state, "goal_id": goal_id, "goal_ref": goal_ref, "source_profile": source_profile} + validation_argv = [sys.executable, "-c", + "from pathlib import Path; Path('completion-validator-ran').write_text('ran')"] + if source_profile: + todo = _source_create_todo(context, validation_argv) + else: + code, added = cli("todo", "add", "--goal-id", goal_id, "--role", "agent", + "--text", "Validate the original task before declaring completion.", + "--action-kind", "validate", "--continuation-policy", "same_agent_non_delivery", + "--claimed-by", OWNER, "--operation-id", "execution-loss-task", "--execute", + "--validation-command-json", json.dumps(validation_argv)) + assert code == 0, json.dumps(added, ensure_ascii=False) + todo = added["todo_id"] + context["todo"] = todo + if source_profile: + _source_reservation(context) + if not prepared: + if source_profile: + pending, appended = _source_requalify(context, None) + assert appended is True and "prepared_lease_key_sha256" not in pending["details"] + else: + code, pending = cli(*_guard_args(context)) + assert code == 0 and pending["execution_preparation"]["state"] == "claim_required", pending + claim = _claim(context, OWNER, "execution-loss-original-claim") + original_lease = _lease(context) + context["original_lease"] = original_lease + if prepared: + if source_profile: + admitted, appended = _source_requalify(context, original_lease) + assert appended is True + assert admitted["details"]["settlement_receipt_revision"] == "work_admission" + assert admitted["details"]["closeout_required"] is True + assert admitted["details"]["prepared_lease_epoch"] == original_lease["lease_epoch"] + else: + code, admitted = cli(*_guard_args(context)) + assert code == 0 and admitted["normal_delivery_allowed"] is True, admitted + assert admitted["heartbeat_receipt"]["closeout_required"] is True + assert admitted["execution_preparation"]["lease_epoch"] == original_lease["lease_epoch"] + context["admitted"] = admitted + context["receipt_lines"] = _receipt_lines(context) + assert context["receipt_lines"], "the original receipt must be production-generated" + if replace: + after_expiry = datetime.fromisoformat( + original_lease["expires_at"].replace("Z", "+00:00"), + ).replace(microsecond=0) + timedelta(seconds=2) + + class AfterExpiryDatetime(datetime): + @classmethod + def now(cls, tz=None): + return (after_expiry.astimezone(tz) if tz + else after_expiry.astimezone().replace(tzinfo=None)) + + # Registered transport clock seams, never edits to persisted lease bytes. + monkeypatch.setattr(runtime_time, "datetime", AfterExpiryDatetime) + monkeypatch.setattr(local_authority, "now_local", lambda: after_expiry.isoformat()) + monkeypatch.setattr(task_lease, "now_utc", lambda: after_expiry.astimezone(timezone.utc)) + assert runtime_time.now_utc() == after_expiry.astimezone(timezone.utc) + replacement = _claim(context, replacement_owner, "execution-loss-replacement-claim") + assert replacement["claim_operation_id"] != claim["claim_operation_id"] + current = _lease(context) + assert current["owner"] == replacement_owner + assert current["lease_epoch"] > original_lease["lease_epoch"] + assert current["version"] > original_lease["version"] + assert current["idempotency_key"] != original_lease["idempotency_key"] + context["current_lease"] = _lease(context) + assert _receipt_lines(context) == context["receipt_lines"] + return context + + +def _binding(context): + return ["--goal-id", context["goal_id"], + *(["--goal-instance-id", context["goal_ref"]["goal_instance_id"]] if context["goal_ref"] else []), + "--agent-id", OWNER, "--todo-id", context["todo"], "--turn-instance-id", TURN] + + +def _guard_args(context): + return ["quota", "should-run", "--codex-app", "--context-delivery", "off", *_binding(context)] + + +def _proof(lease): + return ["--task-lease-idempotency-key", lease["idempotency_key"], + "--task-lease-expected-version", str(lease["version"])] + + +def _closeout_args(context, *, lease=None, execution_loss=True): + return ["refresh-state", *_binding(context), + *(["--execution-loss-closeout"] if execution_loss else []), + "--classification", "execution_loss_closeout", "--delivery-batch-scale", "single_surface", + "--delivery-outcome", "outcome_gap", "--delivery-boundary", "semantic_closeout", + "--progress-result-class", "blocked", "--progress-work-item-id", context["todo"], + "--progress-blocker-id", "original-execution-lost", + "--progress-evidence-id", "evidence:original-lease-expired", + *(["--vision-unchanged-reason", "The original work remains open; close only its interrupted Turn."] + if not execution_loss else []), + "--no-global-sync", "--suppress-external-sinks", + *_proof(lease or context["current_lease"])] + + +def _lease(context): + if context["source_profile"]: + inspected = effect_runtime_result("task_lease.inspect.native", { + "schema_version": "loopx_task_lease_inspect_request_v0", "source": "canonical", + "runtime_root": str(context["runtime"].resolve()), "goal_id": context["goal_id"], + "todo_id": context["todo"], "authority": {"handoff_mode": "hard_lease", "todos": [], + "registered_agent_candidates": [_registered_agents(context)], + "source_receipts": [{"source_id": "registry", "path": str(context["registry"].resolve()), + "state": "file", "sha256": sha256(context["registry"].read_bytes()).hexdigest()}]}, + }) + assert inspected["ok"] is True and inspected["source_authority"] in {"file_v0", "sqlite_v0"}, inspected + assert inspected["provider_revision"] == _canonical(context)["provider_revision"] + assert inspected["legacy_fallback_used"] is False + assert isinstance(inspected["lease"], dict) + return inspected["lease"] + code, inspected = context["cli"]( + "task-lease", "inspect", "--goal-id", context["goal_id"], "--todo-id", context["todo"], + ) + assert code == 0, inspected + assert isinstance(inspected["lease"], dict) + return inspected["lease"] + + +def _readback(context): + return settlement.read_heartbeat_settlement( + context["runtime"], goal_id=context["goal_id"], agent_id=OWNER, todo_id=context["todo"], + turn_instance_id=TURN, registry_path=context["registry"], goal_ref=context["goal_ref"], + ) + + +def _receipt_lines(context): + path = rollout_event_log_path(context["runtime"], context["goal_id"]) + if not path.exists(): + return [] + return [line for line in path.read_bytes().splitlines(keepends=True) + if (event := json.loads(line)).get("event_kind") == "quota_should_run" + and event.get("run_id") == TURN + and (event.get("goal_ref") == context["goal_ref"] if context["goal_ref"] else "goal_ref" not in event)] + + +def _runs(context): + directory = context["runtime"] / "goals" / context["goal_id"] / "runs" + return {path.name: path.read_bytes() for path in directory.glob("*.json")} + + +def _canonical(context): + payload = local_authority.read_canonical_todos_if_promoted( + runtime_root=context["runtime"], goal_id=context["goal_id"], include_leases=True, + ) + assert payload is not None + return {key: payload[key] for key in ("store_identity", "provider_revision", "todos", "leases")} + + +def _unchanged_state(context): + log = rollout_event_log_path(context["runtime"], context["goal_id"]) + return (_canonical(context), context["state"].read_bytes(), _runs(context), log.read_bytes()) + + +def _assert_no_completion_or_debit(context): + if context["source_profile"]: + todo = next(row for row in _canonical(context)["todos"] if row["todo_id"] == context["todo"]) + else: + code, listed = context["cli"]("todo", "list", "--goal-id", context["goal_id"], "--todo-id", context["todo"]) + assert code == 0, listed + todo = listed["todo"] + assert todo["status"] == "open" and todo.get("completion_validation_required") is True + assert not (context["project"] / "completion-validator-ran").exists() + index = context["runtime"] / "goals" / context["goal_id"] / "runs" / "index.jsonl" + records = [json.loads(line) for line in index.read_text().splitlines()] if index.exists() else [] + assert not any(record.get("classification") == "quota_slot_spent" for record in records) + + +def _assert_original_prepared_generation(context, readback): + original, current = context["original_lease"], context["current_lease"] + assert readback.prepared_lease == { + "prepared_lease_key_sha256": sha256(original["idempotency_key"].encode()).hexdigest(), + "prepared_lease_version": original["version"], + "prepared_lease_epoch": original["lease_epoch"], + } + if current["lease_epoch"] != original["lease_epoch"]: + assert readback.prepared_lease["prepared_lease_key_sha256"] != sha256( + current["idempotency_key"].encode(), + ).hexdigest() + + +def _reject_without_effect(context, argv, *, expected_code=None): + before = _unchanged_state(context) + code, rejected = context["cli"](*argv) + assert code != 0 and rejected["ok"] is False, rejected + if expected_code is not None: + assert rejected.get("error_code") == expected_code, json.dumps(rejected, ensure_ascii=False) + assert _unchanged_state(context) == before + _assert_no_completion_or_debit(context) + return rejected + + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("source_profile", [False, True], ids=["legacy", "exact-source"]) +def test_closeout_preserves_the_original_turn_and_releases_the_next_guard( + tmp_path, monkeypatch, capsys, provider, source_profile, +): + context = _fixture(tmp_path, monkeypatch, capsys, provider, source_profile=source_profile) + original = _readback(context) + _assert_original_prepared_generation(context, original) + assert not original.writeback.receipts and not original.spend.receipts + if not source_profile: + # A fresh guard recognizes the generation change before attempting to + # re-enter the original guard. It offers only the administrative route. + code, recovery = context["cli"]( + "quota", "should-run", "--context-delivery", "off", "--codex-app", + "--goal-id", context["goal_id"], "--agent-id", OWNER, "--turn-instance-id", "needs-recovery", + ) + assert code == 0, recovery + debt = recovery["unsettled_host_turn_recovery"] + assert debt["repair"] == "execution_loss_closeout" + assert debt["prior_turn_instance_id"] == TURN + assert debt["execution_loss"]["original_prepared_epoch"] == context["original_lease"]["lease_epoch"] + assert debt["execution_loss"]["current_lease_epoch"] == context["current_lease"]["lease_epoch"] + assert recovery["execution_obligation"]["delivery_allowed"] is False + cli_channel = recovery["interaction_contract"]["cli_channel"] + assert cli_channel["spend_allowed_now"] is False + assert any("--execution-loss-closeout" in cmd and "--dry-run" in cmd + for cmd in cli_channel["next_cli_actions"]) + argv = _closeout_args(context) + before = _unchanged_state(context) + code, preview = context["cli"](*argv, "--dry-run") + assert code == 0 and preview["would_close_without_spend"] is True, preview + assert preview["appended"] is False and preview["replay_phase"] == "open" + assert _unchanged_state(context) == before + + code, closed = context["cli"](*argv) + assert code == 0 and closed["appended"] is True, closed + assert closed["settlement_identity"] == original.identity.value.as_dict() + assert closed["settlement_progress"]["state"] == "settled" + assert closed["settlement_progress"]["no_spend"] is True + assert _canonical(context) == before[0] and context["state"].read_bytes() == before[1] + assert _receipt_lines(context) == context["receipt_lines"] + assert _readback(context).heartbeat_receipt == original.heartbeat_receipt + _assert_no_completion_or_debit(context) + + before = _unchanged_state(context) + code, replay = context["cli"](*argv) + assert code == 0 and replay["idempotent_replay"] is True and replay["appended"] is False, replay + assert _unchanged_state(context) == before + if not source_profile: + fresh_args = [*(_guard_args(context))] + fresh_args[fresh_args.index("--turn-instance-id") + 1] = "next-real-turn" + code, fresh = context["cli"](*fresh_args) + assert code == 0 and fresh["normal_delivery_allowed"] is True, fresh + assert fresh.get("unsettled_host_turn_recovery") is None + code, debited = context["cli"]( + "quota", "spend-slot", *_binding(context), "--slots", "1", "--source", "heartbeat", "--execute", + ) + assert code == 0 and debited["appended"] is False, debited + _assert_no_completion_or_debit(context) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_rejects_same_generation_and_business_side_effects(tmp_path, monkeypatch, capsys, provider): + context = _fixture(tmp_path, monkeypatch, capsys, provider, replace=False, source_profile=False) + code, recovery = context["cli"]( + "quota", "should-run", "--context-delivery", "off", "--codex-app", + "--goal-id", context["goal_id"], "--agent-id", OWNER, "--turn-instance-id", "same-generation", + ) + assert code == 0, recovery + assert recovery["unsettled_host_turn_recovery"]["repair"] == "resume_prior_turn" + args = _closeout_args(context) + _reject_without_effect(context, args, expected_code="refresh_task_lease_unavailable") + _reject_without_effect(context, [*args, "--next-action", "Promote the replacement's business work."]) + _reject_without_effect(context, [*args, "--completion-todo-id", context["todo"]]) + _reject_without_effect(context, [*args, "--vision-state", "active"]) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_rejects_another_owner_and_stale_proof(tmp_path, monkeypatch, capsys, provider): + context = _fixture(tmp_path, monkeypatch, capsys, provider, source_profile=False) + _reject_without_effect(context, _closeout_args(context, lease=context["original_lease"]), + expected_code="refresh_task_lease_unavailable") + args = _closeout_args(context) + args[args.index("--agent-id") + 1] = PEER + _reject_without_effect(context, args) diff --git a/tests/control_plane/test_goal_outcome_diagnostics.py b/tests/control_plane/test_goal_outcome_diagnostics.py index 59ebd19bb1..27985fe0a4 100644 --- a/tests/control_plane/test_goal_outcome_diagnostics.py +++ b/tests/control_plane/test_goal_outcome_diagnostics.py @@ -40,7 +40,10 @@ def arguments(project, cli, entrypoint, document, operation): @pytest.mark.parametrize("entrypoint", ["refine", "refresh"]) @pytest.mark.parametrize(("source_ref", "detail"), [ - ("synthetic/private-ref", "source ref must be an opaque identifier"), + ( + "synthetic/private-ref", + "source ref must be an opaque identifier (ASCII letters/digits and . _ : @ -, no '/' paths or spaces)", + ), ("synthetic-private-ref ", "source ref must be bounded nonempty text"), ]) def test_native_rejection_then_corrected_same_operation(acceptance_goal, entrypoint, source_ref, detail): diff --git a/tests/control_plane/test_release_commit_qualification.py b/tests/control_plane/test_release_commit_qualification.py index 214d303c2f..37c96f532a 100644 --- a/tests/control_plane/test_release_commit_qualification.py +++ b/tests/control_plane/test_release_commit_qualification.py @@ -545,6 +545,32 @@ def test_qualify_release_commit_parallelism_and_preflight_selection(tmp_path: Pa "tests/test_custom.py", ] + release_repo = tmp_path / "release-repo" + for rel in ( + "tests/test_dsh_plugin_publish_workflow.py", + "tests/desktop/test_desktop_signing_workflow.py", + "tests/desktop/test_update_feed.py", + "tests/control_plane/test_release_multi_surface_preflight.py", + ): + target = release_repo / rel + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text("def test_ok(): pass\n", encoding="utf-8") + + selected_release = runner["select_preflight_tests"]( + [ + ".github/workflows/dsh-plugin-publish.yml", + ".github/workflows/desktop-release-artifacts.yml", + "docs/product/release-readiness.md", + ], + repo_root=release_repo, + ) + assert selected_release == [ + "tests/test_dsh_plugin_publish_workflow.py", + "tests/desktop/test_desktop_signing_workflow.py", + "tests/desktop/test_update_feed.py", + "tests/control_plane/test_release_multi_surface_preflight.py", + ] + def test_qualify_release_commit_resume_requires_exact_source_and_reduces_junit(tmp_path: Path) -> None: import importlib.util diff --git a/tests/control_plane/test_release_multi_surface_preflight.py b/tests/control_plane/test_release_multi_surface_preflight.py new file mode 100644 index 0000000000..cd3f2e9b0d --- /dev/null +++ b/tests/control_plane/test_release_multi_surface_preflight.py @@ -0,0 +1,348 @@ +from __future__ import annotations + +import json +import runpy +import subprocess +import sys +from pathlib import Path +from typing import Any + +import pytest + +REPO_ROOT = Path(__file__).resolve().parents[2] +SCRIPT_PATH = REPO_ROOT / "scripts" / "release_multi_surface_preflight.py" + + +def _git(repo: Path, *args: str) -> None: + subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True, text=True) + + +def _create_fixture_repo(tmp_path: Path, *, core_version: str = "2.4.0", dsh_version: str = "0.1.1-beta.7") -> Path: + remote = tmp_path / "remote.git" + _git(tmp_path, "init", "--bare", str(remote)) + + repo = tmp_path / "repo" + repo.mkdir() + _git(repo, "init", "-b", "main") + _git(repo, "config", "user.name", "Fixture User") + _git(repo, "config", "user.email", "fixture@example.com") + + (repo / "pyproject.toml").write_text( + f'[project]\nname = "loopx"\nversion = "{core_version}"\n', + encoding="utf-8", + ) + (repo / "loopx" / "control_plane" / "testing").mkdir(parents=True) + (repo / "loopx" / "__init__.py").write_text(f'__version__ = "{core_version}"\n', encoding="utf-8") + (repo / "loopx" / "control_plane" / "testing" / "release_metadata.py").write_text( + (REPO_ROOT / "loopx" / "control_plane" / "testing" / "release_metadata.py").read_text(encoding="utf-8"), + encoding="utf-8", + ) + (repo / "man").mkdir() + (repo / "man" / "loopx.1").write_text(".TH LOOPX 1\n", encoding="utf-8") + + desktop = repo / "apps" / "desktop" / "loopx-control-plane" / "src-tauri" + desktop.mkdir(parents=True) + (repo / "apps" / "desktop" / "loopx-control-plane" / "package.json").write_text( + '{"name": "@loopx/control-plane-desktop", "version": "0.1.0"}\n', + encoding="utf-8", + ) + (desktop / "Cargo.toml").write_text('[package]\nname = "loopx-control-plane"\nversion = "0.1.0"\n', encoding="utf-8") + (desktop / "tauri.conf.json").write_text( + json.dumps( + { + "version": "0.1.0", + "plugins": { + "updater": { + "pubkey": "fixture-pubkey", + "endpoints": ["https://github.com/loopx-project/loopx/releases/download/desktop-stable/desktop-updater.json"], + } + }, + } + ), + encoding="utf-8", + ) + (repo / "scripts").mkdir() + (repo / "scripts" / "desktop_macos_signing.py").write_text("#!/usr/bin/env python3\n", encoding="utf-8") + (repo / "scripts" / "desktop_release_artifacts.py").write_text( + (REPO_ROOT / "scripts" / "desktop_release_artifacts.py").read_text(encoding="utf-8"), + encoding="utf-8", + ) + + dsh = repo / "packages" / "dsh-loopx-plugin" + dsh.mkdir(parents=True) + (dsh / "package.json").write_text( + json.dumps( + { + "name": "dsh-loopx-plugin", + "version": dsh_version, + "keywords": ["dsh-plugin"], + "dsh": {"bundle": {"patch": "./cordis.patch.yml"}}, + "repository": {"type": "git", "url": "git+https://github.com/loopx-project/loopx.git"}, + } + ), + encoding="utf-8", + ) + (dsh / "cordis.patch.yml").write_text("patches: {}\n", encoding="utf-8") + (dsh / "pnpm-lock.yaml").write_text("lockfileVersion: '9.0'\n", encoding="utf-8") + + notes_dir = repo / "docs" / "product" / "releases" + notes_dir.mkdir(parents=True) + (notes_dir / f"v{core_version}.md").write_text( + "## Release Decision\n\nGuide: https://my.feishu.cn/docx/FixtureDoc123\n\n### 升级决策\n\n验证完成。\n", + encoding="utf-8", + ) + + _git(repo, "add", ".") + _git(repo, "commit", "-m", "fixture release candidate") + _git(repo, "remote", "add", "origin", str(remote)) + _git(repo, "push", "-u", "origin", "HEAD:refs/heads/stable") + _git(repo, "push", "-u", "origin", "HEAD:refs/heads/main") + _git(repo, "fetch", "origin") + return repo + + +def test_real_checkout_offline_preflight_passes() -> None: + proc = subprocess.run( + [ + sys.executable, + str(SCRIPT_PATH), + "--repo-root", + str(REPO_ROOT), + "--format", + "json", + ], + check=False, + capture_output=True, + text=True, + ) + assert proc.returncode == 0, proc.stdout + proc.stderr + payload = json.loads(proc.stdout) + assert payload["ok"] is True + assert payload["schema_version"] == "loopx_multi_surface_release_preflight_v1" + assert payload["ready_for_local_qualification"] is True + assert payload["published_complete"] is None + assert set(payload["surfaces"]) == {"core", "desktop", "dsh", "notes"} + + +def test_fixture_offline_detects_dirty_tree_forbidden_note_path_and_version_mismatch(tmp_path: Path) -> None: + mod = runpy.run_path(str(SCRIPT_PATH)) + run_preflight = mod["run_preflight"] + repo = _create_fixture_repo(tmp_path) + + clean = run_preflight(repo_root=repo, selected_surfaces=("core", "desktop", "dsh", "notes"), require_clean=True) + assert clean["ok"] is True + + # Dirty tracked file fails --require-clean + (repo / "man" / "loopx.1").write_text(".TH LOOPX 1 modified\n", encoding="utf-8") + # Forbidden local path string breaks notes local_ok + (repo / "docs" / "product" / "releases" / "v2.4.0.md").write_text( + "## Release Decision\nBad path /Users/example/work\n### 升级决策\n", + encoding="utf-8", + ) + bad = run_preflight(repo_root=repo, selected_surfaces=("core", "notes"), require_clean=True) + assert bad["ok"] is False + assert bad["surfaces"]["core"]["tracked_clean"] is False + assert bad["surfaces"]["core"]["local_ok"] is False + assert bad["surfaces"]["notes"]["public_boundary_clean"] is False + assert bad["surfaces"]["notes"]["local_ok"] is False + + # Version mismatch fails metadata loader + (repo / "loopx" / "__init__.py").write_text('__version__ = "2.5.0"\n', encoding="utf-8") + with pytest.raises(ValueError, match="version mismatch"): + run_preflight(repo_root=repo, selected_surfaces=("core",)) + + +@pytest.mark.parametrize( + ("npm_status", "npm_payload", "expected_state", "expected_code", "expected_published"), + [ + (404, {}, "bootstrap_required", "npm_bootstrap_required", False), + ( + 200, + {"dist-tags": {"latest": "0.0.0-stage"}, "versions": {"0.0.0-stage": {}}, "maintainers": []}, + "staging_scan_in_progress", + "npm_staging_scan_in_progress", + False, + ), + ( + 200, + { + "dist-tags": {"latest": "0.1.1-beta.7"}, + "versions": {"0.1.1-beta.7": {}}, + "maintainers": [{"name": "fixture-maintainer"}], + }, + "published", + None, + True, + ), + ], +) +def test_fixture_online_classifies_npm_bootstrap_staging_and_published( + tmp_path: Path, + npm_status: int, + npm_payload: dict[str, Any], + expected_state: str, + expected_code: str | None, + expected_published: bool, +) -> None: + mod = runpy.run_path(str(SCRIPT_PATH)) + run_preflight = mod["run_preflight"] + repo = _create_fixture_repo(tmp_path) + + expected_dsh_tarball = "https://github.com/loopx-project/loopx/releases/download/dsh-loopx-plugin-v0.1.1-beta.7/dsh-loopx-plugin-0.1.1-beta.7.tgz" + + def fake_gh_release(_gh_repo: str, tag: str) -> dict[str, Any]: + if tag == "v2.4.0": + return { + "available": True, + "exists": True, + "is_draft": False, + "body": "## Release Decision\nGuide: https://my.feishu.cn/docx/FixtureDoc123\n\n### 升级决策\n验证完成。\n", + "asset_names": [ + "DESKTOP-SHA256SUMS", + "LoopX.app.tar.gz", + "LoopX.app.tar.gz.sig", + "LoopX.app.zip", + "LoopX_2.4.0_aarch64.dmg", + "LoopX_2.4.0_x64-setup.exe", + "LoopX_2.4.0_x64_en-US.msi", + "SHA256SUMS", + "desktop-updater.json", + "loopx-2.4.0-py3-none-any.whl", + "loopx-2.4.0.tar.gz", + ], + } + if tag == "desktop-stable": + return { + "available": True, + "exists": True, + "is_draft": False, + "asset_names": ["desktop-updater.json"], + } + if tag == "dsh-loopx-plugin-v0.1.1-beta.7": + return { + "available": True, + "exists": True, + "is_draft": False, + "asset_names": ["dsh-loopx-plugin-0.1.1-beta.7.tgz"], + } + return {"available": True, "exists": False, "asset_names": []} + + def fake_http(url: str) -> tuple[int | None, str, str | None]: + if "pypi.org/pypi/loopx/json" in url: + return 200, json.dumps({"releases": {"2.4.0": []}}), None + if "desktop-updater.json" in url: + return ( + 200, + json.dumps( + { + "version": "2.4.0", + "platforms": {"darwin-aarch64": {"url": "https://example.com/LoopX.app.tar.gz"}}, + } + ), + None, + ) + if "registry.npmjs.org/dsh-loopx-plugin" in url: + return npm_status, json.dumps(npm_payload), None + if "awesome-dsh-plugin" in url: + return 200, f"tarball: {expected_dsh_tarball}\n", None + return 404, "", "HTTP 404" + + result = run_preflight( + repo_root=repo, + selected_surfaces=("core", "desktop", "dsh", "notes"), + online=True, + require_published=True, + http_get=fake_http, + gh_release=fake_gh_release, + ) + assert result["surfaces"]["dsh"]["online"]["npm"]["state"] == expected_state + assert result["surfaces"]["dsh"]["published_ok"] is expected_published + assert result["surfaces"]["desktop"]["online"]["updater_feed_version"] == "2.4.0" + assert result["surfaces"]["notes"]["online"]["feishu_doc_verification"] == "requires_authenticated_lark_cli" + assert result["published_complete"] is expected_published + assert result["ok"] is expected_published + codes = [item["code"] for item in result["remediations"]] + if expected_code is None: + assert codes == [] + else: + assert expected_code in codes + if expected_code == "npm_bootstrap_required": + bootstrap_msg = next( + item["action"] for item in result["remediations"] if item["code"] == "npm_bootstrap_required" + ) + assert "Allow npm publish" in bootstrap_msg + + +def test_fixture_detects_bilingual_note_gap_updater_version_skew_and_keep_proxy( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + mod = runpy.run_path(str(SCRIPT_PATH)) + run_preflight = mod["run_preflight"] + build_parser = mod["build_parser"] + repo = _create_fixture_repo(tmp_path) + + # 1. Missing bilingual Chinese heading emits explicit remediation + note = repo / "docs" / "product" / "releases" / "v2.4.0.md" + note.write_text("## Release Decision\nGuide: https://my.feishu.cn/docx/FixtureDoc123\n", encoding="utf-8") + bilingual_gap = run_preflight(repo_root=repo, selected_surfaces=("notes",)) + assert bilingual_gap["surfaces"]["notes"]["local_ok"] is False + assert any(r["code"] == "release_note_bilingual_sections_incomplete" for r in bilingual_gap["remediations"]) + + # Restore valid local note, verify stale desktop-updater.json & release body without Feishu link fail online + note.write_text( + "## Release Decision\nGuide: https://my.feishu.cn/docx/FixtureDoc123\n\n### 升级决策\n通过。\n", + encoding="utf-8", + ) + + def stale_gh(_gh_repo: str, tag: str) -> dict[str, Any]: + if tag == "v2.4.0": + return { + "available": True, + "exists": True, + "is_draft": False, + "body": "## Release Decision\n\n### 升级决策\nMissing feishu link.\n", + "asset_names": [ + "DESKTOP-SHA256SUMS", + "LoopX.app.tar.gz", + "LoopX.app.tar.gz.sig", + "LoopX.app.zip", + "LoopX_2.4.0_aarch64.dmg", + "LoopX_2.4.0_x64-setup.exe", + "LoopX_2.4.0_x64_en-US.msi", + "desktop-updater.json", + ], + } + if tag == "desktop-stable": + return {"available": True, "exists": True, "is_draft": False, "asset_names": ["desktop-updater.json"]} + return {"available": True, "exists": False, "asset_names": []} + + def stale_http(url: str) -> tuple[int | None, str, str | None]: + if "desktop-updater.json" in url: + return 200, json.dumps({"version": "2.3.0", "platforms": {"darwin-aarch64": {"url": "https://example.com"}}}), None + return 404, "", "HTTP 404" + + bad_online = run_preflight( + repo_root=repo, + selected_surfaces=("desktop", "notes"), + online=True, + require_published=True, + http_get=stale_http, + gh_release=stale_gh, + ) + assert bad_online["ok"] is False + assert bad_online["surfaces"]["desktop"]["published_ok"] is False + assert bad_online["surfaces"]["notes"]["published_ok"] is False + codes = {item["code"] for item in bad_online["remediations"]} + assert "desktop_updater_feed_version_mismatch" in codes + assert "github_release_notes_incomplete" in codes + + # 2. --keep-proxy preserves ambient proxy env while default strips it + monkeypatch.setenv("HTTPS_PROXY", "http://127.0.0.1:7890") + assert build_parser().parse_args(["--keep-proxy"]).keep_proxy is True + assert build_parser().parse_args([]).keep_proxy is False + mod["main"](["--repo-root", str(repo), "--surface", "core", "--keep-proxy", "--format", "json"]) + import os + + assert os.environ.get("HTTPS_PROXY") == "http://127.0.0.1:7890" + mod["main"](["--repo-root", str(repo), "--surface", "core", "--format", "json"]) + assert "HTTPS_PROXY" not in os.environ diff --git a/tests/control_plane/test_source_cli_entrypoint.py b/tests/control_plane/test_source_cli_entrypoint.py index a35d501a01..9666c01499 100644 --- a/tests/control_plane/test_source_cli_entrypoint.py +++ b/tests/control_plane/test_source_cli_entrypoint.py @@ -135,10 +135,13 @@ def replace_process(executable, argv): result = run_entry(entry, native_argv(), setup=setup, assertions=""" assert len(seen) == 1 assert seen[0][0] == "/fixture/node" -assert seen[0][1][1:3] == ["--no-warnings", "--experimental-strip-types"] +from loopx.control_plane.runtime.node_probe import node_typescript_flags +expected_flags = list(node_typescript_flags()) +script_index = 3 + len(expected_flags) +assert seen[0][1][1:script_index] == ["--no-warnings", "--experimental-strip-types", *expected_flags] from pathlib import Path -assert Path(seen[0][1][3]).parts[-2:] == ("scheduler", "heartbeat_followup_cli.ts") -assert seen[0][1][4:] == sys.argv[1:] +assert Path(seen[0][1][script_index]).parts[-2:] == ("scheduler", "heartbeat_followup_cli.ts") +assert seen[0][1][script_index + 1:] == sys.argv[1:] assert "loopx.cli_runtime" not in sys.modules assert "loopx.cli" not in sys.modules """) diff --git a/tests/control_plane/test_status_facade_vocabulary_owners.py b/tests/control_plane/test_status_facade_vocabulary_owners.py index 9b6069fb2c..cbe909193c 100644 --- a/tests/control_plane/test_status_facade_vocabulary_owners.py +++ b/tests/control_plane/test_status_facade_vocabulary_owners.py @@ -87,6 +87,19 @@ ), } +RETIRED_FACADE_REEXPORTS: tuple[str, ...] = ( + "AUTONOMOUS_REPLAN_SCHEMA_VERSION", + "BACKLOG_HYGIENE_BULLET_PATTERN", + "BACKLOG_HYGIENE_HINT_PATTERN", + "BACKLOG_HYGIENE_SECTION_HEADINGS", + "DEAD_MONITOR_REPEAT_SCHEMA_VERSION", + "MINIMUM_DASHBOARD_STATUS_CONTRACT_SCHEMA_VERSION", + "MONITOR_DISPLAY_SCHEMA_VERSION", + "SECTION_HEADING_PATTERN", + "STATUS_CONTRACT_SCHEMA_VERSION", + "STATUS_CONTRACT_SIGNAL_LIMIT", +) + # Nothing is left forked outside the facade. The last recorded name, # AGENT_LANE_PROGRESS_SCOPE, was single-sourced into # ``loopx/control_plane/progress_scope.py``; it is asserted as a fully merged name @@ -200,6 +213,8 @@ def test_the_facade_and_its_projections_share_one_object() -> None: assert getattr(importer, name) is getattr(owner, name), ( f"{name} via {importer}" ) + for name in RETIRED_FACADE_REEXPORTS: + assert not hasattr(status, name), name def test_merging_the_copies_changed_no_value() -> None: diff --git a/tests/control_plane/test_todo_claim_argument_recovery.py b/tests/control_plane/test_todo_claim_argument_recovery.py index 871640cd88..2a9ad438e3 100644 --- a/tests/control_plane/test_todo_claim_argument_recovery.py +++ b/tests/control_plane/test_todo_claim_argument_recovery.py @@ -795,5 +795,107 @@ def test_task_help_exposes_managed_reference_not_host_lease_flags(): result = subprocess.run([sys.executable, "-m", "loopx.cli", "todo", "claim", "--help"], cwd=REPO, capture_output=True, text=True, check=True) assert "--claim-operation-id" in result.stdout + assert "--ttl-seconds" in result.stdout assert "--task-lease-idempotency-key" not in result.stdout assert "--task-lease-expected-version" not in result.stdout + + +@pytest.mark.parametrize("thin", [False, True]) +def test_claim_ttl_seconds_bounds_visibility_and_replay_parity(claim_cli, thin): + _, run, snapshot, prefix, claim, _, _, _ = claim_cli + before = snapshot() + + for bad_ttl in (0, 86401): + rejected = run([ + *prefix, *claim, "--claimed-by", "peer-a", + "--ttl-seconds", str(bad_ttl), + *(["--thin"] if thin else []), + ], expected_exit=1) + assert rejected["ok"] is False + assert "1 and 86400" in rejected["error"] + assert snapshot() == before + + unmanaged = run([ + *prefix, "todo", "claim", "--goal-id", GOAL, "--todo-id", TODO, + "--claimed-by", "peer-a", "--ttl-seconds", "7200", + ], expected_exit=1) + assert unmanaged["ok"] is False + assert "--ttl-seconds requires managed execution" in unmanaged["error"] + assert snapshot() == before + + accepted = run([ + *prefix, *claim, "--claimed-by", "peer-a", + "--claim-operation-id", f"claim-long-{thin}", + "--ttl-seconds", "7200", + *(["--thin"] if thin else []), + ]) + assert accepted["ok"] is True and accepted["execution_managed"] is True + assert "lease" not in accepted + assert accepted["lease_ttl_seconds"] == 7200 + assert isinstance(accepted["lease_expires_at"], str) and accepted["lease_expires_at"].endswith("Z") + assert "--ttl-seconds" in accepted["instruction"] + assert "task-lease renew" in accepted["instruction"] + assert "--next-action" in accepted["instruction"] + + inspected = run([*prefix, "task-lease", "inspect", "--goal-id", GOAL, "--todo-id", TODO]) + assert inspected["active"] is True + assert inspected["lease"]["acquire_ttl_seconds"] == 7200 + assert inspected["lease"]["expires_at"] == accepted["lease_expires_at"] + + replayed = run([ + *prefix, *claim, "--claimed-by", "peer-a", + "--claim-operation-id", f"claim-long-{thin}", + "--ttl-seconds", "7200", + *(["--thin"] if thin else []), + ]) + assert replayed["ok"] is True and replayed["status"] == "replayed" + assert replayed["lease_ttl_seconds"] == 7200 + assert replayed["lease_expires_at"] == accepted["lease_expires_at"] + + mismatched = run([ + *prefix, *claim, "--claimed-by", "peer-a", + "--claim-operation-id", f"claim-long-{thin}", + "--ttl-seconds", "3600", + ], expected_exit=1) + assert mismatched["ok"] is False + assert mismatched["error_code"] == "coordination_operation_identity_mismatch" + + md = subprocess.run( + [ + sys.executable, "-m", "loopx.cli", + *prefix[:-2], "--format", "markdown", + *claim, "--claimed-by", "peer-a", + "--claim-operation-id", f"claim-long-{thin}", + "--ttl-seconds", "7200", + ], + cwd=REPO, capture_output=True, text=True, timeout=90, check=True, + ) + assert f"lease_expires_at: `{accepted['lease_expires_at']}`" in md.stdout + assert "lease_ttl_seconds: `7200`" in md.stdout + + +def test_claim_omitted_ttl_preserves_2700_default_and_explicit_lease_ttl(claim_cli): + _, run, _, prefix, claim, _, _, _ = claim_cli + default_claim = run([ + *prefix, *claim, "--claimed-by", "peer-a", "--claim-operation-id", "claim-default-ttl", + ]) + assert default_claim["ok"] is True and default_claim["execution_managed"] is True + assert default_claim["lease_ttl_seconds"] == 2700 + assert isinstance(default_claim["lease_expires_at"], str) and default_claim["lease_expires_at"] + inspected = run([*prefix, "task-lease", "inspect", "--goal-id", GOAL, "--todo-id", TODO]) + assert inspected["lease"]["acquire_ttl_seconds"] == 2700 + + # Release and verify explicit --task-lease-idempotency-key honors --ttl-seconds too. + released = run([ + *prefix, "task-lease", "release", "--goal-id", GOAL, "--todo-id", TODO, + "--owner", "peer-a", "--idempotency-key", inspected["lease"]["idempotency_key"], + "--expected-version", str(inspected["lease"]["version"]), + ]) + assert released["ok"] is True + explicit = run([ + *prefix, *claim, "--claimed-by", "peer-a", "--claim-operation-id", "claim-explicit-ttl", + "--task-lease-idempotency-key", "explicit-ttl-key", "--task-lease-expected-version", "1", + "--ttl-seconds", "5400", + ]) + assert explicit["ok"] is True + assert explicit["lease"]["acquire_ttl_seconds"] == 5400 diff --git a/tests/control_plane/test_turn_run_once_claim_preparation.py b/tests/control_plane/test_turn_run_once_claim_preparation.py index 47692a920e..74f3f14295 100644 --- a/tests/control_plane/test_turn_run_once_claim_preparation.py +++ b/tests/control_plane/test_turn_run_once_claim_preparation.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +import shlex import subprocess from pathlib import Path @@ -44,6 +45,7 @@ def _decision(*, state: str = "claim_required", host_execution_allowed: bool = T "reason_code": "task_lease_missing", "claim": { "command": "loopx todo claim", + "command_line": shlex.join(["loopx", *advertised, "--thin"]), "cli_args": advertised if cli_args is None else cli_args, "host_execution_allowed": host_execution_allowed, "postcondition": ( @@ -316,3 +318,109 @@ def test_a_legacy_unstarted_cadence_reservation_recovers_without_a_second_start( migrated.confirm() duplicate = migrated.admit(attempt) assert duplicate["admitted"] is False and duplicate["reason"] == "duplicate_or_stale_trigger" + + +def test_unconsumed_preparation_refusal_names_the_advertised_claim() -> None: + from loopx.control_plane.turn_driver.codex_execution_preparation import ( + unconsumed_preparation_refusal, + ) + + decision = _decision() + refusal = unconsumed_preparation_refusal(decision, goal_id=GOAL, agent_id=AGENT) + assert refusal is not None + assert refusal.code == "turn_execution_preparation_claim_not_consumed" + assert refusal.payload["todo_id"] == TODO + assert refusal.payload["claim_command"] == decision["execution_preparation"]["claim"]["command_line"] + + +def test_unconsumed_preparation_refusal_leaves_other_states_alone() -> None: + from loopx.control_plane.turn_driver.codex_execution_preparation import ( + unconsumed_preparation_refusal, + ) + + assert unconsumed_preparation_refusal(_decision(state="ready"), goal_id=GOAL, agent_id=AGENT) is None + assert unconsumed_preparation_refusal({"ok": True}, goal_id=GOAL, agent_id=AGENT) is None + + +@pytest.mark.parametrize( + "decision, goal_id, agent_id, altered_command", [ + (_decision(host_execution_allowed=False), GOAL, AGENT, None), + (_decision(todo_id="todo_other"), GOAL, AGENT, None), + (_decision(), "goal-other", AGENT, None), + (_decision(), GOAL, "agent-b", None), + (_decision(), GOAL, AGENT, "loopx todo claim --goal-id goal-other --thin"), + ], +) +def test_unconsumed_preparation_refusal_never_advertises_an_unverified_claim( + decision, goal_id, agent_id, altered_command, +) -> None: + from loopx.control_plane.turn_driver.codex_execution_preparation import ( + unconsumed_preparation_refusal, + ) + if altered_command: + decision["execution_preparation"]["claim"]["command_line"] = altered_command + refusal = unconsumed_preparation_refusal(decision, goal_id=goal_id, agent_id=agent_id) + assert refusal is not None + assert "claim_command" not in refusal.payload and "next_step" not in refusal.payload + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("output_format", ["default", "json"]) +def test_run_once_refuses_typed_when_the_builtin_claim_is_not_consumed( + tmp_path: Path, monkeypatch, provider: str, output_format: str, +) -> None: + import contextlib + import io + + from loopx.cli import main + from loopx.control_plane.turn_driver import codex_execution_preparation + from test_loopx_turn_codex_cli import _fake_codex + from test_loopx_turn_driver import _write_live_fixture + + project, runtime, registry = _write_live_fixture( + tmp_path, provider=provider, handoff_mode="hard_lease", + ) + native, marker = _fake_codex(tmp_path) + monkeypatch.setenv("FAKE_CODEX_LOG", str(marker)) + declined = [] + monkeypatch.setattr( + codex_execution_preparation, + "builtin_execution_preparation_claim", + lambda decision, **kwargs: declined.append(decision["execution_preparation"]["state"]), + ) + output = io.StringIO() + with contextlib.redirect_stdout(output): + code = main([ + "--registry", str(registry), "--runtime-root", str(runtime), + *(["--format", "json"] if output_format == "json" else []), + "turn", "run-once", "--goal-id", "loopx-turn-fixture", "--agent-id", "codex-fixture", + "--host", "codex-cli", "--project", str(project), "--codex-bin", str(native), + "--codex-sandbox", "read-only", "--no-global-sync", "--iteration-context", "fresh", + "--timeout-seconds", "15", "--execute", + ]) + rendered = output.getvalue() + claim_command = ( + "loopx todo claim --goal-id loopx-turn-fixture --todo-id todo_fixture0001 " + "--agent-id codex-fixture --claimed-by codex-fixture --thin" + ) + assert code == 1, rendered + assert declined == ["claim_required"], rendered + if output_format == "json": + packet = json.loads(rendered) + assert packet["schema_version"] == "loopx_turn_execution_v0" + assert packet["ok"] is False and packet["executed"] is False + assert packet["status"] == "execution_preparation_required" + assert packet["error_code"] == "turn_execution_preparation_claim_not_consumed" + assert packet["claim_command"] == claim_command + assert "execution_preparation.state is ready" in packet["next_step"] + assert not any(packet["effects"].values()) + assert "journal_ref" not in packet + else: + assert rendered.startswith("# LoopX Turn Run Once\n") + assert "- status: execution_preparation_required" in rendered + assert "- reason: turn_execution_preparation_claim_not_consumed" in rendered + assert f"- claim_command: {claim_command}" in rendered + assert "execution_preparation.state is ready" in rendered + assert "- host_invoked: False" in rendered + assert "- quota_spent: False" in rendered + assert not marker.exists(), "the Host must not be invoked on a refused preparation" diff --git a/tests/control_plane/test_unsettled_recovery_admission_bound.py b/tests/control_plane/test_unsettled_recovery_admission_bound.py index 0a326e0e7f..857d083888 100644 --- a/tests/control_plane/test_unsettled_recovery_admission_bound.py +++ b/tests/control_plane/test_unsettled_recovery_admission_bound.py @@ -1,13 +1,22 @@ """Recovery admissions are bounded per original debt, never treated as spend.""" -import json +import argparse from concurrent.futures import ThreadPoolExecutor +import json from pathlib import Path +import shlex +import sys from threading import Barrier import pytest from loopx.capabilities.manager_context import deliver -from loopx.rollout_event_log import load_rollout_events, rollout_event_log_path +from loopx.rollout_event_log import ( + append_rollout_event, + build_rollout_event, + load_rollout_events, + rollout_event_log_path, +) +from scripts import external_scheduler_worker as worker from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime from tests.control_plane.test_quota_settlement_cli import ( AGENT_ID, GOAL_ID, TODO_ID, _run_cli, _spend_run_count, _write_fixture, @@ -448,3 +457,185 @@ def test_paused_goal_blocks_unsettled_recovery_without_fabricating_receipts( assert debt["settlement_effect_id"] == effect assert debt["admissions_without_progress"] == 0, debt assert _spend_run_count(runtime) == 0 + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_scheduler_observation_and_external_worker_enforce_recovery_admission_limit( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + provider: str, +) -> None: + isolate_sqlite_runtime(tmp_path, monkeypatch) + monkeypatch.setenv("PYTHONPATH", str(Path(__file__).resolve().parents[2])) + project, runtime, registry = _write_fixture(tmp_path, provider=provider) + cli = tmp_path / "loopx-cli" + cli.write_text( + f"#!{sys.executable}\nfrom loopx.entrypoint import main\nraise SystemExit(main())\n", + encoding="utf-8", + ) + cli.chmod(0o700) + + def observe() -> dict: + rc, payload = _run_cli( + registry, runtime, "quota", "should-run", + "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, + "--runtime-profile", "generic_cli", "--scheduler-observation", + cwd=project, raw_guard=False, + ) + assert rc == 0, payload + return payload + + rc, original = _run_cli( + registry, runtime, "quota", "should-run", "--codex-app", + "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, + "--turn-instance-id", "owed-original", "--todo-id", TODO_ID, + cwd=project, + ) + assert rc == 0 and original["heartbeat_receipt"]["closeout_required"] is True, original + effect = original["heartbeat_receipt"]["settlement_identity"]["effect_id"] + log = rollout_event_log_path(runtime, GOAL_ID) + + def _admission_receipts() -> list[dict]: + return [ + event for event in load_rollout_events(log) + if event.get("run_id") + or (event.get("details") or {}).get("closeout_required") + or (event.get("details") or {}).get("recovery_checkpoint_schema") + or (event.get("details") or {}).get("turn_instance_id") + ] + + for index in range(3): + receipts_before = _admission_receipts() + obs = observe() + assert _admission_receipts() == receipts_before + assert obs["should_run"] is True, obs + assert obs["decision"] == "unsettled_host_turn_recovery", obs + assert obs["effective_action"] == "unsettled_host_turn_recovery", obs + assert obs["interaction_contract"]["agent_channel"]["must_attempt"] is True + assert obs["scheduler_hint"]["action"] == "run_now" + recovery = obs["unsettled_host_turn_recovery"] + assert recovery["state"] == "recovery_required", recovery + assert recovery["prior_turn_instance_id"] == "owed-original" + assert recovery["settlement_effect_id"] == effect + assert recovery["binding_id"] == TODO_ID + assert recovery["admissions_without_progress"] == index + assert recovery["admission_limit"] == 3 + + if index == 0: + allowed_marker = tmp_path / "allowed-wake-ran" + allowed_args = argparse.Namespace( + cli_bin=str(cli), registry=str(registry), runtime_root=str(runtime), + runtime_profile="generic_cli", goal_id=GOAL_ID, agent_id=AGENT_ID, + state_file=str(tmp_path / "worker-allowed.json"), + wake_cmd=shlex.join([ + sys.executable, "-c", + f"from pathlib import Path; Path({str(allowed_marker)!r}).touch()", + ]), + once=True, error_backoff_seconds=5.0, + quota_timeout_seconds=30.0, wake_timeout_seconds=10.0, + ) + assert worker.run_worker(allowed_args) == 0 + assert allowed_marker.exists() + + rc, admitted = _run_cli( + registry, runtime, "quota", "should-run", "--codex-app", + "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, + "--turn-instance-id", f"recovery-{index}", cwd=project, + ) + assert rc == 0 and admitted["should_run"] is True, admitted + + receipts_before = _admission_receipts() + exhausted = observe() + assert _admission_receipts() == receipts_before + assert exhausted["should_run"] is False, exhausted + assert exhausted["decision"] == "blocked_wait", exhausted + assert exhausted["effective_action"] == "blocked_wait", exhausted + assert exhausted["reason_code"] == "unsettled_recovery_admission_limit", exhausted + assert exhausted["interaction_contract"]["agent_channel"]["must_attempt"] is False + assert exhausted["scheduler_hint"]["action"] == "backoff_waiting_for_user", exhausted + debt = exhausted["unsettled_host_turn_recovery"] + assert debt["state"] == "attention_required", debt + assert debt["reason_code"] == "unsettled_recovery_admission_limit", debt + assert debt["prior_turn_instance_id"] == "owed-original" + assert debt["settlement_effect_id"] == effect + assert debt["admissions_without_progress"] == 3 + assert debt["admission_limit"] == 3 + + capsys.readouterr() + forbidden_marker = tmp_path / "forbidden-wake-ran" + sleeps: list[float] = [] + held_args = argparse.Namespace( + cli_bin=str(cli), registry=str(registry), runtime_root=str(runtime), + runtime_profile="generic_cli", goal_id=GOAL_ID, agent_id=AGENT_ID, + state_file=str(tmp_path / "worker-held.json"), + wake_cmd=shlex.join([ + sys.executable, "-c", + f"from pathlib import Path; Path({str(forbidden_marker)!r}).touch()", + ]), + once=False, error_backoff_seconds=5.0, + quota_timeout_seconds=30.0, wake_timeout_seconds=10.0, + ) + assert worker.run_worker(held_args, sleep=sleeps.append) == 0 + assert not forbidden_marker.exists() + assert len(sleeps) >= 1 and all(delay > 0 for delay in sleeps) + worker_log = capsys.readouterr().out + assert "status=waiting" in worker_log + assert "effective_action=blocked_wait" in worker_log + assert "status=stop_after_unchanged_limit" in worker_log + assert _spend_run_count(runtime) == 0 + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_scheduler_observation_recovery_overrides_blocked_todo_wait_hint( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + provider: str, +) -> None: + isolate_sqlite_runtime(tmp_path, monkeypatch) + project, runtime, registry = _write_fixture(tmp_path, provider=provider) + rc, blocked = _run_cli( + registry, runtime, "todo", "update", "--goal-id", GOAL_ID, + "--agent-id", AGENT_ID, "--todo-id", TODO_ID, + "--status", "blocked", "--reason", "Await independent evidence.", cwd=project, + ) + assert rc == 0, blocked + replan_id = "replan-1111111111111111" + prior_turn = "prior-replan-turn" + append_rollout_event( + rollout_event_log_path(runtime, GOAL_ID), + build_rollout_event( + goal_id=GOAL_ID, + event_kind="quota_should_run", + agent_id=AGENT_ID, + run_id=prior_turn, + status="autonomous_replan_required", + summary="A previous autonomous replan Turn still requires closeout.", + details={ + "replan_obligation_id": replan_id, + "settlement_effect_id": f"{GOAL_ID}:{AGENT_ID}:{replan_id}:{prior_turn}", + "closeout_required": True, + }, + ), + ) + + rc, obs = _run_cli( + registry, runtime, "quota", "should-run", + "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, + "--runtime-profile", "generic_cli", "--scheduler-observation", + cwd=project, raw_guard=False, + ) + assert rc == 0, obs + assert obs["should_run"] is True, obs + assert obs["decision"] == "unsettled_host_turn_recovery", obs + assert obs["effective_action"] == "unsettled_host_turn_recovery", obs + assert obs["interaction_contract"]["agent_channel"]["must_attempt"] is True + assert obs["scheduler_hint"]["action"] == "run_now", obs + assert obs["scheduler_hint"]["cadence_class"] == "active_work", obs + assert obs["scheduler_hint"]["unchanged_poll"].get("local_scheduler") != "stop", obs + assert obs["scheduler_hint"]["cold_path_detail"]["local_scheduler"]["after_limit"] == "continue", obs + recovery = obs["unsettled_host_turn_recovery"] + assert recovery["state"] == "recovery_required", recovery + assert recovery["prior_turn_instance_id"] == prior_turn + assert recovery["binding_kind"] == "autonomous_replan" + assert recovery["binding_id"] == replan_id diff --git a/tests/control_plane_ts/dashboard_node_runtime.test.ts b/tests/control_plane_ts/dashboard_node_runtime.test.ts index bf4100850f..5463c5632c 100644 --- a/tests/control_plane_ts/dashboard_node_runtime.test.ts +++ b/tests/control_plane_ts/dashboard_node_runtime.test.ts @@ -5,6 +5,7 @@ import {tmpdir} from "node:os"; import {dirname, join} from "node:path"; import test from "node:test"; import {fileURLToPath} from "node:url"; +import {nodeTypescriptFlags} from "../../loopx/control_plane/runtime/node_version.ts"; const root = fileURLToPath(new URL("../../", import.meta.url)); const contract = "loopx/control_plane/runtime/node_version.ts"; @@ -75,3 +76,19 @@ for (const [onPath, inNvm, allowed] of cases) { } }); } + +test("nodeTypescriptFlags returns V8 baseline Wasm flags only on Linux x86_64/amd64", () => { + assert.deepEqual(nodeTypescriptFlags("linux", "x64"), [ + "--liftoff-only", + "--no-wasm-tier-up", + "--no-wasm-dynamic-tiering", + ]); + assert.deepEqual(nodeTypescriptFlags("linux", "amd64"), [ + "--liftoff-only", + "--no-wasm-tier-up", + "--no-wasm-dynamic-tiering", + ]); + assert.deepEqual(nodeTypescriptFlags("linux", "arm64"), []); + assert.deepEqual(nodeTypescriptFlags("darwin", "arm64"), []); + assert.deepEqual(nodeTypescriptFlags("darwin", "x64"), []); +}); diff --git a/tests/control_plane_ts/local_authority_runtime.test.ts b/tests/control_plane_ts/local_authority_runtime.test.ts index a9110392e2..2dcdd75562 100644 --- a/tests/control_plane_ts/local_authority_runtime.test.ts +++ b/tests/control_plane_ts/local_authority_runtime.test.ts @@ -1841,6 +1841,9 @@ test("managed execution fields cannot be ignored by older public transports", as const result = await runtime.claimLocalCoordinationTodo({schema_version: `loopx_local_coordination_todo_claim_request_v${v}`, manage_execution: true}, noStore); assert.match(String(result.reason), /requires claim request v2/); + const ttlResult = await runtime.claimLocalCoordinationTodo({schema_version: `loopx_local_coordination_todo_claim_request_v${v}`, + ttl_seconds: 7200}, noStore); + assert.match(String(ttlResult.reason), /Managed execution TTL requires claim request v2/); } for (const v of [0, 1, 2, 3, 4, 5]) { const result = await runtime.updateLocalCoordinationTodo({schema_version: `loopx_local_coordination_todo_update_request_v${v}`, diff --git a/tests/control_plane_ts/managed_claim_execution_conformance.ts b/tests/control_plane_ts/managed_claim_execution_conformance.ts index 54bda5ab23..e7d5f8444f 100644 --- a/tests/control_plane_ts/managed_claim_execution_conformance.ts +++ b/tests/control_plane_ts/managed_claim_execution_conformance.ts @@ -249,6 +249,45 @@ export function registerManagedClaimExecutionConformance(provider: string, facto assert.equal((await execute({...original, claim_operation_id: String(prepared.claim_operation_id)})).status, "applied"); } }); + test(`${provider} managed execution: explicit ttl_seconds controls expiry, final-third renewal, bounds and replay identity`, async t => { + const {store, request, progress} = await setup(t); + const before = await loaded(store); + for (const invalid of [0, 86401]) { + const rejected = await claim(store, {...request, operation_id: `bad-ttl-${invalid}`, ttl_seconds: invalid}); + assert.equal(rejected.status, "failed"); + assert.equal(rejected.reason_code, "invalid_coordination_todo_claim"); + assert.match(String(rejected.reason), /ttl seconds must be between 1 and 86400/); + assert.deepEqual(await loaded(store), before); + } + const longClaim = await claim(store, {...request, operation_id: "claim-long-ttl", ttl_seconds: 7200}); + assert.equal(longClaim.status, "applied", JSON.stringify(longClaim)); + const lease = longClaim.lease as JsonObject; + assert.equal(lease.acquire_ttl_seconds, 7200); + assert.equal(lease.expires_at, "2026-09-13T12:00:00Z"); + const unchangedReplay = await claim(store, { + ...request, operation_id: "claim-long-ttl", ttl_seconds: 7200, now: new Date("2026-09-13T10:30:00Z"), + }); + assert.equal(unchangedReplay.status, "replayed"); + assert.equal((unchangedReplay.lease as JsonObject).acquire_ttl_seconds, 7200); + const mismatchedReplay = await claim(store, { + ...request, operation_id: "claim-long-ttl", ttl_seconds: 3600, now: new Date("2026-09-13T10:30:00Z"), + }); + assert.equal(mismatchedReplay.status, "failed"); + assert.equal(mismatchedReplay.reason_code, "coordination_operation_identity_mismatch"); + // 10:31 is outside the final third of a 7200s lease (only 4440s left, > 2400s), so early update never renews; + // 11:25 (only 2100s <= 2400s left) renews with the same 7200s TTL. + assert.equal((await update(store, {...progress, claim_operation_id: "claim-long-ttl", + operation_id: "early-long-progress", now: new Date("2026-09-13T10:31:00Z")})).status, "applied"); + let current = await loaded(store); + assert.equal((current.head.leases as JsonObject[])[0]!.version, 1); + assert.equal((await update(store, {...progress, claim_operation_id: "claim-long-ttl", + operation_id: "late-long-progress", now: new Date("2026-09-13T11:25:00Z")})).status, "applied"); + current = await loaded(store); + const renewed = (current.head.leases as JsonObject[])[0]!; + assert.equal(renewed.version, 2); + assert.equal(renewed.acquire_ttl_seconds, 7200); + assert.equal(renewed.expires_at, "2026-09-13T13:25:00Z"); + }); test(`${provider} managed execution: changed identity requires reconciliation instead of claim adoption`, async t => { for (const change of [{owner: "agent-b"}, {lease_epoch: 2, version: 2}, {idempotency_key: "different-execution"}, {write_repository: "git:github.com/example/other"}, diff --git a/tests/control_plane_ts/steward_managed_mode.test.ts b/tests/control_plane_ts/steward_managed_mode.test.ts index 538ec92d2b..ac7ac991cf 100644 --- a/tests/control_plane_ts/steward_managed_mode.test.ts +++ b/tests/control_plane_ts/steward_managed_mode.test.ts @@ -671,3 +671,636 @@ test("observeStewardSignalMonitor preserves feature-off parity and isolates scop repository_snapshot: sampleRepo, })); }); + +test("observeStewardSignalMonitor uses stalled_since, author-reply bypass, and stalled_bucket wakeups", () => { + const stalledInternalScope = { + schema_version: "steward_signal_monitor_scope_v0", + include_portfolio: false, + include_inbox: false, + pr_filter: { + exclude_drafts: true, + effective_verdicts: ["REQUEST_CHANGES"], + author_mode: "include", + authors: ["alice"], + min_stalled_hours: 24, + }, + }; + const stalledExternalScope = { + schema_version: "steward_signal_monitor_scope_v0", + include_portfolio: false, + include_inbox: false, + pr_filter: { + exclude_drafts: true, + effective_verdicts: ["REQUEST_CHANGES"], + author_mode: "exclude", + authors: ["alice"], + min_stalled_hours: 24, + }, + }; + + const makeRepo = (botUpdatedAt: string) => ({ + status: "ok", + repository: "acme/widgets", + items: [ + { + number: 201, + title: "Internal RC with Mergify bot ping", + isDraft: false, + mergeable: "MERGEABLE", + author: {login: "alice"}, + updatedAt: botUpdatedAt, + stalled_since: "2026-11-20T09:00:00Z", + author_replied_after_request_changes: false, + review_summary: { + effective_verdict: "REQUEST_CHANGES", + has_review_conflict: false, + latest_request_changes_review_id: "PRR_201", + stalled_since: "2026-11-20T09:00:00Z", + author_replied_after_request_changes: false, + exact_head_reviews: [], + }, + }, + { + number: 202, + title: "External author replied right after RC", + isDraft: false, + mergeable: "MERGEABLE", + author: {login: "ext-user"}, + updatedAt: "2026-11-21T08:30:00Z", + stalled_since: "2026-11-21T07:00:00Z", + author_replied_after_request_changes: true, + review_summary: { + effective_verdict: "REQUEST_CHANGES", + has_review_conflict: false, + latest_request_changes_review_id: "PRR_202", + stalled_since: "2026-11-21T07:00:00Z", + author_replied_after_request_changes: true, + exact_head_reviews: [], + }, + }, + { + number: 203, + title: "Stale RC on previous commit after new head push", + isDraft: false, + mergeable: "MERGEABLE", + author: {login: "ext-user"}, + updatedAt: "2026-11-18T00:00:00Z", + stalled_since: null, + author_replied_after_request_changes: false, + review_summary: { + effective_verdict: "REQUEST_CHANGES", + has_review_conflict: false, + latest_request_changes_review_id: null, + stalled_since: null, + author_replied_after_request_changes: false, + exact_head_reviews: [], + }, + }, + ], + }); + + // At 23h since stalled_since (2026-11-20T09:00 -> 2026-11-21T08:00), PR #201 is excluded even with newer updatedAt. + const before24h = observeStewardSignalMonitor({ + signal_scope: stalledInternalScope, + repository_snapshot: makeRepo("2026-11-21T08:30:00Z"), + observed_at: "2026-11-21T08:00:00Z", + }); + assert.deepEqual(before24h.scoped_repository_items, []); + + // At 24h exact (2026-11-21T09:00), PR #201 enters 24h_to_72h bucket. + const at24h = observeStewardSignalMonitor({ + signal_scope: stalledInternalScope, + previous_hash: before24h.result_hash, + repository_snapshot: makeRepo("2026-11-21T08:30:00Z"), + observed_at: "2026-11-21T09:00:00Z", + }); + assert.equal(at24h.material_change, true); + assert.equal(at24h.scoped_repository_items[0].number, 201); + assert.equal(at24h.scoped_repository_items[0].stalled_threshold_met, true); + assert.equal(at24h.scoped_repository_items[0].stalled_bucket, "24h_to_72h"); + + // Bot comment bumping updatedAt at 71h produces zero hash change in the same bucket. + const at71hBotBump = observeStewardSignalMonitor({ + signal_scope: stalledInternalScope, + previous_hash: at24h.result_hash, + repository_snapshot: makeRepo("2026-11-23T07:55:00Z"), + observed_at: "2026-11-23T08:00:00Z", + }); + assert.equal(at71hBotBump.result_hash, at24h.result_hash); + assert.equal(at71hBotBump.material_change, false); + + // Crossing into 72h_plus and 7d_plus wakes the monitor exactly at bucket boundaries. + const at72h = observeStewardSignalMonitor({ + signal_scope: stalledInternalScope, + previous_hash: at71hBotBump.result_hash, + repository_snapshot: makeRepo("2026-11-23T07:55:00Z"), + observed_at: "2026-11-23T09:00:00Z", + }); + assert.equal(at72h.material_change, true); + assert.equal(at72h.scoped_repository_items[0].stalled_bucket, "72h_plus"); + + const at73h = observeStewardSignalMonitor({ + signal_scope: stalledInternalScope, + previous_hash: at72h.result_hash, + repository_snapshot: makeRepo("2026-11-23T07:55:00Z"), + observed_at: "2026-11-23T10:00:00Z", + }); + assert.equal(at73h.material_change, false); + + const at7d = observeStewardSignalMonitor({ + signal_scope: stalledInternalScope, + previous_hash: at73h.result_hash, + repository_snapshot: makeRepo("2026-11-23T07:55:00Z"), + observed_at: "2026-11-27T09:00:00Z", + }); + assert.equal(at7d.material_change, true); + assert.equal(at7d.scoped_repository_items[0].stalled_bucket, "7d_plus"); + + // External monitor prioritizes awaiting_maintainer_reply immediately (<24h) and drops stale-commit RC (#203). + const externalObs = observeStewardSignalMonitor({ + signal_scope: stalledExternalScope, + repository_snapshot: makeRepo("2026-11-21T08:30:00Z"), + observed_at: "2026-11-21T09:00:00Z", + }); + assert.deepEqual(externalObs.scoped_repository_items.map((row: {number: number}) => row.number), [202]); + assert.equal(externalObs.scoped_repository_items[0].stalled_threshold_met, false); + assert.equal(externalObs.scoped_repository_items[0].stalled_bucket, "awaiting_maintainer_reply"); + + // Scoped monitor WITHOUT min_stalled_hours retains updatedAt sensitivity even when items carry stalled_since. + const noAgeScope = { + schema_version: "steward_signal_monitor_scope_v0", + include_portfolio: false, + include_inbox: false, + pr_filter: { + exclude_drafts: true, + effective_verdicts: ["REQUEST_CHANGES"], + author_mode: "include", + authors: ["alice"], + }, + }; + const noAgeInitial = observeStewardSignalMonitor({ + signal_scope: noAgeScope, + repository_snapshot: makeRepo("2026-11-21T08:30:00Z"), + observed_at: "2026-11-21T09:00:00Z", + }); + const noAgeUpdated = observeStewardSignalMonitor({ + signal_scope: noAgeScope, + previous_hash: noAgeInitial.result_hash, + repository_snapshot: makeRepo("2026-11-21T08:45:00Z"), + observed_at: "2026-11-21T09:15:00Z", + }); + assert.equal(noAgeUpdated.material_change, true); + + // Scoped monitor with sub-24h min_stalled_hours (e.g. 6h) emits under_24h at 7h and transitions to 24h_to_72h at 24h. + const sixHourScope = { + schema_version: "steward_signal_monitor_scope_v0", + include_portfolio: false, + include_inbox: false, + pr_filter: { + exclude_drafts: true, + effective_verdicts: ["REQUEST_CHANGES"], + author_mode: "include", + authors: ["alice"], + min_stalled_hours: 6, + }, + }; + const at7h = observeStewardSignalMonitor({ + signal_scope: sixHourScope, + repository_snapshot: makeRepo("2026-11-20T15:00:00Z"), + observed_at: "2026-11-20T16:00:00Z", + }); + assert.equal(at7h.scoped_repository_items.length, 1); + assert.equal(at7h.scoped_repository_items[0].stalled_threshold_met, true); + assert.equal(at7h.scoped_repository_items[0].stalled_bucket, "under_24h"); + const at24hFromSixHour = observeStewardSignalMonitor({ + signal_scope: sixHourScope, + previous_hash: at7h.result_hash, + repository_snapshot: makeRepo("2026-11-21T08:30:00Z"), + observed_at: "2026-11-21T09:00:00Z", + }); + assert.equal(at24hFromSixHour.material_change, true); + assert.equal(at24hFromSixHour.scoped_repository_items[0].stalled_bucket, "24h_to_72h"); +}); + +test("observeStewardSignalMonitor fails closed on comments_coverage_incomplete only for matching stalled-age PRs", () => { + const externalStalledScope = { + schema_version: "steward_signal_monitor_scope_v0", + include_portfolio: false, + include_inbox: false, + pr_filter: { + exclude_drafts: true, + effective_verdicts: ["REQUEST_CHANGES"], + author_mode: "exclude", + authors: ["alice"], + min_stalled_hours: 24, + }, + }; + const internalStalledScope = { + schema_version: "steward_signal_monitor_scope_v0", + include_portfolio: false, + include_inbox: false, + pr_filter: { + exclude_drafts: true, + effective_verdicts: ["REQUEST_CHANGES"], + author_mode: "include", + authors: ["alice"], + min_stalled_hours: 24, + }, + }; + const noAgeScope = { + schema_version: "steward_signal_monitor_scope_v0", + include_portfolio: false, + include_inbox: false, + pr_filter: { + exclude_drafts: true, + effective_verdicts: ["REQUEST_CHANGES"], + author_mode: "exclude", + authors: ["alice"], + }, + }; + + const makeExternalPr = (overrides: Record = {}) => ({ + number: 302, + title: "External RC awaiting maintainer reply", + isDraft: false, + mergeable: "MERGEABLE", + author: {login: "ext-user"}, + updatedAt: "2026-11-21T08:30:00Z", + stalled_since: "2026-11-21T07:00:00Z", + author_replied_after_request_changes: true, + comments_coverage_incomplete: false, + review_summary: { + effective_verdict: "REQUEST_CHANGES", + has_review_conflict: false, + latest_request_changes_review_id: "PRR_302", + stalled_since: "2026-11-21T07:00:00Z", + author_replied_after_request_changes: true, + comments_coverage_incomplete: false, + exact_head_reviews: [], + }, + ...overrides, + }); + + const baseline = observeStewardSignalMonitor({ + signal_scope: externalStalledScope, + repository_snapshot: {status: "ok", repository: "acme/widgets", items: [makeExternalPr()]}, + observed_at: "2026-11-21T09:00:00Z", + }); + assert.equal(baseline.observation_incomplete, false); + assert.equal(baseline.scoped_repository_items[0].stalled_bucket, "awaiting_maintainer_reply"); + + // Truncated comment suffix (<24h and >=24h) fails closed and preserves previous_hash, + // whether comments_coverage_incomplete is surfaced at top-level or inside review_summary. + for (const [observedAt, truncatedItem] of [ + [ + "2026-11-21T10:00:00Z", + makeExternalPr({ + updatedAt: "2026-11-21T09:50:00Z", + author_replied_after_request_changes: false, + comments_coverage_incomplete: true, + review_summary: { + ...makeExternalPr().review_summary, + author_replied_after_request_changes: false, + comments_coverage_incomplete: true, + }, + }), + ], + [ + "2026-11-22T09:00:00Z", + makeExternalPr({ + updatedAt: "2026-11-22T08:30:00Z", + author_replied_after_request_changes: false, + comments_coverage_incomplete: false, + review_summary: { + ...makeExternalPr().review_summary, + author_replied_after_request_changes: false, + comments_coverage_incomplete: true, + }, + }), + ], + ] as const) { + const truncated = observeStewardSignalMonitor({ + signal_scope: externalStalledScope, + previous_hash: baseline.result_hash, + repository_snapshot: {status: "ok", repository: "acme/widgets", items: [truncatedItem]}, + observed_at: observedAt, + }); + assert.deepEqual(truncated, { + result_hash: baseline.result_hash, + material_change: false, + observation_incomplete: true, + own_monitor_bookkeeping_excluded: true, + }); + } + + // Recovered complete coverage with bumped updatedAt yields identical hash and material_change=false. + const recovered = observeStewardSignalMonitor({ + signal_scope: externalStalledScope, + previous_hash: baseline.result_hash, + repository_snapshot: { + status: "ok", + repository: "acme/widgets", + items: [makeExternalPr({updatedAt: "2026-11-21T10:30:00Z"})], + }, + observed_at: "2026-11-21T11:00:00Z", + }); + assert.equal(recovered.result_hash, baseline.result_hash); + assert.equal(recovered.material_change, false); + assert.equal(recovered.observation_incomplete, false); + + // Maintainer reply with complete coverage exits awaiting_maintainer_reply. + const maintainerCleared = observeStewardSignalMonitor({ + signal_scope: externalStalledScope, + previous_hash: baseline.result_hash, + repository_snapshot: { + status: "ok", + repository: "acme/widgets", + items: [ + makeExternalPr({ + author_replied_after_request_changes: false, + review_summary: { + ...makeExternalPr().review_summary, + author_replied_after_request_changes: false, + }, + }), + ], + }, + observed_at: "2026-11-21T11:00:00Z", + }); + assert.equal(maintainerCleared.material_change, true); + assert.equal(maintainerCleared.observation_incomplete, false); + assert.deepEqual(maintainerCleared.scoped_repository_items, []); + + // Non-age-filtered scopes and non-matching items are unaffected by comments_coverage_incomplete. + const truncatedExternal = makeExternalPr({ + author_replied_after_request_changes: false, + comments_coverage_incomplete: true, + review_summary: { + ...makeExternalPr().review_summary, + author_replied_after_request_changes: false, + comments_coverage_incomplete: true, + }, + }); + const noAgeObs = observeStewardSignalMonitor({ + signal_scope: noAgeScope, + repository_snapshot: {status: "ok", repository: "acme/widgets", items: [truncatedExternal]}, + observed_at: "2026-11-21T11:00:00Z", + }); + assert.equal(noAgeObs.observation_incomplete, false); + assert.equal(noAgeObs.scoped_repository_items.length, 1); + + const internalObs = observeStewardSignalMonitor({ + signal_scope: internalStalledScope, + repository_snapshot: { + status: "ok", + repository: "acme/widgets", + items: [ + truncatedExternal, + makeExternalPr({number: 303, isDraft: true, comments_coverage_incomplete: true}), + ], + }, + observed_at: "2026-11-21T11:00:00Z", + }); + assert.equal(internalObs.observation_incomplete, false); + assert.deepEqual(internalObs.scoped_repository_items, []); + + const externalIgnoringDraftOrApprove = observeStewardSignalMonitor({ + signal_scope: externalStalledScope, + repository_snapshot: { + status: "ok", + repository: "acme/widgets", + items: [ + makeExternalPr({number: 304, isDraft: true, comments_coverage_incomplete: true}), + makeExternalPr({ + number: 305, + comments_coverage_incomplete: true, + review_summary: { + effective_verdict: "APPROVE", + has_review_conflict: false, + comments_coverage_incomplete: true, + exact_head_reviews: [], + }, + }), + ], + }, + observed_at: "2026-11-21T11:00:00Z", + }); + assert.equal(externalIgnoringDraftOrApprove.observation_incomplete, false); + assert.deepEqual(externalIgnoringDraftOrApprove.scoped_repository_items, []); +}); + +test("observeStewardSignalMonitor preserves pre-#9207 upgrade parity and excludes pagination metadata from hashes", () => { + const noAgeScope = { + schema_version: "steward_signal_monitor_scope_v0", + include_portfolio: false, + include_inbox: false, + pr_filter: { + exclude_drafts: true, + effective_verdicts: ["REQUEST_CHANGES"], + author_mode: "exclude", + authors: ["alice"], + }, + }; + const mergeableScope = { + schema_version: "steward_signal_monitor_scope_v0", + include_portfolio: false, + include_inbox: false, + pr_filter: { + exclude_drafts: true, + exclude_conflicting: true, + effective_verdicts: ["APPROVE"], + required_approver_declarations: ["gpt"], + }, + }; + const externalStalledScope = { + schema_version: "steward_signal_monitor_scope_v0", + include_portfolio: false, + include_inbox: false, + pr_filter: { + exclude_drafts: true, + effective_verdicts: ["REQUEST_CHANGES"], + author_mode: "exclude", + authors: ["alice"], + min_stalled_hours: 24, + }, + }; + + const pre9207RcPr = { + number: 410, + title: "External PR with RC", + url: "https://github.com/acme/widgets/pull/410", + headRefOid: "head410", + isDraft: false, + mergeable: "MERGEABLE", + author: {login: "ext-user"}, + updatedAt: "2026-11-21T08:30:00Z", + checks_summary: {total: 1, pass_count: 1, fail_count: 0, pending_count: 0}, + bypassed_gates: [], + review_summary: { + effective_verdict: "REQUEST_CHANGES", + has_review_conflict: false, + stale_review_count: 0, + exact_head_reviews: [], + }, + }; + const upgradedCompleteRcPr = { + ...pre9207RcPr, + stalled_since: "2026-11-21T07:00:00Z", + author_replied_after_request_changes: true, + comments_coverage_incomplete: false, + stalled_threshold_met: false, + stalled_bucket: "awaiting_maintainer_reply", + review_summary: { + ...pre9207RcPr.review_summary, + latest_request_changes_review_id: "PRR_410", + stalled_since: "2026-11-21T07:00:00Z", + author_replied_after_request_changes: true, + comments_coverage_incomplete: false, + }, + }; + const simulatedBackfillFailureRcPr = { + ...upgradedCompleteRcPr, + author_replied_after_request_changes: false, + comments_coverage_incomplete: true, + stalled_bucket: "under_24h", + review_summary: { + ...upgradedCompleteRcPr.review_summary, + author_replied_after_request_changes: false, + comments_coverage_incomplete: true, + }, + }; + + for (const scope of [null, noAgeScope]) { + const legacy = observeStewardSignalMonitor({ + signal_scope: scope, + portfolio_observation: {result_hash: "p1"}, + inbox_items: [{request_id: "req_1"}], + repository_snapshot: {status: "ok", repository: "acme/widgets", items: [pre9207RcPr]}, + observed_at: "2026-11-21T09:00:00Z", + }); + const upgraded = observeStewardSignalMonitor({ + signal_scope: scope, + previous_hash: legacy.result_hash, + portfolio_observation: {result_hash: "p1"}, + inbox_items: [{request_id: "req_1"}], + repository_snapshot: {status: "ok", repository: "acme/widgets", items: [upgradedCompleteRcPr]}, + observed_at: "2026-11-21T09:05:00Z", + }); + assert.equal(upgraded.result_hash, legacy.result_hash); + assert.equal(upgraded.material_change, false); + assert.equal(upgraded.observation_incomplete, false); + + // Simulated backfill failure -> recovery on monitors without an age filter yields no false wakeup. + const failedBackfill = observeStewardSignalMonitor({ + signal_scope: scope, + previous_hash: legacy.result_hash, + portfolio_observation: {result_hash: "p1"}, + inbox_items: [{request_id: "req_1"}], + repository_snapshot: {status: "ok", repository: "acme/widgets", items: [simulatedBackfillFailureRcPr]}, + observed_at: "2026-11-21T09:10:00Z", + }); + assert.equal(failedBackfill.result_hash, legacy.result_hash); + assert.equal(failedBackfill.material_change, false); + assert.equal(failedBackfill.observation_incomplete, false); + + const recoveredBackfill = observeStewardSignalMonitor({ + signal_scope: scope, + previous_hash: failedBackfill.result_hash, + portfolio_observation: {result_hash: "p1"}, + inbox_items: [{request_id: "req_1"}], + repository_snapshot: {status: "ok", repository: "acme/widgets", items: [upgradedCompleteRcPr]}, + observed_at: "2026-11-21T09:15:00Z", + }); + assert.equal(recoveredBackfill.result_hash, legacy.result_hash); + assert.equal(recoveredBackfill.material_change, false); + assert.equal(recoveredBackfill.observation_incomplete, false); + + // Real updatedAt change still triggers material_change=true when !usesStalledAgeFilter. + const bumpedUpdatedAt = observeStewardSignalMonitor({ + signal_scope: scope, + previous_hash: legacy.result_hash, + portfolio_observation: {result_hash: "p1"}, + inbox_items: [{request_id: "req_1"}], + repository_snapshot: { + status: "ok", + repository: "acme/widgets", + items: [{...upgradedCompleteRcPr, updatedAt: "2026-11-21T09:20:00Z"}], + }, + observed_at: "2026-11-21T09:25:00Z", + }); + assert.equal(bumpedUpdatedAt.material_change, true); + assert.equal(bumpedUpdatedAt.observation_incomplete, false); + assert.notEqual(bumpedUpdatedAt.result_hash, legacy.result_hash); + } + + // Mergeable non-age scope also retains 100% pre-#9207 hash parity. + const pre9207Approved = { + number: 411, + title: "Approved PR", + isDraft: false, + mergeable: "MERGEABLE", + author: {login: "alice"}, + updatedAt: "2026-11-21T08:00:00Z", + review_summary: { + effective_verdict: "APPROVE", + has_review_conflict: false, + exact_head_reviews: [ + {author_login: "bob", reviewer_declaration: "GPT-5.4", verdict: "APPROVE", valid_verdict_review: true, state: "APPROVED"}, + ], + }, + }; + const upgradedApproved = { + ...pre9207Approved, + stalled_since: null, + author_replied_after_request_changes: false, + comments_coverage_incomplete: false, + review_summary: { + ...pre9207Approved.review_summary, + latest_request_changes_review_id: null, + stalled_since: null, + author_replied_after_request_changes: false, + comments_coverage_incomplete: false, + }, + }; + const legacyMergeable = observeStewardSignalMonitor({ + signal_scope: mergeableScope, + repository_snapshot: {status: "ok", repository: "acme/widgets", items: [pre9207Approved]}, + observed_at: "2026-11-21T09:00:00Z", + }); + const upgradedMergeable = observeStewardSignalMonitor({ + signal_scope: mergeableScope, + previous_hash: legacyMergeable.result_hash, + repository_snapshot: {status: "ok", repository: "acme/widgets", items: [upgradedApproved]}, + observed_at: "2026-11-21T09:05:00Z", + }); + assert.equal(upgradedMergeable.result_hash, legacyMergeable.result_hash); + assert.equal(upgradedMergeable.material_change, false); + + // Even under an age filter, comments_coverage_incomplete metadata never enters result_hash. + const withoutPaginationField = observeStewardSignalMonitor({ + signal_scope: externalStalledScope, + repository_snapshot: {status: "ok", repository: "acme/widgets", items: [pre9207RcPr]}, + observed_at: "2026-11-22T10:00:00Z", + }); + const withPaginationFieldFalse = observeStewardSignalMonitor({ + signal_scope: externalStalledScope, + previous_hash: withoutPaginationField.result_hash, + repository_snapshot: { + status: "ok", + repository: "acme/widgets", + items: [ + { + ...pre9207RcPr, + comments_coverage_incomplete: false, + review_summary: { + ...pre9207RcPr.review_summary, + comments_coverage_incomplete: false, + }, + }, + ], + }, + observed_at: "2026-11-22T10:05:00Z", + }); + assert.equal(withPaginationFieldFalse.result_hash, withoutPaginationField.result_hash); + assert.equal(withPaginationFieldFalse.material_change, false); +}); diff --git a/tests/control_plane_ts/unsettled_host_turn_recovery.test.ts b/tests/control_plane_ts/unsettled_host_turn_recovery.test.ts index edff1eface..e462f4622f 100644 --- a/tests/control_plane_ts/unsettled_host_turn_recovery.test.ts +++ b/tests/control_plane_ts/unsettled_host_turn_recovery.test.ts @@ -267,6 +267,9 @@ test("the admission bound keeps debt identity, deduplicates replays, and accepts const observed = await preflight(runtime.root); assert.deepEqual(observed.recovery_admissions, {count: RECOVERY_ADMISSION_LIMIT, owner_action_id: null, checkpoint}); + const observedNull = await preflight(runtime.root, null); + assert.deepEqual(observedNull.recovery_admissions, + {count: RECOVERY_ADMISSION_LIMIT, owner_action_id: null, checkpoint}); const decide = (facts: JsonObject, missing = observed.missing_receipts) => reduceUnsettledHostTurnRecovery({ schema_version: UNSETTLED_HOST_TURN_RECOVERY_REQUEST_SCHEMA, goal_id: GOAL, agent_id: AGENT, candidate, missing_receipts: missing, @@ -275,6 +278,14 @@ test("the admission bound keeps debt identity, deduplicates replays, and accepts const attention = decide(READ_TODO(ADVANCEMENT_OPEN)); assert.equal(attention.status, "attention_required"); assert.equal((attention.obligation as JsonObject).must_attempt_work, false); + const attentionNull = reduceUnsettledHostTurnRecovery({ + schema_version: UNSETTLED_HOST_TURN_RECOVERY_REQUEST_SCHEMA, + goal_id: GOAL, agent_id: AGENT, candidate: candidateFrom(observedNull), + missing_receipts: observedNull.missing_receipts, + recovery_admissions: observedNull.recovery_admissions, binding_facts: READ_TODO(ADVANCEMENT_OPEN), + }); + assert.equal(attentionNull.status, "attention_required"); + assert.equal((attentionNull.obligation as JsonObject).must_attempt_work, false); assert.equal((attention.recovery as JsonObject).settlement_effect_id, candidate.settlement_effect_id); assert.equal(decide(READ_TODO({...ADVANCEMENT_OPEN, status: "blocked"})).status, "none"); const owner = await preflightPriorHostTurnCloseout({ diff --git a/tests/test_cli_argument_diagnostics.py b/tests/test_cli_argument_diagnostics.py index 9c886f6909..fa353f10c5 100644 --- a/tests/test_cli_argument_diagnostics.py +++ b/tests/test_cli_argument_diagnostics.py @@ -556,7 +556,7 @@ def test_monitor_change_scope_requires_material_transition() -> None: "Continue the work.", ], "todo claim only accepts --todo-id, --claimed-by, --agent-id, optional --role, " - "--claim-operation-id, --task-lease-idempotency-key, " + "--claim-operation-id, --ttl-seconds, --task-lease-idempotency-key, " "--task-lease-expected-version, --project, --state-file, --dry-run, and --thin; unsupported: " "--decision-outcome, --next-agent-todo", ), @@ -598,6 +598,35 @@ def test_managed_claim_reference_is_retained_for_the_execution_owner(command, op assert args.claim_operation_id == operation_id +@pytest.mark.parametrize("command", ["add", "list", "update", "complete", "supersede"]) +def test_ttl_seconds_is_rejected_on_non_claim_todo_commands(command): + args = build_parser().parse_args([ + "todo", command, "--goal-id", "example-goal", "--ttl-seconds", "7200", + ]) + with pytest.raises(ValueError, match="--ttl-seconds is supported only by todo claim"): + validate_shared_todo_options(args) + + +@pytest.mark.parametrize("bad_ttl", [0, 86401]) +def test_todo_claim_rejects_out_of_range_ttl_seconds(bad_ttl): + args = build_parser().parse_args([ + "todo", "claim", "--goal-id", "example-goal", "--todo-id", "todo_example", + "--claimed-by", "codex-example", "--agent-id", "codex-example", + "--ttl-seconds", str(bad_ttl), + ]) + with pytest.raises(ValueError, match="ttl seconds must be between 1 and 86400"): + validate_todo_claim_options(args) + + +def test_todo_claim_ttl_seconds_requires_managed_or_explicit_lease(): + args = build_parser().parse_args([ + "todo", "claim", "--goal-id", "example-goal", "--todo-id", "todo_example", + "--claimed-by", "codex-example", "--ttl-seconds", "7200", + ]) + with pytest.raises(ValueError, match="--ttl-seconds requires managed execution"): + validate_todo_claim_options(args) + + @pytest.mark.parametrize( ("extra_args", "expected"), [ diff --git a/tests/test_codex_operation_host.py b/tests/test_codex_operation_host.py index 336ebbbc19..697a8b4002 100644 --- a/tests/test_codex_operation_host.py +++ b/tests/test_codex_operation_host.py @@ -108,6 +108,179 @@ def _registered_host_goal(tmp_path: Path) -> Path: return registry +def _managed_writeback_args( + project: Path, runtime: Path, registry: Path, executable: Path, +) -> list[str]: + return [ + "--registry", str(registry), "--runtime-root", str(runtime), "--format", "json", + "turn", "run-once", "--goal-id", "loopx-turn-fixture", "--agent-id", "codex-fixture", + "--host", "codex-cli", "--project", str(project), "--no-global-sync", "--codex-operation-tools", + "--codex-bin", str(executable), "--codex-model", "test-model", "--codex-reasoning-effort", "xhigh", + "--codex-sandbox", "read-only", "--iteration-context", "fresh", "--execute", + "--turn-instance-id", "isolated-writeback", "--timeout-seconds", "30", + "--validation-command-json", json.dumps([sys.executable, "-c", "import json,sys; json.load(sys.stdin)"]), + ] + + +@pytest.mark.parametrize("another_todo", [False, True], ids=["single-terminal", "multiple-open"]) +def test_isolated_core_rechecks_goal_before_todo_completion(tmp_path, monkeypatch, another_todo): + from loopx.cli import main as cli_main + from loopx.control_plane.goals.activation_service import set_goal_activation_state + from loopx.control_plane.goals.first_party_host_admission import FirstPartyHostGoalAdmission + from loopx.control_plane.turn_driver import codex_worker_identity, executor + + other_todo = ( + "- [ ] [P1] Validate the next fixture.", + " ", + ) + project, runtime, registry = _write_live_fixture( + tmp_path, + todo_metadata_extra="" if another_todo else "no_followup=true", + extra_agent_todo_lines=other_todo if another_todo else (), + ) + executable = tmp_path / "codex-worker-fixture" + executable.write_text(FAKE_SERVER) + executable.chmod(0o700) + monkeypatch.setenv("FAKE_OPERATION_RESULT_FIELDS", json.dumps({ + "result_kind": "validated_completion", + "classification": "isolated_completion_fixture", + "recommended_action": "Review the next fixture.", + "next_action": "Review the next fixture.", + "delivery_batch_scale": "implementation", + "delivery_outcome": "outcome_progress", + "vision_unchanged_reason": "The goal remains active after this fixture.", + "work_evidence": ["artifact:completion-fixture"], + "validation_evidence": ["check:completion-fixture"], + })) + # Exercise the Core decision with an ordinary local fixture process. + # The Linux launcher test below qualifies the OS identity transition. + monkeypatch.setattr(codex_worker_identity, "worker_isolation_requested", lambda: True) + monkeypatch.setattr(codex_worker_identity, "load_worker_identity", lambda *_: None) + + original_check = FirstPartyHostGoalAdmission.require_running + checks = [] + + def stop_at_writeback(admission, *, operation): + if operation == "isolated_codex_durable_writeback": + checks.append(operation) + set_goal_activation_state( + registry_path=registry, goal_id="loopx-turn-fixture", state="stopped", + reason="Fixture stops before completion", actor_kind="owner", execute=True, + ) + return original_check(admission, operation=operation) + + original_requirement = executor.terminal_closeout_requirement + closeouts = [] + + def record_closeout(**kwargs): + result = original_requirement(**kwargs) + closeouts.append(result) + return result + + monkeypatch.setattr(FirstPartyHostGoalAdmission, "require_running", stop_at_writeback) + monkeypatch.setattr(executor, "terminal_closeout_requirement", record_closeout) + output = io.StringIO() + with contextlib.redirect_stdout(output): + status = cli_main(_managed_writeback_args(project, runtime, registry, executable)) + payload = json.loads(output.getvalue()) + assert closeouts == [(not another_todo, None)], payload + assert checks == ["isolated_codex_durable_writeback"], payload + assert status == 1 and not payload["effects"]["state_written"] and not payload["effects"]["quota_spent"], payload + index = runtime / "goals/loopx-turn-fixture/runs/index.jsonl" + assert not index.exists() or "isolated_completion_fixture" not in index.read_text() + + +@pytest.mark.skipif(sys.platform != "linux" or (hasattr(os, "geteuid") and os.geteuid() != 0), + reason="requires a Linux setuid launcher") +@pytest.mark.parametrize("stop_before_write", [False, True]) +def test_isolated_codex_worker_cannot_publish_or_override_core(monkeypatch, stop_before_write): + import pwd + import shutil + import tempfile + + from loopx.cli import main as cli_main + from loopx.control_plane.goals.activation_service import set_goal_activation_state + from loopx.control_plane.goals.first_party_host_admission import FirstPartyHostGoalAdmission + + if shutil.which("setpriv", path=os.defpath) is None: + pytest.skip("system setpriv is unavailable") + try: + worker = pwd.getpwnam("nobody") + except KeyError: + pytest.skip("nobody fixture account is unavailable") + with tempfile.TemporaryDirectory(prefix="loopx-isolated-operation-", dir="/var/tmp") as directory: + area = Path(directory) + area.chmod(0o755) + project, runtime, registry = _write_live_fixture(area) + runtime.chmod(0o700) + registry.parent.chmod(0o700) + worker_home = area / "worker" + worker_home.mkdir(mode=0o700) + codex_home = worker_home / ".codex" + codex_home.mkdir(mode=0o700) + for path in (worker_home, codex_home): + os.chown(path, worker.pw_uid, worker.pw_gid) + monkeypatch.setenv("LOOPX_CODEX_OPERATION_WORKER_USER", worker.pw_name) + monkeypatch.setenv("LOOPX_CODEX_OPERATION_WORKER_HOME", str(worker_home)) + monkeypatch.setenv("LOOPX_CORE_TEST_SECRET", "only-in-core") + marker = worker_home / "isolation-observed" + probe = f''' +from pathlib import Path +assert os.geteuid() == {worker.pw_uid} and os.getgroups() == [] +assert "LOOPX_CORE_TEST_SECRET" not in os.environ +assert "NoNewPrivs:\\t1" in Path("/proc/self/status").read_text() +for path in ({str(registry)!r}, {str(runtime / 'worker-write')!r}): + try: + Path(path).write_text("worker attempted a direct write") + except PermissionError: + pass + else: + raise AssertionError("worker wrote to Core authority") +Path({str(marker)!r}).touch() +''' + executable = area / "codex-worker-fixture" + answer = {"result_kind": "validated_progress", "classification": "isolated_fixture", + "recommended_action": "Continue validation", "next_action": "Continue validation", + "delivery_batch_scale": "implementation", "delivery_outcome": "outcome_progress", + "vision_unchanged_reason": "Fixture remains open", + "work_evidence": ["artifact:isolated-fixture"], "validation_evidence": ["check:fixture-validation"]} + executable.write_text(FAKE_SERVER.replace('\nimport os\n', '\nimport os\n' + probe, 1).replace( + 'answer.update(json.loads(os.environ.get("FAKE_OPERATION_RESULT_FIELDS", "{}")))', + f"answer.update({answer!r})")) + executable.chmod(0o755) + original_check = FirstPartyHostGoalAdmission.require_running + checks = [] + + def check_at_writeback(admission, *, operation): + if operation == "isolated_codex_durable_writeback": + checks.append(operation) + if stop_before_write: + set_goal_activation_state(registry_path=registry, goal_id="loopx-turn-fixture", + state="stopped", reason="Fixture stop at writeback", actor_kind="owner", execute=True) + return original_check(admission, operation=operation) + + monkeypatch.setattr(FirstPartyHostGoalAdmission, "require_running", check_at_writeback) + args = _managed_writeback_args(project, runtime, registry, executable) + output = io.StringIO() + with contextlib.redirect_stdout(output): + status = cli_main(args) + payload = json.loads(output.getvalue()) + assert marker.is_file() and marker.stat().st_uid == worker.pw_uid, payload + assert checks == ["isolated_codex_durable_writeback"], json.dumps(payload, indent=2) + index = runtime / "goals/loopx-turn-fixture/runs/index.jsonl" + if stop_before_write: + assert status == 1 and not payload["effects"]["quota_spent"] and not payload["effects"]["state_written"], payload + assert not index.exists() or "isolated_fixture" not in index.read_text() + else: + assert status == 0 and payload["effects"]["quota_spent"] and payload["effects"]["state_written"], payload + before = index.read_bytes() + assert b"isolated_fixture" in before + with contextlib.redirect_stdout(io.StringIO()): + cli_main(args) + assert index.read_bytes() == before + + def _claimed_native_fixture(tmp_path: Path): from examples import operation_action_fixtures as fixtures from loopx.control_plane.turn_driver.managed_operation_host import operation_tool_handler diff --git a/tests/test_dsh_plugin_publish_workflow.py b/tests/test_dsh_plugin_publish_workflow.py index 976c6317c6..24e9cdb09c 100644 --- a/tests/test_dsh_plugin_publish_workflow.py +++ b/tests/test_dsh_plugin_publish_workflow.py @@ -39,16 +39,27 @@ def test_dsh_plugin_publish_workflow_allows_tag_or_main_dispatch_with_relative_a assert "DSH_ARTIFACT=./output/${manifest.name}-${manifest.version}.tgz" in identity_run assert re.search(r"DSH_ARTIFACT=output/", raw) is None + download_step = next( + step for step in steps if step.get("name") == "Download the immutable GitHub package" + ) + assert "DSH_NPM_PACKAGE_MISSING=" in download_step["run"] + assert "DSH_NPM_STAGING_PLACEHOLDER=" in download_step["run"] + publish_step = next( step for step in steps if step.get("name") == "Publish the same bytes with npm trusted publishing" ) assert 'npm publish "$DSH_ARTIFACT" --access public --tag latest --ignore-scripts --provenance' in publish_step["run"] + assert "Allow npm publish checked" in publish_step["run"] + assert "blank Environment name" in publish_step["run"] verify_step = next( step for step in steps if step.get("name") == "Read back npm bytes, latest, and marketplace repository discovery" ) + assert "git show origin/main:packages/dsh-loopx-plugin/scripts/verify-distribution.mjs > scripts/verify-distribution.mjs" in verify_step["run"] assert 'node scripts/verify-distribution.mjs --tarball "$DSH_ARTIFACT"' in verify_step["run"] readme = README_PATH.read_text(encoding="utf-8") - assert "on the existing published plugin tag or on `main`" in readme - assert "refs/tags/" in readme + normalized_readme = " ".join(readme.split()) + assert "on the existing published plugin tag or on `main`" in normalized_readme + assert "refs/tags/" in normalized_readme + assert "Allow npm publish" in normalized_readme diff --git a/tests/test_host_thread_activity.py b/tests/test_host_thread_activity.py index 620ebc792b..f9225abe81 100644 --- a/tests/test_host_thread_activity.py +++ b/tests/test_host_thread_activity.py @@ -1153,3 +1153,183 @@ def observe(thread_ids: Any) -> dict[str, HostThreadActivity]: expectations=lambda scopes: pytest.fail("no observed lane may ask for a cadence"), ) assert unattached == expected + + +@pytest.mark.parametrize("unavailable_identity", [None, "st_dev", "st_ino"]) +@pytest.mark.parametrize("platform", ["nt", "posix"]) +@pytest.mark.parametrize("field", ["st_mtime_ns", "st_ctime_ns"]) +def test_same_size_read_fence_metadata_policy(home, monkeypatch, platform, field, unavailable_identity): + rollout = home.thread("t", [_event(T2, "task_complete")]) + rollout_stat = rollout.stat() + assert rollout_stat.st_dev and rollout_stat.st_ino + original_fstat = os.fstat + original_stat = Path.stat + descriptor_observations = 0 + + def partial_identity(observed): + if unavailable_identity is None or (observed.st_dev, observed.st_ino) != ( + rollout_stat.st_dev, rollout_stat.st_ino + ): + return observed + # Unavailable volume/file indexes are injected at every rollout stat. + fields = {name: getattr(observed, name) for name in dir(observed) if name.startswith("st_")} + fields[unavailable_identity] = 0 + return SimpleNamespace(**fields) + + def path_stat(self, *args, **kwargs): + return partial_identity(original_stat(self, *args, **kwargs)) + + def descriptor_stat(fd): + nonlocal descriptor_observations + observed = original_fstat(fd) + if (observed.st_dev, observed.st_ino) != (rollout_stat.st_dev, rollout_stat.st_ino): + return observed + descriptor_observations += 1 + observed = partial_identity(observed) + if descriptor_observations != 2: + return observed + fields = {name: getattr(observed, name) for name in dir(observed) if name.startswith("st_")} + fields[field] += 1 + return SimpleNamespace(**fields) + + monkeypatch.setattr(Path, "stat", path_stat) + monkeypatch.setattr(codex_activity, "os", SimpleNamespace(**{ + **vars(os), "name": platform, "fstat": descriptor_stat, + })) + result = observe_codex_threads(["t"], homes=[home.root])["t"] + if platform == "nt" and field == "st_ctime_ns" and unavailable_identity is None: + assert result.state is HostThreadState.IDLE + assert result.last_turn_ended_at == T2 + assert descriptor_observations == 4 + else: + assert result == HostThreadActivity.unknown(HostThreadUnknownReason.RECORD_UNRECOGNIZED) + assert descriptor_observations == 2 + + +@pytest.mark.parametrize("warm_cursor", [False, True], ids=["cold", "forward"]) +@pytest.mark.parametrize("change", ["none", "marker", "latest", "append"]) +def test_windows_ctime_skew_checks_current_rollout_records(home, monkeypatch, warm_cursor, change): + records = [_event(T1, "task_complete"), _item(T2)] + if warm_cursor: + path = home.thread("t", [_event(T0, "task_started")]) + assert _observe(home, "t")["t"].state is HostThreadState.TURN_OPEN + with path.open("ab") as handle: + handle.write("".join(json.dumps(row) + "\n" for row in records).encode()) + else: + path = home.thread("t", records) + initial = path.stat() + old_bytes = path.read_bytes() + old_identity = (initial.st_dev, initial.st_ino) + observed_stats = 0 + + def fstat(fd): + nonlocal observed_stats + observed = os.fstat(fd) + if (observed.st_dev, observed.st_ino) != old_identity: + return observed + observed_stats += 1 + if observed_stats != 2: + return observed + if change == "append": + with path.open("ab") as handle: + handle.write((json.dumps(_event(T3, "task_started")) + "\n").encode()) + return os.fstat(fd) + if change in {"marker", "latest"}: + new_bytes = ( + old_bytes.replace(b'"task_complete"', b'"task_started" ') + if change == "marker" + else old_bytes.replace(T2.encode(), T3.encode()) + ) + assert old_bytes != new_bytes and len(old_bytes) == len(new_bytes) + path.write_bytes(new_bytes) + os.utime(path, ns=(initial.st_atime_ns, initial.st_mtime_ns)) + fields = {name: getattr(observed, name) for name in dir(observed) if name.startswith("st_")} + fields["st_ctime_ns"] = initial.st_ctime_ns + 1 + return SimpleNamespace(**fields) + + monkeypatch.setattr(codex_activity, "os", SimpleNamespace(**{**vars(os), "name": "nt", "fstat": fstat})) + result = _observe(home, "t")["t"] + if change == "none": + assert result == HostThreadActivity( + state=HostThreadState.IDLE, last_turn_ended_at=T1, last_event_at=T2, + ) + elif change == "append": + assert result == HostThreadActivity.unknown(HostThreadUnknownReason.NO_TURN_MARKER) + assert _observe(home, "t")["t"].turn_started_at == T3 + else: + assert result == HostThreadActivity.unknown(HostThreadUnknownReason.RECORD_UNRECOGNIZED) + refreshed = _observe(home, "t")["t"] + if change == "marker": + assert refreshed == HostThreadActivity( + state=HostThreadState.TURN_OPEN, turn_started_at=T1, last_event_at=T2, + ) + else: + assert refreshed == HostThreadActivity( + state=HostThreadState.IDLE, last_turn_ended_at=T1, last_event_at=T3, + ) + + +def test_windows_ctime_skew_does_not_exceed_remaining_read_budget(home, monkeypatch): + path = home.thread("t", [_event(T2, "task_complete")]) + total_bytes = 0 + read = codex_activity.Reader.read + + def count(reader, offset, count): + nonlocal total_bytes + data = read(reader, offset, count) + total_bytes += len(data) + return data + + monkeypatch.setattr(codex_activity.Reader, "read", count) + assert _observe(home, "t")["t"].state is HostThreadState.IDLE + budget = total_bytes + monkeypatch.setattr(codex_activity, "_OBSERVATION_READ_BYTES", budget) + codex_activity._rollout_cache.clear() + total_bytes = observations = 0 + original = path.stat() + + def fstat(fd): + nonlocal observations + observed = os.fstat(fd) + if (observed.st_dev, observed.st_ino) != (original.st_dev, original.st_ino): + return observed + observations += 1 + if observations != 2: + return observed + fields = {name: getattr(observed, name) for name in dir(observed) if name.startswith("st_")} + fields["st_ctime_ns"] += 1 + return SimpleNamespace(**fields) + + monkeypatch.setattr(codex_activity, "os", SimpleNamespace(**{**vars(os), "name": "nt", "fstat": fstat})) + result = _observe(home, "t")["t"] + assert result == HostThreadActivity.unknown(HostThreadUnknownReason.RECORD_UNRECOGNIZED) + assert total_bytes == budget + + +@pytest.mark.parametrize(("sample", "field"), [ + (3, "st_ino"), + (4, "st_mtime_ns"), + (4, "st_ctime_ns"), +]) +def test_windows_ctime_skew_requires_a_stable_second_read(home, monkeypatch, sample, field): + path = home.thread("t", [_event(T2, "task_complete")]) + original = path.stat() + sampled_descriptors = [] + + def fstat(fd): + observed = os.fstat(fd) + if (observed.st_dev, observed.st_ino) != (original.st_dev, original.st_ino): + return observed + sampled_descriptors.append(fd) + sample_number = len(sampled_descriptors) + if sample_number not in {2, sample}: + return observed + fields = {name: getattr(observed, name) for name in dir(observed) if name.startswith("st_")} + fields["st_ctime_ns" if sample_number == 2 else field] += 1 + return SimpleNamespace(**fields) + + monkeypatch.setattr(codex_activity, "os", SimpleNamespace(**{**vars(os), "name": "nt", "fstat": fstat})) + actual = _observe(home, "t")["t"] + assert actual == HostThreadActivity.unknown(HostThreadUnknownReason.RECORD_UNRECOGNIZED) + assert len(sampled_descriptors) == sample + assert sampled_descriptors[0] != sampled_descriptors[2] diff --git a/tests/test_native_steward_turn_host.py b/tests/test_native_steward_turn_host.py index 5e8e6ca99f..b32d9a1e5b 100644 --- a/tests/test_native_steward_turn_host.py +++ b/tests/test_native_steward_turn_host.py @@ -501,6 +501,36 @@ def checked_plan(source, *args, **kwargs): service.submit(sid, agent_id=actor["agent_id"], operation_id="local-native-1", todo_id="todo_other") +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_native_preparer_declining_a_claim_keeps_the_native_refusal(steward, tmp_path, monkeypatch, provider): + from loopx.control_plane.turn_driver import codex_execution_preparation + + service, session, actor, _, _, capture = managed_fixture(steward, tmp_path, monkeypatch, provider) + store, runtime, *_ = steward + original_calls = capture.read_bytes() + preparation_states = [] + monkeypatch.setattr( + codex_execution_preparation, + "compact_execution_preparation_request", + lambda decision: preparation_states.append(decision["execution_preparation"]["state"]), + ) + sid = session["session_id"] + accepted, _ = service.submit(sid, agent_id=actor["agent_id"], operation_id="native-declines-claim") + finish(runtime, accepted) + assert preparation_states == ["claim_required"] + results = [ + event["payload"] for event in store.events_after(sid, accepted["turn_id"], None) + if event["kind"] == "native_loopx.result" + ] + result, = results + assert result["ok"] is False + assert result["error"] == "LoopX Turn route is not host executable" + assert "claim_command" not in result + assert not any(result["effects"].values()) + calls = [json.loads(row) for row in capture.read_bytes()[len(original_calls):].splitlines()] + assert not any(call["method"] == "turn/start" for call in calls) + + @pytest.mark.parametrize("fault", ["busy", "queued", "attached", "foreign_goal", "stopped_goal", "private", "native_goal", "unregistered", "host_closed"]) def test_local_managed_session_denials_never_launch_or_accept(steward, tmp_path, monkeypatch, fault): service, session, actor, todo_id, _, capture = managed_fixture(steward, tmp_path, monkeypatch) diff --git a/tests/test_scheduler_native_launcher.py b/tests/test_scheduler_native_launcher.py index d3a47d7aa7..2bd5f14e4d 100644 --- a/tests/test_scheduler_native_launcher.py +++ b/tests/test_scheduler_native_launcher.py @@ -14,6 +14,7 @@ write_cli_fixture, write_codex_heartbeat_fixture, ) +from loopx.control_plane.runtime.node_probe import node_typescript_flags from loopx.control_plane.testing.canary_harness import run_json_cli_result from tests.control_plane.canonical_authority_fixture import ( isolate_sqlite_runtime, @@ -71,9 +72,12 @@ def test_unix_launcher_process_replaces_python_for_exact_native_followup( assert completed.returncode == 0, completed.stderr lines = completed.stdout.splitlines() - assert lines[:3] == [ + expected_flags = list(node_typescript_flags()) + script_index = 2 + len(expected_flags) + assert lines[: script_index + 1] == [ "--no-warnings", "--experimental-strip-types", + *expected_flags, str( REPO_ROOT / "loopx" @@ -85,6 +89,75 @@ def test_unix_launcher_process_replaces_python_for_exact_native_followup( assert lines[-len(args) :] == args +@pytest.mark.skipif( + os.name == "nt", + reason="the POSIX source launcher runs only on POSIX hosts", +) +@pytest.mark.parametrize( + ("uname_s", "uname_m", "expected_v8_flags"), + [ + ("Linux", "x86_64", ["--liftoff-only", "--no-wasm-tier-up", "--no-wasm-dynamic-tiering"]), + ("Linux", "amd64", ["--liftoff-only", "--no-wasm-tier-up", "--no-wasm-dynamic-tiering"]), + ("Linux", "aarch64", []), + ("Darwin", "arm64", []), + ], +) +def test_unix_launcher_native_followup_passes_linux_x86_wasm_flags( + tmp_path: Path, + uname_s: str, + uname_m: str, + expected_v8_flags: list[str], +) -> None: + fake_bin = tmp_path / "bin" + fake_bin.mkdir() + (fake_bin / "node").write_text("#!/bin/sh\nprintf '%s\\n' \"$@\"\n", encoding="utf-8") + (fake_bin / "node").chmod(0o755) + (fake_bin / "uname").write_text( + f"#!/bin/sh\ncase \"$1\" in -s) echo {uname_s};; -m) echo {uname_m};; *) /usr/bin/uname \"$@\";; esac\n", + encoding="utf-8", + ) + (fake_bin / "uname").chmod(0o755) + env = { + **os.environ, + "PATH": str(fake_bin) + os.pathsep + os.environ.get("PATH", ""), + "LOOPX_PYTHON": str(tmp_path / "python-must-not-run"), + } + args = [ + "--format", + "json", + "--runtime-root", + str(tmp_path / "runtime"), + "quota", + "scheduler-ack-current", + "--goal-id", + "goal-native-launcher", + "--agent-id", + "agent-native-launcher", + "--scheduler-host-facts-chunk", + "facts", + "--turn-instance-id", + "turn-native-launcher", + "--execute", + ] + completed = subprocess.run( + [str(REPO_ROOT / "scripts" / "loopx"), *args], + check=False, + capture_output=True, + text=True, + env=env, + ) + assert completed.returncode == 0, completed.stderr + lines = completed.stdout.splitlines() + script_index = 2 + len(expected_v8_flags) + assert lines[: script_index + 1] == [ + "--no-warnings", + "--experimental-strip-types", + *expected_v8_flags, + str(REPO_ROOT / "loopx" / "control_plane" / "scheduler" / "heartbeat_followup_cli.ts"), + ] + assert lines[-len(args) :] == args + + @pytest.mark.skipif( os.name == "nt", reason="the POSIX source launcher runs only on POSIX hosts", diff --git a/tests/test_steward_pr_merge_and_review_signal.py b/tests/test_steward_pr_merge_and_review_signal.py index 0d216334da..c0582df93d 100644 --- a/tests/test_steward_pr_merge_and_review_signal.py +++ b/tests/test_steward_pr_merge_and_review_signal.py @@ -8,7 +8,9 @@ import pytest +from loopx.capabilities.native_chat.conversation_bindings import ChatConversationBindings from loopx.capabilities.native_chat.github_pr_evidence import ( + _normalize_graphql_pr_node, inspect_github_pull_request, parse_github_pr_target, summarize_github_pr_signal, @@ -562,3 +564,887 @@ def fake_gh(cmd, **_kwargs): assert recovered["status"] == "applied" assert recovered["receipt"]["outcome"] == "pr_merged_recovered" assert recovered["receipt"]["resource_ids"]["merge_commit_oid"] == "9" * 40 + + +def test_summarize_pr_stalled_since_and_author_reply_detection(monkeypatch) -> None: + head = "e" * 40 + old = "0" * 40 + gpt_decl = "model_agent · gpt-6.2-sol · OpenAI (runtime_reported, max)" + + # Mergify bot comment bumps updatedAt without resetting stalled_since or flagging author reply. + bot_bumped = summarize_github_pr_signal( + { + **_sample_pr( + number=301, + head_oid=head, + author="ext-contributor", + review_decision="CHANGES_REQUESTED", + reviews=[ + { + "id": "PRR_rc1", + "author": {"login": "maintainer"}, + "state": "CHANGES_REQUESTED", + "commit": {"oid": head}, + "submittedAt": "2030-01-01T08:00:00Z", + "body": _valid_bilingual_body(head_oid=head, verdict="REQUEST_CHANGES", reviewer=gpt_decl), + } + ], + ), + "updatedAt": "2030-01-02T00:00:00Z", + "comments": [ + {"createdAt": "2030-01-01T09:00:00Z", "author": {"login": "mergify[bot]"}}, + ], + } + ) + assert bot_bumped["stalled_since"] == "2030-01-01T08:00:00Z" + assert bot_bumped["author_replied_after_request_changes"] is False + assert bot_bumped["review_summary"]["latest_request_changes_review_id"] == "PRR_rc1" + + # External author replies after REQUEST_CHANGES -> awaiting maintainer reply; maintainer reply resets it. + author_replied = summarize_github_pr_signal( + { + **_sample_pr( + number=302, + head_oid=head, + author="ext-contributor", + review_decision="CHANGES_REQUESTED", + reviews=[ + { + "id": "PRR_rc2", + "author": {"login": "maintainer"}, + "state": "CHANGES_REQUESTED", + "commit": {"oid": head}, + "submittedAt": "2030-01-01T08:00:00Z", + "body": _valid_bilingual_body(head_oid=head, verdict="REQUEST_CHANGES", reviewer=gpt_decl), + } + ], + ), + "comments": [ + {"createdAt": "2030-01-01T10:00:00Z", "author": {"login": "ext-contributor"}}, + {"createdAt": "2030-01-01T10:30:00Z", "author": {"login": "mergify[bot]"}}, + ], + } + ) + assert author_replied["author_replied_after_request_changes"] is True + + maintainer_replied = summarize_github_pr_signal( + { + **_sample_pr( + number=302, + head_oid=head, + author="ext-contributor", + review_decision="CHANGES_REQUESTED", + reviews=[ + { + "id": "PRR_rc2", + "author": {"login": "maintainer"}, + "state": "CHANGES_REQUESTED", + "commit": {"oid": head}, + "submittedAt": "2030-01-01T08:00:00Z", + "body": _valid_bilingual_body(head_oid=head, verdict="REQUEST_CHANGES", reviewer=gpt_decl), + }, + { + "id": "PRR_reply", + "author": {"login": "maintainer"}, + "state": "COMMENTED", + "commit": {"oid": head}, + "submittedAt": "2030-01-01T11:00:00Z", + "body": "Please keep the existing state field unchanged.", + }, + ], + ), + "comments": [ + {"createdAt": "2030-01-01T10:00:00Z", "author": {"login": "ext-contributor"}}, + ], + } + ) + assert maintainer_replied["author_replied_after_request_changes"] is False + + # Visitor (authorAssociation=NONE), suffixless Bot (__typename=Bot), and unknown commenter never clear author reply; + # another maintainer (authorAssociation=MEMBER) DOES clear it. + visitor_and_bot_ignored = summarize_github_pr_signal( + { + **_sample_pr( + number=305, + head_oid=head, + author="ext-contributor", + review_decision="CHANGES_REQUESTED", + reviews=[ + { + "id": "PRR_rc5", + "author": {"__typename": "User", "login": "orig-reviewer"}, + "authorAssociation": "MEMBER", + "state": "CHANGES_REQUESTED", + "commit": {"oid": head}, + "submittedAt": "2030-01-01T08:00:00Z", + "body": _valid_bilingual_body(head_oid=head, verdict="REQUEST_CHANGES", reviewer=gpt_decl), + }, + { + "id": "PRR_bystander", + "author": {"__typename": "User", "login": "random-reviewer"}, + "authorAssociation": "CONTRIBUTOR", + "state": "COMMENTED", + "commit": {"oid": head}, + "submittedAt": "2030-01-01T11:30:00Z", + "body": "Looks interesting!", + }, + ], + ), + "comments": [ + {"createdAt": "2030-01-01T10:00:00Z", "authorAssociation": "NONE", "author": {"__typename": "User", "login": "ext-contributor"}}, + {"createdAt": "2030-01-01T10:20:00Z", "authorAssociation": "NONE", "author": {"__typename": "User", "login": "random-visitor"}}, + {"createdAt": "2030-01-01T10:40:00Z", "authorAssociation": "NONE", "author": {"__typename": "Bot", "login": "custom-ci-helper"}}, + {"createdAt": "2030-01-01T11:00:00Z", "author": {"login": "missing-association-user"}}, + ], + } + ) + assert visitor_and_bot_ignored["author_replied_after_request_changes"] is True + + other_maintainer_replied = summarize_github_pr_signal( + { + **_sample_pr( + number=305, + head_oid=head, + author="ext-contributor", + review_decision="CHANGES_REQUESTED", + reviews=[ + { + "id": "PRR_rc5", + "author": {"__typename": "User", "login": "orig-reviewer"}, + "authorAssociation": "MEMBER", + "state": "CHANGES_REQUESTED", + "commit": {"oid": head}, + "submittedAt": "2030-01-01T08:00:00Z", + "body": _valid_bilingual_body(head_oid=head, verdict="REQUEST_CHANGES", reviewer=gpt_decl), + }, + ], + ), + "comments": [ + {"createdAt": "2030-01-01T10:00:00Z", "authorAssociation": "NONE", "author": {"__typename": "User", "login": "ext-contributor"}}, + {"createdAt": "2030-01-01T12:00:00Z", "authorAssociation": "MEMBER", "author": {"__typename": "User", "login": "second-maintainer"}}, + ], + } + ) + assert other_maintainer_replied["author_replied_after_request_changes"] is False + + # Stale-commit CHANGES_REQUESTED after new head commit push leaves stalled_since as None. + stale_after_push = summarize_github_pr_signal( + _sample_pr( + number=303, + head_oid=head, + author="ext-contributor", + review_decision="CHANGES_REQUESTED", + reviews=[ + { + "id": "PRR_stale_rc", + "author": {"login": "maintainer"}, + "state": "CHANGES_REQUESTED", + "commit": {"oid": old}, + "submittedAt": "2030-01-01T08:00:00Z", + "body": _valid_bilingual_body(head_oid=old, verdict="REQUEST_CHANGES", reviewer=gpt_decl), + } + ], + ) + ) + assert stale_after_push["stalled_since"] is None + assert stale_after_push["review_summary"]["latest_request_changes_review_id"] is None + assert stale_after_push["author_replied_after_request_changes"] is False + + # GraphQL page normalization retains comments and head commit pushedDate. + gql_node = _graphql_node( + _sample_pr( + number=304, + head_oid=head, + author="ext-contributor", + review_decision="CHANGES_REQUESTED", + reviews=[ + { + "id": "PRR_rc4", + "author": {"login": "maintainer"}, + "state": "CHANGES_REQUESTED", + "commit": {"oid": head}, + "submittedAt": "2030-01-01T08:00:00Z", + "body": _valid_bilingual_body(head_oid=head, verdict="REQUEST_CHANGES", reviewer=gpt_decl), + } + ], + ) + ) + gql_node["comments"] = { + "nodes": [ + {"createdAt": "2030-01-01T12:00:00Z", "authorAssociation": "NONE", "author": {"__typename": "User", "login": "ext-contributor"}}, + {"createdAt": "2030-01-01T12:15:00Z", "authorAssociation": "NONE", "author": {"__typename": "User", "login": "random-visitor"}}, + {"createdAt": "2030-01-01T12:30:00Z", "authorAssociation": "NONE", "author": {"__typename": "Bot", "login": "custom-ci-helper"}}, + ] + } + gql_node["commits"]["nodes"][0]["commit"]["oid"] = head + gql_node["commits"]["nodes"][0]["commit"]["committedDate"] = "2030-01-01T07:00:00Z" + gql_node["commits"]["nodes"][0]["commit"]["pushedDate"] = "2030-01-01T09:00:00Z" + + def fake_gql(cmd, **_kwargs): + return subprocess.CompletedProcess(cmd, 0, stdout=json.dumps(_graphql_page([gql_node])), stderr="") + + monkeypatch.setattr("loopx.capabilities.native_chat.steward_monitor.subprocess.run", fake_gql) + observed = _observe_github_repository_prs("org/repo") + assert observed["status"] == "ok" + item = observed["items"][0] + assert item["stalled_since"] == "2030-01-01T09:00:00Z" + assert item["author_replied_after_request_changes"] is True + assert item["comments_coverage_incomplete"] is False + assert item["review_summary"]["comments_coverage_incomplete"] is False + assert item["review_summary"]["latest_request_changes_review_id"] == "PRR_rc4" + + +def test_observe_github_prs_backfills_evicted_author_reply_and_preserves_incomplete_coverage( + monkeypatch, +) -> None: + head = "f" * 40 + gpt_decl = "model_agent · gpt-6.2-sol · OpenAI (runtime_reported, max)" + rc_review = { + "id": "PRR_rc_401", + "author": {"__typename": "User", "login": "maintainer"}, + "authorAssociation": "MEMBER", + "state": "CHANGES_REQUESTED", + "commit": {"oid": head}, + "submittedAt": "2030-01-01T08:00:00Z", + "body": _valid_bilingual_body(head_oid=head, verdict="REQUEST_CHANGES", reviewer=gpt_decl), + } + + def _visitor_comments(count: int, *, start_minute: int = 1, prefix_hour: str = "10") -> list[dict[str, Any]]: + return [ + { + "createdAt": f"2030-01-01T{prefix_hour}:{start_minute + idx:02d}:00Z", + "authorAssociation": "NONE", + "author": {"__typename": "User", "login": f"visitor-{idx}"}, + } + for idx in range(count) + ] + + author_comment = { + "createdAt": "2030-01-01T09:00:00Z", + "authorAssociation": "NONE", + "author": {"__typename": "User", "login": "ext-contributor"}, + } + maintainer_comment = { + "createdAt": "2030-01-01T09:30:00Z", + "authorAssociation": "MEMBER", + "author": {"__typename": "User", "login": "maintainer"}, + } + + # Normalization defaults vs pageInfo propagation. + plain_norm = _normalize_graphql_pr_node(_sample_pr(number=400, head_oid=head)) + assert plain_norm["commentsHasPreviousPage"] is False + assert plain_norm["commentsStartCursor"] is None + + # Pre-anchor comment inside truncated window proves completeness without backfill. + pre_anchor_summary = summarize_github_pr_signal( + { + **_sample_pr(number=400, head_oid=head, author="ext-contributor", reviews=[rc_review]), + "commentsHasPreviousPage": True, + "commentsStartCursor": "c0", + "comments": [ + {"createdAt": "2030-01-01T07:30:00Z", "authorAssociation": "NONE", "author": {"login": "old-visitor"}}, + *_visitor_comments(19), + ], + } + ) + assert pre_anchor_summary["comments_coverage_incomplete"] is False + assert pre_anchor_summary["review_summary"]["comments_coverage_incomplete"] is False + + # No exact-head REQUEST_CHANGES means comments_coverage_incomplete is always False. + no_rc_summary = summarize_github_pr_signal( + { + **_sample_pr(number=400, head_oid=head, author="ext-contributor", reviews=[]), + "commentsHasPreviousPage": True, + "comments": _visitor_comments(20), + } + ) + assert no_rc_summary["comments_coverage_incomplete"] is False + + def _base_node(*, updated_at: str, comments_conn: dict[str, Any]) -> dict[str, Any]: + node = _graphql_node( + _sample_pr( + number=401, + head_oid=head, + author="ext-contributor", + review_decision="CHANGES_REQUESTED", + reviews=[rc_review], + ) + ) + node["updatedAt"] = updated_at + node["comments"] = comments_conn + return node + + external_scope = { + "schema_version": "steward_signal_monitor_scope_v0", + "include_portfolio": False, + "include_inbox": False, + "pr_filter": { + "exclude_drafts": True, + "effective_verdicts": ["REQUEST_CHANGES"], + "author_mode": "exclude", + "authors": ["maintainer"], + "min_stalled_hours": 24, + }, + } + + # 1. Snapshot 1 -> awaiting_maintainer_reply; Snapshot 2 evicts author reply into page 2 -> + # backfill recovers author_replied_after_request_changes=True and identical TS result_hash. + snap1_node = _base_node( + updated_at="2030-01-01T10:19:00Z", + comments_conn={ + "pageInfo": {"hasPreviousPage": False, "startCursor": "c1"}, + "nodes": [author_comment, *_visitor_comments(19)], + }, + ) + snap2_node = _base_node( + updated_at="2030-01-01T10:20:00Z", + comments_conn={ + "pageInfo": {"hasPreviousPage": True, "startCursor": "c20"}, + "nodes": _visitor_comments(20), + }, + ) + + def _observe_with(fake_runner, *, backfill_comments: bool = True) -> dict[str, Any]: + with monkeypatch.context() as mp: + if backfill_comments: + mp.setattr( + "loopx.capabilities.native_chat.steward_monitor.subprocess.run", + fake_runner, + ) + return _observe_github_repository_prs("org/repo", backfill_comments=True) + mp.setattr( + "loopx.capabilities.native_chat.steward_monitor.subprocess.run", + fake_runner, + ) + return _observe_github_repository_prs("org/repo") + + calls_snap1: list[list[str]] = [] + repo_snap1 = _observe_with( + lambda cmd, **_kw: ( + calls_snap1.append(list(cmd)) + or subprocess.CompletedProcess(cmd, 0, stdout=json.dumps(_graphql_page([snap1_node])), stderr="") + ) + ) + assert len(calls_snap1) == 1 + assert repo_snap1["items"][0]["author_replied_after_request_changes"] is True + assert repo_snap1["items"][0]["comments_coverage_incomplete"] is False + obs1 = ChatConversationBindings._core( + "collaboration.steward.monitor.signal_observation", + { + "signal_scope": external_scope, + "repository_snapshot": repo_snap1, + "observed_at": "2030-01-01T11:00:00Z", + "previous_hash": None, + }, + ) + assert obs1["observation_incomplete"] is False + assert obs1["scoped_repository_items"][0]["stalled_bucket"] == "awaiting_maintainer_reply" + + calls_snap2: list[list[str]] = [] + + def run_snap2(cmd, **_kwargs): + calls_snap2.append(list(cmd)) + if any(arg == "before=c20" for arg in cmd): + assert "-F" in cmd and "number=401" in cmd + body = { + "data": { + "repository": { + "pullRequest": { + "comments": { + "pageInfo": {"hasPreviousPage": False, "startCursor": "c1"}, + "nodes": [author_comment], + } + } + } + } + } + return subprocess.CompletedProcess(cmd, 0, stdout=json.dumps(body), stderr="") + return subprocess.CompletedProcess(cmd, 0, stdout=json.dumps(_graphql_page([snap2_node])), stderr="") + + repo_snap2 = _observe_with(run_snap2) + assert len(calls_snap2) == 2 + assert repo_snap2["items"][0]["author_replied_after_request_changes"] is True + assert repo_snap2["items"][0]["comments_coverage_incomplete"] is False + assert repo_snap2["items"][0]["review_summary"]["comments_coverage_incomplete"] is False + obs2 = ChatConversationBindings._core( + "collaboration.steward.monitor.signal_observation", + { + "signal_scope": external_scope, + "repository_snapshot": repo_snap2, + "observed_at": "2030-01-01T11:05:00Z", + "previous_hash": obs1["result_hash"], + }, + ) + assert obs2["result_hash"] == obs1["result_hash"] + assert obs2["material_change"] is False + assert obs2["observation_incomplete"] is False + + # 2a. Maintainer (MEMBER) reply in visible page 1 (hasPreviousPage=True) requires 0 backfill calls. + page1_maintainer_node = _base_node( + updated_at="2030-01-01T10:25:00Z", + comments_conn={ + "pageInfo": {"hasPreviousPage": True, "startCursor": "c20"}, + "nodes": [maintainer_comment, *_visitor_comments(19)], + }, + ) + calls_maintainer_p1: list[list[str]] = [] + repo_maintainer_p1 = _observe_with( + lambda cmd, **_kw: ( + calls_maintainer_p1.append(list(cmd)) + or subprocess.CompletedProcess(cmd, 0, stdout=json.dumps(_graphql_page([page1_maintainer_node])), stderr="") + ) + ) + assert len(calls_maintainer_p1) == 1 + assert repo_maintainer_p1["items"][0]["author_replied_after_request_changes"] is False + assert repo_maintainer_p1["items"][0]["comments_coverage_incomplete"] is False + obs_maintainer_p1 = ChatConversationBindings._core( + "collaboration.steward.monitor.signal_observation", + { + "signal_scope": external_scope, + "repository_snapshot": repo_maintainer_p1, + "observed_at": "2030-01-01T11:10:00Z", + "previous_hash": obs1["result_hash"], + }, + ) + assert obs_maintainer_p1["material_change"] is True + assert obs_maintainer_p1["observation_incomplete"] is False + assert obs_maintainer_p1["scoped_repository_items"] == [] + + # 2b. Maintainer reply after author on backfill page 2 exits awaiting_maintainer_reply. + calls_maintainer_p2: list[list[str]] = [] + + def run_maintainer_p2(cmd, **_kwargs): + calls_maintainer_p2.append(list(cmd)) + if any(arg == "before=c20" for arg in cmd): + body = { + "data": { + "repository": { + "pullRequest": { + "comments": { + "pageInfo": {"hasPreviousPage": True, "startCursor": "c0"}, + "nodes": [author_comment, maintainer_comment], + } + } + } + } + } + return subprocess.CompletedProcess(cmd, 0, stdout=json.dumps(body), stderr="") + return subprocess.CompletedProcess(cmd, 0, stdout=json.dumps(_graphql_page([snap2_node])), stderr="") + + repo_maintainer_p2 = _observe_with(run_maintainer_p2) + assert len(calls_maintainer_p2) == 2 + assert repo_maintainer_p2["items"][0]["author_replied_after_request_changes"] is False + assert repo_maintainer_p2["items"][0]["comments_coverage_incomplete"] is False + obs_maintainer_p2 = ChatConversationBindings._core( + "collaboration.steward.monitor.signal_observation", + { + "signal_scope": external_scope, + "repository_snapshot": repo_maintainer_p2, + "observed_at": "2030-01-01T11:15:00Z", + "previous_hash": obs1["result_hash"], + }, + ) + assert obs_maintainer_p2["material_change"] is True + assert obs_maintainer_p2["observation_incomplete"] is False + assert obs_maintainer_p2["scoped_repository_items"] == [] + + # 3. Backfill budget exhausted (3 pages of visitor comments, still hasPreviousPage=True) -> + # comments_coverage_incomplete=True and TS retains previous_hash with observation_incomplete=True. + backfill_cursors: list[str] = [] + + def run_exhausted(cmd, **_kwargs): + before_args = [arg.split("=", 1)[1] for arg in cmd if arg.startswith("before=")] + if before_args: + cursor = before_args[0] + backfill_cursors.append(cursor) + next_map = {"c20": ("c70", "11"), "c70": ("c120", "12"), "c120": ("c170", "13")} + next_cursor, hour = next_map[cursor] + body = { + "data": { + "repository": { + "pullRequest": { + "comments": { + "pageInfo": {"hasPreviousPage": True, "startCursor": next_cursor}, + "nodes": _visitor_comments(5, prefix_hour=hour), + } + } + } + } + } + return subprocess.CompletedProcess(cmd, 0, stdout=json.dumps(body), stderr="") + return subprocess.CompletedProcess(cmd, 0, stdout=json.dumps(_graphql_page([snap2_node])), stderr="") + + repo_exhausted = _observe_with(run_exhausted) + assert backfill_cursors == ["c20", "c70", "c120"] + assert repo_exhausted["status"] == "ok" + assert repo_exhausted["items"][0]["comments_coverage_incomplete"] is True + assert repo_exhausted["items"][0]["review_summary"]["comments_coverage_incomplete"] is True + obs_exhausted = ChatConversationBindings._core( + "collaboration.steward.monitor.signal_observation", + { + "signal_scope": external_scope, + "repository_snapshot": repo_exhausted, + "observed_at": "2030-01-01T11:20:00Z", + "previous_hash": obs1["result_hash"], + }, + ) + assert obs_exhausted == { + "result_hash": obs1["result_hash"], + "material_change": False, + "observation_incomplete": True, + "own_monitor_bookkeeping_excluded": True, + } + + # Backfill RPC error also fails closed with comments_coverage_incomplete=True. + def run_backfill_error(cmd, **_kwargs): + if any(arg.startswith("before=") for arg in cmd): + return subprocess.CompletedProcess(cmd, 1, stdout="", stderr="rate limited") + return subprocess.CompletedProcess(cmd, 0, stdout=json.dumps(_graphql_page([snap2_node])), stderr="") + + repo_rpc_err = _observe_with(run_backfill_error) + assert repo_rpc_err["status"] == "ok" + assert repo_rpc_err["items"][0]["comments_coverage_incomplete"] is True + obs_rpc_err = ChatConversationBindings._core( + "collaboration.steward.monitor.signal_observation", + { + "signal_scope": external_scope, + "repository_snapshot": repo_rpc_err, + "observed_at": "2030-01-01T11:25:00Z", + "previous_hash": obs1["result_hash"], + }, + ) + assert obs_rpc_err["observation_incomplete"] is True + assert obs_rpc_err["result_hash"] == obs1["result_hash"] + + # Default backfill_comments=False invokes zero comment backfill RPCs even when hasPreviousPage=True. + default_calls: list[list[str]] = [] + repo_default_no_backfill = _observe_with( + lambda cmd, **_kw: ( + default_calls.append(list(cmd)) + or subprocess.CompletedProcess(cmd, 0, stdout=json.dumps(_graphql_page([snap2_node])), stderr="") + ), + backfill_comments=False, + ) + assert len(default_calls) == 1 + assert not any(arg.startswith("before=") for cmd in default_calls for arg in cmd) + assert repo_default_no_backfill["items"][0]["comments_coverage_incomplete"] is True + + +def test_steward_monitor_gates_backfill_and_preserves_non_age_hashes( + steward, tmp_path, monkeypatch, # noqa: F811 +) -> None: + from test_native_steward_managed_mode import original, storage + from tests.control_plane.canonical_authority_fixture import isolate_sqlite_runtime + from loopx.capabilities.native_chat.steward_monitor import StewardMonitor + + isolate_sqlite_runtime(tmp_path, monkeypatch) + _store, runtime, _provider, transport, binding, _capture, _ = steward + sid, managed = original(steward) + storage(runtime, "sqlite") + plan = managed.prepare(binding["binding_id"], session_id=sid)["plan"] + actor = managed.prepare( + binding["binding_id"], + session_id=sid, + expected_plan_id=plan["plan_id"], + execute=True, + )["actor"] + context = {"authorization_scope_id": "scope_test", "goals": [{"id": actor["goal_id"], "status": "active"}]} + monitor = StewardMonitor(runtime) + monkeypatch.setattr( + monitor.bindings, + "steward_scope", + lambda _session: [actor["goal_id"]], + ) + monkeypatch.setattr( + monitor.bindings, + "_core", + lambda op, params: ( + {"result_hash": "sha256:portfolio-fixed"} + if op == "collaboration.steward.monitor.observation" + else ChatConversationBindings._core(op, params) + ), + ) + + head = "c" * 40 + gpt_decl = "model_agent · gpt-6.2-sol · OpenAI (runtime_reported, max)" + rc_review = { + "id": "PRR_rc_501", + "author": {"__typename": "User", "login": "maintainer"}, + "authorAssociation": "MEMBER", + "state": "CHANGES_REQUESTED", + "commit": {"oid": head}, + "submittedAt": "2030-01-01T08:00:00Z", + "body": _valid_bilingual_body(head_oid=head, verdict="REQUEST_CHANGES", reviewer=gpt_decl), + } + author_comment = { + "createdAt": "2030-01-01T09:00:00Z", + "authorAssociation": "NONE", + "author": {"__typename": "User", "login": "ext-contributor"}, + } + + def _visitors(count: int) -> list[dict[str, Any]]: + return [ + { + "createdAt": f"2030-01-01T10:{1 + idx:02d}:00Z", + "authorAssociation": "NONE", + "author": {"__typename": "User", "login": f"visitor-{idx}"}, + } + for idx in range(count) + ] + + def _pr_node(*, updated_at: str, comments_conn: dict[str, Any]) -> dict[str, Any]: + node = _graphql_node( + _sample_pr( + number=501, + head_oid=head, + author="ext-contributor", + review_decision="CHANGES_REQUESTED", + reviews=[rc_review], + ) + ) + node["updatedAt"] = updated_at + node["comments"] = comments_conn + return node + + complete_node = _pr_node( + updated_at="2030-01-01T10:19:00Z", + comments_conn={ + "pageInfo": {"hasPreviousPage": False, "startCursor": "c1"}, + "nodes": [author_comment, *_visitors(19)], + }, + ) + truncated_node = _pr_node( + updated_at="2030-01-01T10:19:00Z", + comments_conn={ + "pageInfo": {"hasPreviousPage": True, "startCursor": "c20"}, + "nodes": _visitors(20), + }, + ) + updated_at_changed_node = _pr_node( + updated_at="2030-01-01T10:30:00Z", + comments_conn={ + "pageInfo": {"hasPreviousPage": True, "startCursor": "c20"}, + "nodes": _visitors(20), + }, + ) + + def _create_monitor(target_key: str, signal_scope: dict[str, Any] | None) -> dict[str, Any]: + actions = transport.core.actions + params_dict: dict[str, Any] = { + "goal_id": actor["goal_id"], + "agent_id": actor["agent_id"], + "target": f"Monitor {target_key}", + "target_key": target_key, + "task_repository": "org/repo", + "cadence": "every_2_hours", + "timezone": "Asia/Shanghai", + "stop_condition": "watch_only", + } + if signal_scope is not None: + params_dict["signal_scope"] = signal_scope + preview = actions.preview({ + "action_kind": "monitor.create", + "summary": f"Create {target_key}", + "normalized_parameters": params_dict, + "context": {"kind": "goal", "goal_id": actor["goal_id"]}, + "idempotency_key": f"create-{target_key}", + }) + assert preview["status"] == "preview_ready" + todo_id = actions.apply(preview["proposal_id"])["proposal"]["receipt"]["resource_ids"]["todo_id"] + return next(row for row in monitor.todos(actor) if row["todo_id"] == todo_id) + + def _collect_with_gh(todo_row: dict[str, Any], gh_runner) -> tuple[dict[str, Any], list[str], list[list[str]]]: + seen_cmds: list[list[str]] = [] + real_subprocess_run = subprocess.run + + def wrapped(cmd, **kwargs): + if cmd and cmd[0] == "gh": + seen_cmds.append(list(cmd)) + return gh_runner(cmd, **kwargs) + return real_subprocess_run(cmd, **kwargs) + + with monkeypatch.context() as mp: + mp.setattr("loopx.capabilities.native_chat.steward_monitor.subprocess.run", wrapped) + obs, succ = monitor._collect_signal_monitor(actor, context, todo_row) + return obs, succ, seen_cmds + + # 1. Pre-#9207 persisted hash parity + unscoped (signal_scope=None) monitor: + # 0 backfill calls, no false wakeup on truncated window, real updatedAt change wakes up. + unscoped_todo = _create_monitor("steward-unscoped-no-backfill", None) + pre9207_item = { + "number": 501, + "title": "PR #501", + "url": "https://github.com/org/repo/pull/501", + "headRefOid": head, + "headRefName": "codex/test-pr", + "baseRefName": "main", + "isDraft": False, + "author": {"login": "ext-contributor"}, + "reviewDecision": "CHANGES_REQUESTED", + "mergeStateStatus": "BLOCKED", + "mergeable": "MERGEABLE", + "updatedAt": "2030-01-01T10:19:00Z", + "checks_summary": {"total": 1, "pass_count": 1, "fail_count": 0, "pending_count": 0}, + "review_summary": { + "effective_verdict": "REQUEST_CHANGES", + "has_review_conflict": False, + "stale_review_count": 0, + "exact_head_reviews": [ + { + "id": "PRR_rc_501", + "url": None, + "author_login": "maintainer", + "author_is_pr_author": False, + "state": "CHANGES_REQUESTED", + "verdict": "REQUEST_CHANGES", + "formal_github_verdict": "REQUEST_CHANGES", + "author_owned_fallback": False, + "bilingual_valid": True, + "valid_verdict_review": True, + "reviewer_declaration": gpt_decl, + "submitted_at": "2030-01-01T08:00:00Z", + } + ], + }, + "bypassed_gates": ["BLOCKED_MERGE_STATE"], + } + pre9207_unscoped_obs = ChatConversationBindings._core( + "collaboration.steward.monitor.signal_observation", + { + "portfolio_observation": {"result_hash": "sha256:portfolio-fixed"}, + "inbox_items": [], + "repository_snapshot": {"status": "ok", "repository": "org/repo", "items": [pre9207_item]}, + "previous_hash": None, + }, + ) + unscoped_todo_with_pre9207 = {**unscoped_todo, "result_hash": pre9207_unscoped_obs["result_hash"]} + + obs_unscoped_complete, succ_u1, cmds_u1 = _collect_with_gh( + unscoped_todo_with_pre9207, + lambda cmd, **_kw: subprocess.CompletedProcess(cmd, 0, stdout=json.dumps(_graphql_page([complete_node])), stderr=""), + ) + assert len(cmds_u1) == 1 + assert obs_unscoped_complete["result_hash"] == pre9207_unscoped_obs["result_hash"] + assert obs_unscoped_complete["material_change"] is False + assert obs_unscoped_complete["observation_incomplete"] is False + assert succ_u1 == [] + + # Truncated suffix (even if backfill RPC would fail!) executes 0 backfill RPCs and keeps hash unchanged. + def _fail_if_backfill(node_to_return): + def _runner(cmd, **_kw): + if any(arg.startswith("before=") for arg in cmd): + raise AssertionError("backfill RPC must not run without min_stalled_hours > 0") + return subprocess.CompletedProcess(cmd, 0, stdout=json.dumps(_graphql_page([node_to_return])), stderr="") + return _runner + + obs_unscoped_truncated, succ_u2, cmds_u2 = _collect_with_gh( + unscoped_todo_with_pre9207, + _fail_if_backfill(truncated_node), + ) + assert len(cmds_u2) == 1 + assert obs_unscoped_truncated["result_hash"] == pre9207_unscoped_obs["result_hash"] + assert obs_unscoped_truncated["material_change"] is False + assert obs_unscoped_truncated["observation_incomplete"] is False + assert succ_u2 == [] + + # Real updatedAt change wakes up unscoped monitor with --next-agent-todo. + obs_unscoped_updated, succ_u3, _ = _collect_with_gh( + unscoped_todo_with_pre9207, + _fail_if_backfill(updated_at_changed_node), + ) + assert obs_unscoped_updated["material_change"] is True + assert obs_unscoped_updated["observation_incomplete"] is False + assert "--next-agent-todo" in succ_u3 + + # 2. Scoped monitor WITHOUT min_stalled_hours: 0 backfill calls, pre-#9207 parity, no false wakeup, + # and real updatedAt change wakes up. + no_age_scope = { + "schema_version": "steward_signal_monitor_scope_v0", + "include_portfolio": False, + "include_inbox": False, + "pr_filter": { + "exclude_drafts": True, + "effective_verdicts": ["REQUEST_CHANGES"], + "author_mode": "exclude", + "authors": ["maintainer"], + }, + } + no_age_todo = _create_monitor("steward-no-age-no-backfill", no_age_scope) + pre9207_no_age_obs = ChatConversationBindings._core( + "collaboration.steward.monitor.signal_observation", + { + "signal_scope": no_age_scope, + "repository_snapshot": {"status": "ok", "repository": "org/repo", "items": [pre9207_item]}, + "observed_at": "2030-01-01T11:00:00Z", + "previous_hash": None, + }, + ) + no_age_todo_with_pre = {**no_age_todo, "result_hash": pre9207_no_age_obs["result_hash"]} + + obs_na1, succ_na1, cmds_na1 = _collect_with_gh(no_age_todo_with_pre, _fail_if_backfill(truncated_node)) + assert len(cmds_na1) == 1 + assert obs_na1["result_hash"] == pre9207_no_age_obs["result_hash"] + assert obs_na1["material_change"] is False + assert obs_na1["observation_incomplete"] is False + assert succ_na1 == [] + + obs_na_rec, succ_na_rec, cmds_na_rec = _collect_with_gh(no_age_todo_with_pre, _fail_if_backfill(complete_node)) + assert len(cmds_na_rec) == 1 + assert obs_na_rec["result_hash"] == pre9207_no_age_obs["result_hash"] + assert obs_na_rec["material_change"] is False + assert succ_na_rec == [] + + obs_na2, succ_na2, _ = _collect_with_gh(no_age_todo_with_pre, _fail_if_backfill(updated_at_changed_node)) + assert obs_na2["material_change"] is True + assert obs_na2["observation_incomplete"] is False + assert "--next-agent-todo" in succ_na2 + + # 3. Scoped monitor WITH min_stalled_hours > 0 DOES invoke backfill RPC and preserves state on failure. + age_scope = { + **no_age_scope, + "pr_filter": {**no_age_scope["pr_filter"], "min_stalled_hours": 24}, + } + age_todo = _create_monitor("steward-age-backfill", age_scope) + + def _age_backfill_runner(cmd, **_kw): + if any(arg == "before=c20" for arg in cmd): + return subprocess.CompletedProcess( + cmd, + 0, + stdout=json.dumps( + { + "data": { + "repository": { + "pullRequest": { + "comments": { + "pageInfo": {"hasPreviousPage": False, "startCursor": "c1"}, + "nodes": [author_comment], + } + } + } + } + } + ), + stderr="", + ) + return subprocess.CompletedProcess(cmd, 0, stdout=json.dumps(_graphql_page([truncated_node])), stderr="") + + obs_age, succ_age, cmds_age = _collect_with_gh(age_todo, _age_backfill_runner) + assert len(cmds_age) == 2 + assert any("before=c20" in cmd for cmd in cmds_age) + assert obs_age["material_change"] is True + assert obs_age["observation_incomplete"] is False + assert obs_age["scoped_repository_items"][0]["stalled_bucket"] == "awaiting_maintainer_reply" + assert "--next-agent-todo" in succ_age + + # And backfill failure on age-filtered monitor fails closed (RuntimeError -> no hash overwrite). + age_todo_with_hash = {**age_todo, "result_hash": obs_age["result_hash"]} + with pytest.raises(RuntimeError, match="temporarily unavailable"): + _collect_with_gh( + age_todo_with_hash, + lambda cmd, **_kw: ( + subprocess.CompletedProcess(cmd, 1, stdout="", stderr="502") + if any(arg.startswith("before=") for arg in cmd) + else subprocess.CompletedProcess(cmd, 0, stdout=json.dumps(_graphql_page([truncated_node])), stderr="") + ), + )