SLOPSHOPPER

apu-session

Exact-session APU diagnosis, preparation and opt-in native continuation through the existing portable CLI.

panecommandprocess
v0.2.0MITupdated 2026-10-25mdn87/apu
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · apu-session
│ ┃ apu-continuation ✕ › fix the failing auth test and add an audit log call │ ┃ Session changed. Run /apu-diagnose and │ ┃ /apu-prepare again. ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /apu-diagnose │ ⎿ apu-session: APU result unavailable. No automatic retry or conti │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · apu-continuation
Session changed. Run /apu-diagnose and /apu-prepare again.
README

APU — Agent Policy Updater

APU is a local-first command-line tool for auditing, simplifying, installing, and evaluating durable coding-agent instructions.

The deterministic core inventories Codex and Claude instruction surfaces, produces reviewable JSON plans, applies approved changes transactionally, and rolls them back from local receipts. Optional behavioral fixtures can run through an independently installed and authenticated Codex or Claude CLI.

Install and use

Optional Claude session commands

After installing APU's CLI from this checkout (native continuation requires 0.11.0 or later), load this checkout with claude --plugin-dir /absolute/path/to/apu. On Claude Code 2.1.287+, /apu-diagnose passes the current provider, session ID and working directory to apu-wtf --fresh. It saves an ordinary APU incident and diagnosis and prints their IDs and the existing status. It does not infer a session from nearby files or replace journal evidence with mod events.

/apu-prepare uses that saved diagnosis with apu-intervene --dry-run. APU owns attribution, barrier checks, prompt integrity and policy-mutation checks. A refusal stays a refusal. A successful preparation prints the saved continuation argument vector and leaves its outcome unverified. Repeating the command returns the same preparation in the current mod instance. Neither diagnosis nor preparation submits a prompt, enables a watcher or changes policy.

/apu-continue opens a native panel. Its Continue this session button revalidates the diagnosis, provider, exact session and directory, current evidence, saved prompt and prohibition on durable policy mutation. It durably reserves the attempt before calling Claude's native submit API. It never runs the printed claude --resume command alongside the live session. Stay in the same idle main session until delivery settles; do not clear, resume, switch directories or reload while submitting. The API has no atomic expected-session argument, so that concurrent lifecycle case is not qualified.

The panel records queued/started/turn-ended observations against the same APU incident. A turn ending is not proof of recovery: outcome_verification stays unverified until the operator records an ordinary intervention result. A repeated claim of the same evidence cannot return a prompt, including after reload or a lost response. No automatic resend occurs. Unknown delivery needs artifact inspection before any new diagnosis or manual recovery.

APU keeps the full transcript hash for audit. A second evidence hash excludes only the recognized inert /apu-diagnose, /apu-prepare, and /apu-continue local command records emitted by Claude Code 2.1.296. New user/model/tool content, policy records, malformed rows and unknown records invalidate the diagnosis. An older incident without that hash must be captured again.

Clear, resume, branch, reload and directory changes discard the adapter's cached diagnosis. Diagnose the current session again before preparing. Failed or timed-out calls are not retried automatically; inspect APU's saved artifacts. Diagnosis and preparation are explicit immediate commands with a 15-second subprocess deadline. Continuation opens a panel and requires a separate button press: the native host forbids submission from a command handler. There is no background polling. The ordinary CLI remains available without the mod for both Codex and Claude. apu-watch controls the watcher and is separate from these commands.

The pilot targets native Windows first. Run claude plugin validate . and claude plugin test .; the generated types and runtime were checked with Claude Code 2.1.296. Windows CLI native delivery and exact turn correlation passed a controlled live fixture; qualification evidence distinguishes that from real recovery. macOS/Linux, live Desktop, operator-effort measurement, concurrent lifecycle changes and voice transport remain separate qualification work. No UI event implies successful recovery.

Portable CLI

python -m pip install .
apu audit /path/to/repository --json inventory.json
apu propose --inventory inventory.json --output plan.json
apu review plan.json
apu apply plan.json
apu validate

apu init /path/to/repository creates a draft preview. Add --apply for the explicit interactive review and transactional installation flow.

System audit and restore points

M5 adds deterministic machine-level inventory and campaign-grade restore points. Declare the roots APU may inspect in ~/.config/apu/profile.toml (or %APPDATA%\apu\profile.toml on Windows):

schema_version = 1
global_surfaces = ["~/.claude", "~/.codex", "~/.agents"]

[[roots]]
path = "~/Desktop/MyDocs"
excludes = ["node_modules", "archive/**"]

Root exclusions are enforced before APU descends into matching directories or reads matching instruction surfaces. They constrain both nested repository discovery and each selected repository's child inventory.

apu system audit --json system-inventory.json
apu snapshot create --label before-policy-update
apu snapshot list
apu snapshot diff SNAPSHOT_ID
apu snapshot restore SNAPSHOT_ID
apu system status

Snapshot manifests preserve object types, links, junctions, empty directories, content hashes, and meaningful POSIX modes. Restore is journaled and reverses completed swaps on failure; interrupted recovery uses apu snapshot restore --resume JOURNAL_ID [--unwind].

Campaigns and work orders

M6 turns a system inventory into an immutable campaign with deterministic operations and privacy-safe work orders:

apu system propose --inventory system-inventory.json --output campaign.json
apu system apply campaign.json --auto-only
apu system status

To explicitly ask APU to consolidate the effective AGENTS.md and CLAUDE.md policy for one audited repository, add the repository path:

apu system propose --inventory system-inventory.json \
  --consolidate-instructions /path/to/repository \
  --output instruction-campaign.json

This task is explicit rather than an automatic semantic heuristic. It creates review-required, target-scoped work orders even when the deterministic audit has no findings. It combines audited machine-level instructions with only the repository surfaces present in an effective provider stack, excluding inactive nested files. Effective ancestor instructions are eligible for this explicit review task; ordinary deterministic operations remain profile-bound. Each work order includes the stack as untrusted context and asks the runner to state shared behavior once, keep project facts near the project, preserve provider-specific syntax, and prefer supported imports when appropriate. APU does not edit live files during proposal or dispatch; every accepted candidate still requires review and apply.

Add --emit-prompts DIR to export hand-run work orders; APU warns that these copies are outside private state protection. Credential-exposure findings are always manual-only and render file, line, and content hash without the value. Other findings on sensitive surfaces use private sanitized staging and structurally verified placeholders. Before the first deterministic mutation, APU locks the campaign, records a campaign-bound snapshot covering every planned target, and stamps the receipt with campaign, snapshot, and idempotency data.

Guidance and model refresh

M7 makes guidance and model identity explicit, versioned inputs. Refresh is explicit network activity:

apu refresh guidance --profile profile.toml --output guidance-refresh.json
apu refresh models --profile profile.toml --output model-refresh.json
apu system audit --profile profile.toml --json system-inventory.json

Guidance refresh stores bounded exact-byte HTTPS snapshots privately and emits a distillation work order. It never adopts model-written guidance automatically. After reviewing a returned candidate and approval artifact:

apu refresh guidance --profile profile.toml \
  --adopt baseline-candidate.json --approval approval.json
apu guidance diff BEFORE_BASELINE AFTER_BASELINE

Model refresh observes installed CLI versions and configured selectors offline, then resolves them only against fixed official provider listing endpoints. Provider credentials are read at request time from the process environment and are never persisted. Exact published model IDs can resolve directly; aliases and omitted defaults remain visibly unverified unless the authoritative listing supplies their mapping. Failed refreshes preserve the matching last-known identity as stale rather than presenting it as current.

System inventories now carry a typed baseline/model evaluation context. New campaigns verify its immutable private artifacts and freeze it in the campaign manifest; older M6 campaigns remain readable, while v1 inventories must be regenerated before creating a new campaign.

Review-only AETA policy intake

APU accepts a content-addressed policy-delta proposal produced from a pinned Git source by AETA. Intake validates the complete proposal, its content-derived identity, and its declared source-hash binding; rejects credential-shaped material; and stores one immutable candidate plus a pending_review receipt in private APU state:

apu intake policy-delta proposal.json

This command does not apply, adopt, or promote the proposal. A later APU-owned review and approval flow must make any policy change.

Package research

M8 observes tracked Claude packages from authoritative installed metadata, resolves stable upstream tags during an explicit networked research command, and stores candidate trees privately by content hash. Add package coordinates to the system profile:

packages = ["superpowers@claude-plugins-official"]

Then compare one installed package with its latest stable candidate:

apu research packages superpowers --profile profile.toml
apu research packages superpowers --profile profile.toml --upgrade-capability

Installed and candidate trees run through the same frozen classifier policy. Reports contain only relative finding metadata, hashes, provenance, and explicitly unclassified dynamic surfaces—never instruction bodies. Package caches and provider-managed installation metadata remain read-only. Archive links are never created or followed on disk: a versioned manifest records validated package-internal links, and analysis reads the bound target blob through that virtual view. Research emits hold or work-order; applying a package update is a separate, explicit operation with a verified restore point.

The apu.package_transactions library coordinates trusted provider adapters: it journals before update, verifies the exact version and tree, restores and verifies the pre-state on failure, and returns a durable receipt. Retries never repeat an interrupted update. Ambiguous state and failed rollback require explicit recovery bound to a fresh observation. Per-package locks serialize APU transactions; adapters must also protect against concurrent provider changes. Claude updates use the official CLI and APU's existing snapshot/restore journal. The rule permits APU-managed restoration of Claude files; it does not require an official provider downgrade command. Before updating, APU captures the plugin store (cache, installation records, and marketplaces), user settings, relevant project/local settings, and the selected marketplace checkout if stored outside the plugin store. Restore points remain protected from snapshot retention.

apu packages upgrade sample@marketplace --target-version 2.0.0 --target-tree ./reviewed-plugin --operation-id sample-update
apu packages status TRANSACTION_ID
apu packages rollback TRANSACTION_ID

--target-tree names the reviewed plugin directory, including its manifest. Alternatively, --target-sha256 accepts the installed-tree digest, not a research candidate artifact digest. Claude selects its latest version; APU keeps it only if both the installed version and tree match the requested target. A failed or different update triggers restoration and verification of the captured state. Use --claude-home HOME for an isolated home containing .claude.

Keep Claude and other writers idle during update and restore. The plugin store is restored as a unit, so later changes to any captured surface stop automatic restoration. After inspecting those changes, explicit recovery can bind to the current_state_sha256 from packages status using packages rollback TRANSACTION_ID --expected-state DIGEST. This authorizes replacing that observed state with the backup, including later edits. Interrupted restore journals can resume; unknown state after a crash requires reconciliation. Linked paths, ambiguous installations, and managed installations are refused. Restoration covers captured files, not external effects of plugin commands or Windows ACLs. Restart Claude to load restored plugins; configured automatic updates can subsequently install a newer version again.

Isolated dispatch and efficacy

Dispatch accepts only a work order inside APU's private campaign state. On Windows, the Codex adapter first proves that its confined context can write the disposable stage but cannot open the live target for writing. If that probe fails, dispatch is unavailable and the work order stays in the hand-run queue. Claude dispatch uses the installed Codex CLI as an OS sandbox broker and the installed Claude CLI as the model provider. It requires a fresh successful write-denial probe for the exact stage before each invocation. Both CLIs are required; Windows npm wrappers must expose the native Claude executable. A per-invocation profile inherits workspace protection and permits only api.anthropic.com through the network proxy, with managed requirements applied. The Claude process receives staged content through stdin with tools, hooks, customizations, MCP servers, and session persistence disabled. Only successful structured edits bound to the staged logical paths are accepted. Authentication and network access remain subject to the installed provider and sandbox policy; failures leave the work order unapplied. Timeouts terminate the launched process tree. APU does not change global profiles or bypass managed requirements.

Select it with apu dispatch WORK_ORDER --runner claude. The adapter follows Claude's programmatic CLI contract; it does not install a provider or modify live-file permissions.

apu dispatch %LOCALAPPDATA%\apu\campaigns\CAMPAIGN_ID\work-orders\WORK_ORDER_ID.md
apu review %LOCALAPPDATA%\apu\campaigns\CAMPAIGN_ID\plans\PLAN_ID.json \
  --output reviewed-plan.json
apu apply reviewed-plan.json --yes

The runner sees only an exact staged copy, or a sanitized copy with structural placeholders on sensitive surfaces. Returned content is secret-scanned and quarantined on any file-set, placeholder, relocation, or secret violation. Accepted output becomes a pending full-file plan; it cannot mutate live files until reviewed and applied. The resulting receipt remains bound to the campaign snapshot.

Campaign-bound outcomes derive installed categories from the immutable campaign rather than trusting user input. --activate records an explicit user attestation; empty activation evidence remains the default.

apu outcome record --receipt RECEIPT.json --task-id TASK_ID \
  --activate guidance-conflict --validation passed
apu outcome promotion --receipt RECEIPT.json --category guidance-conflict \
  --profile profile.toml --deterministic-remediation
apu system status --profile profile.toml

Promotion only emits a review-required profile-edit proposal after ten distinct material activations, a closed monitoring window, no implicating defects, and green close-window fixtures. One implicating escaped defect writes a visible APU-private demotion override without editing the profile.

Behavioral pressure watch

The live watcher detects likely primary-agent-autonomy-loss in existing Codex and Claude Code JSONL sessions. Automatic attribution requires exactly one provider to have exactly one incomplete session whose normalized working directory matches the current directory and whose last event is no more than ten minutes old:

apu-event "asked me to approve a reversible filename choice"
apu wtf
# Run the exact apu-intervene --diagnosis ... command printed by the diagnosis.

Use --provider codex|claude-code and --session-id to resolve an ambiguity explicitly. If the supplied session belongs to another working directory, if multiple providers qualify, or if selection finds zero or multiple fresh incomplete matches, APU returns no_attribution with a bounded reason code and exits nonzero. It never falls back to a recent session from another project or provider.

apu wtf (also apu-wtf) reuses the latest marked incident only when it matches the current directory, or the directory supplied with --cwd, and every explicit provider/session selector. Otherwise it selects one fresh, incomplete run in that directory. --fresh forces a new snapshot of the run; --trace-root also forces fresh selection. Use --incident ID to inspect a specific saved incident from any directory. It cannot be combined with --fresh, --cwd, --session-id, or --trace-root.

Both commands explain the result and show the session, directory, evidence location, possible causes, and saved diagnosis. Matching instruction rules are clues rather than proof of causation. A continuation command includes --diagnosis ID, so another diagnosis cannot redirect it to a different incident. Insufficient evidence prompts you to describe the stop; possible barriers prompt review instead of continuation. Selection failures explain how to resolve the mismatch or ambiguity. --json retains the existing diagnosis and attribution-error formats.

apu ezpz (also apu-ezpz) prepares recovery when the requested outcome is still unresolved: the agent stopped early, repeated an ineffective approach, or handed routine work and approval requests back to you. It marks a fresh incident with operator-requested-recovery and reports recovery-requested, not a proven diagnosis. The optional description identifies what still needs fixing and travels with the continuation.

The primary-agent-outcome-recovery-v1 instruction tells the agent to verify the actual behavior, test its suspected cause, change an ineffective approach, and act within existing authorization. Tests passing or a process being healthy are supporting evidence, not proof that the user's task works. Necessary human actions remain explicit and unverified until their results are known.

Normal output includes the recovery instruction and the exact incident-bound continuation command. --prompt prints only that instruction for use in the selected chat; it cannot be combined with --json. Neither form launches an agent. Selection remains exact to the working directory and provider. If the agent already ended its turn, use --session-id to select that fresh session explicitly. Automatic selection does not guess between idle chats.

Barrier evidence still takes precedence: possible-legitimate-barrier blocks both prompt-only output and apu-intervene. Old easy-decision-gate incidents retain their original template. Saved diagnosis hashes bind the specific instruction and operator report used by the continuation.

apu ezpz
apu ezpz "tests pass but the voice command still does not work"
apu ezpz "keeps trying the same restart without new evidence" --prompt
apu ezpz "asked me to approve a reversible filename choice" --session-id SESSION_ID
# Run the exact apu-intervene --diagnosis ... command printed by the diagnosis.

apu-intervene resumes a non-interactive Codex session directly; for Codex Desktop and Claude Code sessions it records and prints the exact provider continuation because APU cannot inject into the desktop process. Claude Code transcripts do not reliably distinguish interactive CLI runs from --print, so their continuations always require --execute. Add --dry-run to only record the proposed action. An executed continuation is recorded as resumed, with turn_completed tracking an observed Codex turn-end marker (null when not observed through that transport) and outcome_verification: unverified. A model turn ending does not mark the task completed. After checking the actual result, record the outcome as an operator attestation:

apu-intervene --result completed

Before it constructs or launches a continuation, apu-intervene re-reads the exact trace and proves that its provider, session ID, and working directory still match the incident. It also rejects any diagnosis whose durable_policy_mutation value is not exactly false. The mutating apu apply command keeps its strict session gate and is provider-neutral: it binds to one fresh, incomplete Codex or Claude Code session in the exact working directory, fails closed on ambiguity, and accepts --provider, --session-id, --trace-root, and --cwd like the incident commands.

Watcher state is explicit and never starts a background service. Its health output names both supported providers and includes per-provider attribution time, ambiguity count, and heartbeat plus package version and build hash; it contains no session ID, trace path, cwd, or transcript content:

apu-watch
apu-watch autonomy-loss --disable
apu-watch autonomy-loss --enable

Incident artifacts keep the provider, operator's short description, session identity, nearby record hashes/types, runtime-setting labels, and active surface hashes. They do not persist nearby messages, reasoning, tool inputs or outputs, base instructions, or environment content. request-substitution identifies a different task being substituted for the requested one. A denial produced by provider permissions or a user-authored hook is an operator-designed-gate barrier and suppresses automatic intervention. Interventions are temporary session instructions and never rewrite durable policy.

Execution evidence plane

APU normalizes provider execution records into three content-minimized evidence classes: invocation, result, and repository-state observation. Provider message bodies, reasoning, tool inputs, tool outputs, and command text are inspected only in memory and never enter APU state. Stored records contain safe labels, hashes, exit status, duration, correlation hashes, and optional Git state.

Evidence schema v3 is the default. It retains v2's selector provenance and interprets typed Codex command-result envelopes, including explicit nonzero, zero, running, and unknown statuses. Output bodies are never recursively searched for embedded statuses. A nonzero sibling result dominates; opaque siblings prevent a success claim. A tool response may finish while its command is still running, so consumers use observation status as well as event type.

V1, v2, and v3 records remain in separate append-only routes; v3 uses behavior/evidence/v3. Readers select v3's result status for the same Codex source record without double-counting older interpretations. V3 also classifies Codex exec_command and functions.exec_command requests using their cmd argument. Existing bash, shell, and shell_command inputs still use command. These are coarse test, Git, network, and shell labels; the classifier does not interpret shell control flow or commands embedded in exec orchestration code. Failed, running, and unknown results cannot count as passing tests.

Replaying an unclassified Codex execution request appends a distinct v3 record. The reader selects one effective classification for the same source record; only an abse

Source 1 files
hooks/register.js 229 lines
1let diagnosis = null;
2let generation = 0;
3let busy = false;
4let nativeAttempt = null;
5let activeTurn = null;
6let turnGeneration = 0;
7let paneReady = false;
8let paneText = 'Prepare a diagnosis before continuing this session.';
9const PANE = 'apu-continuation';
10
11function isNativeTurn(text, prompt) {
12  // Claude Code 2.1.296 preserves plugin attribution by wrapping its prompt.
13  // Match the complete observed wrapper, never a substring of another turn.
14  return text === prompt || text === `The apu-session plugin sent a message:\n${prompt}\n\nThis is how Claude Code surfaces a prompt a plugin submits between turns — it starts this turn in the user's place. Address the message above.`;
15}
16
17function reset() {
18  generation += 1;
19  diagnosis = null;
20  busy = false;
21  nativeAttempt = null;
22  paneReady = false;
23  activeTurn = null;
24  turnGeneration += 1;
25  paneText = 'Session changed. Run /apu-diagnose and /apu-prepare again.';
26}
27
28async function sameSession($, attempt) {
29  const session = await $.session.id();
30  const cwd = await $.session.cwd();
31  return attempt.epoch === generation && session === attempt.session && cwd === attempt.cwd;
32}
33
34async function nativeCall($, action, args) {
35  const result = await $.process.run(
36    ['apu-intervene', '--provider', 'claude-code', '--native-action', action, ...args, '--json'],
37    { timeoutMs: 15000 });
38  if (result.exitCode !== 0) throw new Error('native operation refused');
39  return JSON.parse(result.stdout);
40}
41
42function observe($, attempt, state, args = []) {
43  attempt.recording = attempt.recording.then(async () => {
44    const value = await nativeCall($, state, ['--intervention', attempt.id, ...args]);
45    attempt.state = value.native_delivery.state;
46    $.ui.invalidate('ui.render');
47  }).catch(() => { attempt.recordingFailed = true; });
48  return attempt.recording;
49}
50
51async function continueNative($) {
52  if (busy) return { text: 'APU: the previous request is still running.' };
53  if (!paneReady || activeTurn !== null) return { text: 'APU: wait for this session to become idle and reopen /apu-continue.' };
54  busy = true;
55  const epoch = generation;
56  try {
57    const session = await $.session.id();
58    const cwd = await $.session.cwd();
59    if (epoch !== generation || !diagnosis || diagnosis.session !== session || diagnosis.cwd !== cwd || !diagnosis.prepared)
60      return { text: 'Run /apu-diagnose and /apu-prepare in this session before /apu-continue.' };
61    if (nativeAttempt) return { text: `APU native delivery: ${nativeAttempt.state}. No resend.\nIntervention: ${nativeAttempt.id}\nRecovery outcome remains unverified.${nativeAttempt.recordingFailed ? '\nAn observation could not be saved; inspect APU artifacts.' : ''}` };
62    const diagnosisId = diagnosis.id;
63    const idleGeneration = turnGeneration;
64    const value = await nativeCall($, 'claim', ['--diagnosis', diagnosisId, '--session-id', session, '--cwd', cwd]);
65    if (value.should_submit === false)
66      return { text: `APU: this continuation is already reserved (${value.native_delivery.state}); no resend.\nIntervention: ${value.intervention_id}\nInspect saved APU evidence; outcome remains unverified.` };
67    if (value.should_submit !== true || value.provider !== 'claude-code' || value.session_id !== session
68      || value.diagnosis_id !== diagnosisId || value.executed !== false || value.durable_policy_mutation !== false
69      || !/^native-[a-f0-9]{64}$/.test(value.intervention_id) || typeof value.prompt !== 'string' || !value.prompt)
70      throw new Error('invalid native reservation');
71    const attempt = { id: value.intervention_id, session, cwd, epoch, prompt: value.prompt,
72      idleGeneration, state: 'reserved', admitted: false, turn: null, recording: Promise.resolve(), recordingFailed: false };
73    if (!await sameSession($, attempt) || activeTurn !== null || turnGeneration !== idleGeneration) {
74      await observe($, attempt, 'outcome-unknown');
75      return { text: 'APU: session changed while reserving. No prompt submitted; reservation retained to prevent replay.' };
76    }
77    nativeAttempt = attempt;
78    // Calls originating in this plugin can skip its prompt.submit hook in the
79    // native runtime. Perform admission in the button action itself, not in a
80    // middleware hook that may never see our submission.
81    try {
82      const admitted = await nativeCall($, 'admit', ['--intervention', attempt.id,
83        '--session-id', session, '--cwd', cwd]);
84      if (admitted.should_enter !== true || !await sameSession($, attempt)
85        || activeTurn !== null || turnGeneration !== idleGeneration) {
86        await observe($, attempt, 'outcome-unknown');
87        return { text: 'APU refused: reservation or session changed before submission. No resend.' };
88      }
89      attempt.admitted = true;
90    } catch (_) {
91      await observe($, attempt, 'dropped');
92      return { text: 'APU refused: native admission could not be verified. No prompt submitted.' };
93    }
94    // A native button is a fresh ui.press event. The host explicitly forbids
95    // submitting from command.run, even without awaiting it. Never execute --resume.
96    await $.prompt.submit({ text: attempt.prompt }).then(async result => {
97      if (!await sameSession($, attempt)) return observe($, attempt, 'outcome-unknown');
98      return observe($, attempt, typeof result.drop === 'string' ? 'dropped' : 'queued');
99    }).catch(() => observe($, attempt, 'outcome-unknown'));
100    return { text: `APU native delivery: ${attempt.state}.\nIntervention: ${attempt.id}\nRecovery outcome remains unverified. No automatic resend.` };
101  } catch (_) {
102    return { text: 'APU native continuation unavailable. No automatic retry; inspect saved APU artifacts before taking further action.' };
103  } finally {
104    if (epoch === generation) busy = false;
105  }
106}
107
108async function act($, prepare) {
109  if (busy) return { text: 'APU: the previous request is still running.' };
110  busy = true;
111  const epoch = generation;
112  try {
113    const session = await $.session.id();
114    const cwd = await $.session.cwd();
115    if (!session || !cwd) return { text: 'APU: exact session identity is unavailable.' };
116    if (diagnosis && (diagnosis.session !== session || diagnosis.cwd !== cwd)) diagnosis = null;
117    if (prepare && !diagnosis) return { text: 'Run /apu-diagnose in this session before preparing a continuation.' };
118    if (prepare && diagnosis.prepared) return { text: diagnosis.prepared };
119    if (!prepare) diagnosis = null;
120    const argv = prepare
121      ? ['apu-intervene', '--provider', 'claude-code', '--diagnosis', diagnosis.id, '--dry-run', '--json']
122      : ['apu-wtf', '--provider', 'claude-code', '--session-id', session, '--cwd', cwd, '--fresh', '--json'];
123    const result = await $.process.run(argv, { timeoutMs: 15000 });
124    if (epoch !== generation) return { text: 'APU: session changed; discard this view and diagnose the current session.' };
125    if (result.exitCode !== 0) {
126      diagnosis = null;
127      let reason = `exit ${result.exitCode}`;
128      try {
129        const failure = JSON.parse(result.stdout);
130        if (failure.kind === 'no_attribution' && /^[a-z_]+$/.test(failure.reason_code)) reason = failure.reason_code;
131      } catch (_) {}
132      return { text: `APU refused or could not complete the request (${reason}). No turn was submitted.\nSession: ${session}\nDirectory: ${cwd}\nRun apu-wtf with this exact provider, session ID and cwd for details.` };
133    }
134    const value = JSON.parse(result.stdout);
135    if (value.provider !== 'claude-code' || typeof value.status !== 'string') throw new Error('invalid result');
136    if (!prepare) {
137      if (typeof value.diagnosis_id !== 'string' || typeof value.incident_id !== 'string') throw new Error('invalid diagnosis');
138      // The CLI owns attribution, evidence, barrier classification and saved artifacts.
139      diagnosis = { id: value.diagnosis_id, session, cwd, prepared: null };
140      const allowed = ['likely-autonomy-loss', 'recovery-requested'].includes(value.status)
141        && value.recommended_intervention?.durable_policy_mutation === false;
142      return { text: `APU: ${value.status}\nSession: ${session}\nDiagnosis: ${value.diagnosis_id}\nIncident: ${value.incident_id}\n`
143        + (allowed ? 'Use /apu-prepare to revalidate and prepare a continuation.' : 'The evidence does not authorize continuation. Resolve any barrier or gather more evidence.') };
144    }
145    if (value.session_id !== session || value.diagnosis_id !== diagnosis.id
146      || value.executed !== false || value.durable_policy_mutation !== false
147      || value.status !== 'planned' || !Array.isArray(value.command)
148      || !value.command.every(part => typeof part === 'string')) throw new Error('invalid preparation');
149    diagnosis.prepared = `APU: ${value.status}\nIntervention: ${value.intervention_id}\nNo turn was submitted; outcome remains unverified.\nContinuation argv:\n${JSON.stringify(value.command)}`;
150    return { text: diagnosis.prepared };
151  } catch (_) {
152    if (epoch === generation) diagnosis = null;
153    return { text: 'APU result unavailable. No automatic retry or continuation was attempted; inspect saved APU artifacts before retrying.' };
154  } finally {
155    if (epoch === generation) busy = false;
156  }
157}
158
159export function register(on) {
160  on('session.start', async ($, e, next) => {
161    reset();
162    await $.command.register({ name: 'apu-diagnose', immediate: true,
163      description: 'Save an APU diagnosis for this exact Claude session' });
164    await $.command.register({ name: 'apu-prepare', immediate: true,
165      description: 'Revalidate the saved diagnosis and print a continuation without executing it' });
166    await $.command.register({ name: 'apu-continue',
167      description: 'Open the native continuation panel for this prepared session' });
168    return next(e);
169  });
170  on('classic.SessionStart', async ($, e, next) => { reset(); return next(e); });
171  on('classic.CwdChanged', async ($, e, next) => { reset(); return next(e); });
172  on('session.end', async ($, e, next) => { reset(); return next(e); });
173  on('command.run', { command: 'apu-diagnose' }, async ($, e) =>
174    e.args.trim() ? { text: 'Usage: /apu-diagnose (targets the current session only)' } : act($, false));
175  on('command.run', { command: 'apu-prepare' }, async ($, e) =>
176    e.args.trim() ? { text: 'Usage: /apu-prepare (uses this session’s saved diagnosis)' } : act($, true));
177  on('command.run', { command: 'apu-continue' }, async ($, e) => {
178    if (e.args.trim()) return { text: 'Usage: /apu-continue (uses this session’s prepared diagnosis)' };
179    const epoch = generation;
180    const session = await $.session.id();
181    const cwd = await $.session.cwd();
182    if (epoch !== generation || !diagnosis?.prepared || diagnosis.session !== session || diagnosis.cwd !== cwd)
183      return { text: 'Run /apu-diagnose and /apu-prepare in this session before /apu-continue.' };
184    paneReady = true;
185    paneText = 'Continue the prepared recovery instruction once in this session. This does not change policy or attest recovery.';
186    const opened = await $.ui.open({ id: PANE, title: 'APU continuation', focus: true, closeOnEscape: true, rows: 8 });
187    if (!opened.isPlaced) { paneReady = false; return { text: 'APU continuation panel is unavailable on this surface. No prompt submitted.' }; }
188    return { text: 'APU continuation panel opened. Use Continue this session when ready; opening it submits nothing.' };
189  });
190  on('ui.close', async ($, e, next) => {
191    if (e.id === PANE) paneReady = false;
192    return next(e);
193  });
194  on('ui.render', { component: 'Pane', requestId: PANE }, ($, e) => {
195    const { Box, Text, Button } = $.ui.resolve(e);
196    const status = nativeAttempt ? `Native delivery: ${nativeAttempt.state}. Recovery outcome remains unverified.\nIntervention: ${nativeAttempt.id}${nativeAttempt.recordingFailed ? '\nAn observation could not be saved; inspect APU artifacts.' : ''}` : paneText;
197    const epoch = generation;
198    const idleGeneration = turnGeneration;
199    const eligible = paneReady && !busy && activeTurn === null && nativeAttempt === null && !e.props.view?.agentId;
200    const children = [Text({ children: [status] })];
201    // ButtonProps has no disabled property. Ineligible views expose no action.
202    if (eligible) children.push(Button({ key: 'continue', label: 'Continue this session', hotkey: '1',
203      onPress: async () => {
204        if (epoch !== generation || idleGeneration !== turnGeneration) return;
205        paneText = (await continueNative($)).text;
206        $.ui.invalidate('ui.render');
207      } }));
208    return Box({ flexDirection: 'column', children });
209  });
210  on('turn.start', async ($, e, next) => {
211    const attempt = nativeAttempt;
212    activeTurn = e.turnId;
213    turnGeneration += 1;
214    if (attempt?.admitted && attempt.turn === null && isNativeTurn(e.text, attempt.prompt) && await sameSession($, attempt)) {
215      attempt.turn = e.turnId;
216      await observe($, attempt, 'started', ['--turn-id', e.turnId]);
217    }
218    return next(e);
219  });
220  on('turn.complete', async ($, e, next) => {
221    const attempt = nativeAttempt;
222    if (attempt?.turn === e.turnId && !e.agentId && await sameSession($, attempt))
223      await observe($, attempt, 'turn-ended', ['--turn-id', e.turnId, '--reason', e.reason]);
224    if (!e.agentId && activeTurn === e.turnId) activeTurn = null;
225    $.ui.invalidate('ui.render');
226    return next(e);
227  });
228}
229